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
Answer llama-server discovery probes instead of serving them the app shell (#10037)
Daniel Han640f0dbe225d
diff --git a/studio/backend/main.py b/studio/backend/main.pyindex d4242b0107c..a3f4d87e91f 100644--- a/studio/backend/main.py+++ b/studio/backend/main.py@@ -317,6 +317,7 @@ from routes import (youtube_router,)from routes.llama import router as llama_router+from routes.llama_compat import is_engine_probe_path, router as llama_compat_routerfrom routes.whisper import router as whisper_routerfrom routes.preview import router as preview_routerfrom hub.routes import (@@ -1460,6 +1461,11 @@ app.include_router(video_openai_router, prefix = "/v1", tags = ["openai-compat"]# OpenAI-compatible: mount the inference router at /v1 for external tools.app.include_router(inference_router, prefix = "/v1", tags = ["openai-compat"])+# llama-server / Ollama discovery probes. Declares its own full paths (/props,+# /version, /api/tags, ...) so it needs no prefix, and must be registered here --+# ahead of the SPA catch-all in serve_frontend() -- or /props and /version go on+# resolving to index.html with a 200.+app.include_router(llama_compat_router, tags = ["openai-compat"])app.include_router(preview_router, prefix = "/p", tags = ["preview"])app.include_router(providers_router, prefix = "/api/providers", tags = ["providers"])@@ -2545,6 +2551,13 @@ def setup_frontend(if file_path.is_file():return FileResponse(file_path)+ # Last, so a real asset always wins: an engine endpoint Studio does not serve+ # must 404 rather than render the app shell, which reads as "supported" to a+ # client that checks the status before the body. Deliberately after the file+ # lookup -- a build that ever ships one of these names still serves it.+ if is_engine_probe_path(full_path):+ raise HTTPException(status_code = 404, detail = "API endpoint not found")+# Serve index.html as bytes — avoids Content-Length mismatchreturn _build_index_response(request)diff --git a/studio/backend/routes/llama_compat.py b/studio/backend/routes/llama_compat.pynew file mode 100644index 00000000000..fdd5dd31a31--- /dev/null+++ b/studio/backend/routes/llama_compat.py@@ -0,0 +1,226 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Answer engine discovery probes with JSON, or with a 404, but never with the app.++Probes for engine endpoints used to land on main.py's SPA catch-all, so ``GET /props``+returned 200 and a page of HTML. That is worse than a 404: a probe reads the status+before the body. Served here: ``/props``, ``/v1/props``, ``/version``. Everything else+in llama-server's table gets an explicit 404, on its real method as well as GET.++Deliberately NOT served: Ollama's ``/api/tags`` and ``/api/show``. Answering them makes+a client select Ollama and then fail on ``/api/chat``, which Studio does not implement;+the reporting user's client instead fell back to the OpenAI surface and worked.+Advertising a protocol we do not have is the HTML 200 again, one layer up.+"""++from __future__ import annotations++import asyncio+import functools+from typing import Any, Optional++from fastapi import APIRouter, Depends, HTTPException++from auth.authentication import get_current_subject+from loggers import get_logger++logger = get_logger(__name__)++router = APIRouter()+++# llama-server's table (tools/server/server.cpp) minus /props, so the set is complete+# rather than growing per complaint. Bare only, so it cannot shadow /api/ or /v1/.+_ENGINE_PROBE_PATHS = frozenset(+ {+ "apply-template",+ "audio/transcriptions",+ "chat/completions",+ "chat/completions/input_tokens",+ "completion",+ "completions",+ "cors-proxy",+ "detokenize",+ "embedding",+ "embeddings",+ "health",+ "infill",+ "lora-adapters",+ "metrics",+ "models",+ "models/load",+ "models/sse",+ "models/unload",+ "rerank",+ "reranking",+ "responses",+ "responses/input_tokens",+ "slots",+ "tokenize",+ "tools",+ }+)++# /slots/:id_slot is the one dynamic entry in that table, and Studio calls it itself.+_ENGINE_PROBE_PREFIXES = ("slots/",)++# The /v1 entries Studio does not implement. A test asserts each is really absent from+# the assembled app, so implementing one fails CI instead of being shadowed by a 404.+_UNSERVED_V1_PROBE_PATHS = frozenset(+ {+ "v1/chat/completions/control",+ "v1/chat/completions/input_tokens",+ "v1/health",+ "v1/rerank",+ "v1/reranking",+ "v1/responses/input_tokens",+ "v1/stream",+ "v1/streams/lookup",+ }+)+++def is_engine_probe_path(full_path: str) -> bool:+ """True for an engine endpoint that must 404 rather than render the app shell."""+ normalized = full_path.strip("/").lower()+ return normalized in _ENGINE_PROBE_PATHS or normalized.startswith(_ENGINE_PROBE_PREFIXES)+++def _inference():+ """``routes.inference``, deferred because it pulls the whole inference stack. One+ indirection, so a test replaces this instead of mutating sys.modules."""+ from routes import inference+ return inference++[email protected]_cache(maxsize = 1)+def _studio_version() -> str:+ """The version string, resolved once: get_studio_version() shells out to git twice+ on a source checkout, and uncached that lands on the event loop per probe."""+ try:+ # Inside the guard: an ImportError here would 500 a probe about something else.+ from utils.studio_version import get_studio_version+ return get_studio_version()+ except Exception: # noqa: BLE001 -- discovery must not 500 on a version lookup+ return "dev"+++def _loaded_public_model_id() -> Optional[str]:+ """The id ``/v1/models`` publishes for whatever is resident, or None."""+ inf = _inference()+ llama_backend = inf.get_llama_cpp_backend()+ if getattr(llama_backend, "is_loaded", False):+ return inf._llama_public_model_id(llama_backend)+ # peek, not get: the orchestrator's cold build waits on hardware detection.+ orchestrator = inf._peek_inference_backend()+ if orchestrator is not None and getattr(orchestrator, "active_model_name", None):+ return inf._orchestrator_public_model_id(orchestrator)+ return None+++def _server_props() -> dict:+ """llama-server's /props, with model_path mapped to the public id like every other+ Studio response: upstream reports the absolute .gguf path and this is LAN reachable."""+ llama_backend = _inference().get_llama_cpp_backend()+ public_id = _loaded_public_model_id()+ llama_loaded = bool(getattr(llama_backend, "is_loaded", False))+ props: dict[str, Any] = {}+ if llama_loaded:+ # Documented not to raise, but a probe is the wrong place to find out it does.+ try:+ upstream = llama_backend._query_server_props()+ except Exception: # noqa: BLE001+ upstream = None+ if isinstance(upstream, dict):+ props = dict(upstream)++ props.pop("model_path", None)+ if public_id:+ props["model_path"] = public_id++ # These describe the CHILD's route table and web UI, not ours: Studio launches with+ # --metrics, so endpoint_metrics arrives true while public /metrics 404s here+ # (tools/server/server-context.cpp puts all three flags in the payload).+ for _child_only in ("ui", "ui_settings", "cors_proxy_enabled"):+ props.pop(_child_only, None)+ props["endpoint_slots"] = False+ props["endpoint_props"] = False+ props["endpoint_metrics"] = False++ # Only when llama-server owns the resident model: with MLX loaded, reading the+ # unloaded llama backend describes a serving model as having no context or slots.+ if llama_loaded:+ props.setdefault("default_generation_settings", {})+ settings = props["default_generation_settings"]+ if isinstance(settings, dict) and "n_ctx" not in settings:+ n_ctx = getattr(llama_backend, "context_length", None)+ if n_ctx:+ settings["n_ctx"] = int(n_ctx)+ if "total_slots" not in props:+ # Not zero beside a model this response advertises as loaded.+ try:+ slots = int(getattr(llama_backend, "effective_parallel_slots", 0) or 0)+ except Exception: # noqa: BLE001+ slots = 0+ if slots > 0:+ props["total_slots"] = slots+ props.setdefault("chat_template", getattr(llama_backend, "chat_template", "") or "")+ props["build_info"] = f"unsloth-studio/{_studio_version()}"+ return props+++# Slash forms too: FastAPI's redirect never fires, since the catch-all fully matches+# "/props/" and returns index.html. routes/inference.py registers "/v1/models/" likewise.[email protected]("/props", include_in_schema = False)[email protected]("/props/", include_in_schema = False)[email protected]("/v1/props", include_in_schema = False)[email protected]("/v1/props/", include_in_schema = False)+async def llama_props(current_subject: str = Depends(get_current_subject)):+ """llama-server-compatible ``GET /props``."""+ return await asyncio.to_thread(_server_props)++[email protected]("/version", include_in_schema = False)[email protected]("/version/", include_in_schema = False)+async def studio_version(current_subject: str = Depends(get_current_subject)):+ """Bare /version only: Ollama spells it /api/version, and answering there is part+ of claiming to be Ollama."""+ return {"version": _studio_version()}+++async def _probe_not_found():+ raise HTTPException(status_code = 404, detail = "API endpoint not found")+++# Without these a POST hit the GET-only catch-all and returned 405, reading as "exists,+# wrong method". HEAD is here because Starlette does not admit it on a GET route+# (measured, fastapi 0.141.1). GET stays with the catch-all so its asset lookup wins;+# OPTIONS is untouched for CORS preflight.+_PROBE_DENIED_METHODS = ["HEAD", "POST", "PUT", "PATCH", "DELETE"]++for _probe_path in sorted(_ENGINE_PROBE_PATHS):+ router.add_api_route(+ f"/{_probe_path}",+ _probe_not_found,+ methods = _PROBE_DENIED_METHODS,+ include_in_schema = False,+ )++# main.py already 404s an unknown GET under /v1/, so only the other methods need these.+for _v1_path in sorted(_UNSERVED_V1_PROBE_PATHS):+ router.add_api_route(+ f"/{_v1_path}",+ _probe_not_found,+ methods = _PROBE_DENIED_METHODS,+ include_in_schema = False,+ )++# Both slash forms: FastAPI's slash redirect does not apply to a path matching no route.+for _slots_form in ("/slots/{id_slot}", "/slots/{id_slot}/"):+ router.add_api_route(+ _slots_form,+ _probe_not_found,+ methods = _PROBE_DENIED_METHODS,+ include_in_schema = False,+ )diff --git a/studio/backend/tests/test_desktop_auth.py b/studio/backend/tests/test_desktop_auth.pyindex e364edb3a02..2c23e6204cc 100644--- a/studio/backend/tests/test_desktop_auth.py+++ b/studio/backend/tests/test_desktop_auth.py@@ -804,6 +804,10 @@ def test_health_response_reports_desktop_capability_fields(monkeypatch):settings_module.router = APIRouter()llama_module = ModuleType("routes.llama")llama_module.router = APIRouter()+ llama_compat_module = ModuleType("routes.llama_compat")+ llama_compat_module.router = APIRouter()+ # main.py imports this name alongside the router and calls it from serve_frontend.+ llama_compat_module.is_engine_probe_path = lambda full_path: Falseprompts_module = ModuleType("routes.prompts")prompts_module.router = APIRouter()preview_module = ModuleType("routes.preview")@@ -829,6 +833,7 @@ def test_health_response_reports_desktop_capability_fields(monkeypatch):monkeypatch.setitem(sys.modules, "routes", routes_module)monkeypatch.setitem(sys.modules, "routes.settings", settings_module)monkeypatch.setitem(sys.modules, "routes.llama", llama_module)+ monkeypatch.setitem(sys.modules, "routes.llama_compat", llama_compat_module)monkeypatch.setitem(sys.modules, "routes.prompts", prompts_module)monkeypatch.setitem(sys.modules, "routes.preview", preview_module)monkeypatch.setitem(sys.modules, "routes.whisper", whisper_module)diff --git a/studio/backend/tests/test_llama_compat_routes.py b/studio/backend/tests/test_llama_compat_routes.pynew file mode 100644index 00000000000..f9a594717b8--- /dev/null+++ b/studio/backend/tests/test_llama_compat_routes.py@@ -0,0 +1,709 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""routes/llama_compat.py: the discovery surface a third-party client probes.++Reproduces a real user report. A client pointed at Studio's port ran this sequence:++ GET /api/v1/models 404 GET /props 200 text/html+ GET /api/tags 404 GET /version 200 text/html+ GET /v1/props 404 POST /api/show 405++The two 200s are the bug: neither was a Studio route, so both fell through the SPA+catch-all and returned index.html, which a probe reads as "supported" before failing+on the body. The module is loaded standalone with a double for routes.inference.+"""++from __future__ import annotations++import importlib.util+import sys+import time+import types+from pathlib import Path++import pytest++_BACKEND = Path(__file__).resolve().parents[1]+if str(_BACKEND) not in sys.path:+ sys.path.insert(0, str(_BACKEND))++pytest.importorskip("fastapi")++from fastapi import FastAPI, HTTPException # noqa: E402+from fastapi.responses import Response # noqa: E402+from fastapi.testclient import TestClient # noqa: E402+++CATALOG = [+ {+ "id": "unsloth/Qwen3.8-27B-GGUF",+ "object": "model",+ "created": 1_700_000_000,+ "owned_by": "unsloth",+ "loaded": True,+ "quant": "UD-Q4_K_XL",+ },+ {+ "id": "unsloth/Laguna-S-2.1-GGUF",+ "object": "model",+ "created": 1_700_000_000,+ "owned_by": "unsloth",+ "loaded": False,+ },+]+++class _Backend:+ """Enough of LlamaCppBackend for the props handler."""++ def __init__(+ self,+ *,+ loaded = True,+ props = None,+ slots = 4,+ ):+ self.is_loaded = loaded+ self.effective_parallel_slots = slots+ self.model_identifier = "/media/models/qwen/model.gguf"+ self._openai_advertised_id = "unsloth/Qwen3.8-27B-GGUF"+ self.context_length = 262144+ self.chat_template = "{{ messages }}"+ self._props = props++ def _query_server_props(self):+ return self._props+++def _inference_double(+ backend,+ catalog,+ orchestrator = None,+):+ """Stand-in for routes.inference. Deliberately not a sys.modules entry: stubbing it+ globally broke two unrelated route tests when the suite ran in one process."""+ inference = types.SimpleNamespace()+ inference.get_llama_cpp_backend = lambda: backend+ inference._llama_public_model_id = lambda b, fallback = None: b._openai_advertised_id+ inference._peek_inference_backend = lambda: orchestrator+ inference._orchestrator_public_model_id = lambda b: b.active_model_name++ async def _objects():+ return catalog++ inference._openai_catalog_objects = _objects+ return inference+++_MOD = None+++def _load(+ backend = None,+ catalog = None,+ orchestrator = None,+):+ """The real routes/llama_compat.py, with routes.inference replaced by a double."""+ global _MOD+ if _MOD is None:+ spec = importlib.util.spec_from_file_location(+ "llama_compat_under_test", str(_BACKEND / "routes" / "llama_compat.py")+ )+ _MOD = importlib.util.module_from_spec(spec)+ sys.modules["llama_compat_under_test"] = _MOD+ spec.loader.exec_module(_MOD)+ double = _inference_double(+ backend if backend is not None else _Backend(),+ CATALOG if catalog is None else catalog,+ orchestrator,+ )+ _MOD._inference = lambda: double+ return _MOD+++def _client(mod):+ app = FastAPI()+ app.include_router(mod.router)++ # The SPA catch-all in main.py's order. Without it a test cannot tell "serves JSON"+ # from "serves the app shell with a 200", which is the whole defect.+ @app.get("/{full_path:path}")+ async def _spa(full_path: str):+ if full_path in {"api", "v1"} or full_path.startswith(("api/", "v1/")):+ raise HTTPException(status_code = 404, detail = "API endpoint not found")+ if mod.is_engine_probe_path(full_path):+ raise HTTPException(status_code = 404, detail = "API endpoint not found")+ return Response(content = b"<!doctype html>", media_type = "text/html")++ # Override the exact object the router closed over.+ app.dependency_overrides[mod.get_current_subject] = lambda: "test"+ return TestClient(app)++[email protected](scope = "module", autouse = True)+def _teardown():+ yield+ sys.modules.pop("llama_compat_under_test", None)+++# ── the reported probe sequence ───────────────────────────────────────────────+++def test_the_reported_probe_sequence_no_longer_returns_html():+ """THE REGRESSION THIS FILE EXISTS FOR: every probed path answers JSON or 404,+ never 200 text/html."""+ mod = _load()+ with _client(mod) as c:+ # The two that used to answer with the app shell now answer with JSON.+ for path in ("/props", "/v1/props", "/version"):+ r = c.get(path)+ assert r.status_code == 200, (path, r.status_code)+ assert "application/json" in r.headers["content-type"], path++ # The Ollama pair stays a 404 on purpose: see test_the_ollama_surface_is_not+ # _advertised. What matters is that no probe in the sequence gets HTML.+ # 405 for POST /api/show is main.py's standing answer for a POST to any unknown+ # /api/ path, unchanged by this PR; what matters is that none of them is HTML.+ for method, path in (+ ("GET", "/api/v1/models"),+ ("GET", "/api/tags"),+ ("POST", "/api/show"),+ ):+ r = c.request(method, path, json = {} if method == "POST" else None)+ assert r.status_code in (404, 405), (method, path, r.status_code)+ assert "text/html" not in r.headers.get("content-type", ""), (method, path)+++def test_the_html_fallback_is_what_used_to_answer_these():+ """The control: without it the test above passes on a build that 404s everything,+ which would break every deep link into the UI."""+ mod = _load()+ with _client(mod) as c:+ r = c.get("/some-ui-deep-link")+ assert r.status_code == 200+ assert "text/html" in r.headers["content-type"]+++def test_engine_endpoints_studio_does_not_serve_are_404_not_html():+ mod = _load()+ with _client(mod) as c:+ for path in ("/slots", "/completion", "/metrics", "/tokenize", "/health"):+ r = c.get(path)+ assert r.status_code == 404, path+ assert "text/html" not in r.headers.get("content-type", ""), path+++def test_probe_matching_ignores_case_and_stray_slashes():+ mod = _load()+ assert mod.is_engine_probe_path("slots")+ assert mod.is_engine_probe_path("/slots/")+ assert mod.is_engine_probe_path("Metrics")+ assert not mod.is_engine_probe_path("chat")+ # Served paths are deliberately absent: they are real routes, matched first.+ assert not mod.is_engine_probe_path("props")+ assert not mod.is_engine_probe_path("version")+++# ── /props ────────────────────────────────────────────────────────────────────+++def test_props_never_echoes_the_on_disk_gguf_path():+ """Upstream reports the absolute .gguf path and this is LAN reachable."""+ upstream = {+ "model_path": "/media/llm4/HDD-Models1/models/hub/models--unsloth--Qwen/model.gguf",+ "total_slots": 4,+ "default_generation_settings": {"n_ctx": 65536},+ }+ mod = _load(backend = _Backend(props = upstream))+ with _client(mod) as c:+ raw = c.get("/props")+ body = raw.json()+ assert body["model_path"] == "unsloth/Qwen3.8-27B-GGUF"+ assert "HDD-Models1" not in raw.text+ assert body["total_slots"] == 4+ assert body["default_generation_settings"]["n_ctx"] == 65536+++def test_props_degrades_to_the_local_view_when_the_engine_cannot_be_read():+ """A mid-restart engine returns None; the probe still answers from the local view."""+ mod = _load(backend = _Backend(props = None))+ with _client(mod) as c:+ body = c.get("/props").json()+ assert body["model_path"] == "unsloth/Qwen3.8-27B-GGUF"+ assert body["default_generation_settings"]["n_ctx"] == 262144+ # Not 0: this same response advertises the model as loaded, and a client reading+ # props for capacity would conclude it cannot serve. The backend knows what it+ # launched with.+ assert body["total_slots"] == 4+ assert body["build_info"].startswith("unsloth-studio/")+++def test_props_with_nothing_loaded_reports_no_model():+ mod = _load(backend = _Backend(loaded = False))+ with _client(mod) as c:+ body = c.get("/props").json()+ assert "model_path" not in body+ # No llama-server, so no llama-server props. Reporting total_slots 0 and an empty+ # template would describe an engine that is not running.+ assert "total_slots" not in body+ assert "chat_template" not in body+ assert body["build_info"].startswith("unsloth-studio/")+++def test_v1_props_and_props_agree():+ mod = _load(backend = _Backend(props = {"total_slots": 2}))+ with _client(mod) as c:+ assert c.get("/props").json() == c.get("/v1/props").json()+++# ── /version ──────────────────────────────────────────────────────────────────+++def test_version_answers_on_the_bare_path_only():+ """Ollama spells it /api/version; answering there is part of claiming to be Ollama."""+ mod = _load()+ with _client(mod) as c:+ bare = c.get("/version")+ prefixed = c.get("/api/version")+ assert bare.status_code == 200+ assert isinstance(bare.json()["version"], str) and bare.json()["version"]+ assert prefixed.status_code == 404+++# ── platform and robustness, from the sandbox run ─────────────────────────────+++ "upstream",+ [+ None,+ [],+ "not a dict",+ 42,+ {},+ {"default_generation_settings": None},+ {"default_generation_settings": []},+ {"total_slots": None},+ {"model_path": "/media/llm4/HDD/models/x.gguf"},+ ],+)+def test_props_never_500s_and_never_leaks_a_path_on_a_hostile_upstream(upstream):+ mod = _load(backend = _Backend(props = upstream))+ with _client(mod) as c:+ r = c.get("/props")+ assert r.status_code == 200, r.text+ assert "/media/" not in r.text+ assert r.json()["model_path"] == "unsloth/Qwen3.8-27B-GGUF"+++def test_props_survives_an_engine_query_that_raises():+ """A probe is the wrong place to find out that contract slipped."""++ class _Raises(_Backend):+ def _query_server_props(self):+ raise RuntimeError("engine unreachable")++ mod = _load(backend = _Raises())+ with _client(mod) as c:+ r = c.get("/props")+ assert r.status_code == 200+ assert r.json()["model_path"] == "unsloth/Qwen3.8-27B-GGUF"+++def test_the_version_lookup_survives_an_import_failure(monkeypatch):+ """An ImportError above the guard would 500 a probe about something else."""+ mod = _load()+ mod._studio_version.cache_clear()+ monkeypatch.setitem(sys.modules, "utils.studio_version", None)+ try:+ assert mod._studio_version() == "dev"+ finally:+ mod._studio_version.cache_clear()+++def test_the_version_lookup_is_resolved_once(monkeypatch):+ """Two git subprocesses per call, on the event loop, if uncached."""+ mod = _load()+ mod._studio_version.cache_clear()+ calls = []+ fake = types.ModuleType("utils.studio_version")+ fake.get_studio_version = lambda repo_root = None: (calls.append(1), "v0.1.999")[1]+ monkeypatch.setitem(sys.modules, "utils.studio_version", fake)+ try:+ for _ in range(25):+ assert mod._studio_version() == "v0.1.999"+ assert len(calls) == 1+ finally:+ mod._studio_version.cache_clear()+++def test_a_real_asset_wins_over_the_probe_deny_list(tmp_path):+ """The guard runs after the static lookup, so a shipped file named `metrics` wins."""+ mod = _load()+ (tmp_path / "metrics").write_text("asset-body")+ app = FastAPI()+ app.include_router(mod.router)++ @app.get("/{full_path:path}")+ async def _spa(full_path: str):+ candidate = tmp_path / full_path+ if candidate.is_file():+ return Response(content = candidate.read_bytes(), media_type = "text/plain")+ if mod.is_engine_probe_path(full_path):+ raise HTTPException(status_code = 404, detail = "API endpoint not found")+ return Response(content = b"<!doctype html>", media_type = "text/html")++ app.dependency_overrides[mod.get_current_subject] = lambda: "test"+ with TestClient(app) as c:+ assert c.get("/metrics").text == "asset-body"+ assert c.get("/slots").status_code == 404+++def test_no_client_side_ui_route_is_shadowed_by_the_deny_list():+ """Reads the routes the frontend declares, so a UI page named /metrics fails here+ rather than 404-ing in the browser."""+ routes_dir = _BACKEND.parent / "frontend" / "src" / "app" / "routes"+ if not routes_dir.is_dir():+ pytest.skip("frontend sources not present in this checkout")+ mod = _load()+ declared = set()+ for path in routes_dir.glob("*.tsx"):+ for line in path.read_text(encoding = "utf-8").splitlines():+ line = line.strip()+ if line.startswith('path: "') and line.endswith('",'):+ declared.add(line[len('path: "') : -2])+ assert declared, "no client routes parsed; the parser needs updating"+ shadowed = {p for p in declared if mod.is_engine_probe_path(p)}+ assert not shadowed, f"UI route(s) shadowed by the probe deny-list: {shadowed}"+++# ── the four findings from review ─────────────────────────────────────────────+++def test_the_ollama_surface_is_not_advertised():+ """Answering /api/tags makes a client select Ollama and then fail on /api/chat.+ The reporting user's client got 404 here, fell back to OpenAI, and worked, so+ advertising the pair would have broken the very client this started from."""+ mod = _load()+ routes = {r.path for r in mod.router.routes}+ assert "/api/tags" not in routes+ assert "/api/show" not in routes+ assert "/api/version" not in routes+ # And the inference endpoints an Ollama client would go on to call are absent, which+ # is what makes advertising the discovery pair wrong rather than merely incomplete.+ assert "/api/chat" not in routes and "/api/generate" not in routes++[email protected]("method", ["POST", "PUT", "PATCH", "DELETE"])+ "path",+ [+ "/completion",+ "/tokenize",+ "/detokenize",+ "/rerank",+ "/infill",+ "/embedding",+ "/apply-template",+ "/slots",+ ],+)+def test_unserved_engine_endpoints_404_on_their_real_method_not_405(method, path):+ """POST endpoints in llama-server, so before this they returned 405 from the+ GET-only catch-all, which reads as "exists, wrong method"."""+ mod = _load()+ with _client(mod) as c:+ r = c.request(method, path, json = {})+ assert r.status_code == 404, (method, path, r.status_code)+ assert "text/html" not in r.headers.get("content-type", ""), (method, path)+++def test_get_on_a_probe_path_still_reaches_the_asset_lookup(tmp_path):+ """Omitting GET is what keeps the catch-all's static lookup reachable."""+ mod = _load()+ assert not any(+ "GET" in (getattr(r, "methods", None) or set()) and r.path == "/completion"+ for r in mod.router.routes+ )+++def test_props_does_not_pair_an_orchestrator_model_with_llama_server_fields():+ """With MLX resident the llama backend is unloaded, so reading its fields anyway+ described a serving model as having no context and no slots."""++ class _Orchestrator:+ active_model_name = "unsloth/Llama-3.2-3B"++ mod = _load(backend = _Backend(loaded = False), orchestrator = _Orchestrator())+ with _client(mod) as c:+ body = c.get("/props").json()+ assert body["model_path"] == "unsloth/Llama-3.2-3B"+ for llama_only in ("total_slots", "chat_template", "default_generation_settings"):+ assert llama_only not in body, llama_only+++def test_the_probe_paths_are_admitted_under_keyless_inference_scope():+ """A 401 on /props in front of a surface the scope grants reads as an auth wall+ over the whole thing and stops discovery."""+ from utils.keyless_api_access import _INFERENCE_ROUTES++ assert ("GET", "/v1/models") in _INFERENCE_ROUTES, "baseline moved; re-derive this"+ for path in ("/props", "/v1/props", "/version"):+ assert ("GET", path) in _INFERENCE_ROUTES, path+ # Not the Ollama paths: they are not served at all.+ for path in ("/api/tags", "/api/show", "/api/version"):+ assert ("GET", path) not in _INFERENCE_ROUTES, path+++# ── round two ─────────────────────────────────────────────────────────────────+++def test_head_on_an_unserved_probe_path_is_404_not_405():+ """Starlette does NOT admit HEAD on a GET route (measured on the pinned fastapi+ 0.141.1 / starlette 1.6.0). A comment here previously claimed the opposite."""+ mod = _load()+ with _client(mod) as c:+ for path in ("/completion", "/tokenize", "/metrics", "/slots"):+ assert c.request("HEAD", path).status_code == 404, path+++def test_head_is_405_on_a_plain_get_route_which_is_why_it_is_listed():+ """Pins the framework behaviour the fix depends on."""+ app = FastAPI()++ @app.get("/{p:path}")+ async def _catchall(p: str):+ return {"p": p}++ with TestClient(app) as c:+ assert c.get("/anything").status_code == 200+ assert c.request("HEAD", "/anything").status_code == 405++[email protected]("path", ["/slots/0", "/slots/3", "/slots/abc", "/slots/0/"])+def test_the_nested_slot_endpoint_is_denied_too(path):+ """A real llama-server route Studio calls itself, missed by exact membership."""+ mod = _load()+ assert mod.is_engine_probe_path(path.strip("/"))+ with _client(mod) as c:+ for method in ("GET", "HEAD", "POST", "DELETE"):+ r = c.request(method, path, json = {} if method == "POST" else None)+ assert r.status_code == 404, (method, path, r.status_code)+++def test_the_deny_list_matches_llama_servers_own_route_table():+ """Transcribed from tools/server/server.cpp. /props is the only bare route Studio+ serves, so anything else missing means a probe still reaches the app shell."""+ mod = _load()+ bare_llama_routes = {+ "apply-template",+ "audio/transcriptions",+ "chat/completions",+ "chat/completions/input_tokens",+ "completion",+ "completions",+ "cors-proxy",+ "detokenize",+ "embedding",+ "embeddings",+ "health",+ "infill",+ "lora-adapters",+ "metrics",+ "models",+ "models/load",+ "models/sse",+ "models/unload",+ "props",+ "rerank",+ "reranking",+ "responses",+ "responses/input_tokens",+ "slots",+ "tokenize",+ "tools",+ }+ served = {"props"}+ for route in bare_llama_routes - served:+ assert mod.is_engine_probe_path(route), route+ assert not mod.is_engine_probe_path("props"), "Studio serves /props"+++def test_a_bare_llama_route_404s_on_every_method_a_client_would_use():+ mod = _load()+ with _client(mod) as c:+ for path in (+ "/chat/completions",+ "/responses",+ "/models",+ "/tools",+ "/audio/transcriptions",+ ):+ for method in ("GET", "HEAD", "POST"):+ r = c.request(method, path, json = {} if method == "POST" else None)+ assert r.status_code == 404, (method, path, r.status_code)+ assert "text/html" not in r.headers.get("content-type", ""), (method, path)+++def test_props_does_not_advertise_child_endpoints_studio_denies():+ """tools/server/server-context.cpp puts all three flags in the payload, and Studio+ launches with --metrics, so endpoint_metrics arrived true while /metrics 404s here."""+ upstream = {+ "endpoint_slots": True,+ "endpoint_props": True,+ "endpoint_metrics": True,+ "ui": True,+ "ui_settings": {"theme": "dark"},+ "cors_proxy_enabled": True,+ "total_slots": 4,+ }+ mod = _load(backend = _Backend(props = upstream))+ with _client(mod) as c:+ body = c.get("/props").json()+ assert body["endpoint_slots"] is False+ assert body["endpoint_props"] is False+ assert body["endpoint_metrics"] is False+ for child_only in ("ui", "ui_settings", "cors_proxy_enabled"):+ assert child_only not in body, child_only+ # The fields that do describe the model still come through untouched.+ assert body["total_slots"] == 4+++def test_the_denied_endpoints_props_advertises_really_are_denied():+ """Every flag set False above names a path that really 404s."""+ mod = _load()+ with _client(mod) as c:+ for path in ("/slots", "/metrics"):+ assert c.get(path).status_code == 404, path+ # POST /props is llama-server's props-change endpoint; Studio serves GET only.+ assert c.post("/props", json = {}).status_code in (404, 405)+++# ── round three ───────────────────────────────────────────────────────────────+++def test_a_transient_props_failure_does_not_report_zero_slots():+ """total_slots 0 beside a model this response advertises as loaded reads as+ "cannot serve"."""+ mod = _load(backend = _Backend(props = None, slots = 8))+ with _client(mod) as c:+ body = c.get("/props").json()+ assert body["model_path"] == "unsloth/Qwen3.8-27B-GGUF"+ assert body["total_slots"] == 8++[email protected]("slots", [0, None, "x", -1])+def test_an_unreadable_slot_count_is_omitted_rather_than_reported_as_zero(slots):+ mod = _load(backend = _Backend(props = None, slots = slots))+ with _client(mod) as c:+ body = c.get("/props").json()+ assert "total_slots" not in body, body.get("total_slots")+ assert body["model_path"] == "unsloth/Qwen3.8-27B-GGUF"+++def test_a_backend_that_raises_on_the_slot_count_still_answers():+ class _Raises(_Backend):+ # A property, not the plain attribute the base class sets, so the read itself+ # raises the way a backend mid-restart would.+ @property+ def effective_parallel_slots(self):+ raise RuntimeError("backend mid-restart")++ @effective_parallel_slots.setter+ def effective_parallel_slots(self, _value):+ pass++ mod = _load(backend = _Raises(props = None))+ with _client(mod) as c:+ r = c.get("/props")+ assert r.status_code == 200+ assert "total_slots" not in r.json()+++def test_the_upstream_slot_count_still_wins_when_it_can_be_read():+ mod = _load(backend = _Backend(props = {"total_slots": 2}, slots = 8))+ with _client(mod) as c:+ assert c.get("/props").json()["total_slots"] == 2+++ "path",+ [+ "/v1/rerank",+ "/v1/reranking",+ "/v1/chat/completions/control",+ "/v1/chat/completions/input_tokens",+ "/v1/responses/input_tokens",+ "/v1/health",+ "/v1/stream",+ "/v1/streams/lookup",+ ],+)[email protected]("method", ["HEAD", "POST", "DELETE"])+def test_unserved_v1_aliases_404_on_their_real_method(path, method):+ """GET already 404s through main.py's /v1/ rule; the rest came back 405."""+ mod = _load()+ with _client(mod) as c:+ r = c.request(method, path, json = {} if method == "POST" else None)+ assert r.status_code == 404, (method, path, r.status_code)+ assert "text/html" not in r.headers.get("content-type", ""), (method, path)+++def test_the_v1_deny_list_never_shadows_a_path_studio_serves():+ """The drift guard: implementing one of these must fail here rather than let a 404+ shadow a real route."""+ import os++ os.environ.setdefault("TMPDIR", os.environ.get("UNSLOTH_WORKSPACE", "/tmp") + "/temp")+ try:+ import main+ except Exception as exc: # noqa: BLE001+ pytest.skip(f"main.py not importable in this environment: {exc}")++ from routes.llama_compat import _probe_not_found++ def _record(into, path, endpoint):+ # This module registers its own 404 handlers on exactly these paths, so a naive+ # walk reports every one of them as served and the guard can never fire.+ if path and endpoint is not _probe_not_found:+ into.add(path)++ served = set()+ for route in main.app.routes:+ _record(served, getattr(route, "path", None), getattr(route, "endpoint", None))+ context = getattr(route, "include_context", None)+ inner = getattr(context, "included_router", None) if context is not None else None+ if inner is not None:+ prefix = getattr(context, "prefix", "")+ for sub in inner.routes:+ _record(+ served,+ (prefix + getattr(sub, "path", "")) if getattr(sub, "path", None) else None,+ getattr(sub, "endpoint", None),+ )++ assert "/v1/models" in served, "route walk found nothing; re-derive this"+ mod = _load()+ for probe in mod._UNSERVED_V1_PROBE_PATHS:+ assert (+ f"/{probe}" not in served+ ), f"Studio now serves /{probe}; drop it from _UNSERVED_V1_PROBE_PATHS"++[email protected]("path", ["/props/", "/v1/props/", "/version/"])+def test_the_trailing_slash_forms_answer_json_not_the_app_shell(path):+ """No slash redirect fires here: the catch-all fully matches "/props/", so before+ this these returned the app shell with a 200, the defect this module exists to fix."""+ mod = _load()+ with _client(mod) as c:+ r = c.get(path)+ assert r.status_code == 200, (path, r.status_code)+ assert "application/json" in r.headers["content-type"], path+++def test_the_slash_and_bare_forms_agree():+ mod = _load()+ with _client(mod) as c:+ assert c.get("/props").json() == c.get("/props/").json()+ assert c.get("/version").json() == c.get("/version/").json()diff --git a/studio/backend/utils/keyless_api_access.py b/studio/backend/utils/keyless_api_access.pyindex c6806fad4c4..31dedc2a3b2 100644--- a/studio/backend/utils/keyless_api_access.py+++ b/studio/backend/utils/keyless_api_access.py@@ -55,6 +55,12 @@ _INFERENCE_ROUTES = frozenset(("POST", "/v1/messages/count_tokens"),("GET", "/v1/models"),("POST", "/v1/responses"),+ # Discovery probes, read-only. A keyless client that may list models and chat+ # but gets 401 on /props reads that as an auth wall in front of the whole+ # surface and stops, which is the opposite of what the scope grants.+ ("GET", "/props"),+ ("GET", "/v1/props"),+ ("GET", "/version"),})