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.

feat(local-models): assistant routes (run / session / test / benchmarks / health) and the CLI group

rubenluetke10-beep19de69fd4d10
diff --git a/docs/jarvis-cli-reference.md b/docs/jarvis-cli-reference.md
index a14b39b3e7..e18266d2ea 100644
--- a/docs/jarvis-cli-reference.md
+++ b/docs/jarvis-cli-reference.md
@@ -113,6 +113,12 @@ _Generated from the curated command tree by `scripts/ci/gen_cli_reference.py`
## local-models
+- `jarvis local-models assistant benchmarks --refresh --provider` — The benchmark table behind the proven / new labels (cached seven days).
+- `jarvis local-models assistant diagnose --provider` — Ask the assistant what is broken and how to fix it.
+- `jarvis local-models assistant health --provider` — The last self-check: status, reason, since when, last ok.
+- `jarvis local-models assistant session --provider` — The assistant's session and whether the Agents tier can run it.
+- `jarvis local-models assistant setup --provider` — Start a guided setup turn; answers with the session and turn ids.
+- `jarvis local-models assistant test --role --provider` — Run the end-to-end setup test and print the per-role table.
- `jarvis local-models catalog recommended --provider` — The curated shortlist ranked for this machine, with its review date.
- `jarvis local-models catalog search <query> --sort --capability --limit --provider` — Browse the library; offline is reported as a sentence, not a failure.
- `jarvis local-models catalog tags <name> --provider` — Every tag of one library model with size, quantization, context and fit.
@@ -136,7 +142,6 @@ _Generated from the curated command tree by `scripts/ci/gen_cli_reference.py`
- `jarvis local-models server stop --provider --yes --dry-run` — Stop the server Jarvis itself started (never one started elsewhere).
- `jarvis local-models server test <base_url> --provider` — Probe a host before saving it: version and latency, or why it failed.
-
## marketplace
- `jarvis marketplace browse` — Show everything the community marketplace offers, and what you already have.
diff --git a/docs/jarvis-cli.md b/docs/jarvis-cli.md
index 3340cc3f50..8dfc4d5f6f 100644
--- a/docs/jarvis-cli.md
+++ b/docs/jarvis-cli.md
@@ -138,6 +138,10 @@ jarvis local-models hf search "llama 3.1 gguf"
jarvis local-models hf files bartowski Llama-3.1-8B-Instruct-GGUF
jarvis local-models hf pull bartowski Llama-3.1-8B-Instruct-GGUF --quant Q4_K_M
jarvis local-models server status
+jarvis local-models assistant setup # the setup assistant proposes one complete setup
+jarvis local-models assistant diagnose # names what is broken and the smallest fix
+jarvis local-models assistant test # end-to-end test: one line per role, ok / error
+jarvis local-models assistant health # the last self-check (status, reason, since)
jarvis local-models server test http://127.0.0.1:11434
jarvis local-models server log --lines 80
jarvis local-models server env-guide --os linux
diff --git a/jarvis/cli_ctl/command_index.py b/jarvis/cli_ctl/command_index.py
index 48893a5d6b..44a9ca96a3 100644
--- a/jarvis/cli_ctl/command_index.py
+++ b/jarvis/cli_ctl/command_index.py
@@ -155,6 +155,12 @@ COMMAND_INDEX: dict[str, tuple[str, ...]] = {
"server test <url>",
"server log [--lines]",
"server env-guide [--os]",
+ "assistant setup",
+ "assistant diagnose",
+ "assistant test [--role]",
+ "assistant benchmarks [--refresh]",
+ "assistant health",
+ "assistant session",
),
"marketplace": (
"install <id>",
diff --git a/jarvis/cli_ctl/commands/local_models.py b/jarvis/cli_ctl/commands/local_models.py
index 8e290e71a2..ee1e9ae7e2 100644
--- a/jarvis/cli_ctl/commands/local_models.py
+++ b/jarvis/cli_ctl/commands/local_models.py
@@ -402,3 +402,69 @@ def server_env_guide(
"""Copyable per-OS commands for the server's environment variables."""
params = {"os": os_name.strip()} if os_name.strip() else None
invoke.run("GET", f"{_base(provider)}/server/env-guide", params=params)
+
+
+# ----------------------------------------------------------------------
+# assistant
+# ----------------------------------------------------------------------
+
+assistant_app = typer.Typer(
+ no_args_is_help=True,
+ help="The setup assistant: guided setup, diagnosis, the end-to-end test, benchmarks, health.",
+)
+app.add_typer(assistant_app, name="assistant")
+
+
+_ROLE_FILTER = typer.Option(
+ [],
+ "--role",
+ help="Restrict to a role (repeatable): chat, voice, tools_screen, deep, embedding.",
+)
+
+
+def _assistant(provider: str) -> str:
+ return f"{_base(provider)}/assistant"
+
+
+@assistant_app.command("setup")
+def assistant_setup(provider: str = _PROVIDER) -> None:
+ """Start a guided setup turn; answers with the session and turn ids."""
+ invoke.run("POST", f"{_assistant(provider)}/run", body={"mode": "setup"}, dangerous=False)
+
+
+@assistant_app.command("diagnose")
+def assistant_diagnose(provider: str = _PROVIDER) -> None:
+ """Ask the assistant what is broken and how to fix it."""
+ invoke.run("POST", f"{_assistant(provider)}/run", body={"mode": "diagnose"}, dangerous=False)
+
+
+@assistant_app.command("test")
+def assistant_test(
+ roles: list[str] = _ROLE_FILTER,
+ provider: str = _PROVIDER,
+) -> None:
+ """Run the end-to-end setup test and print the per-role table."""
+ body = {"roles": list(roles)} if roles else None
+ invoke.run("POST", f"{_assistant(provider)}/test", body=body, dangerous=False)
+
+
+@assistant_app.command("benchmarks")
+def assistant_benchmarks(
+ refresh: bool = typer.Option(False, "--refresh", help="Rebuild the table from the web."),
+ provider: str = _PROVIDER,
+) -> None:
+ """The benchmark table behind the proven / new labels (cached seven days)."""
+ params = {"refresh": "1"} if refresh else None
+ invoke.run("GET", f"{_assistant(provider)}/benchmarks", params=params)
+
+
+@assistant_app.command("health")
+def assistant_health(provider: str = _PROVIDER) -> None:
+ """The last self-check: status, reason, since when, last ok."""
+ invoke.run("GET", f"{_assistant(provider)}/health")
+
+
+@assistant_app.command("session")
+def assistant_session(provider: str = _PROVIDER) -> None:
+ """The assistant's session and whether the Agents tier can run it."""
+ invoke.run("GET", f"{_assistant(provider)}/session")
diff --git a/jarvis/local_models/assistant_session.py b/jarvis/local_models/assistant_session.py
new file mode 100644
index 0000000000..4d1dcb1667
--- /dev/null
+++ b/jarvis/local_models/assistant_session.py
@@ -0,0 +1,134 @@
+"""Session policy of the setup assistant: one chat per install, on the Agents tier.
+
+The assistant is a ``local-models`` agent-chat session. It runs on the
+Jarvis-Agents tier (``[brain.worker]`` provider / model, the fallback pair
+when the primary is unknown to the chat) — never on the voice brain, so a
+person whose voice runs on Ollama still gets a capable cloud model to set
+Ollama up. There is ONE session per install: the routes reuse the newest
+``local-models`` session and re-create it only when the worker tier moved.
+
+No usable Agents-tier credential → an honest refusal (:data:`NOT_READY`),
+never a silent fallback onto another tier.
+"""
+
+from __future__ import annotations
+
+import logging
+from collections.abc import Callable
+from dataclasses import dataclass
+from typing import Any, Final
+
+log = logging.getLogger(__name__)
+
+__all__ = [
+ "NOT_READY",
+ "SURFACE",
+ "AgentsTier",
+ "agents_tier",
+ "ensure_session",
+ "session_state",
+]
+
+SURFACE: Final[str] = "local-models"
+NOT_READY: Final[str] = "Connect the Jarvis Agents tier first — the setup assistant runs on it."
+
+
+@dataclass(frozen=True, slots=True)
+class AgentsTier:
+ provider: str
+ model: str
+ ready: bool
+ reason: str
+
+
+def _known(provider: str) -> bool:
+ from jarvis.agent_chat.catalog import provider_row
+ from jarvis.agent_chat.runner_api import supports_api_runner
+
+ return provider_row(provider) is not None or supports_api_runner(provider)
+
+
+def _default_usable(provider: str) -> bool:
+ from jarvis.core.config import get_jarvis_agent_secret
+
+ try:
+ return bool(get_jarvis_agent_secret(provider))
+ except Exception: # noqa: BLE001 — no credential readable counts as none
+ log.debug("agents tier: credential lookup for %s failed", provider, exc_info=True)
+ return False
+
+
+def agents_tier(cfg: Any, *, usable: Callable[[str], bool] | None = None) -> AgentsTier:
+ """The pair the assistant runs on and whether it can run right now.
+
+ ``usable(provider)`` is the credential / login probe; the routes pass the
+ provider-agnostic worker check the API-keys page uses, the default reads
+ the Agents-tier secret.
+ """
+ brain = getattr(cfg, "brain", None)
+ worker = getattr(brain, "worker", None)
+ provider = str(getattr(worker, "provider", "") or "").strip()
+ model = str(getattr(worker, "model", "") or "").strip()
+ if not provider or not _known(provider):
+ fallback = str(getattr(worker, "fallback_provider", "") or "").strip()
+ if fallback and _known(fallback):
+ provider = fallback
+ model = str(getattr(worker, "fallback_model", "") or "").strip()
+ if not provider:
+ return AgentsTier("", "", False, NOT_READY)
+ if not _known(provider):
+ return AgentsTier(provider, model, False, NOT_READY)
+ probe = usable or _default_usable
+ try:
+ ok = bool(probe(provider))
+ except Exception: # noqa: BLE001 — a failing probe is "not ready", with the reason logged
+ log.info("agents tier: usability probe for %s failed", provider, exc_info=True)
+ ok = False
+ return AgentsTier(provider, model, ok, "" if ok else NOT_READY)
+
+
+def _current(svc: Any) -> Any | None:
+ sessions = svc.store.list_sessions(limit=1, surface=SURFACE)
+ return sessions[0] if sessions else None
+
+
+def session_state(svc: Any, cfg: Any, *, usable: Callable[[str], bool] | None = None) -> dict:
+ """``GET /session``: the session id (or null), the pair, readiness, reason."""
+ tier = agents_tier(cfg, usable=usable)
+ current = _current(svc)
+ matches = (
+ current is not None
+ and current.provider == tier.provider
+ and (not tier.model or current.model == tier.model)
+ )
+ return {
+ "session_id": current.session_id if matches and current is not None else None,
+ "surface": SURFACE,
+ "provider": tier.provider,
+ "model": tier.model,
+ "ready": tier.ready,
+ "reason": tier.reason,
+ }
+
+
+def ensure_session(svc: Any, cfg: Any, *, usable: Callable[[str], bool] | None = None) -> Any:
+ """The one ``local-models`` session, created or re-created for the current pair.
+
+ Raises ``PermissionError(NOT_READY)`` when the Agents tier cannot run.
+ """
+ tier = agents_tier(cfg, usable=usable)
+ if not tier.ready:
+ raise PermissionError(tier.reason or NOT_READY)
+ current = _current(svc)
+ if (
+ current is not None
+ and current.provider == tier.provider
+ and (not tier.model or current.model == tier.model)
+ ):
+ return current
+ return svc.create_session(
+ provider=tier.provider,
+ model=tier.model,
+ title="Local models setup",
+ surface=SURFACE,
+ )
diff --git a/jarvis/ui/web/local_models_assistant_routes.py b/jarvis/ui/web/local_models_assistant_routes.py
new file mode 100644
index 0000000000..afe8a9e425
--- /dev/null
+++ b/jarvis/ui/web/local_models_assistant_routes.py
@@ -0,0 +1,192 @@
+"""REST for the Local models setup assistant.
+
+ POST /api/providers/{provider_id}/local-models/assistant/run start a guided turn
+ GET /api/providers/{provider_id}/local-models/assistant/session the one session + tier
+ POST /api/providers/{provider_id}/local-models/assistant/test end-to-end setup test
+ GET /api/providers/{provider_id}/local-models/assistant/benchmarks the proven/new table
+ GET /api/providers/{provider_id}/local-models/assistant/health the badge record
+
+The assistant is a ``local-models`` agent-chat session (the timeline, the
+WebSocket stream and the approval cards are the agent chat's — see
+``agent_chat_routes.py``); these routes only start it with the canned opener
+of a mode and expose the runner, the benchmark table and the health file.
+Every handler sits behind the pull-capability gate the section uses
+(``provider_routes._require_pull_capable``). ``/run`` answers 409 with one
+English sentence when the Jarvis-Agents tier cannot run — never a silent
+fallback.
+"""
+
+from __future__ import annotations
+
+import logging
+from typing import Any, Literal
+
+from fastapi import APIRouter, HTTPException, Request
+from pydantic import BaseModel, Field
+
+from jarvis.ui.web.agent_chat_routes import _service_from_state
+from jarvis.ui.web.provider_routes import (
+ _require_pull_capable,
+ _resolve_cfg,
+ _worker_flagged_dead,
+ _worker_usable,
+)
+
+log = logging.getLogger(__name__)
+
+router = APIRouter(
+ prefix="/api/providers/{provider_id}/local-models/assistant",
+ tags=["local-models-assistant"],
+)
+
+Mode = Literal["setup", "diagnose", "test"]
+
+
+class RunBody(BaseModel):
+ mode: Mode = "setup"
+
+
+class RunResponse(BaseModel):
+ session_id: str
+ turn_id: str
+ surface: str = "local-models"
+
+
+class SessionResponse(BaseModel):
+ session_id: str | None
+ surface: str = "local-models"
+ provider: str
+ model: str
+ ready: bool
+ reason: str
+
+
+class TestBody(BaseModel):
+ roles: list[str] | None = Field(default=None, description="Subset of the writable roles.")
+
+
+class HealthResponse(BaseModel):
+ status: str
+ reason: str
+ since: str | None = None
+ last_ok: str | None = None
+ checked_at: str | None = None
+
+
+def _opener(mode: str) -> str:
+ from jarvis.local_models.assistant_prompt import (
+ DIAGNOSE_OPENER,
+ SETUP_OPENER,
+ TEST_OPENER,
+ )
+
+ return {"setup": SETUP_OPENER, "diagnose": DIAGNOSE_OPENER, "test": TEST_OPENER}[mode]
+
+
+def _usable(provider: str) -> bool:
+ """The provider-agnostic worker check the API-keys page uses."""
+ from jarvis.local_models.assistant_session import _default_usable
+
+ return (_worker_usable(provider) or _default_usable(provider)) and not _worker_flagged_dead(
+ provider
+ )
+
+
+def _svc(request: Request) -> Any:
+ svc = _service_from_state(request.app.state)
+ if svc is None:
+ raise HTTPException(status_code=503, detail="agent-chat-unavailable")
+ return svc
+
+
+def _cfg(request: Request) -> Any:
+ cfg = _resolve_cfg(request)
+ if cfg is None:
+ raise HTTPException(status_code=503, detail="Configuration is unavailable (headless mode?)")
+ return cfg
+
+
[email protected]("/run", response_model=RunResponse)
+async def post_run(provider_id: str, body: RunBody, request: Request) -> RunResponse:
+ """Start a guided turn: ensure the one session, send the mode's opener."""
+ from jarvis.agent_chat.service import SessionBusy
+ from jarvis.local_models.assistant_session import ensure_session
+
+ _require_pull_capable(provider_id)
+ cfg = _cfg(request)
+ svc = _svc(request)
+ try:
+ session = ensure_session(svc, cfg, usable=_usable)
+ except PermissionError as exc:
+ raise HTTPException(status_code=409, detail=str(exc)) from exc
+ except ValueError as exc:
+ raise HTTPException(status_code=409, detail=str(exc)) from exc
+ try:
+ turn_id = await svc.send(session.session_id, _opener(body.mode))
+ except SessionBusy as exc:
+ raise HTTPException(
+ status_code=409, detail="The assistant is still answering; wait for that turn."
+ ) from exc
+ return RunResponse(session_id=session.session_id, turn_id=turn_id)
+
+
[email protected]("/session", response_model=SessionResponse)
+async def get_session(provider_id: str, request: Request) -> SessionResponse:
+ """The one ``local-models`` session (or null) and whether the tier can run."""
+ from jarvis.local_models.assistant_session import session_state
+
+ _require_pull_capable(provider_id)
+ cfg = _cfg(request)
+ svc = _svc(request)
+ return SessionResponse(**session_state(svc, cfg, usable=_usable))
+
+
+async def post_test(provider_id: str, request: Request, body: TestBody | None = None) -> dict:
+ """Run the end-to-end setup test and persist the report."""
+ from jarvis.local_models.assistant_test import run_setup_test
+
+ _require_pull_capable(provider_id)
+ cfg = _cfg(request)
+ roles = tuple(body.roles) if body is not None and body.roles else None
+ try:
+ report = await run_setup_test(cfg, roles)
+ except ValueError as exc:
+ raise HTTPException(status_code=400, detail=str(exc)) from exc
+ return report.to_payload()
+
+
[email protected]("/benchmarks")
+async def get_benchmarks(provider_id: str, request: Request, refresh: bool = False) -> dict:
+ """The benchmark table; ``refresh=1`` rebuilds it through the brain's web search."""
+ from jarvis.local_models import benchmarks
+
+ _require_pull_capable(provider_id)
+ table: benchmarks.BenchmarkTable | None
+ if refresh:
+ from jarvis.agent_chat.runner_brain import brain_manager
+ from jarvis.agent_chat.surface_kits import local_models_search_fn
+
+ search_fn = local_models_search_fn(brain_manager())
+ if search_fn is None:
+ raise HTTPException(
+ status_code=503, detail="Web search is not available yet; try again shortly."
+ )
+ table = await benchmarks.refresh_benchmarks(search_fn)
+ else:
+ table = benchmarks.load_cached() or benchmarks.curated_only(
+ "No benchmark cache yet; refresh=1 builds one."
+ )
+ return table.to_payload()
+
+
[email protected]("/health", response_model=HealthResponse)
+async def get_health(provider_id: str) -> HealthResponse:
+ """The persisted badge record — a file read, no live call."""
+ from jarvis.local_models.health_monitor import read_health_record
+
+ _require_pull_capable(provider_id)
+ return HealthResponse(**read_health_record())
+
+
+__all__ = ["router"]
diff --git a/tests/unit/cli_ctl/test_commands_local_models_assistant.py b/tests/unit/cli_ctl/test_commands_local_models_assistant.py
new file mode 100644
index 0000000000..379f4de0dd
--- /dev/null
+++ b/tests/unit/cli_ctl/test_commands_local_models_assistant.py
@@ -0,0 +1,58 @@
+"""`jarvis local-models assistant ...` hits the assistant routes with the exact bodies."""
+
+from __future__ import annotations
+
+import pytest
+from typer.testing import CliRunner
+
+from jarvis.cli_ctl.__main__ import app
+
+runner = CliRunner()
+_BASE = "/api/providers/ollama/local-models/assistant"
+
+
+def _one(capture_api) -> dict:
+ assert len(capture_api["calls"]) == 1, capture_api["calls"]
+ return capture_api["calls"][0]
+
+
[email protected]("mode", ["setup", "diagnose"])
+def test_run_modes_post_without_a_confirmation(capture_api, mode: str) -> None:
+ res = runner.invoke(app, ["local-models", "assistant", mode])
+ assert res.exit_code == 0, res.output
+ call = _one(capture_api)
+ assert (call["method"], call["path"]) == ("POST", f"{_BASE}/run")
+ assert call["body"] == {"mode": mode}
+
+
+def test_test_posts_the_role_filter(capture_api) -> None:
+ argv = ["local-models", "assistant", "test", "--role", "chat", "--role", "deep"]
+ res = runner.invoke(app, argv)
+ assert res.exit_code == 0, res.output
+ call = _one(capture_api)
+ assert (call["method"], call["path"]) == ("POST", f"{_BASE}/test")
+ assert call["body"] == {"roles": ["chat", "deep"]}
+
+
+def test_test_without_roles_sends_no_body(capture_api) -> None:
+ res = runner.invoke(app, ["local-models", "assistant", "test"])
+ assert res.exit_code == 0, res.output
+ assert _one(capture_api)["body"] is None
+
+
+def test_benchmarks_health_and_session_are_gets(capture_api) -> None:
+ res = runner.invoke(app, ["local-models", "assistant", "benchmarks", "--refresh"])
+ assert res.exit_code == 0, res.output
+ call = _one(capture_api)
+ assert (call["method"], call["path"]) == ("GET", f"{_BASE}/benchmarks")
+ assert call["query"] == {"refresh": "1"}
+
+ capture_api["calls"].clear()
+ res = runner.invoke(app, ["local-models", "assistant", "health", "--provider", "llamacpp"])
+ assert res.exit_code == 0, res.output
+ assert _one(capture_api)["path"] == "/api/providers/llamacpp/local-models/assistant/health"
+
+ capture_api["calls"].clear()
+ res = runner.invoke(app, ["local-models", "assistant", "session"])
+ assert res.exit_code == 0, res.output
+ assert (_one(capture_api)["method"], _one(capture_api)["path"]) == ("GET", f"{_BASE}/session")
diff --git a/tests/unit/local_models/test_assistant_session.py b/tests/unit/local_models/test_assistant_session.py
new file mode 100644
index 0000000000..27f8e70632
--- /dev/null
+++ b/tests/unit/local_models/test_assistant_session.py
@@ -0,0 +1,78 @@
+"""Session policy: the Agents-tier pair, one session per install, an honest refusal."""
+
+from __future__ import annotations
+
+import pytest
+
+from jarvis.agent_chat.service import AgentChatService
+from jarvis.agent_chat.store import AgentChatStore
+from jarvis.core.config import BrainTierConfig, JarvisConfig
+from jarvis.local_models import assistant_session as policy
+
+
+def _cfg(provider: str = "openai", model: str = "gpt-x", **fallback: str) -> JarvisConfig:
+ cfg = JarvisConfig()
+ cfg.brain.worker = BrainTierConfig(provider=provider, model=model, **fallback)
+ return cfg
+
+
+def _svc() -> AgentChatService:
+ return AgentChatService(AgentChatStore(":memory:"))
+
+
+def test_tier_is_the_worker_pair_and_ready_only_with_a_credential() -> None:
+ ready = policy.agents_tier(_cfg(), usable=lambda p: p == "openai")
+ assert (ready.provider, ready.model, ready.ready, ready.reason) == ("openai", "gpt-x", True, "")
+ blocked = policy.agents_tier(_cfg(), usable=lambda _p: False)
+ assert blocked.ready is False and blocked.reason == policy.NOT_READY
+
+
+def test_unknown_primary_falls_back_to_the_fallback_pair() -> None:
+ cfg = _cfg("some-cli-only-thing", "m", fallback_provider="gemini", fallback_model="g-2")
+ tier = policy.agents_tier(cfg, usable=lambda _p: True)
+ assert (tier.provider, tier.model) == ("gemini", "g-2")
+
+
+def test_no_worker_tier_is_not_ready() -> None:
+ cfg = JarvisConfig()
+ cfg.brain.worker = None
+ tier = policy.agents_tier(cfg, usable=lambda _p: True)
+ assert tier.ready is False and tier.reason == policy.NOT_READY
+
+
+def test_ensure_session_creates_once_and_recreates_when_the_tier_moves() -> None:
+ svc = _svc()
+ cfg = _cfg()
+ first = policy.ensure_session(svc, cfg, usable=lambda _p: True)
+ again = policy.ensure_session(svc, cfg, usable=lambda _p: True)
+ assert first.session_id == again.session_id
+ assert first.surface == "local-models" and first.provider == "openai"
+ assert first.permission_mode == "ask"
+
+ moved = policy.ensure_session(svc, _cfg(model="gpt-y"), usable=lambda _p: True)
+ assert moved.session_id != first.session_id and moved.model == "gpt-y"
+ assert len(svc.store.list_sessions(surface="local-models")) == 2
+
+
+def test_ensure_session_refuses_without_the_tier() -> None:
+ svc = _svc()
+ with pytest.raises(PermissionError, match="Connect the Jarvis Agents tier first"):
+ policy.ensure_session(svc, _cfg(), usable=lambda _p: False)
+ assert svc.store.list_sessions(surface="local-models") == []
+
+
+def test_session_state_shape() -> None:
+ svc = _svc()
+ cfg = _cfg()
+ assert policy.session_state(svc, cfg, usable=lambda _p: True) == {
+ "session_id": None,
+ "surface": "local-models",
+ "provider": "openai",
+ "model": "gpt-x",
+ "ready": True,
+ "reason": "",
+ }
+ session = policy.ensure_session(svc, cfg, usable=lambda _p: True)
+ state = policy.session_state(svc, cfg, usable=lambda _p: False)
+ assert state["session_id"] == session.session_id
+ assert state["ready"] is False and state["reason"] == policy.NOT_READY
diff --git a/tests/unit/ui/web/test_local_models_assistant_routes.py b/tests/unit/ui/web/test_local_models_assistant_routes.py
new file mode 100644
index 0000000000..b28b2bbbc2
--- /dev/null
+++ b/tests/unit/ui/web/test_local_models_assistant_routes.py
@@ -0,0 +1,191 @@
+"""The assistant routes: run / session / test / benchmarks / health behind the pull gate.
+
+The agent-chat service is real (in-memory store); the brain turn is not run
+— ``send`` is observed through the service's own store events. The Ollama
+server is the fake; the Agents-tier check is injected by patching the routes'
+``_usable`` seam (a plain function, not a mock library).
+"""
+
+from __future__ import annotations
+
+import json
+from pathlib import Path
+
+import httpx
+import pytest
+from fastapi.testclient import TestClient
+
+from jarvis.agent_chat.service import AgentChatService
+from jarvis.agent_chat.store import AgentChatStore
+from jarvis.brain import ollama_inventory, ollama_runtime
+from jarvis.core import config as cfg_mod
+from jarvis.core.bus import EventBus
+from jarvis.core.config import BrainProviderConfig, BrainTierConfig, JarvisConfig
+from jarvis.local_models.assistant_prompt import DIAGNOSE_OPENER, SETUP_OPENER
+from jarvis.local_models.assistant_session import NOT_READY
+from jarvis.ui.web import local_models_assistant_routes as routes
+from jarvis.ui.web.server import WebServer
+from tests.fakes.fake_ollama_server import FakeOllamaServer
+
+BASE = "/api/providers/ollama/local-models/assistant"
+
+
+def fake(monkeypatch: pytest.MonkeyPatch) -> FakeOllamaServer:
+ server = FakeOllamaServer()
+ server.add("embeddinggemma", capabilities=("embedding",), embed_dim=768)
+
+ def _client(transport: httpx.AsyncBaseTransport | None = None) -> httpx.AsyncClient:
+ return httpx.AsyncClient(transport=server.transport(), timeout=5.0)
+
+ monkeypatch.setattr(ollama_inventory, "_make_client", _client)
+
+ real_probe = ollama_runtime.probe_host
+
+ async def _probe(base_url: str, *, transport=None) -> dict:
+ return await real_probe(base_url, transport=server.transport())
+
+ monkeypatch.setattr(ollama_runtime, "probe_host", _probe)
+ return server
+
+
+def server(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> WebServer:
+ monkeypatch.setenv("JARVIS_DATA_DIR", str(tmp_path))
+ monkeypatch.setattr(cfg_mod, "DATA_DIR", tmp_path)
+ cfg = JarvisConfig()
+ cfg.ui.dev_mode = True
+ cfg.brain.providers["ollama"] = BrainProviderConfig(base_url="http://fake:11434")
+ cfg.brain.worker = BrainTierConfig(provider="openai", model="gpt-x")
+ cfg.ultrawiki.embedding_provider = "ollama"
+ cfg.ultrawiki.embedding_model = "embeddinggemma"
+ srv = WebServer(cfg, bus=EventBus())
+ srv.app.state.config = cfg
+ srv.app.state.agent_chat = AgentChatService(AgentChatStore(":memory:"))
+ return srv
+
+
+def ready(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(routes, "_usable", lambda _p: True)
+
+
+def test_routes_sit_behind_the_pull_gate(server: WebServer) -> None:
+ with TestClient(server.app) as client:
+ assert client.get("/api/providers/openai/local-models/assistant/health").status_code == 400
+ assert client.get("/api/providers/nope/local-models/assistant/session").status_code == 404
+
+
+def test_session_is_null_until_a_run_and_names_the_tier(server: WebServer, ready: None) -> None:
+ with TestClient(server.app) as client:
+ body = client.get(f"{BASE}/session").json()
+ assert body == {
+ "session_id": None,
+ "surface": "local-models",
+ "provider": "openai",
+ "model": "gpt-x",
+ "ready": True,
+ "reason": "",
+ }
+
+
+def test_run_refuses_honestly_without_the_agents_tier(
+ server: WebServer, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ monkeypatch.setattr(routes, "_usable", lambda _p: False)
+ with TestClient(server.app) as client:
+ resp = client.post(f"{BASE}/run", json={"mode": "setup"})
+ assert resp.status_code == 409
+ assert resp.json()["detail"] == NOT_READY
+ assert client.get(f"{BASE}/session").json()["ready"] is False
+ assert server.app.state.agent_chat.store.list_sessions(surface="local-models") == []
+
+
+def test_run_creates_one_session_and_sends_the_mode_opener(
+ server: WebServer, ready: None, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ svc: AgentChatService = server.app.state.agent_chat
+ sent: list[tuple[str, str]] = []
+
+ async def fake_send(session_id: str, text: str) -> str:
+ sent.append((session_id, text))
+ return "turn-1"
+
+ monkeypatch.setattr(svc, "send", fake_send)
+ with TestClient(server.app) as client:
+ first = client.post(f"{BASE}/run", json={"mode": "setup"})
+ assert first.status_code == 200, first.text
+ assert first.json() == {
+ "session_id": first.json()["session_id"],
+ "turn_id": "turn-1",
+ "surface": "local-models",
+ }
+ second = client.post(f"{BASE}/run", json={"mode": "diagnose"})
+ assert second.json()["session_id"] == first.json()["session_id"]
+ state = client.get(f"{BASE}/session").json()
+ assert state["session_id"] == first.json()["session_id"]
+ assert client.post(f"{BASE}/run", json={"mode": "bogus"}).status_code == 422
+ assert [text for _sid, text in sent] == [SETUP_OPENER, DIAGNOSE_OPENER]
+ sessions = svc.store.list_sessions(surface="local-models")
+ assert len(sessions) == 1 and sessions[0].provider == "openai"
+
+
+def test_run_answers_409_while_a_turn_is_running(
+ server: WebServer, ready: None, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ from jarvis.agent_chat.service import SessionBusy
+
+ svc: AgentChatService = server.app.state.agent_chat
+
+ async def busy(session_id: str, text: str) -> str:
+ raise SessionBusy(session_id)
+
+ monkeypatch.setattr(svc, "send", busy)
+ with TestClient(server.app) as client:
+ resp = client.post(f"{BASE}/run", json={"mode": "test"})
+ assert resp.status_code == 409 and "still answering" in resp.json()["detail"]
+
+
+def test_test_route_runs_the_setup_test_and_health_reads_the_file(
+ server: WebServer, fake: FakeOllamaServer, tmp_path: Path
+) -> None:
+ with TestClient(server.app) as client:
+ before = client.get(f"{BASE}/health").json()
+ assert before == {
+ "status": "unknown",
+ "reason": "",
+ "since": None,
+ "last_ok": None,
+ "checked_at": None,
+ }
+ resp = client.post(f"{BASE}/test", json={"roles": ["embedding"]})
+ assert resp.status_code == 200, resp.text
+ report = resp.json()
+ assert report["roles"]["embedding"]["status"] == "ok"
+ assert report["overall"] == "ok"
+ assert client.post(f"{BASE}/test", json={"roles": ["ack"]}).status_code == 400
+ after = client.get(f"{BASE}/health").json()
+ assert after["status"] == "ok" and after["checked_at"] == report["checked_at"]
+ assert after["since"] == after["last_ok"] == report["checked_at"]
+ written = json.loads((tmp_path / "state" / "local_models_health.json").read_text("utf-8"))
+ assert written["overall"] == "ok"
+
+
+def test_benchmarks_without_a_cache_is_curated_only(server: WebServer) -> None:
+ with TestClient(server.app) as client:
+ body = client.get(f"{BASE}/benchmarks").json()
+ assert body["source"] == "curated" and body["rows"] == [] and body["note"]
+
+
+def test_section_health_carries_the_local_models_badge_from_the_file(
+ server: WebServer, fake: FakeOllamaServer
+) -> None:
+ from jarvis.local_models.health_monitor import write_health_record
+
+ write_health_record("error", "chat: model not found")
+ with TestClient(server.app) as client:
+ resp = client.get("/api/providers/section-health?refresh=true")
+ assert resp.status_code == 200, resp.text
+ section = resp.json()["sections"]["local_models"]
+ assert section["status"] == "error"
+ assert section["detail"] == "chat: model not found"