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.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
feat(local-models): end-to-end setup test runner with per-role verdicts and a persisted health report
rubenluetke10-beep7926209c4009
diff --git a/jarvis/brain/ollama_inventory.py b/jarvis/brain/ollama_inventory.pyindex daa22c53f2..5b0bc325f6 100644--- a/jarvis/brain/ollama_inventory.py+++ b/jarvis/brain/ollama_inventory.py@@ -15,6 +15,10 @@ Ollama surface behind the "Local models" section:* :func:`unload_model` — a ``keep_alive: 0`` ping, Ollama's own "unload now".* :func:`delete_model` — ``DELETE /api/delete``.* :func:`disk_usage` — the sum of the user-visible downloads.+* :func:`cached_snapshot` — ONE sweep (``/api/tags`` + ``/api/show`` per+ download + ``/api/ps``) shared by every panel of the section for a few+ seconds, so an open of the section costs one sweep instead of five;+ :func:`invalidate_snapshot` drops it after an unload, a delete or a pull.Two families of download are Jarvis's own bookkeeping, not the user'schoice, and are hidden from every user-facing list by :func:`is_hidden_alias`:@@ -34,6 +38,7 @@ from __future__ import annotationsimport asyncioimport loggingimport re+import timefrom dataclasses import dataclassfrom typing import Any@@ -60,6 +65,10 @@ __all__ = ["unload_model","delete_model","disk_usage",+ "InventorySnapshot",+ "cached_snapshot",+ "peek_snapshot",+ "invalidate_snapshot",]#: Per-model option profiles are derived models named ``<base>-jarvis-<hash>``@@ -128,6 +137,23 @@ class OllamaRunningModel:digest: str = ""+@dataclass(frozen=True, slots=True)+class InventorySnapshot:+ """One sweep of the server, shared by every reader for a few seconds.++ ``models`` are the user-visible downloads with their ``/api/show`` facts;+ ``running`` is ``/api/ps`` (empty when that probe failed — logged, the+ downloads still render); ``all_names`` also lists Jarvis's own aliases,+ for the pull bookkeeping that asks "is this tag on the server at all".+ ``fetched_at`` is ``time.time()`` when the sweep finished.+ """++ models: tuple[OllamaModelInfo, ...]+ running: tuple[OllamaRunningModel, ...]+ fetched_at: float+ all_names: frozenset[str] = frozenset()++# ── Names ────────────────────────────────────────────────────────────────@@ -291,23 +317,34 @@ async def list_models("""root = normalize_server_root(root)async with _make_client(transport) as client:- payload = await _get_json(client, root, "/api/tags")- rows = payload.get("models") if isinstance(payload, dict) else None- if not isinstance(rows, list):- raise OllamaServerError(f"Ollama at {root} answered /api/tags in an unexpected shape.")- base: list[OllamaModelInfo] = []- for row in rows:- if not isinstance(row, dict):- continue- info = _from_tags_row(row)- if not info.name or info.name.endswith(":cloud") or row.get("remote"):- continue- if not include_hidden and is_hidden_alias(info.name):- continue- base.append(info)- semaphore = asyncio.Semaphore(_SHOW_CONCURRENCY)- probed = await asyncio.gather(*(_show(client, root, m, semaphore) for m in base))- return sorted(probed, key=lambda m: m.modified_at, reverse=True)+ probed, _names = await _sweep(client, root, include_hidden=include_hidden)+ return probed+++async def _sweep(+ client: httpx.AsyncClient, root: str, *, include_hidden: bool+) -> tuple[list[OllamaModelInfo], frozenset[str]]:+ """``/api/tags`` + ``/api/show`` per kept download: ``(models newest first,+ every local name incl. hidden aliases)``."""+ payload = await _get_json(client, root, "/api/tags")+ rows = payload.get("models") if isinstance(payload, dict) else None+ if not isinstance(rows, list):+ raise OllamaServerError(f"Ollama at {root} answered /api/tags in an unexpected shape.")+ base: list[OllamaModelInfo] = []+ names: set[str] = set()+ for row in rows:+ if not isinstance(row, dict):+ continue+ info = _from_tags_row(row)+ if not info.name or info.name.endswith(":cloud") or row.get("remote"):+ continue+ names.add(info.name)+ if not include_hidden and is_hidden_alias(info.name):+ continue+ base.append(info)+ semaphore = asyncio.Semaphore(_SHOW_CONCURRENCY)+ probed = await asyncio.gather(*(_show(client, root, m, semaphore) for m in base))+ return sorted(probed, key=lambda m: m.modified_at, reverse=True), frozenset(names)async def get_model(@@ -371,6 +408,7 @@ async def unload_model(resp = await client.post(f"{root}/api/generate", json={"model": name, "keep_alive": 0})except httpx.HTTPError as exc:raise _unreachable(root, exc) from exc+ invalidate_snapshot(root)if resp.status_code == 404:raise OllamaModelNotFound(f"No download named {name!r} on the Ollama server at {root}.")if resp.status_code >= 400:@@ -397,6 +435,7 @@ async def delete_model(resp = await client.request("DELETE", f"{root}/api/delete", json={"model": name})except httpx.HTTPError as exc:raise _unreachable(root, exc) from exc+ invalidate_snapshot(root)if resp.status_code == 404:raise OllamaModelNotFound(f"No download named {name!r} on the Ollama server at {root}.")if resp.status_code >= 400:@@ -406,13 +445,115 @@ async def delete_model(async def disk_usage(root: str, *, transport: httpx.AsyncBaseTransport | None = None) -> int:- """Bytes held by the user-visible downloads.+ """Bytes held by the user-visible downloads (from the shared snapshot).Aliases are excluded on purpose: they share their weights with the basemodel, and counting both would report a 4 GB model as 8 GB."""- models = await list_models(root, include_hidden=False, transport=transport)- return sum(m.size_bytes for m in models)+ snapshot = await cached_snapshot(root, transport=transport)+ return sum(m.size_bytes for m in snapshot.models)+++# ── Shared snapshot ──────────────────────────────────────────────────────++#: How long one sweep serves every reader. Five seconds covers one paint of+#: the section (inventory, roles, server and shortlist ask within the same+#: second) without hiding a model that a voice turn just loaded for long.+DEFAULT_SNAPSHOT_MAX_AGE_S = 5.0++#: Per-root memo: the last good snapshot, or the last failure (so an offline+#: server is not asked five times per paint either — the sentence is the same).+_snapshots: dict[str, InventorySnapshot] = {}+_failures: dict[str, tuple[float, OllamaServerError]] = {}+#: Per-root sweep lock, bound to the loop that created it: concurrent callers+#: join the in-flight sweep instead of starting their own.+_locks: dict[str, tuple[asyncio.AbstractEventLoop, asyncio.Lock]] = {}+++def _lock_for(root: str) -> asyncio.Lock:+ loop = asyncio.get_running_loop()+ hit = _locks.get(root)+ if hit is None or hit[0] is not loop:+ hit = (loop, asyncio.Lock())+ _locks[root] = hit+ return hit[1]+++def _fresh(root: str, max_age_s: float) -> InventorySnapshot | None:+ snapshot = _snapshots.get(root)+ if snapshot is not None and time.time() - snapshot.fetched_at < max_age_s:+ return snapshot+ return None+++def peek_snapshot(+ root: str, *, max_age_s: float = DEFAULT_SNAPSHOT_MAX_AGE_S+) -> InventorySnapshot | None:+ """The fresh snapshot for ``root`` if one exists, without fetching."""+ return _fresh(normalize_server_root(root), max_age_s)+++def invalidate_snapshot(root: str) -> None:+ """Forget what is known about ``root``; the next reader sweeps again.++ Called after an unload, a delete and a finished pull — the three moments+ the inventory changes because of something Jarvis did.+ """+ root = normalize_server_root(root)+ _snapshots.pop(root, None)+ _failures.pop(root, None)+++def _reset_for_tests() -> None:+ """Drop every memoised snapshot, failure and lock (tests only)."""+ _snapshots.clear()+ _failures.clear()+ _locks.clear()+++async def cached_snapshot(+ root: str,+ *,+ max_age_s: float = DEFAULT_SNAPSHOT_MAX_AGE_S,+ transport: httpx.AsyncBaseTransport | None = None,+) -> InventorySnapshot:+ """The server's downloads and loaded models, one sweep per ``max_age_s``.++ Concurrent callers wait for the sweep in flight and share its result.+ Raises :class:`OllamaServerError` when ``/api/tags`` did not answer; that+ failure is remembered for the same window, so the panels of one paint+ all show the same sentence after ONE refused connection. A failing+ ``/api/ps`` is not an error: ``running`` is empty and the downloads render.+ """+ root = normalize_server_root(root)+ if (hit := _fresh(root, max_age_s)) is not None:+ return hit+ async with _lock_for(root):+ if (hit := _fresh(root, max_age_s)) is not None:+ return hit+ failed = _failures.get(root)+ if failed is not None and time.time() - failed[0] < max_age_s:+ raise failed[1]+ try:+ async with _make_client(transport) as client:+ models, names = await _sweep(client, root, include_hidden=False)+ try:+ running = await running_models(root, transport=transport)+ except OllamaServerError as exc:+ log.info("ollama-inventory: /api/ps unavailable at %s: %s", root, exc)+ running = []+ except OllamaServerError as exc:+ _failures[root] = (time.time(), exc)+ raise+ snapshot = InventorySnapshot(+ models=tuple(models),+ running=tuple(running),+ fetched_at=time.time(),+ all_names=names,+ )+ _snapshots[root] = snapshot+ _failures.pop(root, None)+ return snapshotdef _error_text(resp: httpx.Response) -> str:@@ -423,3 +564,33 @@ def _error_text(resp: httpx.Response) -> str:if isinstance(payload, dict) and payload.get("error"):return str(payload["error"])return resp.text.strip()[:200]+++async def embed_probe(+ root: str, model: str, *, transport: httpx.AsyncBaseTransport | None = None+) -> int:+ """One real embedding of a short input via ``/api/embed``; returns the vector length.++ The setup assistant's proof that an embedding role actually embeds: a+ listed model with the ``embedding`` capability can still fail to load.+ ``0`` when the server answered without a vector; raises+ :class:`OllamaServerError` when the server refused or is unreachable.+ """+ root = normalize_server_root(root)+ async with _make_client(transport) as client:+ try:+ resp = await client.post(f"{root}/api/embed", json={"model": model, "input": "ping"})+ except httpx.HTTPError as exc:+ raise _unreachable(root, exc) from exc+ if resp.status_code == 404:+ raise OllamaModelNotFound(f"Ollama at {root} does not list {model!r}.")+ if resp.status_code >= 400:+ raise OllamaServerError(f"/api/embed for {model!r} failed: {_error_text(resp)}")+ try:+ payload = resp.json()+ except ValueError as exc:+ raise OllamaServerError(f"/api/embed for {model!r} answered non-JSON.") from exc+ vectors = payload.get("embeddings") if isinstance(payload, dict) else None+ if isinstance(vectors, list) and vectors and isinstance(vectors[0], list):+ return len(vectors[0])+ return 0diff --git a/jarvis/local_models/__init__.py b/jarvis/local_models/__init__.pynew file mode 100644index 0000000000..5755fb6826--- /dev/null+++ b/jarvis/local_models/__init__.py@@ -0,0 +1,12 @@+"""The local-models setup assistant: test runner, benchmarks, tools and prompt.++Everything the "Help me set up" panel of the Local models section runs on,+kept apart from :mod:`jarvis.brain.ollama_*` (which own the server, the+inventory and the roles) and from :mod:`jarvis.agent_chat` (which owns the+chat surface). Nothing here runs at import time (AP-26); every module+imports its heavy neighbours lazily inside the function that needs them.+"""++from __future__ import annotations++__all__: list[str] = []diff --git a/jarvis/local_models/assistant_test.py b/jarvis/local_models/assistant_test.pynew file mode 100644index 0000000000..c43ffbf238--- /dev/null+++ b/jarvis/local_models/assistant_test.py@@ -0,0 +1,399 @@+"""The end-to-end test of a local setup: does every configured role actually answer?++A role that is *configured* proves nothing — the model may have been deleted,+the server may be down, a "tools + vision" pick may declare neither. So this+runner asks the server (``probe_host``), then makes one REAL call per+configured role: a 1-token generation for the chat / deep / tools_screen+roles (through :func:`jarvis.brain.provider_test.run_provider_test`, so the+status vocabulary is the one the API-keys cards already speak), a+capability assertion on top for ``tools_screen``, an embedding round trip+for the embedding role, and — only when the managed voice server is+configured — the voice smoke probe. The report is persisted to+``DATA_DIR/state/local_models_health.json`` so the section badge and the+health monitor read the same file.+"""++from __future__ import annotations++import asyncio+import datetime as _dt+import json+import logging+import os+import uuid+from collections.abc import Awaitable, Callable+from dataclasses import dataclass+from pathlib import Path+from typing import Any++log = logging.getLogger(__name__)++__all__ = [+ "HEALTH_FILE_NAME",+ "NOT_SET",+ "OVERALL_STATUSES",+ "RoleCheck",+ "TestReport",+ "health_path",+ "load_last_report",+ "run_setup_test",+]++#: Status of a role nobody configured — it is not an error, there is simply+#: nothing to test. Alongside :data:`PROVIDER_TEST_STATUSES` in ``status``.+NOT_SET = "not_set"++#: ``overall`` vocabulary — the same the health monitor (D7) writes.+OVERALL_STATUSES: tuple[str, ...] = ("ok", "error", "needs_setup", "unknown")++HEALTH_FILE_NAME = "local_models_health.json"++#: The generation-tested roles and the role whose pick embeds.+_GENERATION_ROLES: tuple[str, ...] = ("chat", "tools_screen", "deep")+_EMBEDDING_ROLE = "embedding"+_VOICE_ROLE = "voice"++_DEFAULT_TIMEOUT_S = 90.0+_VOICE_DEFAULT_URL = "http://127.0.0.1:8765"+++@dataclass(frozen=True, slots=True)+class _OllamaSpec:+ """The three fields :func:`run_provider_test` reads from a provider spec."""++ id: str = "ollama"+ tier: str = "brain"+ auth_mode: str = "none"+++@dataclass(frozen=True, slots=True)+class RoleCheck:+ """One role's verdict."""++ model: str+ #: :data:`PROVIDER_TEST_STATUSES` value or :data:`NOT_SET`.+ status: str+ latency_ms: float+ detail: str++ def to_payload(self) -> dict[str, Any]:+ return {+ "model": self.model,+ "status": self.status,+ "latency_ms": round(self.latency_ms, 1),+ "detail": self.detail,+ }+++@dataclass(frozen=True, slots=True)+class TestReport:+ """The whole run, as the panel's table and the health file show it."""++ #: Not a pytest class, whatever the name suggests.+ __test__ = False++ checked_at: str+ server: dict[str, Any]+ roles: dict[str, RoleCheck]+ #: The voice smoke probe's payload, ``None`` when no managed voice server exists.+ voice: dict[str, Any] | None+ #: One of :data:`OVERALL_STATUSES`.+ overall: str++ def to_payload(self) -> dict[str, Any]:+ return {+ "checked_at": self.checked_at,+ "server": dict(self.server),+ "roles": {role: check.to_payload() for role, check in self.roles.items()},+ "voice": dict(self.voice) if self.voice is not None else None,+ "overall": self.overall,+ # The badge keys the health monitor writes as well (D7), so one+ # reader serves both writers.+ "status": self.overall,+ "reason": self.reason(),+ }++ def reason(self) -> str:+ """One sentence naming the first failure, or ``""`` when all is well."""+ if not self.server.get("ok"):+ return str(self.server.get("detail") or "Ollama did not answer.")+ for role, check in self.roles.items():+ if check.status not in ("ok", NOT_SET):+ return f"{role}: {check.detail or check.status}"+ if self.voice is not None and not self.voice.get("ok", False):+ return f"voice: {self.voice.get('detail') or 'the voice probe failed'}"+ return ""+++def health_path() -> Path:+ """``DATA_DIR/state/local_models_health.json`` — resolved at call time."""+ from jarvis.core import config as cfg_mod # lazy: DATA_DIR is monkeypatched by tests++ return Path(cfg_mod.DATA_DIR) / "state" / HEALTH_FILE_NAME+++def _atomic_write_json(path: Path, payload: dict[str, Any]) -> bool:+ temporary = path.with_name(f".{path.name}.{os.getpid()}.{uuid.uuid4().hex}.tmp")+ try:+ path.parent.mkdir(parents=True, exist_ok=True)+ temporary.write_text(json.dumps(payload, indent=2), encoding="utf-8")+ os.replace(temporary, path)+ return True+ except OSError:+ log.warning("local-models: health file %s not written", path, exc_info=True)+ return False+ finally:+ try:+ temporary.unlink(missing_ok=True)+ except OSError:+ log.debug("local-models: temporary health file cleanup failed", exc_info=True)+++def load_last_report() -> dict[str, Any] | None:+ """The persisted payload of the last run, or ``None`` when none / unreadable."""+ path = health_path()+ try:+ payload = json.loads(path.read_text(encoding="utf-8"))+ except FileNotFoundError:+ return None+ except (OSError, ValueError):+ log.info("local-models: health file %s unreadable", path, exc_info=True)+ return None+ return payload if isinstance(payload, dict) else None+++# ── Reading the config ────────────────────────────────────────────────────+++def _voice_launch_command(cfg: Any) -> str:+ providers = getattr(getattr(cfg, "brain", None), "providers", None) or {}+ voice = providers.get("local-realtime") if isinstance(providers, dict) else None+ return str(getattr(voice, "launch_command", "") or "")+++def _voice_base_url(cfg: Any) -> str:+ providers = getattr(getattr(cfg, "brain", None), "providers", None) or {}+ voice = providers.get("local-realtime") if isinstance(providers, dict) else None+ return str(getattr(voice, "base_url", "") or "") or _VOICE_DEFAULT_URL+++def _server_root(cfg: Any) -> str:+ providers = getattr(getattr(cfg, "brain", None), "providers", None) or {}+ ollama = providers.get("ollama") if isinstance(providers, dict) else None+ override = str(getattr(ollama, "base_url", "") or "")+ if override:+ from jarvis.plugins.brain.ollama import normalize_server_root++ return normalize_server_root(override)+ from jarvis.brain.ollama_pull import server_root++ return server_root()+++# ── The checks ────────────────────────────────────────────────────────────+++async def _generation_check(+ cfg: Any,+ model: str,+ *,+ timeout_s: float,+ brain_probe: Callable[[str, str], Awaitable[Any]] | None,+) -> RoleCheck:+ from jarvis.brain import provider_test++ result = await provider_test.run_provider_test(+ _OllamaSpec(), cfg, model=model, timeout_s=timeout_s, brain_probe=brain_probe+ )+ return RoleCheck(+ model=model,+ status=result.status,+ latency_ms=float(result.latency_ms),+ detail=result.detail or ("Answered." if result.status == "ok" else ""),+ )+++async def _capability_check(root: str, check: RoleCheck, *, transport: Any) -> RoleCheck:+ """``tools_screen`` must DECLARE tools + vision, not only answer a prompt."""+ from jarvis.brain import ollama_inventory as inventory+ from jarvis.brain.provider_test import ERROR, MODEL_UNAVAILABLE++ if check.status != "ok":+ return check+ try:+ info = await inventory.get_model(root, check.model, transport=transport)+ except inventory.OllamaModelNotFound as exc:+ return RoleCheck(check.model, MODEL_UNAVAILABLE, check.latency_ms, str(exc))+ except inventory.OllamaServerError as exc:+ return RoleCheck(check.model, ERROR, check.latency_ms, str(exc))+ missing = [c for c in ("tools", "vision") if c not in info.capabilities]+ if missing:+ return RoleCheck(+ check.model,+ ERROR,+ check.latency_ms,+ f"{check.model} answers, but does not declare {' + '.join(missing)} — "+ "it cannot read the screen or call tools for Jarvis.",+ )+ return RoleCheck(check.model, "ok", check.latency_ms, "Answered; declares tools + vision.")+++async def _embedding_check(root: str, model: str, *, transport: Any) -> RoleCheck:+ import time++ from jarvis.brain import ollama_inventory as inventory+ from jarvis.brain.provider_test import ERROR, MODEL_UNAVAILABLE, UNREACHABLE++ started = time.perf_counter()+ try:+ dim = await inventory.embed_probe(root, model, transport=transport)+ except inventory.OllamaModelNotFound as exc:+ return RoleCheck(model, MODEL_UNAVAILABLE, _ms(started), str(exc))+ except inventory.OllamaServerError as exc:+ text = str(exc)+ status = UNREACHABLE if "No Ollama" in text or "unreachable" in text.lower() else ERROR+ return RoleCheck(model, status, _ms(started), text)+ if dim <= 0:+ return RoleCheck(model, ERROR, _ms(started), f"{model} returned no embedding vector.")+ return RoleCheck(model, "ok", _ms(started), f"Embeds ({dim} dimensions).")+++async def _voice_check(+ cfg: Any,+ *,+ timeout_s: float,+ voice_probe: Callable[[str], Awaitable[dict[str, Any]]] | None,+) -> dict[str, Any] | None:+ """The voice smoke probe — only for the Jarvis-managed server (``--model_name``)."""+ command = _voice_launch_command(cfg)+ if "--model_name" not in command:+ return None+ base_url = _voice_base_url(cfg)+ try:+ if voice_probe is not None:+ payload = await asyncio.wait_for(voice_probe(base_url), timeout=timeout_s)+ else:+ from jarvis.realtime.local_server.smoke import probe_voice_roundtrip++ payload = await probe_voice_roundtrip(base_url, timeout_s=timeout_s)+ except TimeoutError:+ return {"ok": False, "detail": f"The voice probe timed out after {timeout_s:.0f} s."}+ except Exception as exc: # noqa: BLE001 — the report names the failure, never raises+ log.info("local-models: voice probe failed", exc_info=True)+ return {"ok": False, "detail": f"{type(exc).__name__}: {exc}"}+ out = dict(payload or {})+ out.setdefault("ok", True)+ out.setdefault("detail", "Voice round trip answered with audio.")+ return out+++def _ms(started: float) -> float:+ import time++ return (time.perf_counter() - started) * 1000.0+++def _overall(server: dict[str, Any], roles: dict[str, RoleCheck], voice: Any) -> str:+ configured = [c for c in roles.values() if c.status != NOT_SET]+ if not server.get("ok"):+ return "needs_setup" if not configured else "error"+ if not configured and voice is None:+ return "needs_setup"+ if any(c.status != "ok" for c in configured):+ return "error"+ if voice is not None and not voice.get("ok", False):+ return "error"+ return "ok"+++# ── The runner ────────────────────────────────────────────────────────────+++async def run_setup_test(+ cfg: Any,+ roles: tuple[str, ...] | None = None,+ *,+ transport: Any = None,+ brain_probe: Callable[[str, str], Awaitable[Any]] | None = None,+ voice_probe: Callable[[str], Awaitable[dict[str, Any]]] | None = None,+ timeout_s: float = _DEFAULT_TIMEOUT_S,+ persist: bool = True,+) -> TestReport:+ """Test the configured local setup end to end and persist the report.++ ``roles`` restricts the run to those writable role ids (default: all of+ them). ``transport`` is the httpx test seam for the Ollama calls;+ ``brain_probe`` / ``voice_probe`` are the seams for the generation and+ voice probes (production wiring when ``None``). Never raises for a+ failing check — every failure is a row in the report.+ """+ from jarvis.brain.ollama_roles import WRITABLE_ROLE_IDS, current_pick+ from jarvis.brain.ollama_runtime import probe_host+ from jarvis.brain.provider_test import UNREACHABLE++ wanted = tuple(roles) if roles else WRITABLE_ROLE_IDS+ unknown = [r for r in wanted if r not in WRITABLE_ROLE_IDS]+ if unknown:+ raise ValueError(f"Unknown role(s): {', '.join(unknown)}")++ root = _server_root(cfg)+ server = await probe_host(root, transport=transport)+ server["base_url"] = root++ checks: dict[str, RoleCheck] = {}+ for role in wanted:+ if role == _VOICE_ROLE:+ continue # the voice role is judged by the smoke probe below+ model, note = current_pick(cfg, role)+ if not model:+ checks[role] = RoleCheck("", NOT_SET, 0.0, note or "No model set.")+ continue+ if not server.get("ok"):+ checks[role] = RoleCheck(model, UNREACHABLE, 0.0, str(server.get("detail") or ""))+ continue+ if role == _EMBEDDING_ROLE:+ checks[role] = await _embedding_check(root, model, transport=transport)+ elif role in _GENERATION_ROLES:+ check = await _generation_check(+ cfg, model, timeout_s=timeout_s, brain_probe=brain_probe+ )+ if role == "tools_screen":+ check = await _capability_check(root, check, transport=transport)+ checks[role] = check++ voice: dict[str, Any] | None = None+ if _VOICE_ROLE in wanted:+ voice = await _voice_check(cfg, timeout_s=timeout_s, voice_probe=voice_probe)+ voice_model, voice_note = current_pick(cfg, _VOICE_ROLE)+ if voice is None:+ checks[_VOICE_ROLE] = RoleCheck(+ voice_model, NOT_SET, 0.0, voice_note or "No managed voice server."+ )+ else:+ checks[_VOICE_ROLE] = RoleCheck(+ voice_model,+ "ok" if voice.get("ok") else "error",+ float(voice.get("first_audio_ms") or voice.get("latency_ms") or 0.0),+ str(voice.get("detail") or ""),+ )++ report = TestReport(+ checked_at=_dt.datetime.now(_dt.UTC).isoformat(timespec="seconds"),+ server=server,+ roles=checks,+ voice=voice,+ overall=_overall(server, checks, voice),+ )+ if persist:+ payload = report.to_payload()+ previous = load_last_report() or {}+ payload["since"] = (+ previous.get("since")+ if previous.get("status") == report.overall and previous.get("since")+ else report.checked_at+ )+ payload["last_ok"] = (+ report.checked_at if report.overall == "ok" else previous.get("last_ok")+ )+ _atomic_write_json(health_path(), payload)+ return reportdiff --git a/tests/fakes/fake_ollama_server.py b/tests/fakes/fake_ollama_server.pyindex 6ae4b1d35a..4678dc98cd 100644--- a/tests/fakes/fake_ollama_server.py+++ b/tests/fakes/fake_ollama_server.py@@ -1,7 +1,7 @@"""An in-process Ollama server for tests: the native API over ``httpx.MockTransport``.Models the surface :mod:`jarvis.brain.ollama_inventory` talks to — ``/api/tags``,-``/api/show``, ``/api/ps``, ``/api/generate`` (unload ping), ``/api/delete`` —+``/api/show``, ``/api/ps``, ``/api/generate`` (unload ping), ``/api/embed``, ``/api/delete`` —with real state: deleting a model removes it from the next ``/api/tags``, anunload ping removes it from ``/api/ps``, and every call is recorded so a testcan assert on what was sent. Nothing here touches the network.@@ -42,6 +42,8 @@ class FakeOllamaModel:show_fails: bool = False#: Present in ``/api/ps`` when set.loaded: bool = False+ #: Vector length ``/api/embed`` answers with (0 = the server returns no vector).+ embed_dim: int = 768size_vram: int = 0expires_at: str = "2026-08-24T12:05:00Z"running_context: int = 8192@@ -54,6 +56,8 @@ class FakeOllamaServer:calls: list[tuple[str, str, Any]] = field(default_factory=list)#: When True every request raises ``httpx.ConnectError``.offline: bool = False+ #: What ``GET /api/version`` answers.+ version: str = "0.32.15"# -- building state ----------------------------------------------------@@ -95,6 +99,8 @@ class FakeOllamaServer:body = self._body(request)self.calls.append((request.method, path, body))+ if request.method == "GET" and path == "/api/version":+ return httpx.Response(200, json={"version": self.version})if request.method == "GET" and path == "/api/tags":rows = [self._tags_row(m) for m in self.models.values()]return httpx.Response(200, json={"models": rows})@@ -120,6 +126,16 @@ class FakeOllamaServer:)model.loaded = Truereturn httpx.Response(200, json={"model": model.name, "done": True, "response": ""})+ if request.method == "POST" and path == "/api/embed":+ model = self._find((body or {}).get("model") or "")+ if model is None:+ return httpx.Response(404, json={"error": "model not found"})+ if "embedding" not in model.capabilities:+ return httpx.Response(+ 400, json={"error": f"{model.name} does not support embeddings"}+ )+ vectors = [[0.1] * model.embed_dim] if model.embed_dim > 0 else []+ return httpx.Response(200, json={"model": model.name, "embeddings": vectors})if request.method == "DELETE" and path == "/api/delete":model = self._find((body or {}).get("model") or "")if model is None:diff --git a/tests/unit/local_models/__init__.py b/tests/unit/local_models/__init__.pynew file mode 100644index 0000000000..e69de29bb2diff --git a/tests/unit/local_models/test_assistant_test.py b/tests/unit/local_models/test_assistant_test.pynew file mode 100644index 0000000000..a4f165cd73--- /dev/null+++ b/tests/unit/local_models/test_assistant_test.py@@ -0,0 +1,204 @@+"""The setup test runner: one real call per configured role, an honest table.++Fakes only: the Ollama server is :class:`tests.fakes.fake_ollama_server.FakeOllamaServer`+over ``httpx.MockTransport``; the 1-token generation and the voice probe go+through the runner's injectable seams.+"""++from __future__ import annotations++import json+from pathlib import Path+from typing import Any++import pytest++from jarvis.brain import ollama_inventory as inventory+from jarvis.core import config as cfg_mod+from jarvis.core.config import BrainProviderConfig, JarvisConfig+from jarvis.local_models import assistant_test+from jarvis.local_models.assistant_test import NOT_SET, run_setup_test+from tests.fakes.fake_ollama_server import FakeOllamaServer++pytestmark = pytest.mark.asyncio+++class _HealthResult:+ def __init__(self, ok: bool, error: str | None) -> None:+ self.ok = ok+ self.error = error+ self.duration_ms = 12.0+++class _Probe:+ """Records the generation probes and answers ok unless told otherwise."""++ def __init__(self, failing: dict[str, str] | None = None) -> None:+ self.calls: list[tuple[str, str]] = []+ self.failing = failing or {}++ async def __call__(self, provider: str, model: str) -> Any:+ self.calls.append((provider, model))+ return _HealthResult(model not in self.failing, self.failing.get(model))+++def _cfg(**picks: str) -> JarvisConfig:+ cfg = JarvisConfig()+ cfg.brain.providers["ollama"] = BrainProviderConfig(+ model=picks.get("chat", ""),+ tool_model=picks.get("tools_screen", ""),+ deep_model=picks.get("deep", ""),+ base_url="http://fake-ollama:11434",+ )+ cfg.ultrawiki.embedding_provider = "ollama"+ cfg.ultrawiki.embedding_model = picks.get("embedding", "")+ return cfg+++def _server() -> FakeOllamaServer:+ fake = FakeOllamaServer()+ fake.add("qwen3.5:4b", capabilities=("completion", "tools", "vision"))+ fake.add("chatonly:7b", capabilities=("completion",))+ fake.add("embeddinggemma", capabilities=("embedding",), embed_dim=768)+ return fake++[email protected](autouse=True)+def _data_dir(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:+ monkeypatch.setattr(cfg_mod, "DATA_DIR", tmp_path)+ return tmp_path+++async def test_embed_probe_returns_the_vector_length() -> None:+ fake = _server()+ dim = await inventory.embed_probe("http://x", "embeddinggemma", transport=fake.transport())+ assert dim == 768+ assert ("POST", "/api/embed", {"model": "embeddinggemma", "input": "ping"}) in fake.calls+ with pytest.raises(inventory.OllamaModelNotFound):+ await inventory.embed_probe("http://x", "nope", transport=fake.transport())+++async def test_full_setup_answers_ok_per_role_and_persists(tmp_path: Path) -> None:+ fake = _server()+ probe = _Probe()+ cfg = _cfg(+ chat="qwen3.5:4b", tools_screen="qwen3.5:4b", deep="qwen3.5:4b", embedding="embeddinggemma"+ )+ report = await run_setup_test(cfg, transport=fake.transport(), brain_probe=probe)++ assert isinstance(report, assistant_test.TestReport)+ assert report.server["ok"] is True and report.server["version"] == "0.32.15"+ assert {r: c.status for r, c in report.roles.items()} == {+ "chat": "ok",+ "tools_screen": "ok",+ "deep": "ok",+ "embedding": "ok",+ "voice": NOT_SET,+ }+ assert report.voice is None+ assert report.overall == "ok"+ # Exactly one real generation per generation role, on the Ollama provider.+ assert probe.calls == [("ollama", "qwen3.5:4b")] * 3+ # Persisted to the state file with the badge keys the monitor also writes.+ written = json.loads((tmp_path / "state" / "local_models_health.json").read_text("utf-8"))+ assert written["status"] == "ok" and written["overall"] == "ok"+ assert written["roles"]["embedding"]["detail"] == "Embeds (768 dimensions)."+ assert written["last_ok"] == written["checked_at"] == report.checked_at+ assert report.to_payload()["roles"]["chat"]["model"] == "qwen3.5:4b"+++async def test_tools_screen_needs_declared_tools_and_vision() -> None:+ fake = _server()+ cfg = _cfg(tools_screen="chatonly:7b")+ report = await run_setup_test(+ cfg, ("tools_screen",), transport=fake.transport(), brain_probe=_Probe()+ )+ check = report.roles["tools_screen"]+ assert check.status == "error"+ assert "tools + vision" in check.detail+ assert report.overall == "error"+ assert report.reason().startswith("tools_screen:")+++async def test_nothing_configured_is_needs_setup_not_error() -> None:+ fake = _server()+ report = await run_setup_test(_cfg(), transport=fake.transport(), brain_probe=_Probe())+ assert all(c.status == NOT_SET for c in report.roles.values())+ assert report.overall == "needs_setup"+ assert report.reason() == ""+++async def test_server_down_marks_every_configured_role_unreachable() -> None:+ fake = _server()+ fake.offline = True+ probe = _Probe()+ cfg = _cfg(chat="qwen3.5:4b", embedding="embeddinggemma")+ report = await run_setup_test(cfg, transport=fake.transport(), brain_probe=probe)+ assert report.server["ok"] is False+ assert report.roles["chat"].status == "unreachable"+ assert report.roles["embedding"].status == "unreachable"+ assert probe.calls == [], "no generation is attempted against a dead server"+ assert report.overall == "error"+++async def test_generation_failure_is_classified_with_the_provider_vocabulary() -> None:+ fake = _server()+ cfg = _cfg(chat="qwen3.5:4b")+ probe = _Probe(failing={"qwen3.5:4b": "model 'qwen3.5:4b' not found (404)"})+ report = await run_setup_test(cfg, ("chat",), transport=fake.transport(), brain_probe=probe)+ assert report.roles["chat"].status == "model_unavailable"+++async def test_voice_probe_runs_only_for_the_managed_server() -> None:+ fake = _server()+ seen: list[str] = []++ async def voice_probe(base_url: str) -> dict[str, Any]:+ seen.append(base_url)+ return {"ok": True, "first_audio_ms": 640}++ cfg = _cfg(chat="qwen3.5:4b")+ cfg.brain.providers["local-realtime"] = BrainProviderConfig(+ launch_command="python server.py --model_name qwen3.5:4b --port 8765",+ base_url="http://127.0.0.1:8765",+ )+ report = await run_setup_test(+ cfg,+ ("chat", "voice"),+ transport=fake.transport(),+ brain_probe=_Probe(),+ voice_probe=voice_probe,+ )+ assert seen == ["http://127.0.0.1:8765"]+ assert report.voice == {+ "ok": True,+ "first_audio_ms": 640,+ "detail": "Voice round trip answered with audio.",+ }+ assert report.roles["voice"].status == "ok"+ assert report.roles["voice"].latency_ms == 640+ assert report.overall == "ok"++ # A bring-your-own command (no --model_name) is never probed.+ cfg.brain.providers["local-realtime"].launch_command = "my-own-server --port 8765"+ report = await run_setup_test(+ cfg, ("voice",), transport=fake.transport(), brain_probe=_Probe(), voice_probe=voice_probe+ )+ assert seen == ["http://127.0.0.1:8765"]+ assert report.voice is None and report.roles["voice"].status == NOT_SET+++async def test_unknown_role_is_refused() -> None:+ with pytest.raises(ValueError, match="Unknown role"):+ await run_setup_test(_cfg(), ("chat", "ack"), transport=_server().transport())+++async def test_since_is_kept_while_the_status_holds() -> None:+ fake = _server()+ cfg = _cfg(chat="qwen3.5:4b")+ first = await run_setup_test(cfg, ("chat",), transport=fake.transport(), brain_probe=_Probe())+ second = await run_setup_test(cfg, ("chat",), transport=fake.transport(), brain_probe=_Probe())+ written = assistant_test.load_last_report()+ assert written is not None+ assert written["since"] == first.checked_at+ assert written["checked_at"] == second.checked_at