Skip to content

Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.

fix(web): keep /ws open on a bad command and answer unknown API routes with 404

rubenluetke10-beep50a2e5f9f035
diff --git a/jarvis/ui/web/server.py b/jarvis/ui/web/server.py
index 22d0472129..c8e8735a6b 100644
--- a/jarvis/ui/web/server.py
+++ b/jarvis/ui/web/server.py
@@ -25,9 +25,12 @@ from uuid import uuid4
from fastapi import FastAPI, WebSocket, WebSocketDisconnect
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import FileResponse, HTMLResponse, JSONResponse, Response
+from fastapi.routing import APIRoute
from fastapi.staticfiles import StaticFiles
from loguru import logger
-from pydantic import ValidationError
+from pydantic import BaseModel, ValidationError
+from starlette.routing import Match
+from starlette.types import Scope
from jarvis import __version__
from jarvis.core.branding import CONFIG_FILE_NAME
@@ -92,6 +95,39 @@ REALTIME_WARM_BOOT_DELAY_S = 5.0
REALTIME_WARM_TASK_NAME = "realtime-transport-warm"
+def _is_backend_path(path: str) -> bool:
+ """Paths the SPA catch-all must never claim: the API and the sockets."""
+ return path == "/api" or path.startswith(("/api/", "/ws"))
+
+
+class _SpaFallbackRoute(APIRoute):
+ """The SPA catch-all, invisible to API and socket paths.
+
+ A plain ``GET /{full_path:path}`` partially matches EVERY path, so the
+ router answered an unknown ``POST /api/...`` with 405 and ``Allow: GET`` —
+ pointing a client at a GET that does not exist — and a bare ``GET /api``
+ with the SPA's HTML. Declining backend paths lets the router answer
+ honestly: 404 for a route that does not exist, 405 only for a real route
+ asked with the wrong method.
+ """
+
+ def matches(self, scope: Scope) -> tuple[Match, Scope]:
+ if scope.get("type") == "http" and _is_backend_path(scope.get("path", "")):
+ return Match.NONE, {}
+ return super().matches(scope)
+
+
+class MemoryFactBody(BaseModel):
+ """Body of ``POST``/``DELETE /api/memory/facts``.
+
+ Typed so a non-string ``fact`` is a 422 at the boundary instead of an
+ ``AttributeError`` (500) inside the handler.
+ """
+
+ fact: str
+ category: str = "general"
+
+
class WebServer:
"""In-process uvicorn + FastAPI, run by the orchestrator loop."""
@@ -333,6 +369,8 @@ class WebServer:
from .agentic_ide_git_routes import router as agentic_ide_git_router
from .agentic_ide_routes import router as agentic_ide_router
from .antigravity_routes import router as antigravity_router
+ from .app_actions_routes import router as app_actions_router
+ from .appshot_routes import router as appshot_router
from .board_routes import (
board_router as board_meta_router,
)
@@ -364,11 +402,11 @@ class WebServer:
from .frontier_routes import router as frontier_router
from .grok_build_routes import router as grok_build_router
from .live_routes import router as live_router
- from .local_voice_routes import router as local_voice_router
from .local_models_assistant_routes import (
router as local_models_assistant_router,
)
from .local_models_routes import router as local_models_router
+ from .local_voice_routes import router as local_voice_router
from .marketplace_publish_routes import router as marketplace_publish_router
from .marketplace_routes import router as marketplace_router
from .mcp_routes import router as mcp_router
@@ -390,20 +428,18 @@ class WebServer:
from .provider_routes import router as provider_router
from .review_routes import router as review_router
from .routine_hooks_routes import router as routine_hooks_router
- from .app_actions_routes import router as app_actions_router
- from .appshot_routes import router as appshot_router
from .screen_context_routes import router as screen_context_router
from .self_mod_routes import router as self_mod_router
from .sessions_routes import router as sessions_router
from .settings_routes import router as settings_router
- from .soul_routes import router as soul_router
from .setup_report_routes import router as setup_report_router
from .setup_routes import router as setup_router
from .skills_routes import router as skills_router
from .socials_routes import router as socials_router
- from .society_routes import router as society_router
from .society_browser_routes import router as society_browser_router
from .society_figure_routes import router as society_figure_router
+ from .society_routes import router as society_router
+ from .soul_routes import router as soul_router
from .starter_plan_routes import router as starter_plan_router
from .sub_agents_routes import router as sub_agents_router
from .tasks_routes import router as tasks_router
@@ -1547,15 +1583,15 @@ class WebServer:
return {"ok": False, "error": "memory read failed. " + LOG_HINT, "data": {}}
@app.post("/api/memory/facts")
- async def add_memory_fact(payload: dict[str, Any]) -> dict[str, Any]:
+ async def add_memory_fact(payload: MemoryFactBody) -> dict[str, Any]:
"""User-driven add from the UI."""
from jarvis.core.config import DATA_DIR
from jarvis.memory import CORE_MEMORY_FILENAME, CoreMemory
from .error_text import LOG_HINT
- fact = (payload.get("fact") or "").strip()
- category = (payload.get("category") or "general").strip()
+ fact = payload.fact.strip()
+ category = payload.category.strip() or "general"
if not fact:
return {"ok": False, "error": "fact is missing"}
try:
@@ -1567,15 +1603,15 @@ class WebServer:
return {"ok": False, "error": "memory write failed. " + LOG_HINT}
@app.delete("/api/memory/facts")
- async def delete_memory_fact(payload: dict[str, Any]) -> dict[str, Any]:
+ async def delete_memory_fact(payload: MemoryFactBody) -> dict[str, Any]:
"""User-driven remove from the UI."""
from jarvis.core.config import DATA_DIR
from jarvis.memory import CORE_MEMORY_FILENAME, CoreMemory
from .error_text import LOG_HINT
- fact = (payload.get("fact") or "").strip()
- category = (payload.get("category") or "general").strip()
+ fact = payload.fact.strip()
+ category = payload.category.strip() or "general"
if not fact:
return {"ok": False, "error": "fact is missing"}
try:
@@ -1920,6 +1956,27 @@ class WebServer:
source_layer="ui.web.ws",
)
)
+ except WebSocketDisconnect:
+ # A reply frame (pong, terminal.spawned) hit a closed socket — that
+ # is the receive loop's business, not a failed command.
+ raise
+ except Exception as exc: # noqa: BLE001 — one bad frame must not end the session
+ # A handler failing on one frame (a malformed terminal.resize, a
+ # PTY write error) used to escape into _handle_ws, which closed the
+ # whole UI event socket. Report it and keep the connection.
+ action = raw.get("action") if frame_type == "command" else None
+ logger.opt(exception=exc).warning(
+ "WS frame handler failed", frame_type=frame_type, action=action
+ )
+ await self.bus.publish(
+ ErrorOccurred(
+ layer="ui.web.ws",
+ error_type="CommandFailed" if frame_type == "command" else "FrameFailed",
+ message=f"{action or frame_type} failed: {type(exc).__name__}",
+ recoverable=True,
+ source_layer="ui.web.ws",
+ )
+ )
async def _handle_command(
self,
@@ -2198,12 +2255,11 @@ class WebServer:
# up in a loop-stall stack (2026-08-26, BUG-189).
return await asyncio.to_thread(self._spa_index_response)
- @app.get("/{full_path:path}", include_in_schema=False, response_model=None)
async def _spa_fallback(
full_path: str,
) -> FileResponse | HTMLResponse | JSONResponse:
- if full_path.startswith("api/") or full_path.startswith("ws"):
- return JSONResponse({"detail": "Not Found"}, status_code=404)
+ # API and socket paths never reach this handler: _SpaFallbackRoute
+ # declines them, so the router answers 404 / 405 itself.
try:
target = (DIST_DIR / full_path).resolve()
dist_root = DIST_DIR.resolve()
@@ -2219,6 +2275,15 @@ class WebServer:
return JSONResponse({"detail": "Not Found"}, status_code=404)
return await asyncio.to_thread(self._spa_index_response)
+ app.router.add_api_route(
+ "/{full_path:path}",
+ _spa_fallback,
+ methods=["GET"],
+ include_in_schema=False,
+ response_model=None,
+ route_class_override=_SpaFallbackRoute,
+ )
+
def _spa_index_response(self) -> FileResponse | HTMLResponse:
# An index.html whose own entry bundle is not on disk is worse than no
# index.html at all: the window paints the boot splash, the module
diff --git a/tests/integration/test_rest_api.py b/tests/integration/test_rest_api.py
index ec50be2a21..ac649dc6f7 100644
--- a/tests/integration/test_rest_api.py
+++ b/tests/integration/test_rest_api.py
@@ -76,3 +76,21 @@ def test_window_focus_endpoint(web_server: WebServer) -> None:
assert body["ok"] is False
assert body.get("focused") is False
assert body.get("reason") == "no_window"
+
+
[email protected]("method", ["POST", "DELETE"])
[email protected]("body", [{"fact": 123}, {"category": "general"}, ["a fact"]])
+def test_memory_fact_body_is_validated_at_the_boundary(
+ web_server: WebServer, method: str, body: object
+) -> None:
+ # A non-string fact used to reach ``.strip()`` and answer 500.
+ with TestClient(web_server.app) as client:
+ resp = client.request(method, "/api/memory/facts", json=body)
+ assert resp.status_code == 422
+
+
+def test_memory_fact_blank_text_is_refused_without_a_write(web_server: WebServer) -> None:
+ with TestClient(web_server.app) as client:
+ resp = client.post("/api/memory/facts", json={"fact": " "})
+ assert resp.status_code == 200
+ assert resp.json() == {"ok": False, "error": "fact is missing"}
diff --git a/tests/integration/test_spa_fallback_status.py b/tests/integration/test_spa_fallback_status.py
new file mode 100644
index 0000000000..a5d6b903d6
--- /dev/null
+++ b/tests/integration/test_spa_fallback_status.py
@@ -0,0 +1,66 @@
+"""Status codes at the edge of the production SPA catch-all.
+
+The production server registers ``GET /{full_path:path}`` so client-side
+routes load the SPA. That route used to partially match every path, so an
+unknown ``POST /api/...`` got 405 with ``Allow: GET`` instead of 404, and a
+bare ``GET /api`` got the SPA's HTML with a 200. A CLI or an older frontend
+calling a removed endpoint then saw a misleading "method not allowed".
+"""
+
+from __future__ import annotations
+
+import pytest
+from fastapi.testclient import TestClient
+
+from jarvis.core.bus import EventBus
+from jarvis.core.config import JarvisConfig
+from jarvis.ui.web.server import WebServer
+
+
+def client() -> TestClient:
+ cfg = JarvisConfig()
+ cfg.ui.dev_mode = False # the SPA catch-all exists only in production mode
+ server = WebServer(cfg, bus=EventBus())
+ # The suite-wide conftest wraps TestClient with an authenticated session.
+ return TestClient(server.app)
+
+
+ ("method", "path"),
+ [
+ ("GET", "/api/no-such-route"),
+ ("POST", "/api/no-such-route"),
+ ("PUT", "/api/no-such-route/1"),
+ ("DELETE", "/api/no-such-route/1"),
+ ("GET", "/api"),
+ ],
+)
+def test_unknown_api_route_is_404_json(client: TestClient, method: str, path: str) -> None:
+ response = client.request(method, path)
+
+ assert response.status_code == 404
+ assert response.headers["content-type"].startswith("application/json")
+ assert response.json() == {"detail": "Not Found"}
+
+
+def test_real_route_with_wrong_method_is_405_naming_the_real_method(
+ client: TestClient,
+) -> None:
+ response = client.post("/api/health")
+
+ assert response.status_code == 405
+ assert response.headers["allow"] == "GET"
+
+
+def test_client_side_route_still_serves_the_spa(client: TestClient) -> None:
+ response = client.get("/settings/providers")
+
+ assert response.status_code == 200
+ assert response.headers["content-type"].startswith("text/html")
+
+
+def test_missing_asset_is_still_an_honest_404(client: TestClient) -> None:
+ response = client.get("/brand/no-such-logo.png")
+
+ assert response.status_code == 404
diff --git a/tests/integration/test_websocket_echo.py b/tests/integration/test_websocket_echo.py
index 5338ed28f0..93d87d98b5 100644
--- a/tests/integration/test_websocket_echo.py
+++ b/tests/integration/test_websocket_echo.py
@@ -158,3 +158,41 @@ def test_client_disconnect_cleans_up_subscription(web_server: WebServer) -> None
time.sleep(0.1)
after = len(web_server.bus._wildcard_subscribers) # type: ignore[attr-defined]
assert after == before, f"Leak: {before} → {after}"
+
+
+def test_failing_command_handler_keeps_the_socket_open(web_server: WebServer) -> None:
+ """One malformed command must not tear down the UI's whole event socket.
+
+ ``terminal.resize`` with a non-numeric size used to raise ``ValueError``
+ out of the frame router; the receive loop treated it as fatal and closed
+ ``/ws``, so every live view lost its event stream until a reconnect.
+ """
+ received: list[ErrorOccurred] = []
+
+ async def handler(evt: ErrorOccurred) -> None:
+ received.append(evt)
+
+ web_server.bus.subscribe(ErrorOccurred, handler)
+
+ with TestClient(web_server.app) as client:
+ with client.websocket_connect("/ws") as ws:
+ _receive_welcome(ws)
+ ws.send_json(
+ {
+ "type": "command",
+ "action": "terminal.resize",
+ "payload": {"terminal_id": "t-1", "cols": "wide", "rows": 1},
+ }
+ )
+ frame = ws.receive_json()
+ assert frame["type"] == "event"
+ assert frame["event_name"] == "ErrorOccurred"
+ assert frame["payload"]["recoverable"] is True
+
+ # The same connection still answers.
+ ws.send_json({"type": "command", "action": "ping", "payload": {"n": 7}})
+ frame = ws.receive_json()
+ assert frame["type"] == "pong"
+ assert frame["payload"] == {"n": 7}
+
+ assert [evt.error_type for evt in received] == ["CommandFailed"]