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): rank the download shortlist against the machine it runs on

rubenluetke10-beep0cdccf64d286
diff --git a/jarvis/brain/ollama_pull.py b/jarvis/brain/ollama_pull.py
index ff7d16b794..3a2b5c51d2 100644
--- a/jarvis/brain/ollama_pull.py
+++ b/jarvis/brain/ollama_pull.py
@@ -57,52 +57,151 @@ _COMFORTABLE_SHARE = 0.6
_OVERHEAD_GB = 2.0
+#: The jobs a local install has to fill. Each one is a separate decision — a
+#: machine needs a chat model AND an embedder, they do not substitute for each
+#: other — so the shortlist offers a best pick per role rather than one ranked
+#: list where the embedder looks like a weak chat model.
+Role = Literal["chat", "vision", "coder", "embedding"]
+
+#: Display order of the roles, most-load-bearing first.
+ROLE_ORDER: tuple[Role, ...] = ("chat", "vision", "coder", "embedding")
+
+
@dataclass(frozen=True, slots=True)
class RecommendedModel:
"""One curated pull suggestion.
- ``size_gb`` is the approximate download size (the server reports the exact
- one during the pull). ``tools`` / ``vision`` are the capabilities the model
- line is known for — the same two gates the brain applies per turn, so the
- card can say WHY a pull matters instead of listing names.
+ ``size_gb`` is the fallback download size, used only until the registry
+ answers with the real one (see :func:`registry_size_gb`). ``tools`` /
+ ``vision`` are the capabilities the model line is known for — the same two
+ gates the brain applies per turn, so the card can say WHY a pull matters
+ instead of listing names.
"""
id: str
label: str
size_gb: float
purpose: str
+ role: Role = "chat"
tools: bool = True
vision: bool = False
-#: The shortlist. Kept small on purpose — a wall of names is not a choice. One
-#: general model per memory class, one multimodal, one embedder for UltraWiki,
-#: because those are the three roles a local-only install actually needs.
+#: The shortlist, spread across memory classes rather than pinned to one.
+#:
+#: The old list held one small chat model, one mid one, one multimodal and one
+#: embedder — the same four names on a 8 GB laptop and on a workstation with a
+#: 48 GB card, so the workstation was told to run a 4B model and the laptop was
+#: shown nothing it could not also have found itself. The classes below exist so
+#: :func:`recommendations` can pick the LARGEST entry per role that this
+#: particular machine runs well, which is the whole point of a recommendation.
+#:
+#: Every id here is verified to exist in the Ollama library (see
+#: ``tests/integration/test_ollama_catalog_is_current.py``, which asks the
+#: registry). That test is also the guard against the list going stale: a tag
+#: that is retired fails it rather than reaching a user as "Ollama does not know
+#: a model called …". Sizes are the registry's own, refreshed at request time.
RECOMMENDED_MODELS: tuple[RecommendedModel, ...] = (
+ # ── chat / voice / tools ────────────────────────────────────────────────
+ RecommendedModel(
+ id="qwen3.5:2b",
+ label="Qwen 3.5 2B",
+ size_gb=2.7,
+ purpose="Chat and voice on a small laptop. Calls tools.",
+ ),
RecommendedModel(
id="qwen3.5:4b",
label="Qwen 3.5 4B",
- size_gb=2.6,
- purpose="Chat and voice on a small machine. Calls tools.",
+ size_gb=3.4,
+ purpose="Chat and voice with more headroom, still light on memory.",
),
RecommendedModel(
id="qwen3.5",
- label="Qwen 3.5 (default size)",
- size_gb=5.2,
+ label="Qwen 3.5 9B",
+ size_gb=6.6,
purpose="The balanced default: chat, voice, and reliable tool calling.",
),
+ RecommendedModel(
+ id="gpt-oss:20b",
+ label="GPT-OSS 20B",
+ size_gb=13.8,
+ purpose="Noticeably stronger reasoning; wants a GPU or plenty of memory.",
+ ),
+ RecommendedModel(
+ id="gemma3:27b",
+ label="Gemma 3 27B",
+ size_gb=17.4,
+ purpose="A second strong option at this size, with a different style.",
+ ),
+ RecommendedModel(
+ id="gpt-oss:120b",
+ label="GPT-OSS 120B",
+ size_gb=65.4,
+ purpose="Frontier-class answers, for a workstation-sized accelerator.",
+ ),
+ # ── vision (Screen Context / Computer-Use) ──────────────────────────────
+ RecommendedModel(
+ id="qwen3-vl:2b",
+ label="Qwen 3 VL 2B",
+ size_gb=1.9,
+ purpose="Sees your screen on a small machine.",
+ role="vision",
+ vision=True,
+ ),
+ RecommendedModel(
+ id="qwen3-vl:4b",
+ label="Qwen 3 VL 4B",
+ size_gb=3.3,
+ purpose="Sees your screen, with more detail than the 2B.",
+ role="vision",
+ vision=True,
+ ),
RecommendedModel(
id="qwen3-vl",
- label="Qwen 3 VL",
- size_gb=6.0,
- purpose="Sees images — needed for Screen Context and Computer-Use.",
+ label="Qwen 3 VL 8B",
+ size_gb=6.1,
+ purpose="The balanced choice for Screen Context and Computer-Use.",
+ role="vision",
vision=True,
),
+ RecommendedModel(
+ id="qwen3-vl:32b",
+ label="Qwen 3 VL 32B",
+ size_gb=20.9,
+ purpose="Reads dense screens and small text most reliably.",
+ role="vision",
+ vision=True,
+ ),
+ # ── coding worker (the Agents tab's heavy-task model) ───────────────────
+ RecommendedModel(
+ id="devstral",
+ label="Devstral",
+ size_gb=14.3,
+ purpose="Built for agentic coding work — a local heavy-task worker.",
+ role="coder",
+ ),
+ RecommendedModel(
+ id="qwen3-coder",
+ label="Qwen 3 Coder",
+ size_gb=18.6,
+ purpose="The stronger local coding worker where memory allows.",
+ role="coder",
+ ),
+ # ── embeddings (UltraWiki search) ───────────────────────────────────────
+ RecommendedModel(
+ id="embeddinggemma",
+ label="EmbeddingGemma",
+ size_gb=0.6,
+ purpose="Embeddings for search on any machine. Not a chat model.",
+ role="embedding",
+ tools=False,
+ ),
RecommendedModel(
id="bge-m3",
label="BGE-M3",
size_gb=1.2,
- purpose="Embeddings for UltraWiki search. Not a chat model.",
+ purpose="Multilingual embeddings for UltraWiki. Not a chat model.",
+ role="embedding",
tools=False,
),
)
@@ -146,24 +245,66 @@ def total_memory_gb() -> float | None:
9 GB model look safe on a 4 GB box.
"""
try:
- import psutil # noqa: PLC0415 — lazy (AP-26)
+ from jarvis.hardware.detection import system_ram_gb # noqa: PLC0415 — lazy (AP-26)
- return round(psutil.virtual_memory().total / (1024**3), 1)
+ return system_ram_gb()
except Exception: # noqa: BLE001 — an unreadable host is not an error
log.debug("ollama-pull: total memory could not be read")
return None
-def fit_verdict(size_gb: float, memory_gb: float | None) -> tuple[str, str]:
+def accelerator_gb() -> tuple[float, str]:
+ """``(GiB, source)`` of GPU memory this machine can give a model.
+
+ ``(0.0, "none")`` means "no accelerator I can vouch for" — a CPU-only box,
+ but equally an AMD or Intel card this probe cannot read. It is never read as
+ "cannot run models": system RAM still runs them, just slower, which is
+ exactly what :func:`fit_verdict` then says.
+ """
+ try:
+ from jarvis.hardware.detection import ( # noqa: PLC0415 — lazy (AP-26)
+ usable_accelerator_gb,
+ )
+
+ return usable_accelerator_gb()
+ except Exception: # noqa: BLE001 — a probe failure is not an error state
+ log.debug("ollama-pull: accelerator probe unavailable", exc_info=True)
+ return 0.0, "none"
+
+
+def fit_verdict(
+ size_gb: float,
+ memory_gb: float | None,
+ accel_gb: float = 0.0,
+) -> tuple[str, str]:
"""``(verdict, English sentence)`` for running ``size_gb`` on this machine.
Verdicts: ``comfortable`` | ``tight`` | ``unknown``. Never "impossible" —
- Ollama offloads to GPU memory this probe cannot see, and a hard no would be
- wrong on exactly the machines that run local models best.
+ a hard no would be wrong on exactly the machines that run local models best.
+
+ GPU memory decides first when it is known. The RAM rule alone called a 14 GB
+ model "tight" on a box with a 24 GB card that runs it at full speed, and
+ "comfortable" on a 64 GB CPU-only server where it crawls — both backwards.
+ Whichever memory answers, the sentence names it, so the verdict can be
+ checked against the machine rather than taken on faith.
"""
+ needed = size_gb + _OVERHEAD_GB
+ if accel_gb > 0:
+ if needed <= accel_gb:
+ return (
+ "comfortable",
+ f"Fits in the {accel_gb:.0f} GB of graphics memory on this "
+ "machine — it will run at full speed.",
+ )
+ if memory_gb is not None and needed <= memory_gb * _COMFORTABLE_SHARE:
+ return (
+ "tight",
+ f"Bigger than the {accel_gb:.0f} GB of graphics memory, so part "
+ f"of it runs on the CPU out of {memory_gb:g} GB of RAM. It "
+ "works, just slower.",
+ )
if memory_gb is None:
return "unknown", "This machine's memory could not be read."
- needed = size_gb + _OVERHEAD_GB
if needed <= memory_gb * _COMFORTABLE_SHARE:
return "comfortable", f"Runs comfortably in {memory_gb:g} GB of memory."
return (
@@ -215,31 +356,137 @@ def _is_installed(model: str, installed: set[str]) -> bool:
return False
+#: Real download sizes from the public Ollama registry, cached for the process.
+#: Sizes drift as a tag is re-quantised, and the hardcoded estimates were up to
+#: a third off — enough to turn "fits in my card" into an eviction at load time.
+_registry_sizes: dict[str, float] = {}
+
+#: The registry is a nice-to-have: without it the curated estimates are used.
+#: Short timeout because it sits in front of a UI panel, not a download.
+_REGISTRY_TIMEOUT = httpx.Timeout(connect=2.0, read=6.0, write=6.0, pool=6.0)
+_REGISTRY_ROOT = "https://registry.ollama.ai/v2/library"
+_MANIFEST_ACCEPT = "application/vnd.docker.distribution.manifest.v2+json"
+
+
+async def registry_size_gb(client: httpx.AsyncClient, model: str) -> float | None:
+ """The real download size of ``model`` in GB, or ``None`` if unknown.
+
+ Sums the manifest's layer sizes — what the pull actually transfers. Any
+ failure (offline, proxy, retired tag) answers ``None`` and the caller keeps
+ the curated estimate, so an air-gapped machine still sees a usable panel.
+ """
+ if model in _registry_sizes:
+ return _registry_sizes[model]
+ name, _, tag = model.partition(":")
+ try:
+ resp = await client.get(
+ f"{_REGISTRY_ROOT}/{name}/manifests/{tag or 'latest'}",
+ headers={"Accept": _MANIFEST_ACCEPT},
+ )
+ if resp.status_code != 200:
+ return None
+ layers = resp.json().get("layers") or []
+ total = sum(int(layer.get("size") or 0) for layer in layers)
+ except Exception: # noqa: BLE001 — an unreachable registry is a normal state
+ log.debug("ollama-pull: registry size unavailable for %s", model)
+ return None
+ if total <= 0:
+ return None
+ size = round(total / 1e9, 1)
+ _registry_sizes[model] = size
+ return size
+
+
+async def _real_sizes() -> dict[str, float]:
+ """Registry sizes for the whole shortlist, fetched concurrently."""
+ async with httpx.AsyncClient(timeout=_REGISTRY_TIMEOUT) as client:
+ results = await asyncio.gather(
+ *(registry_size_gb(client, entry.id) for entry in RECOMMENDED_MODELS),
+ return_exceptions=True,
+ )
+ sizes: dict[str, float] = {}
+ for entry, result in zip(RECOMMENDED_MODELS, results, strict=True):
+ if isinstance(result, float):
+ sizes[entry.id] = result
+ return sizes
+
+
+def _pick_recommended(rows: list[dict[str, Any]]) -> None:
+ """Mark the best pick per role on ``rows``, in place.
+
+ The best pick is the LARGEST model of that role this machine still runs
+ comfortably — bigger is better right up to the point where it stops fitting,
+ and that point is the only thing the hardware probe is for. If nothing in a
+ role fits comfortably, the SMALLEST one is marked instead: a machine that
+ cannot run any of them still deserves a starting point rather than four
+ entries all flagged "tight" and no answer to "so which one?".
+
+ A role whose model is already installed marks nothing: the user has made
+ that choice, and re-recommending a different size over the top of it is how
+ a panel starts nagging.
+ """
+ for role in ROLE_ORDER:
+ in_role = [r for r in rows if r["role"] == role]
+ if not in_role or any(r["installed"] for r in in_role):
+ continue
+ comfortable = [r for r in in_role if r["fit"] == "comfortable"]
+ pick = (
+ max(comfortable, key=lambda r: r["size_gb"])
+ if comfortable
+ else min(in_role, key=lambda r: r["size_gb"])
+ )
+ pick["recommended"] = True
+
+
async def recommendations() -> dict[str, Any]:
- """The curated shortlist, annotated with what THIS machine already has."""
+ """The curated shortlist, ranked for THIS machine.
+
+ Three things happen here that a static list cannot do: sizes come from the
+ registry (so the fit verdict is judged against the real download), the
+ verdict weighs GPU memory ahead of RAM, and each role gets exactly one
+ "recommended" entry — the largest one this box runs well.
+ """
installed, error = await installed_models()
memory_gb = total_memory_gb()
+ accel, accel_source = accelerator_gb()
+ real_sizes = await _real_sizes()
+
models: list[dict[str, Any]] = []
for entry in RECOMMENDED_MODELS:
- verdict, note = fit_verdict(entry.size_gb, memory_gb)
+ size = real_sizes.get(entry.id, entry.size_gb)
+ verdict, note = fit_verdict(size, memory_gb, accel)
models.append(
{
"id": entry.id,
"label": entry.label,
- "size_gb": entry.size_gb,
+ "size_gb": size,
"purpose": entry.purpose,
+ "role": entry.role,
"tools": entry.tools,
"vision": entry.vision,
"installed": _is_installed(entry.id, installed),
"fit": verdict,
"fit_note": note,
+ "recommended": False,
}
)
+ _pick_recommended(models)
+ # Within a role, largest first: the strongest option a machine can take is
+ # the interesting one, and the recommended entry lands at or near the top
+ # instead of below three smaller models the user has to scroll past.
+ models.sort(key=lambda r: (ROLE_ORDER.index(r["role"]), -r["size_gb"]))
+
return {
"server": server_root(),
"server_reachable": error is None,
"message": error or "",
"memory_gb": memory_gb,
+ # The accelerator the verdicts were judged against. 0 with source
+ # "none" means "none I could read" — the panel says so rather than
+ # implying the machine has no GPU at all.
+ "accelerator_gb": round(accel, 1),
+ "accelerator_source": accel_source,
+ "roles": list(ROLE_ORDER),
"models": models,
"installed": sorted(installed),
}
@@ -374,11 +621,15 @@ async def pull_status(model: str) -> dict[str, Any]:
__all__ = [
"PULL_CAPABLE_PROVIDERS",
"RECOMMENDED_MODELS",
+ "ROLE_ORDER",
"RecommendedModel",
+ "Role",
+ "accelerator_gb",
"fit_verdict",
"installed_models",
"pull_status",
"recommendations",
+ "registry_size_gb",
"server_root",
"start_pull",
"total_memory_gb",
diff --git a/jarvis/hardware/detection.py b/jarvis/hardware/detection.py
index a265e17e8a..f3898ed710 100644
--- a/jarvis/hardware/detection.py
+++ b/jarvis/hardware/detection.py
@@ -7,6 +7,7 @@ All checks are read-only; nothing is installed or modified.
"""
from __future__ import annotations
+import logging
import platform
import shutil
import subprocess
@@ -15,6 +16,8 @@ from dataclasses import dataclass, field
from jarvis.core.process_utils import NO_WINDOW_CREATIONFLAGS
+log = logging.getLogger(__name__)
+
# ----------------------------------------------------------------------
# DataClasses
# ----------------------------------------------------------------------
@@ -128,8 +131,9 @@ def _detect_nvidia_gpus() -> list[GPUInfo]:
)
pynvml.nvmlShutdown()
return gpus
- except Exception: # noqa: BLE001
- pass
+ except Exception: # noqa: BLE001 — no pynvml / no driver is a normal state
+ log.debug("hardware: pynvml probe unavailable, falling back to nvidia-smi",
+ exc_info=True)
# Fallback: nvidia-smi
out = _run(["nvidia-smi", "--query-gpu=name,memory.total", "--format=csv,noheader,nounits"])
@@ -337,7 +341,8 @@ def _format_report(report: HardwareReport, rec: WhisperRecommendation) -> str:
"║ Jarvis Hardware Analysis ║",
"╚══════════════════════════════════════════════════════════╝",
"",
- f"OS: {report.os_name} {report.os_version.split()[0] if report.os_version else ''}",
+ f"OS: {report.os_name} "
+ f"{report.os_version.split()[0] if report.os_version else ''}",
f"Python: {report.python_version} ({report.python_executable})",
f"CPU: {report.cpu_name}",
f" {report.cpu_cores_physical} phys / {report.cpu_cores_logical} log cores",
@@ -406,6 +411,56 @@ def cuda_inference_verified() -> bool | None:
return None
+def usable_accelerator_gb() -> tuple[float, str]:
+ """Usable accelerator memory in GiB and where that figure came from.
+
+ ``(gb, source)`` with source ``"nvidia-smi"`` | ``"apple-unified"`` |
+ ``"none"``. Dedicated NVIDIA VRAM counts as-is; on Apple Silicon the GPU
+ shares the unified memory, so total RAM is the honest figure. Every other
+ host reports ``0.0`` — a GPU-less box, a machine with an AMD or Intel card
+ this probe cannot read, and a locked-down host are all "no accelerator
+ memory I can vouch for", and callers must treat 0 as *unknown accelerator*
+ rather than *no memory* (system RAM still runs the model, just slower).
+
+ The LARGEST single device, never the fleet sum: inference runs on one GPU,
+ so two 8 GB cards are an 8 GB machine.
+
+ Shared on purpose. The realtime-server preflight and the local-model
+ recommender both have to answer "how much can this machine actually run?",
+ and two probes drifting apart would show a user two different verdicts
+ about one box.
+ """
+ try:
+ gpus = _detect_nvidia_gpus()
+ except Exception: # noqa: BLE001 — nvidia-smi quirks must not crash a caller
+ gpus = []
+ vram_mb = max((g.vram_mb for g in gpus), default=0)
+ if vram_mb > 0:
+ return vram_mb / 1024.0, "nvidia-smi"
+ if sys.platform == "darwin" and platform.machine() == "arm64":
+ try:
+ total_mb, _available = _detect_ram()
+ except Exception: # noqa: BLE001
+ total_mb = 0
+ if total_mb > 0:
+ return total_mb / 1024.0, "apple-unified"
+ return 0.0, "none"
+
+
+def system_ram_gb() -> float | None:
+ """Total system memory in GiB, or ``None`` when it cannot be read.
+
+ ``None`` stays a real answer on a locked-down host: a caller then says
+ "unknown" instead of inventing a number that would make a 14 GB model look
+ safe on a 4 GB box.
+ """
+ try:
+ total_mb, _available = _detect_ram()
+ except Exception: # noqa: BLE001
+ return None
+ return round(total_mb / 1024.0, 1) if total_mb > 0 else None
+
+
def main() -> int:
report = analyze()
rec = recommend_whisper(report, gpu_inference_verified=cuda_inference_verified())
diff --git a/jarvis/realtime/local_server/preflight.py b/jarvis/realtime/local_server/preflight.py
index d37ff3f605..ac7ec12ee6 100644
--- a/jarvis/realtime/local_server/preflight.py
+++ b/jarvis/realtime/local_server/preflight.py
@@ -14,9 +14,7 @@ anything (the same doctrine as ``jarvis/speech/local_models.py``).
from __future__ import annotations
import logging
-import platform
import shutil
-import sys
from dataclasses import dataclass, field
from pathlib import Path
@@ -50,37 +48,20 @@ class PreflightReport:
def _usable_accelerator_gb() -> tuple[float, str]:
"""Usable accelerator memory in GiB and the source of that figure.
- Dedicated NVIDIA VRAM counts as-is. On Apple Silicon the GPU shares the
- unified memory, so total RAM is the honest figure (the probe measures
- what is THERE; whether the OS grants it is the smoke boot's job).
- Anything else reports 0 — and 0 is below the floor, which is exactly
- the honest outcome for a GPU-less host.
+ Delegates to the shared probe in :mod:`jarvis.hardware.detection`, which is
+ where this logic now lives: the local-model recommender asks the very same
+ question ("how much can this machine actually run?"), and two copies would
+ eventually give one box two different verdicts. Behaviour is unchanged —
+ largest single NVIDIA device, Apple Silicon unified memory, otherwise 0,
+ and 0 is below the floor, which is the honest outcome for a GPU-less host.
"""
try:
- from jarvis.hardware.detection import _detect_nvidia_gpus # read-only probe
-
- gpus = _detect_nvidia_gpus()
- except Exception: # pragma: no cover — nvidia-smi quirks must not crash preflight
- log.debug("preflight: NVIDIA probe failed", exc_info=True)
- gpus = []
- # The LARGEST single device, never the fleet sum: the whole stack runs
- # on one GPU (--num_pipelines 1, one TTS device), so two 8 GB cards are
- # an 8 GB machine for this feature — summing them would defeat the
- # 12 GB floor and OOM at first call (review 2026-08-07).
- vram_mb = max((g.vram_mb for g in gpus), default=0)
- if vram_mb > 0:
- return vram_mb / 1024.0, "nvidia-smi"
- if sys.platform == "darwin" and platform.machine() == "arm64":
- try:
- from jarvis.hardware.detection import _detect_ram
-
- total_mb, _available = _detect_ram()
- except Exception: # pragma: no cover
- log.debug("preflight: RAM probe failed", exc_info=True)
- total_mb = 0
- if total_mb > 0:
- return total_mb / 1024.0, "apple-unified"
- return 0.0, "none"
+ from jarvis.hardware.detection import usable_accelerator_gb
+
+ return usable_accelerator_gb()
+ except Exception: # pragma: no cover — probe quirks must not crash preflight
+ log.debug("preflight: accelerator probe failed", exc_info=True)
+ return 0.0, "none"
def _disk_free_gb(root: Path) -> float:
diff --git a/jarvis/ui/web/frontend/src/components/JarvisAgentSection.tsx b/jarvis/ui/web/frontend/src/components/JarvisAgentSection.tsx
index 2ab8e46484..284635079f 100644
--- a/jarvis/ui/web/frontend/src/components/JarvisAgentSection.tsx
+++ b/jarvis/ui/web/frontend/src/components/JarvisAgentSection.tsx
@@ -15,6 +15,7 @@ import {
startCodexLogin,
switchSubagentProvider,
testAgentCli,
+ useProviders,
type AgentCliTestResult,
type AntigravityStatus,
type Billing,
@@ -24,7 +25,10 @@ import {
import { BrainModelSelector } from "@/components/BrainModelSelector";
import { ApiKeyForm } from "@/components/ApiKeyForm";
import { AgentAccountsPanel } from "@/components/AgentAccountsPanel";
-import { LocalModeNotice } from "@/components/providers/ProviderTierSection";
+import {
+ LocalModeNotice,
+ LocalModelDownloadPanel,
+} from "@/components/providers/ProviderTierSection";
import { filterForLocalMode, useLocalMode } from "@/lib/localMode";
/**
@@ -429,6 +433,13 @@ function SubagentModelCard({
// "openai-codex" maps to the catalog's "codex"; all others match 1:1).
const catalogProvider =
status.brain_primary === "openai-codex" ? "codex" : status.brain_primary;
+ // Whether the ACTIVE worker's server can be told to download a model. Read
+ // off the provider catalog rather than a provider name, so a second local
+ // server type that ships a puller lights this up on its own (AP-21).
+ const { providers } = useProviders();
+ const pullable = providers.find(
+ (p) => p.id === catalogProvider && p.supports_model_pull,
+ );
return (
<div className="card-outline space-y-3 p-4">
<p className="text-[11px] leading-relaxed text-muted-foreground">
@@ -462,6 +473,13 @@ function SubagentModelCard({
{t("subagent_model.model_hint")}
{status.model_resolved ? ` (${status.model_resolved})` : ""}
</p>
+
+ {/* The download panel, for a worker whose server can be told to fetch a
+ model. Without it this tab dead-ended a local-only install: the picker
+ above lists what the server HOLDS, so on a fresh Ollama it is empty,
+ and the one screen that could fix that was three tabs away under
+ Brain. Same panel, same endpoints — the capability flag decides. */}
+ {pullable && <LocalModelDownloadPanel descriptor={pullable} onChanged={onSaved} />}
</div>
);
}
diff --git a/jarvis/ui/web/frontend/src/components/providers/LocalModelDownloadPanel.test.tsx b/jarvis/ui/web/frontend/src/components/providers/LocalModelDownloadPanel.test.tsx
index da0ea31db4..c6dcc9d677 100644
--- a/jarvis/ui/web/frontend/src/components/providers/LocalModelDownloadPanel.test.tsx
+++ b/jarvis/ui/web/frontend/src/components/providers/LocalModelDownloadPanel.test.tsx
@@ -27,6 +27,12 @@ vi.mock("@/i18n", () => ({
"apikeys_model_pull.installed": "Installed",
"apikeys_model_pull.download": "Download",
"apikeys_model_pull.custom_placeholder": "Any model name",
+ "apikeys_model_pull.hardware_gpu": "{0} GB graphics memory",
+ "apikeys_model_pull.best_for_machine": "Best for your machine",
+ "apikeys_model_pull.role_chat": "Chat and voice",
+ "apikeys_model_pull.role_vision": "Sees your screen",
+ "apikeys_model_pull.role_coder": "Coding worker",
+ "apikeys_model_pull.role_embedding": "Search embeddings",
})[key] ?? key,
}));
@@ -192,3 +198,131 @@ describe("local model download panel", () => {
}
});
});
+
+/**
+ * Hardware-aware ranking.
+ *
+ * The shortlist used to be the same four names on every machine. These pin the
+ * three things that replaced it: the panel groups by the job a model does, it
+ * marks the server's pick for THIS machine, and it says which memory figure the
+ * verdicts were judged against — because "18 GB is tight" is bewildering on a
+ * box with 64 GB of RAM until you know the number being compared is the card's.
+ */
+const RANKED_CATALOG = {
+ server: "http://localhost:11434",
+ server_reachable: true,
+ message: "",
+ memory_gb: 64,
+ accelerator_gb: 24,
+ accelerator_source: "nvidia-smi",
+ roles: ["chat", "vision", "embedding"],
+ installed: [],
+ models: [
+ {
+ id: "gpt-oss:120b",
+ label: "GPT-OSS 120B",
+ size_gb: 65.4,
+ purpose: "Frontier-class answers.",
+ role: "chat",
+ tools: true,
+ vision: false,
+ installed: false,
+ fit: "tight",
+ fit_note: "Bigger than the 24 GB of graphics memory.",
+ recommended: false,
+ },
+ {
+ id: "gpt-oss:20b",
+ label: "GPT-OSS 20B",
+ size_gb: 13.8,
+ purpose: "Noticeably stronger reasoning.",
+ role: "chat",
+ tools: true,
+ vision: false,
+ installed: false,
+ fit: "comfortable",
+ fit_note: "Fits in the 24 GB of graphics memory on this machine.",
+ recommended: true,
+ },
+ {
+ id: "qwen3-vl",
+ label: "Qwen 3 VL 8B",
+ size_gb: 6.1,
+ purpose: "Screen Context and Computer-Use.",
+ role: "vision",
+ tools: true,
+ vision: true,
+ installed: false,
+ fit: "comfortable",
+ fit_note: "Fits in the 24 GB of graphics memory on this machine.",
+ recommended: true,
+ },
+ {
+ id: "bge-m3",
+ label: "BGE-M3",
+ size_gb: 1.2,
+ purpose: "Multilingual embeddings.",
+ role: "embedding",
+ tools: false,
+ vision: false,
+ installed: false,
+ fit: "comfortable",
+ fit_note: "Fits in the 24 GB of graphics memory on this machine.",
+ recommended: false,
+ },
+ ],
+};
+
+describe("local model download panel — hardware-aware ranking", () => {
+ it("marks the server's pick for this machine, one per role", async () => {
+ installFetchMock(() => RANKED_CATALOG);
+
+ render(<AuthWidget descriptor={PULL_CARD} onChanged={() => {}} />);
+
+ await waitFor(() => expect(screen.getByText("GPT-OSS 20B")).toBeTruthy());
+ const recommended = document.querySelectorAll('[data-recommended="true"]');
+ expect(recommended).toHaveLength(2);
+ expect(
+ screen.getByTestId("model-pull-row-gpt-oss:20b").getAttribute("data-recommended"),
+ ).toBe("true");
+ // The biggest model is NOT the pick — it does not fit this card.
+ expect(
+ screen
+ .getByTestId("model-pull-row-gpt-oss:120b")
+ .getAttribute("data-recommended"),
+ ).toBe("false");
+ });
+
+ it("names the graphics memory the verdicts were judged against", async () => {
+ installFetchMock(() => RANKED_CATALOG);
+
+ render(<AuthWidget descriptor={PULL_CARD} onChanged={() => {}} />);
+
+ await waitFor(() => expect(screen.getByTestId("model-pull-hardware")).toBeTruthy());
+ expect(screen.getByTestId("model-pull-hardware").textContent).toContain("24");
+ });
+
+ it("falls back to the RAM figure when no accelerator could be read", async () => {
+ installFetchMock(() => ({
+ ...RANKED_CATALOG,
+ accelerator_gb: 0,
+ accelerator_source: "none",
+ }));
+
+ render(<AuthWidget descriptor={PULL_CARD} onChanged={() => {}} />);
+
+ await waitFor(() => expect(screen.getByTestId("model-pull-hardware")).toBeTruthy());
+ expect(screen.getByTestId("model-pull-hardware").textContent).toContain("64");
+ });
+
+ it("keeps working on a payload with no roles at all", async () => {
+ // An older backend: one unlabelled group, exactly as the panel looked
+ // before roles existed. No empty headings, no crash.
+ installFetchMock(() => CATALOG);
+
+ render(<AuthWidget descriptor={PULL_CARD} onChanged={() => {}} />);
+
+ await waitFor(() => expect(screen.getByText("Qwen 3 VL")).toBeTruthy());
+ expect(document.querySelectorAll('[data-recommended="true"]')).toHaveLength(0);
+ });
+});
diff --git a/jarvis/ui/web/frontend/src/components/providers/ProviderTierSection.tsx b/jarvis/ui/web/frontend/src/components/providers/ProviderTierSection.tsx
index 32db45f4c3..e68b70474d 100644
--- a/jarvis/ui/web/frontend/src/components/providers/ProviderTierSection.tsx
+++ b/jarvis/ui/web/frontend/src/components/providers/ProviderTierSection.tsx
@@ -1,5 +1,5 @@
import { useEffect, useMemo, useRef, useState } from "react";
-import { AlertCircle, Bot, Brain, Check, Copy, Download, HardDrive, Loader2, LogIn, LogOut, Mic, PlugZap, Radio, Sparkles, Terminal, Volume2, Wand2, Waypoints, XCircle } from "lucide-react";
+import { AlertCircle, Bot, Brain, Check, Copy, Download, HardDrive, Loader2, LogIn, LogOut, Mic, Play, PlugZap, Radio, Sparkles, Square, Terminal, Volume2, Wand2, Waypoints, XCircle } from "lucide-react";
import { AltCredentialNote } from "@/components/AltCredentialNote";
import { ApiKeyForm } from "@/components/ApiKeyForm";
import { BrainModelSelector } from "@/components/BrainModelSelector";
@@ -15,8 +15,11 @@ import {
logoutAntigravity,
managedServerInstall,
managedServerPreflight,
+ managedServerStart,
managedServerStatus,
+ managedServerStop,
managedServerUninstall,
+ type ManagedServerRuntime,
modelPullStatus,
pullableModels,
startLocalInstall,
@@ -27,6 +30,7 @@ import {
type ModelPullProgress,
type ProviderDescriptor,
type PullableModel,
+ type PullableRole,
type PullableModels,
type ProviderTestResult,
type ProviderTestStatus,
@@ -1908,8 +1912,10 @@ function ManagedServerPanel({
const status = descriptor.managed_server;
const [preflight, setPreflight] = useState<ManagedPreflight | null>(null);
const [progress, setProgress] = useState<ManagedInstallProgress | null>(null);
+ const [runtime, setRuntime] = useState<ManagedServerRuntime | null>(null);
const [error, setError] = useState<string | null>(null);
const [checking, setChecking] = useState(false);
+ const [lifecycleBusy, setLifecycleBusy] = useState(false);
const [confirmRemove, setConfirmRemove] = useState(false);
const running = Boolean(progress?.running);
@@ -1921,6 +1927,7 @@ function ManagedServerPanel({
const next = await managedServerStatus();
if (cancelled) return;
setProgress(next.progress);
+ setRuntime(next.runtime ?? null);
if (!next.progress.running) {
window.clearInterval(timer);
if (next.progress.phase === "error") {
@@ -1941,6 +1948,29 @@ function ManagedServerPanel({
};
}, [running, onChanged]);
+ // Idle runtime poll: the panel used to only look at the server DURING an
+ // install, so a crashed/stopped/foreign server rendered as whatever the
+ // last install left behind. One fetch on mount, then a slow heartbeat.
+ const installed = Boolean(status?.ready);
+ useEffect(() => {
+ if (running || !installed) return;
+ let cancelled = false;
+ const read = async () => {
+ try {
+ const next = await managedServerStatus();
+ if (!cancelled) setRuntime(next.runtime ?? null);
+ } catch {
+ if (!cancelled) setRuntime(null);
+ }
+ };
+ void read();
+ const timer = window.setInterval(read, 20_000);
+ return () => {
+ cancelled = true;
+ window.clearInterval(timer);
+ };
+ }, [running, installed]);
+
if (!status) return null;
// The Remove control must survive a PARTIAL state: after a failed
@@ -1987,12 +2017,50 @@ function ManagedServerPanel({
await managedServerUninstall();
setPreflight(null);
setProgress(null);
+ setRuntime(null);
onChanged();
} catch (err) {
setError(err instanceof Error ? err.message : String(err));
}
};
+ const startServer = async () => {
+ setError(null);
+ setLifecycleBusy(true);
+ try {
+ setRuntime(await managedServerStart());
+ } catch (err) {
+ setError(err instanceof Error ? err.message : String(err));
+ } finally {
+ setLifecycleBusy(false);
+ }
+ };
+
+ const stopServer = async () => {
+ setError(null);
+ setLifecycleBusy(true);
+ try {
+ setRuntime(await managedServerStop());
+ } catch (err) {
+ setError(err instanceof Error ? err.message : String(err));
+ } finally {
+ setLifecycleBusy(false);
+ }
+ };
+
+ // Live server verdict, honest about ownership: reachable-and-not-ours is a
+ // port conflict (or an orphan of a removed install), never claimed as ours.
+ const runtimeBadge =
+ runtime === null
+ ? null
+ : runtime.reachable && (runtime.owned || status.ready)
+ ? { key: "apikeys_view.managed_server_running", tone: "ok" as const }
+ : runtime.reachable
+ ? { key: "apikeys_view.managed_server_port_conflict", tone: "warn" as const }
+ : runtime.owned
+ ? { key: "apikeys_view.managed_server_starting", tone: "warn" as const }
+ : { key: "apikeys_view.managed_server_stopped", tone: "muted" as const };
+
const failed = progress?.phase === "error";
return (
<div className="space-y-2 rounded-md border border-border/60 bg-muted/30 p-3">
@@ -2007,6 +2075,65 @@ function ManagedServerPanel({
</span>
</div>
+ {!running && installed && runtimeBadge && (
+ <div
+ className="flex items-center gap-2 text-[11px]"
+ data-testid="managed-server-runtime"
+ aria-live="polite"
+ >
+ <span
+ aria-hidden="true"
+ className={cn(
+ "h-1.5 w-1.5 shrink-0 rounded-full",
+ runtimeBadge.tone === "ok"
+ ? "bg-emerald-400"
+ : runtimeBadge.tone === "warn"
+ ? "animate-pulse bg-amber-400 motion-reduce:animate-none"
+ : "bg-muted-foreground/40",
+ )}
+ />
+ <span
+ className={cn(
+ runtimeBadge.tone === "warn" ? "text-amber-400" : "text-muted-foreground",
+ )}
+ >
+ {t(runtimeBadge.key)}
+ </span>
+ {runtime && !runtime.reachable && !runtime.owned && (
+ <Button
+ size="sm"
+ variant="secondary"
+ onClick={startServer}
+ disabled={lifecycleBusy}
+ className="h-6 gap-1.5 px-2 text-[11px]"
+ >
+ {lifecycleBusy ? (
+ <Loader2 className="h-3 w-3 animate-spin" />
+ ) : (
+ <Play className="h-3 w-3" />
+ )}
+ {t("apikeys_view.managed_start_cta")}
+ </Button>
+ )}
+ {runtime?.owned && (
+ <Button
+ size="sm"
+ variant="ghost"
+ onClick={stopServer}
+ disabled={lifecycleBusy}
+ className="h-6 gap-1.5 px-2 text-[11px]"
+ >
+ {lifecycleBusy ? (
+ <Loader2 className="h-3 w-3 animate-spin" />
+ ) : (
+ <Square className="h-3 w-3" />
+ )}
+ {t("apikeys_view.managed_stop_cta")}
+ </Button>
+ )}
+ </div>
+ )}
+
{running && (
<div className="space-y-1">
<div className="h-1.5 w-full overflow-hidden rounded bg-muted">
@@ -2101,11 +2228,17 @@ function ManagedServerPanel({
* advisory — a GPU runs models the RAM rule calls tight, so it never disables
* the button.
*/
-function LocalModelDownloadPanel({
+export function LocalModelDownloadPanel({
descriptor,
onChanged,
}: {
- descriptor: ProviderDescriptor;
+ /**
+ * Only the two fields the panel actually uses. Widened from
+ * `ProviderDescriptor` so the Subagents tab — whose rows come from a
+ * different endpoint with a different shape — can render the very same panel
+ * instead of dead-ending a local-only user at an empty model dropdown.
+ */
+ descriptor: { id: string; supports_model_pull?: boolean };
onChanged: () => void;
}) {
const t = useT();
@@ -2186,6 +2319,31 @@ function LocalModelDownloadPanel({
const percent = progress?.percent ?? 0;
const rows: PullableModel[] = catalog?.models ?? [];
+ // Roles come from the backend, in its order. A payload without them (an older
+ // server) collapses into one unlabelled group, which is exactly how this
+ // panel looked before roles existed — no empty headings, no crash.
+ const roles: PullableRole[] = catalog?.roles ?? [];
+ const groups: { role: PullableRole | null; rows: PullableModel[] }[] = roles.length
+ ? roles
+ .map((role) => ({
+ role,
+ rows: rows.filter((r) => (r.role ?? "chat") === role),
+ }))
+ .filter((g) => g.rows.length > 0)
+ : [{ role: null, rows }];
+ // What the fit verdicts were judged against, in one short phrase. Naming the
+ // GPU matters: "18 GB is tight" is confusing on a box with 64 GB of RAM until
+ // you know the number being compared is the graphics card's.
+ const hardwareNote = catalog
+ ? (catalog.accelerator_gb ?? 0) > 0
+ ? t("apikeys_model_pull.hardware_gpu").replace(
+ "{0}",
+ String(Math.round(catalog.accelerator_gb ?? 0)),
+ )
+ : catalog.memory_gb
+ ? t("apikeys_model_pull.memory").replace("{0}", String(catalog.memory_gb))
+ : ""
+ : "";
return (
<div
@@ -2194,12 +2352,12 @@ function LocalModelDownloadPanel({
>
<div className="flex items-center justify-between gap-2">
<p className="text-xs font-medium">{t("apikeys_model_pull.title")}</p>
- {catalog?.memory_gb ? (
- <span className="text-[11px] text-muted-foreground">
- {t("apikeys_model_pull.memory").replace(
- "{0}",
- String(catalog.memory_gb),
- )}
+ {hardwareNote ? (
+ <span
+ data-testid="model-pull-hardware"
+ className="text-[11px] text-muted-foreground"
+ >
+ {hardwareNote}
</span>
) : null}
</div>
@@ -2208,11 +2366,24 @@ function LocalModelDownloadPanel({
<p className="text-[11px] text-amber-500">{catalog.message}</p>
)}
- <div className="space-y-1.5">
- {rows.map((row) => (
+ {groups.map((group) => (
+ <div key={group.role ?? "all"} className="space-y-1.5">
+ {group.role && (
+ <p className="pt-1 text-[10px] font-semibold uppercase tracking-wider text-muted-foreground/80">
+ {t(`apikeys_model_pull.role_${group.role}`)}
+ </p>
+ )}
+ {group.rows.map((row) => (
<div
key={row.id}
- className="flex items-start justify-between gap-2 rounded border border-border/50 bg-background/50 px-2 py-1.5"
+ data-testid={`model-pull-row-${row.id}`}
+ data-recommended={row.recommended ? "true" : "false"}
+ className={cn(
+ "flex items-start justify-between gap-2 rounded border bg-background/50 px-2 py-1.5",
+ row.recommended
+ ? "border-primary/40 bg-primary/[0.04]"
+ : "border-border/50",
+ )}
>
<div className="min-w-0">
<p className="truncate text-xs font-medium">
@@ -2223,12 +2394,25 @@ function LocalModelDownloadPanel({
String(row.size_gb),
)}
</span>
+ {row.recommended && (
+ <span className="ml-1.5 whitespace-nowrap rounded-full bg-primary/15 px-1.5 py-px text-[9px] font-semibold uppercase tracking-wide text-primary">
+ {t("apikeys_model_pull.best_for_machine")}
+ </span>
+ )}
</p>
<p className="text-[11px] leading-snug text-muted-foreground">
{row.purpose}
</p>
- {row.fit === "tight" && (
- <p className="text-[11px] leading-snug text-amber-500">
+ {/* The honest half of a recommendation: the comfortable note
+ explains why THIS one was picked, the tight note explains what
+ a bigger one would cost. Both are the server's wording. */}
+ {(row.fit === "tight" || row.recommended) && (
+ <p
+ className={cn(
+ "text-[11px] leading-snug",
+ row.fit === "tight" ? "text-amber-500" : "text-muted-foreground/80",
+ )}
+ >
{row.fit_note}
</p>
)}
@@ -2241,7 +2425,7 @@ function LocalModelDownloadPanel({
) : (
<Button
size="sm"
- variant="secondary"
+ variant={row.recommended ? "default" : "secondary"}
className="shrink-0 gap-1.5"
disabled={running || !catalog?.server_reachable}
onClick={() => void pull(row.id)}
@@ -2255,8 +2439,9 @@ function LocalModelDownloadPanel({
</Button>
)}
</div>
- ))}
- </div>
+ ))}
+ </div>
+ ))}
{/* Any name the library knows — the shortlist is a starting point, not a
gate, and a user who wants a specific model should not have to leave
diff --git a/jarvis/ui/web/frontend/src/hooks/useProviders.ts b/jarvis/ui/web/frontend/src/hooks/useProviders.ts
index 79a733aa6c..78fe61819d 100644
--- a/jarvis/ui/web/frontend/src/hooks/useProviders.ts
+++ b/jarvis/ui/web/frontend/src/hooks/useProviders.ts
@@ -279,7 +279,12 @@ export function useProviders(options: UseProvidersOptions = {}) {
const data: ProvidersResponse = await res.json();
if (version === requestVersion.current) {
retryAttempt.current = 0;
- setProviders(data.providers);
+ // A 200 whose body is not the expected shape (a proxy's error page, a
+ // partially-written response) must leave an EMPTY list, never
+ // `undefined`: every consumer maps or filters this, so one malformed
+ // payload would take the whole provider console down with a TypeError
+ // instead of showing the honest "no providers" state.
+ setProviders(Array.isArray(data?.providers) ? data.providers : []);
}
} catch (e) {
if ((e as Error).name !== "AbortError" && version === requestVersion.current) {
@@ -819,10 +824,24 @@ export async function localInstallStatus(
/** Fail-closed readiness of the managed local realtime server. */
export interface ManagedServerStatus {
ready: boolean;
+ /** Install files gone while jarvis.toml still points a launch command at them. */
+ stale?: boolean;
components: Record<string, boolean>;
sentence: string;
}
+/** Live runtime view of the managed server (what the disk cannot know). */
+export interface ManagedServerRuntime {
+ /** Something answers on the configured port right now. */
+ reachable: boolean;
+ port: number;
+ pid: number | null;
+ /** The recorded server process verifiably runs (PID-reuse safe). */
+ owned: boolean;
+ /** A pidfile exists but its process is gone. */
+ stale: boolean;
+}
+
/** Honest go/no-go report for the one-click managed install. */
export interface ManagedPreflight {
ok: boolean;
@@ -881,11 +900,34 @@ export async function managedServerInstall(
export async function managedServerStatus(): Promise<{
progress: ManagedInstallProgress;
server: ManagedServerStatus;
+ runtime?: ManagedServerRuntime;
}> {
const res = await fetch("/api/providers/local-realtime/managed-server/status");
const body = await res.json().catch(() => ({}));
if (!res.ok) throw new Error(body.detail ?? `HTTP ${res.status}`);
- return body as { progress: ManagedInstallProgress; server: ManagedServerStatus };
+ return body as {
+ progress: ManagedInstallProgress;
+ server: ManagedServerStatus;
+ runtime?: ManagedServerRuntime;
+ };
+}
+
+export async function managedServerStart(): Promise<ManagedServerRuntime | null> {
+ const res = await fetch("/api/providers/local-realtime/managed-server/start", {
+ method: "POST",
+ });
+ const body = await res.json().catch(() => ({}));
+ if (!res.ok) throw new Error(body.detail ?? `HTTP ${res.status}`);
+ return (body.runtime ?? null) as ManagedServerRuntime | null;
+}
+
+export async function managedServerStop(): Promise<ManagedServerRuntime | null> {
+ const res = await fetch("/api/providers/local-realtime/managed-server/stop", {
+ method: "POST",
+ });
+ const body = await res.json().catch(() => ({}));
+ if (!res.ok) throw new Error(body.detail ?? `HTTP ${res.status}`);
+ return (body.runtime ?? null) as ManagedServerRuntime | null;
}
export async function managedServerUninstall(): Promise<void> {
@@ -898,18 +940,30 @@ export async function managedServerUninstall(): Promise<void> {
}
}
+/** The job a local model fills — mirror of `ollama_pull.Role`. */
+export type PullableRole = "chat" | "vision" | "coder" | "embedding";
+
/** One curated model a local server can download, annotated for THIS machine. */
export interface PullableModel {
id: string;
label: string;
+ /** The registry's real download size when it answered, else the estimate. */
size_gb: number;
purpose: string;
+ /** Which slot this fills. Absent on older payloads — treated as "chat". */
+ role?: PullableRole;
tools: boolean;
vision: boolean;
installed: boolean;
/** "comfortable" | "tight" | "unknown" — advisory, never a block. */
fit: string;
fit_note: string;
+ /**
+ * The backend's pick for THIS machine in this role: the largest model it
+ * runs comfortably. At most one per role, and none at all once the role has
+ * something installed. Presentation hint — it never gates the pull button.
+ */
+ recommended?: boolean;
}
export interface PullableModels {
@@ -917,6 +971,12 @@ export interface PullableModels {
server_reachable: boolean;
message: string;
memory_gb: number | null;
+ /** GPU memory the fit verdicts were judged against; 0 = none readable. */
+ accelerator_gb?: number;
+ /** "nvidia-smi" | "apple-unified" | "none" — where that figure came from. */
+ accelerator_source?: string;
+ /** Role display order from the backend; the UI never invents its own. */
+ roles?: PullableRole[];
models: PullableModel[];
installed: string[];
}
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/de.json b/jarvis/ui/web/frontend/src/i18n/locales/de.json
index 72e65b6daa..873cad8222 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/de.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/de.json
@@ -1157,6 +1157,12 @@
"managed_latency": "Erwartete Antwortlatenz",
"managed_uninstall": "Lokalen Server entfernen",
"managed_uninstall_confirm": "Zum Bestätigen erneut klicken",
+ "managed_server_running": "Server läuft",
+ "managed_server_stopped": "Server gestoppt",
+ "managed_server_starting": "Server startet — Sprachmodelle werden geladen…",
+ "managed_server_port_conflict": "Ein anderer Prozess belegt diesen Port",
+ "managed_start_cta": "Server starten",
+ "managed_stop_cta": "Server stoppen",
"shared_delete_prefix": "Dieser Schlüssel wird auch verwendet von:",
"shared_delete_suffix": "Beim Löschen werden auch diese Provider deaktiviert.",
"delete_anyway": "Trotzdem löschen",
@@ -1331,7 +1337,13 @@
"size": "~{0} GB",
"installed": "Installiert",
"download": "Laden",
- "custom_placeholder": "Beliebiger Modellname, z. B. mistral"
+ "custom_placeholder": "Beliebiger Modellname, z. B. mistral",
+ "hardware_gpu": "{0} GB Grafikspeicher",
+ "best_for_machine": "Am besten für deinen Rechner",
+ "role_chat": "Chat und Sprache",
+ "role_vision": "Sieht deinen Bildschirm",
+ "role_coder": "Coding-Worker",
+ "role_embedding": "Such-Embeddings"
},
"apikeys_model": {
"heading": "Modell",
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/en.json b/jarvis/ui/web/frontend/src/i18n/locales/en.json
index 6ecd11f200..7e322806a3 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/en.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/en.json
@@ -1157,6 +1157,12 @@
"managed_latency": "Expected answer latency",
"managed_uninstall": "Remove local server",
"managed_uninstall_confirm": "Click again to confirm removal",
+ "managed_server_running": "Server running",
+ "managed_server_stopped": "Server stopped",
+ "managed_server_starting": "Server starting — loading voice models…",
+ "managed_server_port_conflict": "Another process is serving this port",
+ "managed_start_cta": "Start server",
+ "managed_stop_cta": "Stop server",
"shared_delete_prefix": "This key is also used by:",
"shared_delete_suffix": "Deleting it disables those providers too.",
"delete_anyway": "Delete anyway",
@@ -1331,7 +1337,13 @@
"size": "~{0} GB",
"installed": "Installed",
"download": "Download",
- "custom_placeholder": "Any model name, e.g. mistral"
+ "custom_placeholder": "Any model name, e.g. mistral",
+ "hardware_gpu": "{0} GB graphics memory",
+ "best_for_machine": "Best for your machine",
+ "role_chat": "Chat and voice",
+ "role_vision": "Sees your screen",
+ "role_coder": "Coding worker",
+ "role_embedding": "Search embeddings"
},
"apikeys_model": {
"heading": "Model",
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/es.json b/jarvis/ui/web/frontend/src/i18n/locales/es.json
index 2a10df6d2b..41d63bfaf7 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/es.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/es.json
@@ -1157,6 +1157,12 @@
"managed_latency": "Latencia de respuesta esperada",
"managed_uninstall": "Quitar el servidor local",
"managed_uninstall_confirm": "Haz clic de nuevo para confirmar",
+ "managed_server_running": "Servidor en marcha",
+ "managed_server_stopped": "Servidor detenido",
+ "managed_server_starting": "Servidor iniciándose — cargando los modelos de voz…",
+ "managed_server_port_conflict": "Otro proceso está sirviendo en este puerto",
+ "managed_start_cta": "Iniciar servidor",
+ "managed_stop_cta": "Detener servidor",
"shared_delete_prefix": "Esta clave también la usan:",
"shared_delete_suffix": "Al eliminarla, esos proveedores también se desactivan.",
"delete_anyway": "Eliminar de todos modos",
@@ -1331,7 +1337,13 @@
"size": "~{0} GB",
"installed": "Instalado",
"download": "Descargar",
- "custom_placeholder": "Cualquier nombre de modelo, p. ej. mistral"
+ "custom_placeholder": "Cualquier nombre de modelo, p. ej. mistral",
+ "hardware_gpu": "{0} GB de memoria gráfica",
+ "best_for_machine": "Lo mejor para tu equipo",
+ "role_chat": "Chat y voz",
+ "role_vision": "Ve tu pantalla",
+ "role_coder": "Worker de programación",
+ "role_embedding": "Embeddings de búsqueda"
},
"apikeys_model": {
"heading": "Modelo",
diff --git a/tests/integration/test_ollama_catalog_is_current.py b/tests/integration/test_ollama_catalog_is_current.py
new file mode 100644
index 0000000000..3437b8f962
--- /dev/null
+++ b/tests/integration/test_ollama_catalog_is_current.py
@@ -0,0 +1,93 @@
+"""The local-model shortlist must name models that actually exist, today.
+
+A curated list of model names is a maintenance liability: tags in the Ollama
+library are retired, renamed and re-quantised, and a stale entry does not fail
+loudly — it reaches a user as "Ollama does not know a model called 'qwen3.5:32b'"
+at the moment they finally decided to download something. That is the worst
+possible time to discover it, and it is invisible to every offline test, because
+offline the shortlist is just a tuple of strings that parses fine.
+
+This is the guard. It asks the public registry whether each curated id resolves,
+and it is also what keeps the list CURRENT: a maintainer bumping the catalog to
+a newer model generation finds out here whether the tags they wrote are real,
+instead of shipping guesses.
+
+Network-dependent by nature, so it is marked ``integration`` and self-skips when
+the registry cannot be reached — an offline CI run or a developer on a train
+must not go red over it. Run it explicitly with ``pytest -m integration``.
+"""
+
+from __future__ import annotations
+
+import httpx
+import pytest
+
+from jarvis.brain.ollama_pull import RECOMMENDED_MODELS, ROLE_ORDER
+
+pytestmark = pytest.mark.integration
+
+_REGISTRY = "https://registry.ollama.ai/v2/library"
+_ACCEPT = {"Accept": "application/vnd.docker.distribution.manifest.v2+json"}
+
+
+def _manifest(client: httpx.Client, model: str) -> httpx.Response:
+ name, _, tag = model.partition(":")
+ return client.get(f"{_REGISTRY}/{name}/manifests/{tag or 'latest'}", headers=_ACCEPT)
+
+
[email protected](scope="module")
+def registry() -> httpx.Client:
+ with httpx.Client(timeout=15.0) as client:
+ try:
+ probe = _manifest(client, "bge-m3")
+ except Exception as exc: # noqa: BLE001 — offline is a skip, not a failure
+ pytest.skip(f"Ollama registry unreachable: {type(exc).__name__} {exc}")
+ if probe.status_code != 200:
+ pytest.skip(f"Ollama registry answered {probe.status_code} for the probe")
+ yield client
+
+
[email protected]("entry", RECOMMENDED_MODELS, ids=lambda e: e.id)
+def test_every_curated_model_exists_in_the_library(entry, registry) -> None:
+ resp = _manifest(registry, entry.id)
+ assert resp.status_code == 200, (
+ f"'{entry.id}' is offered as a one-click download but the Ollama library "
+ f"answered {resp.status_code}. Replace it with a tag that exists — a user "
+ "clicking Download here gets a dead end otherwise."
+ )
+
+
[email protected]("entry", RECOMMENDED_MODELS, ids=lambda e: e.id)
+def test_the_fallback_size_is_in_the_right_ballpark(entry, registry) -> None:
+ """The curated size is the estimate shown until the registry answers.
+
+ It only has to be close: the fit verdict compares it against the machine's
+ memory, and an estimate that is off by half turns "fits in my card" into an
+ eviction at load time. A wide tolerance keeps a re-quantised tag from
+ failing the suite over a few hundred megabytes.
+ """
+ resp = _manifest(registry, entry.id)
+ if resp.status_code != 200:
+ pytest.skip("covered by the existence test above")
+ real_gb = sum(int(layer.get("size") or 0) for layer in resp.json().get("layers", [])) / 1e9
+ assert real_gb > 0
+ assert abs(real_gb - entry.size_gb) <= max(1.0, real_gb * 0.25), (
+ f"'{entry.id}' is listed at {entry.size_gb} GB but the library ships "
+ f"{real_gb:.1f} GB. Update the curated estimate."
+ )
+
+
+def test_every_role_still_offers_something() -> None:
+ """A role whose last entry is removed would silently stop being recommended
+ — the panel would just have one fewer group, which reads as "not needed"."""
+ roles = {entry.role for entry in RECOMMENDED_MODELS}
+ assert roles == set(ROLE_ORDER)
+
+
+def test_every_role_spans_more_than_one_size() -> None:
+ """The whole point of the hardware probe is picking BETWEEN sizes. A role
+ with a single entry gives it nothing to pick from, and a small machine and a
+ workstation get the same answer again."""
+ for role in ROLE_ORDER:
+ sizes = {e.size_gb for e in RECOMMENDED_MODELS if e.role == role}
+ assert len(sizes) >= 2, f"role '{role}' offers only one size"
diff --git a/tests/unit/brain/test_ollama_pull.py b/tests/unit/brain/test_ollama_pull.py
index c2b5a375c3..78ec49d072 100644
--- a/tests/unit/brain/test_ollama_pull.py
+++ b/tests/unit/brain/test_ollama_pull.py
@@ -85,6 +85,10 @@ class _FakeTagsClient:
payload: dict[str, Any] = {}
fail: bool = False
+ #: Registry manifests keyed by model id, for the real-size lookup. Empty by
+ #: default, which is the offline case: the curated estimates are used.
+ manifests: dict[str, dict[str, Any]] = {}
+
def __init__(self, **kwargs: Any) -> None:
pass
@@ -94,11 +98,19 @@ class _FakeTagsClient:
async def __aexit__(self, *exc: Any) -> None:
return None
- async def get(self, url: str) -> Any:
+ async def get(self, url: str, **kwargs: Any) -> Any:
+ # The registry lookup is a SECOND caller of this client. It must answer
+ # separately: handing it the /api/tags payload would make every model
+ # report a nonsense size, and a test suite that reaches the real
+ # registry would be a network dependency in a unit test.
+ if "registry.ollama.ai" in url:
+ return _registry_response(url)
if _FakeTagsClient.fail:
raise httpx.ConnectError("connection refused")
class _Resp:
+ status_code = 200
+
@staticmethod
def raise_for_status() -> None:
return None
@@ -110,12 +122,32 @@ class _FakeTagsClient:
return _Resp()
+def _registry_response(url: str) -> Any:
+ """A manifest for a model the test declared, else an honest 404."""
+ # ".../v2/library/<name>/manifests/<tag>"
+ parts = url.split("/v2/library/", 1)[-1].split("/manifests/")
+ model = parts[0] if len(parts) < 2 or parts[1] == "latest" else f"{parts[0]}:{parts[1]}"
+ manifest = _FakeTagsClient.manifests.get(model)
+
+ class _Resp:
+ status_code = 200 if manifest else 404
+
+ @staticmethod
+ def json() -> dict[str, Any]:
+ return manifest or {}
+
+ return _Resp()
+
+
@pytest.fixture()
def fake_tags(monkeypatch):
monkeypatch.setattr(httpx, "AsyncClient", _FakeTagsClient)
_FakeTagsClient.fail = False
_FakeTagsClient.payload = {}
- return _FakeTagsClient
+ _FakeTagsClient.manifests = {}
+ pull._registry_sizes.clear()
+ yield _FakeTagsClient
+ pull._registry_sizes.clear()
async def test_installed_models_excludes_cloud_references(fake_tags) -> None:
@@ -290,3 +322,134 @@ async def test_stream_error_line_becomes_an_error_state(monkeypatch) -> None:
run = pull._run_for("qwen3-vl")
assert run.state == "error"
assert "file does not exist" in run.message
+
+
+# ── Hardware-aware recommendation ────────────────────────────────────────
+# The shortlist used to be the same four names on every machine, so a
+# workstation with a 48 GB card was told to run a 4B model and a small laptop
+# was offered one it could not load. These pin the ranking that replaced it.
+
+
+def test_gpu_memory_outranks_ram_in_the_verdict() -> None:
+ """A 14 GB model on a box with a 24 GB card runs at full speed. Judging it
+ by the RAM rule alone called that "tight", which is backwards — and called
+ the same model "comfortable" on a 64 GB CPU-only server, where it crawls."""
+ verdict, note = pull.fit_verdict(14.0, memory_gb=32.0, accel_gb=24.0)
+ assert verdict == "comfortable"
+ assert "graphics memory" in note
+
+ verdict, note = pull.fit_verdict(14.0, memory_gb=64.0, accel_gb=8.0)
+ assert verdict == "tight"
+ assert "CPU" in note
+
+
+def test_a_machine_with_no_readable_gpu_falls_back_to_the_ram_rule() -> None:
+ """0 GB of accelerator means "none I could read", never "no memory": an AMD
+ card this probe cannot see must not downgrade the machine to unusable."""
+ verdict, note = pull.fit_verdict(5.0, memory_gb=32.0, accel_gb=0.0)
+ assert verdict == "comfortable"
+ assert "32" in note
+
+
+def test_accelerator_probe_survives_a_missing_hardware_module(monkeypatch) -> None:
+ import jarvis.hardware.detection as detection
+
+ def _boom() -> tuple[float, str]:
+ raise OSError("no nvidia-smi")
+
+ monkeypatch.setattr(detection, "usable_accelerator_gb", _boom)
+ assert pull.accelerator_gb() == (0.0, "none")
+
+
+def _machine(monkeypatch, *, ram: float | None, accel: float) -> None:
+ monkeypatch.setattr(pull, "total_memory_gb", lambda: ram)
+ monkeypatch.setattr(pull, "accelerator_gb", lambda: (accel, "nvidia-smi"))
+
+
+async def test_a_big_machine_is_recommended_a_big_model(fake_tags, monkeypatch) -> None:
+ _machine(monkeypatch, ram=128.0, accel=80.0)
+ result = await pull.recommendations()
+ chat = [m for m in result["models"] if m["role"] == "chat"]
+ picked = [m for m in chat if m["recommended"]]
+ assert len(picked) == 1, "exactly one pick per role"
+ # The largest chat model that still fits comfortably — on 80 GB that is the
+ # top of the list, which is the entire point of probing the hardware.
+ assert picked[0]["size_gb"] == max(m["size_gb"] for m in chat)
+
+
+async def test_a_small_machine_is_recommended_a_small_model(
+ fake_tags, monkeypatch
+) -> None:
+ _machine(monkeypatch, ram=8.0, accel=0.0)
+ result = await pull.recommendations()
+ chat = [m for m in result["models"] if m["role"] == "chat"]
+ picked = next(m for m in chat if m["recommended"])
+ assert picked["size_gb"] <= 4.0
+ assert picked["fit"] == "comfortable"
+
+
+async def test_a_machine_too_small_for_anything_still_gets_a_starting_point(
+ fake_tags, monkeypatch
+) -> None:
+ """Four entries all flagged "tight" and no pick answers "so which one?"
+ with silence. The smallest is marked instead."""
+ _machine(monkeypatch, ram=2.0, accel=0.0)
+ result = await pull.recommendations()
+ chat = [m for m in result["models"] if m["role"] == "chat"]
+ picked = next(m for m in chat if m["recommended"])
+ assert picked["size_gb"] == min(m["size_gb"] for m in chat)
+
+
+async def test_every_role_gets_its_own_pick(fake_tags, monkeypatch) -> None:
+ """A chat model does not substitute for an embedder. Each role is a separate
+ decision and gets a separate answer."""
+ _machine(monkeypatch, ram=64.0, accel=24.0)
+ result = await pull.recommendations()
+ picked_roles = {m["role"] for m in result["models"] if m["recommended"]}
+ assert picked_roles == set(result["roles"])
+
+
+async def test_an_installed_role_stops_being_recommended(
+ fake_tags, monkeypatch
+) -> None:
+ """Re-recommending a different size over a choice the user already made is
+ how a panel starts nagging."""
+ _machine(monkeypatch, ram=64.0, accel=24.0)
+ fake_tags.payload = {"models": [{"name": "qwen3.5:latest"}]}
+ result = await pull.recommendations()
+ chat = [m for m in result["models"] if m["role"] == "chat"]
+ assert not any(m["recommended"] for m in chat)
+ # Other roles are untouched — one installed model does not silence the rest.
+ assert any(m["recommended"] for m in result["models"] if m["role"] == "vision")
+
+
+async def test_real_registry_sizes_replace_the_estimates(fake_tags, monkeypatch) -> None:
+ """The hardcoded estimates were up to a third off, which is enough to turn
+ "fits in my card" into an eviction at load time."""
+ _machine(monkeypatch, ram=64.0, accel=24.0)
+ fake_tags.manifests = {"qwen3.5": {"layers": [{"size": 9_000_000_000}]}}
+ result = await pull.recommendations()
+ by_id = {m["id"]: m for m in result["models"]}
+ assert by_id["qwen3.5"]["size_gb"] == 9.0
+ # A model the registry did not answer for keeps its curated estimate rather
+ # than vanishing or reporting zero.
+ assert by_id["bge-m3"]["size_gb"] > 0
+
+
+async def test_an_offline_registry_leaves_a_usable_panel(fake_tags, monkeypatch) -> None:
+ _machine(monkeypatch, ram=32.0, accel=0.0)
+ result = await pull.recommendations()
+ assert all(m["size_gb"] > 0 for m in result["models"])
+ assert any(m["recommended"] for m in result["models"])
+
+
+async def test_the_payload_names_the_hardware_it_judged_against(
+ fake_tags, monkeypatch
+) -> None:
+ """A verdict the user cannot check against their own machine is a verdict
+ they have to take on faith."""
+ _machine(monkeypatch, ram=32.0, accel=16.0)
+ result = await pull.recommendations()
+ assert result["accelerator_gb"] == 16.0
+ assert result["accelerator_source"] == "nvidia-smi"
+ assert result["memory_gb"] == 32.0