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): inventory — every download with its facts, what is loaded, unload and delete

rubenluetke10-beepbfe5b729e18c
diff --git a/jarvis/brain/model_catalog.py b/jarvis/brain/model_catalog.py
index d4baf3c7a8..fec340a1f8 100644
--- a/jarvis/brain/model_catalog.py
+++ b/jarvis/brain/model_catalog.py
@@ -172,6 +172,14 @@ class ModelInfo:
# only source, and every new model generation shipped as "$0.00" until
# someone noticed (2026-07-28 and 2026-08-18 audits).
pricing: tuple[float, float] | None = None
+ # Local-server facts from Ollama's ``/api/show`` (``model_info.<arch>.
+ # context_length`` and ``details``). ``None`` for every gateway/cloud
+ # catalog — they carry no such manifest — so nothing downstream changes for
+ # them. Read by the Local models section and the per-model option sheet
+ # (native context caps the ``num_ctx`` chips).
+ context_length: int | None = None
+ quantization_level: str | None = None
+ parameter_size: str | None = None
def _curated(pairs: list[tuple[str, str]]) -> list[ModelInfo]:
@@ -1806,7 +1814,8 @@ class ModelCatalog:
try:
resp = await client.post(f"{root}/api/show", json={"model": info.id})
resp.raise_for_status()
- caps = resp.json().get("capabilities")
+ shown = resp.json()
+ caps = shown.get("capabilities")
except Exception as exc: # noqa: BLE001 — unknown stays capable
log.debug("ollama: /api/show failed for %s: %s", info.id, exc)
return info
@@ -1815,10 +1824,19 @@ class ModelCatalog:
declared = {str(c) for c in caps}
if "completion" not in declared:
return None
+ # Keep the manifest facts instead of dropping them: the Local
+ # models section and the option sheet read them from the SAME
+ # cached catalog the pickers use (no second probe per model).
+ from jarvis.brain.ollama_inventory import native_context_length
+
+ details = shown.get("details") if isinstance(shown.get("details"), dict) else {}
return replace(
info,
input_modalities=("text", "image") if "vision" in declared else ("text",),
supported_parameters=("tools",) if "tools" in declared else (),
+ context_length=native_context_length(shown.get("model_info")),
+ quantization_level=str(details.get("quantization_level") or "") or None,
+ parameter_size=str(details.get("parameter_size") or "") or None,
)
probed = await asyncio.gather(*(probe(m) for m in models))
diff --git a/jarvis/brain/ollama_inventory.py b/jarvis/brain/ollama_inventory.py
new file mode 100644
index 0000000000..727a03478b
--- /dev/null
+++ b/jarvis/brain/ollama_inventory.py
@@ -0,0 +1,421 @@
+"""What the local Ollama server holds, loaded, and can let go of.
+
+The provider card only ever asked ``/api/tags`` — a list of names. That is
+enough to pick a model and not enough to manage them: nothing said how big a
+download was, what it can do (vision? tools? embeddings?), how much context it
+natively carries, whether it is sitting in graphics memory right now, or how
+to free that memory without restarting the server. This module is the native
+Ollama surface behind the "Local models" section:
+
+* :func:`list_models` — ``/api/tags`` joined with ``/api/show`` per download
+ (bounded concurrency, fail-open per model so one broken manifest never
+ blanks the table).
+* :func:`running_models` — ``/api/ps``: what is loaded, how much of it sits
+ in graphics memory, when it expires.
+* :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.
+
+Two families of download are Jarvis's own bookkeeping, not the user's
+choice, and are hidden from every user-facing list by :func:`is_hidden_alias`:
+the per-model option profiles (``<base>-jarvis-<8 hex>``, created via
+``/api/create`` so ``num_ctx`` & co. can ride the OpenAI-compatible ``/v1``
+path) and the voice brain's ``-voice-8k`` alias. Aliases share their weights
+with the base model, so hiding them also keeps :func:`disk_usage` honest.
+
+Every function takes the server ``root`` explicitly (see
+:func:`jarvis.brain.ollama_pull.server_root` for the configured one) and an
+optional ``transport`` so tests drive it through a fake server rather than
+the network. HTTP only — identical on every OS, including a headless box.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import logging
+import re
+from dataclasses import dataclass
+from typing import Any
+
+import httpx
+
+from jarvis.plugins.brain.ollama import CLIENT_TIMEOUT, normalize_server_root
+
+log = logging.getLogger(__name__)
+
+__all__ = [
+ "OllamaModelInfo",
+ "OllamaRunningModel",
+ "OllamaServerError",
+ "OllamaModelNotFound",
+ "PROFILE_ALIAS_SUFFIX_RE",
+ "VOICE_ALIAS_SUFFIX",
+ "is_hidden_alias",
+ "native_context_length",
+ "same_model",
+ "list_models",
+ "get_model",
+ "running_models",
+ "unload_model",
+ "delete_model",
+ "disk_usage",
+]
+
+#: Per-model option profiles are derived models named ``<base>-jarvis-<hash>``
+#: (``jarvis.brain.ollama_profiles``); the hash is the first 8 hex characters
+#: of the baked option dict.
+PROFILE_ALIAS_SUFFIX_RE = re.compile(r"-jarvis-[0-9a-f]{8}$")
+
+#: The managed voice brain's fixed-context alias (``supervisor.py``).
+VOICE_ALIAS_SUFFIX = "-voice-8k"
+
+#: ``/api/show`` is one round-trip per download; eight in flight keeps a
+#: 40-model host under a second on localhost without hammering a LAN box.
+_SHOW_CONCURRENCY = 8
+
+
+class OllamaServerError(RuntimeError):
+ """The server did not answer usefully. ``str(exc)`` is an English sentence
+ the UI can show verbatim."""
+
+
+class OllamaModelNotFound(OllamaServerError):
+ """The named download does not exist on the server (HTTP 404)."""
+
+
+@dataclass(frozen=True, slots=True)
+class OllamaModelInfo:
+ """One installed download with the facts ``/api/tags`` + ``/api/show`` give.
+
+ ``context_length`` is the model's NATIVE window from ``model_info``
+ (``<arch>.context_length``), not what the server currently runs it with;
+ ``None`` when the manifest does not say. ``capabilities`` is the declared
+ list (``completion``, ``vision``, ``tools``, ``thinking``, ``embedding``,
+ ``audio`` ...), empty when the probe failed — callers treat empty as
+ "unknown", never as "can do nothing".
+ """
+
+ name: str
+ size_bytes: int
+ digest: str
+ modified_at: str
+ family: str
+ parameter_size: str
+ quantization_level: str
+ context_length: int | None
+ capabilities: tuple[str, ...]
+ license: str
+ #: Free-text extras from ``/api/show`` for the details view.
+ parameters: str = ""
+ template: str = ""
+ #: True when ``/api/show`` answered — False means only ``/api/tags`` facts.
+ probed: bool = True
+
+
+@dataclass(frozen=True, slots=True)
+class OllamaRunningModel:
+ """One entry of ``/api/ps``: a model currently held in memory."""
+
+ name: str
+ size_bytes: int
+ size_vram_bytes: int
+ expires_at: str
+ context_length: int | None
+ digest: str = ""
+
+
+# ── Names ────────────────────────────────────────────────────────────────
+
+
+def _strip_latest(name: str) -> str:
+ return name[: -len(":latest")] if name.endswith(":latest") else name
+
+
+def same_model(a: str, b: str) -> bool:
+ """``qwen3.5`` and ``qwen3.5:latest`` are one download (Ollama's own rule)."""
+ a, b = a.strip(), b.strip()
+ if not a or not b:
+ return False
+ return _strip_latest(a) == _strip_latest(b)
+
+
+def is_hidden_alias(name: str) -> bool:
+ """True for Jarvis's own derived models, which no user list should show.
+
+ Profile aliases fold ``:`` into ``-`` and therefore carry no tag of their
+ own, so ``/api/tags`` reports them as ``…-jarvis-ab12cd34:latest``.
+ """
+ bare = _strip_latest((name or "").strip())
+ if not bare:
+ return False
+ if PROFILE_ALIAS_SUFFIX_RE.search(bare):
+ return True
+ return bare.endswith(VOICE_ALIAS_SUFFIX)
+
+
+# ── HTTP ─────────────────────────────────────────────────────────────────
+
+
+def _make_client(transport: httpx.AsyncBaseTransport | None = None) -> httpx.AsyncClient:
+ """One client per call; tests inject a fake transport here."""
+ return httpx.AsyncClient(timeout=CLIENT_TIMEOUT, transport=transport)
+
+
+def _unreachable(root: str, exc: Exception) -> OllamaServerError:
+ log.info("ollama-inventory: %s did not answer (%s)", root, type(exc).__name__)
+ return OllamaServerError(
+ f"Ollama did not answer at {root}. Start the server (or install it "
+ "from ollama.com/download) and try again."
+ )
+
+
+async def _get_json(client: httpx.AsyncClient, root: str, path: str) -> Any:
+ try:
+ resp = await client.get(f"{root}{path}")
+ resp.raise_for_status()
+ return resp.json()
+ except httpx.HTTPStatusError as exc:
+ raise OllamaServerError(
+ f"Ollama answered {exc.response.status_code} for {path} at {root}."
+ ) from exc
+ except (httpx.HTTPError, ValueError) as exc:
+ raise _unreachable(root, exc) from exc
+
+
+def _as_int(value: Any) -> int:
+ try:
+ return int(value or 0)
+ except (TypeError, ValueError):
+ return 0
+
+
+def native_context_length(model_info: Any) -> int | None:
+ """``model_info`` keys are ``<architecture>.context_length``; the
+ architecture itself sits under ``general.architecture``."""
+ if not isinstance(model_info, dict):
+ return None
+ arch = str(model_info.get("general.architecture") or "").strip()
+ candidates = [f"{arch}.context_length"] if arch else []
+ candidates += [k for k in model_info if k.endswith(".context_length")]
+ for key in candidates:
+ value = model_info.get(key)
+ if isinstance(value, (int, float)) and value > 0:
+ return int(value)
+ return None
+
+
+def _details_of(payload: dict[str, Any]) -> dict[str, Any]:
+ details = payload.get("details")
+ return details if isinstance(details, dict) else {}
+
+
+def _from_tags_row(row: dict[str, Any]) -> OllamaModelInfo:
+ details = _details_of(row)
+ return OllamaModelInfo(
+ name=str(row.get("name") or row.get("model") or "").strip(),
+ size_bytes=_as_int(row.get("size")),
+ digest=str(row.get("digest") or ""),
+ modified_at=str(row.get("modified_at") or ""),
+ family=str(details.get("family") or ""),
+ parameter_size=str(details.get("parameter_size") or ""),
+ quantization_level=str(details.get("quantization_level") or ""),
+ context_length=None,
+ capabilities=(),
+ license="",
+ probed=False,
+ )
+
+
+def _merge_show(info: OllamaModelInfo, show: dict[str, Any]) -> OllamaModelInfo:
+ details = _details_of(show)
+ caps_raw = show.get("capabilities")
+ caps = tuple(str(c) for c in caps_raw) if isinstance(caps_raw, list) else ()
+ license_text = show.get("license")
+ if isinstance(license_text, list):
+ license_text = "\n".join(str(x) for x in license_text)
+ return OllamaModelInfo(
+ name=info.name,
+ size_bytes=info.size_bytes,
+ digest=info.digest,
+ modified_at=info.modified_at,
+ family=str(details.get("family") or info.family),
+ parameter_size=str(details.get("parameter_size") or info.parameter_size),
+ quantization_level=str(details.get("quantization_level") or info.quantization_level),
+ context_length=native_context_length(show.get("model_info")),
+ capabilities=caps,
+ license=str(license_text or "").strip(),
+ parameters=str(show.get("parameters") or ""),
+ template=str(show.get("template") or ""),
+ probed=True,
+ )
+
+
+async def _show(
+ client: httpx.AsyncClient, root: str, info: OllamaModelInfo, semaphore: asyncio.Semaphore
+) -> OllamaModelInfo:
+ async with semaphore:
+ try:
+ resp = await client.post(f"{root}/api/show", json={"model": info.name})
+ resp.raise_for_status()
+ payload = resp.json()
+ except Exception as exc: # noqa: BLE001 — fail-open per model, the row stays
+ log.debug("ollama-inventory: /api/show failed for %s: %s", info.name, exc)
+ return info
+ if not isinstance(payload, dict):
+ log.debug("ollama-inventory: /api/show for %s is not an object", info.name)
+ return info
+ return _merge_show(info, payload)
+
+
+# ── Public API ───────────────────────────────────────────────────────────
+
+
+async def list_models(
+ root: str,
+ *,
+ include_hidden: bool = False,
+ transport: httpx.AsyncBaseTransport | None = None,
+) -> list[OllamaModelInfo]:
+ """Every download with its facts, newest first.
+
+ ``:cloud`` references and remote entries are dropped for the same reason
+ the brain drops them: they are ollama.com-proxied, not local weights.
+ Jarvis's own aliases are hidden unless ``include_hidden`` is set (the
+ profile code needs them to find stale ones). Raises
+ :class:`OllamaServerError` when ``/api/tags`` does not answer; a failing
+ ``/api/show`` only leaves that row without capabilities.
+ """
+ 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)
+
+
+async def get_model(
+ root: str, name: str, *, transport: httpx.AsyncBaseTransport | None = None
+) -> OllamaModelInfo:
+ """One download by name (``:latest`` tolerant). Raises
+ :class:`OllamaModelNotFound` when the server does not list it."""
+ for info in await list_models(root, include_hidden=True, transport=transport):
+ if same_model(info.name, name):
+ return info
+ raise OllamaModelNotFound(f"No download named {name!r} on the Ollama server at {root}.")
+
+
+async def running_models(
+ root: str, *, transport: httpx.AsyncBaseTransport | None = None
+) -> list[OllamaRunningModel]:
+ """What ``/api/ps`` says is loaded right now (aliases included — they DO
+ occupy memory, and the caller maps them back to their base by name)."""
+ root = normalize_server_root(root)
+ async with _make_client(transport) as client:
+ payload = await _get_json(client, root, "/api/ps")
+ rows = payload.get("models") if isinstance(payload, dict) else None
+ if not isinstance(rows, list):
+ raise OllamaServerError(f"Ollama at {root} answered /api/ps in an unexpected shape.")
+ out: list[OllamaRunningModel] = []
+ for row in rows:
+ if not isinstance(row, dict):
+ continue
+ name = str(row.get("name") or row.get("model") or "").strip()
+ if not name:
+ continue
+ ctx = row.get("context_length")
+ out.append(
+ OllamaRunningModel(
+ name=name,
+ size_bytes=_as_int(row.get("size")),
+ size_vram_bytes=_as_int(row.get("size_vram")),
+ expires_at=str(row.get("expires_at") or ""),
+ context_length=int(ctx) if isinstance(ctx, (int, float)) and ctx > 0 else None,
+ digest=str(row.get("digest") or ""),
+ )
+ )
+ return out
+
+
+async def unload_model(
+ root: str, name: str, *, transport: httpx.AsyncBaseTransport | None = None
+) -> None:
+ """Free the memory a loaded model holds — Ollama's own ``keep_alive: 0``.
+
+ An empty prompt with ``keep_alive: 0`` is the documented unload call; the
+ server answers ``done_reason: "unload"``. Unloading a model that is not
+ loaded is a no-op on the server and here.
+ """
+ root = normalize_server_root(root)
+ name = name.strip()
+ if not name:
+ raise OllamaServerError("A model name is required to unload it.")
+ async with _make_client(transport) as client:
+ try:
+ 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
+ if resp.status_code == 404:
+ raise OllamaModelNotFound(f"No download named {name!r} on the Ollama server at {root}.")
+ if resp.status_code >= 400:
+ raise OllamaServerError(
+ f"Ollama refused to unload {name!r} ({resp.status_code}): {_error_text(resp)}"
+ )
+
+
+async def delete_model(
+ root: str, name: str, *, transport: httpx.AsyncBaseTransport | None = None
+) -> None:
+ """Remove a download from the server's store (``DELETE /api/delete``).
+
+ Deleting an alias only drops the manifest; the shared weights stay until
+ the last name pointing at them is gone. Unknown names raise
+ :class:`OllamaModelNotFound`.
+ """
+ root = normalize_server_root(root)
+ name = name.strip()
+ if not name:
+ raise OllamaServerError("A model name is required to delete it.")
+ async with _make_client(transport) as client:
+ try:
+ resp = await client.request("DELETE", f"{root}/api/delete", json={"model": name})
+ except httpx.HTTPError as exc:
+ raise _unreachable(root, exc) from exc
+ if resp.status_code == 404:
+ raise OllamaModelNotFound(f"No download named {name!r} on the Ollama server at {root}.")
+ if resp.status_code >= 400:
+ raise OllamaServerError(
+ f"Ollama refused to delete {name!r} ({resp.status_code}): {_error_text(resp)}"
+ )
+
+
+async def disk_usage(root: str, *, transport: httpx.AsyncBaseTransport | None = None) -> int:
+ """Bytes held by the user-visible downloads.
+
+ Aliases are excluded on purpose: they share their weights with the base
+ model, 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)
+
+
+def _error_text(resp: httpx.Response) -> str:
+ try:
+ payload = resp.json()
+ except ValueError:
+ return resp.text.strip()[:200]
+ if isinstance(payload, dict) and payload.get("error"):
+ return str(payload["error"])
+ return resp.text.strip()[:200]
diff --git a/jarvis/ui/web/local_models_routes.py b/jarvis/ui/web/local_models_routes.py
new file mode 100644
index 0000000000..6aef248781
--- /dev/null
+++ b/jarvis/ui/web/local_models_routes.py
@@ -0,0 +1,374 @@
+"""REST surface of the "Local models" section: inventory, unload, delete.
+
+Everything the section shows about what is INSTALLED on the pull-capable
+local server (Ollama today) lives here, separate from ``provider_routes.py``
+which keeps serving the provider card (model pick, pull, runtime). Every
+handler sits behind the same capability gate as the pull routes —
+:func:`provider_routes._require_pull_capable` — so a cloud card answers 400
+with a sentence, never a silent empty table.
+
+Response bodies are Pydantic models: the Python half of the five-layer
+parity contract (AP-4); the TS mirror lives in ``src/hooks/useLocalModels.ts``.
+
+Deleting is the one destructive action, and it is refused — 409 with the
+reason — while a configured role still points at the model, unless the
+caller names a replacement (``?reassign=``) that is installed; then the
+roles are rewritten through the config writers FIRST, so a crash between
+the two steps leaves a valid config, never an empty slot.
+"""
+
+from __future__ import annotations
+
+import logging
+from dataclasses import asdict
+from typing import Any
+
+from fastapi import APIRouter, HTTPException, Query, Request
+from pydantic import BaseModel, Field
+
+from jarvis.brain import ollama_inventory as inventory
+from jarvis.brain.ollama_inventory import (
+ OllamaModelInfo,
+ OllamaModelNotFound,
+ OllamaRunningModel,
+ OllamaServerError,
+ same_model,
+)
+from jarvis.ui.web.provider_routes import _require_pull_capable, _resolve_cfg
+
+log = logging.getLogger(__name__)
+
+router = APIRouter(prefix="/api/providers/{provider_id}/local-models", tags=["local-models"])
+
+#: Role id -> where the brain reads it. The three ``[brain.providers.ollama]``
+#: model fields plus the wiki's embedding slot (Ollama-backed when
+#: ``embedding_provider == "ollama"``). Chunk 5 grows this into
+#: ``ollama_roles.ROLES``; the ids are kept stable for that.
+ROLE_FIELDS: tuple[tuple[str, str], ...] = (
+ ("chat", "model"),
+ ("tools_screen", "tool_model"),
+ ("deep", "deep_model"),
+)
+EMBEDDING_ROLE = "embedding"
+
+
+# ── Response / body models (AP-4, Python half) ───────────────────────────
+
+
+class LocalModelRow(BaseModel):
+ name: str
+ size_bytes: int
+ digest: str
+ modified_at: str
+ family: str
+ parameter_size: str
+ quantization_level: str
+ context_length: int | None
+ capabilities: list[str]
+ license: str
+ probed: bool
+ #: Role ids (``chat`` / ``tools_screen`` / ``deep`` / ``embedding``) whose
+ #: configured pick is this download.
+ used_by: list[str] = Field(default_factory=list)
+ #: Present when ``/api/ps`` lists it.
+ loaded: bool = False
+ size_vram_bytes: int = 0
+ expires_at: str = ""
+ running_context_length: int | None = None
+
+
+class LocalModelDetail(LocalModelRow):
+ parameters: str = ""
+ template: str = ""
+
+
+class RunningModelRow(BaseModel):
+ name: str
+ size_bytes: int
+ size_vram_bytes: int
+ expires_at: str
+ context_length: int | None
+ digest: str = ""
+
+
+class InventoryResponse(BaseModel):
+ provider: str
+ server: str
+ models: list[LocalModelRow]
+ running: list[RunningModelRow]
+ disk_bytes: int
+ #: Sum of ``size_vram_bytes`` over the loaded models.
+ loaded_vram_bytes: int
+ #: English sentence when the server did not answer; the lists are empty
+ #: then and the UI shows this instead of "you have nothing installed".
+ error: str | None = None
+
+
+class UnloadResponse(BaseModel):
+ ok: bool
+ model: str
+ message: str
+
+
+class DeleteResponse(BaseModel):
+ ok: bool
+ model: str
+ message: str
+ #: Roles rewritten to ``reassign`` before the delete (empty when none).
+ reassigned: list[str] = Field(default_factory=list)
+ reassigned_to: str | None = None
+
+
+# ── Helpers ──────────────────────────────────────────────────────────────
+
+
+def _server_root() -> str:
+ from jarvis.brain.ollama_pull import server_root
+
+ return server_root()
+
+
+def _ollama_provider_cfg(cfg: Any) -> Any:
+ providers = getattr(getattr(cfg, "brain", None), "providers", None) or {}
+ return providers.get("ollama") if isinstance(providers, dict) else None
+
+
+def _roles_using(cfg: Any, name: str) -> list[str]:
+ """Role ids whose configured pick is ``name`` (``:latest`` tolerant)."""
+ if cfg is None:
+ return []
+ out: list[str] = []
+ provider = _ollama_provider_cfg(cfg)
+ for role, field in ROLE_FIELDS:
+ value = str(getattr(provider, field, "") or "") if provider is not None else ""
+ if value and same_model(value, name):
+ out.append(role)
+ ultrawiki = getattr(cfg, "ultrawiki", None)
+ if (
+ ultrawiki is not None
+ and str(getattr(ultrawiki, "embedding_provider", "") or "") == "ollama"
+ and same_model(str(getattr(ultrawiki, "embedding_model", "") or ""), name)
+ ):
+ out.append(EMBEDDING_ROLE)
+ return out
+
+
+def _row(
+ info: OllamaModelInfo, running: dict[str, OllamaRunningModel], used_by: list[str]
+) -> dict[str, Any]:
+ live = next((r for key, r in running.items() if same_model(key, info.name)), None)
+ return {
+ "name": info.name,
+ "size_bytes": info.size_bytes,
+ "digest": info.digest,
+ "modified_at": info.modified_at,
+ "family": info.family,
+ "parameter_size": info.parameter_size,
+ "quantization_level": info.quantization_level,
+ "context_length": info.context_length,
+ "capabilities": list(info.capabilities),
+ "license": info.license,
+ "probed": info.probed,
+ "used_by": used_by,
+ "loaded": live is not None,
+ "size_vram_bytes": live.size_vram_bytes if live else 0,
+ "expires_at": live.expires_at if live else "",
+ "running_context_length": live.context_length if live else None,
+ }
+
+
+async def _running_by_name(root: str) -> dict[str, OllamaRunningModel]:
+ """``/api/ps`` as a map; an unanswered probe is an empty map (logged), so a
+ server that lists downloads but stalls on ``/api/ps`` still renders."""
+ try:
+ return {r.name: r for r in await inventory.running_models(root)}
+ except OllamaServerError as exc:
+ log.info("local-models: /api/ps unavailable at %s: %s", root, exc)
+ return {}
+
+
+def _http_error(exc: OllamaServerError) -> HTTPException:
+ if isinstance(exc, OllamaModelNotFound):
+ return HTTPException(status_code=404, detail=str(exc))
+ return HTTPException(status_code=503, detail=str(exc))
+
+
+# ── Routes ───────────────────────────────────────────────────────────────
+
+
[email protected]("/inventory", response_model=InventoryResponse)
+async def get_inventory(provider_id: str, request: Request) -> InventoryResponse:
+ """Every download with its facts, what is loaded, and the disk total.
+
+ Jarvis's own aliases (option profiles, the voice alias) are hidden from
+ ``models``; ``running`` still names them, so the memory an alias holds is
+ visible and ``loaded_vram_bytes`` stays honest.
+ """
+ _require_pull_capable(provider_id)
+ root = _server_root()
+ cfg = _resolve_cfg(request)
+ try:
+ models = await inventory.list_models(root)
+ except OllamaServerError as exc:
+ return InventoryResponse(
+ provider=provider_id,
+ server=root,
+ models=[],
+ running=[],
+ disk_bytes=0,
+ loaded_vram_bytes=0,
+ error=str(exc),
+ )
+ running = await _running_by_name(root)
+ rows = [LocalModelRow(**_row(m, running, _roles_using(cfg, m.name))) for m in models]
+ return InventoryResponse(
+ provider=provider_id,
+ server=root,
+ models=rows,
+ running=[RunningModelRow(**asdict(r)) for r in running.values()],
+ disk_bytes=sum(m.size_bytes for m in models),
+ loaded_vram_bytes=sum(r.size_vram_bytes for r in running.values()),
+ )
+
+
[email protected]("/inventory/{name:path}", response_model=LocalModelDetail)
+async def get_inventory_model(provider_id: str, name: str, request: Request) -> LocalModelDetail:
+ """One download with the long facts (license, parameters, template)."""
+ _require_pull_capable(provider_id)
+ root = _server_root()
+ try:
+ info = await inventory.get_model(root, name)
+ except OllamaServerError as exc:
+ raise _http_error(exc) from exc
+ running = await _running_by_name(root)
+ payload = _row(info, running, _roles_using(_resolve_cfg(request), info.name))
+ payload["parameters"] = info.parameters
+ payload["template"] = info.template
+ return LocalModelDetail(**payload)
+
+
+ "/inventory/{name:path}/unload",
+ response_model=UnloadResponse,
+ openapi_extra={"x-jarvis-dangerous": True},
+)
+async def unload_inventory_model(provider_id: str, name: str) -> UnloadResponse:
+ """Free the memory a loaded model holds (``keep_alive: 0``).
+
+ Dangerous-flagged because the next turn on that model pays the load time
+ again — a voice session mid-conversation notices. Nothing is deleted.
+ """
+ _require_pull_capable(provider_id)
+ root = _server_root()
+ try:
+ await inventory.unload_model(root, name)
+ except OllamaServerError as exc:
+ raise _http_error(exc) from exc
+ return UnloadResponse(
+ ok=True,
+ model=name,
+ message=f"{name} was unloaded; its memory is free until the next turn uses it.",
+ )
+
+
+ "/inventory/{name:path}",
+ response_model=DeleteResponse,
+ openapi_extra={"x-jarvis-dangerous": True},
+)
+async def delete_inventory_model(
+ provider_id: str,
+ name: str,
+ request: Request,
+ reassign: str | None = Query(
+ default=None,
+ description=(
+ "Installed model that takes over every role currently pointing at "
+ "the deleted one. Required when a role points at it."
+ ),
+ ),
+) -> DeleteResponse:
+ """Remove a download from the server (``DELETE /api/delete``).
+
+ 409 while a configured role (chat / tools & screen / deep / embeddings)
+ still names the model and no ``reassign`` is given; with one, the roles
+ are rewritten through the config writers first, then the delete runs.
+ """
+ _require_pull_capable(provider_id)
+ root = _server_root()
+ cfg = _resolve_cfg(request)
+ roles = _roles_using(cfg, name)
+ reassigned: list[str] = []
+ target = (reassign or "").strip()
+ if roles and not target:
+ raise HTTPException(
+ status_code=409,
+ detail=(
+ f"{name} is still the pick for {', '.join(roles)}. Choose another "
+ "installed model for those roles first, or pass ?reassign=<model>."
+ ),
+ )
+ if roles and target:
+ if same_model(target, name):
+ raise HTTPException(
+ status_code=422,
+ detail="The replacement must be a different model than the one being deleted.",
+ )
+ try:
+ installed = await inventory.list_models(root)
+ except OllamaServerError as exc:
+ raise _http_error(exc) from exc
+ if not any(same_model(m.name, target) for m in installed):
+ raise HTTPException(
+ status_code=422,
+ detail=f"{target} is not installed on the server, so it cannot take over.",
+ )
+ reassigned = _reassign_roles(cfg, roles, target)
+ try:
+ await inventory.delete_model(root, name)
+ except OllamaServerError as exc:
+ raise _http_error(exc) from exc
+ message = f"{name} was deleted from the server."
+ if reassigned:
+ message += f" {', '.join(reassigned)} now use {target}."
+ return DeleteResponse(
+ ok=True,
+ model=name,
+ message=message,
+ reassigned=reassigned,
+ reassigned_to=target or None,
+ )
+
+
+def _reassign_roles(cfg: Any, roles: list[str], target: str) -> list[str]:
+ """Persist ``target`` for every role in ``roles`` and mirror it into the
+ live config object so the next read agrees with the TOML."""
+ from jarvis.core import config_writer
+
+ fields = [field for role, field in ROLE_FIELDS if role in roles]
+ done: list[str] = []
+ try:
+ if fields:
+ config_writer.set_brain_provider_model(
+ "ollama",
+ model=target if "model" in fields else None,
+ deep_model=target if "deep_model" in fields else None,
+ tool_model=target if "tool_model" in fields else None,
+ )
+ provider = _ollama_provider_cfg(cfg)
+ for field in fields:
+ if provider is not None:
+ setattr(provider, field, target)
+ done.extend(role for role, field in ROLE_FIELDS if field in fields)
+ if EMBEDDING_ROLE in roles:
+ config_writer.set_ultrawiki_slot("embedding_model", target)
+ ultrawiki = getattr(cfg, "ultrawiki", None)
+ if ultrawiki is not None:
+ ultrawiki.embedding_model = target
+ done.append(EMBEDDING_ROLE)
+ except Exception as exc: # noqa: BLE001 — the delete must not run on a half-written config
+ log.warning("local-models: reassigning %s to %s failed: %s", roles, target, exc)
+ raise HTTPException(
+ status_code=500, detail=f"Could not rewrite the roles to {target}: {exc}"
+ ) from exc
+ return done
diff --git a/jarvis/ultrawiki/embedding_models.py b/jarvis/ultrawiki/embedding_models.py
index 2cf18860b4..afa8a42aea 100644
--- a/jarvis/ultrawiki/embedding_models.py
+++ b/jarvis/ultrawiki/embedding_models.py
@@ -143,11 +143,14 @@ async def _get_json(
async def _ollama(cfg: Any, transport: Any) -> EmbeddingModelList:
- """Everything the local Ollama has pulled.
-
- Ollama exposes no "is this an embedding model" flag, so the list is what is
- installed and the user picks. That is honest: guessing by name would hide a
- freshly pulled model behind a filter the user cannot see.
+ """The local Ollama downloads that DECLARE the ``embedding`` capability.
+
+ ``/api/show`` names each download's capabilities, so a chat model no
+ longer sits in the embedding picker waiting to 400 on the first embed.
+ Fail-open, per model and as a whole: a download whose probe does not
+ answer stays listed (unknown is not "no"), and when nothing declares the
+ capability at all — an old server that predates the field — the full
+ list is offered exactly as before, with the reason logged.
"""
ultrawiki = getattr(cfg, "ultrawiki", None)
endpoint = str(
@@ -157,18 +160,56 @@ async def _ollama(cfg: Any, transport: Any) -> EmbeddingModelList:
rows = data.get("models") if isinstance(data, dict) else None
if not isinstance(rows, list):
raise ValueError("unexpected /api/tags shape")
- models = [
- EmbeddingModel(id=str(row["name"]), label=str(row["name"]))
- for row in rows
- if isinstance(row, dict) and row.get("name")
+ names = [
+ str(row["name"]) for row in rows if isinstance(row, dict) and row.get("name")
]
- if not models:
+ if not names:
return _curated(
"ollama",
"Ollama is running but has no models pulled yet — "
"'ollama pull qwen3-embedding:4b' installs the current default.",
)
- return _live(models)
+ from jarvis.brain.ollama_inventory import is_hidden_alias
+
+ names = [n for n in names if not is_hidden_alias(n)]
+ declared = await _ollama_capabilities(endpoint, names, transport)
+ keep = [n for n in names if declared.get(n) is None or "embedding" in declared[n]]
+ if not keep:
+ return _curated(
+ "ollama",
+ "None of the installed Ollama models declares the embedding "
+ "capability — 'ollama pull qwen3-embedding:4b' installs the current "
+ "default.",
+ )
+ return _live([EmbeddingModel(id=n, label=n) for n in keep])
+
+
+async def _ollama_capabilities(
+ endpoint: str, names: list[str], transport: Any
+) -> dict[str, tuple[str, ...] | None]:
+ """``name -> declared capabilities`` from ``/api/show``.
+
+ ``None`` when the probe failed or the server predates the field: that
+ download stays offered (fail-open — unknown is not "no"), and the reason
+ is logged so a filter that seems to do nothing can be explained.
+ """
+ out: dict[str, tuple[str, ...] | None] = {}
+ async with httpx.AsyncClient(timeout=_TIMEOUT, transport=transport) as client:
+ for name in names:
+ try:
+ response = await client.post(f"{endpoint}/api/show", json={"model": name})
+ response.raise_for_status()
+ caps = response.json().get("capabilities")
+ except Exception as exc: # noqa: BLE001 — unknown stays offered
+ log.info(
+ "ultrawiki: /api/show failed for %s (%s); offering it unfiltered",
+ name,
+ type(exc).__name__,
+ )
+ out[name] = None
+ continue
+ out[name] = tuple(str(c) for c in caps) if isinstance(caps, list) else None
+ return out
async def _gemini(cfg: Any, transport: Any) -> EmbeddingModelList:
diff --git a/tests/fakes/fake_ollama_server.py b/tests/fakes/fake_ollama_server.py
new file mode 100644
index 0000000000..6ae4b1d35a
--- /dev/null
+++ b/tests/fakes/fake_ollama_server.py
@@ -0,0 +1,177 @@
+"""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`` —
+with real state: deleting a model removes it from the next ``/api/tags``, an
+unload ping removes it from ``/api/ps``, and every call is recorded so a test
+can assert on what was sent. Nothing here touches the network.
+
+Usage::
+
+ fake = FakeOllamaServer()
+ fake.add("qwen3.5:4b", size=3_400_000_000, capabilities=("completion", "tools"))
+ models = await list_models("http://localhost:11434", transport=fake.transport())
+"""
+
+from __future__ import annotations
+
+import json
+from dataclasses import dataclass, field
+from typing import Any
+
+import httpx
+
+__all__ = ["FakeOllamaModel", "FakeOllamaServer"]
+
+
+@dataclass
+class FakeOllamaModel:
+ name: str
+ size: int = 1_000_000_000
+ digest: str = "sha256:deadbeef"
+ modified_at: str = "2026-08-20T10:00:00Z"
+ family: str = "qwen3"
+ parameter_size: str = "4B"
+ quantization_level: str = "Q4_K_M"
+ context_length: int | None = 262_144
+ capabilities: tuple[str, ...] = ("completion", "tools", "vision")
+ license: str = "Apache-2.0"
+ parameters: str = "temperature 0.7"
+ template: str = "{{ .Prompt }}"
+ #: When True the ``/api/show`` probe for this model answers 500.
+ show_fails: bool = False
+ #: Present in ``/api/ps`` when set.
+ loaded: bool = False
+ size_vram: int = 0
+ expires_at: str = "2026-08-24T12:05:00Z"
+ running_context: int = 8192
+
+
+@dataclass
+class FakeOllamaServer:
+ models: dict[str, FakeOllamaModel] = field(default_factory=dict)
+ #: ``(method, path, json body)`` of every request, in order.
+ calls: list[tuple[str, str, Any]] = field(default_factory=list)
+ #: When True every request raises ``httpx.ConnectError``.
+ offline: bool = False
+
+ # -- building state ----------------------------------------------------
+
+ def add(self, name: str, **facts: Any) -> FakeOllamaModel:
+ model = FakeOllamaModel(name=name, **facts)
+ self.models[name] = model
+ return model
+
+ def load(self, name: str, *, size_vram: int | None = None) -> None:
+ model = self.models[name]
+ model.loaded = True
+ model.size_vram = model.size if size_vram is None else size_vram
+
+ # -- transport ---------------------------------------------------------
+
+ def transport(self) -> httpx.MockTransport:
+ return httpx.MockTransport(self._handle)
+
+ def _body(self, request: httpx.Request) -> Any:
+ if not request.content:
+ return None
+ try:
+ return json.loads(request.content.decode("utf-8"))
+ except ValueError:
+ return None
+
+ def _find(self, name: str) -> FakeOllamaModel | None:
+ name = (name or "").strip()
+ if name in self.models:
+ return self.models[name]
+ if ":" not in name and f"{name}:latest" in self.models:
+ return self.models[f"{name}:latest"]
+ return None
+
+ def _handle(self, request: httpx.Request) -> httpx.Response:
+ if self.offline:
+ raise httpx.ConnectError("connection refused", request=request)
+ path = request.url.path
+ body = self._body(request)
+ self.calls.append((request.method, path, body))
+
+ 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})
+ if request.method == "POST" and path == "/api/show":
+ model = self._find((body or {}).get("model") or (body or {}).get("name") or "")
+ if model is None:
+ return httpx.Response(404, json={"error": "model not found"})
+ if model.show_fails:
+ return httpx.Response(500, json={"error": "manifest unreadable"})
+ return httpx.Response(200, json=self._show_payload(model))
+ if request.method == "GET" and path == "/api/ps":
+ return httpx.Response(
+ 200, json={"models": [self._ps_row(m) for m in self.models.values() if m.loaded]}
+ )
+ if request.method == "POST" and path == "/api/generate":
+ model = self._find((body or {}).get("model") or "")
+ if model is None:
+ return httpx.Response(404, json={"error": "model not found"})
+ if (body or {}).get("keep_alive") == 0:
+ model.loaded = False
+ return httpx.Response(
+ 200, json={"model": model.name, "done": True, "done_reason": "unload"}
+ )
+ model.loaded = True
+ return httpx.Response(200, json={"model": model.name, "done": True, "response": ""})
+ if request.method == "DELETE" and path == "/api/delete":
+ model = self._find((body or {}).get("model") or "")
+ if model is None:
+ return httpx.Response(404, json={"error": "model not found"})
+ del self.models[model.name]
+ return httpx.Response(200, json={})
+ return httpx.Response(404, json={"error": f"no route for {request.method} {path}"})
+
+ # -- payload shapes (mirror Ollama 0.32) --------------------------------
+
+ @staticmethod
+ def _details(m: FakeOllamaModel) -> dict[str, Any]:
+ return {
+ "format": "gguf",
+ "family": m.family,
+ "families": [m.family],
+ "parameter_size": m.parameter_size,
+ "quantization_level": m.quantization_level,
+ }
+
+ def _tags_row(self, m: FakeOllamaModel) -> dict[str, Any]:
+ return {
+ "name": m.name,
+ "model": m.name,
+ "modified_at": m.modified_at,
+ "size": m.size,
+ "digest": m.digest,
+ "details": self._details(m),
+ }
+
+ def _show_payload(self, m: FakeOllamaModel) -> dict[str, Any]:
+ model_info: dict[str, Any] = {"general.architecture": m.family}
+ if m.context_length is not None:
+ model_info[f"{m.family}.context_length"] = m.context_length
+ return {
+ "license": m.license,
+ "modelfile": f"FROM {m.name}",
+ "parameters": m.parameters,
+ "template": m.template,
+ "details": self._details(m),
+ "model_info": model_info,
+ "capabilities": list(m.capabilities),
+ }
+
+ def _ps_row(self, m: FakeOllamaModel) -> dict[str, Any]:
+ return {
+ "name": m.name,
+ "model": m.name,
+ "size": m.size,
+ "digest": m.digest,
+ "details": self._details(m),
+ "expires_at": m.expires_at,
+ "size_vram": m.size_vram,
+ "context_length": m.running_context,
+ }
diff --git a/tests/unit/brain/test_ollama_inventory.py b/tests/unit/brain/test_ollama_inventory.py
new file mode 100644
index 0000000000..54153582fc
--- /dev/null
+++ b/tests/unit/brain/test_ollama_inventory.py
@@ -0,0 +1,170 @@
+"""The native Ollama inventory, driven through the in-process fake server.
+
+What would lie if it broke: a download shown without its facts, an alias of
+Jarvis's own making shown as a user's model (or counted twice on disk), a
+broken manifest blanking the whole table, an unload that quietly did
+nothing, a delete that reported success for a name the server never had.
+"""
+
+from __future__ import annotations
+
+import pytest
+
+from jarvis.brain import ollama_inventory as inv
+from tests.fakes.fake_ollama_server import FakeOllamaServer
+
+ROOT = "http://localhost:11434"
+
+
+def fake() -> FakeOllamaServer:
+ server = FakeOllamaServer()
+ server.add(
+ "qwen3.5:4b",
+ size=3_400_000_000,
+ modified_at="2026-08-20T10:00:00Z",
+ capabilities=("completion", "tools", "vision", "thinking"),
+ context_length=262_144,
+ )
+ server.add(
+ "qwen3-embedding:4b",
+ size=2_500_000_000,
+ modified_at="2026-08-22T10:00:00Z",
+ family="qwen3",
+ capabilities=("embedding",),
+ context_length=40_960,
+ )
+ return server
+
+
+# ── Alias hiding ─────────────────────────────────────────────────────────
+ ("name", "hidden"),
+ [
+ ("qwen3.5-4b-jarvis-ab12cd34", True),
+ ("qwen3.5-4b-jarvis-ab12cd34:latest", True),
+ ("qwen3.5:4b-voice-8k", True),
+ ("qwen3.5:4b", False),
+ ("gemma4:12b-it-qat", False),
+ # Eight hex characters exactly — a user tag that merely contains
+ # "jarvis" is not ours.
+ ("my-jarvis-model:latest", False),
+ ("", False),
+ ],
+)
+def test_hidden_aliases_are_recognised_by_shape_only(name: str, hidden: bool) -> None:
+ assert inv.is_hidden_alias(name) is hidden
+
+
+def test_same_model_treats_latest_as_the_bare_name() -> None:
+ assert inv.same_model("qwen3.5", "qwen3.5:latest")
+ assert not inv.same_model("qwen3.5", "qwen3.5:4b")
+ assert not inv.same_model("", "qwen3.5")
+
+
+# ── list_models ──────────────────────────────────────────────────────────
+async def test_list_models_joins_tags_with_show_facts(fake: FakeOllamaServer) -> None:
+ models = await inv.list_models(ROOT, transport=fake.transport())
+ by_name = {m.name: m for m in models}
+ chat = by_name["qwen3.5:4b"]
+ assert chat.size_bytes == 3_400_000_000
+ assert chat.capabilities == ("completion", "tools", "vision", "thinking")
+ assert chat.context_length == 262_144
+ assert chat.quantization_level == "Q4_K_M"
+ assert chat.parameter_size == "4B"
+ assert chat.license == "Apache-2.0"
+ assert chat.probed is True
+ # Newest first — the user looks for what they just pulled.
+ assert [m.name for m in models] == ["qwen3-embedding:4b", "qwen3.5:4b"]
+
+
+async def test_list_models_hides_jarvis_aliases_unless_asked(fake: FakeOllamaServer) -> None:
+ fake.add("qwen3.5-4b-jarvis-ab12cd34:latest", size=3_400_000_000)
+ fake.add("qwen3.5:4b-voice-8k", size=3_400_000_000)
+ visible = await inv.list_models(ROOT, transport=fake.transport())
+ assert {m.name for m in visible} == {"qwen3.5:4b", "qwen3-embedding:4b"}
+ everything = await inv.list_models(ROOT, include_hidden=True, transport=fake.transport())
+ assert len(everything) == 4
+
+
+async def test_list_models_drops_cloud_references(fake: FakeOllamaServer) -> None:
+ fake.add("gpt-oss:cloud", size=0)
+ models = await inv.list_models(ROOT, transport=fake.transport())
+ assert all(not m.name.endswith(":cloud") for m in models)
+
+
+async def test_a_broken_manifest_keeps_its_row_without_facts(fake: FakeOllamaServer) -> None:
+ """One download whose /api/show fails must not blank the table (fail-open)."""
+ fake.add("broken:latest", size=10, show_fails=True)
+ models = await inv.list_models(ROOT, transport=fake.transport())
+ broken = next(m for m in models if m.name == "broken:latest")
+ assert broken.probed is False
+ assert broken.capabilities == ()
+ assert broken.context_length is None
+ assert broken.size_bytes == 10 # the /api/tags facts survive
+
+
+async def test_list_models_raises_an_english_sentence_when_offline(fake: FakeOllamaServer) -> None:
+ fake.offline = True
+ with pytest.raises(inv.OllamaServerError) as excinfo:
+ await inv.list_models(ROOT, transport=fake.transport())
+ assert "did not answer" in str(excinfo.value)
+
+
+async def test_get_model_is_latest_tolerant_and_404s_honestly(fake: FakeOllamaServer) -> None:
+ fake.add("nomic-embed-text:latest", size=1)
+ info = await inv.get_model(ROOT, "nomic-embed-text", transport=fake.transport())
+ assert info.name == "nomic-embed-text:latest"
+ with pytest.raises(inv.OllamaModelNotFound):
+ await inv.get_model(ROOT, "never-pulled:7b", transport=fake.transport())
+
+
+def test_native_context_length_reads_the_architecture_key() -> None:
+ assert inv.native_context_length(
+ {"general.architecture": "gemma4", "gemma4.context_length": 131072}
+ ) == 131072
+ # No architecture hint: any ``*.context_length`` key still counts.
+ assert inv.native_context_length({"llama.context_length": 8192}) == 8192
+ assert inv.native_context_length({"general.architecture": "x"}) is None
+ assert inv.native_context_length(None) is None
+
+
+# ── running / unload / delete / disk ─────────────────────────────────────
+async def test_running_models_reports_vram_and_expiry(fake: FakeOllamaServer) -> None:
+ fake.load("qwen3.5:4b", size_vram=3_000_000_000)
+ running = await inv.running_models(ROOT, transport=fake.transport())
+ assert len(running) == 1
+ assert running[0].name == "qwen3.5:4b"
+ assert running[0].size_vram_bytes == 3_000_000_000
+ assert running[0].expires_at.startswith("2026-")
+ assert running[0].context_length == 8192
+
+
+async def test_unload_sends_keep_alive_zero_and_frees_the_model(fake: FakeOllamaServer) -> None:
+ fake.load("qwen3.5:4b")
+ await inv.unload_model(ROOT, "qwen3.5:4b", transport=fake.transport())
+ assert ("POST", "/api/generate", {"model": "qwen3.5:4b", "keep_alive": 0}) in fake.calls
+ assert await inv.running_models(ROOT, transport=fake.transport()) == []
+
+
+async def test_unload_of_an_unknown_model_is_a_404_not_a_success(
+ fake: FakeOllamaServer,
+) -> None:
+ with pytest.raises(inv.OllamaModelNotFound):
+ await inv.unload_model(ROOT, "ghost:latest", transport=fake.transport())
+
+
+async def test_delete_removes_the_download_and_404s_afterwards(fake: FakeOllamaServer) -> None:
+ await inv.delete_model(ROOT, "qwen3.5:4b", transport=fake.transport())
+ assert ("DELETE", "/api/delete", {"model": "qwen3.5:4b"}) in fake.calls
+ assert "qwen3.5:4b" not in fake.models
+ with pytest.raises(inv.OllamaModelNotFound):
+ await inv.delete_model(ROOT, "qwen3.5:4b", transport=fake.transport())
+
+
+async def test_disk_usage_counts_each_weight_once(fake: FakeOllamaServer) -> None:
+ """An alias shares its weights with the base — counting it would double the total."""
+ fake.add("qwen3.5-4b-jarvis-ab12cd34:latest", size=3_400_000_000)
+ assert await inv.disk_usage(ROOT, transport=fake.transport()) == (
+ 3_400_000_000 + 2_500_000_000
+ )
diff --git a/tests/unit/ui/web/test_local_models_routes.py b/tests/unit/ui/web/test_local_models_routes.py
new file mode 100644
index 0000000000..612332344c
--- /dev/null
+++ b/tests/unit/ui/web/test_local_models_routes.py
@@ -0,0 +1,214 @@
+"""Local-models routes: inventory, unload, delete — through the fake server.
+
+Pins: the routes exist only on pull-capable cards, the inventory pairs the
+downloads with what is loaded and marks which role uses which model, an
+offline server answers a sentence instead of an empty "you have nothing",
+and delete refuses while a role points at the model unless a replacement is
+named — in which case the roles are rewritten through the config writers
+before the delete runs.
+"""
+
+from __future__ import annotations
+
+import httpx
+import pytest
+from fastapi.testclient import TestClient
+
+from jarvis.brain import ollama_inventory
+from jarvis.core import config_writer
+from jarvis.core.bus import EventBus
+from jarvis.core.config import BrainProviderConfig, JarvisConfig
+from jarvis.ui.web import local_models_routes
+from jarvis.ui.web.server import WebServer
+from tests.fakes.fake_ollama_server import FakeOllamaServer
+
+ROOT = "http://localhost:11434"
+BASE = "/api/providers/ollama/local-models"
+
+
+def fake(monkeypatch: pytest.MonkeyPatch) -> FakeOllamaServer:
+ server = FakeOllamaServer()
+ server.add("qwen3.5:4b", size=3_400_000_000, capabilities=("completion", "tools", "vision"))
+ server.add("gemma4:12b-it-qat", size=7_200_000_000, capabilities=("completion", "tools"))
+ server.add("qwen3-embedding:4b", size=2_500_000_000, capabilities=("embedding",))
+ server.add("qwen3.5:4b-voice-8k", size=3_400_000_000)
+
+ def _client(transport: httpx.AsyncBaseTransport | None = None) -> httpx.AsyncClient:
+ return httpx.AsyncClient(transport=server.transport())
+
+ monkeypatch.setattr(ollama_inventory, "_make_client", _client)
+ monkeypatch.setattr(local_models_routes, "_server_root", lambda: ROOT)
+ return server
+
+
+def writes(monkeypatch: pytest.MonkeyPatch) -> list[tuple]:
+ """Record the config writes instead of touching jarvis.toml."""
+ calls: list[tuple] = []
+ monkeypatch.setattr(
+ config_writer,
+ "set_brain_provider_model",
+ lambda provider, **kw: calls.append(("brain", provider, kw)),
+ )
+ monkeypatch.setattr(
+ config_writer,
+ "set_ultrawiki_slot",
+ lambda key, value: calls.append(("ultrawiki", key, value)),
+ )
+ return calls
+
+
+def server(tmp_path, monkeypatch: pytest.MonkeyPatch) -> WebServer:
+ monkeypatch.setenv("JARVIS_DATA_DIR", str(tmp_path))
+ cfg = JarvisConfig()
+ cfg.ui.dev_mode = True
+ cfg.brain.providers["ollama"] = BrainProviderConfig(
+ model="qwen3.5:4b", deep_model="gemma4:12b-it-qat"
+ )
+ cfg.ultrawiki.embedding_provider = "ollama"
+ cfg.ultrawiki.embedding_model = "qwen3-embedding:4b"
+ srv = WebServer(cfg, bus=EventBus())
+ srv.app.state.config = cfg
+ return srv
+
+
+def test_routes_refuse_cards_without_a_pull_api(server: WebServer, fake) -> None:
+ with TestClient(server.app) as client:
+ assert client.get("/api/providers/openai/local-models/inventory").status_code == 400
+ assert client.get("/api/providers/nope/local-models/inventory").status_code == 404
+
+
+def test_inventory_lists_facts_roles_and_loaded_state(server: WebServer, fake) -> None:
+ fake.load("qwen3.5:4b", size_vram=3_000_000_000)
+ with TestClient(server.app) as client:
+ resp = client.get(f"{BASE}/inventory")
+ assert resp.status_code == 200
+ body = resp.json()
+ assert body["error"] is None
+ assert body["server"] == ROOT
+ rows = {m["name"]: m for m in body["models"]}
+ # The voice alias is Jarvis's own — hidden.
+ assert set(rows) == {"qwen3.5:4b", "gemma4:12b-it-qat", "qwen3-embedding:4b"}
+ chat = rows["qwen3.5:4b"]
+ assert chat["used_by"] == ["chat"]
+ assert chat["loaded"] is True
+ assert chat["size_vram_bytes"] == 3_000_000_000
+ assert chat["capabilities"] == ["completion", "tools", "vision"]
+ assert chat["context_length"] == 262_144
+ assert rows["gemma4:12b-it-qat"]["used_by"] == ["deep"]
+ assert rows["qwen3-embedding:4b"]["used_by"] == ["embedding"]
+ assert body["disk_bytes"] == 3_400_000_000 + 7_200_000_000 + 2_500_000_000
+ assert body["loaded_vram_bytes"] == 3_000_000_000
+ assert [r["name"] for r in body["running"]] == ["qwen3.5:4b"]
+
+
+def test_inventory_answers_a_sentence_when_the_server_is_offline(server: WebServer, fake) -> None:
+ fake.offline = True
+ with TestClient(server.app) as client:
+ resp = client.get(f"{BASE}/inventory")
+ assert resp.status_code == 200
+ body = resp.json()
+ assert body["models"] == []
+ assert "did not answer" in body["error"]
+
+
+def test_detail_carries_the_long_facts(server: WebServer, fake) -> None:
+ with TestClient(server.app) as client:
+ resp = client.get(f"{BASE}/inventory/qwen3.5:4b")
+ missing = client.get(f"{BASE}/inventory/ghost:7b")
+ assert resp.status_code == 200
+ body = resp.json()
+ assert body["license"] == "Apache-2.0"
+ assert body["parameters"] == "temperature 0.7"
+ assert body["template"] == "{{ .Prompt }}"
+ assert missing.status_code == 404
+
+
+def test_unload_frees_the_model(server: WebServer, fake) -> None:
+ fake.load("qwen3.5:4b")
+ with TestClient(server.app) as client:
+ resp = client.post(f"{BASE}/inventory/qwen3.5:4b/unload")
+ after = client.get(f"{BASE}/inventory")
+ assert resp.status_code == 200
+ assert resp.json()["ok"] is True
+ assert ("POST", "/api/generate", {"model": "qwen3.5:4b", "keep_alive": 0}) in fake.calls
+ assert after.json()["running"] == []
+
+
+def test_delete_refuses_while_a_role_points_at_the_model(server: WebServer, fake, writes) -> None:
+ with TestClient(server.app) as client:
+ resp = client.delete(f"{BASE}/inventory/qwen3.5:4b")
+ assert resp.status_code == 409
+ assert "chat" in resp.json()["detail"]
+ assert "qwen3.5:4b" in fake.models # nothing was deleted
+ assert writes == []
+
+
+def test_delete_with_reassign_rewrites_the_roles_first(server: WebServer, fake, writes) -> None:
+ with TestClient(server.app) as client:
+ resp = client.delete(
+ f"{BASE}/inventory/qwen3.5:4b", params={"reassign": "gemma4:12b-it-qat"}
+ )
+ assert resp.status_code == 200, resp.text
+ body = resp.json()
+ assert body["reassigned"] == ["chat"]
+ assert body["reassigned_to"] == "gemma4:12b-it-qat"
+ assert writes == [
+ (
+ "brain",
+ "ollama",
+ {"model": "gemma4:12b-it-qat", "deep_model": None, "tool_model": None},
+ )
+ ]
+ assert "qwen3.5:4b" not in fake.models
+ # The live config agrees with the TOML from now on.
+ assert server.app.state.config.brain.providers["ollama"].model == "gemma4:12b-it-qat"
+
+
+def test_delete_reassigns_the_embedding_slot_through_its_own_writer(
+ server: WebServer, fake, writes
+) -> None:
+ fake.add("embeddinggemma:latest", size=300_000_000, capabilities=("embedding",))
+ with TestClient(server.app) as client:
+ resp = client.delete(
+ f"{BASE}/inventory/qwen3-embedding:4b", params={"reassign": "embeddinggemma"}
+ )
+ assert resp.status_code == 200, resp.text
+ assert resp.json()["reassigned"] == ["embedding"]
+ assert writes == [("ultrawiki", "embedding_model", "embeddinggemma")]
+ assert server.app.state.config.ultrawiki.embedding_model == "embeddinggemma"
+
+
+def test_delete_rejects_a_replacement_that_is_not_installed(
+ server: WebServer, fake, writes
+) -> None:
+ with TestClient(server.app) as client:
+ resp = client.delete(f"{BASE}/inventory/qwen3.5:4b", params={"reassign": "never:pulled"})
+ same = client.delete(f"{BASE}/inventory/qwen3.5:4b", params={"reassign": "qwen3.5:4b"})
+ assert resp.status_code == 422
+ assert same.status_code == 422
+ assert writes == []
+ assert "qwen3.5:4b" in fake.models
+
+
+def test_delete_of_an_unused_model_just_deletes(server: WebServer, fake, writes) -> None:
+ fake.add("old-thing:7b", size=1)
+ with TestClient(server.app) as client:
+ resp = client.delete(f"{BASE}/inventory/old-thing:7b")
+ gone = client.delete(f"{BASE}/inventory/old-thing:7b")
+ assert resp.status_code == 200
+ assert resp.json()["reassigned"] == []
+ assert writes == []
+ assert gone.status_code == 404
+
+
+def test_destructive_routes_carry_the_danger_flag() -> None:
+ flagged = {
+ route.path
+ for route in local_models_routes.router.routes
+ if (getattr(route, "openapi_extra", None) or {}).get("x-jarvis-dangerous")
+ }
+ assert f"{BASE.replace('ollama', '{provider_id}')}/inventory/{{name:path}}/unload" in flagged
+ assert f"{BASE.replace('ollama', '{provider_id}')}/inventory/{{name:path}}" in flagged
diff --git a/tests/unit/ultrawiki/test_embedding_models.py b/tests/unit/ultrawiki/test_embedding_models.py
index 7f6c3dcc86..03422f3519 100644
--- a/tests/unit/ultrawiki/test_embedding_models.py
+++ b/tests/unit/ultrawiki/test_embedding_models.py
@@ -186,3 +186,45 @@ def test_the_catalog_default_model_is_in_its_curated_list():
for spec in provider_catalog.EMBEDDING_PROVIDERS:
ids = {i for i, _label in em.CURATED_EMBEDDING_MODELS[spec.id]}
assert spec.default_model in ids, spec.id
+
+
+async def test_ollama_keeps_only_downloads_that_declare_embedding(cfg):
+ """A chat model in the embedding picker 400s on the first embed — /api/show
+ says which downloads actually embed, so only those are offered."""
+
+ def handler(request: httpx.Request) -> httpx.Response:
+ if request.url.path == "/api/tags":
+ return httpx.Response(
+ 200,
+ json={
+ "models": [
+ {"name": "qwen3.5:4b"},
+ {"name": "qwen3-embedding:4b"},
+ {"name": "qwen3.5-4b-jarvis-ab12cd34:latest"},
+ ]
+ },
+ )
+ if request.url.path == "/api/show":
+ name = json.loads(request.content)["model"]
+ caps = ["embedding"] if "embedding" in name else ["completion", "tools"]
+ return httpx.Response(200, json={"capabilities": caps})
+ return httpx.Response(404, json={"error": "nope"})
+
+ result = await em.list_embedding_models(
+ "ollama", cfg, transport=httpx.MockTransport(handler)
+ )
+ assert result.source == "live"
+ assert [m.id for m in result.models] == ["qwen3-embedding:4b"]
+
+
+async def test_ollama_with_only_chat_models_says_what_to_pull(cfg):
+ def handler(request: httpx.Request) -> httpx.Response:
+ if request.url.path == "/api/tags":
+ return httpx.Response(200, json={"models": [{"name": "qwen3.5:4b"}]})
+ return httpx.Response(200, json={"capabilities": ["completion"]})
+
+ result = await em.list_embedding_models(
+ "ollama", cfg, transport=httpx.MockTransport(handler)
+ )
+ assert result.source == "curated"
+ assert "pull" in result.reason