Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Studio: stop the macOS launcher killing a warming backend, and the Mac tab blackout (#8076)
Daniel Han8b34acebcd8a
diff --git a/.github/workflows/studio-mac-ui-smoke.yml b/.github/workflows/studio-mac-ui-smoke.ymlindex 662e39b7fad..dd892e343bd 100644--- a/.github/workflows/studio-mac-ui-smoke.yml+++ b/.github/workflows/studio-mac-ui-smoke.yml@@ -384,6 +384,67 @@ jobs:kill "${STUDIO_EXTRA_PID}" 2>/dev/null || truesleep 2+ # ---------------------------------------------------------------+ # Tab-capability phase. The assertion is that the Train row SPINS rather than+ # greying out while the hardware verdict is unmeasured.+ #+ # It gets its own boot on a cold port anyway, and no "wait for healthy" step+ # where every other phase has one, because a settled backend is the wrong+ # starting state to walk the tabs from. But do not read that as the phase+ # keeping the provisional window open for the script: it does not, and this+ # comment used to claim it did. `hardware_detecting` covers stage 0 of the warm+ # only, and on this runner's --no-torch install with no MLX present that stage+ # is a failed `import torch` plus one failed metadata lookup, so the verdict+ # settles inside a second of the port binding -- while Playwright is still+ # launching Chromium. Boot ordering buys the first /api/health probe a+ # provisional reply and nothing past it.+ #+ # So the script does not depend on the window being open. It holds the+ # browser's own /api/health at hardware_detecting=true and asserts against+ # that, which is open for as long as it needs on any host. The real warm is+ # still sampled when it happens to still be running, and still fails on a real+ # grey-out, but nothing is required of it.+ # ---------------------------------------------------------------+ - name: Reset auth + boot Unsloth for the tab-capability smoke (port 18893)+ run: |+ bash .github/scripts/boot-studio-api-only.sh \+ --port 18893 --log logs/studio_tabs.log --pid-var STUDIO_TABS_PID++ - name: Pass bootstrap pw for the tab-capability smoke+ run: |+ # Wait for the password file, not for health: health is the thing under test.+ for i in $(seq 1 180); do+ [ -f ~/.unsloth/studio/auth/.bootstrap_password ] && break+ sleep 1+ done+ OLD=$(cat ~/.unsloth/studio/auth/.bootstrap_password)+ echo "::add-mask::$OLD"+ echo "STUDIO_TABS_OLD_PW=$OLD" >> "$GITHUB_ENV"++ - name: Drive the Train/Video capability gate with Playwright+ env:+ BASE_URL: http://127.0.0.1:18893+ STUDIO_OLD_PW: ${{ env.STUDIO_TABS_OLD_PW }}+ PW_ART_DIR: logs/playwright_mac_tabs+ # The default 330s outlives the launcher's 300s startup grace, which is the+ # point when a Tauri shell is driving the backend. Nothing here runs that+ # watchdog (this phase boots `unsloth studio` directly), so the full window+ # would spend five macOS-runner minutes proving something this job cannot+ # observe. The watchdog itself is covered by the Rust tests in+ # studio/src-tauri/src/commands.rs. What is unique to this phase is the+ # first-paint tab assertion, so keep the liveness poll just long enough to+ # cover the warm and the tab walk.+ STUDIO_MAC_SURVIVAL_S: '120'+ run: |+ mkdir -p logs/playwright_mac_tabs+ python tests/studio/playwright_mac_tab_capabilities.py++ - name: Stop tab-capability Unsloth+ if: always()+ run: |+ kill "${STUDIO_TABS_PID}" 2>/dev/null || true+ sleep 2+# ---------------------------------------------------------------# API + auth phase, absorbed from studio-mac-api-smoke.yml.# Runs on 18894: 18896 and 18897 were used by the UI phases above and@@ -567,6 +628,8 @@ jobs:logs/playwright-permissions-*logs/playwright_extralogs/studio-permissions-*.log+ logs/studio_tabs.log+ logs/playwright_mac_tabs# 1 day, matching the repository-wide cap. A larger value here is# silently clamped to that cap today, so stating 7 only invites the# artifacts to re-inflate if the cap is ever raised.diff --git a/studio/backend/loggers/__init__.py b/studio/backend/loggers/__init__.pyindex 721dde46885..5d1594d97e0 100644--- a/studio/backend/loggers/__init__.py+++ b/studio/backend/loggers/__init__.py@@ -1,6 +1,6 @@# SPDX-License-Identifier: AGPL-3.0-only# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0-from .handlers import get_logger+from .handlers import get_logger, install_uvicorn_duplicate_exception_filter-__all__ = ["get_logger"]+__all__ = ["get_logger", "install_uvicorn_duplicate_exception_filter"]diff --git a/studio/backend/loggers/handlers.py b/studio/backend/loggers/handlers.pyindex 4492a4f03d4..8a32544259d 100644--- a/studio/backend/loggers/handlers.py+++ b/studio/backend/loggers/handlers.py@@ -10,6 +10,7 @@ get_logger (factory for structured loggers).from __future__ import annotations+import loggingimport osimport reimport time@@ -106,6 +107,19 @@ _QUIET_SUCCESS_PATHS = {"/api/hub/datasets/download-progress","/api/hub/datasets/active-downloads","/api/hub/datasets/transport-status",+ # Boot-burst catalog reads. The SPA refetches these on every auth change, store+ # rehydration and settings/provider dialog open, and each one is a plain read whose+ # outcome is already visible as the populated (or empty) list in the UI.+ # Provider registry + configs: syncExternalProvidersFromBackend fetches the pair in+ # one Promise.all, so they always arrive as two lines saying the same thing.+ "/api/providers/registry",+ "/api/providers/",+ # Fetched in the same Promise.all as /api/models/list and /api/inference/status, both+ # of which keep their access line, so the resync is still traceable without it.+ "/api/models/loras",+ # Re-read once per auth generation at boot. Suppression is GET-only, so the PUT that+ # actually writes a profile change still logs.+ "/api/settings/personalization",}# The token-refresh route. Its first 2xx means the client has obtained a valid# session, so from then on chat 401s are real failures and must stay visible.@@ -131,6 +145,55 @@ def _is_quiet_success(method: str, path: str, status_code: int, pre_auth: bool)return pre_auth and status_code == 401 and path in _CHAT_LIST_PATHS+# An unhandled request exception is logged twice: once here as a structured+# request_failed event whose "exception" field already carries the whole traceback+# (format_exc_info renders it, see loggers/config.py), and then again by uvicorn on+# stderr as "Exception in ASGI application" after the re-raise. The desktop shell+# mirrors every stderr line separately into tauri.log, so the second copy alone costs+# ~90 lines per failure. Keep the structured copy and drop uvicorn's.+_UVICORN_ASGI_EXC_MSG = "Exception in ASGI application"+# Set on the exception instance itself rather than tracked in a side table: the object+# is what uvicorn hands us, so the match cannot go stale or collide with a recycled id,+# and an exception raised above this middleware (CORS, remote-access, the protocol+# layer) carries no marker and keeps uvicorn's traceback.+_LOGGED_EXC_ATTR = "_unsloth_request_failed_logged"+++def _mark_exception_logged(exc: BaseException) -> None:+ """Flag exc as already reported by request_failed. Best effort: an exception type+ that refuses attributes just means both copies are logged, as before."""+ try:+ setattr(exc, _LOGGED_EXC_ATTR, True)+ except Exception:+ pass+++class _DropDuplicateAsgiException(logging.Filter):+ """Drop uvicorn's "Exception in ASGI application" record when request_failed has+ already logged that same exception. Anything else, including a failure that never+ reached this middleware, passes through untouched. --verbose keeps both copies."""++ def filter(self, record: logging.LogRecord) -> bool:+ if _VERBOSE_ACCESS_LOG:+ return True+ try:+ msg = record.msg if isinstance(record.msg, str) else ""+ if not msg.startswith(_UVICORN_ASGI_EXC_MSG):+ return True+ exc_info = record.exc_info+ exc = exc_info[1] if isinstance(exc_info, tuple) else exc_info+ return not getattr(exc, _LOGGED_EXC_ATTR, False)+ except Exception:+ return True+++def install_uvicorn_duplicate_exception_filter() -> None:+ """Attach the duplicate-traceback filter to uvicorn's error logger. Same+ logger-level filter technique as run.py's startup-line rewrite; safe to call more+ than once because a second identical install only re-checks the same records."""+ logging.getLogger("uvicorn.error").addFilter(_DropDuplicateAsgiException())++class LoggingMiddleware:"""ASGI request logger that avoids BaseHTTPMiddleware streaming wrappers."""@@ -195,6 +258,7 @@ class LoggingMiddleware:process_time_ms = round((time.perf_counter() - start_time) * 1000, 2),exc_info = True,)+ _mark_exception_logged(exc)raiseelse:end_time = time.perf_counter()diff --git a/studio/backend/main.py b/studio/backend/main.pyindex d0a8effaf31..272223e4531 100644--- a/studio/backend/main.py+++ b/studio/backend/main.py@@ -322,6 +322,7 @@ from utils.torch_warmup import (join_background_warm,reset_background_warm,start_background_warm,+ warm_status,)from utils.cache_cleanup import clear_unsloth_compiled_cachefrom utils.lifespan_shutdown import run_lifespan_shutdown@@ -1292,10 +1293,36 @@ def _hardware_snapshot() -> Optional[tuple[bool, Optional[str]]]:return None+def _torch_warm_in_progress() -> bool:+ """True while the coordinated warm thread is still working through its stages.++ A separate field from ``hardware_detecting`` on purpose, rather than widening that one.+ Hardware detection is only ``_STAGES[0]``; inference_backend, transformers, datasets and+ unsloth_zoo import after it, and those C-extension imports are the ones that hold the GIL+ for seconds at a time. A launcher ending its startup grace on ``hardware_detecting``+ alone ends it with the expensive half of the warm still ahead of it, which is the window+ the grace exists for. But that marker also means "this hardware verdict is provisional,+ re-read it", and config/hardware-verdict.ts keeps the UI provisional and polling while it+ is set, so keeping it lit through datasets would hide Train for the whole warm over a+ verdict that settled seconds in. Two meanings, two fields.++ A snapshot read of module state, no lock and no wait, so /api/liveness stays cheap.++ False whenever no warm thread is running, which is what keeps the deferred case working:+ with UNSLOTH_STUDIO_DISABLE_TORCH_WARM=1 the warm never starts, and one retired mid-stage+ by a shutdown never finishes. Neither will ever set ``finished``, so deriving this from+ "not finished" would report warming forever and hold the launcher's startup grace open+ until it expired on its own. Absence therefore covers both "warm is over" and "no warm is+ coming", and the field needs no deferred companion of its own.+ """+ status = warm_status()+ return bool(status["started"] and not status["finished"] and status["alive"])++@app.get("/api/liveness")async def liveness_check():"""Cheap process liveness for desktop port validation."""- return {+ alive = {"status": "alive","service": "Unsloth UI Backend","desktop_protocol_version": 1,@@ -1307,6 +1334,23 @@ async def liveness_check():"studio_root_id": _studio_root_id(),**({"desktop_owner": owner} if (owner := _desktop_owner()) else {}),}+ # Same unsettled markers /api/health publishes, and for the desktop health watchdog they+ # are the point of the route: it probes liveness every 15s and holds its startup grace+ # period open until a reply says the warm-up is over, because the warm thread's+ # `import torch` holds the GIL and can stall the next probes on a healthy process.+ # The watchdog reads torch_warm_in_progress for that, not hardware_detecting: the GIL is+ # held just as hard by transformers and unsloth_zoo, which import after detection settles.+ # Both are non-blocking reads of module-level state, so unlike health this neither starts+ # detection nor waits on it and the route stays cheap.+ if _torch_warm_in_progress():+ alive["torch_warm_in_progress"] = True+ if _hardware_snapshot() is None:+ alive["hardware_detecting"] = True+ if os.environ.get(DISABLE_ENV_VAR) == "1":+ # Nothing is detecting while the warm is switched off, so the verdict will not+ # settle on its own. Say so, or the watchdog holds its grace open for nothing.+ alive["hardware_detection_deferred"] = True+ return alive@app.get("/api/health")@@ -1340,6 +1384,10 @@ async def health_check(request: Request):"native_path_leases_supported": native_path_leases_supported(),**({"desktop_owner": owner} if (owner := _desktop_owner()) else {}),}+ # Lockstep with /api/liveness: the launcher falls back to this route on a backend too old+ # to have liveness, so the warm marker has to reach it by the same path.+ if _torch_warm_in_progress():+ base["torch_warm_in_progress"] = Trueif snapshot is None:# chat_only above is the pre-detection default, not a measurement; clients should re-read.base["hardware_detecting"] = True@@ -1386,6 +1434,10 @@ async def health_check(request: Request):authed.pop("hardware_detecting", None)# Same for the deferred marker: the client reads it first and would keep the old reason.authed.pop("hardware_detection_deferred", None)+ # torch_warm_in_progress deliberately survives. It does not qualify the verdict below;+ # a settled verdict is exactly the state where the warm has finished stage one and is+ # off importing transformers, and dropping it here would hand the watchdog the same+ # too-early "startup is over" this field exists to replace.else:# A re-detect started during the bearer await and base carries no chat_only_reason, so a# client reading this as measured would store reason null and stop the sidebar's recovery@@ -1583,7 +1635,7 @@ def get_system_info(current_subject: str = Depends(get_current_subject)):import osimport timeimport logging- from utils.hardware import get_device, export_capability+ from utils.hardware import get_device, export_capability, video_capabilityfrom utils.hardware.hardware import _backend_labellogger = logging.getLogger(__name__)@@ -1659,6 +1711,8 @@ def get_system_info(current_subject: str = Depends(get_current_subject)):"ml_packages": ml_packages,# Export capability + torch-aware reason. See /api/system/hardware.**export_capability(),+ # Video capability + reason, same shape. Additive: older clients ignore the extra keys.+ **video_capability(),}@@ -1682,13 +1736,20 @@ def get_hardware_info(method auto-selection. Sync def (not async): hardware/detail probes canshell out, and FastAPI runs sync endpoints in a threadpool."""- from utils.hardware import get_gpu_summary, get_package_versions, export_capability+ from utils.hardware import (+ get_gpu_summary,+ get_package_versions,+ export_capability,+ video_capability,+ )body = {"gpu": get_gpu_summary(),"versions": get_package_versions(),# Export capability + torch-aware reason; the Export UI grays out with the message.**export_capability(),+ # Video capability + reason; the Video page shows the message in place of the generator.+ **video_capability(),}if include_details:from utils.llama_cpp_update import get_installed_llama_versiondiff --git a/studio/backend/routes/rag.py b/studio/backend/routes/rag.pyindex b078261cb22..918262b934b 100644--- a/studio/backend/routes/rag.py+++ b/studio/backend/routes/rag.py@@ -3,8 +3,14 @@"""HTTP API for the RAG engine: KB CRUD, uploads, SSE ingestion, search.-Single-tenant: the subject gates access, not data. Without sqlite-vec the router-mounts but every endpoint returns 503.+Single-tenant: the subject gates access, not data.++Without a working sqlite-vec the router still mounts, and one contract covers every+endpoint. The KB list is polled, so it answers 200 with an empty list carrying an+availability marker, which is what lets a client tell an empty store from a machine+where RAG cannot run. Every other endpoint answers 503 stating the same reason.+Nothing logs a traceback for it: the condition is fixed for the session and rag_db+warns about it exactly once."""from __future__ import annotations@@ -16,8 +22,11 @@ import loggingimport osimport reimport secrets+import sqlite3import timeimport uuid+from contextlib import contextmanager+from typing import Iteratorfrom fastapi import APIRouter, Depends, File, Form, HTTPException, Query, UploadFilefrom fastapi.responses import FileResponse, StreamingResponse@@ -33,12 +42,56 @@ logger = logging.getLogger(__name__)router = APIRouter()+_UNAVAILABLE_DETAIL = "RAG is unavailable: the sqlite-vec extension could not be loaded."++def _require_rag() -> None:- if not rag_db.RAG_AVAILABLE:- raise HTTPException(- status_code = 503,- detail = "RAG is unavailable: the sqlite-vec extension could not be loaded.",- )+ """Gate an endpoint on RAG being runnable here.++ Covers both halves of unavailable: sqlite-vec never imported, and it imported but+ its native library will not load. 503 with a stated reason rather than the 500 plus+ traceback a raising connection would produce, and rag_db's warn-once keeps the log+ quiet however often this fires.+ """+ if not rag_db.rag_available():+ raise HTTPException(status_code = 503, detail = _UNAVAILABLE_DETAIL)+++@contextmanager+def _rag_unavailable_as_503(cleanup_path: str | None = None) -> Iterator[None]:+ """Report RagExtensionUnavailable as the same 503, wherever it is raised.++ _require_rag() has normally answered for the session already; this closes the window+ where the very first request is the one that discovers the missing library, and it+ reaches the connections ingestion opens for itself. ``cleanup_path`` removes an+ upload that was saved before the failure, so nothing is orphaned in the uploads+ root. Real database errors are left alone.+ """+ try:+ yield+ except rag_db.RagExtensionUnavailable as exc:+ _remove_stored_upload(cleanup_path)+ raise HTTPException(status_code = 503, detail = _UNAVAILABLE_DETAIL) from exc+++def _rag_connection() -> sqlite3.Connection:+ """rag_db.get_connection() with the unavailable case reported as 503."""+ with _rag_unavailable_as_503():+ return rag_db.get_connection()+++def _availability(available: bool) -> dict:+ """Availability marker carried by the KB list, the one response that degrades+ rather than erroring.++ Additive: a client that only reads the list is unaffected, one that reads this can+ say "RAG cannot run here" instead of showing an empty page that looks ready to use+ and offering a Create that can only 503.+ """+ return {+ "ragAvailable": available,+ "ragUnavailableReason": None if available else _UNAVAILABLE_DETAIL,+ }_SAFE = re.compile(r"[^A-Za-z0-9._-]+")@@ -194,8 +247,18 @@ class SearchRequest(BaseModel):@router.get("/knowledge-bases")def list_knowledge_bases(subject: str = Depends(get_current_subject)) -> dict:- _require_rag()- conn = rag_db.get_connection()+ try:+ conn = rag_db.get_connection()+ except rag_db.RagExtensionUnavailable:+ # RAG_AVAILABLE only covers the import; the native library can still fail to+ # load per connection (a missing vec0 binary in the venv). The UI polls this+ # list, so 500ing here costs a traceback every few seconds for a condition that+ # never changes within a session. rag_db has warned once; an empty list is what+ # a machine without RAG has anyway. The marker is what keeps that honest: it is+ # the difference between "no knowledge bases yet" and "RAG cannot run here", and+ # without it the empty page looks ready to use. Only the unavailable case+ # degrades: a locked or corrupt database still raises.+ return {"knowledgeBases": [], **_availability(False)}try:kbs = store.list_kbs(conn)out = []@@ -210,7 +273,7 @@ def list_knowledge_bases(subject: str = Depends(get_current_subject)) -> dict:"documentCount": len(docs),})- return {"knowledgeBases": out}+ return {"knowledgeBases": out, **_availability(True)}finally:conn.close()@@ -220,7 +283,7 @@ def create_knowledge_base(payload: CreateKbRequest, subject: str = Depends(get_current_subject)) -> dict:_require_rag()- conn = rag_db.get_connection()+ conn = _rag_connection()try:kb_id = store.create_kb(conn,@@ -240,7 +303,7 @@ def update_knowledge_base(subject: str = Depends(get_current_subject),) -> dict:_require_rag()- conn = rag_db.get_connection()+ conn = _rag_connection()try:if store.get_kb(conn, kb_id) is None:raise HTTPException(status_code = 404, detail = "Knowledge base not found")@@ -263,7 +326,7 @@ def update_knowledge_base(@router.delete("/knowledge-bases/{kb_id}")def delete_knowledge_base(kb_id: str, subject: str = Depends(get_current_subject)) -> dict:_require_rag()- conn = rag_db.get_connection()+ conn = _rag_connection()try:if store.get_kb(conn, kb_id) is None:raise HTTPException(status_code = 404, detail = "Knowledge base not found")@@ -283,23 +346,24 @@ async def upload_kb_document(subject: str = Depends(get_current_subject),) -> dict:_require_rag()- conn = rag_db.get_connection()+ conn = _rag_connection()try:if store.get_kb(conn, kb_id) is None:raise HTTPException(status_code = 404, detail = "Knowledge base not found")finally:conn.close()stored_path, filename = _resolve_document_upload(file, native_path_lease)- document_id, job_id = ingestion.start_ingestion(- store.kb_scope(kb_id), kb_id, None, filename, stored_path, ocr = ocr, caption = caption- )+ with _rag_unavailable_as_503(stored_path):+ document_id, job_id = ingestion.start_ingestion(+ store.kb_scope(kb_id), kb_id, None, filename, stored_path, ocr = ocr, caption = caption+ )return {"documentId": document_id, "jobId": job_id, "filename": filename}@router.get("/knowledge-bases/{kb_id}/documents")def list_kb_documents(kb_id: str, subject: str = Depends(get_current_subject)) -> dict:_require_rag()- conn = rag_db.get_connection()+ conn = _rag_connection()try:docs = store.list_documents(conn, store.kb_scope(kb_id))return {"documents": [_doc_view(d) for d in docs]}@@ -318,22 +382,23 @@ async def upload_thread_document() -> dict:_require_rag()stored_path, filename = _resolve_document_upload(file, native_path_lease)- document_id, job_id = ingestion.start_ingestion(- store.thread_scope(thread_id),- None,- thread_id,- filename,- stored_path,- ocr = ocr,- caption = caption,- )+ with _rag_unavailable_as_503(stored_path):+ document_id, job_id = ingestion.start_ingestion(+ store.thread_scope(thread_id),+ None,+ thread_id,+ filename,+ stored_path,+ ocr = ocr,+ caption = caption,+ )return {"documentId": document_id, "jobId": job_id, "filename": filename}@router.get("/threads/{thread_id}/documents")def list_thread_documents(thread_id: str, subject: str = Depends(get_current_subject)) -> dict:_require_rag()- conn = rag_db.get_connection()+ conn = _rag_connection()try:docs = store.list_documents(conn, store.thread_scope(thread_id))return {"documents": [_doc_view(d) for d in docs]}@@ -356,23 +421,24 @@ async def upload_project_document(if get_chat_project(project_id) is None:raise HTTPException(status_code = 404, detail = "Project not found")stored_path, filename = _resolve_document_upload(file, native_path_lease)- document_id, job_id = ingestion.start_ingestion(- store.project_scope(project_id),- None,- None,- filename,- stored_path,- project_id = project_id,- ocr = ocr,- caption = caption,- )+ with _rag_unavailable_as_503(stored_path):+ document_id, job_id = ingestion.start_ingestion(+ store.project_scope(project_id),+ None,+ None,+ filename,+ stored_path,+ project_id = project_id,+ ocr = ocr,+ caption = caption,+ )return {"documentId": document_id, "jobId": job_id, "filename": filename}@router.get("/projects/{project_id}/documents")def list_project_documents(project_id: str, subject: str = Depends(get_current_subject)) -> dict:_require_rag()- conn = rag_db.get_connection()+ conn = _rag_connection()try:docs = store.list_documents(conn, store.project_scope(project_id))return {"documents": [_doc_view(d) for d in docs]}@@ -385,7 +451,7 @@ def list_all_uploaded_documents(subject: str = Depends(get_current_subject)) ->"""Every uploaded file across chats, projects, and knowledge bases (settingsData tab)."""_require_rag()- conn = rag_db.get_connection()+ conn = _rag_connection()try:docs = store.list_all_documents(conn)kb_names = {kb["id"]: kb["name"] for kb in store.list_kbs(conn)}@@ -416,7 +482,7 @@ def list_all_uploaded_documents(subject: str = Depends(get_current_subject)) ->@router.delete("/documents/{document_id}")def delete_document(document_id: str, subject: str = Depends(get_current_subject)) -> dict:_require_rag()- conn = rag_db.get_connection()+ conn = _rag_connection()try:doc = store.get_document(conn, document_id)if doc is None:@@ -431,7 +497,8 @@ def delete_document(document_id: str, subject: str = Depends(get_current_subject@router.get("/jobs/{job_id}")def job_status(job_id: str, subject: str = Depends(get_current_subject)) -> dict:_require_rag()- row = ingestion.get_job_status(job_id)+ with _rag_unavailable_as_503():+ row = ingestion.get_job_status(job_id)if row is None:raise HTTPException(status_code = 404, detail = "Job not found")return {@@ -479,7 +546,7 @@ def search(payload: SearchRequest, subject: str = Depends(get_current_subject))raise HTTPException(status_code = 400, detail = "Provide kb_id, project_id, or thread_id")scope = scopes[0] if len(scopes) == 1 else scopes- conn = rag_db.get_connection()+ conn = _rag_connection()try:if payload.mode == "lexical":hits = retrieval.retrieve_lexical(conn, scope, payload.query, payload.top_k)@@ -560,7 +627,7 @@ def preview_target() -> dict:"""Resolve a citation to filename, page, and highlight regions."""_require_rag()- conn = rag_db.get_connection()+ conn = _rag_connection()try:doc = store.get_document(conn, document_id)if doc is None:@@ -596,7 +663,7 @@ def preview_target(def document_file_url(document_id: str, subject: str = Depends(get_current_subject)) -> dict:"""Mint a short-lived signed URL for the source file."""_require_rag()- conn = rag_db.get_connection()+ conn = _rag_connection()try:doc = store.get_document(conn, document_id)if doc is None or not doc.get("stored_path"):@@ -611,11 +678,13 @@ def document_file_url(document_id: str, subject: str = Depends(get_current_subjedef document_file_signed(document_id: str, token: str = Query(...)) -> FileResponse:"""Serve the source file gated by the HMAC token (no bearer) so pdf.js rangerequests work."""- _require_rag()+ # Token first: this is the one endpoint with no bearer, and _require_rag() now opens+ # a connection on its first call, which is not work an unverified token should buy.signed_id = _verify_document_token(token)if signed_id != document_id:raise HTTPException(status_code = 401, detail = "Invalid or expired token")- conn = rag_db.get_connection()+ _require_rag()+ conn = _rag_connection()try:doc = store.get_document(conn, document_id)finally:diff --git a/studio/backend/run.py b/studio/backend/run.pyindex ca97404066a..86667f8ee39 100644--- a/studio/backend/run.py+++ b/studio/backend/run.py@@ -138,7 +138,7 @@ except ValueError as exc:# See: https://github.com/python/cpython/issues/102396import _platform_compat # noqa: F401-from loggers import get_logger+from loggers import get_logger, install_uvicorn_duplicate_exception_filterfrom startup_banner import print_studio_access_banner, print_studio_stop_hintlogger = get_logger(__name__)@@ -2018,6 +2018,10 @@ def run_server(# Resolve once; shared by the log rewrite and banner.display_host = _display_host_for_bind(host)_install_uvicorn_startup_log_rewrite(host, display_host)+ # LoggingMiddleware already logs every unhandled request exception with its full+ # traceback as a structured event; without this uvicorn prints the same traceback+ # again on stderr and the desktop shell copies it into tauri.log line by line.+ install_uvicorn_duplicate_exception_filter()logger.info("run_server pre-uvicorn setup completed in %.1fms",diff --git a/studio/backend/storage/rag_db.py b/studio/backend/storage/rag_db.pyindex cbd6ceb617f..c21e21e3a0a 100644--- a/studio/backend/storage/rag_db.py+++ b/studio/backend/storage/rag_db.py@@ -5,8 +5,9 @@Same pattern as providers_db.py / studio_db.py (module functions, raw sqlite3,WAL, per-call connections, lazy schema), but every connection also loads-sqlite-vec (vec0 needs it per-connection). If it cannot load, RAG_AVAILABLE is-False and get_connection() raises rather than failing import.+sqlite-vec (vec0 needs it per-connection). If it cannot load, get_connection()+raises RagExtensionUnavailable rather than failing import, and rag_available()+reports the machine as one where RAG cannot run.One rag.db holds the ``documents`` / ``chunks`` model, the FTS5 lexical index(``chunks_fts``) and the sqlite-vec dense index (``chunks_vec``, created lazily@@ -34,8 +35,66 @@ except Exception as exc: # noqa: BLE001 - any import failure disables RAG_RAG_UNAVAILABLE_MSG = "RAG unavailable: sqlite-vec extension could not be loaded"++class RagExtensionUnavailable(RuntimeError):+ """sqlite-vec is installed but its native library will not load (a missing+ vec0 binary in the venv is the common macOS case). Subclasses RuntimeError so+ existing ``except RuntimeError`` callers are unaffected; it exists so a caller+ can tell "RAG is switched off on this machine" from a real database error and+ degrade instead of returning 500 on every poll."""++_schema_lock = threading.Lock()_schema_ready = False+# The dylib is either there or it is not, and the UI polls the KB list on a timer, so+# one warning per process says everything the repeat lines would. Same shape as the+# per-job throttle in hub/services/snapshot_progress.py.+_unavailable_lock = threading.Lock()+_unavailable_warned = False+# Set once a connection has actually loaded the extension, so the request gate can+# answer without reopening the database. Only the positive verdict is kept: a failure+# stays retried per connection exactly as it was before, so a one-off cannot latch RAG+# off for the rest of the session.+_extension_loaded = False+++def _warn_unavailable_once(exc: BaseException | None = None) -> None:+ """Log the sqlite-vec unavailability at most once per process."""+ global _unavailable_warned+ with _unavailable_lock:+ if _unavailable_warned:+ return+ _unavailable_warned = True+ logger.warning(+ "%s; RAG features are disabled for this session%s",+ _RAG_UNAVAILABLE_MSG,+ f" ({exc})" if exc is not None else "",+ )+++def rag_available() -> bool:+ """Whether RAG can actually run in this process.++ RAG_AVAILABLE only records that ``import sqlite_vec`` worked. The vec0 native+ library it loads is a separate file, and a venv can have the package without it+ (the common macOS case), which nothing finds out until a connection tries. So try,+ unless one already got through: a machine where RAG works answers from the flag+ instead of opening a second connection per request, and a machine where it does not+ pays the same failed connect it paid before, quietly.++ A genuine database error (locked, corrupt, bad schema) is not an answer to this+ question, so it propagates instead of being reported as "RAG is off here".+ """+ if not RAG_AVAILABLE:+ return False+ if _extension_loaded:+ return True+ try:+ conn = get_connection()+ except RagExtensionUnavailable:+ return False+ conn.close()+ return Truedef _ensure_schema(conn: sqlite3.Connection) -> None:@@ -117,9 +176,9 @@ def _ensure_schema(conn: sqlite3.Connection) -> None:def get_connection() -> sqlite3.Connection:"""Open rag.db (WAL + sqlite-vec loaded, schema created once). Raises if the extension is unavailable."""- global _schema_ready+ global _schema_ready, _extension_loadedif not RAG_AVAILABLE:- raise RuntimeError(_RAG_UNAVAILABLE_MSG)+ raise RagExtensionUnavailable(_RAG_UNAVAILABLE_MSG)db_path = rag_db_path()ensure_dir(db_path.parent)@@ -135,7 +194,11 @@ def get_connection() -> sqlite3.Connection:conn.enable_load_extension(False)except Exception as exc: # noqa: BLE001conn.close()- raise RuntimeError(_RAG_UNAVAILABLE_MSG) from exc+ _warn_unavailable_once(exc)+ raise RagExtensionUnavailable(_RAG_UNAVAILABLE_MSG) from exc+ # Set before the schema step: the library loaded, so RAG runs on this machine+ # whatever a broken database does next. A monotonic flip, so no lock.+ _extension_loaded = Trueif not _schema_ready:with _schema_lock:@@ -216,7 +279,10 @@ def reconcile_orphaned_ingestion_jobs() -> int:showing as stuck "processing" and become re-ingestible. Run at startup.No-op without RAG. Returns the number of jobs reset."""- if not RAG_AVAILABLE:+ # rag_available(), not RAG_AVAILABLE: a venv with the package but no vec0 binary+ # would otherwise raise out of startup and be logged as a reconcile failure, when+ # there is simply nothing here to reconcile.+ if not rag_available():return 0conn = get_connection()try:diff --git a/studio/backend/tests/test_liveness_reports_warmup_state.py b/studio/backend/tests/test_liveness_reports_warmup_state.pynew file mode 100644index 00000000000..da28b641094--- /dev/null+++ b/studio/backend/tests/test_liveness_reports_warmup_state.py@@ -0,0 +1,278 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Invariant: /api/liveness says whether the backend is still warming up, and stays cheap.++The desktop health watchdog probes this route every 15s and kills the backend after 3+consecutive misses. It cannot use /api/health for that -- health awaits hardware detection,+so a probe is billed for the warm thread's `import torch` -- and it cannot treat one reply+as "startup finished" either, because those C-extension imports hold the GIL and stall the+next probes on a process that is perfectly healthy. So liveness carries a+`torch_warm_in_progress` marker and the watchdog holds its startup grace open until a reply+omits it. See studio/src-tauri/src/commands.rs.++That marker tracks the whole coordinated warm, not hardware detection alone: detection is+only the first of utils/torch_warmup.py's stages and the inference_backend, transformers,+datasets and unsloth_zoo imports that follow it are the ones that stall a probe. The older+`hardware_detecting` marker stays exactly what it was, a "this verdict is provisional"+signal the frontend reads, and is still published beside it.++The markers must not cost what health costs: liveness reads settled snapshots, it must+never start detection or wait on it.++CPU-only, no network, no GPU, no weights: the subprocess tests stub detection.+"""++from __future__ import annotations++import json+import re+import subprocess+import sys+from pathlib import Path++_BACKEND_DIR = Path(__file__).resolve().parent.parent # studio/backend+_COMMANDS_RS = _BACKEND_DIR.parent / "src-tauri" / "src" / "commands.rs"+++_SNIPPET = r"""+import json, os, time++# The warm is what would settle the verdict, and these tests decide by hand whether it is+# settled, so keep a real one out of the way. DEFERRED picks the kill switch on or off.+if %(deferred)s:+ os.environ["UNSLOTH_STUDIO_DISABLE_TORCH_WARM"] = "1"+else:+ os.environ.pop("UNSLOTH_STUDIO_DISABLE_TORCH_WARM", None)++import main+from fastapi import FastAPI+from fastapi.testclient import TestClient++hw = main._hw_module++# The real warm imports the ML stack, which is the cost these tests exist to keep off the+# route, so drive its published state by hand instead. WARM picks which of the four states+# the thread can be observed in.+import utils.torch_warmup as tw++class _FakeWarmThread:+ def __init__(self, alive):+ self._alive = alive+ def is_alive(self):+ return self._alive++# started / finished / thread, per state:+# running -- mid-stage, the state the startup grace is for+# finished -- every stage done, so startup really is over+# never -- the kill switch is on and no warm was ever started+# retired -- a shutdown stopped it between stages; it will never set finished+tw._status["started"], tw._status["finished"], tw._thread = {+ "running": (True, False, _FakeWarmThread(True)),+ "finished": (True, True, _FakeWarmThread(False)),+ "never": (False, False, None),+ "retired": (True, False, _FakeWarmThread(False)),+}[%(warm)r]++if %(settled)s:+ hw.DEVICE = hw.DeviceType.CPU+ hw.CHAT_ONLY = True+ hw.CHAT_ONLY_REASON = "no_accelerator"+ hw.DETECTION_COMPLETE.set()+else:+ # "detection has not run": DEVICE alone is not the completion signal, the branches+ # assign it partway through, so clear the event too.+ hw.DEVICE = None+ hw.CHAT_ONLY = True+ hw.CHAT_ONLY_REASON = None+ hw.DETECTION_COMPLETE.clear()++def must_not_run(*_):+ raise AssertionError("liveness started hardware detection")++hw.ensure_hardware_detected = must_not_run++app = FastAPI()+app.add_api_route("/api/liveness", main.liveness_check, methods = ["GET"])+client = TestClient(app)++started = time.perf_counter()+response = client.get("/api/liveness")+elapsed = time.perf_counter() - started+body = response.json()++print("RESULT" + json.dumps({+ "status_code": response.status_code,+ "elapsed": elapsed,+ "status": body.get("status"),+ "service": body.get("service"),+ "hardware_detecting": body.get("hardware_detecting"),+ "hardware_detection_deferred": body.get("hardware_detection_deferred"),+ "has_detecting_key": "hardware_detecting" in body,+ "torch_warm_in_progress": body.get("torch_warm_in_progress"),+ "has_warm_key": "torch_warm_in_progress" in body,+ "studio_root_id": body.get("studio_root_id"),+ "has_root_id": "studio_root_id" in body,+}))+"""+++def _probe(+ settled: bool,+ deferred: bool = False,+ warm: str = "running",+) -> dict:+ proc = subprocess.run(+ [+ sys.executable,+ "-c",+ _SNIPPET % {"settled": settled, "deferred": deferred, "warm": warm},+ ],+ cwd = str(_BACKEND_DIR),+ capture_output = True,+ text = True,+ timeout = 900,+ )+ assert (+ proc.returncode == 0+ ), f"probe failed\nstdout:\n{proc.stdout}\nstderr:\n{proc.stderr[-4000:]}"+ line = next(ln for ln in proc.stdout.splitlines() if ln.startswith("RESULT"))+ return json.loads(line[len("RESULT") :])+++def test_an_unsettled_verdict_is_published_as_still_warming_up():+ """Without this the watchdog ends its startup grace on the first reply, and the next+ GIL stall inside the torch import reads as three dead probes."""+ result = _probe(settled = False)++ assert result["status_code"] == 200+ assert result["status"] == "alive"+ assert result["service"] == "Unsloth UI Backend"+ assert result["torch_warm_in_progress"] is True+ assert result["hardware_detecting"] is True+ assert result["hardware_detection_deferred"] is None, (+ "the warm is running here; a deferred marker would tell the watchdog the verdict "+ "will never settle"+ )+++def test_a_late_warm_stage_still_holds_the_startup_grace_open():+ """The regression: hardware detection is _STAGES[0], and inference_backend,+ transformers, datasets and unsloth_zoo import after it.++ So hardware_detecting is already gone while the warm is at its most expensive. A+ watchdog reading only that marker ends its grace mid-warm and the next GIL stall,+ which is exactly what the reported "torch warm finished in 8190.4ms" timeline shows+ happening well after detection, is billed as three dead probes against a healthy+ backend."""+ result = _probe(settled = True, warm = "running")++ assert not result["has_detecting_key"], (+ "the point of this case is a settled verdict; if detection still reads unsettled "+ "the late-stage window is not being modelled"+ )+ assert result["torch_warm_in_progress"] is True, (+ "liveness reports startup finished while the warm is still importing transformers, "+ "datasets and unsloth_zoo; the watchdog ends its grace and the next GIL stall kills "+ "a backend that is starting normally"+ )+++def test_a_settled_verdict_carries_no_warming_up_marker():+ """The markers are the whole signal, so they have to disappear once the warm is done, or+ the watchdog never counts a real failure until the grace period expires."""+ result = _probe(settled = True, warm = "finished")++ assert result["status"] == "alive"+ assert not result["has_detecting_key"], (+ "liveness still reports hardware_detecting after detection settled; the desktop "+ "watchdog would hold its startup grace open for the full 5 minutes"+ )+ assert not result["has_warm_key"], (+ "liveness still reports torch_warm_in_progress after every stage finished; the "+ "watchdog would never count a failure against a genuinely hung backend"+ )+++def test_a_deferred_warm_says_so_instead_of_looking_like_a_slow_start():+ """With UNSLOTH_STUDIO_DISABLE_TORCH_WARM=1 nothing will settle the verdict, so a bare+ hardware_detecting would be indistinguishable from a backend still importing torch."""+ result = _probe(settled = False, deferred = True, warm = "never")++ assert result["hardware_detecting"] is True+ assert result["hardware_detection_deferred"] is True+ assert not result["has_warm_key"], (+ "no warm was started, so nothing will ever finish one; a warm marker here would "+ "hold the watchdog's startup grace open until it expired on its own"+ )+++def test_a_warm_retired_mid_stage_is_not_reported_as_warming_forever():+ """A shutdown stops the warm at a stage boundary, so it never sets finished and its+ thread is gone. Deriving the marker from "not finished" alone would leave it lit for+ the rest of the process, which is the deferred trap by another route."""+ result = _probe(settled = False, warm = "retired")++ assert not result["has_warm_key"], (+ "a warm whose thread has exited is reported as still running; the watchdog would "+ "hold its startup grace open for the full 5 minutes and never trust the backend"+ )+++def test_liveness_answers_immediately_and_never_starts_detection():+ """The route exists because health's detection wait is too expensive to probe every+ 15s. The stub raises if detection is started, so returning at all proves it was not."""+ result = _probe(settled = False)++ assert result["elapsed"] < 0.5, (+ f"/api/liveness took {result['elapsed']:.2f}s; it must read the settled snapshot "+ f"rather than wait for one"+ )+ # Still the full port-validation payload the launcher matches on. The key must be+ # present because the launcher reads it; its value is environment-derived and is+ # legitimately empty on a bare CI runner, so presence is what this asserts.+ #+ # Read it off has_root_id, not off `result`. The subprocess snippet builds `result`+ # with `body.get("studio_root_id")`, so the key exists in `result` whether or not the+ # reply carried it -- `"studio_root_id" in result` was true even with the field+ # deleted from liveness_check(). Its two neighbours already use this indirection.+ assert result["has_root_id"], (+ "/api/liveness dropped studio_root_id; desktop_backend_owner.rs deserializes it "+ "into DesktopLiveness and rejects a sibling port without it"+ )+++def test_the_desktop_watchdog_still_reads_these_fields():+ """Cross-language guard: the marker only does anything because commands.rs reads it,+ and either side can be changed without the other."""+ assert _COMMANDS_RS.is_file(), f"{_COMMANDS_RS} moved; update this guard"+ rust = _COMMANDS_RS.read_text(encoding = "utf-8")+ probe = rust[rust.index("async fn check_health_inner") :]+ end = probe.find("\n}\n")+ if end != -1:+ probe = probe[: end + 3]++ assert '"/api/liveness"' in probe, (+ "the watchdog probe no longer asks for /api/liveness; it must not go back to "+ "/api/health, which awaits hardware detection"+ )+ assert '"torch_warm_in_progress"' in probe, (+ "the watchdog probe no longer reads torch_warm_in_progress, so one early reply ends "+ "the startup grace again and a GIL stall can kill a healthy backend"+ )+ assert '"hardware_detecting"' in probe, (+ "the watchdog probe dropped its hardware_detecting fallback; a backend older than "+ "torch_warm_in_progress then gets no startup grace at all"+ )+ assert '"hardware_detection_deferred"' in probe++ match = re.search(r"const HEALTH_PROBE_TIMEOUT: Duration = Duration::from_secs\((\d+)\)", rust)+ assert match, "commands.rs no longer sets a whole-seconds probe timeout"+ interval = re.search(+ r"const HEALTH_WATCHDOG_INTERVAL: Duration = Duration::from_secs\((\d+)\)", rust+ )+ assert interval, "commands.rs no longer sets a whole-seconds watchdog interval"+ assert int(match.group(1)) < int(interval.group(1)), (+ f"a {match.group(1)}s probe outlives the {interval.group(1)}s watchdog interval, "+ f"so the next tick starts on top of the last one"+ )diff --git a/studio/backend/tests/test_logging_middleware.py b/studio/backend/tests/test_logging_middleware.pyindex 23d87dc4079..1ca5b370f7f 100644--- a/studio/backend/tests/test_logging_middleware.py+++ b/studio/backend/tests/test_logging_middleware.py@@ -435,6 +435,58 @@ def test_verbose_restores_the_dropped_success_polls(logs, monkeypatch):logs.events.clear()+def test_boot_burst_catalog_reads_suppressed(logs):+ # The catalog reads the SPA fans out on every auth change / rehydration: their 2xx+ # only restates the list the UI is already showing.+ for path in (+ "/api/providers/registry",+ "/api/providers/",+ "/api/models/loras",+ "/api/settings/personalization",+ ):+ _run(LoggingMiddleware(_status_app(200))(_http_scope(path), _noop_receive, _drop))+ assert logs.events == []+++def test_boot_burst_catalog_errors_still_log(logs):+ # 4xx/5xx on the same paths are real failures and stay visible.+ for path, status in (+ ("/api/providers/registry", 500),+ ("/api/providers/", 502),+ ("/api/models/loras", 404),+ ("/api/settings/personalization", 401),+ ):+ _run(LoggingMiddleware(_status_app(status))(_http_scope(path), _noop_receive, _drop))+ assert _paths_logged(logs) == [+ "/api/providers/registry",+ "/api/providers/",+ "/api/models/loras",+ "/api/settings/personalization",+ ]+++def test_boot_burst_catalog_mutations_still_log(logs):+ # Suppression is GET-only: creating a provider or saving a profile keeps its line.+ for path, method in (+ ("/api/providers/", "POST"),+ ("/api/settings/personalization", "PUT"),+ ):+ _run(+ LoggingMiddleware(_status_app(200))(+ _http_scope(path, method = method), _noop_receive, _drop+ )+ )+ assert _paths_logged(logs) == ["/api/providers/", "/api/settings/personalization"]+++def test_provider_detail_routes_still_log(logs, monkeypatch):+ # Only the exact list/registry paths are quieted; per-provider reads keep theirs.+ monkeypatch.setattr(hmod, "_ACCESS_LOG_DEDUP_MS", 0)+ for path in ("/api/providers/abc123", "/api/providers/registry/openai"):+ _run(LoggingMiddleware(_status_app(200))(_http_scope(path), _noop_receive, _drop))+ assert _paths_logged(logs) == ["/api/providers/abc123", "/api/providers/registry/openai"]++def test_verbose_off_by_default_keeps_the_polls_quiet(logs):# Default env leaves both windows set, so a normal launch is unchanged.assert hmod._VERBOSE_ACCESS_LOG is Falsediff --git a/studio/backend/tests/test_mlx_repair.py b/studio/backend/tests/test_mlx_repair.pyindex 81f54d317f0..9bcc93d742d 100644--- a/studio/backend/tests/test_mlx_repair.py+++ b/studio/backend/tests/test_mlx_repair.py@@ -357,3 +357,116 @@ def test_mlx_install_env_routes_uv_override_through_safe_path(monkeypatch):assert "path" in seenassert str(seen["path"]).endswith("overrides-darwin-arm64.txt")assert env["UV_OVERRIDE"] == "/space_free/marker.txt"+++def _fake_venv(tmp_path: Path) -> Path:+ """A venv-shaped directory: uv accepts a root that carries pyvenv.cfg."""+ (tmp_path / "pyvenv.cfg").write_text("home = /usr/bin\n", encoding = "utf-8")+ (tmp_path / "bin").mkdir()+ return tmp_path+++def test_venv_root_is_none_outside_a_venv(monkeypatch, tmp_path):+ monkeypatch.setattr(mr.sys, "prefix", str(tmp_path))+ monkeypatch.setattr(mr.sys, "base_prefix", str(tmp_path))+ assert mr._venv_root() is None+++def test_venv_root_requires_the_marker_file(monkeypatch, tmp_path):+ # A half-deleted tree must not be offered to uv as an install target.+ monkeypatch.setattr(mr.sys, "prefix", str(tmp_path))+ monkeypatch.setattr(mr.sys, "base_prefix", "/usr")+ assert mr._venv_root() is None+ _fake_venv(tmp_path)+ assert mr._venv_root() == str(tmp_path)+++def test_install_env_names_the_target_venv_for_uv(monkeypatch, tmp_path):+ # VIRTUAL_ENV is set from sys.prefix, never forwarded from os.environ: it names+ # the environment uv installs into, so inheriting it would let a caller+ # redirect the install.+ venv = _fake_venv(tmp_path)+ monkeypatch.setattr(mr.sys, "prefix", str(venv))+ monkeypatch.setattr(mr.sys, "base_prefix", "/usr")+ monkeypatch.setenv("VIRTUAL_ENV", "/tmp/attacker-controlled")++ env = mr._mlx_install_env()++ assert env["VIRTUAL_ENV"] == str(venv)+++def test_unresolvable_venv_reports_the_unsloth_repair_command(monkeypatch, tmp_path, capsys):+ # uv's own text tells the user to run `uv venv`, which would build an+ # environment Unsloth does not manage. Point at `unsloth studio update`.+ venv = _fake_venv(tmp_path)+ monkeypatch.setattr(mr.sys, "prefix", str(venv))+ monkeypatch.setattr(mr.sys, "base_prefix", "/usr")+ monkeypatch.setattr(mr, "_uv_executable", lambda: "/usr/bin/uv")+ monkeypatch.setattr(mr, "_transformers_constraint_args", lambda: ([], None))++ class _Result:+ returncode = 2+ stdout = "error: No virtual environment or system Python installation found\n"++ monkeypatch.setattr(mr.subprocess, "run", lambda cmd, **kw: _Result())++ assert mr.attempt_mlx_repair() is False++ # structlog renders to stdout, not through the stdlib logging caplog handler.+ text = capsys.readouterr().out+ assert "unsloth studio update" in text+ assert "uv venv" not in text.split("uv said:")[0]+++def test_virtual_env_is_not_advertised_as_a_dangling_symlink_recovery():+ """The docstring must not re-sell the reverted placebo.++ _mlx_install_env once claimed VIRTUAL_ENV let uv "identify the target environment+ even when bin/python no longer resolves", and named a _uv_python_target helper. Both+ were removed: an explicit --python outranks VIRTUAL_ENV, so uv reports the same+ unresolved-interpreter error either way. The claim outlived the code and then misled a+ reviewer into asking for the mechanism back, so pin it rather than trusting prose.+ """+ src = (Path(mr.__file__)).read_text(encoding = "utf-8")+ assert "_uv_python_target" not in src, (+ "_uv_python_target was deleted with the venv-root retry; a reference to it means "+ "the placebo is back or the comment is stale again"+ )+ doc = mr._mlx_install_env.__doc__ or ""+ assert "even when bin/python no longer resolves" not in doc, (+ "the docstring claims VIRTUAL_ENV recovers a dangling interpreter, which uv "+ "disproves: --python outranks it and both paths report the same error"+ )+++def test_an_unresolvable_interpreter_is_diagnosed_not_retried(monkeypatch, tmp_path):+ """One uv attempt, then a diagnosis -- never a second install with a different target.++ --target and --prefix do exit 0 against a broken venv, but resolve against whatever+ ambient interpreter uv finds and write a wrong-ABI or off-sys.path install. That looks+ like a repair while leaving mlx_stack_available() False, so it must never be reached.+ """+ venv = _fake_venv(tmp_path)+ monkeypatch.setattr(mr.sys, "prefix", str(venv))+ monkeypatch.setattr(mr.sys, "base_prefix", "/usr")+ monkeypatch.setattr(mr, "_uv_executable", lambda: "/usr/bin/uv")+ monkeypatch.setattr(mr, "_transformers_constraint_args", lambda: ([], None))++ calls = []++ class _Result:+ returncode = 2+ stdout = "error: No virtual environment or system Python installation found\n"++ def _run(cmd, **kw):+ calls.append(cmd)+ return _Result()++ monkeypatch.setattr(mr.subprocess, "run", _run)++ assert mr.attempt_mlx_repair() is False+ assert len(calls) == 1, f"uv was invoked {len(calls)} times; the retry is back: {calls}"+ flat = " ".join(str(part) for part in calls[0])+ assert (+ "--target" not in flat and "--prefix" not in flat+ ), f"a corrupting install target reached the uv command line: {flat}"diff --git a/studio/backend/tests/test_rag_unavailable_quiet.py b/studio/backend/tests/test_rag_unavailable_quiet.pynew file mode 100644index 00000000000..207d4b64fed--- /dev/null+++ b/studio/backend/tests/test_rag_unavailable_quiet.py@@ -0,0 +1,400 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""A missing sqlite-vec binary must be reported once, not on every KB poll.++sqlite_vec imports fine while its native vec0 library is absent from the venv (a+real macOS condition), so RAG_AVAILABLE stays True and every+/api/rag/knowledge-bases poll used to raise, producing a 500 plus two full+tracebacks a few seconds apart for a condition that cannot change mid-session.+rag_db now warns once and raises RagExtensionUnavailable.++The router answers that with one contract: the polled KB list degrades to an empty+list plus an availability marker, so the frontend can tell an empty store from a+machine where RAG cannot run, and every other endpoint answers a clean 503 carrying+the same reason, so clicking Create in that state gets a stated reason rather than a+500 and a fresh traceback. Genuine database errors are untouched.+"""++import sqlite3++import pytest+from fastapi import HTTPException++from storage import rag_db++UNAVAILABLE = "RAG is unavailable: the sqlite-vec extension could not be loaded."+++def reset_unavailable_warning(monkeypatch):+ """Each test starts from an unwarned process that has not yet loaded the library."""+ monkeypatch.setattr(rag_db, "_unavailable_warned", False)+ monkeypatch.setattr(rag_db, "_extension_loaded", False)+++def _break_extension_load(monkeypatch, exc = None):+ """Make sqlite_vec.load fail the way a missing vec0 dylib does."""++ class _Stub:+ @staticmethod+ def load(conn):+ raise exc or sqlite3.OperationalError("dlopen(vec0.dylib): no such file")++ monkeypatch.setattr(rag_db, "sqlite_vec", _Stub)+ monkeypatch.setattr(rag_db, "RAG_AVAILABLE", True)+++def _client():+ """The RAG router alone behind TestClient, with the subject dependency stubbed."""+ from fastapi import FastAPI+ from fastapi.testclient import TestClient++ from auth.authentication import get_current_subject+ from routes import rag as rag_routes++ app = FastAPI()+ app.include_router(rag_routes.router, prefix = "/api/rag")+ app.dependency_overrides[get_current_subject] = lambda: "tester"+ return TestClient(app)+++def test_unavailable_is_a_runtime_error_subclass():+ # Callers that already catch RuntimeError keep working.+ assert issubclass(rag_db.RagExtensionUnavailable, RuntimeError)+++def test_extension_load_failure_raises_the_typed_error(+ rag_home, reset_unavailable_warning, monkeypatch+):+ _break_extension_load(monkeypatch)+ with pytest.raises(rag_db.RagExtensionUnavailable):+ rag_db.get_connection()+++def test_import_failure_also_raises_the_typed_error(reset_unavailable_warning, monkeypatch):+ monkeypatch.setattr(rag_db, "RAG_AVAILABLE", False)+ with pytest.raises(rag_db.RagExtensionUnavailable):+ rag_db.get_connection()+++def test_unavailability_warns_only_once(rag_home, reset_unavailable_warning, monkeypatch, caplog):+ _break_extension_load(monkeypatch)+ with caplog.at_level("WARNING", logger = rag_db.__name__):+ for _ in range(5):+ with pytest.raises(rag_db.RagExtensionUnavailable):+ rag_db.get_connection()+ warnings = [+ r for r in caplog.records if "sqlite-vec extension could not be loaded" in r.message+ ]+ assert len(warnings) == 1+ assert "disabled for this session" in warnings[0].getMessage()+++def test_rag_available_is_false_when_the_library_will_not_load(+ rag_home, reset_unavailable_warning, monkeypatch+):+ _break_extension_load(monkeypatch)+ assert rag_db.rag_available() is False+++def test_rag_available_propagates_real_database_errors(+ rag_home, reset_unavailable_warning, monkeypatch+):+ # "Is RAG switched off here" is not the question a locked database answers.+ def _boom():+ raise sqlite3.OperationalError("database is locked")++ monkeypatch.setattr(rag_db, "RAG_AVAILABLE", True)+ monkeypatch.setattr(rag_db, "get_connection", _boom)+ with pytest.raises(sqlite3.OperationalError, match = "database is locked"):+ rag_db.rag_available()+++def test_list_knowledge_bases_degrades_to_empty(rag_home, reset_unavailable_warning, monkeypatch):+ from routes import rag as rag_routes++ _break_extension_load(monkeypatch)+ out = rag_routes.list_knowledge_bases(subject = "tester")+ assert out["knowledgeBases"] == []+ # The marker is what stops the frontend reading this as a working empty state.+ assert out["ragAvailable"] is False+ assert out["ragUnavailableReason"] == UNAVAILABLE+++ "call",+ [+ pytest.param(+ lambda r: r.create_knowledge_base(r.CreateKbRequest(name = "notes"), subject = "tester"),+ id = "create-kb",+ ),+ pytest.param(+ lambda r: r.update_knowledge_base(+ "kb1", r.UpdateKbRequest(name = "renamed"), subject = "tester"+ ),+ id = "update-kb",+ ),+ pytest.param(+ lambda r: r.delete_knowledge_base("kb1", subject = "tester"),+ id = "delete-kb",+ ),+ pytest.param(+ lambda r: r.list_kb_documents("kb1", subject = "tester"),+ id = "list-kb-documents",+ ),+ pytest.param(+ lambda r: r.list_thread_documents("t1", subject = "tester"),+ id = "list-thread-documents",+ ),+ pytest.param(+ lambda r: r.list_project_documents("p1", subject = "tester"),+ id = "list-project-documents",+ ),+ pytest.param(+ lambda r: r.list_all_uploaded_documents(subject = "tester"),+ id = "list-all-documents",+ ),+ pytest.param(+ lambda r: r.delete_document("doc1", subject = "tester"),+ id = "delete-document",+ ),+ pytest.param(+ lambda r: r.search(r.SearchRequest(query = "hello", kb_id = "kb1"), subject = "tester"),+ id = "search",+ ),+ pytest.param(+ lambda r: r.job_status("job1", subject = "tester"),+ id = "job-status",+ ),+ pytest.param(+ lambda r: r.preview_target("doc1", subject = "tester"),+ id = "preview-target",+ ),+ pytest.param(+ lambda r: r.document_file_url("doc1", subject = "tester"),+ id = "file-url",+ ),+ ],+)+def test_every_other_endpoint_answers_503_not_a_traceback(+ rag_home, reset_unavailable_warning, monkeypatch, call+):+ # The regression Codex caught: a user who sees the degraded empty list clicks+ # Create, and the POST must state the reason instead of raising a 500. The document+ # listings are here rather than degrading, so that a frontend which has not learned+ # to read the marker keeps the error surfaces it has today.+ from routes import rag as rag_routes++ _break_extension_load(monkeypatch)+ with pytest.raises(HTTPException) as err:+ call(rag_routes)+ assert err.value.status_code == 503+ assert err.value.detail == UNAVAILABLE+++def test_upload_is_refused_before_the_file_is_written(+ rag_home, reset_unavailable_warning, monkeypatch+):+ # The gate runs before _resolve_document_upload, so an unavailable session does+ # not leave the uploads root filling up with files nothing will ever index. Driven+ # over HTTP: called directly, the unsupplied Form default is a truthy FieldInfo and+ # the request would die on the native-lease branch whatever the gate did.+ from utils.paths import rag_uploads_root++ _break_extension_load(monkeypatch)+ with _client() as client:+ response = client.post(+ "/api/rag/threads/t1/documents",+ files = {"file": ("notes.txt", b"alpha bravo", "text/plain")},+ )+ assert response.status_code == 503+ assert response.json() == {"detail": UNAVAILABLE}+ uploads = rag_uploads_root()+ assert not uploads.exists() or list(uploads.iterdir()) == []+++def test_a_saved_upload_is_removed_when_ingestion_cannot_start(+ rag_home, reset_unavailable_warning, monkeypatch+):+ # The window the gate cannot cover: the extension has loaded before, so the request+ # is admitted and the upload persisted, and start_ingestion's own connection is what+ # discovers the library has gone. 503 like everywhere else, and no orphan left.+ from utils.paths import rag_uploads_root++ _break_extension_load(monkeypatch)+ monkeypatch.setattr(rag_db, "_extension_loaded", True)+ with _client() as client:+ response = client.post(+ "/api/rag/threads/t1/documents",+ files = {"file": ("notes.txt", b"alpha bravo", "text/plain")},+ )+ assert response.status_code == 503+ assert response.json() == {"detail": UNAVAILABLE}+ assert list(rag_uploads_root().iterdir()) == []+++def test_a_first_request_that_discovers_the_missing_library_still_gets_503(+ rag_home, reset_unavailable_warning, monkeypatch+):+ # Same window on the connection path: _require_rag() admits the request from the+ # remembered verdict, so _rag_connection() is what has to report the 503.+ from routes import rag as rag_routes++ _break_extension_load(monkeypatch)+ monkeypatch.setattr(rag_db, "_extension_loaded", True)+ assert rag_db.rag_available() is True+ with pytest.raises(HTTPException) as err:+ rag_routes.create_knowledge_base(rag_routes.CreateKbRequest(name = "notes"), subject = "tester")+ assert err.value.status_code == 503+ assert err.value.detail == UNAVAILABLE+++ not hasattr(sqlite3.Connection, "enable_load_extension"),+ reason = "this interpreter's sqlite3 is built without extension loading, so the "+ "healthy path cannot be exercised (python.org macOS builds, some distros)",+)+def test_a_failed_load_is_not_latched_for_the_session(+ rag_home, reset_unavailable_warning, monkeypatch+):+ # Only the positive verdict is remembered. A one-off load failure must not switch+ # RAG off until restart, and it must not leave the listings and the mutations+ # disagreeing about whether RAG works.+ real = rag_db.sqlite_vec+ calls = {"n": 0}++ class _FailsOnce:+ @staticmethod+ def load(conn):+ calls["n"] += 1+ if calls["n"] == 1:+ raise sqlite3.OperationalError("dlopen(vec0.dylib): no such file")+ real.load(conn)++ monkeypatch.setattr(rag_db, "sqlite_vec", _FailsOnce)+ monkeypatch.setattr(rag_db, "RAG_AVAILABLE", True)+ assert rag_db.rag_available() is False+ assert rag_db.rag_available() is True+++def test_the_whole_router_stays_quiet_under_repeated_use(+ rag_home, reset_unavailable_warning, monkeypatch, caplog+):+ # A 503 path that logged per request would reinstate the spam this all exists to+ # remove, so hammer both halves of the contract and count the warnings.+ from routes import rag as rag_routes++ _break_extension_load(monkeypatch)+ with caplog.at_level("WARNING", logger = rag_db.__name__):+ for _ in range(5):+ rag_routes.list_knowledge_bases(subject = "tester")+ with pytest.raises(HTTPException):+ rag_routes.create_knowledge_base(+ rag_routes.CreateKbRequest(name = "notes"), subject = "tester"+ )+ records = [r for r in caplog.records if r.name == rag_db.__name__]+ assert len(records) == 1+ assert "sqlite-vec extension could not be loaded" in records[0].message+ assert not any(r.exc_info for r in records)+++def test_startup_reconcile_is_a_no_op_when_rag_cannot_run(+ rag_home, reset_unavailable_warning, monkeypatch+):+ # It already claims to be a no-op without RAG; raising out of startup so main.py+ # logs "reconcile failed" reads like a fault when there is nothing to reconcile.+ _break_extension_load(monkeypatch)+ assert rag_db.reconcile_orphaned_ingestion_jobs() == 0+++def test_over_http_the_poll_is_200_and_create_is_503(+ rag_home, reset_unavailable_warning, monkeypatch+):+ # What the browser actually sees: the polled list stays a success carrying the+ # marker, and the Create it offers comes back 503 with the reason in `detail`+ # (the shape the frontend's parseErrorText already surfaces).+ _break_extension_load(monkeypatch)+ with _client() as client:+ listed = client.get("/api/rag/knowledge-bases")+ assert listed.status_code == 200+ assert listed.json() == {+ "knowledgeBases": [],+ "ragAvailable": False,+ "ragUnavailableReason": UNAVAILABLE,+ }++ created = client.post("/api/rag/knowledge-bases", json = {"name": "notes"})+ assert created.status_code == 503+ assert created.json() == {"detail": UNAVAILABLE}+++def test_list_knowledge_bases_still_raises_real_database_errors(+ rag_home, reset_unavailable_warning, monkeypatch+):+ # Only "the extension is not there" degrades. A locked or corrupt database is a+ # real failure and must keep surfacing.+ from routes import rag as rag_routes++ def _boom():+ raise sqlite3.OperationalError("database is locked")++ monkeypatch.setattr(rag_db, "RAG_AVAILABLE", True)+ monkeypatch.setattr(rag_db, "get_connection", _boom)+ with pytest.raises(sqlite3.OperationalError, match = "database is locked"):+ rag_routes.list_knowledge_bases(subject = "tester")+++def test_mutating_endpoints_still_raise_real_database_errors(+ rag_home, reset_unavailable_warning, monkeypatch+):+ # Same rule on the 503 side: a locked database must not be dressed up as+ # "RAG is switched off on this machine".+ from routes import rag as rag_routes++ def _boom():+ raise sqlite3.OperationalError("database is locked")++ monkeypatch.setattr(rag_db, "RAG_AVAILABLE", True)+ monkeypatch.setattr(rag_db, "_extension_loaded", True)+ monkeypatch.setattr(rag_db, "get_connection", _boom)+ with pytest.raises(sqlite3.OperationalError, match = "database is locked"):+ rag_routes.create_knowledge_base(rag_routes.CreateKbRequest(name = "notes"), subject = "tester")+++ not hasattr(sqlite3.Connection, "enable_load_extension"),+ reason = "this interpreter's sqlite3 is built without extension loading, so the "+ "healthy path cannot be exercised (python.org macOS builds, some distros)",+)+def test_list_knowledge_bases_works_when_the_extension_loads(rag_home, rag_conn):+ # The healthy path is unchanged: a real connection still lists what is stored,+ # and says so, which is what makes an empty list readable as genuinely empty.+ from core.rag import store+ from routes import rag as rag_routes++ store.create_kb(rag_conn, name = "notes", description = None, embedding_model = None)+ rag_conn.commit()+ out = rag_routes.list_knowledge_bases(subject = "tester")+ assert [kb["name"] for kb in out["knowledgeBases"]] == ["notes"]+ assert out["ragAvailable"] is True+ assert out["ragUnavailableReason"] is None+++ not hasattr(sqlite3.Connection, "enable_load_extension"),+ reason = "this interpreter's sqlite3 is built without extension loading, so the "+ "healthy path cannot be exercised (python.org macOS builds, some distros)",+)+def test_mutations_still_work_when_the_extension_loads(rag_home, rag_conn):+ # The 503 gate must not stand in the way of a machine where RAG does run.+ from routes import rag as rag_routes++ created = rag_routes.create_knowledge_base(+ rag_routes.CreateKbRequest(name = "notes"), subject = "tester"+ )+ assert created["name"] == "notes"+ assert rag_routes.update_knowledge_base(+ created["id"], rag_routes.UpdateKbRequest(name = "renamed"), subject = "tester"+ ) == {"ok": True}+ assert rag_routes.delete_knowledge_base(created["id"], subject = "tester") == {"ok": True}diff --git a/studio/backend/tests/test_uvicorn_exception_dedup.py b/studio/backend/tests/test_uvicorn_exception_dedup.pynew file mode 100644index 00000000000..9fdc14bf0d5--- /dev/null+++ b/studio/backend/tests/test_uvicorn_exception_dedup.py@@ -0,0 +1,158 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""An unhandled request exception must be logged once, not twice.++LoggingMiddleware emits request_failed with the full traceback in its structured+"exception" field, then re-raises; uvicorn logs the very same exception again on+stderr as "Exception in ASGI application", and the desktop shell copies every+stderr line into tauri.log separately (~90 lines per failure). The filter drops+uvicorn's copy only for exceptions the middleware already reported, so a failure+raised above the middleware, or a run with --verbose, keeps both.+"""++import asyncio+import logging++import pytest++from loggers import handlers as hmod+from loggers.handlers import (+ LoggingMiddleware,+ _DropDuplicateAsgiException,+ install_uvicorn_duplicate_exception_filter,+)++_UVICORN_MSG = "Exception in ASGI application\n"+++class _LogCapture:+ def __init__(self):+ self.events = []++ def info(self, event, **kw):+ self.events.append(("info", event, kw))++ def error(self, event, **kw):+ self.events.append(("error", event, kw))+++def logs(monkeypatch):+ capture = _LogCapture()+ monkeypatch.setattr(hmod, "logger", capture)+ return capture+++def _http_scope(path, method = "GET"):+ return {"type": "http", "path": path, "method": method}+++async def _noop_receive():+ return {"type": "http.disconnect"}+++async def _drop(message):+ pass+++def _uvicorn_record(exc, msg = _UVICORN_MSG):+ """The record uvicorn builds: logger.error(msg, exc_info=exc) on uvicorn.error."""+ return logging.LogRecord(+ name = "uvicorn.error",+ level = logging.ERROR,+ pathname = __file__,+ lineno = 1,+ msg = msg,+ args = (),+ exc_info = (type(exc), exc, exc.__traceback__),+ )+++def _raise_through_middleware(exc, path = "/api/rag/knowledge-bases"):+ """Run a failing app under the middleware and hand back the exception uvicorn+ would see (the same object, re-raised)."""++ async def app(scope, receive, send):+ raise exc++ with pytest.raises(type(exc)) as caught:+ asyncio.run(LoggingMiddleware(app)(_http_scope(path), _noop_receive, _drop))+ return caught.value+++def test_middleware_marks_the_exception_it_logged(logs):+ raised = _raise_through_middleware(RuntimeError("RAG unavailable"))+ assert logs.events[0][1] == "request_failed"+ assert getattr(raised, hmod._LOGGED_EXC_ATTR, False) is True+++def test_uvicorn_duplicate_traceback_is_dropped(logs):+ raised = _raise_through_middleware(RuntimeError("RAG unavailable"))+ assert _DropDuplicateAsgiException().filter(_uvicorn_record(raised)) is False+++def test_exception_never_seen_by_the_middleware_still_logs():+ # Raised above LoggingMiddleware (CORS, remote-access, the protocol layer): it+ # carries no marker, so uvicorn's traceback is the only record of it and must stay.+ try:+ raise RuntimeError("cors blew up")+ except RuntimeError as exc:+ record = _uvicorn_record(exc)+ assert _DropDuplicateAsgiException().filter(record) is True+++def test_other_uvicorn_error_records_pass_through(logs):+ # Only the ASGI-application traceback is a duplicate; every other uvicorn error+ # line is uvicorn's alone.+ raised = _raise_through_middleware(RuntimeError("boom"))+ record = _uvicorn_record(raised, msg = "ASGI callable returned without starting response.")+ assert _DropDuplicateAsgiException().filter(record) is True+++def test_record_without_exc_info_passes_through():+ record = logging.LogRecord(+ name = "uvicorn.error",+ level = logging.ERROR,+ pathname = __file__,+ lineno = 1,+ msg = _UVICORN_MSG,+ args = (),+ exc_info = None,+ )+ assert _DropDuplicateAsgiException().filter(record) is True+++def test_verbose_keeps_both_copies(logs, monkeypatch):+ raised = _raise_through_middleware(RuntimeError("RAG unavailable"))+ monkeypatch.setattr(hmod, "_VERBOSE_ACCESS_LOG", True)+ assert _DropDuplicateAsgiException().filter(_uvicorn_record(raised)) is True+++def test_installed_filter_suppresses_the_record_on_uvicorn_error(logs):+ # End to end through the logging module: the filter is attached to the+ # uvicorn.error logger, so the handler never sees the duplicate.+ uvicorn_logger = logging.getLogger("uvicorn.error")+ before = list(uvicorn_logger.filters)+ seen = []++ class _Collect(logging.Handler):+ def emit(self, record):+ seen.append(record.getMessage())++ handler = _Collect()+ uvicorn_logger.addHandler(handler)+ install_uvicorn_duplicate_exception_filter()+ try:+ raised = _raise_through_middleware(RuntimeError("RAG unavailable"))+ uvicorn_logger.error(_UVICORN_MSG, exc_info = raised)+ assert seen == []++ try:+ raise RuntimeError("not ours")+ except RuntimeError as exc:+ uvicorn_logger.error(_UVICORN_MSG, exc_info = exc)+ assert [m.strip() for m in seen] == ["Exception in ASGI application"]+ finally:+ uvicorn_logger.removeHandler(handler)+ uvicorn_logger.filters = beforediff --git a/studio/backend/tests/test_video_capability.py b/studio/backend/tests/test_video_capability.pynew file mode 100644index 00000000000..188a447ad9b--- /dev/null+++ b/studio/backend/tests/test_video_capability.py@@ -0,0 +1,196 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Tests for video generation capability gating.++Video runs through the diffusers pipelines in core/inference/video.py, which have no Apple path,+so it is supported iff ``get_device() in {CUDA, XPU}`` with a reason otherwise (macos_unsupported+/ pytorch_not_installed / no_accelerator / detection_failed). Mirrors test_export_capability.py:+the matrix mocks the hardware probes, wiring is checked with ast, so it runs on CPU.+"""++import ast+from pathlib import Path++import utils.hardware.hardware as hw++_BACKEND = Path(__file__).resolve().parent.parent+++def _src(rel):+ return (_BACKEND / rel).read_text(encoding = "utf-8")+++def _func_src(rel, name):+ src = _src(rel)+ node = next(+ n for n in ast.walk(ast.parse(src)) if isinstance(n, ast.FunctionDef) and n.name == name+ )+ return ast.get_source_segment(src, node)+++def _patch(+ monkeypatch,+ *,+ torch: bool,+ device,+ apple: bool,+ chat_only_reason = "no_gpu",+ system = None,+):+ monkeypatch.setattr(hw, "_has_torch", lambda: torch)+ monkeypatch.setattr(hw, "get_device", lambda: device)+ monkeypatch.setattr(hw, "is_apple_silicon", lambda: apple)+ monkeypatch.setattr(hw, "CHAT_ONLY_REASON", chat_only_reason)+ # Pin the OS too. video_capability() asks platform.system() directly so an Intel Mac+ # is covered, which means the non-Mac cases below would flip to macos_unsupported+ # when this suite runs on a macOS runner. Default follows `apple` so existing callers+ # keep the host they were written for.+ monkeypatch.setattr(hw.platform, "system", lambda: system or ("Darwin" if apple else "Linux"))+++# -- capability matrix --------------------------------------------------------------------------+++def test_cuda_supports_video(monkeypatch):+ _patch(monkeypatch, torch = True, device = hw.DeviceType.CUDA, apple = False)+ cap = hw.video_capability()+ assert cap["video_supported"] is True+ assert cap["video_unsupported_reason"] is None+ assert cap["video_unsupported_message"] is None+++def test_xpu_supports_video(monkeypatch):+ _patch(monkeypatch, torch = True, device = hw.DeviceType.XPU, apple = False)+ assert hw.video_capability()["video_supported"] is True+++def test_apple_silicon_reports_coming_soon(monkeypatch):+ """A healthy Apple Silicon host is not chat-only, so the tab is enabled and would just fail+ at load. Say what is actually true instead: there is no Apple video path yet."""+ for device in (hw.DeviceType.MLX, hw.DeviceType.CPU):+ _patch(monkeypatch, torch = True, device = device, apple = True)+ cap = hw.video_capability()+ assert cap["video_supported"] is False+ assert cap["video_unsupported_reason"] == "macos_unsupported"+ assert "coming soon" in cap["video_unsupported_message"].lower()+++def test_mlx_device_is_unsupported_even_without_the_apple_probe(monkeypatch):+ # MLX only exists on Apple, so an is_apple_silicon() that fails to answer must not+ # reclassify the host as a CPU box missing a GPU.+ _patch(monkeypatch, torch = False, device = hw.DeviceType.MLX, apple = False)+ cap = hw.video_capability()+ assert cap["video_supported"] is False+ assert cap["video_unsupported_reason"] == "macos_unsupported"+++def test_no_torch_non_apple_reports_pytorch_missing(monkeypatch):+ _patch(monkeypatch, torch = False, device = hw.DeviceType.CPU, apple = False)+ cap = hw.video_capability()+ assert cap["video_supported"] is False+ assert cap["video_unsupported_reason"] == "pytorch_not_installed"+ assert "PyTorch is not installed" in cap["video_unsupported_message"]+++def test_cpu_with_torch_reports_no_accelerator(monkeypatch):+ _patch(monkeypatch, torch = True, device = hw.DeviceType.CPU, apple = False)+ cap = hw.video_capability()+ assert cap["video_supported"] is False+ assert cap["video_unsupported_reason"] == "no_accelerator"+ # Must not tell a user who has PyTorch to install PyTorch.+ assert "PyTorch is not installed" not in cap["video_unsupported_message"]+++def test_a_failed_detection_is_reported_as_such(monkeypatch):+ """Same rule as export: a broken probe leaves the host looking CPU-only, so reporting+ no_accelerator would point the remediation at hardware that may be fine."""+ _patch(+ monkeypatch,+ torch = True,+ device = hw.DeviceType.CPU,+ apple = False,+ chat_only_reason = "detection_failed",+ )+ cap = hw.video_capability()+ assert cap["video_supported"] is False+ assert cap["video_unsupported_reason"] == "detection_failed"+ assert "detection failed" in cap["video_unsupported_message"].lower()+++# -- endpoint / package wiring (ast) ------------------------------------------------------------+++def test_main_endpoints_expose_video_capability():+ m = _src("main.py")+ # Both system endpoints spread video_capability() into their response, as they do for export.+ assert m.count("**video_capability()") >= 2+ assert '"/api/system/hardware"' in m and '"/api/system"' in m+++def test_hardware_package_reexports_video_capability():+ init = _src("utils/hardware/__init__.py")+ assert "def video_capability()" in init+ assert '"video_capability"' in init+++def test_video_capability_excludes_the_apple_backends():+ cap = _func_src("utils/hardware/hardware.py", "video_capability")+ # Supported set is CUDA + XPU only; MLX is named solely on the unsupported side.+ assert "DeviceType.CUDA, DeviceType.XPU" in cap+ assert "_has_torch()" in cap+ # Strip comments and docstrings before asserting on the gate. This assertion used to+ # name is_apple_silicon(), and when the check widened to every Darwin host it kept+ # passing on the word surviving in a comment, which is not a test of anything.+ code = "\n".join(+ line.split("#", 1)[0] for line in cap.splitlines() if not line.strip().startswith("#")+ )+ assert 'platform.system() == "Darwin"' in code, (+ "the macOS branch must key on Darwin, not Apple Silicon, or an Intel Mac is told "+ "to install PyTorch or buy a GPU for something macOS cannot do at all"+ )+ assert "DeviceType.MLX" in code+++def test_frontend_reads_the_new_fields():+ hook = (_BACKEND.parent / "frontend" / "src" / "hooks" / "use-hardware-info.ts").read_text(+ encoding = "utf-8"+ )+ for field in ("video_supported", "video_unsupported_reason", "video_unsupported_message"):+ assert field in hook, f"{field} is not consumed by use-hardware-info.ts"+++def test_intel_mac_is_macos_unsupported_not_a_missing_gpu(monkeypatch):+ # An Intel Mac detects as plain CPU and is_apple_silicon() is False, so the reason+ # used to come out as pytorch_not_installed or no_accelerator. Both tell the user to+ # install PyTorch or add a GPU, and neither enables video: the pipelines have no+ # supported macOS path at all. Same answer on both Macs.+ for torch_present in (True, False):+ _patch(+ monkeypatch,+ torch = torch_present,+ device = hw.DeviceType.CPU,+ apple = False,+ system = "Darwin",+ )+ cap = hw.video_capability()+ assert cap["video_supported"] is False+ assert cap["video_unsupported_reason"] == "macos_unsupported", (+ f"Intel Mac with torch={torch_present} reported " f"{cap['video_unsupported_reason']!r}"+ )+ assert "coming soon" in cap["video_unsupported_message"].lower()+ assert "GPU" not in cap["video_unsupported_message"]+++def test_a_broken_probe_still_beats_the_macos_branch(monkeypatch):+ # detection_failed is checked first on purpose: a Mac whose probe fell over should be+ # told detection failed, not that video is coming soon, because the verdict is unknown.+ _patch(+ monkeypatch,+ torch = True,+ device = hw.DeviceType.CPU,+ apple = True,+ chat_only_reason = "detection_failed",+ system = "Darwin",+ )+ assert hw.video_capability()["video_unsupported_reason"] == "detection_failed"diff --git a/studio/backend/tests/test_warm_window_review_fixes.py b/studio/backend/tests/test_warm_window_review_fixes.pyindex 8d83b0678d9..ef6cd379f52 100644--- a/studio/backend/tests/test_warm_window_review_fixes.py+++ b/studio/backend/tests/test_warm_window_review_fixes.py@@ -164,13 +164,17 @@ def test_building_the_orchestrator_makes_no_outbound_request():init = next(node for node in cls.body if isinstance(node, ast.FunctionDef) and node.name == "__init__")+ # Both names. The fetch is now started through the public wrapper, so scanning only+ # for the private one let `self._start_top_models_fetch()` back into __init__ -- which+ # restores the huggingface.co call on every boot, exactly what this guards against.+ _BOOT_FETCH_NAMES = ("_fetch_top_models", "_start_top_models_fetch")offenders = [- sub+ sub.attrfor sub in ast.walk(init)- if isinstance(sub, ast.Attribute) and sub.attr == "_fetch_top_models"+ if isinstance(sub, ast.Attribute) and sub.attr in _BOOT_FETCH_NAMES]assert not offenders, (- "the orchestrator constructor references _fetch_top_models again; building "+ f"the orchestrator constructor references {offenders} again; building ""it on the warm thread then reaches huggingface.co on every boot, before ""anyone signs in")@@ -680,6 +684,24 @@ def test_detection_wait_requires_a_device_not_just_the_event():and sub.left.attr == "DEVICE"and any(isinstance(op, (ast.IsNot, ast.Is)) for op in sub.ops)]++ # Bind to the SITES, not to a count. The function has three DEVICE comparisons (the+ # kill-switch return, the fast path, the poll loop), so `>= 2` stayed green after+ # deleting the poll loop's -- the very guard whose absence serves a torn verdict.+ def _requires_device(node) -> bool:+ return any(+ isinstance(sub, ast.Attribute) and sub.attr == "DEVICE" for sub in ast.walk(node)+ )++ whiles = [sub for sub in ast.walk(fn) if isinstance(sub, ast.While)]+ assert whiles and all(_requires_device(w.test) for w in whiles), (+ "the detection poll loop no longer requires DEVICE, so a torn "+ "event-set/DEVICE-None state ends the wait and nothing re-detects"+ )+ assert any(_requires_device(sub.test) for sub in ast.walk(fn) if isinstance(sub, ast.If)), (+ "the fast path no longer requires DEVICE, so a torn event-set/DEVICE-None "+ "state is reported as detected"+ )assert len(device_tests) >= 2, (f"found {len(device_tests)} DEVICE comparison(s); both the fast path and "f"the poll loop must require a device, or a torn event-set/DEVICE-None "diff --git a/studio/backend/utils/hardware/__init__.py b/studio/backend/utils/hardware/__init__.pyindex 4195d0c680d..4d06fb20737 100644--- a/studio/backend/utils/hardware/__init__.py+++ b/studio/backend/utils/hardware/__init__.py@@ -68,6 +68,11 @@ def export_capability() -> dict:return _hardware.export_capability()+def video_capability() -> dict:+ """Return live video-generation capability from the hardware module."""+ return _hardware.video_capability()++def get_torch_device_str() -> str:"""Return the torch device string ("cuda", "xpu", "cpu") for the detected hardware."""return _hardware.get_torch_device_str()@@ -83,6 +88,7 @@ __all__ = ["start_background_detection","get_device","export_capability",+ "video_capability","is_apple_silicon","clear_gpu_cache","get_gpu_memory_info",diff --git a/studio/backend/utils/hardware/hardware.py b/studio/backend/utils/hardware/hardware.pyindex add9708ae54..82ccc27369b 100644--- a/studio/backend/utils/hardware/hardware.py+++ b/studio/backend/utils/hardware/hardware.py@@ -601,6 +601,58 @@ def export_capability() -> dict:}+def video_capability() -> dict:+ """Whether video generation can run here, with a torch-aware reason when it cannot.++ Video runs through the diffusers pipelines in core/inference/video.py, which have no Apple+ path: no MLX backend, and the families ship no MPS-tested route, so macOS is reported as+ unsupported rather than left to fail at load. Supported iff ``get_device() in {CUDA, XPU}``.+ Safe to call without torch.++ Returns {video_supported, video_unsupported_reason, video_unsupported_message}.+ """+ if get_device() in (DeviceType.CUDA, DeviceType.XPU):+ return {+ "video_supported": True,+ "video_unsupported_reason": None,+ "video_unsupported_message": None,+ }+ # Detection failure first, as in export_capability: the branches below all describe a+ # measured host, so a broken probe would tell a GPU box to go buy a GPU.+ if CHAT_ONLY_REASON == "detection_failed":+ reason = "detection_failed"+ message = (+ "Hardware detection failed on this host, so video generation is disabled. The server "+ "log records the underlying error; restart Unsloth Studio to retry detection."+ )+ elif platform.system() == "Darwin" or get_device() == DeviceType.MLX:+ # Every Mac, not just Apple Silicon. An Intel Mac detects as plain CPU, so an+ # is_apple_silicon() test drops it into the branches below and tells the user to+ # install PyTorch or add a GPU. Neither enables video here: the pipelines have no+ # supported macOS path at all, so the honest answer is the same on both Macs.+ # The MLX arm covers an Apple host whose platform probe somehow disagrees.+ reason = "macos_unsupported"+ message = "Video generation on macOS is coming soon."+ elif not _has_torch():+ reason = "pytorch_not_installed"+ message = (+ "PyTorch is not installed. Video generation requires PyTorch with an NVIDIA, AMD or "+ "Intel GPU. Install PyTorch to enable video generation."+ )+ else:+ reason = "no_accelerator"+ message = (+ "Video generation requires an NVIDIA, AMD or Intel GPU. No supported accelerator was "+ "found on this host. (PyTorch is installed, but the video pipelines cannot run on CPU "+ "only.)"+ )+ return {+ "video_supported": False,+ "video_unsupported_reason": reason,+ "video_unsupported_message": message,+ }++def clear_gpu_cache():"""Clear GPU memory cache for the current device.diff --git a/studio/backend/utils/mlx_repair.py b/studio/backend/utils/mlx_repair.pyindex 0d2b3a2e921..f3879acf5e2 100644--- a/studio/backend/utils/mlx_repair.py+++ b/studio/backend/utils/mlx_repair.py@@ -42,6 +42,10 @@ from utils.uv_path_safety import uv_safe_pathlogger = structlog.get_logger(__name__)DISABLE_ENV_VAR = "UNSLOTH_DISABLE_MLX_AUTOREPAIR"+# uv's wording when --python names a path it will not install into. Matched on the+# stable leading clause only: uv appends the offending path and a "run `uv venv`"+# hint, and has reworded the tail across releases.+_UNRESOLVED_PYTHON_MARKER = "No virtual environment or system Python installation found"# Minimum versions unsloth-zoo requires on Apple Silicon (its pyproject darwin# deps). mlx-vlm especially must be >=0.4.4: an older one still imports but# breaks VLM Train/Export, so installing it would wrongly clear chat-only.@@ -179,6 +183,21 @@ def _uv_executable() -> str | None:return None+def _venv_root() -> str | None:+ """The venv directory this interpreter runs from, or None outside a venv.++ `sys.prefix` differs from `sys.base_prefix` exactly when a venv is active.+ Confirm the marker file so a half-deleted tree is never named as the target."""+ if sys.prefix == sys.base_prefix:+ return None+ try:+ if (Path(sys.prefix) / "pyvenv.cfg").is_file():+ return sys.prefix+ except OSError:+ pass+ return None++def _uv_install_cmd(*args: str) -> list[str] | None:uv = _uv_executable()if not uv:@@ -201,8 +220,24 @@ def _mlx_install_env() -> dict[str, str]:by silently backtracking mlx-vlm to an old, unsupported version (uv honoursUV_OVERRIDE; plain pip ignores it, so the transformers constraint below is thepip-path safety net). We set UV_OVERRIDE ourselves, so a poisoned one in the- process env is ignored."""+ process env is ignored.++ VIRTUAL_ENV is set from sys.prefix rather than forwarded from os.environ, for+ the same reason: it names the environment uv must install into, and taking it+ from the process env would let a caller redirect the install elsewhere.++ It does NOT rescue a venv whose bin/python has stopped resolving. An explicit+ --python outranks VIRTUAL_ENV, so uv reports the same unresolved-interpreter+ error either way; this once claimed otherwise, and named an interpreter-probe+ helper that was deleted with it. Nothing passable to `uv pip install` recovers+ that state -- --target and --prefix do exit 0, but resolve against whatever+ ambient interpreter uv finds and write a wrong-ABI or off-sys.path install,+ which is worse than staying chat-only because it defeats the+ mlx_stack_available() gate. That case is detected and reported instead: see+ the _UNRESOLVED_PYTHON_MARKER branch in attempt_mlx_repair."""env = {key: os.environ[key] for key in _MLX_ENV_ALLOWLIST if key in os.environ}+ if (venv_root := _venv_root()) is not None:+ env["VIRTUAL_ENV"] = venv_rootoverride = (Path(__file__).resolve().parents[1]/ "requirements"@@ -292,6 +327,24 @@ def attempt_mlx_repair(*, timeout: int = _REPAIR_TIMEOUT_S) -> bool:passif result.returncode != 0:tail = (result.stdout or "")[-2000:]+ if _UNRESOLVED_PYTHON_MARKER in (result.stdout or ""):+ # uv will not install into this environment at all, so the venv is broken+ # rather than merely missing MLX, and no install flag recovers it from in+ # here: `--python <venv>/bin/python`, `--python <venv>` and a bare+ # VIRTUAL_ENV all report the same error against an interpreter uv cannot+ # resolve. Only rebuilding the environment fixes it, so name the command+ # that does. uv's own text says to run `uv venv`, which would build an+ # environment Unsloth does not manage.+ logger.warning(+ "MLX self-heal could not use the Unsloth environment at %s: uv did not "+ "recognise it as a virtual environment. This usually means the venv's "+ "bin/python points at an interpreter that has since been upgraded or "+ "removed. Train/Export stay disabled until the environment is rebuilt: "+ "run `unsloth studio update`. uv said:\n%s",+ _venv_root() or sys.prefix,+ tail,+ )+ return Falselogger.warning("MLX self-heal failed (staying chat-only):\n%s", tail)return Falseimportlib.invalidate_caches()diff --git a/studio/frontend/src/app/routes/__root.tsx b/studio/frontend/src/app/routes/__root.tsxindex 6c8867bc115..d4c9f2cadbc 100644--- a/studio/frontend/src/app/routes/__root.tsx+++ b/studio/frontend/src/app/routes/__root.tsx@@ -93,12 +93,30 @@ const CHAT_ONLY_ALLOWED = new Set(["/api-monitor",]);+// Paths that render their own "still checking" state and self-gate once the verdict lands.+// The redirect below is one-way, so acting on the pre-measurement guess strands a healthy host+// on /chat; these two wait it out instead. Everything else keeps the old behaviour.+// /video is allowed outright below, so in practice this is what keeps /studio off the guess;+// it stays listed because that is the property the page's own loading panel relies on.+const SELF_GATED_WHILE_UNKNOWN = ["/studio", "/video"];++function waitsOutUnknownVerdict(pathname: string): boolean {+ return SELF_GATED_WHILE_UNKNOWN.some(+ (base) => pathname === base || pathname.startsWith(`${base}/`),+ );+}+function isChatOnlyAllowed(pathname: string): boolean {if (CHAT_ONLY_ALLOWED.has(pathname)) return true;if (pathname === "/data-recipes" || pathname.startsWith("/data-recipes/"))return true;// Images runs on CPU/MPS via the native sd.cpp engine, the very no-GPU setup it was added for. The chat-only flag is about training/export, so it must not redirect /images.if (pathname === "/images" || pathname.startsWith("/images/")) return true;+ // Video follows /export: the page explains an unsupported host itself, using the backend's+ // own video verdict (no GPU, no PyTorch, no Apple path). A measured chat-only host is exactly+ // where that explanation belongs, so a direct link or a reload has to reach VideoPage's gate+ // instead of bouncing to /chat. It self-gates on videoSupported, so nothing loads.+ if (pathname === "/video" || pathname.startsWith("/video/")) return true;return false;}@@ -107,8 +125,13 @@ export const Route = createRootRoute({// Fetch platform info before the chat-only guard. fetchDeviceType caches,// so later navigations are instant.await fetchDeviceType();- const chatOnly = usePlatformStore.getState().isChatOnly();- if (chatOnly && !isChatOnlyAllowed(location.pathname)) {+ const { isChatOnly, capabilitiesUnknown } = usePlatformStore.getState();+ const unmeasured = capabilitiesUnknown();+ if (+ isChatOnly() &&+ !isChatOnlyAllowed(location.pathname) &&+ !(unmeasured && waitsOutUnknownVerdict(location.pathname))+ ) {throw redirect({ to: "/chat" });}},diff --git a/studio/frontend/src/components/app-sidebar.tsx b/studio/frontend/src/components/app-sidebar.tsxindex f8db62a983e..c16a8cc40fe 100644--- a/studio/frontend/src/components/app-sidebar.tsx+++ b/studio/frontend/src/components/app-sidebar.tsx@@ -142,6 +142,7 @@ import {} from "@/features/settings";import type { SidebarNavItemId } from "@/features/settings";import { useEffectiveProfile, UserAvatar } from "@/features/profile";+import { resolveNavRowState } from "@/components/nav-row-state";import { fetchDeviceType, usePlatformStore } from "@/config/env";import { clearAuthTokens, logout } from "@/features/auth";import { TOUR_OPEN_EVENT } from "@/features/tour";@@ -223,6 +224,9 @@ type NavRowDef = {disabled?: boolean;tooltip?: string;spinner?: boolean;+ // The capability that decides `disabled` has not been measured yet. A row in this state is+ // neither enabled-looking nor blacked out: resolveNavRowState renders it with the spinner.+ pending?: boolean;badge?: string;onClick: () => void;onIntent?: () => void;@@ -330,6 +334,7 @@ function NavItem({onIntent,badge,overlay,+ testId,}: {icon: typeof ZapIcon;label: string;@@ -341,6 +346,9 @@ function NavItem({className?: string;spinner?: boolean;onIntent?: () => void;+ // Stable hook for the UI smokes, which assert a row spins rather than greys out+ // while its capability verdict is still unmeasured.+ testId?: string;// Overrides the hover tooltip; explains why a disabled item is greyed out.tooltip?: string;// Trailing "New" pill text.@@ -359,6 +367,8 @@ function NavItem({onFocus={disabled ? undefined : onIntent}isActive={active}data-tour={dataTour}+ data-testid={testId}+ data-spinner={spinner ? "true" : undefined}className="sidebar-nav-btn h-[33px] rounded-full gap-[8.5px] pl-3 pr-2.5 font-medium group-data-[collapsible=icon]:px-2.5 group-data-[collapsible=icon]:!w-[32px] group-data-[collapsible=icon]:mx-auto"><HugeiconsIcon icon={icon} strokeWidth={1.75} className="size-icon! shrink-0 translate-x-0.5 group-hover/menu-button:animate-icon-pop" />@@ -391,6 +401,15 @@ function getSidebarItemThreadIds(item: SidebarItem) {const WORKFLOW_UNAVAILABLE = "The loaded model cannot do this";+// Re-read cadences for the hardware verdict below. An unmeasured verdict holds Train and Video+// on a spinner, so it is re-read sooner than the background MLX self-heal check, which only+// pays off after the user has repaired an install. A re-read outstanding longer than the stall+// window is given up on rather than latching the poll off: the backend it is waiting on is the+// one case this has to recover from.+const VERDICT_UNKNOWN_POLL_MS = 3000;+const SELF_HEAL_POLL_MS = 15000;+const VERDICT_POLL_STALL_MS = 30000;+/** One workflow in the list under the Images row. */function WorkflowChoice({tab,@@ -576,9 +595,15 @@ export function AppSidebar() {const chatOnly = usePlatformStore((s) => s.isChatOnly());const chatOnlyReason = usePlatformStore((s) => s.chatOnlyReason);const detectionDeferred = usePlatformStore((s) => s.detectionDeferred);+ const platformDeviceType = usePlatformStore((s) => s.deviceType);+ // Until /api/health answers, `chatOnly` is the browser-platform guess, so every Mac painted+ // Train and Video blacked out on load and only recovered once the backend reported. Gate the+ // rows on a measured verdict and let them spin until it lands.+ const capabilitiesUnknown = usePlatformStore((s) => s.capabilitiesUnknown());+ const chatOnlyMeasured = chatOnly && !capabilitiesUnknown;// Explain a greyed-out Train (chat-only host) on hover. Export stays navigable so its page// can show a precise reason.- const trainDisabledHint: string | undefined = !chatOnly+ const trainDisabledHint: string | undefined = !chatOnlyMeasured? undefined: chatOnlyReason === "mlx_unavailable"? "Training needs MLX. Run `unsloth studio update` to enable Train."@@ -587,18 +612,53 @@ export function AppSidebar() {: chatOnlyReason === "no_gpu"? "Training needs an NVIDIA or AMD GPU.": undefined;+ // Video's hint is derived the same way. It used to be hardcoded to "needs an NVIDIA or AMD+ // GPU", which is wrong on an Apple Silicon host: video has no Apple path at all, so the row+ // says so rather than pointing at hardware the user cannot add.+ const videoDisabledHint: string | undefined = !chatOnlyMeasured+ ? undefined+ : platformDeviceType === "mac"+ ? "Video generation on macOS is coming soon."+ : chatOnlyReason === "no_gpu"+ ? "Video generation needs an NVIDIA or AMD GPU."+ : undefined;- // The backend MLX self-heal (utils/mlx_repair) can reinstall MLX and flip chat_only false- // without a restart. The platform store cached the initial /api/health, so re-poll while- // chat-only for the recoverable mlx_unavailable case; the guard below stops it after.+ // Two things can change the verdict after the first /api/health. The backend MLX self-heal+ // (utils/mlx_repair) can reinstall MLX and flip chat_only false without a restart, and+ // detection can land after fetchDeviceType gave up waiting for it. The platform store cached+ // that first reply, so re-poll for both; the guard below stops it once neither applies.useEffect(() => {// Also while deferred: under the kill switch health settles nothing, so a GPU host would stay chat-only.- if (!chatOnly || (chatOnlyReason !== "mlx_unavailable" && !detectionDeferred)) return;+ const selfHealSettled =+ !chatOnly || (chatOnlyReason !== "mlx_unavailable" && !detectionDeferred);+ // And on any platform while the verdict itself is out. fetchDeviceType spends its bounded+ // wait at most once per page load, so a host that detects slower than that keeps the+ // provisional reply, and nothing else is scheduled to re-read it: the rows above would spin+ // and /studio would hold its loading panel for the rest of the session. This is the only+ // recovery poll in the app, and the sidebar is mounted on every route that gates on the+ // verdict (studio-page and video-page read the same store, so they recover with it).+ if (selfHealSettled && !capabilitiesUnknown) return;+ let pollingSince = 0;+ // Which read currently owns the guard. A read that outlived the stall window is replaced,+ // and the replacement takes the guard with it; without an owner the abandoned read's+ // `finally` would clear a guard it no longer holds and let the next tick stack another+ // forced read onto the slow backend, every interval, which is the pile-up this prevents.+ let pollOwner = 0;const id = window.setInterval(() => {- void fetchDeviceType({ force: true }).catch(() => undefined);- }, 15000);+ // A backend still importing torch answers slowly, so skip while a re-read is outstanding+ // rather than stacking them against it. Bounded, or a request that never settles would+ // hold the poll off for good.+ if (pollingSince && Date.now() - pollingSince < VERDICT_POLL_STALL_MS) return;+ const owned = ++pollOwner;+ pollingSince = Date.now();+ void fetchDeviceType({ force: true })+ .catch(() => undefined)+ .finally(() => {+ if (owned === pollOwner) pollingSince = 0;+ });+ }, capabilitiesUnknown ? VERDICT_UNKNOWN_POLL_MS : SELF_HEAL_POLL_MS);return () => window.clearInterval(id);- }, [chatOnly, chatOnlyReason, detectionDeferred]);+ }, [capabilitiesUnknown, chatOnly, chatOnlyReason, detectionDeferred]);const [shutdownOpen, setShutdownOpen] = useState(false);@@ -974,11 +1034,12 @@ export function AppSidebar() {icon: TestTubeOutlineIcon,label: t("shell.navigation.train"),active: pathname === "/studio" || pathname.startsWith("/studio/"),- disabled: chatOnly,+ disabled: chatOnlyMeasured,tooltip: trainDisabledHint,spinner: trainingInProgress,+ pending: capabilitiesUnknown,onClick: () => {- if (chatOnly) return;+ if (chatOnlyMeasured) return;navigate({ to: "/studio" });closeMobileIfOpen();},@@ -991,10 +1052,9 @@ export function AppSidebar() {icon: FlimSlateIcon,label: t("shell.navigation.video"),active: pathname === "/video" || pathname.startsWith("/video/"),- disabled: chatOnly,- tooltip: chatOnly- ? "Video generation needs an NVIDIA or AMD GPU."- : undefined,+ disabled: chatOnlyMeasured,+ tooltip: videoDisabledHint,+ pending: capabilitiesUnknown,onClick: () => {navigate({ to: "/video" });closeMobileIfOpen();@@ -1935,6 +1995,8 @@ export function AppSidebar() {Sidebar navigation. */}{inlineNavIds.map((id) => {const row = navRows[id];+ // A row whose capability is still unmeasured spins instead of blacking out.+ const rowState = resolveNavRowState(row);return (<NavItemkey={id}@@ -1945,9 +2007,10 @@ export function AppSidebar() {active={id === "images" && imagesWorkflowsListed ? false : row.active}- disabled={row.disabled}- tooltip={row.tooltip}- spinner={row.spinner}+ disabled={rowState.disabled}+ tooltip={rowState.tooltip}+ spinner={rowState.spinner}+ testId={`nav-row-${id}`}onClick={row.onClick}onIntent={row.onIntent}className={cn(@@ -2035,6 +2098,8 @@ export function AppSidebar() {>{overflowNavIds.map((id) => {const row = navRows[id];+ // Same pending handling as the inline rows above.+ const rowState = resolveNavRowState(row);return (<MoreMenuItemkey={id}@@ -2042,9 +2107,9 @@ export function AppSidebar() {label={row.label}badge={row.badge}active={row.active}- disabled={row.disabled}- tooltip={row.tooltip}- spinner={row.spinner}+ disabled={rowState.disabled}+ tooltip={rowState.tooltip}+ spinner={rowState.spinner}onSelect={row.onClick}onIntent={row.onIntent}/>diff --git a/studio/frontend/src/components/assistant-ui/thread.tsx b/studio/frontend/src/components/assistant-ui/thread.tsxindex 17f0869ec35..e4c9d5bb151 100644--- a/studio/frontend/src/components/assistant-ui/thread.tsx+++ b/studio/frontend/src/components/assistant-ui/thread.tsx@@ -143,6 +143,7 @@ import {shouldSubmitDictation,} from "@/features/chat/utils/dictation-send";import { listThreadDocuments } from "@/features/rag/api/rag-api";+import { useRagAvailabilityStore } from "@/features/rag/api/rag-availability";import { ThreadDocumentsBar } from "@/features/rag/components/thread-documents-bar";import { KnowledgeBaseComposerButton } from "@/features/rag/components/knowledge-base-composer-button";import { DocumentPreviewMount } from "@/features/rag/components/document-preview-mount";@@ -445,7 +446,12 @@ async function targetHasIndexingDocuments(item: PromptQueueItem) {// A failed status probe cannot prove that this thread's documents are// ready. Keep the queued send pending and retry instead of dispatching// without the RAG documents it was explicitly waiting for.- return true;+ //+ // Unless RAG cannot run on this host at all: the probe can never succeed+ // there, and dispatchQueuedPrompt reschedules on every "still indexing",+ // so waiting it out means the queued prompt is never sent. There are no+ // documents to wait for, so send it.+ return !useRagAvailabilityStore.getState().isUnavailable();}}diff --git a/studio/frontend/src/components/nav-row-state.ts b/studio/frontend/src/components/nav-row-state.tsnew file mode 100644index 00000000000..7e6bd65daae--- /dev/null+++ b/studio/frontend/src/components/nav-row-state.ts@@ -0,0 +1,31 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++// How a sidebar nav row renders once its pending state is folded in. Its own import-free+// module so it is testable: app-sidebar.tsx pulls in the whole shell.++export type NavRowState = {+ disabled?: boolean;+ tooltip?: string;+ spinner?: boolean;+ pending?: boolean;+};++/**+ * Fold `pending` into the props the row renders with.+ *+ * A guessed gray-out reads exactly like a measured one, so while the capability verdict is out+ * the row stays enabled and spins instead: the user sees "still checking", and the click lands+ * on a page that shows its own loading state. Both render sites (the inline rows and the More+ * flyout) go through here so they cannot drift.+ */+export function resolveNavRowState(row: NavRowState): {+ disabled?: boolean;+ tooltip?: string;+ spinner?: boolean;+} {+ if (row.pending) {+ return { disabled: false, tooltip: undefined, spinner: true };+ }+ return { disabled: row.disabled, tooltip: row.tooltip, spinner: row.spinner };+}diff --git a/studio/frontend/src/config/env.ts b/studio/frontend/src/config/env.tsindex f531284fef6..cae937205da 100644--- a/studio/frontend/src/config/env.ts+++ b/studio/frontend/src/config/env.ts@@ -37,6 +37,11 @@ interface PlatformState {// until a first-use operation detects, so the sidebar polls on this.detectionDeferred: boolean;isChatOnly: () => boolean;+ // True until /api/health has answered with a server-measured verdict. Before that `chatOnly`+ // is the browser-platform seed below, not an answer, so anything that would gray a+ // capability out has to treat it as unknown: rendering the guess blacks out Train and Video+ // on every Mac from first paint, visually identical to a measured "unsupported".+ capabilitiesUnknown: () => boolean;}// Client-side fallback when backend isn't ready yet.@@ -53,6 +58,9 @@ const localDeviceType = detectLocalPlatform();export const usePlatformStore = create<PlatformState>()((_, get) => ({deviceType: localDeviceType,+ // A guess from the user agent, kept only as the pre-measurement fallback for the redirects+ // that must decide something before /api/health answers. Capability gating must read+ // capabilitiesUnknown() first and hold, not gray a tab out on this.chatOnly: localDeviceType === "mac",chatOnlyReason: null,cloudflareUrl: null,@@ -61,6 +69,14 @@ export const usePlatformStore = create<PlatformState>()((_, get) => ({fetched: false,detectionDeferred: false,isChatOnly: () => get().chatOnly,+ // `fetched` already means "a server-reported verdict is stored" (see fetchDeviceType), so it+ // is the unknown/known line; no second flag to keep in step with it. A deferred reply counts+ // as settled even though it carries no device_type: under the torch-warm kill switch nothing+ // else is coming this session, so treating it as unknown would spin the tabs forever.+ capabilitiesUnknown: () => {+ const state = get();+ return !state.fetched && !state.detectionDeferred;+ },}));// Once an authoritative (server-reported) platform has been fetched, adiff --git a/studio/frontend/src/features/rag/api/rag-api.ts b/studio/frontend/src/features/rag/api/rag-api.tsindex 3fd342a5cdc..3c7f759084d 100644--- a/studio/frontend/src/features/rag/api/rag-api.ts+++ b/studio/frontend/src/features/rag/api/rag-api.ts@@ -13,6 +13,7 @@ import type {RagDocument,UploadedDocument,} from "../types/rag";+import { noteRagAvailability, noteRagResponse } from "./rag-availability";const RAG_BASE = "/api/rag";@@ -35,8 +36,14 @@ async function ragRequest<T>(headers: init?.body ? { "Content-Type": "application/json" } : undefined,body: init?.body ? JSON.stringify(init.body) : undefined,});- if (response.status === 204) return undefined as T;+ if (response.status === 204) {+ noteRagResponse(204, null);+ return undefined as T;+ }const json = await response.json().catch(() => null);+ // Every RAG endpoint but the list gates on the extension loading, so its status is+ // also an availability answer. See api/rag-availability.+ noteRagResponse(response.status, json);if (!response.ok) throw new Error(parseErrorText(response.status, json));return json as T;}@@ -66,14 +73,21 @@ async function ragUpload(body: form,});const json = await response.json().catch(() => null);+ // Uploads bypass ragRequest, so they have to report availability themselves.+ noteRagResponse(response.status, json);if (!response.ok) throw new Error(parseErrorText(response.status, json));return json as DocumentUploadResult;}export async function listKnowledgeBases(): Promise<KnowledgeBase[]> {- const data = await ragRequest<{ knowledgeBases: KnowledgeBase[] }>(- "/knowledge-bases",- );+ const data = await ragRequest<{+ knowledgeBases: KnowledgeBase[];+ ragAvailable?: boolean;+ ragUnavailableReason?: string | null;+ }>("/knowledge-bases");+ // The one endpoint that degrades to 200 instead of 503, so an empty list here means+ // either an empty store or a host where RAG cannot run. The marker tells them apart.+ noteRagAvailability(data);return data.knowledgeBases ?? [];}@@ -240,6 +254,8 @@ export async function* streamJobEvents();if (!response.ok) {const body = await response.json().catch(() => null);+ // Also gated on the extension, and also not routed through ragRequest.+ noteRagResponse(response.status, body);throw new Error(parseErrorText(response.status, body));}if (!response.body) throw new Error("Stream response missing body");diff --git a/studio/frontend/src/features/rag/api/rag-availability.ts b/studio/frontend/src/features/rag/api/rag-availability.tsnew file mode 100644index 00000000000..01ad1c751f5--- /dev/null+++ b/studio/frontend/src/features/rag/api/rag-availability.ts@@ -0,0 +1,159 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++import { create } from "zustand";++import { formatFastApiDetail } from "@/lib/format-fastapi-error";++// Whether RAG can run on this host at all, as reported by the backend.+//+// A machine where sqlite-vec imports but its native library will not load has a working+// server and a dead RAG engine. The router says so rather than raising: GET+// /api/rag/knowledge-bases answers 200 with an availability marker beside the (empty)+// list, and every other RAG endpoint answers 503 with the same reason. Without this+// store both readings are dropped on the floor and the Knowledge bases dialog looks+// like an empty store, offering a Create button that can only 503.+//+// Read it the way the platform store in config/env.ts is read: `isUnavailable()`, never+// `available` on its own. Everything here is optimistic until the backend has actually+// answered, because graying a feature out on a guess is indistinguishable from a+// measured "unsupported", and a backend that predates the marker never answers at all.++/** The shape the KB list carries; older backends send neither field. */+interface RagAvailabilityMarker {+ ragAvailable?: unknown;+ ragUnavailableReason?: unknown;+}++/** Used when the backend states unavailable without stating why. */+const DEFAULT_UNAVAILABLE_REASON =+ "RAG is unavailable on this machine: the sqlite-vec extension could not be loaded.";++// What routes/rag.py sends with its 503 ("RAG is unavailable: the sqlite-vec extension+// could not be loaded."). Matched on the extension name rather than the whole sentence,+// so a reworded detail still reads as the backend's verdict while a proxy's "Service+// Temporarily Unavailable" does not.+//+// Deliberately NOT "rag is unavailable" as well. That phrase is the loose half of the+// pair: anything RAG-aware in front of the backend could emit it without meaning the+// extension, and matching either fragment would then persist a capability verdict from a+// transient outage. "sqlite-vec" is a package name, so nothing upstream says it by+// accident, and the whole capability being gated here is exactly that extension.+const RAG_UNAVAILABLE_MARKERS = ["sqlite-vec"];++/** True only for a 503 body the RAG router itself produced. */+function isRagUnavailableDetail(detail: string | null | undefined): detail is string {+ if (!detail) return false;+ const text = detail.toLowerCase();+ return RAG_UNAVAILABLE_MARKERS.some((marker) => text.includes(marker));+}++interface RagAvailabilityState {+ // Optimistic seed. Never gate on this directly; it is "not known to be broken",+ // not an answer. See isUnavailable().+ available: boolean;+ // Why RAG cannot run, straight from the backend, so the UI explains itself instead+ // of showing a generic empty state. Null while available or unknown.+ reason: string | null;+ // True once a RAG response has actually said something about availability.+ answered: boolean;+ /** The only safe gate: a measured "RAG cannot run here", never the optimistic seed. */+ isUnavailable: () => boolean;+ /** True until a response has settled it. Callers that would disable something hold. */+ availabilityUnknown: () => boolean;+ /** The reason to show, or null when there is nothing measured to explain. */+ unavailableReason: () => string | null;+}++export const useRagAvailabilityStore = create<RagAvailabilityState>()(+ (_, get) => ({+ available: true,+ reason: null,+ answered: false,+ // `answered` is the unknown/known line, so the optimistic seed can never gate+ // anything: an unreachable backend, a slow first poll and a backend with no marker+ // at all all render exactly as they do today.+ isUnavailable: () => {+ const state = get();+ return state.answered && !state.available;+ },+ availabilityUnknown: () => !get().answered,+ unavailableReason: () => {+ const state = get();+ return state.answered && !state.available ? state.reason : null;+ },+ }),+);++/** True when a response body carries the backend's availability marker. */+export function hasRagAvailabilityMarker(body: unknown): boolean {+ if (!body || typeof body !== "object") return false;+ return typeof (body as RagAvailabilityMarker).ragAvailable === "boolean";+}++/**+ * Record the availability marker the KB list carries.+ *+ * No-op when the body has no marker: that is an older backend, or a build without the+ * contract, and inventing an answer for it is what would gray the dialog out on a guess.+ */+export function noteRagAvailability(body: unknown): void {+ if (!hasRagAvailabilityMarker(body)) return;+ const { ragAvailable, ragUnavailableReason } = body as RagAvailabilityMarker;+ if (ragAvailable === true) {+ useRagAvailabilityStore.setState({+ available: true,+ reason: null,+ answered: true,+ });+ return;+ }+ useRagAvailabilityStore.setState({+ available: false,+ reason:+ typeof ragUnavailableReason === "string" && ragUnavailableReason+ ? ragUnavailableReason+ : DEFAULT_UNAVAILABLE_REASON,+ answered: true,+ });+}++/**+ * Record what an arbitrary RAG response says about availability.+ *+ * The KB list is the only endpoint that states it in the body; the rest state it as a+ * 503, which every one of them gates on. Reading both means a user who lands on a+ * mutating route first gets a coherent UI instead of waiting for the list poll.+ *+ * A 2xx from a gated endpoint is proof RAG is runnable, so it clears a stale+ * unavailable. The list is excluded from that rule: it answers 200 either way, and its+ * marker is the authority.+ */+export function noteRagResponse(status: number, body: unknown): void {+ if (status === 503) {+ const detail = formatFastApiDetail(+ (body as { detail?: unknown } | null)?.detail,+ );+ // Only the backend's own wording is a capability verdict. A 503 is also what a+ // reverse proxy, Cloudflare, or a briefly overloaded server returns, and those+ // bodies say nothing about sqlite-vec. Recording one as unavailable would gate the+ // dialog for the session behind a transient outage, showing an extension+ // explanation for something that was never the extension.+ if (!isRagUnavailableDetail(detail)) return;+ useRagAvailabilityStore.setState({+ available: false,+ reason: detail,+ answered: true,+ });+ return;+ }+ // Any other failure is transient (auth, validation, a dead network) and says nothing+ // about whether the extension loads.+ if (status < 200 || status >= 300) return;+ if (hasRagAvailabilityMarker(body)) return;+ useRagAvailabilityStore.setState({+ available: true,+ reason: null,+ answered: true,+ });+}diff --git a/studio/frontend/src/features/rag/components/knowledge-base-dialog.tsx b/studio/frontend/src/features/rag/components/knowledge-base-dialog.tsxindex d80c77b12c8..8245b353be7 100644--- a/studio/frontend/src/features/rag/components/knowledge-base-dialog.tsx+++ b/studio/frontend/src/features/rag/components/knowledge-base-dialog.tsx@@ -41,6 +41,7 @@ import {listKnowledgeBases,updateKnowledgeBase,} from "../api/rag-api";+import { useRagAvailabilityStore } from "../api/rag-availability";import { RAG_UPLOAD_ACCEPT, type KnowledgeBase } from "../types/rag";import { DocumentStatusChip } from "./document-status-chip";import { useRagDocuments } from "./use-rag-documents";@@ -69,6 +70,15 @@ export function KnowledgeBaseDialog({const [confirmingDelete, setConfirmingDelete] = useState<KnowledgeBase | null>(null,);+ // Measured only: while the answer is unknown this stays false and the dialog renders+ // exactly as it always has. See api/rag-availability.+ const ragUnavailable = useRagAvailabilityStore((s) => s.isUnavailable());+ const ragUnavailableReason = useRagAvailabilityStore((s) =>+ s.unavailableReason(),+ );+ const ragUnavailableHint = ragUnavailable+ ? (ragUnavailableReason ?? undefined)+ : undefined;const refresh = useCallback(async () => {setLoading(true);@@ -106,6 +116,14 @@ export function KnowledgeBaseDialog({}async function submitForm() {+ // The button is disabled for this, but the form is also reachable by keyboard and+ // the verdict can land while it is open. A 503 toast is not an explanation.+ if (ragUnavailable) {+ toast.error("Knowledge bases are unavailable", {+ description: ragUnavailableReason ?? undefined,+ });+ return;+ }const trimmed = name.trim();if (!trimmed) {toast.error("Name is required");@@ -193,7 +211,7 @@ export function KnowledgeBaseDialog({<Button variant="ghost" onClick={backToList} disabled={saving}>Cancel</Button>- <Button onClick={submitForm} disabled={saving}>+ <Button onClick={submitForm} disabled={saving || ragUnavailable}>{saving ? <Spinner /> : null}{view.kind === "edit" ? "Save changes" : "Create"}</Button>@@ -202,7 +220,12 @@ export function KnowledgeBaseDialog({) : (<div className="flex min-w-0 flex-col gap-3"><div className="flex justify-end">- <Button size="sm" onClick={startCreate}>+ <Button+ size="sm"+ onClick={startCreate}+ disabled={ragUnavailable}+ title={ragUnavailableHint}+ ><HugeiconsIcon icon={PlusSignIcon} size={14} />New knowledge base</Button>@@ -211,6 +234,11 @@ export function KnowledgeBaseDialog({<div className="flex justify-center py-6"><Spinner /></div>+ ) : ragUnavailable ? (+ // An empty list on this host is not an empty store, so say which one it is.+ <div className="rounded-md border border-dashed px-4 py-6 text-center text-sm text-muted-foreground">+ {ragUnavailableReason ?? "Knowledge bases are unavailable."}+ </div>) : kbs.length === 0 ? (<div className="rounded-md border border-dashed py-6 text-center text-sm text-muted-foreground">No knowledge bases yet.diff --git a/studio/frontend/src/features/studio/studio-page.tsx b/studio/frontend/src/features/studio/studio-page.tsxindex 1b20a73d0a4..6b458f62beb 100644--- a/studio/frontend/src/features/studio/studio-page.tsx+++ b/studio/frontend/src/features/studio/studio-page.tsx@@ -1,8 +1,10 @@// SPDX-License-Identifier: AGPL-3.0-only// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0+import { usePlatformStore } from "@/config/env";import { Button } from "@/components/ui/button";import { useSidebar } from "@/components/ui/sidebar";+import { Spinner } from "@/components/ui/spinner";import { Tabs, TabsContent } from "@/components/ui/tabs";import { useHfTokenStore } from "@/features/hub";import { GuidedTour, useGuidedTourController } from "@/features/tour";@@ -17,6 +19,7 @@ import { MediaPageLink } from "@/components/media-page-link";import { useImageWorkflowStore } from "@/features/images/stores/image-workflow-store";import { ArrowLeft01Icon, Image03Icon } from "@hugeicons/core-free-icons";import { HugeiconsIcon } from "@hugeicons/react";+import { useNavigate } from "@tanstack/react-router";import {type ReactElement,useCallback,@@ -69,6 +72,16 @@ export function StudioPage(): ReactElement {isDatasetImage: s.isDatasetImage,})),);+ // Unknown until /api/health reports; see the showTrainingHydrating note below.+ const capabilitiesUnknown = usePlatformStore((s) => s.capabilitiesUnknown());+ const chatOnly = usePlatformStore((s) => s.isChatOnly());+ const navigate = useNavigate();+ // Once the verdict lands and it really is chat-only, leave: the guard let this load on the+ // guess, so without this a chat-only host would sit on a Train page it cannot use.+ useEffect(() => {+ if (capabilitiesUnknown || !chatOnly) return;+ void navigate({ to: "/chat", replace: true });+ }, [capabilitiesUnknown, chatOnly, navigate]);const hfToken = useHfTokenStore((s) => s.token);const selectedModel = useTrainingConfigStore((s) => s.selectedModel);const ensureModelDefaultsLoaded = useTrainingConfigStore(@@ -137,7 +150,13 @@ export function StudioPage(): ReactElement {t,});- const showTrainingHydrating = !hasHydratedRuntime && isHydratingRuntime;+ // The root guard now lets /studio through while the hardware verdict is out (redirecting on+ // the browser-platform guess strands a healthy host on /chat), so the page owns the wait:+ // show the same loading panel as a hydrating runtime rather than a half-built wizard. The+ // wait ends by itself: AppSidebar (mounted on this route) re-reads /api/health while the+ // verdict is unknown and writes it to this same store, so no second poll is needed here.+ const showTrainingHydrating =+ capabilitiesUnknown || (!hasHydratedRuntime && isHydratingRuntime);const showHistoryBack = activeTab === "history" && !!selectedHistoryRunId;return (@@ -196,7 +215,8 @@ export function StudioPage(): ReactElement {<GuidedTour {...tour.tourProps} celebrate={isConfigTour} />{showTrainingHydrating ? (- <div className="rounded-2xl border border-border/60 p-8 text-sm text-muted-foreground">+ <div className="flex items-center gap-3 rounded-2xl border border-border/60 p-8 text-sm text-muted-foreground">+ <Spinner className="size-4 shrink-0" />{t("studio.loadingRuntime")}</div>) : (diff --git a/studio/frontend/src/features/video/video-page.tsx b/studio/frontend/src/features/video/video-page.tsxindex bde15d5562c..818500e739e 100644--- a/studio/frontend/src/features/video/video-page.tsx+++ b/studio/frontend/src/features/video/video-page.tsx@@ -14,6 +14,8 @@ import { HugeiconsIcon } from "@hugeicons/react";import { AdvancedDisclosure } from "@/components/advanced-disclosure";import { MediaPageLink } from "@/components/media-page-link";+import { usePlatformStore } from "@/config/env";+import { useHardwareInfo } from "@/hooks/use-hardware-info";import { usePersistedToggle } from "@/hooks/use-persisted-toggle";import { Button } from "@/components/ui/button";import {@@ -491,7 +493,61 @@ function RecipeRow({type Busy = "loading" | "unloading" | "generating" | null;+// Centered panel used for both halves of the capability gate below: the wait, and the answer.+function VideoGate({ children }: { children: ReactNode }) {+ return (+ <div className="diffusion-surface flex h-full min-h-0 min-w-0 flex-1 flex-col items-center justify-center gap-3 pt-[var(--studio-content-top-inset,0px)] text-center text-sm text-muted-foreground">+ {children}+ </div>+ );+}++/**+ * Capability gate in front of the generator.+ *+ * The root guard never bounces /video: not on the browser-platform guess, and not on a measured+ * chat-only verdict either, because a CPU-only host or a Mac without MLX is precisely where the+ * explanation below has something to say. Video also has no Apple path in the backend, so the+ * page answers for itself: spin while the answer is out, explain when it is no.+ *+ * The spin is bounded: AppSidebar is mounted on this route and re-reads /api/health while the+ * verdict is unknown, writing it to the same store this reads, so a host slower than+ * fetchDeviceType's bounded wait still lands here rather than spinning for the session.+ */export function VideoPage({ active = true }: { active?: boolean }) {+ const hardware = useHardwareInfo();+ const capabilitiesUnknown = usePlatformStore((s) => s.capabilitiesUnknown());++ if (capabilitiesUnknown || !hardware.loaded) {+ return (+ <VideoGate>+ <Spinner className="size-5" />+ <span>Checking this machine for video support...</span>+ </VideoGate>+ );+ }++ // Only an authoritative "no" hides the generator; an older backend omits the field, which+ // arrives as null, and must keep the page it has always served.+ if (hardware.videoSupported === false) {+ return (+ <VideoGate>+ <HugeiconsIcon+ icon={FlimSlateIcon}+ className="size-7 shrink-0 text-muted-foreground/70"+ />+ <p className="max-w-sm text-balance">+ {hardware.videoUnsupportedMessage ??+ "Video generation is not supported on this machine."}+ </p>+ </VideoGate>+ );+ }++ return <VideoGenerator active={active} />;+}++function VideoGenerator({ active = true }: { active?: boolean }) {const [quant, setQuant] = useState<string | null>(galleryCache.quant);const [prompt, setPrompt] = useState("a tiny ginger sloth surfing a wave at sunset, cinematic, smooth motion",diff --git a/studio/frontend/src/hooks/use-hardware-info.ts b/studio/frontend/src/hooks/use-hardware-info.tsindex 1db96016d93..36f42f94054 100644--- a/studio/frontend/src/hooks/use-hardware-info.ts+++ b/studio/frontend/src/hooks/use-hardware-info.ts@@ -34,6 +34,12 @@ export interface HardwareInfo {exportSupported: boolean | null;exportUnsupportedReason: string | null;exportUnsupportedMessage: string | null;+ // Whether video generation can run here. Same tri-state as export: `null` until the+ // authoritative response lands, and `null` too against a backend that predates the field,+ // so only an explicit `false` hides the generator.+ videoSupported: boolean | null;+ videoUnsupportedReason: string | null;+ videoUnsupportedMessage: string | null;loaded: boolean;}@@ -52,9 +58,15 @@ const DEFAULT: HardwareInfo = {exportSupported: null,exportUnsupportedReason: null,exportUnsupportedMessage: null,+ videoSupported: null,+ videoUnsupportedReason: null,+ videoUnsupportedMessage: null,loaded: false,};+// How long a caller waits before re-probing after a failed read. See useHardwareInfo.+const RETRY_MS = 3000;+// Module-level cache so multiple components share one fetch.let cached: HardwareInfo | null = null;let fetchPromise: Promise<HardwareInfo> | null = null;@@ -106,6 +118,9 @@ async function fetchOnce(): Promise<HardwareInfo> {exportSupported: data?.export_supported ?? null,exportUnsupportedReason: data?.export_unsupported_reason ?? null,exportUnsupportedMessage: data?.export_unsupported_message ?? null,+ videoSupported: data?.video_supported ?? null,+ videoUnsupportedReason: data?.video_unsupported_reason ?? null,+ videoUnsupportedMessage: data?.video_unsupported_message ?? null,loaded: true,};if (generation === cacheGeneration) {@@ -113,7 +128,10 @@ async function fetchOnce(): Promise<HardwareInfo> {notifyHardwareInfo(info);return info;}- return cached ?? DEFAULT;+ // Superseded by a later invalidate, so it must not become the cache. It is+ // still a real 200 though: returning DEFAULT tells every caller riding this+ // promise that a healthy read failed, and load() reads that as a failed probe.+ return cached ?? info;} catch {// Reset so subsequent calls retry (e.g. backend wasn't ready).if (generation === cacheGeneration) fetchPromise = null;@@ -138,10 +156,28 @@ export function useHardwareInfo(): HardwareInfo {};listeners.add(listener);- if (!cached) fetchOnce().then(listener);+ // A failed probe resolves to DEFAULT (loaded false) and clears the in-flight promise,+ // but nothing re-ran it, so the only retry was another component happening to mount.+ // Callers that gate a whole page on `loaded` would wait out the session on one blip.+ let retry: ReturnType<typeof setTimeout> | undefined;+ const load = () => {+ fetchOnce().then((hw) => {+ listener(hw);+ if (!cancelled && !hw.loaded) retry = setTimeout(load, RETRY_MS);+ });+ };+ // `info` was seeded from `cached` at render time, but this listener only joins the+ // set now. A probe that resolved in between notified the listeners registered at+ // the time -- not this one -- and left `cached` set, so `if (!cached) load()` alone+ // skipped the fetch and nothing was ever going to call setInfo. The component then+ // sat on DEFAULT with loaded false for its whole life, which on /video is the+ // capability gate's "Checking this machine for video support..." for the session.+ if (cached) listener(cached);+ else load();return () => {cancelled = true;listeners.delete(listener);+ if (retry !== undefined) clearTimeout(retry);};}, []);diff --git a/studio/frontend/tests/chat-only-route-guard.test.ts b/studio/frontend/tests/chat-only-route-guard.test.tsnew file mode 100644index 00000000000..37558008903--- /dev/null+++ b/studio/frontend/tests/chat-only-route-guard.test.ts@@ -0,0 +1,110 @@+// 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 chat-only route guard in __root.tsx, run rather than pattern-matched. Its own tests read+// the file as text (the module is .tsx and pulls in the whole app, so it is not importable+// here), which cannot answer the question that matters: given a host and a path, does the guard+// redirect? Lift the constants, the two predicates and the beforeLoad condition out of the+// source and evaluate them.+//+// The case this was written for: a measured chat-only host, meaning a CPU-only box, a Mac+// without usable MLX, or one with no PyTorch. `unmeasured` is false there, so the wait-it-out+// list does not apply, and /video used to fall through to the redirect. VideoPage carries the+// backend's own explanation for exactly those hosts (video_capability reports+// pytorch_not_installed / no_accelerator / macos_unsupported), so bouncing to /chat made the+// message unreachable in the only cases it exists for.++import assert from "node:assert/strict";+import { readFile } from "node:fs/promises";+import test from "node:test";++const src = await readFile(new URL("../src/app/routes/__root.tsx", import.meta.url), "utf8");++function lift(pattern: RegExp, what: string): string {+ const found = pattern.exec(src);+ assert.ok(found, `could not find ${what} in __root.tsx`);+ return found[0];+}++// The only annotations in the lifted code are the two identical predicate signatures. Dropping+// them by hand keeps this a plain-node test; a changed signature fails loudly below, when the+// evaluated source refuses to parse.+const declarations = [+ lift(/const CHAT_ONLY_ALLOWED = new Set\(\[[\s\S]*?\n\]\);/, "CHAT_ONLY_ALLOWED"),+ lift(/const SELF_GATED_WHILE_UNKNOWN = \[[^\]]*\];/, "SELF_GATED_WHILE_UNKNOWN"),+ lift(/function waitsOutUnknownVerdict\([\s\S]*?\n\}/, "waitsOutUnknownVerdict"),+ lift(/function isChatOnlyAllowed\([\s\S]*?\n\}/, "isChatOnlyAllowed"),+]+ .join("\n")+ .replaceAll("(pathname: string): boolean", "(pathname)");++// The guard itself, with its two inputs made into parameters: the store call becomes the+// host verdict, the router's location becomes the path under test.+const guard = /if \(\s*isChatOnly\(\) &&([\s\S]*?)\)\s*\{\s*throw redirect/.exec(src);+assert.ok(guard, "could not find the chat-only redirect in beforeLoad");+const condition = `isChatOnly() &&${guard[1]}`+ .replaceAll("isChatOnly()", "chatOnly")+ .replaceAll("location.pathname", "pathname");+// Both inputs have to have been substituted, or the evaluated guard is not the shipped one.+assert.ok(!condition.includes("location."), "the guard reads a location this test cannot set");+assert.ok(!condition.includes("isChatOnly()"), "the guard reads a verdict this test cannot set");++const redirectsToChat = new Function(+ "pathname",+ "chatOnly",+ "unmeasured",+ `${declarations}\nreturn Boolean(${condition});`,+) as (pathname: string, chatOnly: boolean, unmeasured: boolean) => boolean;++// A host that has answered: chat_only true, nothing left to wait for.+const measuredChatOnly = (pathname: string) => redirectsToChat(pathname, true, false);++test("a measured chat-only host reaches /video and its own explanation", () => {+ assert.equal(+ measuredChatOnly("/video"),+ false,+ "a direct link or a reload at /video bounces to /chat, so the no-GPU, no-PyTorch and " ++ "macOS explanations on VideoPage are unreachable on every host that has one",+ );+ assert.equal(+ measuredChatOnly("/video/anything"),+ false,+ "only the exact path is allowed through, so a child route still bounces",+ );+});++// The Train page has no equivalent message: it is the training wizard or nothing, and+// StudioPage navigates to /chat itself the moment it reads a measured chat-only verdict. Being+// allowed in would buy a flash of the wizard and a lazy chunk before the same exit. The reason+// is on the sidebar row's tooltip instead. Keep the redirect; this pins the asymmetry as chosen.+test("a measured chat-only host is still redirected off /studio", () => {+ assert.equal(measuredChatOnly("/studio"), true);+ assert.equal(measuredChatOnly("/studio/runs"), true);+});++test("an unmeasured verdict still lets both pages wait it out", () => {+ for (const path of ["/studio", "/studio/runs", "/video"]) {+ assert.equal(+ redirectsToChat(path, true, true),+ false,+ `${path} is redirected on the pre-measurement guess, which is one-way`,+ );+ }+});++test("the pages that self-gate are unaffected, and everything else still redirects", () => {+ // Allowed for the same reason /video now is: each explains itself instead of vanishing.+ for (const path of ["/chat", "/export", "/images", "/api-monitor", "/data-recipes"]) {+ assert.equal(measuredChatOnly(path), false, `${path} no longer survives the guard`);+ }+ // Nothing was widened past the paths that opt in.+ for (const path of ["/settings", "/videos", "/videoish"]) {+ assert.equal(measuredChatOnly(path), true, `${path} slipped through the chat-only guard`);+ }+});++test("a host that is not chat-only is never redirected", () => {+ for (const path of ["/studio", "/video", "/settings"]) {+ assert.equal(redirectsToChat(path, false, false), false);+ }+});diff --git a/studio/frontend/tests/hardware-verdict-recovery.test.ts b/studio/frontend/tests/hardware-verdict-recovery.test.tsnew file mode 100644index 00000000000..1c5565a1bf2--- /dev/null+++ b/studio/frontend/tests/hardware-verdict-recovery.test.ts@@ -0,0 +1,178 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++// Train and Video spin instead of graying out while the hardware verdict is unmeasured, so+// something has to end the spin. fetchDeviceType's bounded wait is spent at most once per page+// load, so a host that detects slower than it stores a provisional reply and `fetched` stays+// false. The sidebar's recovery poll used to return early unless the host was chat-only or+// deferred, which on Linux and Windows it is not (the store seeds chatOnly from the user agent),+// so nothing re-read /api/health: the rows spun and /studio held its loading panel until the+// user reloaded. A cold GPU host importing torch is squarely inside that window.++import assert from "node:assert/strict";+import { readFile } from "node:fs/promises";+import { register } from "node:module";+import test from "node:test";++import { installLocalStorageFake, registerBundlerResolver } from "./helpers/kit.ts";++register("./helpers/vite-env-loader.mjs", import.meta.url);+registerBundlerResolver();+const { store } = installLocalStorageFake();+// /api/health reports device_type to authed callers only, and an unauthenticated read never+// spends the detection window, so the slow-host case only exists for a signed-in caller.+store.set("unsloth_auth_token", "token");+// A non-Mac host whatever the runner is: node's own navigator reports process.platform.+Object.defineProperty(globalThis, "navigator", {+ configurable: true,+ value: {+ platform: "Linux x86_64",+ userAgent: "Mozilla/5.0 (X11; Linux x86_64)",+ },+});++// The backend's pre-detection default: chat_only true, no device_type, still measuring.+const DETECTING = { chat_only: true, hardware_detecting: true, version: "2026.1.1" };+// What the same host answers once the torch import lands.+const MEASURED = {+ device_type: "linux",+ chat_only: false,+ chat_only_reason: null,+ version: "2026.1.1",+};++let reply: Record<string, unknown> = DETECTING;+let fetches = 0;+globalThis.fetch = (async () => {+ fetches += 1;+ const body = reply;+ const res = { ok: true, json: async () => ({ ...body }), clone: () => res };+ return res;+}) as unknown as typeof fetch;++const { fetchDeviceType, usePlatformStore } = await import("../src/config/env.ts");++test("a slow non-Mac host converges out of the pending state", async () => {+ const realDateNow = Date.now;+ let clock = realDateNow();+ // The window is 5s of wall clock with 200ms re-reads. Step the clock so the test does not+ // sit through it; detection is still unfinished when it closes, which is the whole case.+ Date.now = () => (clock += 2000);+ try {+ await fetchDeviceType();+ } finally {+ Date.now = realDateNow;+ }++ const stalled = usePlatformStore.getState();+ assert.equal(stalled.deviceType, "linux", "the scenario is a non-Mac host");+ assert.equal(stalled.fetched, false, "a provisional reply was stored as a measurement");+ assert.equal(stalled.detectionDeferred, false, "the reply was slow, not deferred");+ assert.equal(+ stalled.capabilitiesUnknown(),+ true,+ "nothing left unknown, so this is no longer the case the poll has to recover from",+ );+ assert.equal(+ stalled.isChatOnly(),+ false,+ "the browser seed off macOS, which is why the chat-only recovery poll never armed",+ );++ // Detection lands after the window closed. This is the re-read the sidebar interval fires.+ reply = MEASURED;+ const before = fetches;+ await fetchDeviceType({ force: true });+ assert.equal(fetches - before, 1, "one poll should be one re-read");++ const settled = usePlatformStore.getState();+ assert.equal(settled.fetched, true, "the measured reply was not stored");+ assert.equal(+ settled.capabilitiesUnknown(),+ false,+ "Train and Video keep spinning and /studio keeps its loading panel after the verdict arrived",+ );+ assert.equal(settled.isChatOnly(), false, "the measured GPU verdict was dropped");+ assert.equal(settled.deviceType, "linux");+});++test("a cached authoritative verdict is not re-read without force", async () => {+ // The poll passes force, so it must be force that re-reads: a plain call short-circuits on+ // the cached verdict, which is what keeps navigation instant.+ const before = fetches;+ await fetchDeviceType();+ assert.equal(fetches, before, "the cache no longer short-circuits, so every route refetches");+});++test("the recovery poll runs while the verdict is unknown, on every platform", async () => {+ const src = await readFile(+ new URL("../src/components/app-sidebar.tsx", import.meta.url),+ "utf8",+ );+ const call = src.indexOf("void fetchDeviceType({ force: true })");+ assert.ok(call > 0, "the recovery poll left app-sidebar.tsx");+ const start = src.lastIndexOf("useEffect(() => {", call);+ const end = src.indexOf("]);", call) + 3;+ assert.ok(start > 0 && end > start, "could not read the recovery poll effect");+ const effect = src.slice(start, end);++ const guard = /if \(([^;]*)\) return;/.exec(effect);+ assert.ok(guard, "the poll never bails out, so it runs for the life of the app");+ assert.match(+ guard[1],+ /!capabilitiesUnknown/,+ "the poll still only arms on a chat-only or deferred host, so an unmeasured verdict on " ++ "Linux or Windows is never re-read",+ );+ // The MLX self-heal case still polls after a measured chat-only verdict.+ assert.match(+ effect,+ /chatOnlyReason !== "mlx_unavailable" && !detectionDeferred/,+ "a repaired MLX install no longer re-enables Train without a reload",+ );+ const deps = /\}, \[([^\]]*)\]\);$/.exec(effect);+ assert.ok(deps, "could not read the effect's dependencies");+ assert.match(+ deps[1],+ /capabilitiesUnknown/,+ "the effect does not re-run when the verdict lands, so the interval outlives it",+ );+ assert.match(+ effect,+ /return \(\) => window\.clearInterval\(id\);/,+ "the interval is left running once the verdict is known",+ );+});++test("the poll is mounted on every route that gates on the verdict", async () => {+ const root = await readFile(+ new URL("../src/app/routes/__root.tsx", import.meta.url),+ "utf8",+ );+ const hidden = /const HIDDEN_NAVBAR_ROUTES = \[([^\]]*)\]/.exec(root);+ assert.ok(hidden, "could not find HIDDEN_NAVBAR_ROUTES in __root.tsx");+ for (const path of ["/studio", "/video"]) {+ assert.ok(+ !hidden[1].includes(`"${path}"`),+ `${path} renders without the sidebar, so nothing re-reads the verdict it waits on`,+ );+ }+ assert.match(root, /<AppSidebar \/>/, "the component that owns the poll is not rendered");++ // Both pages read the same store rather than starting a second poll of their own.+ for (const page of [+ "../src/features/studio/studio-page.tsx",+ "../src/features/video/video-page.tsx",+ ]) {+ const src = await readFile(new URL(page, import.meta.url), "utf8");+ assert.ok(+ !/fetchDeviceType\(/.test(src),+ `${page} re-reads the verdict itself instead of reading the store`,+ );+ assert.match(+ src,+ /capabilitiesUnknown/,+ `${page} no longer waits on the verdict it shares with the poll`,+ );+ }+});diff --git a/studio/frontend/tests/helpers/vite-env-loader.mjs b/studio/frontend/tests/helpers/vite-env-loader.mjsnew file mode 100644index 00000000000..acff16cd5c7--- /dev/null+++ b/studio/frontend/tests/helpers/vite-env-loader.mjs@@ -0,0 +1,18 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++// vite replaces `import.meta.env` at build time; bare node leaves it undefined, so a src+// module that reads it throws on import. Seed it instead, so a test can drive the real+// module rather than assert on its source. Register before importing any such module.+export async function load(url, context, next) {+ const result = await next(url, context);+ if (!url.includes("/src/") || result.source === undefined) return result;+ const source =+ typeof result.source === "string"+ ? result.source+ : Buffer.from(result.source).toString("utf8");+ if (!source.includes("import.meta.env")) return result;+ const seed =+ 'import.meta.env = import.meta.env ?? { MODE: "test", DEV: false, PROD: false, BASE_URL: "/" };\n';+ return { ...result, source: seed + source };+}diff --git a/studio/frontend/tests/provisional-hardware-verdict.test.ts b/studio/frontend/tests/provisional-hardware-verdict.test.tsindex 9aa7aec5b86..e4d1aa5f96e 100644--- a/studio/frontend/tests/provisional-hardware-verdict.test.ts+++ b/studio/frontend/tests/provisional-hardware-verdict.test.ts@@ -186,13 +186,24 @@ test("the latch is claimed after the wait, not during it", async () => {"utf8",);const loopStart = src.indexOf("while (res.ok && Date.now() < deadline)");- // Located by pattern: the claim carries guards, so a literal anchor goes stale.- const loopEnd = src.search(/if \(spendWait[^)]*\) hardwareWaitSpent = true;/);- assert.ok(loopStart > 0 && loopEnd > loopStart, "the wait loop or the latch moved");+ // Anchor on the loop's own closing brace, NOT on the latch. Searching for the latch+ // made this assertion unfalsifiable: String.prototype.search returns the FIRST match,+ // so moving the latch inside the loop moved loopEnd with it and the slice ended just+ // short of the claim either way. The test then passed against the exact regression its+ // header describes.+ const loopEnd = src.indexOf("\n }\n", loopStart);+ assert.ok(loopStart > 0 && loopEnd > loopStart, "the wait loop moved");assert.ok(!src.slice(loopStart, loopEnd).includes("hardwareWaitSpent = true"),"the latch is claimed inside the loop, so a concurrent caller skips an unfinished window",);+ // And it must still be claimed somewhere after the loop, or deleting it outright+ // would satisfy the check above.+ assert.match(+ src.slice(loopEnd),+ /if \(spendWait[^)]*\) hardwareWaitSpent = true;/,+ "the latch is never claimed after the wait, so the window is never spent",+ );});// A provisional reply omits device_type. A forced refresh in that window must not fall@@ -253,9 +264,10 @@ test("a rejected token stops the wait instead of polling it out", async () => {"utf8",);const loopStart = src.indexOf("while (res.ok && Date.now() < deadline)");- // Located by pattern: the claim carries guards, so a literal anchor goes stale.- const loopEnd = src.search(/if \(spendWait[^)]*\) hardwareWaitSpent = true;/);- assert.ok(loopStart > 0 && loopEnd > loopStart, "the wait loop or the latch moved");+ // Same brace anchor as above rather than the latch pattern, so the slice cannot move+ // with the code it is meant to be measuring.+ const loopEnd = src.indexOf("\n }\n", loopStart);+ assert.ok(loopStart > 0 && loopEnd > loopStart, "the wait loop moved");const loop = src.slice(loopStart, loopEnd);assert.ok(/if \(peek\.version === undefined\)\s*\{?[^}]*break;/.test(loop),@@ -290,3 +302,191 @@ test("a rejected token does not consume the once-per-load window", async () => {"nothing records that the break was caused by a rejected token",);});++// The same guess, one layer up. `chatOnly` is seeded from the user agent, so on every Mac it+// reads true from first paint, before /api/health has said anything. Train and Video rendered+// straight off it, so both tabs blacked out on launch and only came back once the backend+// answered -- which PR #7607's lazy detection can stretch to minutes.+test("the store exposes an unknown state, not just chat-only", async () => {+ const { readFile } = await import("node:fs/promises");+ const src = await readFile(+ new URL("../src/config/env.ts", import.meta.url),+ "utf8",+ );+ assert.match(+ src,+ /capabilitiesUnknown: \(\) => boolean;/,+ "PlatformState has no unknown state, so a caller can only read the guess",+ );+ assert.match(+ src,+ /return !state\.fetched && !state\.detectionDeferred;/,+ "the selector is not derived from `fetched`, the flag that already means " ++ "'a server-reported verdict is stored'",+ );+});++// The torch-warm kill switch (UNSLOTH_STUDIO_DISABLE_TORCH_WARM=1) settles nothing until a+// hardware-dependent operation runs, and a deferred reply carries no device_type, so `fetched`+// never flips. Calling that unknown would spin Train and Video for the whole session.+test("a deferred verdict counts as settled, not as still checking", async () => {+ const { readFile } = await import("node:fs/promises");+ const src = await readFile(+ new URL("../src/config/env.ts", import.meta.url),+ "utf8",+ );+ const selector = /capabilitiesUnknown: \(\) => \{([\s\S]*?)\n \},/.exec(src);+ assert.ok(selector, "capabilitiesUnknown is no longer a block the deferred case can live in");+ assert.match(+ selector[1],+ /detectionDeferred/,+ "a deferred reply leaves the tabs spinning with nothing left to wait for",+ );+});++test("the sidebar gates Train and Video on a measured verdict", async () => {+ const { readFile } = await import("node:fs/promises");+ const src = await readFile(+ new URL("../src/components/app-sidebar.tsx", import.meta.url),+ "utf8",+ );+ assert.match(+ src,+ /const chatOnlyMeasured = chatOnly && !capabilitiesUnknown;/,+ "the rows still read chatOnly directly, so the UA guess disables them",+ );+ // Every row-level use of the verdict goes through the measured form.+ //+ // `disabled: chatOnly` is an object entry, so the regressed form ends in a comma and+ // the old `includes("disabled: chatOnly;")` could never match anything. The character+ // class keeps `disabled: chatOnlyMeasured,` from matching, since "M" is not in it.+ for (const pattern of [/disabled: chatOnly[,;\s]/, /if \(chatOnly\) return;/]) {+ assert.ok(+ !pattern.test(src),+ `${pattern} still reads the unmeasured verdict`,+ );+ }+ // Both rows opt into the pending state rather than rendering a guessed gray-out.+ assert.equal(+ src.match(/pending: capabilitiesUnknown,/g)?.length,+ 2,+ "Train and Video do not both mark themselves pending while the verdict is out",+ );+});++// beforeLoad redirects are one-way: bouncing a cold /studio or /video load to /chat on the+// pre-measurement guess strands a healthy host there for the rest of the session.+test("the route guard waits out an unknown verdict on Train and Video", async () => {+ const { readFile } = await import("node:fs/promises");+ const src = await readFile(+ new URL("../src/app/routes/__root.tsx", import.meta.url),+ "utf8",+ );+ const guard = /const SELF_GATED_WHILE_UNKNOWN = \[([^\]]*)\]/.exec(src);+ assert.ok(guard, "no list of paths that wait the verdict out");+ for (const path of ["/studio", "/video"]) {+ assert.ok(guard[1].includes(`"${path}"`), `${path} is still redirected on the guess`);+ }+ assert.match(+ src,+ /!\(unmeasured && waitsOutUnknownVerdict\(location\.pathname\)\)/,+ "the redirect does not consult the unknown state",+ );+ // Child routes count too, or /studio/anything bounces while /studio does not.+ assert.match(+ src,+ /pathname === base \|\| pathname\.startsWith\(`\$\{base\}\/`\)/,+ "only the exact path waits the verdict out",+ );+});++// The tab is enabled on a healthy Apple Silicon host (chat_only is false there), and the+// backend has no video path for it, so the page has to say so rather than fail at load.+test("the Video page gates on the backend's own capability answer", async () => {+ const { readFile } = await import("node:fs/promises");+ const src = await readFile(+ new URL("../src/features/video/video-page.tsx", import.meta.url),+ "utf8",+ );+ assert.match(+ src,+ /hardware\.videoSupported === false/,+ "the page does not read the backend's video verdict",+ );+ assert.match(+ src,+ /capabilitiesUnknown \|\| !hardware\.loaded/,+ "the page renders its generator before the verdict has landed",+ );+ // A backend that predates the field sends nothing, which arrives as null; only an explicit+ // false may hide the generator.+ assert.ok(+ !/videoSupported !== true/.test(src),+ "an older backend's missing field would hide the page it has always served",+ );+});++// The hardcoded "needs an NVIDIA or AMD GPU" is wrong on Apple Silicon: no GPU the user can+// add would help, because there is no Apple video path at all.+test("the Video tooltip is derived, not hardcoded", async () => {+ const { readFile } = await import("node:fs/promises");+ const src = await readFile(+ new URL("../src/components/app-sidebar.tsx", import.meta.url),+ "utf8",+ );+ assert.match(src, /const videoDisabledHint: string \| undefined/, "no derived video hint");+ assert.match(+ src,+ /platformDeviceType === "mac"\s*\?\s*"Video generation on macOS is coming soon\."/,+ "a Mac is still told to fit a GPU",+ );+ assert.ok(+ !/tooltip: chatOnly\s*\n?\s*\? "Video generation needs an NVIDIA or AMD GPU\."/.test(src),+ "the hardcoded tooltip is still wired to the row",+ );+});++// The Video gate waits on useHardwareInfo's `loaded`, and a failed probe used to resolve to+// DEFAULT (loaded false) with nothing scheduled to run again: one blip and the page spun for+// the rest of the session.+test("a failed hardware probe is retried, not left unloaded", async () => {+ const { readFile } = await import("node:fs/promises");+ const src = await readFile(+ new URL("../src/hooks/use-hardware-info.ts", import.meta.url),+ "utf8",+ );+ assert.match(+ src,+ /if \(!cancelled && !hw\.loaded\) retry = setTimeout\(load, RETRY_MS\);/,+ "nothing re-probes after a failed read",+ );+ assert.match(+ src,+ /if \(retry !== undefined\) clearTimeout\(retry\);/,+ "the retry outlives the component that scheduled it",+ );+});++// The subscribe happens in the effect, one tick after the render read `cached`. A probe+// that resolves in that gap notifies the listeners registered at the time, which does not+// include this one, and leaves `cached` set so the fetch is skipped as redundant. Nothing+// is then scheduled to call setInfo. The PR gates whole pages on `loaded`, so the symptom+// is a permanent "Checking this machine..." rather than a stale value.+test("a cache filled between render and subscribe still reaches the component", async () => {+ const { readFile } = await import("node:fs/promises");+ const src = await readFile(+ new URL("../src/hooks/use-hardware-info.ts", import.meta.url),+ "utf8",+ );+ assert.match(+ src,+ /if \(cached\) listener\(cached\);\s*\n\s*else load\(\);/,+ "a component that missed the notify has no path to the cache it skipped loading for",+ );+ // A 200 superseded by a later invalidate must not be reported as a failed probe: load()+ // reads !loaded as failure and drops the page back to its loading state.+ assert.ok(+ !/return cached \?\? DEFAULT;/.test(src),+ "a superseded but successful read still resolves as an unloaded DEFAULT",+ );+});diff --git a/studio/frontend/tests/rag-availability-marker.test.ts b/studio/frontend/tests/rag-availability-marker.test.tsnew file mode 100644index 00000000000..9e661f1ca9a--- /dev/null+++ b/studio/frontend/tests/rag-availability-marker.test.ts@@ -0,0 +1,382 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++// A Mac where sqlite_vec imports but its native vec0 library is missing has a working+// server and a dead RAG engine. routes/rag.py answers that as a contract: the polled KB+// list degrades to 200 with an availability marker, every other endpoint answers 503 with+// the same reason. Both readings used to be dropped by the client, so the user got an+// apparently-working empty Knowledge bases page whose Create button could only 503.++import assert from "node:assert/strict";+import { readFile } from "node:fs/promises";+import test from "node:test";++import { registerBundlerResolver } from "./helpers/kit.ts";++registerBundlerResolver();++const {+ hasRagAvailabilityMarker,+ noteRagAvailability,+ noteRagResponse,+ useRagAvailabilityStore,+} = await import("../src/features/rag/api/rag-availability.ts");++const BACKEND_REASON =+ "RAG is unavailable: the sqlite-vec extension could not be loaded.";++function resetAvailability() {+ useRagAvailabilityStore.setState({+ available: true,+ reason: null,+ answered: false,+ });+}++function readSrc(path: string) {+ return readFile(new URL(`../src/${path}`, import.meta.url), "utf8");+}++/** The body of a top-level function, so an assertion cannot pass on a neighbour's code. */+function functionBody(src: string, name: string): string {+ const start = src.search(new RegExp(`(async )?function\\*?\\s+${name}\\b`));+ assert.ok(start >= 0, `${name} is gone or was renamed`);+ const end = src.indexOf("\n}\n", start);+ assert.ok(end > start, `could not find the end of ${name}`);+ return src.slice(start, end);+}++test("nothing is gated before the backend has answered", () => {+ resetAvailability();+ const state = useRagAvailabilityStore.getState();+ assert.equal(+ state.isUnavailable(),+ false,+ "the dialog would gray itself out on a guess, the mistake this PR already fixed " ++ "for the Train and Video tabs",+ );+ assert.equal(state.availabilityUnknown(), true);+ assert.equal(state.unavailableReason(), null);+});++test("a list marker of false is a measured unavailable, with its reason", () => {+ resetAvailability();+ noteRagAvailability({+ knowledgeBases: [],+ ragAvailable: false,+ ragUnavailableReason: BACKEND_REASON,+ });+ const state = useRagAvailabilityStore.getState();+ assert.equal(state.isUnavailable(), true);+ assert.equal(state.availabilityUnknown(), false);+ assert.equal(+ state.unavailableReason(),+ BACKEND_REASON,+ "the empty state has nothing to show but the generic 'No knowledge bases yet.'",+ );+});++test("a healthy host stays optimistic and reports no reason", () => {+ resetAvailability();+ noteRagAvailability({+ knowledgeBases: [],+ ragAvailable: true,+ ragUnavailableReason: null,+ });+ const state = useRagAvailabilityStore.getState();+ assert.equal(state.isUnavailable(), false);+ assert.equal(state.availabilityUnknown(), false, "an answer did arrive");+ assert.equal(state.unavailableReason(), null);+});++// Backwards compatibility: an older backend, or a different build, sends the list with no+// marker at all. That has to behave exactly as it does today.+test("a list with no marker leaves availability unknown", () => {+ resetAvailability();+ assert.equal(hasRagAvailabilityMarker({ knowledgeBases: [] }), false);+ noteRagAvailability({ knowledgeBases: [] });+ const state = useRagAvailabilityStore.getState();+ assert.equal(+ state.availabilityUnknown(),+ true,+ "a marker was invented for a backend that never sent one",+ );+ assert.equal(state.isUnavailable(), false);+});++test("a marker of true clears a stale unavailable", () => {+ resetAvailability();+ noteRagResponse(503, { detail: BACKEND_REASON });+ assert.equal(useRagAvailabilityStore.getState().isUnavailable(), true);+ noteRagAvailability({ knowledgeBases: [], ragAvailable: true });+ assert.equal(+ useRagAvailabilityStore.getState().isUnavailable(),+ false,+ "nothing can ever undo a 503, so one blip grays the dialog out for the session",+ );+});++// A user who opens the dialog and hits Create before the first list poll lands gets the+// 503 first. Reading it means the UI is coherent immediately instead of at the next poll.+test("a 503 from any endpoint marks unavailable, with the stated reason", () => {+ resetAvailability();+ noteRagResponse(503, { detail: BACKEND_REASON });+ const state = useRagAvailabilityStore.getState();+ assert.equal(state.isUnavailable(), true);+ assert.equal(state.unavailableReason(), BACKEND_REASON);+});++// A bodyless 503 is precisely what a reverse proxy, Cloudflare or a briefly overloaded+// server returns, and it says nothing about sqlite-vec. This test used to assert the+// opposite: that such a response should still be explained with the extension reason.+// That turns any transient outage into a permanent, wrongly-worded verdict for the rest+// of the session, since only a 2xx from a gated endpoint can clear it. Unknown is the+// honest state, and the dialog stays usable until the backend actually says otherwise.+test("a 503 with no readable body is not a capability verdict", () => {+ resetAvailability();+ noteRagResponse(503, null);+ const state = useRagAvailabilityStore.getState();+ assert.equal(state.isUnavailable(), false);+ assert.equal(+ state.availabilityUnknown(),+ true,+ "a gateway 503 was recorded as a measured sqlite-vec failure",+ );+ assert.equal(state.unavailableReason(), null);+});++// 401, 404, 422 and a genuine 500 say nothing about whether the extension loads. Treating+// them as unavailable would gray the dialog out on any transient failure.+test("a non-503 failure does not mark unavailable", () => {+ for (const status of [401, 404, 422, 500]) {+ resetAvailability();+ noteRagResponse(status, { detail: "nope" });+ assert.equal(+ useRagAvailabilityStore.getState().availabilityUnknown(),+ true,+ `a ${status} was read as a verdict on the sqlite-vec extension`,+ );+ }+});++test("a success from a gated endpoint clears a stale unavailable", () => {+ resetAvailability();+ noteRagResponse(503, { detail: BACKEND_REASON });+ noteRagResponse(200, { documents: [] });+ assert.equal(+ useRagAvailabilityStore.getState().isUnavailable(),+ false,+ "every endpoint but the list gates on the extension, so a 2xx is proof it loads",+ );+ resetAvailability();+ noteRagResponse(503, { detail: BACKEND_REASON });+ noteRagResponse(204, null);+ assert.equal(+ useRagAvailabilityStore.getState().isUnavailable(),+ false,+ "the 204 early return skips the availability read",+ );+});++// The KB list is the one endpoint that answers 200 either way, so the blanket "a 2xx means+// available" rule must not fire on it and race the marker back to available.+test("the KB list's own 200 does not overrule its marker", () => {+ resetAvailability();+ const body = {+ knowledgeBases: [],+ ragAvailable: false,+ ragUnavailableReason: BACKEND_REASON,+ };+ noteRagResponse(200, body);+ // Assert BEFORE the marker read, which is the only call that can prove the exemption+ // exists. noteRagAvailability writes available:false unconditionally, so checking only+ // after it passed even with the exemption deleted -- the last writer hid the bug.+ assert.equal(+ useRagAvailabilityStore.getState().availabilityUnknown(),+ true,+ "the list's 200 was read as a verdict, racing its own marker back to available",+ );+ noteRagAvailability(body);+ assert.equal(+ useRagAvailabilityStore.getState().isUnavailable(),+ true,+ "the list's 200 marked RAG available on a host where it cannot run",+ );+});++// Three call sites, because two of them bypass ragRequest.+test("every RAG response path reports availability", async () => {+ const src = await readSrc("features/rag/api/rag-api.ts");+ assert.match(+ src,+ /import \{ noteRagAvailability, noteRagResponse \} from "\.\/rag-availability";/,+ "rag-api does not read the availability contract at all",+ );+ const request = functionBody(src, "ragRequest");+ assert.match(+ request,+ /noteRagResponse\(204, null\)/,+ "the 204 early return leaves before anything is recorded",+ );+ assert.match(+ request,+ /noteRagResponse\(response\.status, json\);\n\s*if \(!response\.ok\)/,+ "the 503 is turned straight into a thrown Error, so nothing records it",+ );+ const upload = functionBody(src, "ragUpload");+ assert.match(+ upload,+ /noteRagResponse\(response\.status, json\)/,+ "ragUpload bypasses ragRequest, so its 503 is still dropped",+ );+ const stream = functionBody(src, "streamJobEvents");+ assert.match(+ stream,+ /noteRagResponse\(response\.status, body\)/,+ "the SSE endpoint bypasses ragRequest too",+ );+});++test("listKnowledgeBases reads the marker before returning the array", async () => {+ const src = await readSrc("features/rag/api/rag-api.ts");+ const list = functionBody(src, "listKnowledgeBases");+ assert.match(+ list,+ /ragAvailable\?: boolean;/,+ "the response type still discards everything but the array",+ );+ assert.match(+ list,+ /noteRagAvailability\(data\);\n\s*return data\.knowledgeBases/,+ "the marker is read after the return, or not at all",+ );+});++test("the dialog stops offering a Create button that can only 503", async () => {+ const src = await readSrc("features/rag/components/knowledge-base-dialog.tsx");+ assert.match(+ src,+ /const ragUnavailable = useRagAvailabilityStore\(\(s\) => s\.isUnavailable\(\)\);/,+ "the dialog reads the raw flag rather than the measured gate, or nothing at all",+ );+ assert.match(+ src,+ /New knowledge base/,+ "the create entry point moved; this test no longer guards it",+ );+ assert.match(+ src,+ /disabled=\{ragUnavailable\}\n\s*title=\{ragUnavailableHint\}/,+ "'New knowledge base' is still enabled on a host where it can only 503",+ );+ assert.match(+ src,+ /const ragUnavailableHint = ragUnavailable\n\s*\? \(ragUnavailableReason \?\? undefined\)\n\s*: undefined;/,+ "the hover hint is not derived from the measured verdict",+ );+ assert.match(+ src,+ /disabled=\{saving \|\| ragUnavailable\}/,+ "Create/Save is still enabled",+ );+ const submit = functionBody(src, "submitForm");+ assert.match(+ submit,+ /if \(ragUnavailable\) \{/,+ "submitForm is reachable by keyboard with the button disabled",+ );+ assert.match(+ src,+ /\) : ragUnavailable \? \(/,+ "the empty state does not branch on availability",+ );+ assert.match(+ src,+ /\{ragUnavailableReason \?\? "Knowledge bases are unavailable\."\}/,+ "a machine where RAG cannot run still reads 'No knowledge bases yet.'",+ );+});++// The queued-prompt gate polls listThreadDocuments and answers "still indexing" whenever+// it throws, and dispatchQueuedPrompt reschedules on that answer with no cap. On a broken+// RAG host the probe can never succeed, so a queued prompt on a thread using documents+// was never dispatched at all.+test("a queued prompt is not held forever by a probe that can never succeed", async () => {+ const src = await readSrc("components/assistant-ui/thread.tsx");+ assert.match(+ src,+ /import \{ useRagAvailabilityStore \} from "@\/features\/rag\/api\/rag-availability";/,+ "thread.tsx cannot tell a 503 apart from a transient failure",+ );+ const gate = functionBody(src, "targetHasIndexingDocuments");+ const cat = gate.slice(gate.indexOf("} catch {"));+ assert.ok(cat.length > 0, "the probe no longer has a catch to fix");+ assert.ok(+ !/\breturn true;/.test(cat),+ "a failed probe still reports 'still indexing' unconditionally, so the retry " ++ "in dispatchQueuedPrompt never ends",+ );+ assert.match(+ cat,+ /return !useRagAvailabilityStore\.getState\(\)\.isUnavailable\(\);/,+ "the catch does not break out on a measured unavailable",+ );+ // Only a measured unavailable breaks out. A transient failure must still hold the+ // prompt back rather than sending it without the documents it was waiting for.+ resetAvailability();+ assert.equal(+ !useRagAvailabilityStore.getState().isUnavailable(),+ true,+ "an unknown verdict would hold the prompt as it does today",+ );+});++// useRagToolDisabled is a model-capability gate and is deliberately false when no model is+// loaded. Folding host availability into it would conflate two different questions.+test("host availability is kept out of the model-capability gate", async () => {+ const src = await readSrc("features/chat/hooks/use-rag-tool-disabled.ts");+ assert.ok(+ !src.includes("rag-availability"),+ "the sqlite-vec verdict was folded into the tool-capability hook",+ );+});++// A 503 is not automatically a capability verdict. Cloudflare, a reverse proxy and a+// briefly overloaded server all return one, and their bodies say nothing about+// sqlite-vec. Recording those would gate the dialog for the session behind a transient+// outage and show an extension explanation for something that was never the extension.+test("a generic 503 from a proxy is not read as a RAG capability verdict", () => {+ useRagAvailabilityStore.setState({ available: true, reason: null, answered: false });++ for (const body of [+ { detail: "Service Temporarily Unavailable" },+ { detail: "upstream connect error" },+ null,+ {},+ "<html><body><h1>503 Service Unavailable</h1></body></html>",+ // Anything RAG-aware in front of the backend can say this without meaning the+ // extension, so the phrase alone must not persist a capability verdict. Only the+ // package name does, since nothing upstream emits it by accident.+ { detail: "RAG is unavailable right now, try again shortly" },+ { detail: "RAG unavailable: upstream timeout" },+ ]) {+ noteRagResponse(503, body);+ assert.equal(+ useRagAvailabilityStore.getState().isUnavailable(),+ false,+ `a 503 carrying ${JSON.stringify(body)} was treated as a sqlite-vec verdict`,+ );+ assert.equal(+ useRagAvailabilityStore.getState().answered,+ false,+ "a generic 503 must leave the verdict unanswered, not answer it optimistically",+ );+ }+});++test("the backend's own 503 detail is still read as unavailable", () => {+ useRagAvailabilityStore.setState({ available: true, reason: null, answered: false });+ noteRagResponse(503, { detail: BACKEND_REASON });+ assert.equal(useRagAvailabilityStore.getState().isUnavailable(), true);+ assert.equal(useRagAvailabilityStore.getState().reason, BACKEND_REASON);+});diff --git a/studio/frontend/tests/sidebar-nav-backend-parity.test.ts b/studio/frontend/tests/sidebar-nav-backend-parity.test.tsindex 9b0e431b451..54abfc462b3 100644--- a/studio/frontend/tests/sidebar-nav-backend-parity.test.ts+++ b/studio/frontend/tests/sidebar-nav-backend-parity.test.ts@@ -24,3 +24,51 @@ test("the backend sidebar nav defaults match the frontend", async () => {// Order matters too: the backend appends its missing ids in this order.assert.deepEqual(backend, DEFAULT_CUSTOMIZATION.sidebarNav);});++// The two capability-gated rows. They are the ones that can render disabled without the user+// having done anything, so they are also the ones a rename would silently un-gate: navRows is+// keyed by SidebarNavItemId, so a dropped `pending` there just stops spinning, it does not+// fail to compile.+test("Train and Video are still the capability-gated rows", async () => {+ const source = await readFile(+ new URL("../src/components/app-sidebar.tsx", import.meta.url),+ "utf8",+ );+ const rows = /const navRows: Record<SidebarNavItemId, NavRowDef> = \{([\s\S]*?)\n \};/.exec(+ source,+ );+ assert.ok(rows, "could not find navRows in app-sidebar.tsx");+ // Split on the top-level row keys so each row's body can be checked on its own.+ const bodies = new Map<string, string>();+ const keys = [...rows[1].matchAll(/^ ([a-z]+): \{$/gm)];+ keys.forEach((key, i) => {+ const start = key.index + key[0].length;+ const end = i + 1 < keys.length ? keys[i + 1].index : rows[1].length;+ bodies.set(key[1], rows[1].slice(start, end));+ });+ // Every id the backend knows about has a row, or the personalization round-trip renders a gap.+ const backend = await readFile(+ new URL("../../backend/routes/settings.py", import.meta.url),+ "utf8",+ );+ const block = /SIDEBAR_NAV_ITEM_DEFAULTS = \{([\s\S]*?)^\}/m.exec(backend);+ assert.ok(block, "could not find SIDEBAR_NAV_ITEM_DEFAULTS in settings.py");+ for (const [, id] of block[1].matchAll(/"([a-z]+)":/g)) {+ assert.ok(bodies.has(id), `the backend ships a "${id}" row the sidebar does not define`);+ }++ for (const id of ["train", "video"]) {+ const body = bodies.get(id);+ assert.ok(body, `no ${id} row`);+ assert.match(+ body,+ /pending: capabilitiesUnknown,/,+ `the ${id} row renders its disabled state before the verdict is measured`,+ );+ assert.match(+ body,+ /disabled: chatOnlyMeasured,/,+ `the ${id} row disables on the browser-platform guess`,+ );+ }+});diff --git a/studio/frontend/tests/sidebar-spinner-column.test.ts b/studio/frontend/tests/sidebar-spinner-column.test.tsindex c1b6a749ea3..61d7a6b2a7a 100644--- a/studio/frontend/tests/sidebar-spinner-column.test.ts+++ b/studio/frontend/tests/sidebar-spinner-column.test.ts@@ -98,3 +98,57 @@ test("a working Recents row clears the kebab on hover", async () => {assert.ok(pad >= kebabInset, `${pad}px focus padding, needs ${kebabInset}px`);}});++// That same column now carries a second meaning: a row whose capability has not been measured+// yet. On a Mac the platform store seeds chatOnly from the user agent, so Train and Video used+// to paint disabled (opacity-50, inert) from first load and only recover once /api/health+// answered -- indistinguishable from a measured "your machine cannot do this".+test("a pending row spins instead of blacking out", async () => {+ const { resolveNavRowState } = await import("../src/components/nav-row-state.ts");++ const pending = resolveNavRowState({+ disabled: true,+ tooltip: "Training needs an NVIDIA or AMD GPU.",+ pending: true,+ });+ assert.equal(pending.disabled, false, "the guessed gray-out still renders");+ assert.equal(pending.spinner, true, "nothing tells the user the check is still running");+ assert.equal(+ pending.tooltip,+ undefined,+ "a reason for a verdict nobody has reached yet is shown on hover",+ );+});++test("a measured row is left exactly as it was", async () => {+ const { resolveNavRowState } = await import("../src/components/nav-row-state.ts");++ const measured = resolveNavRowState({+ disabled: true,+ tooltip: "Training needs MLX. Run `unsloth studio update` to enable Train.",+ spinner: false,+ });+ assert.equal(measured.disabled, true, "a real chat-only host was let into Train");+ assert.equal(measured.tooltip, "Training needs MLX. Run `unsloth studio update` to enable Train.");+ assert.equal(measured.spinner, false);++ // The pre-existing use of the column (a run in progress) is untouched.+ const working = resolveNavRowState({ spinner: true });+ assert.equal(working.spinner, true);+ assert.equal(working.disabled, undefined);+});++// Two render sites take these props: the inline rows and the More flyout. A row moved into+// More by Settings -> Appearance must not go back to rendering the guess.+test("both nav render sites resolve pending the same way", async () => {+ const source = await readFile(+ new URL("../src/components/app-sidebar.tsx", import.meta.url),+ "utf8",+ );+ const resolves = source.match(/const rowState = resolveNavRowState\(row\);/g) ?? [];+ assert.equal(resolves.length, 2, `expected both render sites to resolve, got ${resolves.length}`);+ // And neither passes the raw fields past it.+ for (const raw of ["disabled={row.disabled}", "tooltip={row.tooltip}", "spinner={row.spinner}"]) {+ assert.ok(!source.includes(raw), `a render site still passes ${raw} unresolved`);+ }+});diff --git a/studio/frontend/tests/verdict-poll-stall-guard.test.ts b/studio/frontend/tests/verdict-poll-stall-guard.test.tsnew file mode 100644index 00000000000..31838d4d127--- /dev/null+++ b/studio/frontend/tests/verdict-poll-stall-guard.test.ts@@ -0,0 +1,189 @@+// 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 recovery poll's no-stacking guard in app-sidebar.tsx, run rather than pattern-matched.+// The effect lives in a .tsx that pulls in the whole shell, so lift the interval out of the+// source and drive it with a fake clock, a fake setInterval and reads the test settles by hand.+//+// The race: a /api/health read that outlives the stall window is given up on and the next tick+// starts a replacement, which takes the guard over. The abandoned read still settles eventually,+// and its `finally` used to zero the shared marker while the replacement was in flight, so every+// following tick saw a free guard and fired another forced read. On the backend this exists for,+// one still importing torch, that is a read every three seconds piled onto the process the poll+// is waiting for.++import assert from "node:assert/strict";+import { readFile } from "node:fs/promises";+import test from "node:test";++const src = await readFile(+ new URL("../src/components/app-sidebar.tsx", import.meta.url),+ "utf8",+);++// The interval, verbatim, from the marker it opens with to the cleanup it returns.+const START = "let pollingSince = 0;";+const END = "return () => window.clearInterval(id);";+const from = src.indexOf(START);+const to = src.indexOf(END, from);+assert.ok(from > 0 && to > from, "the recovery poll's interval moved out of app-sidebar.tsx");+const body = src.slice(from, to + END.length);+assert.ok(+ body.includes("void fetchDeviceType({ force: true })"),+ "the lifted block is not the one that re-reads the verdict",+);++function constant(name: string): number {+ const found = new RegExp(`const ${name} = (\\d+);`).exec(src);+ assert.ok(found, `${name} is no longer declared in app-sidebar.tsx`);+ return Number(found[1]);+}+const STALL_MS = constant("VERDICT_POLL_STALL_MS");+const POLL_MS = constant("VERDICT_UNKNOWN_POLL_MS");++const startPoll = new Function(+ "window",+ "Date",+ "fetchDeviceType",+ "capabilitiesUnknown",+ "VERDICT_POLL_STALL_MS",+ "VERDICT_UNKNOWN_POLL_MS",+ "SELF_HEAL_POLL_MS",+ body,+) as (+ window: { setInterval: (fn: () => void, ms: number) => number; clearInterval: (id: number) => void },+ date: { now: () => number },+ fetchDeviceType: () => Promise<void>,+ capabilitiesUnknown: boolean,+ stallMs: number,+ unknownPollMs: number,+ selfHealPollMs: number,+) => () => void;++/** The interval, wired to a clock and a queue of reads the test settles when it chooses. */+function harness() {+ let clock = 1_700_000_000_000; // any non-zero start: the guard reads its marker as truthy+ let tick: (() => void) | undefined;+ let cadence = 0;+ const pending: Array<{ resolve: () => void; reject: () => void }> = [];+ let cleared = 0;++ const stop = startPoll(+ {+ setInterval: (fn, ms) => {+ tick = fn;+ cadence = ms;+ return 1;+ },+ clearInterval: () => {+ cleared += 1;+ },+ },+ { now: () => clock },+ () =>+ new Promise<void>((resolve, reject) => {+ pending.push({ resolve: () => resolve(), reject: () => reject(new Error("offline")) });+ }),+ true,+ STALL_MS,+ POLL_MS,+ // The self-heal cadence is the other branch; this scenario is the unknown verdict.+ 15000,+ );++ assert.ok(tick, "the poll never scheduled an interval");+ return {+ cadence,+ reads: () => pending.length,+ advance: (ms: number) => {+ clock += ms;+ },+ tick: () => tick?.(),+ // Node runs the promise callbacks the interval attached before the next macrotask.+ settle: async (index: number, how: "resolve" | "reject" = "resolve") => {+ pending[index][how]();+ await new Promise((r) => setImmediate(r));+ },+ stop,+ cleared: () => cleared,+ };+}++test("a read that is still outstanding holds the poll off", async () => {+ const poll = harness();+ assert.equal(poll.cadence, POLL_MS, "an unknown verdict polls at the wrong cadence");+ poll.tick();+ assert.equal(poll.reads(), 1);+ poll.advance(POLL_MS);+ poll.tick();+ assert.equal(poll.reads(), 1, "a second read was stacked on the first");+ poll.stop();+});++test("a read that settles hands the guard back", async () => {+ const poll = harness();+ poll.tick();+ await poll.settle(0);+ poll.advance(POLL_MS);+ poll.tick();+ assert.equal(poll.reads(), 2, "the guard latched the poll off after a completed read");+ poll.stop();+});++test("a stalled read cannot clear the guard its replacement now owns", async () => {+ const poll = harness();+ poll.tick();+ assert.equal(poll.reads(), 1);++ // The first read outlives the stall window, so the poll gives up on it and replaces it.+ poll.advance(STALL_MS + POLL_MS);+ poll.tick();+ assert.equal(poll.reads(), 2, "the stall window did not release the guard");++ // The abandoned read finally answers, long after ownership moved on.+ await poll.settle(0);++ poll.advance(POLL_MS);+ poll.tick();+ assert.equal(+ poll.reads(),+ 2,+ "the abandoned read cleared a guard it no longer held, so the poll stacked another " ++ "forced /api/health onto the backend it is waiting for",+ );+ // And it keeps holding: the replacement is still in flight, tick after tick.+ poll.advance(POLL_MS);+ poll.tick();+ poll.advance(POLL_MS);+ poll.tick();+ assert.equal(poll.reads(), 2, "the guard leaked one tick later instead");++ // The replacement still releases it normally when it answers.+ await poll.settle(1);+ poll.advance(POLL_MS);+ poll.tick();+ assert.equal(poll.reads(), 3, "the owning read never handed the guard back");+ poll.stop();+});++test("a stalled read that fails cannot clear it either", async () => {+ const poll = harness();+ poll.tick();+ poll.advance(STALL_MS + POLL_MS);+ poll.tick();+ await poll.settle(0, "reject");+ poll.advance(POLL_MS);+ poll.tick();+ assert.equal(+ poll.reads(),+ 2,+ "a rejected read takes the same finally, so it frees the live guard too",+ );+ poll.stop();+});++test("the interval is torn down with the effect", () => {+ const poll = harness();+ poll.stop();+ assert.equal(poll.cleared(), 1, "the poll outlives the component that started it");+});diff --git a/studio/src-tauri/src/commands.rs b/studio/src-tauri/src/commands.rsindex 2ab6cd2e03d..4f575b0c0e4 100644--- a/studio/src-tauri/src/commands.rs+++ b/studio/src-tauri/src/commands.rs@@ -9,11 +9,39 @@ use tauri::{AppHandle, Emitter};const BACKEND_STARTUP_GRACE_PERIOD: Duration = Duration::from_secs(5 * 60);const HEALTH_WATCHDOG_INTERVAL: Duration = Duration::from_secs(15);const HEALTH_WATCHDOG_MAX_FAILURES: u32 = 3;+/// Per-probe HTTP budget for the launcher's liveness probe.+///+/// Generous on purpose. The backend imports torch and transformers on a background warm+/// thread, and those C-extension imports hold the GIL, so the event loop can go silent for+/// seconds at a time on a cold start (3735ms measured on a Mac, with the process quiet for+/// ~27s around it). A 2s budget turns that into a probe timeout, and three of those in a row+/// kill a backend that is merely busy. Kept below HEALTH_WATCHDOG_INTERVAL so a slow probe+/// cannot overlap the next one.+///+/// This is not the preflight budget: `preflight::backend::probe_ownerless_spawned_backend`+/// deliberately keeps its own 2s, because a preflight timeout dead-ends the launch rather+/// than retrying, and `backend/tests/test_health_answers_within_probe_budget.py` derives+/// `_HEALTH_DETECT_BUDGET_S` from that number.+const HEALTH_PROBE_TIMEOUT: Duration = Duration::from_secs(10);fn should_count_watchdog_failure(has_seen_healthy: bool, elapsed_since_start: Duration) -> bool {has_seen_healthy || elapsed_since_start >= BACKEND_STARTUP_GRACE_PERIOD}+/// Whether the startup grace has ended, given what the latest probe reported.+///+/// A backend that answers while still warming clears the latch instead of leaving it: an+/// adopted backend starts latched (it was serving before this app attached), so a watchdog+/// that only declined to *set* it would keep counting failures against a host that has just+/// said it is still importing the ML stack. A probe that got no answer leaves the latch+/// alone, since silence says nothing about whether startup finished.+fn watchdog_seen_healthy_after(previous: bool, alive: bool, warming_up: bool) -> bool {+ if !alive {+ return previous;+ }+ !warming_up+}+async fn managed_install_ready_after_repair() -> bool {crate::preflight::managed_install_ready().await}@@ -251,12 +279,22 @@ pub async fn stop_server(.map_err(|e| format!("stop backend task failed: {e}"))?}-/// Check if a healthy Unsloth backend is running on the given port.-/// Expects JSON response with status=="healthy" AND service=="Unsloth UI Backend".+/// What one launcher probe learned about the backend process.+#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]+struct BackendLiveness {+ /// The port answered with an Unsloth backend reply.+ alive: bool,+ /// The backend answered but has not finished its background warm, so the ML-stack+ /// imports on its warm thread are still in flight. Alive, but not yet done starting.+ warming_up: bool,+}++/// Check if an Unsloth backend is running on the given port.+/// Expects JSON with status=="alive" (or "healthy") AND service=="Unsloth UI Backend".#[tauri::command]pub async fn check_health(port: u16) -> Result<bool, String> {match check_health_inner(port).await {- Ok(healthy) => Ok(healthy),+ Ok(liveness) => Ok(liveness.alive),Err(e) => {// Network errors are not command errors — just means not healthyinfo!("Health check on port {} failed: {}", port, e);@@ -265,24 +303,77 @@ pub async fn check_health(port: u16) -> Result<bool, String> {}}-async fn check_health_inner(port: u16) -> Result<bool, reqwest::Error> {- let url = format!("http://127.0.0.1:{}/api/health", port);- let client = crate::loopback_http::client(std::time::Duration::from_secs(2))?;- let resp = client.get(&url).send().await?;- let json: serde_json::Value = resp.json().await?;+/// Probe the backend for process liveness.+///+/// `/api/liveness` rather than `/api/health`: health awaits hardware detection through+/// `_await_hardware_detection`, so it deliberately bills the probe for work that says+/// nothing about whether the process is alive. Liveness reads module-level caches only,+/// which is the reason it was added. Backends older than that route answer 404, so fall+/// back to health for them, the same order `process::generic_backend_health_ok` and+/// `desktop_backend_owner::fetch_liveness` already use.+async fn check_health_inner(port: u16) -> Result<BackendLiveness, reqwest::Error> {+ let client = crate::loopback_http::client(HEALTH_PROBE_TIMEOUT)?;+ let mut json = None;+ for path in ["/api/liveness", "/api/health"] {+ let resp = client+ .get(format!("http://127.0.0.1:{}{}", port, path))+ .send()+ .await?;+ if resp.status() == reqwest::StatusCode::NOT_FOUND && path == "/api/liveness" {+ continue;+ }+ if !resp.status().is_success() {+ return Ok(BackendLiveness::default());+ }+ json = Some(resp.json::<serde_json::Value>().await?);+ break;+ }+ let Some(json) = json else {+ return Ok(BackendLiveness::default());+ };- let healthy = json+ // Liveness answers "alive" and health answers "healthy". Accept either, so the fallback+ // above and a downgraded backend both still validate.+ let live = json.get("status").and_then(|v| v.as_str())- .map(|s| s == "healthy")+ .map(|s| s == "alive" || s == "healthy").unwrap_or(false);let correct_service = json.get("service").and_then(|v| v.as_str()).map(|s| s == "Unsloth UI Backend").unwrap_or(false);+ // Both routes carry `torch_warm_in_progress` while the backend's coordinated warm thread+ // is running, and drop it the moment that thread is done or was never started. That is+ // the whole warm, not just its first stage: hardware detection settles early and the+ // transformers, datasets and unsloth_zoo imports that follow hold the GIL just as hard,+ // so this is the field that says "startup is still in flight".+ let warming = json+ .get("torch_warm_in_progress")+ .and_then(|v| v.as_bool())+ .unwrap_or(false);+ // `hardware_detecting` is the older, narrower signal, kept as a fallback for backends+ // that predate the field above; on those it is the only warm-up marker there is. It also+ // means "this hardware verdict is provisional", which is why a deferred warm sets+ // `hardware_detection_deferred` alongside it: nothing will ever settle the verdict then,+ // and counting that as warming up would hold the startup grace open until it expired.+ // A backend too old to send any of these reads as settled, which is what this launcher+ // assumed before, so a downgrade loses the extra grace and nothing else.+ let detecting = json+ .get("hardware_detecting")+ .and_then(|v| v.as_bool())+ .unwrap_or(false);+ let deferred = json+ .get("hardware_detection_deferred")+ .and_then(|v| v.as_bool())+ .unwrap_or(false);- Ok(healthy && correct_service)+ let alive = live && correct_service;+ Ok(BackendLiveness {+ alive,+ warming_up: alive && (warming || (detecting && !deferred)),+ })}async fn check_watchdog_health(@@ -290,9 +381,9 @@ async fn check_watchdog_health(generation: u64,port: u16,has_adopted: bool,-) -> bool {+) -> BackendLiveness {if !has_adopted {- return check_health_inner(port).await.unwrap_or(false);+ return check_health_inner(port).await.unwrap_or_default();}let snapshot = match process::owned_backend_snapshot(state) {@@ -303,15 +394,44 @@ async fn check_watchdog_health({snapshot}- _ => return false,+ _ => return BackendLiveness::default(),};let Some(owner) = snapshot.owner else {- return false;+ return BackendLiveness::default();};- matches!(- crate::desktop_backend_owner::probe_owned_backend_state(owner, Some(port), false).await,+ // HEALTH_PROBE_TIMEOUT, not the ownership path's default 2s. Every request inside the+ // probe would otherwise time out during the very GIL stall this watchdog is supposed to+ // ride out, so the backend came back unverified and the warm-up read below -- which is+ // gated on that verification -- never ran at all.+ let verified = matches!(+ crate::desktop_backend_owner::probe_owned_backend_state_with_timeout(+ owner,+ Some(port),+ false,+ HEALTH_PROBE_TIMEOUT,+ )+ .await,crate::desktop_backend_owner::OwnedBackendProbe::Verified(_)- )+ );+ // The ownership probe answers "is this still our process", not "is startup over", so+ // ask the backend itself as well. An adopted backend having served one request before+ // this app attached is the same fallacy the owned path fixes below: a force-quit during+ // a cold start leaves the backend running and still importing the ML stack, and the app+ // relaunches straight onto it. Without a warm-up signal that host is declared dead three+ // probes later while it is perfectly healthy.+ //+ // Only consulted when ownership verified, so a foreign process on the port cannot hold+ // the grace open. A failed read reports not-warming, which is the conservative answer:+ // it lets the failure count rather than extending the grace on a backend we cannot read.+ let warming_up = if verified {+ check_health_inner(port).await.unwrap_or_default().warming_up+ } else {+ false+ };+ BackendLiveness {+ alive: verified,+ warming_up,+ }}/// Return buffered server logs.@@ -656,6 +776,7 @@ pub async fn start_managed_repair(#[cfg(test)]mod tests {use std::fs;+ use std::sync::{Arc, Mutex};use std::time::{Duration, SystemTime, UNIX_EPOCH};use tokio::io::{AsyncReadExt, AsyncWriteExt};use tokio::net::TcpListener;@@ -770,6 +891,302 @@ mod tests {assert!(err.contains("Stop that server"));}+ /// Stub backend for the launcher probe. `liveness` of `None` models a backend older+ /// than the route, which answers 404 there. Returns the port and the paths it was asked+ /// for, so a test can assert which route the probe actually used.+ async fn probe_test_backend(+ liveness: Option<String>,+ health: String,+ ) -> (u16, Arc<Mutex<Vec<String>>>) {+ let listener = TcpListener::bind(("127.0.0.1", 0))+ .await+ .expect("probe test needs a loopback port");+ let port = listener.local_addr().unwrap().port();+ let paths = Arc::new(Mutex::new(Vec::new()));+ let recorded = Arc::clone(&paths);+ tokio::spawn(async move {+ loop {+ let Ok((mut stream, _)) = listener.accept().await else {+ return;+ };+ let mut buffer = [0; 2048];+ let Ok(n) = stream.read(&mut buffer).await else {+ return;+ };+ let request = String::from_utf8_lossy(&buffer[..n]);+ let path = request+ .split_whitespace()+ .nth(1)+ .unwrap_or_default()+ .to_string();+ recorded.lock().unwrap().push(path.clone());+ let (status, body) = match path.as_str() {+ "/api/liveness" => match liveness.as_deref() {+ Some(body) => ("200 OK", body),+ None => ("404 Not Found", ""),+ },+ "/api/health" => ("200 OK", health.as_str()),+ _ => ("404 Not Found", ""),+ };+ let response = format!(+ "HTTP/1.1 {status}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",+ body.len()+ );+ let _ = stream.write_all(response.as_bytes()).await;+ }+ });+ (port, paths)+ }++ #[tokio::test]+ async fn liveness_is_probed_instead_of_the_detection_gated_health_route() {+ // /api/health awaits hardware detection on purpose, so probing it bills the+ // watchdog for a torch import. Liveness must be the only route touched.+ let (port, paths) = probe_test_backend(+ Some(r#"{"status":"alive","service":"Unsloth UI Backend"}"#.to_string()),+ ready_health(false),+ )+ .await;++ let liveness = super::check_health_inner(port).await.unwrap();++ assert!(liveness.alive);+ assert!(!liveness.warming_up);+ assert_eq!(paths.lock().unwrap().as_slice(), ["/api/liveness"]);+ }++ #[tokio::test]+ async fn a_backend_without_the_liveness_route_still_validates_through_health() {+ // The desktop app talks to backends of varying versions; a downgrade answers+ // "healthy" from /api/health and 404s liveness.+ let (port, paths) = probe_test_backend(None, ready_health(false)).await;++ let liveness = super::check_health_inner(port).await.unwrap();++ assert!(liveness.alive);+ assert_eq!(+ paths.lock().unwrap().as_slice(),+ ["/api/liveness", "/api/health"]+ );+ }++ #[tokio::test]+ async fn a_warming_backend_is_alive_but_not_finished_starting() {+ let (port, _) = probe_test_backend(+ Some(+ r#"{"status":"alive","service":"Unsloth UI Backend","hardware_detecting":true}"#+ .to_string(),+ ),+ ready_health(false),+ )+ .await;++ let liveness = super::check_health_inner(port).await.unwrap();++ assert!(liveness.alive);+ assert!(+ liveness.warming_up,+ "an unsettled hardware verdict means the torch import is still in flight"+ );+ }++ #[tokio::test]+ async fn a_late_warm_stage_still_counts_as_warming_up() {+ // The regression: hardware detection is the warm's first stage, so its marker is+ // gone while transformers, datasets and unsloth_zoo are still importing. Ending the+ // startup grace here puts a GIL stall from those imports straight back into the+ // three-strikes count that killed a healthy backend.+ let (port, _) = probe_test_backend(+ Some(+ r#"{"status":"alive","service":"Unsloth UI Backend","torch_warm_in_progress":true}"#+ .to_string(),+ ),+ ready_health(false),+ )+ .await;++ let liveness = super::check_health_inner(port).await.unwrap();++ assert!(liveness.alive);+ assert!(+ liveness.warming_up,+ "a settled hardware verdict does not mean the warm is over; the imports that \+ hold the GIL longest run after it"+ );+ }++ #[tokio::test]+ async fn a_finished_warm_ends_the_startup_grace() {+ // The other half: the field has to disappear, or the grace never ends on its own+ // and a genuinely hung backend waits out the full five minutes.+ let (port, _) = probe_test_backend(+ Some(+ r#"{"status":"alive","service":"Unsloth UI Backend","torch_warm_in_progress":false}"#+ .to_string(),+ ),+ ready_health(false),+ )+ .await;++ let liveness = super::check_health_inner(port).await.unwrap();++ assert!(liveness.alive);+ assert!(!liveness.warming_up);+ }++ #[tokio::test]+ async fn a_backend_predating_the_warm_field_still_gets_its_grace() {+ // Backwards compatibility: a downgraded backend sends only hardware_detecting, and+ // it is the only warm-up signal that backend has.+ let (port, _) = probe_test_backend(+ Some(+ r#"{"status":"alive","service":"Unsloth UI Backend","hardware_detecting":true}"#+ .to_string(),+ ),+ ready_health(false),+ )+ .await;++ let liveness = super::check_health_inner(port).await.unwrap();++ assert!(liveness.warming_up);+ }++ #[tokio::test]+ async fn a_deferred_warm_is_not_reported_as_still_warming_up() {+ // With the warm switched off nothing will ever settle the verdict, so treating it+ // as warming up would hold the startup grace open until it expires on its own.+ let (port, _) = probe_test_backend(+ Some(+ r#"{"status":"alive","service":"Unsloth UI Backend","hardware_detecting":true,"hardware_detection_deferred":true}"#+ .to_string(),+ ),+ ready_health(false),+ )+ .await;++ let liveness = super::check_health_inner(port).await.unwrap();++ assert!(liveness.alive);+ assert!(!liveness.warming_up);+ }++ #[tokio::test]+ async fn a_foreign_service_on_the_port_is_not_alive() {+ let (port, _) = probe_test_backend(+ Some(r#"{"status":"alive","service":"Some Other App"}"#.to_string()),+ ready_health(false),+ )+ .await;++ assert_eq!(+ super::check_health_inner(port).await.unwrap(),+ super::BackendLiveness::default()+ );+ }++ #[test]+ fn the_probe_budget_fits_inside_one_watchdog_interval() {+ // A probe that outlives the interval would let the next tick start on top of it.+ assert!(super::HEALTH_PROBE_TIMEOUT < super::HEALTH_WATCHDOG_INTERVAL);+ }++ #[test]+ fn the_startup_grace_survives_the_mac_cold_start_timeline() {+ // Replays the macOS report this grace period exists for. The warm thread held the+ // GIL through `import torch`, three probes in a row timed out inside the first+ // minute, and the watchdog SIGTERMed a backend that was starting normally.+ for (label, elapsed) in [+ ("no validated port yet", Duration::from_secs(15)),+ ("probe timeout 1/3", Duration::from_secs(30)),+ ("probe timeout 2/3", Duration::from_secs(47)),+ ("probe timeout 3/3", Duration::from_secs(64)),+ ] {+ assert!(+ !super::should_count_watchdog_failure(false, elapsed),+ "{label} at {}s was counted against a backend still inside the {}s startup grace",+ elapsed.as_secs(),+ super::BACKEND_STARTUP_GRACE_PERIOD.as_secs()+ );+ }+ assert!(!super::should_count_watchdog_failure(+ false,+ super::BACKEND_STARTUP_GRACE_PERIOD - Duration::from_millis(1)+ ));+ assert!(super::should_count_watchdog_failure(+ false,+ super::BACKEND_STARTUP_GRACE_PERIOD+ ));+ }++ #[test]+ fn the_adopted_ownership_probe_uses_the_watchdog_budget() {+ // The warm-up read for an adopted backend is gated on ownership verifying, and that+ // probe defaults to a 2s per-request budget. At 2s every request inside it times out+ // during the very GIL stall the watchdog exists to ride out, so the backend reads as+ // unverified, the warm-up read never runs, and the grace never reopens. Binding the+ // call to HEALTH_PROBE_TIMEOUT here keeps the two from drifting apart again.+ // Normalise line endings first. include_str! embeds the file exactly as checked+ // out, and on Windows that is CRLF, so a bare "\n}\n" never matches and this+ // panicked on the Tauri CI runner while passing everywhere else.+ let src = include_str!("commands.rs").replace("\r\n", "\n");+ let start = src+ .find("async fn check_watchdog_health")+ .expect("check_watchdog_health moved; update this guard");+ let body = &src[start..];+ let body = &body[..body.find("\n}\n").expect("could not find the function end")];+ assert!(+ body.contains("probe_owned_backend_state_with_timeout"),+ "the adopted path is back on the default-timeout ownership probe"+ );+ assert!(+ body.contains("HEALTH_PROBE_TIMEOUT"),+ "the adopted ownership probe no longer uses the watchdog's probe budget"+ );+ }++ #[test]+ fn an_adopted_backend_that_is_still_warming_gets_the_grace_back() {+ // The other half of the reported crash. A force-quit during a cold start leaves the+ // backend running and still importing the ML stack, and the relaunched app adopts it+ // rather than spawning a new one. Adopted watchdogs start latched, so before this the+ // grace never applied: three GIL-stalled probes cleared the backend at ~45s and put a+ // "server stopped unexpectedly" screen in front of a host that was starting normally.+ let mut has_seen_healthy = true; // adopted: count_failures_immediately+ has_seen_healthy = super::watchdog_seen_healthy_after(has_seen_healthy, true, true);+ assert!(+ !has_seen_healthy,+ "a backend that answered \"still warming\" left the latch set, so the grace stayed off"+ );+ for elapsed in [15, 30, 47, 64] {+ assert!(+ !super::should_count_watchdog_failure(+ has_seen_healthy,+ Duration::from_secs(elapsed)+ ),+ "a stalled probe at {elapsed}s was counted against an adopted backend that had \+ just reported it was still warming"+ );+ }+ // The grace is still bounded: a backend that never finishes warming is not immortal.+ assert!(super::should_count_watchdog_failure(+ has_seen_healthy,+ super::BACKEND_STARTUP_GRACE_PERIOD+ ));+ }++ #[test]+ fn the_latch_tracks_the_last_answer_and_ignores_silence() {+ // alive + done warming latches; alive + warming clears; no answer changes nothing,+ // because a probe that timed out says nothing about whether startup finished.+ assert!(super::watchdog_seen_healthy_after(false, true, false));+ assert!(!super::watchdog_seen_healthy_after(true, true, true));+ assert!(super::watchdog_seen_healthy_after(true, false, false));+ assert!(!super::watchdog_seen_healthy_after(false, false, false));+ // A warm that finishes after a stall re-latches, so the grace does not linger.+ assert!(super::watchdog_seen_healthy_after(false, true, false));+ }+#[test]fn watchdog_failure_policy_counts_only_after_health_or_grace_period() {for (has_seen_healthy, elapsed, expected) in [@@ -791,9 +1208,9 @@ mod tests {/// Periodic health check that detects deadlocked or hung backends./// During startup, failures are ignored for a generous grace period so a slow-/// but legitimate backend boot is not killed. After the backend has answered at-/// least once, or after the startup grace expires, 3 consecutive failed checks-/// emit `server-crashed` so the frontend can offer a restart.+/// but legitimate backend boot is not killed. After the backend has answered a probe+/// that says its warm-up is finished, or after the startup grace expires, 3 consecutive+/// failed checks emit `server-crashed` so the frontend can offer a restart.async fn health_watchdog(app: AppHandle,state: BackendState,@@ -883,8 +1300,21 @@ async fn health_watchdog(continue;};- if check_watchdog_health(&state, generation, port, has_adopted).await {- has_seen_healthy = true;+ let liveness = check_watchdog_health(&state, generation, port, has_adopted).await;+ if liveness.alive {+ // One answer is proof of life, not proof that startup is over. The backend+ // imports the ML stack on a warm thread and those C-extension imports hold the+ // GIL, so a process that replies now can still miss the next three probes while+ // it is perfectly healthy. Only end the startup grace once the backend reports+ // that whole warm finished, not merely its first (hardware detection) stage.+ if liveness.warming_up {+ info!(+ "Health watchdog: backend on port {} is alive but still warming up, holding the startup grace period",+ port+ );+ }+ has_seen_healthy =+ watchdog_seen_healthy_after(has_seen_healthy, liveness.alive, liveness.warming_up);consecutive_failures = 0;} else if !should_count_failure {info!(diff --git a/studio/src-tauri/src/desktop_backend_owner.rs b/studio/src-tauri/src/desktop_backend_owner.rsindex 5e0c7b13edf..a6637f02111 100644--- a/studio/src-tauri/src/desktop_backend_owner.rs+++ b/studio/src-tauri/src/desktop_backend_owner.rs@@ -580,8 +580,11 @@ async fn health_ready_status(}}-async fn fetch_liveness(port: u16) -> Result<Option<DesktopLiveness>, reqwest::Error> {- let client = crate::loopback_http::client(LOCAL_HTTP_TIMEOUT)?;+async fn fetch_liveness(+ port: u16,+ timeout: Duration,+) -> Result<Option<DesktopLiveness>, reqwest::Error> {+ let client = crate::loopback_http::client(timeout)?;for path in ["/api/liveness", "/api/health"] {let response = client.get(format!("http://127.0.0.1:{port}{path}"))@@ -641,8 +644,8 @@ async fn fetch_health(.map_err(|e| e.to_string())}-async fn desktop_login_route_compatible(port: u16) -> bool {- let client = match crate::loopback_http::client(LOCAL_HTTP_TIMEOUT) {+async fn desktop_login_route_compatible(port: u16, timeout: Duration) -> bool {+ let client = match crate::loopback_http::client(timeout) {Ok(client) => client,Err(_) => return false,};@@ -695,6 +698,22 @@ pub(crate) async fn probe_owned_backend_state(owner: BackendOwnerState,port: Option<u16>,require_desktop_secret: bool,+) -> OwnedBackendProbe {+ probe_owned_backend_state_with_timeout(owner, port, require_desktop_secret, LOCAL_HTTP_TIMEOUT)+ .await+}++/// As above, but with an explicit per-request budget.+///+/// The health watchdog needs this. Its probes have to survive the multi-second GIL stalls+/// the backend's warm thread causes while it imports the ML stack, and at the default 2s+/// every request here times out during exactly the stall the watchdog is meant to tolerate,+/// so the backend reads as unverified and gets cleared.+pub(crate) async fn probe_owned_backend_state_with_timeout(+ owner: BackendOwnerState,+ port: Option<u16>,+ require_desktop_secret: bool,+ timeout: Duration,) -> OwnedBackendProbe {let ports: Vec<u16> = match port {Some(port) => vec![port],@@ -702,7 +721,7 @@ pub(crate) async fn probe_owned_backend_state(};let mut verified = Vec::new();for port in ports {- let liveness = match fetch_liveness(port).await {+ let liveness = match fetch_liveness(port, timeout).await {Ok(Some(liveness)) => liveness,Ok(None) => continue,Err(error) => {@@ -719,7 +738,7 @@ pub(crate) async fn probe_owned_backend_state(if let Some(reason) = lifecycle_control_block_reason(&liveness) {return OwnedBackendProbe::Unmanageable { port, reason };}- if !desktop_login_route_compatible(port).await {+ if !desktop_login_route_compatible(port, timeout).await {return OwnedBackendProbe::Unmanageable {port,reason: "desktop_login_probe_failed".to_string(),diff --git a/studio/src-tauri/src/main.rs b/studio/src-tauri/src/main.rsindex 49d97fcc8fb..a6bebc51a27 100644--- a/studio/src-tauri/src/main.rs+++ b/studio/src-tauri/src/main.rs@@ -27,6 +27,7 @@ use simplelog::{};use std::ffi::OsStr;use std::fs;+use std::io::Write;use std::path::{Path, PathBuf};use std::sync::atomic::{AtomicBool, Ordering};use std::sync::{Once, OnceLock};@@ -380,6 +381,87 @@ fn has_saved_window_state(app: tauri::AppHandle) -> bool {dir.join(app.filename()).is_file()}+/// Append target for `tauri.log` that rotates while the app runs, not only at launch.+///+/// The size check used to happen once in `setup_logging`, so a session left open for+/// days (the backend's own log lines are mirrored here as they arrive) grew the file+/// past the cap until the next restart. Tracking the byte count as we write applies the+/// same 5 MiB threshold continuously. Rotation closes the handle before renaming, which+/// Windows requires and which also means the reopened file is the one being written.+struct RotatingLogFile {+ path: PathBuf,+ rotated_path: PathBuf,+ max_bytes: u64,+ file: Option<fs::File>,+ written: u64,+}++impl RotatingLogFile {+ fn open(+ path: PathBuf,+ rotated_path: PathBuf,+ max_bytes: u64,+ ) -> std::io::Result<RotatingLogFile> {+ let mut rotating = RotatingLogFile {+ path,+ rotated_path,+ max_bytes,+ file: None,+ written: 0,+ };+ rotating.reopen()?;+ Ok(rotating)+ }++ fn reopen(&mut self) -> std::io::Result<()> {+ let file = fs::OpenOptions::new()+ .create(true)+ .append(true)+ .open(&self.path)?;+ // Pick up where a previous session left off, so an already-oversized file+ // rotates on its first write instead of growing for another whole session.+ self.written = file.metadata().map(|meta| meta.len()).unwrap_or(0);+ self.file = Some(file);+ Ok(())+ }++ /// Move the current log aside and start a fresh one. Best effort: if reopening+ /// fails we drop lines rather than take the app down over a log file.+ fn rotate(&mut self) {+ self.file = None;+ let _ = fs::remove_file(&self.rotated_path);+ let _ = fs::rename(&self.path, &self.rotated_path);+ if self.reopen().is_err() {+ self.file = None;+ self.written = 0;+ }+ }+}++impl Write for RotatingLogFile {+ fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {+ if self.written >= self.max_bytes {+ self.rotate();+ }+ match self.file.as_mut() {+ Some(file) => {+ let written = file.write(buf)?;+ self.written += written as u64;+ Ok(written)+ }+ // No usable handle: report the bytes as taken so the logger does not spin.+ None => Ok(buf.len()),+ }+ }++ fn flush(&mut self) -> std::io::Result<()> {+ match self.file.as_mut() {+ Some(file) => file.flush(),+ None => Ok(()),+ }+ }+}+fn setup_logging() {let mut loggers: Vec<Box<dyn SharedLogger>> = vec![];@@ -398,18 +480,7 @@ fn setup_logging() {let log_path = log_dir.join("tauri.log");let rotated_path = log_dir.join("tauri.log.1");let max_log_bytes = 5 * 1024 * 1024;- if fs::metadata(&log_path)- .map(|meta| meta.len() >= max_log_bytes)- .unwrap_or(false)- {- let _ = fs::remove_file(&rotated_path);- let _ = fs::rename(&log_path, &rotated_path);- }- if let Ok(file) = fs::OpenOptions::new()- .create(true)- .append(true)- .open(&log_path)- {+ if let Ok(file) = RotatingLogFile::open(log_path, rotated_path, max_log_bytes) {loggers.push(WriteLogger::new(LevelFilter::Info, Config::default(), file));}}@@ -959,6 +1030,47 @@ fn main() {mod tests {use super::*;+ #[test]+ fn log_file_rotates_mid_session_and_keeps_one_generation() {+ let directory = tempfile::tempdir().unwrap();+ let log_path = directory.path().join("tauri.log");+ let rotated_path = directory.path().join("tauri.log.1");++ let mut file = RotatingLogFile::open(log_path.clone(), rotated_path.clone(), 8).unwrap();+ file.write_all(b"aaaaaaaaaa").unwrap();+ file.flush().unwrap();+ // Still the first generation: the threshold is checked before a write, so the+ // line that crosses it is written whole rather than split across two files.+ assert!(!rotated_path.exists());++ file.write_all(b"bbbb").unwrap();+ file.flush().unwrap();+ assert_eq!(fs::read_to_string(&rotated_path).unwrap(), "aaaaaaaaaa");+ assert_eq!(fs::read_to_string(&log_path).unwrap(), "bbbb");++ // A second rotation replaces .1 rather than piling up generations.+ file.write_all(b"cccccccccc").unwrap();+ file.write_all(b"dddd").unwrap();+ file.flush().unwrap();+ assert_eq!(fs::read_to_string(&rotated_path).unwrap(), "bbbbcccccccccc");+ assert_eq!(fs::read_to_string(&log_path).unwrap(), "dddd");+ }++ #[test]+ fn an_oversized_log_from_a_previous_session_rotates_on_the_first_write() {+ let directory = tempfile::tempdir().unwrap();+ let log_path = directory.path().join("tauri.log");+ let rotated_path = directory.path().join("tauri.log.1");+ fs::write(&log_path, b"stale-and-oversized").unwrap();++ let mut file = RotatingLogFile::open(log_path.clone(), rotated_path.clone(), 8).unwrap();+ file.write_all(b"fresh").unwrap();+ file.flush().unwrap();++ assert_eq!(fs::read_to_string(&rotated_path).unwrap(), "stale-and-oversized");+ assert_eq!(fs::read_to_string(&log_path).unwrap(), "fresh");+ }+/// args() panics on a non-Unicode argv[0], so the flag scan has to run over OsStr.#[test]fn hidden_flag_scan_tolerates_non_unicode_args() {diff --git a/tests/studio/install/test_selection_logic.py b/tests/studio/install/test_selection_logic.pyindex 2c18ad3e552..c7f2133530f 100644--- a/tests/studio/install/test_selection_logic.py+++ b/tests/studio/install/test_selection_logic.py@@ -83,6 +83,10 @@ def load_studio_run_module(monkeypatch):)loggers = types.ModuleType("loggers")loggers.get_logger = lambda name: logger+ # run.py imports this at module scope, so the stub has to carry it or the import+ # of run fails before any test body runs. A no-op is right here: the filter only+ # de-duplicates uvicorn's copy of a traceback, and this module never starts a server.+ loggers.install_uvicorn_duplicate_exception_filter = lambda: Nonemonkeypatch.setitem(sys.modules, "loggers", loggers)startup_banner = types.ModuleType("startup_banner")diff --git a/tests/studio/playwright_mac_tab_capabilities.py b/tests/studio/playwright_mac_tab_capabilities.pynew file mode 100644index 00000000000..411d4773660--- /dev/null+++ b/tests/studio/playwright_mac_tab_capabilities.py@@ -0,0 +1,636 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Unsloth macOS tab-capability Playwright test.++Covers the two field failures from Unsloth Desktop 0.1.524-beta on Apple Silicon:++1. The Train and Video sidebar rows rendered blacked out for minutes after launch,+ then came back. The store seeded chat-only from a browser-UA guess, so on a Mac+ both rows greyed out on first paint and stayed that way until /api/health+ answered -- which, after the startup-speedup work moved the ML imports onto a+ background warm thread, can take a long time. A row whose capability is still+ unmeasured must spin, not grey out.++ That state is asserted on a window this script opens itself, by holding the+ browser's /api/health at hardware_detecting=true, rather than on the real warm.+ The real one is a race nobody wins: see sample_natural_warm_window.++2. The desktop launcher's health watchdog killed the backend about a minute in+ ("Server stopped unexpectedly"). The warm thread holds the GIL through its+ C-extension imports, so probes time out while the process is perfectly alive.+ This polls the backend across the whole warm window and asserts it survives.++Runs against a live Studio; drives the real UI. Env contract matches the other+scripts here: BASE_URL, STUDIO_OLD_PW, PW_ART_DIR.+"""++import json+import os+import re+import sys+import threading+import time+import urllib.error+import urllib.request+from pathlib import Path++from playwright.sync_api import sync_playwright++# Run as a plain script (not via pytest), so prepend the dir to sys.path.+sys.path.insert(0, str(Path(__file__).resolve().parent))+from _playwright_robust import ( # noqa: E402+ chromium_launch_args,+ install_view_transition_killer,+ install_wall_clock_watchdog,+ is_benign_page_error,+ wait_for_health,+)++BASE = os.environ["BASE_URL"]+# STUDIO_OLD_PW is what the repo's own macOS workflow exports; STUDIO_PW is what the+# staging harness exports. Accept either so the same script runs under both.+OLD = os.environ.get("STUDIO_OLD_PW") or os.environ["STUDIO_PW"]+# What to rotate the bootstrap password to, when the app forces a change on first+# login. Only used on that path: a harness that already rotated over the API (the+# staging one) never reaches it. Must differ from OLD, or the change is rejected.+NEW = os.environ.get("STUDIO_NEW_PW") or f"{OLD}-Rotated1!"+ART = Path(os.environ.get("PW_ART_DIR", "logs/playwright_mac_tabs"))+ART.mkdir(parents = True, exist_ok = True)++# The watchdog kills after 3 consecutive failures at a 15s interval, and the+# backend's startup grace is 300s. Outliving the grace is the whole point: a+# backend that dies at t+66s (the reported crash) fails here.+SURVIVAL_S = float(os.environ.get("STUDIO_MAC_SURVIVAL_S", "330"))+POLL_INTERVAL_S = float(os.environ.get("STUDIO_MAC_POLL_INTERVAL_S", "5"))+WALL_TIMEOUT_S = float(os.environ.get("STUDIO_UI_WALL_TIMEOUT_S", "900"))+# How long the forced-verdict check gives the row to settle into its pending state.+FORCED_PENDING_S = float(os.environ.get("STUDIO_MAC_FORCED_PENDING_S", "15"))+# Every tab the user reported interacting with, plus the ones that share the+# chat-only gate. (route, nav row id, human name).+TABS = [+ ("/chat", "projects", "Chat"),+ ("/hub", "hub", "Hub"),+ ("/images", "images", "Images"),+ ("/studio", "train", "Train"),+ ("/video", "video", "Video"),+ ("/export", "export", "Export"),+]++# Routes that mean "not signed in". Landing on one invalidates every later assertion,+# so they are matched explicitly rather than folded into the generic redirect check.+_SIGNED_OUT_PATHS = ("/login", "/onboarding", "/change-password")++# Rows the sidebar pins inline by default, per SIDEBAR_NAV_DEFAULT_PINNED in+# studio/frontend/src/features/settings/stores/appearance-custom-store.ts. Only these+# carry a data-testid: the overflow rows render as MoreMenuItem inside a dropdown that+# mounts nothing until it is opened and passes no test id even when it is, so+# `[data-testid="nav-row-video"]` returns null on every host, every time.+#+# That matters for what this file can claim. The field report named Train AND Video, and+# the first version of this script sampled both -- but the Video half could never observe+# anything, so half of its evidence was structurally empty. Video is not lost coverage:+# both rows carry the one `pending: capabilitiesUnknown` flag and both resolve it through+# resolveNavRowState (studio/frontend/src/components/nav-row-state.ts), so Train is the+# observable end of the same wire and the More flyout is covered by the frontend unit+# tests instead.+INLINE_ROW_IDS = ("hub", "projects", "images", "train")+# The row every pending-state assertion below is pinned to.+GATED_ROW_ID = "train"+# Intercept pattern for the browser's health reads. Matches whether api-base.ts builds a+# relative path or an absolute one.+_HEALTH_ROUTE = "**/api/health"++_failed: list[str] = []+# Every nav row located anywhere in the tab walk. A walk that never finds the rows the+# sidebar pins by default proves nothing about the gating, so it is a failure rather+# than a stream of info lines.+_rows_seen: set[str] = set()+++def signed_out(url: str) -> bool:+ return any(url.rstrip("/").endswith(p) or f"{p}?" in url for p in _SIGNED_OUT_PATHS)+++def info(s: str) -> None:+ print(f"[mac-tabs] {s}", flush = True)+++def step(s: str) -> None:+ print(f"[mac-tabs] STEP {s}", flush = True)+++def fail(m: str) -> None:+ print(f"[mac-tabs] FAIL: {m}", flush = True)+ _failed.append(m)+++def _get_json(path: str, timeout: float = 10.0) -> tuple[int, dict | None]:+ try:+ with urllib.request.urlopen(f"{BASE}{path}", timeout = timeout) as resp:+ body = resp.read().decode("utf-8", "replace")+ try:+ return resp.status, json.loads(body)+ except ValueError:+ return resp.status, None+ except urllib.error.HTTPError as exc:+ return exc.code, None+ except Exception:+ return 0, None+++class BackendSurvivalPoller:+ """Poll /api/liveness and /api/health for the whole run, on a daemon thread.++ Records every non-200 and the worst latency seen. The UI drive happens+ concurrently, so this measures the backend under the same load the desktop+ launcher's watchdog would be probing it under.+ """++ def __init__(self) -> None:+ self.samples: list[dict] = []+ self.stop = threading.Event()+ self.thread = threading.Thread(target = self._run, name = "survival-poll", daemon = True)++ def start(self) -> None:+ self.thread.start()++ def _run(self) -> None:+ while not self.stop.is_set():+ for path in ("/api/liveness", "/api/health"):+ began = time.monotonic()+ status, body = _get_json(path)+ self.samples.append(+ {+ "t": round(time.monotonic(), 1),+ "path": path,+ "status": status,+ "ms": round((time.monotonic() - began) * 1000, 1),+ "hardware_detecting": (body or {}).get("hardware_detecting"),+ # Stage 0 of the warm only sets hardware_detecting; this one stays+ # lit through the transformers and datasets imports after it, so the+ # pair is what tells a reader of the artifacts how wide the real+ # provisional window on this host was.+ "torch_warm_in_progress": (body or {}).get("torch_warm_in_progress"),+ }+ )+ self.stop.wait(POLL_INTERVAL_S)++ def finish(self) -> None:+ self.stop.set()+ self.thread.join(timeout = 30)++ def report(self) -> None:+ (ART / "survival_samples.json").write_text(+ json.dumps(self.samples, indent = 1),+ encoding = "utf-8",+ )+ for path in ("/api/liveness", "/api/health"):+ got = [s for s in self.samples if s["path"] == path]+ if not got:+ fail(f"no samples collected for {path}")+ continue+ bad = [s for s in got if s["status"] != 200]+ worst = max(s["ms"] for s in got)+ unmeasured = sum(1 for s in got if s["hardware_detecting"] is True)+ warming = sum(1 for s in got if s["torch_warm_in_progress"] is True)+ info(+ f"{path}: {len(got)} samples, {len(bad)} non-200, worst {worst}ms, "+ f"{unmeasured} with an unmeasured verdict, {warming} with the warm still running"+ )+ if bad:+ fail(+ f"{path} returned non-200 {len(bad)} time(s) "+ f"(first at t={bad[0]['t']}s status={bad[0]['status']}); "+ "the backend did not stay up through the warm window"+ )+++def rotate_password(page) -> None:+ """Complete the forced password change a bootstrap login lands on.++ Studio seeds a one-time bootstrap password and requires it to be replaced before+ the app proper is reachable. A harness that rotates it over the API first (the+ staging one does) never sees this screen; a harness that hands over the raw+ bootstrap password (this repo's macOS smoke does) always does. Handling it here+ means the script works under both instead of only the one it was written against.++ The current-password box is rendered only when the page did NOT receive the+ bootstrap password (auth-form.tsx:362), so fill it when present rather than+ requiring it.+ """+ step("completing the forced password change")+ try:+ page.locator("#new-password").wait_for(state = "visible", timeout = 60000)+ current = page.locator("#current-password")+ if current.count() > 0:+ current.fill(OLD)+ page.locator("#new-password").fill(NEW)+ confirm = page.locator("#confirm-password")+ if confirm.count() > 0:+ confirm.fill(NEW)+ page.get_by_role("button", name = re.compile(r"^change password$", re.I)).first.click()+ page.wait_for_url(lambda url: not signed_out(url), timeout = 60000)+ info("password rotated")+ except Exception as exc:+ info(f"forced password change did not complete: {exc!r}")+ page.screenshot(path = str(ART / "change_password_failed.png"))+++def log_in(page) -> bool:+ """Sign in and prove it took. Returns False if the app is still signed out.++ Three things about this form make the obvious version of this helper silently+ do nothing, and all three cost a green run that checked an empty shell:++ * auth-form.tsx returns null while the auth-status request is in flight, so at+ domcontentloaded there is no form in the DOM at all. A `count()` reads 0 and+ does not wait, which is exactly how this fell through to "assuming desktop+ auth" on the runner. Wait for the field instead.+ * Login mode renders a password and nothing else -- there is no username box+ (auth-form.tsx:329-342). Requiring one made the fill a no-op.+ * The submit button is labelled "Login", not "Sign in".+ """+ page.goto(BASE, wait_until = "domcontentloaded", timeout = 120000)+ # A backend that still has its one-time bootstrap password injects it into the page+ # and signs itself in, landing on /change-password with no login form ever rendered.+ # Check that BEFORE waiting on #password, or the wait burns 60s and reports "no+ # password field" for a session that is actually authenticated.+ try:+ page.wait_for_url(+ lambda url: "/change-password" in url or "/login" in url,+ timeout = 30000,+ )+ except Exception:+ pass+ if "/change-password" in page.url:+ rotate_password(page)+ try:+ # #password is the login field; the change-password screen uses+ # #current-password / #new-password, which we never want to touch here.+ # Only look for a login form when still on a signed-out route. After the+ # bootstrap rotation above we are already authenticated, and waiting a full+ # minute for a form that is correctly absent burns CI time and logs a+ # misleading "no password field".+ pw_box = page.locator("#password") if signed_out(page.url) else None+ if pw_box is not None:+ try:+ pw_box.wait_for(state = "visible", timeout = 60000)+ except Exception:+ # No form after a full minute is either a genuinely password-less+ # desktop build or a frontend that never rendered. The redirect check+ # below tells the two apart, so do not conclude anything here.+ info("no password field appeared within 60s")+ pw_box = None+ if pw_box is not None:+ pw_box.fill(OLD)+ submit = page.get_by_role("button", name = re.compile(r"^(login|sign in)$", re.I))+ submit.first.click()+ # Settle on the post-auth route rather than sleeping a fixed 3s.+ try:+ page.wait_for_url(+ lambda url: not signed_out(url),+ timeout = 60000,+ )+ except Exception:+ info(f"still on {page.url} 60s after submitting the login form")+ # A first login with the bootstrap password lands on /change-password+ # (session.ts:93 getPostAuthRoute -> mustChangePassword), which is a+ # signed-out route here because it has no sidebar to assert against.+ # The session is real, so finish the rotation instead of giving up.+ if "/change-password" in page.url:+ rotate_password(page)+ except Exception as exc:+ info(f"login form interaction raised {exc!r}")++ # Prove it rather than assume it: land somewhere authed and check we stayed.+ try:+ page.goto(f"{BASE}/chat", wait_until = "domcontentloaded", timeout = 60000)+ page.wait_for_timeout(1500)+ except Exception as exc:+ info(f"post-login navigation raised {exc!r}")+ if signed_out(page.url):+ info(f"still signed out after the login attempt (at {page.url})")+ page.screenshot(path = str(ART / "login_failed.png"))+ return False+ info("signed in")+ return True+++_ROW_STATE_JS = """(ids) => {+ const out = {};+ for (const id of ids) {+ const el = document.querySelector(`[data-testid="nav-row-${id}"]`);+ if (!el) { out[id] = null; continue; }+ out[id] = {+ disabled: el.hasAttribute("disabled")+ || el.getAttribute("aria-disabled") === "true",+ spinner: el.getAttribute("data-spinner") === "true",+ };+ }+ return out;+}"""+++def row_states(page, ids = INLINE_ROW_IDS) -> dict:+ """DOM state of each nav row by test id; None for a row that is not rendered."""+ return page.evaluate(_ROW_STATE_JS, list(ids)) or {}+++def sample_natural_warm_window(page) -> None:+ """Watch the real warm close, and fail on a real grey-out. Observes nothing on most runs.++ Deliberately asserts nothing about having reached the window, because reaching it is+ not something this script can arrange. `hardware_detecting` is stage 0 of the warm --+ on the macOS runner's `--no-torch` install that is a failed `import torch` plus one+ failed importlib.metadata lookup, so the verdict settles inside a second of the port+ binding. Getting an authenticated sidebar in front of that costs a Chromium launch,+ a login and two navigations, one of which spends the frontend's own 5s bounded wait+ on the verdict (HARDWARE_DETECT_WAIT_MS in studio/frontend/src/config/env.ts). The+ window is normally shut before the first sample, on a slow host as much as a fast+ one, so requiring it -- under an env flag or otherwise -- would buy a permanently red+ job rather than a test. The guarantee lives in assert_pending_state_on_forced_verdict+ below; this stays for the case the window IS open, where it is the only check that+ sees the real backend and the real UI disagree.+ """+ step("sampling nav rows during the unmeasured window")+ deadline = time.monotonic() + 45+ samples = 0+ unmeasured_samples = 0+ row_samples = 0+ spinner_samples = 0+ violations: list[str] = []+ while time.monotonic() < deadline:+ try:+ state = row_states(page, (GATED_ROW_ID,))+ except Exception as exc:+ # Only fatal before anything was read: a page that cannot be evaluated at all+ # is the signed-out/unrendered shape, and breaking out of it quietly is how+ # this function used to report success on zero observations.+ if samples == 0:+ fail(f"could not read the sidebar during the unmeasured window ({exc!r})")+ else:+ info(f"row sampling stopped early ({exc!r})")+ break+ samples += 1+ unmeasured = (_get_json("/api/health")[1] or {}).get("hardware_detecting") is True+ unmeasured_samples += int(unmeasured)+ got = state.get(GATED_ROW_ID)+ if got and unmeasured:+ row_samples += 1+ spinner_samples += int(bool(got["spinner"]))+ if got["disabled"]:+ violations.append(+ f"{GATED_ROW_ID} rendered disabled while /api/health still reported "+ "hardware_detecting=true"+ )+ if not unmeasured:+ info("hardware detection settled; stopping the unmeasured sampling")+ break+ time.sleep(0.5)++ for v in sorted(set(violations)):+ fail(v)+ info(+ f"real warm window: {samples} sample(s), {unmeasured_samples} with an unmeasured "+ f"verdict, {row_samples} of those with the {GATED_ROW_ID} row rendered, "+ f"{spinner_samples} of those spinning"+ )+++def assert_pending_state_on_forced_verdict(page) -> None:+ """Hold the verdict unmeasured for the browser and require the Train row to spin.++ This is the check that cannot pass having observed nothing, and it is the reason the+ one above does not have to. Instead of racing a sub-second warm, it answers the+ browser's /api/health with a real reply that has the measurement taken back out, so+ the provisional window stays open for as long as the check needs, on every host.++ What the field report described is then exactly what this reads: with the verdict+ unmeasured, `pending` beats `disabled` in resolveNavRowState+ (studio/frontend/src/components/nav-row-state.ts), so nav-row-train must render+ enabled with data-spinner="true". The regression rendered it disabled with no+ spinner, which fails here on any host, fast or slow, warm window or none.++ A missing row is a failure, not a skip: nav-row-train is pinned inline by default, so+ if it is not in the DOM the sidebar did not render and there is nothing to assert on.+ A stub body that drifted out of shape also fails loudly for the same reason, rather+ than quietly passing -- there is no path through here that reports success without+ having read the row.+ """+ step("forcing an unmeasured verdict and re-checking the pinned Train row")+ status, live = _get_json("/api/health")+ if status != 200 or not isinstance(live, dict):+ fail(+ "/api/health gave no body to base the provisional reply on "+ f"(status {status}); the forced pending-state check could not run"+ )+ return+ # A real reply with the measurement removed, so the only thing the browser sees+ # differently is the field under test. device_type is what env.ts reads as "measured",+ # and chat_only stays the conservative pre-detection default -- the exact pair a Mac+ # got on first paint in the field report, where the row blacked out.+ provisional = {+ k: v for k, v in live.items() if k not in ("device_type", "hardware_detection_deferred")+ }+ provisional["hardware_detecting"] = True+ provisional["chat_only"] = True+ body = json.dumps(provisional)++ def serve_provisional(route) -> None:+ route.fulfill(status = 200, content_type = "application/json", body = body)++ page.route(_HEALTH_ROUTE, serve_provisional)+ try:+ try:+ page.goto(f"{BASE}/chat", wait_until = "domcontentloaded", timeout = 60000)+ page.wait_for_selector(f'[data-testid="nav-row-{GATED_ROW_ID}"]', timeout = 30000)+ except Exception as exc:+ page.screenshot(path = str(ART / "forced_pending_missing_row.png"))+ fail(+ f"the {GATED_ROW_ID} nav row never rendered under an unmeasured verdict "+ f"({exc!r}); it is pinned inline by default, so either the sidebar did not "+ "come up or the row is gated on the verdict it is supposed to spin on"+ )+ return+ # The row derives its state synchronously from the store, but the store is filled+ # by the root route's beforeLoad, so give it frames rather than one read.+ deadline = time.monotonic() + FORCED_PENDING_S+ got = None+ while True:+ try:+ got = row_states(page, (GATED_ROW_ID,)).get(GATED_ROW_ID)+ except Exception as exc:+ # Raising out of here would skip the survival report and the exit code+ # main() is built around, so it lands as a failure like any other.+ fail(f"could not read the {GATED_ROW_ID} row under a forced verdict ({exc!r})")+ return+ if got and got["spinner"] and not got["disabled"]:+ break+ if time.monotonic() >= deadline:+ break+ time.sleep(0.25)+ page.screenshot(path = str(ART / "forced_pending.png"))+ if not got:+ fail(f"the {GATED_ROW_ID} nav row vanished between the wait and the read")+ elif got["disabled"]:+ fail(+ f"{GATED_ROW_ID} rendered disabled while /api/health reported "+ "hardware_detecting=true; this is the blacked-out row from the field report"+ )+ elif not got["spinner"]:+ fail(+ f"{GATED_ROW_ID} rendered with no pending spinner while /api/health "+ "reported hardware_detecting=true; an unmeasured capability has to read "+ "as 'still checking', not as a settled verdict"+ )+ else:+ info(f"{GATED_ROW_ID} spun on a forced unmeasured verdict, as it must")+ finally:+ page.unroute(_HEALTH_ROUTE, serve_provisional)+++def assert_row_never_greyed_while_unmeasured(page) -> None:+ """A row whose verdict is unmeasured must spin, never grey out.++ Two passes over the same contract. The first rides the real warm and is silent when+ it misses it; the second creates the window it needs. Only the second can hold this+ file to its promise, so it runs unconditionally and on every host.+ """+ sample_natural_warm_window(page)+ assert_pending_state_on_forced_verdict(page)+++def drive_tabs(page) -> None:+ for route, row_id, name in TABS:+ step(f"open {name} ({route})")+ try:+ page.goto(f"{BASE}{route}", wait_until = "domcontentloaded", timeout = 60000)+ page.wait_for_timeout(1500)+ except Exception as exc:+ fail(f"navigating to {route} raised {exc!r}")+ continue++ landed = page.url+ # The chat-only route guard may legitimately bounce Train/Video on a host+ # without the capability. What it must not do is bounce while the verdict+ # is still unknown, which is the race this run is here to catch.+ if signed_out(landed):+ # Never legitimate here: the session was proven signed in before the walk+ # started. Calling this an allowed redirect is exactly how a run that+ # authenticated with nobody goes green having exercised nothing.+ fail(f"{name}: bounced to the login page at {landed}; the session was lost mid-walk")+ continue+ if route not in landed:+ detecting = (_get_json("/api/health")[1] or {}).get("hardware_detecting")+ if detecting is True:+ fail(+ f"{name}: redirected away from {route} while capabilities were still unmeasured"+ )+ else:+ info(f"{name}: redirected to {landed} after a measured verdict (allowed)")++ # Read every inline row, not just this tab's: they render together, so one read+ # records that the sidebar came up at all and keeps the per-route detail in the log.+ try:+ _rows_seen.update(rid for rid, got in row_states(page).items() if got)+ except Exception as exc:+ info(f"{name}: could not read the sidebar rows ({exc!r})")++ # Clicking the row is the interaction the user reported; a greyed-out row+ # swallows the click, so this doubles as a check that it is reachable.+ try:+ row = page.locator(f'[data-testid="nav-row-{row_id}"]')+ if row.count() > 0 and row.first.is_enabled():+ row.first.click(timeout = 10000)+ page.wait_for_timeout(1000)+ elif row.count() > 0:+ info(f"{name}: nav row present but disabled (measured verdict)")+ elif row_id in INLINE_ROW_IDS:+ # Not an info line: this row is pinned inline by default, so its absence+ # means the sidebar did not render and this tab checked nothing.+ fail(f"{name}: nav row {row_id} is pinned inline by default but did not render")+ else:+ # Expected and permanent for Video and Export: they live under "More",+ # which renders no test id. Reached by route instead.+ info(f"{name}: nav row not pinned inline; reached by route instead")+ except Exception as exc:+ info(f"{name}: row click did not land ({exc!r})")++ page.screenshot(path = str(ART / f"tab_{row_id}.png"), full_page = False)+++def main() -> int:+ step("waiting for the backend to answer")+ if not wait_for_health(BASE, timeout = 600):+ fail("backend never answered /api/health")+ return 1++ poller = BackendSurvivalPoller()+ poller.start()+ began = time.monotonic()+ watchdog = install_wall_clock_watchdog(WALL_TIMEOUT_S, label = "mac-tabs", info = info)++ with sync_playwright() as pw:+ browser = pw.chromium.launch(args = chromium_launch_args(sys.platform))+ ctx = browser.new_context(viewport = {"width": 1440, "height": 900})+ install_view_transition_killer(ctx)+ page = ctx.new_page()+ page.on(+ "pageerror",+ lambda e: None if is_benign_page_error(str(e)) else fail(f"page error: {e}"),+ )++ step("login")+ if not log_in(page):+ # Every assertion past this point reads the authenticated shell. Signed out,+ # the sidebar does not render, so the tab checks would find no rows, report+ # nothing, and the run would go green having tested none of what it claims.+ fail("could not sign in; the tab assertions below would all be vacuous")+ poller.finish()+ poller.report()+ return 1++ assert_row_never_greyed_while_unmeasured(page)+ drive_tabs(page)+ missing = [rid for rid in INLINE_ROW_IDS if rid not in _rows_seen]+ if missing:+ fail(+ f"the sidebar rows pinned by default never rendered on any route ({', '.join(missing)}); "+ "the tab gating was never actually exercised, so a green run here would mean nothing"+ )++ # Hold the session open until the survival window is covered. The reported+ # crash landed at t+66s, well inside this.+ remaining = SURVIVAL_S - (time.monotonic() - began)+ if remaining > 0:+ step(f"holding the session for {remaining:.0f}s more to outlive the watchdog grace")+ while remaining > 0:+ page.wait_for_timeout(min(15000, int(remaining * 1000)))+ # Keep the UI doing real work so the backend is genuinely serving.+ page.goto(f"{BASE}/chat", wait_until = "domcontentloaded", timeout = 60000)+ remaining = SURVIVAL_S - (time.monotonic() - began)++ page.screenshot(path = str(ART / "final.png"))+ ctx.close()+ browser.close()++ watchdog.cancel()+ poller.finish()+ poller.report()++ status, _ = _get_json("/api/liveness")+ if status != 200:+ fail(f"backend was not alive at the end of the run (/api/liveness -> {status})")++ if _failed:+ print(f"[mac-tabs] {len(_failed)} FAILURE(S)", flush = True)+ for m in _failed:+ print(f"[mac-tabs] - {m}", flush = True)+ return 1+ print("[mac-tabs] PASS", flush = True)+ return 0+++if __name__ == "__main__":+ sys.exit(main())diff --git a/tests/studio/test_mac_tab_capability_warm_window.py b/tests/studio/test_mac_tab_capability_warm_window.pynew file mode 100644index 00000000000..f483612fc50--- /dev/null+++ b/tests/studio/test_mac_tab_capability_warm_window.py@@ -0,0 +1,415 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.++"""The macOS tab-capability smoke has to be able to fail.++tests/studio/playwright_mac_tab_capabilities.py needs a live Studio and a browser, so+CI is the only place it runs and nothing else checks that a red case comes out red.+Twice now it has gone green having observed nothing: first by authenticating with+nobody, then by computing `seen_spinner` and only logging it, so a backend that+settled before the browser arrived skipped every assertion.++This drives the same functions with the page and the backend stubbed, over the exact+shapes that used to pass: the warm window already shut, the row absent, the row greyed+out. It is a plain pytest file so it runs in the Backend CI walk over tests/, where+neither playwright nor a Studio is installed.+"""++from __future__ import annotations++import importlib.util+import re+import sys+import types+from pathlib import Path++import pytest++REPO = Path(__file__).resolve().parents[2]+SCRIPT = REPO / "tests/studio/playwright_mac_tab_capabilities.py"+APPEARANCE_STORE = REPO / "studio/frontend/src/features/settings/stores/appearance-custom-store.ts"++BASE = "http://127.0.0.1:18893"+# A settled reply: no hardware_detecting at all. This is the state the runner is in by+# the time the browser is authenticated, and the one the old code passed vacuously on.+SETTLED = {"status": "healthy", "service": "Unsloth UI Backend", "device_type": "mac"}+UNMEASURED = {"status": "healthy", "service": "Unsloth UI Backend", "hardware_detecting": True}++# Spelled out rather than read off the script, so these cases run unchanged against a+# build of it that does not define the constant yet. test_inline_row_ids_match_the_+# frontends_default_pinned_set is what keeps the spelling honest.+TRAIN = "train"++GREYED = {"disabled": True, "spinner": False}+SPINNING = {"disabled": False, "spinner": True}+SETTLED_ENABLED = {"disabled": False, "spinner": False}+++def _load(tmp_path: Path, monkeypatch: pytest.MonkeyPatch):+ """Import the script with playwright and its env contract stubbed out.++ Fresh per test: the script keeps its failures and its row sightings in module+ globals, so a shared instance would carry one test's verdict into the next.+ """+ if "playwright.sync_api" not in sys.modules:+ pkg = types.ModuleType("playwright")+ api = types.ModuleType("playwright.sync_api")+ api.sync_playwright = lambda: None+ pkg.sync_api = api+ monkeypatch.setitem(sys.modules, "playwright", pkg)+ monkeypatch.setitem(sys.modules, "playwright.sync_api", api)+ monkeypatch.setenv("BASE_URL", BASE)+ monkeypatch.setenv("STUDIO_OLD_PW", "stub-password")+ monkeypatch.setenv("PW_ART_DIR", str(tmp_path / "art"))+ # The real default gives the row 15s to settle; the stub answers instantly, so the+ # only thing the wait would buy here is 15s of a red test.+ monkeypatch.setenv("STUDIO_MAC_FORCED_PENDING_S", "0.2")+ spec = importlib.util.spec_from_file_location("mac_tab_capabilities_under_test", SCRIPT)+ mod = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(mod)+ return mod+++class FakeLocator:+ def __init__(self, present: bool) -> None:+ self._present = present+ self.clicked = False++ def count(self) -> int:+ return 1 if self._present else 0++ @property+ def first(self):+ return self++ def is_enabled(self) -> bool:+ return True++ def click(self, timeout = None) -> None:+ self.clicked = True+++class FakePage:+ """Enough of a Playwright page for the pending-state checks.++ `rows` maps a nav row id to the DOM state the stub reports, or None for a row that+ is not in the document. `row_missing` makes wait_for_selector time out the way a+ sidebar that never rendered does.+ """++ def __init__(+ self,+ rows: dict,+ *,+ row_missing: bool = False,+ ) -> None:+ self.rows = rows+ self.row_missing = row_missing+ self.url = f"{BASE}/chat"+ self.routed: list[str] = []+ self.unrouted: list[str] = []+ self.gotos: list[str] = []+ self.screenshots: list[str] = []++ def evaluate(+ self,+ script: str,+ arg = None,+ ):+ return {rid: self.rows.get(rid) for rid in (arg or [])}++ def route(self, pattern, handler) -> None:+ self.routed.append(pattern)+ # Prove the stub body is valid JSON and reaches the browser, rather than only+ # that route() was called: a body the frontend cannot parse would leave the row+ # in its pre-fetch state and the check would read the wrong thing.+ handler(_RecordingRoute(self))++ def unroute(+ self,+ pattern,+ handler = None,+ ) -> None:+ self.unrouted.append(pattern)++ def goto(+ self,+ url,+ wait_until = None,+ timeout = None,+ ) -> None:+ self.gotos.append(url)+ self.url = url++ def wait_for_selector(+ self,+ selector,+ timeout = None,+ ) -> None:+ if self.row_missing:+ raise TimeoutError(f"waiting for {selector}")++ def wait_for_timeout(self, ms) -> None:+ pass++ def screenshot(+ self,+ path = None,+ full_page = None,+ ) -> None:+ self.screenshots.append(str(path))++ def locator(self, selector: str):+ rid = selector.split("nav-row-")[1].rstrip('"]')+ return FakeLocator(self.rows.get(rid) is not None)+++class _RecordingRoute:+ def __init__(self, page: FakePage) -> None:+ self.page = page++ def fulfill(+ self,+ status = None,+ content_type = None,+ body = None,+ ) -> None:+ import json+ self.page.fulfilled = json.loads(body)+ self.page.fulfilled_status = status+++def _health(mod, bodies):+ """Point the script's backend reads at a scripted sequence of /api/health bodies."""+ queue = list(bodies)++ def fake(path, timeout = 10.0):+ body = queue.pop(0) if len(queue) > 1 else queue[0]+ return 200, dict(body)++ mod._get_json = fake+++# --------------------------------------------------------------------------------+# The regression Codex found: the window shut before the browser got there.+# --------------------------------------------------------------------------------+++def test_greyed_row_fails_even_though_the_warm_window_already_shut(tmp_path, monkeypatch):+ """The vacuous-pass case. Health has settled, so the real-warm sampler observes+ nothing and breaks on its first iteration; the row is blacked out exactly as it was+ in the field. Before the forced-verdict check this run went green."""+ mod = _load(tmp_path, monkeypatch)+ _health(mod, [SETTLED])+ page = FakePage({TRAIN: GREYED})++ mod.assert_row_never_greyed_while_unmeasured(page)++ assert mod._failed, (+ "the run passed with the warm window already shut and the Train row greyed "+ "out; this is the state the whole script exists to catch"+ )+ assert any("disabled" in m for m in mod._failed), mod._failed+++def test_row_with_no_spinner_fails(tmp_path, monkeypatch):+ """Enabled but not spinning is still wrong: an unmeasured capability has to read as+ 'still checking', not as a settled verdict that happens to allow the click."""+ mod = _load(tmp_path, monkeypatch)+ _health(mod, [SETTLED])+ page = FakePage({TRAIN: SETTLED_ENABLED})++ mod.assert_row_never_greyed_while_unmeasured(page)++ assert any("spinner" in m for m in mod._failed), mod._failed+++def test_absent_row_fails_instead_of_skipping(tmp_path, monkeypatch):+ """A row that never renders is the signed-out / unrendered shape. It must not be+ read as 'nothing to check here'."""+ mod = _load(tmp_path, monkeypatch)+ _health(mod, [SETTLED])+ page = FakePage({TRAIN: None}, row_missing = True)++ mod.assert_row_never_greyed_while_unmeasured(page)++ assert any("never rendered" in m for m in mod._failed), mod._failed+++def test_spinning_row_passes_and_the_route_is_lifted(tmp_path, monkeypatch):+ """The green case, and the only one there should be: the row spins on a forced+ unmeasured verdict, and the interception is taken back off so the tab walk that+ follows sees the real backend."""+ mod = _load(tmp_path, monkeypatch)+ _health(mod, [SETTLED])+ page = FakePage({TRAIN: SPINNING})++ mod.assert_row_never_greyed_while_unmeasured(page)++ assert mod._failed == []+ assert page.routed == ["**/api/health"]+ assert page.unrouted == ["**/api/health"]+ assert page.gotos == [f"{BASE}/chat"]+++def test_forced_body_is_a_real_reply_with_the_measurement_removed(tmp_path, monkeypatch):+ """What the browser is served has to be provisional by env.ts's rules: hardware+ detecting, no device_type, and not the deferred marker (which env.ts reads as+ settled and would grey the row out legitimately)."""+ mod = _load(tmp_path, monkeypatch)+ _health(mod, [{**SETTLED, "hardware_detection_deferred": True, "studio_root_id": "abc"}])+ page = FakePage({TRAIN: SPINNING})++ mod.assert_row_never_greyed_while_unmeasured(page)++ assert page.fulfilled_status == 200+ assert page.fulfilled["hardware_detecting"] is True+ assert page.fulfilled["chat_only"] is True+ assert "device_type" not in page.fulfilled+ assert "hardware_detection_deferred" not in page.fulfilled+ # Untouched fields survive, so the reply differs from a real one only where it must.+ assert page.fulfilled["studio_root_id"] == "abc"+++def test_unreadable_health_fails_rather_than_returning_early(tmp_path, monkeypatch):+ """No body to build the provisional reply from means the check did not run. Say so."""+ mod = _load(tmp_path, monkeypatch)+ mod._get_json = lambda path, timeout = 10.0: (0, None)+ page = FakePage({TRAIN: SPINNING})++ mod.assert_row_never_greyed_while_unmeasured(page)++ assert any("provisional" in m for m in mod._failed), mod._failed+++# --------------------------------------------------------------------------------+# The real-warm sampler still has to fail when it does catch a grey-out.+# --------------------------------------------------------------------------------+++def test_real_warm_grey_out_still_fails(tmp_path, monkeypatch):+ mod = _load(tmp_path, monkeypatch)+ _health(mod, [UNMEASURED, SETTLED])+ page = FakePage({TRAIN: GREYED})++ mod.sample_natural_warm_window(page)++ assert any("hardware_detecting=true" in m for m in mod._failed), mod._failed+++def test_sampler_that_cannot_read_the_page_at_all_fails(tmp_path, monkeypatch):+ """The bare `except Exception: break` this replaced turned a dead page into a+ silent zero-observation pass."""+ mod = _load(tmp_path, monkeypatch)+ _health(mod, [UNMEASURED])+ page = FakePage({TRAIN: SPINNING})+ page.evaluate = lambda script, arg = None: (_ for _ in ()).throw(RuntimeError("page closed"))++ mod.sample_natural_warm_window(page)++ assert any("could not read the sidebar" in m for m in mod._failed), mod._failed+++def test_missed_warm_window_alone_is_not_a_failure(tmp_path, monkeypatch):+ """Missing the real window is normal and must stay quiet, or the macOS job goes red+ on every run. The forced check above is what carries the guarantee instead."""+ mod = _load(tmp_path, monkeypatch)+ _health(mod, [SETTLED])+ page = FakePage({TRAIN: SPINNING})++ mod.sample_natural_warm_window(page)++ assert mod._failed == []+++# --------------------------------------------------------------------------------+# The tab walk: a pinned row that is not there means the tab checked nothing.+# --------------------------------------------------------------------------------+++def test_drive_tabs_fails_when_the_pinned_rows_never_render(tmp_path, monkeypatch):+ mod = _load(tmp_path, monkeypatch)+ _health(mod, [SETTLED])+ page = FakePage({})++ mod.drive_tabs(page)++ assert mod._rows_seen == set()+ for row_id in mod.INLINE_ROW_IDS:+ assert any(f"nav row {row_id} is pinned inline" in m for m in mod._failed), mod._failed+++def test_drive_tabs_does_not_fail_on_the_rows_that_live_under_more(tmp_path, monkeypatch):+ """Video and Export render inside the More dropdown, which mounts no data-testid at+ all. Their absence is the documented shape, not a miss -- asserting on it would be+ asserting on something that can never be true."""+ mod = _load(tmp_path, monkeypatch)+ _health(mod, [SETTLED])+ page = FakePage({rid: SETTLED_ENABLED for rid in mod.INLINE_ROW_IDS})++ mod.drive_tabs(page)++ assert mod._failed == []+ assert mod._rows_seen == set(mod.INLINE_ROW_IDS)+++# --------------------------------------------------------------------------------+# Drift guard: the row asserted on has to be one the sidebar actually pins.+# --------------------------------------------------------------------------------+++def test_inline_row_ids_match_the_frontends_default_pinned_set():+ """If a row is unpinned in the store, it stops rendering a data-testid and every+ assertion pinned to it silently becomes unobservable. That is how the Video half of+ this script came to check nothing, and it must not happen again unnoticed."""+ src = APPEARANCE_STORE.read_text(encoding = "utf-8")+ block = re.search(+ r"SIDEBAR_NAV_DEFAULT_PINNED[^{]*\{(.*?)\n\};",+ src,+ re.S,+ )+ assert block, "SIDEBAR_NAV_DEFAULT_PINNED is gone or its shape changed"+ entries = re.findall(r"^\s*(\w+):\s*(true|false),", block.group(1), re.M)+ assert entries, "no id: boolean entries parsed out of SIDEBAR_NAV_DEFAULT_PINNED"+ pinned = {name for name, value in entries if value == "true"}++ mod_ids = _module_constant("INLINE_ROW_IDS")+ assert set(mod_ids) == pinned, (+ f"the script treats {sorted(set(mod_ids))} as pinned inline but the store pins "+ f"{sorted(pinned)}; a row that is not pinned renders no data-testid, so any "+ "assertion on it can only ever observe nothing"+ )+ assert _module_constant("GATED_ROW_ID") in pinned+++def _module_constant(name: str):+ """Read a literal constant out of the script without importing it (no playwright,+ no env contract, so this stays usable from a bare collection)."""+ import ast++ tree = ast.parse(SCRIPT.read_text(encoding = "utf-8"))+ for node in tree.body:+ if isinstance(node, ast.Assign) and getattr(node.targets[0], "id", None) == name:+ return ast.literal_eval(node.value)+ raise AssertionError(f"{name} is not defined in {SCRIPT.name}")+++def test_the_forced_verdict_check_is_wired_into_the_public_entry_point():+ """main() calls assert_row_never_greyed_while_unmeasured, and that has to be what+ reaches the forced check. Splitting them apart without calling both from main is the+ one edit that would restore the vacuous pass while every test above still passes."""+ import ast++ tree = ast.parse(SCRIPT.read_text(encoding = "utf-8"))+ called = {}+ for node in ast.walk(tree):+ if isinstance(node, ast.FunctionDef):+ called[node.name] = {+ sub.func.id+ for sub in ast.walk(node)+ if isinstance(sub, ast.Call) and isinstance(sub.func, ast.Name)+ }+ assert "assert_pending_state_on_forced_verdict" in called.get(+ "assert_row_never_greyed_while_unmeasured", set()+ )+ assert "assert_row_never_greyed_while_unmeasured" in called.get("main", set())