Skip to content

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.

Stop the llama-server probe deny-list answering 405 (#10049)

Daniel Han57ef43cb9443
diff --git a/studio/backend/main.py b/studio/backend/main.py
index a3f4d87e91f..3c17f831ae2 100644
--- a/studio/backend/main.py
+++ b/studio/backend/main.py
@@ -642,6 +642,16 @@ async def lifespan(app: FastAPI):
_lifespan_log = _structlog.get_logger(__name__)
clear_compiled_cache_unless_shared(app)
+ # Here because both launch paths reach it after the frontend decision: run.py calls
+ # setup_frontend(), and `uvicorn main:app` bypasses run.py entirely. With no
+ # catch-all the engine paths match on method alone and answer 405, read as "exists".
+ if not getattr(app.state, "frontend_mounted", False):
+ try:
+ from routes.llama_compat import add_get_denials
+ add_get_denials(app)
+ except Exception: # noqa: BLE001 -- never block startup over a discovery route
+ _lifespan_log.warning("could not install API-only probe denials", exc_info = True)
+
# Move the legacy sandbox up here rather than from the first request: the
# copy can be minutes when the studio home is on another filesystem.
try:
@@ -2561,4 +2571,7 @@ def setup_frontend(
# Serve index.html as bytes — avoids Content-Length mismatch
return _build_index_response(request)
+ # The catch-all above is what 404s a GET probe. The lifespan reads this to decide
+ # whether the engine paths still need their own GET denial.
+ app.state.frontend_mounted = True
return True
diff --git a/studio/backend/routes/llama_compat.py b/studio/backend/routes/llama_compat.py
index fdd5dd31a31..8ca707eab75 100644
--- a/studio/backend/routes/llama_compat.py
+++ b/studio/backend/routes/llama_compat.py
@@ -186,7 +186,9 @@ async def llama_props(current_subject: str = Depends(get_current_subject)):
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()}
+ # Threaded like /props: the first call resolves the version, which shells out to git
+ # twice on a source checkout, and that must not sit on the event loop.
+ return {"version": await asyncio.to_thread(_studio_version)}
async def _probe_not_found():
@@ -199,28 +201,51 @@ async def _probe_not_found():
# OPTIONS is untouched for CORS preflight.
_PROBE_DENIED_METHODS = ["HEAD", "POST", "PUT", "PATCH", "DELETE"]
+
+# Both forms of every path: no redirect rescues "POST /completion/", because the
+# catch-all is GET-only, so the slash form was a method mismatch and returned the 405
+# these routes exist to prevent.
+def _both_forms(path: str) -> tuple:
+ return (path, path + "/")
+
+
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,
- )
+ for _form in _both_forms(f"/{_probe_path}"):
+ router.add_api_route(
+ _form,
+ _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}/"):
+ for _form in _both_forms(f"/{_v1_path}"):
+ router.add_api_route(
+ _form,
+ _probe_not_found,
+ methods = _PROBE_DENIED_METHODS,
+ include_in_schema = False,
+ )
+
+for _slots_form in _both_forms("/slots/{id_slot}"):
router.add_api_route(
_slots_form,
_probe_not_found,
methods = _PROBE_DENIED_METHODS,
include_in_schema = False,
)
+
+
+def add_get_denials(app) -> None:
+ """404 the engine paths on GET as well, for an app with no frontend mounted.
+
+ The GET denial normally comes from main.py's SPA catch-all, registered only when
+ setup_frontend() finds a build. In API-only mode there is none, so these paths
+ matched on method alone and answered 405, which a client reads as "endpoint exists".
+ """
+ for path in sorted(_ENGINE_PROBE_PATHS) + sorted(_UNSERVED_V1_PROBE_PATHS):
+ for form in _both_forms(f"/{path}"):
+ app.add_api_route(form, _probe_not_found, methods = ["GET"], include_in_schema = False)
+ for form in _both_forms("/slots/{id_slot}"):
+ app.add_api_route(form, _probe_not_found, methods = ["GET"], include_in_schema = False)
diff --git a/studio/backend/tests/test_llama_compat_routes.py b/studio/backend/tests/test_llama_compat_routes.py
index f9a594717b8..94550876224 100644
--- a/studio/backend/tests/test_llama_compat_routes.py
+++ b/studio/backend/tests/test_llama_compat_routes.py
@@ -707,3 +707,130 @@ def test_the_slash_and_bare_forms_agree():
with _client(mod) as c:
assert c.get("/props").json() == c.get("/props/").json()
assert c.get("/version").json() == c.get("/version/").json()
+
+
+# ── 405 leaks the same signal a 200 did ───────────────────────────────────────
+
+
+def _lifespan_app(mod, *, frontend_mounted = False):
+ """An app wired the way main.py wires one: installed at startup, because that is
+ the point both launch paths reach after the frontend decision."""
+ from contextlib import asynccontextmanager
+
+ @asynccontextmanager
+ async def lifespan(app):
+ if not getattr(app.state, "frontend_mounted", False):
+ mod.add_get_denials(app)
+ yield
+
+ app = FastAPI(lifespan = lifespan)
+ app.include_router(mod.router)
+ if frontend_mounted:
+ app.state.frontend_mounted = True
+ app.dependency_overrides[mod.get_current_subject] = lambda: "test"
+ return app
+
+
+def _api_only_client(mod):
+ return TestClient(_lifespan_app(mod))
+
+
+def _directly_added_get_paths(app):
+ """Paths the app itself registered for GET. include_router() is lazy in this FastAPI
+ (routes stay behind an _IncludedRouter), so this sees only add_api_route() calls."""
+ return {
+ r.path
+ for r in app.routes
+ if getattr(r, "methods", None) and "GET" in r.methods and hasattr(r, "path")
+ }
+
+
+def test_the_denials_are_installed_only_when_no_frontend_is_mounted():
+ """So an app already serving a catch-all does not carry a second, dead copy of
+ every engine path. Ordering, not this flag, is what keeps assets reachable."""
+ mod = _load()
+ with TestClient(_lifespan_app(mod, frontend_mounted = False)):
+ pass
+ unmounted = _directly_added_get_paths(_started(_lifespan_app(mod, frontend_mounted = False)))
+ mounted = _directly_added_get_paths(_started(_lifespan_app(mod, frontend_mounted = True)))
+ assert "/completion" in unmounted, "API-only mode must gain the GET denial"
+ assert "/completion" not in mounted, "a mounted frontend must not gain a second copy"
+
+
+def _started(app):
+ with TestClient(app):
+ pass
+ return app
+
+
+ "method, path",
+ [
+ ("POST", "/completion/"),
+ ("HEAD", "/metrics/"),
+ ("PUT", "/tokenize/"),
+ ("DELETE", "/slots/"),
+ ("POST", "/v1/rerank/"),
+ ("POST", "/v1/health/"),
+ ("POST", "/slots/3/"),
+ ],
+)
+def test_the_slash_form_of_a_denied_path_404s_rather_than_405(method, path):
+ """405 says "endpoint exists, wrong method", which is the signal this module removes.
+ No redirect rescues these: the catch-all is GET-only, so the slash form matched it on
+ path and missed on method."""
+ mod = _load()
+ with _client(mod) as c:
+ r = c.request(method, path)
+ assert r.status_code == 404, (method, path, r.status_code)
+
+
+ "path",
+ ["/completion", "/completion/", "/health", "/metrics", "/slots", "/v1/health", "/slots/3"],
+)
+def test_a_get_probe_404s_in_api_only_mode(path):
+ """--api-only mounts no frontend, so the catch-all that supplies the GET 404 is not
+ registered and these answered 405 on method alone."""
+ mod = _load()
+ with _api_only_client(mod) as c:
+ r = c.get(path)
+ assert r.status_code == 404, (path, r.status_code)
+
+
+def test_api_only_mode_still_serves_the_three_real_routes():
+ mod = _load()
+ with _api_only_client(mod) as c:
+ 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
+
+
+def test_the_get_denials_are_not_added_when_a_frontend_is_mounted():
+ """A shipped asset named like an engine path must still be served by the catch-all,
+ so the GET denial is added only for an app that has no catch-all at all."""
+ mod = _load()
+ app = FastAPI()
+ app.include_router(mod.router)
+
+ @app.get("/{full_path:path}")
+ async def _spa(full_path: str):
+ return Response(content = b"asset", media_type = "text/plain")
+
+ app.dependency_overrides[mod.get_current_subject] = lambda: "test"
+ with TestClient(app) as c:
+ assert c.post("/completion").status_code == 404, "sanity: the deny route is live"
+ r = c.get("/completion")
+ assert (
+ r.status_code == 200 and r.content == b"asset"
+ ), "the router claimed GET, so a shipped asset by that name became unreachable"
+
+
+def test_the_version_lookup_leaves_the_event_loop():
+ """get_studio_version() shells out to git twice on a source checkout; on the event
+ loop that stalls every other request, including the launcher's health probe."""
+ import inspect
+
+ src = inspect.getsource(_load().studio_version)
+ assert "to_thread" in src, "the version handler must resolve off the event loop"
diff --git a/studio/backend/tests/test_middleware.py b/studio/backend/tests/test_middleware.py
index ac23c84c5d9..859ba956d1e 100644
--- a/studio/backend/tests/test_middleware.py
+++ b/studio/backend/tests/test_middleware.py
@@ -921,6 +921,18 @@ class TestResearchPortMiddleware:
class TestFrontendAssets:
+ def test_setup_frontend_records_whether_a_catch_all_exists(self, tmp_path, main_module):
+ """The lifespan reads this to decide whether the engine paths still need their own
+ GET denial: without a catch-all they match on method alone and answer 405."""
+ app = FastAPI()
+ assert not main_module.setup_frontend(app, tmp_path / "missing")
+ assert not getattr(app.state, "frontend_mounted", False)
+
+ (tmp_path / "index.html").write_text("<!doctype html><title>x</title>")
+ mounted = FastAPI()
+ assert main_module.setup_frontend(mounted, tmp_path)
+ assert mounted.state.frontend_mounted is True
+
def test_desktop_frontend_is_available_only_through_live_tunnel(self, tmp_path, main_module):
(tmp_path / "index.html").write_text("<!doctype html><title>remote</title>")
assets = tmp_path / "assets"