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): one fit verdict per job, readable names, an honest voice write
rubenluetke10-beepf771bb18b6fd
diff --git a/jarvis/brain/ollama_names.py b/jarvis/brain/ollama_names.pynew file mode 100644index 0000000000..f874d632e4--- /dev/null+++ b/jarvis/brain/ollama_names.py@@ -0,0 +1,262 @@+"""Readable names for Ollama downloads, from the tag and the manifest.++A tag is an address, not a name: ``deepseek-r1:latest`` hides that it is+the 8B, ``qwen3.8-16gb:latest`` is a 27B at IQ2_S whatever its author called+it, and ``gemma4:12b-it-qat`` carries two variant markers a person scanning+a list does not need. The "Local models" section showed every one of them+verbatim, so a user had to know the tags by heart to tell the cards apart.++:func:`describe` turns a tag plus the ``/api/show`` facts into the parts a+card shows separately: the family name humanised from the repository part+of the tag ("Qwen 3.5", "DeepSeek R1", "BGE M3"), the parameter count as+a short label ("4B", "27B", "567M" — the tag's own size token when it has+one, the manifest's otherwise), the quantisation, and the source namespace+for Hugging Face imports. The tag itself stays on the card, small, so the+address is never lost.++:func:`alias_kind` / :func:`base_of` fold Jarvis's own derived models — the+Tune profiles ``<base>-jarvis-<hash>`` and the voice brain's+``<base>-voice-<N>k`` — back onto the download they share their weights+with, so a loaded alias counts for its base instead of for nobody.++Pure functions, no I/O; the inventory and overview builders call them.+"""++from __future__ import annotations++import re+from collections.abc import Iterable+from dataclasses import dataclass++__all__ = [+ "ModelName",+ "alias_kind",+ "base_of",+ "describe",+ "params_label",+]++_PROFILE_ALIAS_RE = re.compile(r"^(?P<prefix>.+)-jarvis-[0-9a-f]{8}$")+_VOICE_ALIAS_RE = re.compile(r"^(?P<prefix>.+)-voice-\d+k$")++#: Family words whose casing a plain ``capitalize()`` gets wrong.+_WORDS: dict[str, str] = {+ "arctic": "Arctic",+ "bge": "BGE",+ "cascade": "Cascade",+ "codellama": "CodeLlama",+ "coder": "Coder",+ "deepseek": "DeepSeek",+ "dolphin": "Dolphin",+ "e5": "E5",+ "embed": "Embed",+ "embedding": "Embedding",+ "embeddinggemma": "EmbeddingGemma",+ "gemma": "Gemma",+ "glimmer": "Glimmer",+ "glm": "GLM",+ "gpt": "GPT",+ "granite": "Granite",+ "hermes": "Hermes",+ "kimi": "Kimi",+ "lfm": "LFM",+ "lightning": "Lightning",+ "llama": "Llama",+ "llm": "LLM",+ "minicpm": "MiniCPM",+ "minilm": "MiniLM",+ "mistral": "Mistral",+ "mixtral": "Mixtral",+ "moe": "MoE",+ "muse": "Muse",+ "mxbai": "MxBAI",+ "nemotron": "Nemotron",+ "nomic": "Nomic",+ "olmo": "OLMo",+ "ornith": "Ornith",+ "oss": "OSS",+ "phi": "Phi",+ "qwen": "Qwen",+ "qwq": "QwQ",+ "smollm": "SmolLM",+ "snowflake": "Snowflake",+ "starcoder": "StarCoder",+ "tinyllama": "TinyLlama",+ "vl": "VL",+ "yi": "Yi",+}++#: Variant markers that describe a build, not a model line.+_DROP = frozenset({"it", "instruct", "chat", "qat", "latest", "gguf"})+_SIZE_TOKEN = re.compile(r"^(\d+(?:\.\d+)?)(b|m|k|gb)$")+_ACTIVE_TOKEN = re.compile(r"^a\d+(?:\.\d+)?b$")+_QUANT_TOKEN = re.compile(r"^(i?q\d[a-z0-9_]*|fp\d+|f\d+|bf\d+|int\d+)$")+_WORD_NUM = re.compile(r"^([a-z]+)(\d+(?:\.\d+)?)$")+_NUMBER = re.compile(r"^\d+(?:\.\d+)?$")+_PARAMS = re.compile(r"^(\d+(?:\.\d+)?)\s*([bmk])$", re.IGNORECASE)+++@dataclass(frozen=True, slots=True)+class ModelName:+ """The parts of a readable model name, for a card to lay out."""++ #: The model line, humanised: "Qwen 3.5", "DeepSeek R1", "BGE M3".+ name: str+ #: Parameter count as a short label: "4B", "27B", "567M"; "" unknown.+ params: str+ #: Quantisation as the manifest spells it: "Q4_K_M", "IQ2_S"; "" unknown.+ quant: str+ #: ``name`` and ``params`` in one line: "Qwen 3.5 4B".+ label: str+ #: Where the tag comes from when not the Ollama library: "hf.co/unsloth".+ source: str+ #: Variant markers the tag carries beyond the size: "it-qat"; "" none.+ variant: str+++def _strip_latest(tag: str) -> str:+ return tag[: -len(":latest")] if tag.endswith(":latest") else tag+++def _tokens(text: str) -> list[str]:+ """Split on ``-``, then on ``_`` — except inside a quantisation token+ (``q4_k_m``), whose underscores are part of the name."""+ out: list[str] = []+ for piece in text.lower().split("-"):+ if not piece:+ continue+ if _QUANT_TOKEN.match(piece):+ out.append(piece)+ continue+ out.extend(p for p in piece.split("_") if p)+ return out+++def _humanise(part: str) -> str:+ if part in _WORDS:+ return _WORDS[part]+ if _NUMBER.match(part):+ return part+ match = _WORD_NUM.match(part)+ if match:+ word, number = match.groups()+ if len(word) == 1:+ return f"{word.upper()}{number}"+ return f"{_WORDS.get(word, word.capitalize())} {number}"+ return part.capitalize()+++def params_label(parameter_size: str, tag_token: str = "") -> str:+ """``"9.0B"`` → ``"9B"``, ``"26.9B"`` → ``"27B"``, ``"566.70M"`` → ``"567M"``.++ A size token in the tag (``:4b``, ``:14b``) wins over the manifest: it is+ the size the model is known by, and ``4.7B`` next to a card everyone+ calls "the 4B" reads like a different model.+ """+ token = _SIZE_TOKEN.match(tag_token.lower()) if tag_token else None+ if token and token.group(2) in ("b", "m"):+ number, unit = token.groups()+ return f"{_short_number(float(number))}{unit.upper()}"+ match = _PARAMS.match((parameter_size or "").strip())+ if not match:+ return ""+ number, unit = match.groups()+ return f"{_short_number(float(number))}{unit.upper()}"+++def _short_number(value: float) -> str:+ if value >= 10:+ return str(int(round(value)))+ text = f"{value:.1f}"+ return text[:-2] if text.endswith(".0") else text+++def describe(tag: str, parameter_size: str = "", quantization_level: str = "") -> ModelName:+ """The readable parts of ``tag`` (any Ollama tag, ``hf.co/`` imports too)."""+ bare = _strip_latest((tag or "").strip())+ if not bare:+ return ModelName(name="", params="", quant="", label="", source="", variant="")+ repo, _, variant = bare.partition(":")+ source = ""+ if repo.lower().startswith("hf.co/") or repo.lower().startswith("huggingface.co/"):+ pieces = repo.split("/")+ source = "/".join(pieces[:2])+ repo = pieces[-1]+ elif "/" in repo:+ namespace, _, repo = repo.rpartition("/")+ source = namespace++ words: list[str] = []+ size_token = ""+ for part in _tokens(repo):+ if not part or part in _DROP:+ continue+ if _SIZE_TOKEN.match(part):+ if part.endswith("b") or part.endswith("m"):+ size_token = size_token or part+ continue+ if _ACTIVE_TOKEN.match(part) or _QUANT_TOKEN.match(part):+ continue+ words.append(_humanise(part))++ variant_words: list[str] = []+ for part in _tokens(variant):+ if not part or part == "latest":+ continue+ if _SIZE_TOKEN.match(part):+ size_token = size_token or part+ continue+ if _QUANT_TOKEN.match(part) and not quantization_level:+ quantization_level = part.upper()+ continue+ variant_words.append(part)++ name = " ".join(words) or repo+ params = params_label(parameter_size, size_token)+ quant = (quantization_level or "").strip()+ label = f"{name} {params}".strip()+ return ModelName(+ name=name,+ params=params,+ quant=quant,+ label=label,+ source=source,+ variant="-".join(variant_words),+ )+++def alias_kind(tag: str) -> str:+ """``"tune_profile"`` | ``"voice_profile"`` | ``""`` for a user's download."""+ bare = _strip_latest((tag or "").strip())+ if _PROFILE_ALIAS_RE.match(bare):+ return "tune_profile"+ if _VOICE_ALIAS_RE.match(bare):+ return "voice_profile"+ return ""+++def _fold(tag: str) -> str:+ return _strip_latest(tag.strip()).replace(":", "-").replace("/", "-")+++def base_of(tag: str, candidates: Iterable[str] = ()) -> str:+ """The download an alias shares its weights with; ``tag`` itself otherwise.++ A voice alias keeps the base's ``:`` (``ornith:9b-voice-32k``), so the+ suffix simply comes off. A Tune profile folded ``:`` and ``/`` into ``-``+ when it was named (``ornith-9b-jarvis-1a2b3c4d``), so the base is the+ candidate whose folded name equals the prefix; with no candidate to+ match, the folded prefix is the best answer there is.+ """+ bare = _strip_latest((tag or "").strip())+ voice = _VOICE_ALIAS_RE.match(bare)+ if voice:+ return voice.group("prefix")+ profile = _PROFILE_ALIAS_RE.match(bare)+ if not profile:+ return bare+ prefix = profile.group("prefix")+ for candidate in candidates:+ if _fold(candidate) == prefix:+ return _strip_latest(candidate.strip())+ return prefixdiff --git a/jarvis/brain/ollama_overview.py b/jarvis/brain/ollama_overview.pyindex ba9a5f66a4..6532dc81da 100644--- a/jarvis/brain/ollama_overview.py+++ b/jarvis/brain/ollama_overview.py@@ -34,6 +34,7 @@ from pathlib import Pathfrom typing import Anyfrom jarvis.brain import ollama_inventory as inventory+from jarvis.brain import ollama_names as namesfrom jarvis.brain import ollama_pull, ollama_roles, ollama_runtimefrom jarvis.brain.ollama_inventory import (OllamaModelInfo,@@ -56,6 +57,7 @@ __all__ = ["is_paintable","load_snapshot","model_row",+ "resident_payload","role_row","roles_payload","running_row",@@ -77,13 +79,32 @@ STALE_AFTER_S = 24 * 3600.0# ── Row builders (the wire shape, spelled out once) ──────────────────────+def _live_entry(+ info: OllamaModelInfo, running: dict[str, OllamaRunningModel]+) -> OllamaRunningModel | None:+ """The ``/api/ps`` entry holding ``info``'s weights — the download itself+ or one of its aliases (a Tune profile, the voice brain's context alias),+ which is what is actually resident during a call or a tuned chat."""+ for key, entry in running.items():+ if same_model(key, info.name) or same_model(names.base_of(key, [info.name]), info.name):+ return entry+ return None++def model_row(info: OllamaModelInfo, running: dict[str, OllamaRunningModel], used_by: list[str]) -> dict[str, Any]:"""One inventory row: the download's facts plus what ``/api/ps`` says."""- live = next((r for key, r in running.items() if same_model(key, info.name)), None)+ live = _live_entry(info, running)+ shown = names.describe(info.name, info.parameter_size, info.quantization_level)return {"name": info.name,+ "display_name": shown.name,+ "display_label": shown.label,+ "params_label": shown.params,+ "quant_label": shown.quant,+ "source": shown.source,+ "variant": shown.variant,"size_bytes": info.size_bytes,"digest": info.digest,"modified_at": info.modified_at,@@ -96,14 +117,19 @@ def model_row("probed": info.probed,"used_by": used_by,"loaded": live is not None,+ "loaded_as": live.name if live else "","size_vram_bytes": live.size_vram_bytes if live else 0,+ "loaded_size_bytes": live.size_bytes if live else 0,"expires_at": live.expires_at if live else "","running_context_length": live.context_length if live else None,}-def running_row(model: OllamaRunningModel) -> dict[str, Any]:- return asdict(model)+def running_row(model: OllamaRunningModel, candidates: list[str] | None = None) -> dict[str, Any]:+ row = asdict(model)+ row["base_tag"] = names.base_of(model.name, candidates or [])+ row["kind"] = names.alias_kind(model.name) or "model"+ return rowdef role_row(state: ollama_roles.RoleState) -> dict[str, Any]:@@ -112,11 +138,21 @@ def role_row(state: ollama_roles.RoleState) -> dict[str, Any]:"id": spec.id,"label_key": spec.label_key,"config_key": spec.config_key,+ "layout": spec.layout,"current": state.current,"installed": state.installed,+ "current_fit": state.current_fit,+ "current_reason": state.current_reason,"required": list(spec.required),"recommended_capabilities": list(spec.recommended),"qualifying": list(state.qualifying),+ "choices": [+ {"tag": tag, "fit": fit, "reason": reason} for tag, fit, reason in state.choices+ ],+ "downloads": [+ {"tag": tag, "label": label, "size_gb": size, "fit": fit, "note": note}+ for tag, label, size, fit, note in state.downloads+ ],"recommended": state.recommended,"recommended_reason": state.recommended_reason,"writable": spec.writable,@@ -127,6 +163,86 @@ def role_row(state: ollama_roles.RoleState) -> dict[str, Any]:# The size class the job prefers (the voice brain answers within a# breath, so it stays under 6 GB); ``None`` when the job has none."max_size_gb": spec.max_size_gb,+ "min_context_tokens": spec.min_context_tokens,+ }+++#: Rough extra memory a context window costs, in GiB per 1k tokens per GiB of+#: weights — the rule of thumb the Tune suggestion and the frontend chip use.+_CONTEXT_GB_PER_K_PER_GB = 0.03+#: The window an unloaded, untuned model is assumed to open with.+_DEFAULT_CONTEXT_TOKENS = 8192+++def _context_gb(tokens: int | None, weights_gb: float) -> float:+ return (+ (float(tokens or _DEFAULT_CONTEXT_TOKENS) / 1000.0)+ * _CONTEXT_GB_PER_K_PER_GB+ * max(weights_gb, 0.5)+ )+++def resident_payload(+ states: list[ollama_roles.RoleState],+ models: list[OllamaModelInfo],+ running: dict[str, OllamaRunningModel],+ machine: ollama_roles.Machine,+ *,+ voice_reserve_gb: float = 0.0,+) -> dict[str, Any]:+ """What sits in graphics memory when every job is loaded at once.++ The per-card bar answers "does THIS model fit"; this answers the question+ that decides a local setup — whether the chat model, the voice brain and+ the embedder fit TOGETHER, because a call arrives while a chat is loaded.+ One item per distinct download across the writable roles (a model on+ three jobs is loaded once), each with its weights, its context estimate+ (the live ``/api/ps`` figure when loaded, the rule of thumb otherwise)+ and the roles it serves; plus the reserve the local speech stack keeps+ free beside the voice brain. ``over`` says the total exceeds the card.+ """+ by_name = {m.name: m for m in models}+ items: list[dict[str, Any]] = []+ seen: dict[str, dict[str, Any]] = {}+ for state in states:+ if not state.spec.writable or not state.current:+ continue+ info = next((m for m in models if same_model(m.name, state.current)), None)+ if info is None:+ continue+ key = info.name+ if key in seen:+ seen[key]["roles"].append(state.spec.id)+ continue+ weights_gb = info.size_bytes / (1024**3)+ live = _live_entry(info, running)+ tokens = state.context_tokens if state.spec.id == "voice" else None+ if live is not None:+ context_gb = max(0.0, (live.size_bytes - info.size_bytes) / (1024**3))+ tokens = live.context_length or tokens+ else:+ context_gb = _context_gb(tokens, weights_gb)+ shown = names.describe(info.name, info.parameter_size, info.quantization_level)+ item = {+ "tag": info.name,+ "display_label": shown.label,+ "roles": [state.spec.id],+ "weights_gb": round(weights_gb, 2),+ "context_gb": round(context_gb, 2),+ "context_tokens": tokens,+ "loaded": live is not None,+ }+ seen[key] = item+ items.append(item)+ del by_name+ total = sum(i["weights_gb"] + i["context_gb"] for i in items) + voice_reserve_gb+ accelerator = machine.accelerator_gb+ return {+ "items": items,+ "reserve_gb": round(voice_reserve_gb, 2),+ "total_gb": round(total, 2),+ "accelerator_gb": accelerator,+ "over": bool(accelerator > 0 and total > accelerator),}@@ -159,6 +275,7 @@ def _inventory_from("error": error,}running = {r.name: r for r in snapshot.running}+ candidates = [m.name for m in snapshot.models]return {"provider": provider_id,"server": root,@@ -166,7 +283,7 @@ def _inventory_from(model_row(m, running, ollama_roles.roles_using(cfg, m.name) if cfg else [])for m in snapshot.models],- "running": [running_row(r) for r in snapshot.running],+ "running": [running_row(r, candidates) for r in snapshot.running],"disk_bytes": sum(m.size_bytes for m in snapshot.models),"loaded_vram_bytes": sum(r.size_vram_bytes for r in snapshot.running),"error": None,@@ -193,14 +310,35 @@ async def _roles_from(states, _unused = await ollama_roles.list_roles(root, cfg, models=models, shortlist=shortlist, machine=machine)+ running = {r.name: r for r in snapshot.running} if snapshot is not None else {}return {"provider": provider_id,"server": root,"roles": [role_row(s) for s in states],+ "resident": resident_payload(+ states,+ models,+ running,+ machine or ollama_roles.Machine(),+ voice_reserve_gb=_voice_reserve_gb(states),+ ),"error": error,}+def _voice_reserve_gb(states: list[ollama_roles.RoleState]) -> float:+ """The memory the local speech stack keeps free beside the voice brain —+ only when a voice brain is picked (the stack is installed and configured)."""+ voice = next((s for s in states if s.spec.id == "voice"), None)+ if voice is None or not voice.current:+ return 0.0+ try:+ from jarvis.realtime.local_server.supervisor import VOICE_STACK_RESERVE_GB+ except Exception: # noqa: BLE001 — the reserve is an estimate, never a blocker+ return 0.0+ return float(VOICE_STACK_RESERVE_GB)++async def roles_payload(provider_id: str, root: str, cfg: Any) -> dict[str, Any]:"""Every role with its pick, what qualifies, and the recommendation —the body of ``GET .../roles``."""diff --git a/jarvis/brain/ollama_roles.py b/jarvis/brain/ollama_roles.pyindex 3f321fd62c..023b9fac49 100644--- a/jarvis/brain/ollama_roles.py+++ b/jarvis/brain/ollama_roles.py@@ -38,12 +38,16 @@ from jarvis.brain.ollama_inventory import OllamaModelInfo, OllamaServerError, salog = logging.getLogger(__name__)__all__ = [+ "FITS","ROLES","WRITABLE_ROLE_IDS","Machine","RoleSpec","RoleState",+ "choices_for","current_pick",+ "download_picks",+ "fit_for","list_roles","machine_from","pick_installed",@@ -81,6 +85,14 @@ class RoleSpec:#: where speed beats depth (a call must answer within a breath). ``None``#: = the largest model that fits wins.max_size_gb: float | None = None+ #: The smallest native context window that can do the job; a model whose+ #: manifest declares less is unfit, not merely slow. ``None`` = no floor.+ min_context_tokens: int | None = None+ #: Where the section shows the role: ``card`` (one of the peers the user+ #: talks to), ``row`` (set here, not part of the conversation) or+ #: ``footnote`` (follows another pick; read-only). The frontend iterates+ #: what the backend sends, so a new role lands somewhere by construction.+ layout: str = "card"ROLES: tuple[RoleSpec, ...] = (@@ -96,13 +108,19 @@ ROLES: tuple[RoleSpec, ...] = (id="voice",label_key="local_models.role_voice",config_key="brain.providers.local-realtime.launch_command",- required=("completion",),- recommended=("tools",),+ # The live model calls every Jarvis tool itself (ADR-0035), so a+ # download without tool calls is a conversation without hands — a+ # gate, not a preference. Ollama declares ``tools`` per manifest.+ required=("completion", "tools"),+ recommended=("thinking",),pull_role="chat",# A call is judged by its first word, not its best one: the pick stays# in the class that answers within a breath, the chat slot takes the# depth.max_size_gb=6.0,+ # The voice brain runs a machine-sized window of 8k or more; a 4k+ # model would truncate the call's own history.+ min_context_tokens=8192,),RoleSpec(id="tools_screen",@@ -127,6 +145,7 @@ ROLES: tuple[RoleSpec, ...] = (required=("embedding",),recommended=(),pull_role="embedding",+ layout="row",),# Read-only consumers: the ack and polish models have their own pickers# on their own cards, so the rows only say which tag they follow.@@ -139,6 +158,7 @@ ROLES: tuple[RoleSpec, ...] = (pull_role="chat",writable=False,advanced=True,+ layout="footnote",),RoleSpec(id="polish",@@ -149,6 +169,7 @@ ROLES: tuple[RoleSpec, ...] = (pull_role="chat",writable=False,advanced=True,+ layout="footnote",),)@@ -178,6 +199,36 @@ class RoleState:context_tokens: int | None = None#: ``"automatic"`` (sized from memory) | ``"manual"`` (set in Tune) | ``""``.context_source: str = ""+ #: Every installed download judged for this job, inventory order:+ #: ``(tag, fit, reason)`` with ``fit`` from :data:`FITS`.+ choices: tuple[tuple[str, str, str], ...] = ()+ #: The verdict on ``current`` itself: a fit from :data:`FITS`, ``absent``+ #: when it is configured but not on the server, ``""`` when nothing is set.+ current_fit: str = ""+ current_reason: str = ""+ #: Downloads from the shortlist that would do this job on this machine+ #: and are not installed yet: ``(tag, label, size_gb, fit, note)``.+ downloads: tuple[tuple[str, str, float, str, str], ...] = ()+++#: The verdicts :func:`fit_for` hands out, strongest first.+#:+#: ``fits`` — declares every required capability, sits inside the job's size+#: class and context floor, and fits this machine; ``slow`` — can do the job+#: but costs something the job feels (over the size class, or spilling past+#: the graphics memory); ``unfit`` — lacks a required capability, declares a+#: window under the floor, or cannot be held by this machine at all;+#: ``unknown`` — ``/api/show`` did not answer, so nothing can be said.+FITS: tuple[str, ...] = ("fits", "slow", "unfit", "unknown")++_CAPABILITY_WORDS: dict[str, str] = {+ "tools": "no tool calls",+ "vision": "no vision",+ "thinking": "no thinking",+ "embedding": "not an embedding model",+ "completion": "no text completion",+ "audio": "no audio",+}# ── Reading ──────────────────────────────────────────────────────────────@@ -270,22 +321,6 @@ def _voice_pick(cfg: Any) -> tuple[str, str]:return _voice_context_models(model)[0], ""-def qualifying_models(spec: RoleSpec, models: list[OllamaModelInfo]) -> tuple[str, ...]:- """Installed tags that declare every capability ``spec`` requires.-- A row whose ``/api/show`` failed (``probed=False``) is left out: "unknown"- must not read as "qualifies", or a screen reader without vision gets- assigned and fails on the first screenshot.- """- out: list[str] = []- for info in models:- if not info.probed:- continue- if all(cap in info.capabilities for cap in spec.required):- out.append(info.name)- return tuple(out)--@dataclass(frozen=True, slots=True)class Machine:"""The memory an installed pick is judged against.@@ -303,6 +338,79 @@ def _size_gb(info: OllamaModelInfo) -> float:return info.size_bytes / _GIB+def _context_label(tokens: int) -> str:+ return f"{tokens // 1024}k" if tokens >= 1024 else str(tokens)+++def fit_for(+ spec: RoleSpec, info: OllamaModelInfo, machine: Machine | None = None+) -> tuple[str, str]:+ """``(fit, reason)`` — the ONE verdict on ``info`` doing ``spec``'s job.++ The card, the picker, the catalogue badge and the setup automation all+ read this; nothing else re-derives it (BUG-188's over-correction came+ from a second definition of "fits" in the client). The reason is one+ short English clause the picker shows beside the name — "" when it fits.+ """+ machine = machine or Machine()+ if not info.probed:+ return "unknown", "Jarvis could not read what this model can do."+ missing = [cap for cap in spec.required if cap not in info.capabilities]+ if missing:+ return "unfit", ", ".join(_CAPABILITY_WORDS.get(cap, f"no {cap}") for cap in missing)+ floor = spec.min_context_tokens+ if floor and info.context_length and info.context_length < floor:+ return (+ "unfit",+ f"{_context_label(info.context_length)} context — this job needs "+ f"{_context_label(floor)} or more",+ )+ size = _size_gb(info)+ verdict, _note = ollama_pull.fit_verdict(size, machine.memory_gb, machine.accelerator_gb)+ over_card = (+ machine.accelerator_gb > 0 and size + ollama_pull._OVERHEAD_GB > machine.accelerator_gb+ )+ if verdict == "tight" and spec.max_size_gb is not None:+ # A job that must answer within a breath cannot wait for the CPU.+ if over_card:+ return (+ "unfit",+ f"{size:.1f} GB — over the {machine.accelerator_gb:.0f} GB of graphics memory",+ )+ return "unfit", f"{size:.1f} GB — too tight on this machine's memory for a call"+ if spec.max_size_gb is not None and size > spec.max_size_gb:+ return "slow", f"{size:.1f} GB — over {spec.max_size_gb:g} GB, slower to answer"+ if verdict == "tight":+ if over_card:+ return "slow", (+ f"{size:.1f} GB — bigger than the {machine.accelerator_gb:.0f} GB of "+ "graphics memory, runs partly on the processor"+ )+ return "slow", f"{size:.1f} GB — tight on this machine's memory"+ return "fits", ""+++def choices_for(+ spec: RoleSpec, models: list[OllamaModelInfo], machine: Machine | None = None+) -> tuple[tuple[str, str, str], ...]:+ """Every installed download with its verdict for ``spec``, inventory order."""+ return tuple((info.name, *fit_for(spec, info, machine)) for info in models)+++def qualifying_models(+ spec: RoleSpec, models: list[OllamaModelInfo], machine: Machine | None = None+) -> tuple[str, ...]:+ """Installed tags that can do ``spec``'s job (``fits`` or ``slow``).++ A row whose ``/api/show`` failed (``probed=False``) is left out: "unknown"+ must not read as "qualifies", or a screen reader without vision gets+ assigned and fails on the first screenshot.+ """+ return tuple(+ name for name, fit, _reason in choices_for(spec, models, machine) if fit in ("fits", "slow")+ )++def _has_preferred(spec: RoleSpec, info: OllamaModelInfo) -> bool:return all(cap in info.capabilities for cap in spec.recommended)@@ -327,11 +435,7 @@ def pick_installed(runs it. A role with ``max_size_gb`` prefers the class under that size.The reason is one English sentence the row shows beside the button."""- candidates = [- info- for info in models- if info.probed and all(c in info.capabilities for c in spec.required)- ]+ candidates = [info for info in models if fit_for(spec, info, machine)[0] in ("fits", "slow")]if not candidates:return "", ""preferred = _preferred_clause(spec)@@ -374,6 +478,29 @@ def pick_installed()+def _row_serves(spec: RoleSpec, row: dict[str, Any]) -> bool:+ """Whether a shortlist row could do ``spec``'s job at all.++ The shortlist knows two capabilities per entry (``tools``, ``vision``)+ and its role; the size class is the same gate the installed picks get,+ so the voice slot is never sent a 25 GB download for a 6 GB job.+ """+ role_ok = row.get("role") == spec.pull_role or ollama_pull._serves_vision(spec.pull_role, row)+ if not role_ok:+ return False+ # Curated entries declare ``tools`` (default True in the shortlist) and+ # ``vision``; a row without the key is a chat-class model that has them.+ if "tools" in spec.required and not row.get("tools", True):+ return False+ if "vision" in spec.required and not row.get("vision", False):+ return False+ if spec.max_size_gb is not None:+ size = float(row.get("size_gb") or 0)+ if size > spec.max_size_gb:+ return False+ return row.get("fit") != "tight" or spec.max_size_gb is None++def _recommended_for(spec: RoleSpec, rows: list[dict[str, Any]]) -> str:"""The shortlist's pick for ``spec`` on this machine — the fallback when:func:`pick_installed` found nothing installed that qualifies.@@ -381,22 +508,47 @@ def _recommended_for(spec: RoleSpec, rows: list[dict[str, Any]]) -> str::func:`ollama_pull._pick_recommended` marks nothing for a role that hasa curated model installed already — the user has chosen. Then thelargest INSTALLED curated model of that role is named instead, so the- "Use recommended" button always has something honest to assign.+ "Use recommended" button always has something honest to assign. Either+ way the entry has to pass :func:`_row_serves` — the job's own gates."""for row in rows:- if spec.pull_role in (row.get("recommended_for") or []):+ if spec.pull_role in (row.get("recommended_for") or []) and _row_serves(spec, row):return str(row["id"])- installed = [- row- for row in rows- if row.get("installed")- and (row.get("role") == spec.pull_role or ollama_pull._serves_vision(spec.pull_role, row))- ]+ serving = [row for row in rows if _row_serves(spec, row)]+ installed = [row for row in serving if row.get("installed")]if installed:return str(max(installed, key=lambda r: float(r.get("size_gb") or 0))["id"])+ comfortable = [row for row in serving if row.get("fit") == "comfortable"]+ if comfortable:+ return str(max(comfortable, key=lambda r: float(r.get("size_gb") or 0))["id"])return ""+def download_picks(+ spec: RoleSpec, rows: list[dict[str, Any]], *, limit: int = 3+) -> tuple[tuple[str, str, float, str, str], ...]:+ """Shortlist entries that would do ``spec``'s job here and are not on disk.++ What the picker offers under "download a pick": the curated, reviewed+ entries (``ollama_pull.RECOMMENDED_MODELS``, dated by+ ``CURATED_REVIEWED_ON``) that pass the job's gates, largest comfortable+ first, then the tight ones — never more than ``limit``.+ """+ serving = [row for row in rows if _row_serves(spec, row) and not row.get("installed")]+ order = {"comfortable": 0, "unknown": 1, "tight": 2}+ serving.sort(key=lambda r: (order.get(str(r.get("fit")), 3), -float(r.get("size_gb") or 0)))+ return tuple(+ (+ str(row["id"]),+ str(row.get("label") or row["id"]),+ float(row.get("size_gb") or 0),+ str(row.get("fit") or "unknown"),+ str(row.get("fit_note") or ""),+ )+ for row in serving[:limit]+ )++def machine_from(recommended: dict[str, Any] | None) -> Machine:"""The :class:`Machine` a shortlist payload was judged against."""if not isinstance(recommended, dict):@@ -453,7 +605,8 @@ async def list_roles(states: list[RoleState] = []for spec in ROLES:current, note = current_pick(cfg, spec.id)- qualifying = qualifying_models(spec, models)+ choices = choices_for(spec, models, machine)+ qualifying = tuple(name for name, fit, _r in choices if fit in ("fits", "slow"))context_tokens: int | None = Nonecontext_source = ""if spec.id == "voice" and current and error is None:@@ -463,17 +616,31 @@ async def list_roles(recommended_tag = _recommended_for(spec, shortlist)if recommended_tag:reason = "Nothing installed fits this job yet; this download is the pick."+ installed = bool(current) and any(same_model(m.name, current) for m in models)+ current_fit, current_reason = "", ""+ if current:+ verdict = next((c for c in choices if same_model(c[0], current)), None)+ if verdict is not None:+ current_fit, current_reason = verdict[1], verdict[2]+ elif error is not None:+ current_fit, current_reason = "unknown", "The server did not answer."+ else:+ current_fit, current_reason = "absent", "Not downloaded."states.append(RoleState(spec=spec,current=current,- installed=bool(current) and any(same_model(m.name, current) for m in models),+ installed=installed,qualifying=qualifying,recommended=recommended_tag,recommended_reason=reason,note=note,context_tokens=context_tokens,context_source=context_source,+ choices=choices,+ current_fit=current_fit,+ current_reason=current_reason,+ downloads=download_picks(spec, shortlist) if spec.writable else (),))return states, error@@ -552,8 +719,20 @@ def set_role(role_id: str, model: str, *, cfg: Any = None) -> dict[str, Any]:"answers with the Chat model.")# The same writer the voice card uses: rewrites ONLY the model flag of- # the persisted command, never a bring-your-own command.- config_writer.update_local_realtime_launch_model(tag)+ # the persisted command, never a bring-your-own command. It answers+ # False when nothing reached jarvis.toml — a missing block, a command+ # without the flag, or the same value — and only the last of those+ # is a no-op the caller may call a success (BUG class: a pick that+ # reads back from memory while the file still holds the old one).+ current_tag, _note = _voice_pick(cfg)+ written = config_writer.update_local_realtime_launch_model(tag)+ if not written and not same_model(current_tag, tag):+ raise ValueError(+ "The voice server's launch command in jarvis.toml could not be "+ "updated — it names no --model_name, or the local-realtime block "+ "is missing. Reinstall the managed voice server from the Voice "+ "settings, then pick again."+ )if voice is not None:from jarvis.realtime.local_server.supervisor import _replace_brain_model@@ -587,11 +766,16 @@ def set_role(role_id: str, model: str, *, cfg: Any = None) -> dict[str, Any]:}-def roles_using(cfg: Any, name: str) -> list[str]:- """Writable role ids whose configured pick is ``name`` (``:latest`` tolerant)."""+def roles_using(cfg: Any, name: str, *, include_readonly: bool = False) -> list[str]:+ """Role ids whose configured pick is ``name`` (``:latest`` tolerant).++ Writable roles by default; ``include_readonly`` adds the consumers that+ pin their own tag elsewhere (the quick ack, dictation polish), so a+ delete can refuse to pull the model out from under them.+ """out: list[str] = []for spec in ROLES:- if not spec.writable:+ if not spec.writable and not include_readonly:continuecurrent, _note = current_pick(cfg, spec.id)if current and same_model(current, name):diff --git a/jarvis/local_models/health_monitor.py b/jarvis/local_models/health_monitor.pyindex 437357b7ed..0992895f21 100644--- a/jarvis/local_models/health_monitor.py+++ b/jarvis/local_models/health_monitor.py@@ -247,6 +247,10 @@ async def check_once(# ── the on-demand proof ───────────────────────────────────────────────────EmbedFn = Callable[[str, str], Awaitable[int]]+#: ``(root, model) -> detail`` for the two capability probes below; a probe+#: raises when the model cannot do the job, and returns one sentence when it+#: can (what it answered, briefly).+CapabilityFn = Callable[[str, str], Awaitable[str]]async def _default_embed(root: str, model: str) -> int:@@ -255,12 +259,135 @@ async def _default_embed(root: str, model: str) -> int:return await embed_probe(root, model)+#: A 1×1 white PNG — the smallest image a vision model can be asked about.+_PROBE_PNG_B64 = (+ "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+ip1sAAAAASUVORK5CYII="+)++_PROBE_TOOL = {+ "type": "function",+ "function": {+ "name": "ping",+ "description": "Answer the check. Call this tool with the word you were given.",+ "parameters": {+ "type": "object",+ "properties": {"word": {"type": "string"}},+ "required": ["word"],+ },+ },+}+++async def _chat_probe(root: str, body: dict[str, Any]) -> dict[str, Any]:+ """One ``/api/chat`` round trip; raises with Ollama's own sentence on refusal."""+ from jarvis.brain import ollama_inventory+ from jarvis.plugins.brain.ollama import normalize_server_root++ root = normalize_server_root(root)+ # The inventory's client factory, so tests drive this through the same+ # fake server the sweep uses instead of the network.+ async with ollama_inventory._make_client() as client:+ resp = await client.post(+ f"{root}/api/chat", json={**body, "stream": False}, timeout=GENERATION_CAP_S+ )+ if resp.status_code >= 400:+ try:+ detail = str(resp.json().get("error") or "")+ except ValueError:+ detail = ""+ raise RuntimeError(detail or f"Ollama answered {resp.status_code}.")+ payload = resp.json()+ return payload if isinstance(payload, dict) else {}+++async def _default_tool_call(root: str, model: str) -> str:+ """Prove ``model`` can call a tool: one request with one tool, and the+ answer must carry a tool call — that is what a voice turn relies on."""+ payload = await _chat_probe(+ root,+ {+ "model": model,+ "messages": [+ {+ "role": "user",+ "content": "Call the ping tool with the word 'jarvis'. Do not answer in text.",+ }+ ],+ "tools": [_PROBE_TOOL],+ "options": {"num_predict": 64, "temperature": 0},+ "keep_alive": "5m",+ },+ )+ message = payload.get("message") or {}+ calls = message.get("tool_calls") if isinstance(message, dict) else None+ if not calls:+ raise RuntimeError("Answered in text instead of calling the tool.")+ return "Called the tool."+++async def _default_vision(root: str, model: str) -> str:+ """Prove ``model`` can look at a picture: one request with one image."""+ payload = await _chat_probe(+ root,+ {+ "model": model,+ "messages": [+ {+ "role": "user",+ "content": "One word: what colour is this image?",+ "images": [_PROBE_PNG_B64],+ }+ ],+ "options": {"num_predict": 16, "temperature": 0},+ "keep_alive": "5m",+ },+ )+ message = payload.get("message") or {}+ text = str(message.get("content") or "").strip() if isinstance(message, dict) else ""+ if not text:+ raise RuntimeError("The server answered without any text.")+ return f"Saw the image: {text[:40]}"++def _step(step_id: str, ok: bool | None, *, model: str = "", detail: str = "", ms: int = 0) -> dict[str, Any]:return {"id": step_id, "ok": ok, "model": model, "detail": detail, "ms": ms}+async def _capability_step(+ step_id: str, model: str, root: str, probe: CapabilityFn, *, missing: str+) -> dict[str, Any]:+ """One timed capability probe as a verify step; ``None`` when unconfigured."""+ import time++ if not model:+ return _step(step_id, None, detail=missing)+ started = time.monotonic()+ try:+ detail = await asyncio.wait_for(probe(root, model), timeout=GENERATION_CAP_S)+ except TimeoutError:+ return _step(+ step_id,+ False,+ model=model,+ detail=f"No answer within {GENERATION_CAP_S:.0f} s.",+ ms=int(GENERATION_CAP_S * 1000),+ )+ except Exception as exc: # noqa: BLE001 — the step says so, the log keeps it+ log.info("verify: %s probe on %s failed", step_id, model, exc_info=True)+ return _step(+ step_id,+ False,+ model=model,+ detail=str(exc) or type(exc).__name__,+ ms=int((time.monotonic() - started) * 1000),+ )+ return _step(+ step_id, True, model=model, detail=detail, ms=int((time.monotonic() - started) * 1000)+ )++async def verify_setup(cfg: Any,*,@@ -268,24 +395,30 @@ async def verify_setup(probe: ProbeFn | None = None,generate: GenerateFn | None = None,embed: EmbedFn | None = None,+ tool_call: CapabilityFn | None = None,+ vision: CapabilityFn | None = None,persist: bool = True,) -> dict[str, Any]:"""Prove the setup works, step by step, and write the health record.:func:`check_once` is the quiet schedule; this is the answer to a click- ("Set up everything", "Run a check"). Three steps, each with how long it+ ("Set up everything", "Run a check"). Five steps, each with how long ittook: the server answers, the chat pick produces one real answer, the- embedding pick produces one real vector. A step whose role is not- configured is reported as not run (``ok: None``) rather than as a pass,- so "it is set up" is a sentence that was tested, not assumed. Returns- ``{"ok", "status", "reason", "steps"}``; ``status`` uses the badge's- vocabulary (``ok`` / ``needs_setup`` / ``error``).+ voice pick calls one tool (what a call turn relies on), the tools &+ screen pick reads one image, the embedding pick produces one real+ vector. A step whose role is not configured is reported as not run+ (``ok: None``) rather than as a pass, so "it is set up" is a sentence+ that was tested, not assumed. Returns ``{"ok", "status", "reason",+ "steps"}``; ``status`` uses the badge's vocabulary (``ok`` /+ ``needs_setup`` / ``error``)."""import timeroot = root or _server_root(cfg)roles = _configured_roles(cfg)steps: list[dict[str, Any]] = []+ voice_model = roles.get("voice") or ""+ screen_model = roles.get("tools_screen") or ""server = await (probe or _default_probe)(root)server_ok = bool(server.get("ok"))@@ -305,6 +438,8 @@ async def verify_setup(not_run = "Not tested — the server did not answer."if not server_ok:steps.append(_step("chat", None, model=chat_model, detail=not_run))+ steps.append(_step("voice", None, model=voice_model, detail=not_run))+ steps.append(_step("tools_screen", None, model=screen_model, detail=not_run))steps.append(_step("embedding", None, model=embed_model, detail=not_run))else:if chat_model:@@ -336,6 +471,24 @@ async def verify_setup()else:steps.append(_step("chat", None, detail="No chat role is configured."))+ steps.append(+ await _capability_step(+ "voice",+ voice_model,+ root,+ tool_call or _default_tool_call,+ missing="No voice role is configured.",+ )+ )+ steps.append(+ await _capability_step(+ "tools_screen",+ screen_model,+ root,+ vision or _default_vision,+ missing="No tools & screen role is configured.",+ )+ )if embed_model:started = time.monotonic()try:diff --git a/jarvis/ui/web/local_models_routes.py b/jarvis/ui/web/local_models_routes.pyindex a2fe38a5e4..79253fc75d 100644--- a/jarvis/ui/web/local_models_routes.py+++ b/jarvis/ui/web/local_models_routes.py@@ -60,6 +60,16 @@ router = APIRouter(prefix="/api/providers/{provider_id}/local-models", tags=["loclass LocalModelRow(BaseModel):name: str+ #: Readable parts from ``jarvis.brain.ollama_names.describe``: the model+ #: line ("Qwen 3.5"), the line with its size ("Qwen 3.5 4B"), the size+ #: ("4B"), the quantisation ("Q4_K_M"), the source namespace for imports+ #: ("hf.co/unsloth") and the tag's variant markers ("it-qat").+ display_name: str = ""+ display_label: str = ""+ params_label: str = ""+ quant_label: str = ""+ source: str = ""+ variant: str = ""size_bytes: intdigest: strmodified_at: str@@ -73,9 +83,14 @@ class LocalModelRow(BaseModel):#: 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.+ #: Present when ``/api/ps`` lists it — the download itself or one of its+ #: aliases (``loaded_as`` names which; a Tune profile or the voice+ #: brain's context alias holds the same weights).loaded: bool = False+ loaded_as: str = ""size_vram_bytes: int = 0+ #: What ``/api/ps`` reports as the loaded size (weights + context).+ loaded_size_bytes: int = 0expires_at: str = ""running_context_length: int | None = None@@ -92,6 +107,10 @@ class RunningModelRow(BaseModel):expires_at: strcontext_length: int | Nonedigest: str = ""+ #: The download this entry's weights belong to (an alias folded back).+ base_tag: str = ""+ #: ``model`` | ``tune_profile`` | ``voice_profile``.+ kind: str = "model"class InventoryResponse(BaseModel):@@ -155,6 +174,21 @@ def _roles_using(cfg: Any, name: str) -> list[str]:return roles_using(cfg, name)+def _readonly_roles_using(cfg: Any, name: str) -> list[str]:+ """The read-only consumers (quick ack, dictation polish) pinned to ``name``.++ They cannot be reassigned from here — their pick lives on their own+ card — so a delete does not refuse for them, but it says so, because+ the model vanishing under them is otherwise a silent breakage.+ """+ if cfg is None:+ return []+ from jarvis.brain.ollama_roles import roles_using++ writable = set(roles_using(cfg, name))+ return [r for r in roles_using(cfg, name, include_readonly=True) if r not in writable]++async def _running_by_name(root: str) -> dict[str, OllamaRunningModel]:"""``/api/ps`` as a map from the shared snapshot; an unanswered probe is anempty map (logged), so a server that lists downloads but stalls on@@ -295,6 +329,12 @@ async def delete_inventory_model(message = f"{name} was deleted from the server."if reassigned:message += f" {', '.join(reassigned)} now use {target}."+ readonly = _readonly_roles_using(cfg, name)+ if readonly:+ from jarvis.brain.ollama_roles import role_spec++ where = ", ".join(f"{r} ({role_spec(r).config_key})" for r in readonly)+ message += f" Still named by {where} — change that on its own card."return DeleteResponse(ok=True,model=name,@@ -331,18 +371,49 @@ def _reassign_roles(cfg: Any, roles: list[str], target: str) -> list[str]:# ═════════════════════════════════════════════════════════════════════════+class RoleChoice(BaseModel):+ """One installed download judged for one job — the picker's row."""++ tag: str+ #: ``fits`` | ``slow`` | ``unfit`` | ``unknown`` (``ollama_roles.FITS``).+ fit: str+ #: Short clause saying why, ``""`` when it fits.+ reason: str = ""+++class RoleDownload(BaseModel):+ """A shortlist entry that would do the job here and is not on disk."""++ tag: str+ label: str+ size_gb: float+ #: ``comfortable`` | ``tight`` | ``unknown`` — the shortlist's own verdict.+ fit: str+ note: str = ""++class RoleRow(BaseModel):id: strlabel_key: strconfig_key: str+ #: ``card`` | ``row`` | ``footnote`` — where the section shows it.+ layout: str = "card"#: Configured tag; ``""`` = the plugin discovers one.current: str#: ``current`` is on the server right now.installed: bool+ #: The verdict on ``current``: a fit from ``ollama_roles.FITS``, ``absent``+ #: when configured but not on the server, ``""`` when nothing is set.+ current_fit: str = ""+ current_reason: str = ""required: list[str]recommended_capabilities: list[str]- #: Installed tags declaring every required capability.+ #: Installed tags that can do the job (``fits`` or ``slow``).qualifying: list[str]+ #: Every installed download with its verdict, inventory order.+ choices: list[RoleChoice] = Field(default_factory=list)+ #: Shortlist downloads that would do the job on this machine.+ downloads: list[RoleDownload] = Field(default_factory=list)#: The pick for this machine — the best qualifying INSTALLED download,#: or the shortlist's download when nothing installed qualifies (``""``#: when neither has one).@@ -360,12 +431,38 @@ class RoleRow(BaseModel):#: The size class the job prefers, in GB (the voice brain stays under 6#: so a call answers within a breath); ``None`` when the job has none.max_size_gb: float | None = None+ #: The smallest native context that can do the job; ``None`` = no floor.+ min_context_tokens: int | None = None+++class ResidentItem(BaseModel):+ """One distinct download across the roles, with what it costs loaded."""++ tag: str+ display_label: str = ""+ roles: list[str]+ weights_gb: float+ context_gb: float+ context_tokens: int | None = None+ loaded: bool = False+++class ResidentPayload(BaseModel):+ """What graphics memory holds when every job is loaded at once."""++ items: list[ResidentItem] = Field(default_factory=list)+ #: Kept free beside the voice brain for local speech in/out.+ reserve_gb: float = 0.0+ total_gb: float = 0.0+ accelerator_gb: float = 0.0+ over: bool = Falseclass RolesResponse(BaseModel):provider: strserver: strroles: list[RoleRow]+ resident: ResidentPayload = Field(default_factory=ResidentPayload)error: str | None = None@@ -876,7 +973,7 @@ async def put_autostart(class VerifyStep(BaseModel):- #: ``server`` | ``chat`` | ``embedding``.+ #: ``server`` | ``chat`` | ``voice`` | ``tools_screen`` | ``embedding``.id: str#: ``None`` = not run (the role is not configured, or the server is down).ok: bool | Nonediff --git a/tests/unit/brain/test_ollama_names.py b/tests/unit/brain/test_ollama_names.pynew file mode 100644index 0000000000..f6a9b77023--- /dev/null+++ b/tests/unit/brain/test_ollama_names.py@@ -0,0 +1,87 @@+"""Readable names from tags + manifest facts, and alias folding."""++from __future__ import annotations++import pytest++from jarvis.brain import ollama_names as names+++ ("tag", "params", "quant", "name", "label"),+ [+ ("qwen3.5:4b", "4.7B", "Q4_K_M", "Qwen 3.5", "Qwen 3.5 4B"),+ ("gemma4:12b-it-qat", "11.9B", "Q4_0", "Gemma 4", "Gemma 4 12B"),+ ("deepseek-r1:latest", "8.2B", "Q4_K_M", "DeepSeek R1", "DeepSeek R1 8.2B"),+ ("deepseek-r1:14b", "14.8B", "Q4_K_M", "DeepSeek R1", "DeepSeek R1 14B"),+ ("qwen3.8-16gb:latest", "26.9B", "IQ2_S", "Qwen 3.8", "Qwen 3.8 27B"),+ ("qwen3-coder:30b", "30.5B", "Q4_K_M", "Qwen 3 Coder", "Qwen 3 Coder 30B"),+ (+ "nemotron-cascade-2:latest",+ "31.6B",+ "Q4_K_M",+ "Nemotron Cascade 2",+ "Nemotron Cascade 2 32B",+ ),+ ("bge-m3:latest", "566.70M", "F16", "BGE M3", "BGE M3 567M"),+ ("deepseek-llm:latest", "7B", "Q4_0", "DeepSeek LLM", "DeepSeek LLM 7B"),+ ("ornith:9b", "9.0B", "Q4_K_M", "Ornith", "Ornith 9B"),+ ("embeddinggemma", "307.58M", "F16", "EmbeddingGemma", "EmbeddingGemma 308M"),+ ("qwen2.5:7b", "7.6B", "Q4_K_M", "Qwen 2.5", "Qwen 2.5 7B"),+ ],+)+def test_describe_humanises_the_tag_and_takes_the_size_from_the_facts(+ tag: str, params: str, quant: str, name: str, label: str+) -> None:+ shown = names.describe(tag, params, quant)+ assert shown.name == name+ assert shown.label == label+ assert shown.quant == quant+++def test_the_tags_size_token_wins_over_the_manifests_decimals() -> None:+ # Everyone calls it "the 4B"; 4.7B next to it reads like a different model.+ assert names.describe("qwen3.5:4b", "4.7B").params == "4B"+ # With no size token the manifest decides, rounded the way people say it.+ assert names.describe("qwen3.8-16gb", "26.9B").params == "27B"+ assert names.params_label("9.0B") == "9B"+ assert names.params_label("566.70M") == "567M"+ assert names.params_label("") == ""+++def test_variant_markers_stay_off_the_name_but_on_the_variant() -> None:+ shown = names.describe("gemma4:12b-it-qat", "11.9B", "Q4_0")+ assert shown.variant == "it-qat"+ assert "qat" not in shown.name.lower()+++def test_hugging_face_imports_keep_their_source() -> None:+ shown = names.describe("hf.co/unsloth/Qwen3-8B-GGUF:Q4_K_M", "8.2B", "")+ assert shown.source == "hf.co/unsloth"+ assert shown.name == "Qwen 3"+ assert shown.params == "8B"+ # The quantisation comes from the tag when the manifest has none.+ assert shown.quant == "Q4_K_M"+++def test_alias_kind_tells_jarvis_profiles_from_downloads() -> None:+ assert names.alias_kind("ornith:9b-voice-32k") == "voice_profile"+ assert names.alias_kind("ornith-9b-jarvis-04c5d3f6:latest") == "tune_profile"+ assert names.alias_kind("ornith:9b") == ""+ assert names.alias_kind("qwen3.5:4b-voice-8k") == "voice_profile"+++def test_base_of_folds_aliases_back_onto_their_download() -> None:+ assert names.base_of("ornith:9b-voice-32k") == "ornith:9b"+ assert names.base_of("ornith:9b-voice-32k:latest") == "ornith:9b"+ # A Tune profile folded ':' into '-'; the installed candidate says which.+ assert (+ names.base_of("ornith-9b-jarvis-04c5d3f6:latest", ["ornith:9b", "qwen3.5:4b"])+ == "ornith:9b"+ )+ assert names.base_of("ornith-9b-jarvis-04c5d3f6", []) == "ornith-9b"+ assert names.base_of("qwen3.5:4b", ["qwen3.5:4b"]) == "qwen3.5:4b"+++def test_an_empty_tag_describes_to_nothing() -> None:+ assert names.describe("").label == ""diff --git a/tests/unit/brain/test_ollama_overview_resident.py b/tests/unit/brain/test_ollama_overview_resident.pynew file mode 100644index 0000000000..a3715d5b4b--- /dev/null+++ b/tests/unit/brain/test_ollama_overview_resident.py@@ -0,0 +1,110 @@+"""Names on the rows, aliases folded onto their download, and what sits in+graphics memory when every job is loaded at once."""++from __future__ import annotations++from dataclasses import asdict++from jarvis.brain import ollama_overview, ollama_roles+from jarvis.brain.ollama_inventory import OllamaModelInfo, OllamaRunningModel+++def _model(name: str, size_gb: float, *caps: str, params: str = "", quant: str = ""):+ return OllamaModelInfo(+ name=name,+ size_bytes=int(size_gb * 1024**3),+ digest="",+ modified_at="",+ family="",+ parameter_size=params,+ quantization_level=quant,+ context_length=None,+ capabilities=tuple(caps),+ license="",+ )+++def _running(name: str, size_gb: float, ctx: int | None = None) -> OllamaRunningModel:+ return OllamaRunningModel(+ name=name,+ size_bytes=int(size_gb * 1024**3),+ size_vram_bytes=int(size_gb * 1024**3),+ expires_at="2026-08-27T19:00:00+02:00",+ context_length=ctx,+ )+++def test_model_row_carries_a_readable_name_and_folds_a_loaded_alias() -> None:+ info = _model("ornith:9b", 5.2, "completion", "tools", params="9.0B", quant="Q4_K_M")+ running = {"ornith:9b-voice-32k": _running("ornith:9b-voice-32k", 6.5, ctx=32768)}+ row = ollama_overview.model_row(info, running, ["voice"])+ assert row["display_name"] == "Ornith"+ assert row["display_label"] == "Ornith 9B"+ assert row["quant_label"] == "Q4_K_M"+ assert row["loaded"] is True+ assert row["loaded_as"] == "ornith:9b-voice-32k"+ assert row["running_context_length"] == 32768+ live = _running("ornith:9b-voice-32k", 6.5)+ assert ollama_overview.running_row(live, ["ornith:9b"]) == {+ **asdict(live),+ "base_tag": "ornith:9b",+ "kind": "voice_profile",+ }+++def _state(role: str, current: str, **extra) -> ollama_roles.RoleState:+ return ollama_roles.RoleState(+ spec=ollama_roles.role_spec(role),+ current=current,+ installed=True,+ qualifying=(),+ recommended="",+ **extra,+ )+++def test_resident_payload_adds_up_what_the_jobs_load_at_once() -> None:+ chat = _model("qwen3.8-16gb:latest", 7.8, "completion", "tools", params="26.9B")+ voice = _model("ornith:9b", 5.2, "completion", "tools", params="9.0B")+ embed = _model("bge-m3:latest", 1.1, "embedding", params="566.70M")+ running = {"qwen3.8-16gb:latest": _running("qwen3.8-16gb:latest", 8.8, ctx=32768)}+ states = [+ _state("chat", "qwen3.8-16gb:latest"),+ _state("voice", "ornith:9b", context_tokens=32768, context_source="manual"),+ _state("tools_screen", "qwen3.8-16gb:latest"),+ _state("deep", "qwen3.8-16gb:latest"),+ _state("embedding", "bge-m3:latest"),+ _state("ack", "qwen3.8-16gb:latest"),+ ]+ resident = ollama_overview.resident_payload(+ states,+ [chat, voice, embed],+ running,+ ollama_roles.Machine(memory_gb=32.0, accelerator_gb=15.9),+ voice_reserve_gb=4.0,+ )+ items = {i["tag"]: i for i in resident["items"]}+ # One model on three jobs is loaded once; the read-only ack is not counted.+ assert items["qwen3.8-16gb:latest"]["roles"] == ["chat", "tools_screen", "deep"]+ assert items["qwen3.8-16gb:latest"]["loaded"] is True+ # Loaded: the context is what /api/ps reports beyond the weights.+ assert items["qwen3.8-16gb:latest"]["context_gb"] == 1.0+ assert items["qwen3.8-16gb:latest"]["context_tokens"] == 32768+ # Not loaded: the rule of thumb from the voice window.+ assert items["ornith:9b"]["context_tokens"] == 32768+ assert 4.5 < items["ornith:9b"]["context_gb"] < 5.5+ assert items["ornith:9b"]["display_label"] == "Ornith 9B"+ assert resident["reserve_gb"] == 4.0+ assert resident["over"] is True+ assert resident["total_gb"] > 15.9+++def test_resident_payload_is_empty_without_picks() -> None:+ resident = ollama_overview.resident_payload([], [], {}, ollama_roles.Machine())+ assert resident == {+ "items": [],+ "reserve_gb": 0.0,+ "total_gb": 0.0,+ "accelerator_gb": 0.0,+ "over": False,+ }diff --git a/tests/unit/brain/test_ollama_roles_fit.py b/tests/unit/brain/test_ollama_roles_fit.pynew file mode 100644index 0000000000..9cd33e4b4d--- /dev/null+++ b/tests/unit/brain/test_ollama_roles_fit.py@@ -0,0 +1,147 @@+"""One verdict per (job, model): the fit the card, the picker and the setup+automation all read, plus the honest voice write and the download picks."""++from __future__ import annotations++import pytest++from jarvis.brain import ollama_inventory, ollama_roles+from jarvis.core import config_writer+from tests.fakes.fake_ollama_server import FakeOllamaServer+from tests.unit.brain.test_ollama_roles import ( # noqa: F401 — `shortlist` is a fixture+ ROOT,+ _cfg,+ _info,+ shortlist,+)+++def _voice() -> ollama_roles.RoleSpec:+ return ollama_roles.role_spec("voice")+++def _with_context(info: ollama_inventory.OllamaModelInfo, tokens: int):+ return ollama_inventory.OllamaModelInfo(+ name=info.name,+ size_bytes=info.size_bytes,+ digest="",+ modified_at="",+ family="",+ parameter_size="",+ quantization_level="",+ context_length=tokens,+ capabilities=info.capabilities,+ license="",+ )+++def test_fit_for_gates_the_voice_job_on_tool_calls_and_context() -> None:+ card = ollama_roles.Machine(memory_gb=32.0, accelerator_gb=16.0)+ chatty = _info("deepseek-llm:latest", 3.7, "completion")+ assert ollama_roles.fit_for(_voice(), chatty, card) == ("unfit", "no tool calls")+ short = _with_context(_info("short:7b", 3.7, "completion", "tools"), 4096)+ fit, reason = ollama_roles.fit_for(_voice(), short, card)+ assert fit == "unfit" and "4k context" in reason and "8k" in reason+ fits = _info("ornith:9b", 5.2, "completion", "tools", "thinking")+ assert ollama_roles.fit_for(_voice(), fits, card) == ("fits", "")+++def test_fit_for_names_the_cost_of_a_model_that_can_do_the_job_but_slowly() -> None:+ card = ollama_roles.Machine(memory_gb=32.0, accelerator_gb=16.0)+ big = _info("gemma4:12b-it-qat", 6.7, "completion", "tools", "vision")+ fit, reason = ollama_roles.fit_for(_voice(), big, card)+ assert fit == "slow" and "over 6 GB" in reason+ # Past the graphics card a call cannot wait for the processor …+ huge = _info("nemotron-cascade-2:latest", 22.6, "completion", "tools")+ fit, reason = ollama_roles.fit_for(_voice(), huge, card)+ assert fit == "unfit" and "graphics memory" in reason+ # … while the chat job takes it, slower.+ fit, reason = ollama_roles.fit_for(ollama_roles.role_spec("chat"), huge, card)+ assert fit == "slow" and "processor" in reason+++def test_fit_for_calls_an_unprobed_download_unknown_not_unfit() -> None:+ unknown = _info("broken:1b", 1.0, probed=False)+ fit, reason = ollama_roles.fit_for(_voice(), unknown)+ assert fit == "unknown" and reason+++def test_choices_judge_every_installed_download_in_inventory_order() -> None:+ card = ollama_roles.Machine(memory_gb=32.0, accelerator_gb=16.0)+ models = [+ _info("ornith:9b", 5.2, "completion", "tools"),+ _info("bge-m3:latest", 1.1, "embedding"),+ _info("deepseek-llm:latest", 3.7, "completion"),+ ]+ choices = ollama_roles.choices_for(_voice(), models, card)+ assert [c[0] for c in choices] == ["ornith:9b", "bge-m3:latest", "deepseek-llm:latest"]+ assert [c[1] for c in choices] == ["fits", "unfit", "unfit"]+ assert ollama_roles.qualifying_models(_voice(), models, card) == ("ornith:9b",)+++async def test_list_roles_carries_the_verdict_on_the_current_pick(shortlist) -> None: # noqa: F811+ ollama_inventory._reset_for_tests()+ server = FakeOllamaServer()+ server.add("qwen3.5:4b", size=3_400_000_000, capabilities=("completion", "tools", "vision"))+ server.add("blind:7b", size=4_000_000_000, capabilities=("completion", "tools"))+ cfg = _cfg()+ cfg.brain.providers["ollama"].tool_model = "blind:7b"+ cfg.brain.providers["ollama"].deep_model = "gone:1b"+ states, _ = await ollama_roles.list_roles(ROOT, cfg, transport=server.transport())+ by_id = {s.spec.id: s for s in states}+ assert by_id["tools_screen"].current_fit == "unfit"+ assert by_id["tools_screen"].current_reason == "no vision"+ assert by_id["deep"].current_fit == "absent"+ assert by_id["chat"].current_fit == "fits"+ assert [c[0] for c in by_id["chat"].choices] == ["qwen3.5:4b", "blind:7b"]+ assert by_id["chat"].spec.layout == "card"+ assert by_id["embedding"].spec.layout == "row"+ assert by_id["ack"].spec.layout == "footnote"+++def _row(tag: str, size: float, *, vision: bool, installed: bool = False) -> dict:+ return {+ "id": tag,+ "label": tag,+ "role": "chat",+ "tools": True,+ "vision": vision,+ "size_gb": size,+ "installed": installed,+ "fit": "comfortable",+ "fit_note": "",+ }+++def test_download_picks_respect_the_jobs_gates() -> None:+ rows = [+ _row("big:27b", 18.0, vision=True),+ _row("small:4b", 3.4, vision=True),+ _row("blind:9b", 5.6, vision=False),+ _row("here:4b", 3.4, vision=True, installed=True),+ ]+ voice = [t for t, *_ in ollama_roles.download_picks(_voice(), rows)]+ assert voice == ["blind:9b", "small:4b"] # under 6 GB, not installed, largest first+ screen = ollama_roles.role_spec("tools_screen")+ assert [t for t, *_ in ollama_roles.download_picks(screen, rows)] == ["big:27b", "small:4b"]+ assert ollama_roles.download_picks(ollama_roles.role_spec("embedding"), rows) == ()+++def test_set_role_voice_refuses_when_nothing_reached_the_toml(monkeypatch) -> None:+ cfg = _cfg()+ monkeypatch.setattr(config_writer, "update_local_realtime_launch_model", lambda tag: False)+ with pytest.raises(ValueError, match="could not be updated"):+ ollama_roles.set_role("voice", "ornith:9b", cfg=cfg)+ # The same value is a no-op, not a failure.+ assert ollama_roles.set_role("voice", "qwen3.5:4b", cfg=cfg)["model"] == "qwen3.5:4b"+++def test_roles_using_can_include_the_read_only_consumers() -> None:+ cfg = _cfg()+ cfg.ack_brain.providers.ollama.model = "qwen3.5:4b"+ assert ollama_roles.roles_using(cfg, "qwen3.5:4b") == ["chat", "voice"]+ assert ollama_roles.roles_using(cfg, "qwen3.5:4b", include_readonly=True) == [+ "chat",+ "voice",+ "ack",+ ]diff --git a/tests/unit/local_models/test_health_monitor.py b/tests/unit/local_models/test_health_monitor.pyindex 5190ae2c1e..5133a3f50f 100644--- a/tests/unit/local_models/test_health_monitor.py+++ b/tests/unit/local_models/test_health_monitor.py@@ -47,6 +47,15 @@ def _record(tmp_path: Path) -> dict[str, Any]:return json.loads((tmp_path / "state" / "local_models_health.json").read_text("utf-8"))+def _capability(detail: str | Exception):+ async def probe(_root: str, _model: str) -> str:+ if isinstance(detail, Exception):+ raise detail+ return detail++ return probe++def _embed(dims: int | Exception):async def _fn(_root: str, _model: str) -> int:if isinstance(dims, Exception):@@ -73,10 +82,14 @@ async def test_verify_reports_every_step_and_writes_the_record(tmp_path: Path) -probe=_probe(True),generate=_generate,embed=_embed(768),+ tool_call=_capability("Called the tool."),+ vision=_capability("Saw the image: white"),)assert result["ok"] is True and result["status"] == "ok" and result["reason"] == ""steps = {s["id"]: s for s in result["steps"]}- assert list(steps) == ["server", "chat", "embedding"]+ assert list(steps) == ["server", "chat", "voice", "tools_screen", "embedding"]+ # Neither the voice nor the screen role is configured here: not run, not passed.+ assert steps["voice"]["ok"] is None and steps["tools_screen"]["ok"] is Noneassert steps["server"]["ok"] is True and "0.32.15" in steps["server"]["detail"]assert steps["chat"] == {"id": "chat",@@ -115,11 +128,11 @@ async def test_verify_marks_unconfigured_roles_as_not_run_and_a_down_server_firsnothing = await hm.verify_setup(_cfg(), probe=_probe(True), generate=_generate)assert nothing["status"] == "needs_setup"- assert [s["ok"] for s in nothing["steps"]] == [True, None, None]+ assert [s["ok"] for s in nothing["steps"]] == [True, None, None, None, None]down = await hm.verify_setup(_cfg("qwen3.5:4b"), probe=_probe(False), generate=_generate)assert down["status"] == "error" and "No Ollama answered" in down["reason"]- assert [s["ok"] for s in down["steps"]] == [False, None, None]+ assert [s["ok"] for s in down["steps"]] == [False, None, None, None, None]assert down["steps"][1]["model"] == "qwen3.5:4b"assert _record(tmp_path)["status"] == "error"diff --git a/tests/unit/ui/web/test_local_models_routes.py b/tests/unit/ui/web/test_local_models_routes.pyindex e3cf51cb04..0088edaff2 100644--- a/tests/unit/ui/web/test_local_models_routes.py+++ b/tests/unit/ui/web/test_local_models_routes.py@@ -643,7 +643,7 @@ def test_autostart_round_trip(server: WebServer, fake, monkeypatch) -> None:assert server.app.state.config.brain.providers["ollama"].autostart is False-def test_verify_runs_the_three_steps_and_refreshes_the_badge(+def test_verify_runs_the_five_steps_and_refreshes_the_badge(server: WebServer, fake, monkeypatch, tmp_path) -> None:from jarvis.local_models import health_monitor@@ -663,14 +663,26 @@ def test_verify_runs_the_three_steps_and_refreshes_the_badge(monkeypatch.setattr(health_monitor, "_default_probe", _probe)monkeypatch.setattr(health_monitor, "_default_generate", _generate)++ async def _capability(_root: str, _model: str) -> str:+ return "Answered the probe."+monkeypatch.setattr(health_monitor, "_default_embed", _embed)+ monkeypatch.setattr(health_monitor, "_default_tool_call", _capability)+ monkeypatch.setattr(health_monitor, "_default_vision", _capability)with TestClient(server.app) as client:body = client.post(f"{BASE}/verify").json()assert body["ok"] is True and body["status"] == "ok"- assert [s["id"] for s in body["steps"]] == ["server", "chat", "embedding"]+ assert [s["id"] for s in body["steps"]] == [+ "server",+ "chat",+ "voice",+ "tools_screen",+ "embedding",+ ]assert body["steps"][0]["ms"] == 7assert body["steps"][1]["model"] == "qwen3.5:4b"- assert body["steps"][2]["detail"] == "1024 dimensions."+ assert body["steps"][4]["detail"] == "1024 dimensions."assert health_monitor.read_health_record()["status"] == "ok"