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(brain): download local models from inside the app

rubenluetke10-beep6e62da603a20
diff --git a/jarvis/brain/ollama_pull.py b/jarvis/brain/ollama_pull.py
new file mode 100644
index 0000000000..ff7d16b794
--- /dev/null
+++ b/jarvis/brain/ollama_pull.py
@@ -0,0 +1,385 @@
+"""In-app model downloads for a local Ollama server.
+
+CLAUDE.md section 3 requires a capability to be recoverable from INSIDE the
+app. The local brain card missed that bar in the one place it matters most:
+with a running server and no downloads, every path failed with "run: ollama
+pull <model>" — a terminal instruction in a desktop app with no terminal, and
+the point where a keyless install stops being usable at all.
+
+This module is the brain-side twin of :mod:`jarvis.speech.local_install`: a
+curated shortlist of pulls, an honest size/fit verdict against the machine's
+actual memory, and a background download whose progress the UI polls. The
+server does the work — ``POST /api/pull`` streams NDJSON progress lines — so
+nothing here needs a package manager or elevated rights.
+
+Two deliberate choices:
+
+* **Curated names are a starting point, never a gate.** Model names in the
+ Ollama library drift (tags come and go), so any name may be pulled, and a
+ name the registry does not know produces an honest "not in the library"
+ message pointing at ollama.com/library rather than a silent failure.
+* **Fit is advisory, never a block.** The memory verdict uses total RAM and a
+ rule of thumb; a GPU box runs models the rule calls tight. It informs the
+ choice — it does not forbid one (the maintainer's box is not the baseline).
+"""
+
+from __future__ import annotations
+
+import asyncio
+import json
+import logging
+from dataclasses import dataclass
+from typing import Any, Literal
+
+import httpx
+
+from jarvis.plugins.brain.ollama import CLIENT_TIMEOUT, default_server_root, normalize_server_root
+
+log = logging.getLogger(__name__)
+
+PullState = Literal["idle", "running", "done", "error"]
+
+#: Providers whose server speaks a native pull protocol. Membership is a
+#: PROTOCOL fact (Ollama's ``/api/pull``), not a preference: a generic
+#: OpenAI-compatible server has no standard way to be told "fetch this model",
+#: which is why ``local-openai`` is absent rather than disabled. A second
+#: server type joins by shipping its own puller, not by being named here.
+PULL_CAPABLE_PROVIDERS: frozenset[str] = frozenset({"ollama"})
+
+#: A pull streams gigabytes; the read timeout must cover a slow line, while the
+#: connect timeout stays as short as everywhere else so a dead server fails fast.
+_PULL_TIMEOUT = httpx.Timeout(connect=2.0, read=600.0, write=30.0, pool=30.0)
+
+#: Rule of thumb for the fit verdict: weights plus runtime overhead should sit
+#: inside this share of total memory. Above it the machine still runs the model,
+#: just slowly (swap) — hence "tight", not "impossible".
+_COMFORTABLE_SHARE = 0.6
+_OVERHEAD_GB = 2.0
+
+
+@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.
+ """
+
+ id: str
+ label: str
+ size_gb: float
+ purpose: str
+ 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.
+RECOMMENDED_MODELS: tuple[RecommendedModel, ...] = (
+ RecommendedModel(
+ id="qwen3.5:4b",
+ label="Qwen 3.5 4B",
+ size_gb=2.6,
+ purpose="Chat and voice on a small machine. Calls tools.",
+ ),
+ RecommendedModel(
+ id="qwen3.5",
+ label="Qwen 3.5 (default size)",
+ size_gb=5.2,
+ purpose="The balanced default: chat, voice, and reliable tool calling.",
+ ),
+ RecommendedModel(
+ id="qwen3-vl",
+ label="Qwen 3 VL",
+ size_gb=6.0,
+ purpose="Sees images — needed for Screen Context and Computer-Use.",
+ vision=True,
+ ),
+ RecommendedModel(
+ id="bge-m3",
+ label="BGE-M3",
+ size_gb=1.2,
+ purpose="Embeddings for UltraWiki search. Not a chat model.",
+ tools=False,
+ ),
+)
+
+
+@dataclass
+class _PullRun:
+ """Mutable progress of ONE model download."""
+
+ state: PullState = "idle"
+ message: str = ""
+ completed: int = 0
+ total: int = 0
+ task: asyncio.Task[None] | None = None
+
+
+#: One run per model id: pulling a vision model must not look "already running"
+#: because an embedder is still downloading.
+_runs: dict[str, _PullRun] = {}
+
+
+def _run_for(model: str) -> _PullRun:
+ return _runs.setdefault(model, _PullRun())
+
+
+def server_root() -> str:
+ """The configured Ollama server root (override → OLLAMA_HOST → localhost)."""
+ from jarvis.core import config as cfg
+
+ endpoint = cfg.resolve_provider_endpoint(
+ "ollama", vendor_default_base_url=default_server_root()
+ )
+ return normalize_server_root(endpoint.base_url or default_server_root())
+
+
+def total_memory_gb() -> float | None:
+ """Total system memory in GB, or ``None`` when it cannot be read.
+
+ ``None`` is a real answer on a locked-down host and must stay one: the fit
+ verdict then says "unknown" instead of inventing a number that would make a
+ 9 GB model look safe on a 4 GB box.
+ """
+ try:
+ import psutil # noqa: PLC0415 — lazy (AP-26)
+
+ return round(psutil.virtual_memory().total / (1024**3), 1)
+ 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]:
+ """``(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.
+ """
+ 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 (
+ "tight",
+ f"Needs about {needed:g} GB with {memory_gb:g} GB installed — it will "
+ "run, but expect it to be slow unless a GPU takes over.",
+ )
+
+
+async def installed_models() -> tuple[set[str], str | None]:
+ """``(installed model ids, error)`` from the server's own ``/api/tags``.
+
+ ``:cloud`` references are excluded for the same reason the brain excludes
+ them: they are ollama.com-proxied, not local weights. The error string is
+ ``None`` on success and an English sentence when the server did not answer
+ — the caller shows it instead of an empty list that would read as "you have
+ nothing installed".
+ """
+ root = server_root()
+ try:
+ async with httpx.AsyncClient(timeout=CLIENT_TIMEOUT) as client:
+ resp = await client.get(f"{root}/api/tags")
+ resp.raise_for_status()
+ payload = resp.json()
+ except Exception as exc: # noqa: BLE001 — an unreachable server is a normal state
+ log.info("ollama-pull: /api/tags unreachable at %s (%s)", root, type(exc).__name__)
+ return set(), (
+ f"Ollama did not answer at {root}. Start the server (or install it "
+ "from ollama.com/download) and try again."
+ )
+ names = {
+ str(m.get("name") or "").strip()
+ for m in payload.get("models") or []
+ if not str(m.get("name") or "").endswith(":cloud") and not m.get("remote")
+ }
+ return {n for n in names if n}, None
+
+
+def _is_installed(model: str, installed: set[str]) -> bool:
+ """Whether ``model`` is present, treating a bare name as its ``:latest`` tag.
+
+ ``ollama pull qwen3.5`` installs ``qwen3.5:latest``, so a card that compared
+ the two literally would offer a pull the user already completed.
+ """
+ if model in installed:
+ return True
+ if ":" not in model:
+ return f"{model}:latest" in installed
+ return False
+
+
+async def recommendations() -> dict[str, Any]:
+ """The curated shortlist, annotated with what THIS machine already has."""
+ installed, error = await installed_models()
+ memory_gb = total_memory_gb()
+ models: list[dict[str, Any]] = []
+ for entry in RECOMMENDED_MODELS:
+ verdict, note = fit_verdict(entry.size_gb, memory_gb)
+ models.append(
+ {
+ "id": entry.id,
+ "label": entry.label,
+ "size_gb": entry.size_gb,
+ "purpose": entry.purpose,
+ "tools": entry.tools,
+ "vision": entry.vision,
+ "installed": _is_installed(entry.id, installed),
+ "fit": verdict,
+ "fit_note": note,
+ }
+ )
+ return {
+ "server": server_root(),
+ "server_reachable": error is None,
+ "message": error or "",
+ "memory_gb": memory_gb,
+ "models": models,
+ "installed": sorted(installed),
+ }
+
+
+async def _run_pull(model: str) -> None:
+ """Stream ``/api/pull`` into the run state. Never raises."""
+ run = _run_for(model)
+ root = server_root()
+ try:
+ async with httpx.AsyncClient(timeout=_PULL_TIMEOUT) as client, client.stream(
+ "POST", f"{root}/api/pull", json={"model": model, "stream": True}
+ ) as resp:
+ if resp.status_code == 404:
+ run.state = "error"
+ run.message = (
+ f"Ollama does not know a model called '{model}'. Check the "
+ "name at ollama.com/library and try again."
+ )
+ return
+ resp.raise_for_status()
+ async for line in resp.aiter_lines():
+ if not line.strip():
+ continue
+ try:
+ event = json.loads(line)
+ except ValueError:
+ # One unparsable progress line is not a failed download —
+ # log it and keep reading, so a chatty server cannot abort
+ # a pull that is otherwise going fine.
+ log.debug("ollama-pull: unparsable progress line for %s: %r", model, line[:200])
+ continue
+ if error := event.get("error"):
+ run.state = "error"
+ run.message = str(error)
+ return
+ run.message = str(event.get("status") or run.message)
+ run.completed = int(event.get("completed") or run.completed)
+ run.total = int(event.get("total") or run.total)
+ except asyncio.CancelledError:
+ run.state = "error"
+ run.message = f"The download of {model} was cancelled."
+ raise
+ except Exception as exc: # noqa: BLE001 — surface an honest, retryable state
+ run.state = "error"
+ run.message = f"Could not download {model}: {exc}"
+ log.info("ollama-pull: %s failed", model, exc_info=True)
+ return
+
+ # Trust the server's inventory over the stream's last line: a pull can end
+ # cleanly and still leave nothing usable, and a card that says "ready" over
+ # a missing model is the failure this whole area exists to prevent.
+ installed, error = await installed_models()
+ if error or not _is_installed(model, installed):
+ run.state = "error"
+ run.message = error or (
+ f"The download finished, but {model} is not listed on the server. "
+ "Try again — the pull may have been interrupted."
+ )
+ return
+ run.state = "done"
+ run.message = f"{model} is ready — it runs on this machine now."
+ log.info("ollama-pull: %s completed", model)
+
+
+async def start_pull(model: str) -> dict[str, Any]:
+ """Begin (or join) a download of ``model``; returns its current state.
+
+ Idempotent: a second call while a pull is in flight joins the running one
+ instead of starting a duplicate multi-gigabyte download.
+ """
+ name = (model or "").strip()
+ if not name:
+ return {"state": "error", "model": "", "message": "No model name given."}
+ installed, _error = await installed_models()
+ if _is_installed(name, installed):
+ return {
+ "state": "done",
+ "model": name,
+ "already": True,
+ "message": f"{name} is already installed.",
+ }
+ run = _run_for(name)
+ if run.state == "running":
+ return {"state": "running", "model": name, "message": run.message}
+ run.state = "running"
+ run.message = f"Starting the download of {name}…"
+ run.completed = 0
+ run.total = 0
+ # Keep the reference on the run: a bare create_task may be garbage-collected
+ # mid-download, which would look exactly like a stalled server.
+ run.task = asyncio.create_task(_run_pull(name), name=f"ollama-pull-{name}")
+ return {"state": "running", "model": name, "message": run.message}
+
+
+async def pull_status(model: str) -> dict[str, Any]:
+ """Progress of ``model``'s download plus the server's own inventory.
+
+ The inventory wins when the two disagree: a model pulled by some other route
+ (the CLI, another Jarvis window, a previous run) reads as installed even
+ though this process never downloaded it.
+ """
+ name = (model or "").strip()
+ if not name:
+ return {"state": "error", "model": "", "message": "No model name given."}
+ installed, error = await installed_models()
+ present = _is_installed(name, installed)
+ run = _run_for(name)
+ state: PullState = run.state
+ message = run.message
+ if present and state in ("idle", "running"):
+ state = "done"
+ message = f"{name} is installed."
+ elif state == "idle" and error:
+ message = error
+ percent = 0.0
+ if run.total > 0:
+ percent = round(min(100.0, run.completed / run.total * 100), 1)
+ elif state == "done":
+ percent = 100.0
+ return {
+ "state": state,
+ "model": name,
+ "message": message,
+ "installed": present,
+ "completed": run.completed,
+ "total": run.total,
+ "percent": percent,
+ }
+
+
+__all__ = [
+ "PULL_CAPABLE_PROVIDERS",
+ "RECOMMENDED_MODELS",
+ "RecommendedModel",
+ "fit_verdict",
+ "installed_models",
+ "pull_status",
+ "recommendations",
+ "server_root",
+ "start_pull",
+ "total_memory_gb",
+]
diff --git a/jarvis/ui/web/frontend/src/components/providers/LocalModelDownloadPanel.test.tsx b/jarvis/ui/web/frontend/src/components/providers/LocalModelDownloadPanel.test.tsx
new file mode 100644
index 0000000000..da0ea31db4
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/providers/LocalModelDownloadPanel.test.tsx
@@ -0,0 +1,194 @@
+/**
+ * Component tests for the local-model download panel.
+ *
+ * The feature exists because a keyless install used to dead-end at "run:
+ * ollama pull <model>" — a terminal instruction in an app with no terminal.
+ * What these tests pin is that the panel never invents any part of that story:
+ *
+ * - it appears only where the SERVER can actually be told to fetch a model,
+ * decided by a capability flag rather than a provider name (AP-21);
+ * - installed state and the memory verdict come from the server, verbatim;
+ * - a "tight" fit is shown as a caution, never as a disabled button — a GPU
+ * runs models the RAM rule calls tight;
+ * - a started download reports real progress instead of freezing on a spinner.
+ */
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
+
+import { AuthWidget } from "@/components/providers/ProviderTierSection";
+import type { ProviderDescriptor } from "@/hooks/useProviders";
+
+vi.mock("@/i18n", () => ({
+ useT: () => (key: string) =>
+ ({
+ "apikeys_model_pull.title": "Models on this machine",
+ "apikeys_model_pull.memory": "{0} GB RAM",
+ "apikeys_model_pull.size": "~{0} GB",
+ "apikeys_model_pull.installed": "Installed",
+ "apikeys_model_pull.download": "Download",
+ "apikeys_model_pull.custom_placeholder": "Any model name",
+ })[key] ?? key,
+}));
+
+const PULL_CARD: ProviderDescriptor = {
+ id: "ollama",
+ label: "Ollama (local)",
+ tier: "brain",
+ auth_mode: "none",
+ secret_keys: [],
+ secrets_set: {},
+ dashboard_url: null,
+ login_cli: null,
+ install_hint: null,
+ credential_path_hint: null,
+ configured: true,
+ active: false,
+ cli_installed: null,
+ credential_help: "Runs models fully local.",
+ signup_url: null,
+ billing: "local",
+ alt_credential: null,
+ local_runtime: null,
+ supports_model_pull: true,
+} as ProviderDescriptor;
+
+const CATALOG = {
+ server: "http://localhost:11434",
+ server_reachable: true,
+ message: "",
+ memory_gb: 32,
+ installed: ["qwen3.5:latest"],
+ models: [
+ {
+ id: "qwen3.5",
+ label: "Qwen 3.5",
+ size_gb: 5.2,
+ purpose: "The balanced default.",
+ tools: true,
+ vision: false,
+ installed: true,
+ fit: "comfortable",
+ fit_note: "Runs comfortably in 32 GB of memory.",
+ },
+ {
+ id: "qwen3-vl",
+ label: "Qwen 3 VL",
+ size_gb: 6,
+ purpose: "Sees images.",
+ tools: true,
+ vision: true,
+ installed: false,
+ fit: "tight",
+ fit_note: "Needs about 8 GB with 8 GB installed.",
+ },
+ ],
+};
+
+function installFetchMock(handler: (url: string, init?: RequestInit) => unknown) {
+ const fetchMock = vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {
+ const body = handler(String(input), init);
+ return {
+ ok: true,
+ status: 200,
+ statusText: "OK",
+ json: async () => body,
+ text: async () => JSON.stringify(body),
+ } as Response;
+ });
+ (globalThis as unknown as { fetch: typeof fetch }).fetch =
+ fetchMock as unknown as typeof fetch;
+ return fetchMock;
+}
+
+afterEach(() => {
+ cleanup();
+ vi.restoreAllMocks();
+});
+
+describe("local model download panel", () => {
+ it("renders nothing on a card whose server has no download API", async () => {
+ const fetchMock = installFetchMock(() => CATALOG);
+ const cloudCard = { ...PULL_CARD, id: "openai", supports_model_pull: false };
+
+ render(<AuthWidget descriptor={cloudCard} onChanged={() => {}} />);
+
+ expect(screen.queryByText("Models on this machine")).toBeNull();
+ // And it must not even ASK: a cloud card firing this request would get a
+ // 400 on every render of the provider list.
+ expect(
+ fetchMock.mock.calls.filter((c) => String(c[0]).includes("pullable-models")),
+ ).toHaveLength(0);
+ });
+
+ it("shows what the server reports: sizes, memory, and what is already there", async () => {
+ installFetchMock(() => CATALOG);
+
+ render(<AuthWidget descriptor={PULL_CARD} onChanged={() => {}} />);
+
+ await waitFor(() => expect(screen.getByText("Qwen 3 VL")).toBeTruthy());
+ expect(screen.getByText("32 GB RAM")).toBeTruthy();
+ expect(screen.getByText("Installed")).toBeTruthy();
+ expect(screen.getByText("Sees images.")).toBeTruthy();
+ });
+
+ it("shows a tight fit as a caution, never as a blocked download", async () => {
+ installFetchMock(() => CATALOG);
+
+ render(<AuthWidget descriptor={PULL_CARD} onChanged={() => {}} />);
+
+ await waitFor(() =>
+ expect(screen.getByText("Needs about 8 GB with 8 GB installed.")).toBeTruthy(),
+ );
+ const buttons = screen.getAllByRole("button", { name: /download/i });
+ expect(buttons.some((b) => !(b as HTMLButtonElement).disabled)).toBe(true);
+ });
+
+ it("starts a download and then reports the server's progress", async () => {
+ const calls: string[] = [];
+ installFetchMock((url) => {
+ calls.push(url);
+ if (url.includes("/pull/status")) {
+ return {
+ state: "running",
+ model: "qwen3-vl",
+ message: "pulling manifest",
+ percent: 42,
+ };
+ }
+ if (url.endsWith("/pull")) {
+ return { state: "running", model: "qwen3-vl", message: "Starting…" };
+ }
+ return CATALOG;
+ });
+
+ render(<AuthWidget descriptor={PULL_CARD} onChanged={() => {}} />);
+ await waitFor(() => expect(screen.getByText("Qwen 3 VL")).toBeTruthy());
+
+ const download = screen
+ .getAllByRole("button", { name: /download/i })
+ .find((b) => !(b as HTMLButtonElement).disabled)!;
+ fireEvent.click(download);
+
+ await waitFor(() => expect(screen.getByText(/qwen3-vl: Starting/)).toBeTruthy());
+ expect(calls.some((u) => u.endsWith("/api/providers/ollama/pull"))).toBe(true);
+ });
+
+ it("keeps the shortlist visible when the server is down, with its reason", async () => {
+ installFetchMock(() => ({
+ ...CATALOG,
+ server_reachable: false,
+ message: "Ollama did not answer at http://localhost:11434.",
+ }));
+
+ render(<AuthWidget descriptor={PULL_CARD} onChanged={() => {}} />);
+
+ await waitFor(() =>
+ expect(screen.getByText(/Ollama did not answer/)).toBeTruthy(),
+ );
+ expect(screen.getByText("Qwen 3 VL")).toBeTruthy();
+ // Nothing can be pulled from a server that is not there.
+ for (const button of screen.getAllByRole("button", { name: /download/i })) {
+ expect((button as HTMLButtonElement).disabled).toBe(true);
+ }
+ });
+});
diff --git a/jarvis/ui/web/frontend/src/components/providers/ProviderTierSection.tsx b/jarvis/ui/web/frontend/src/components/providers/ProviderTierSection.tsx
index 5abebd883d..585cf0e06a 100644
--- a/jarvis/ui/web/frontend/src/components/providers/ProviderTierSection.tsx
+++ b/jarvis/ui/web/frontend/src/components/providers/ProviderTierSection.tsx
@@ -13,9 +13,15 @@ import {
loginAntigravity,
localInstallStatus,
logoutAntigravity,
+ modelPullStatus,
+ pullableModels,
startLocalInstall,
+ startModelPull,
type LocalInstallProgress,
+ type ModelPullProgress,
type ProviderDescriptor,
+ type PullableModel,
+ type PullableModels,
type ProviderTestResult,
type ProviderTestStatus,
type ProviderTier,
@@ -1732,6 +1738,216 @@ function LocalRuntimePanel({
);
}
+/**
+ * The download half of a keyless local brain card: which models this machine
+ * could run, which it already has, and the one button that fetches one.
+ *
+ * Without it a keyless install dead-ended at "run: ollama pull <model>" — a
+ * terminal instruction in an app that has no terminal, and the exact point
+ * where §3's "recoverable in-app" contract broke. Nothing is inferred client
+ * side: installed state, fit verdict and progress all come from the server,
+ * because only it can see the user's inventory and memory. The fit verdict is
+ * advisory — a GPU runs models the RAM rule calls tight, so it never disables
+ * the button.
+ */
+function LocalModelDownloadPanel({
+ descriptor,
+ onChanged,
+}: {
+ descriptor: ProviderDescriptor;
+ onChanged: () => void;
+}) {
+ const t = useT();
+ const [catalog, setCatalog] = useState<PullableModels | null>(null);
+ const [error, setError] = useState<string | null>(null);
+ const [custom, setCustom] = useState("");
+ const [progress, setProgress] = useState<ModelPullProgress | null>(null);
+ const running = progress?.state === "running";
+
+ // Hooks run before the capability check below, so the fetch itself is gated:
+ // a cloud card that mounted this panel would otherwise fire a request the
+ // route answers with 400 on every render of the provider list.
+ const pullable = Boolean(descriptor.supports_model_pull);
+ const load = useMemo(
+ () => async () => {
+ if (!pullable) return;
+ try {
+ setCatalog(await pullableModels(descriptor.id));
+ setError(null);
+ } catch (err) {
+ setError(err instanceof Error ? err.message : String(err));
+ }
+ },
+ [descriptor.id, pullable],
+ );
+
+ useEffect(() => {
+ void load();
+ }, [load]);
+
+ // Poll only while a pull is in flight. A finished download refreshes both the
+ // shortlist (so the row flips to "installed") and the provider list (so the
+ // model picker sees the new model without a restart).
+ useEffect(() => {
+ if (!running || !progress) return;
+ let cancelled = false;
+ const model = progress.model;
+ const timer = window.setInterval(async () => {
+ try {
+ const next = await modelPullStatus(descriptor.id, model);
+ if (cancelled) return;
+ setProgress(next);
+ if (next.state === "done" || next.state === "error") {
+ window.clearInterval(timer);
+ void load();
+ onChanged();
+ }
+ } catch (err) {
+ if (cancelled) return;
+ window.clearInterval(timer);
+ setError(err instanceof Error ? err.message : String(err));
+ setProgress(null);
+ }
+ }, 2500);
+ return () => {
+ cancelled = true;
+ window.clearInterval(timer);
+ };
+ }, [running, progress, descriptor.id, load, onChanged]);
+
+ if (!pullable) return null;
+
+ const pull = async (model: string) => {
+ const name = model.trim();
+ if (!name) return;
+ setError(null);
+ try {
+ const started = await startModelPull(descriptor.id, name);
+ setProgress(started);
+ if (started.state === "done") {
+ void load();
+ onChanged();
+ }
+ } catch (err) {
+ setError(err instanceof Error ? err.message : String(err));
+ }
+ };
+
+ const percent = progress?.percent ?? 0;
+ const rows: PullableModel[] = catalog?.models ?? [];
+
+ return (
+ <div
+ data-testid={`provider-model-pull-${descriptor.id}`}
+ className="space-y-2 rounded-md border border-border/60 bg-muted/30 p-3"
+ >
+ <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),
+ )}
+ </span>
+ ) : null}
+ </div>
+
+ {catalog && !catalog.server_reachable && (
+ <p className="text-[11px] text-amber-500">{catalog.message}</p>
+ )}
+
+ <div className="space-y-1.5">
+ {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"
+ >
+ <div className="min-w-0">
+ <p className="truncate text-xs font-medium">
+ {row.label}{" "}
+ <span className="font-normal text-muted-foreground">
+ {t("apikeys_model_pull.size").replace(
+ "{0}",
+ String(row.size_gb),
+ )}
+ </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">
+ {row.fit_note}
+ </p>
+ )}
+ </div>
+ {row.installed ? (
+ <span className="flex shrink-0 items-center gap-1 text-[11px] text-emerald-500">
+ <Check className="h-3.5 w-3.5" />
+ {t("apikeys_model_pull.installed")}
+ </span>
+ ) : (
+ <Button
+ size="sm"
+ variant="secondary"
+ className="shrink-0 gap-1.5"
+ disabled={running || !catalog?.server_reachable}
+ onClick={() => void pull(row.id)}
+ >
+ {running && progress?.model === row.id ? (
+ <Loader2 className="h-3.5 w-3.5 animate-spin" />
+ ) : (
+ <Download className="h-3.5 w-3.5" />
+ )}
+ {t("apikeys_model_pull.download")}
+ </Button>
+ )}
+ </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
+ the app for it. */}
+ <div className="flex items-center gap-2">
+ <input
+ type="text"
+ value={custom}
+ onChange={(e) => setCustom(e.target.value)}
+ placeholder={t("apikeys_model_pull.custom_placeholder")}
+ className="h-8 w-full rounded-md border border-border bg-background px-2 text-xs"
+ />
+ <Button
+ size="sm"
+ variant="secondary"
+ disabled={running || !custom.trim() || !catalog?.server_reachable}
+ onClick={() => void pull(custom)}
+ >
+ {t("apikeys_model_pull.download")}
+ </Button>
+ </div>
+
+ {progress && progress.state !== "idle" && (
+ <div className="space-y-1">
+ <p className="text-[11px] text-muted-foreground">
+ {progress.model}: {progress.message}
+ </p>
+ {running && (
+ <div className="h-1 w-full overflow-hidden rounded bg-border">
+ <div
+ className="h-full bg-primary transition-all"
+ style={{ width: `${percent}%` }}
+ />
+ </div>
+ )}
+ </div>
+ )}
+ {error && <p className="text-[11px] text-destructive">{error}</p>}
+ </div>
+ );
+}
+
export function AuthWidget({
descriptor,
onChanged,
@@ -1775,6 +1991,9 @@ export function AuthWidget({
{descriptor.supports_base_url && (
<BaseUrlField descriptor={descriptor} onChanged={onChanged} />
)}
+ <LocalModelDownloadPanel descriptor={descriptor} onChanged={onChanged} />
+ {/* Ordered after the server URL on purpose: a download can only be
+ offered once the card points at the right server. */}
{descriptor.auth_mode === "none" && (
<>
<p className="text-xs text-muted-foreground">
diff --git a/jarvis/ui/web/frontend/src/hooks/useProviders.ts b/jarvis/ui/web/frontend/src/hooks/useProviders.ts
index 2a76f0347c..41fb65da2d 100644
--- a/jarvis/ui/web/frontend/src/hooks/useProviders.ts
+++ b/jarvis/ui/web/frontend/src/hooks/useProviders.ts
@@ -136,6 +136,13 @@ export interface ProviderDescriptor {
/** Local/self-hosted cards: whether the card exposes an editable server URL
* (persisted via PUT /api/providers/{id}/base-url). */
supports_base_url?: boolean;
+ /**
+ * Whether this card's server can be TOLD to download a model
+ * (POST /api/providers/{id}/pull). A capability flag rather than a provider
+ * name: a generic OpenAI-compatible server has no such API, an Ollama server
+ * does, and the UI decides on the flag alone.
+ */
+ supports_model_pull?: boolean;
/** Placeholder while no override is stored; null = the user must set one. */
default_base_url?: string | null;
/** The stored server-URL override; null = the vendor default is in effect. */
@@ -803,6 +810,94 @@ export async function localInstallStatus(
return body as LocalInstallProgress;
}
+/** One curated model a local server can download, annotated for THIS machine. */
+export interface PullableModel {
+ id: string;
+ label: string;
+ size_gb: number;
+ purpose: string;
+ tools: boolean;
+ vision: boolean;
+ installed: boolean;
+ /** "comfortable" | "tight" | "unknown" — advisory, never a block. */
+ fit: string;
+ fit_note: string;
+}
+
+export interface PullableModels {
+ server: string;
+ server_reachable: boolean;
+ message: string;
+ memory_gb: number | null;
+ models: PullableModel[];
+ installed: string[];
+}
+
+/** Progress of ONE model download on the local server. */
+export interface ModelPullProgress {
+ state: "idle" | "running" | "done" | "error";
+ model: string;
+ message: string;
+ installed?: boolean;
+ completed?: number;
+ total?: number;
+ percent?: number;
+ already?: boolean;
+}
+
+/** The curated shortlist plus what this machine already holds. */
+export async function pullableModels(
+ providerId: string,
+): Promise<PullableModels> {
+ const res = await fetch(
+ `/api/providers/${encodeURIComponent(providerId)}/pullable-models`,
+ );
+ const body = await res.json().catch(() => ({}));
+ if (!res.ok) {
+ throw new Error(body.detail ?? `HTTP ${res.status}`);
+ }
+ return body as PullableModels;
+}
+
+/**
+ * Start downloading `model` into the local server. Returns as soon as the pull
+ * is running — a multi-gigabyte download takes minutes, so the caller polls
+ * `modelPullStatus` instead of awaiting it.
+ */
+export async function startModelPull(
+ providerId: string,
+ model: string,
+): Promise<ModelPullProgress> {
+ const res = await fetch(
+ `/api/providers/${encodeURIComponent(providerId)}/pull`,
+ {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ model }),
+ },
+ );
+ const body = await res.json().catch(() => ({}));
+ if (!res.ok) {
+ throw new Error(body.detail ?? `HTTP ${res.status}`);
+ }
+ return body as ModelPullProgress;
+}
+
+/** Poll one download; `installed` reflects the server's inventory, not the run. */
+export async function modelPullStatus(
+ providerId: string,
+ model: string,
+): Promise<ModelPullProgress> {
+ const res = await fetch(
+ `/api/providers/${encodeURIComponent(providerId)}/pull/status?model=${encodeURIComponent(model)}`,
+ );
+ const body = await res.json().catch(() => ({}));
+ if (!res.ok) {
+ throw new Error(body.detail ?? `HTTP ${res.status}`);
+ }
+ return body as ModelPullProgress;
+}
+
export async function switchSttProvider(
providerId: string,
): Promise<PipelineSwitchResult> {
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/de.json b/jarvis/ui/web/frontend/src/i18n/locales/de.json
index 9e090f24fc..4e3950d8b1 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/de.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/de.json
@@ -1299,6 +1299,14 @@
"hint_default": "Leer lassen, um die oben gezeigte Standard-Adresse zu verwenden.",
"hint_required": "Dieser Anbieter braucht eine Server-URL — trage ein, wo dein lokaler Server läuft."
},
+ "apikeys_model_pull": {
+ "title": "Modelle auf diesem Rechner",
+ "memory": "{0} GB RAM",
+ "size": "~{0} GB",
+ "installed": "Installiert",
+ "download": "Laden",
+ "custom_placeholder": "Beliebiger Modellname, z. B. mistral"
+ },
"apikeys_model": {
"heading": "Modell",
"recommended_tag": "Empfohlen",
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/en.json b/jarvis/ui/web/frontend/src/i18n/locales/en.json
index 4b6fd3d2cd..21cc119bf8 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/en.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/en.json
@@ -1299,6 +1299,14 @@
"hint_default": "Leave empty to use the default address shown above.",
"hint_required": "This provider needs a server URL — enter where your local server runs."
},
+ "apikeys_model_pull": {
+ "title": "Models on this machine",
+ "memory": "{0} GB RAM",
+ "size": "~{0} GB",
+ "installed": "Installed",
+ "download": "Download",
+ "custom_placeholder": "Any model name, e.g. mistral"
+ },
"apikeys_model": {
"heading": "Model",
"recommended_tag": "Recommended",
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/es.json b/jarvis/ui/web/frontend/src/i18n/locales/es.json
index 3f6a294014..5f8e638044 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/es.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/es.json
@@ -1299,6 +1299,14 @@
"hint_default": "Déjalo vacío para usar la dirección predeterminada mostrada arriba.",
"hint_required": "Este proveedor necesita una URL de servidor: indica dónde se ejecuta tu servidor local."
},
+ "apikeys_model_pull": {
+ "title": "Modelos en este equipo",
+ "memory": "{0} GB de RAM",
+ "size": "~{0} GB",
+ "installed": "Instalado",
+ "download": "Descargar",
+ "custom_placeholder": "Cualquier nombre de modelo, p. ej. mistral"
+ },
"apikeys_model": {
"heading": "Modelo",
"recommended_tag": "Recomendado",
diff --git a/jarvis/ui/web/provider_routes.py b/jarvis/ui/web/provider_routes.py
index b585eafffd..53e47e462d 100644
--- a/jarvis/ui/web/provider_routes.py
+++ b/jarvis/ui/web/provider_routes.py
@@ -197,6 +197,13 @@ class BrainModelSaveResponse(BaseModel):
probe: BrainModelProbe | None = None
+# Local model downloads: the name to pull into the user's own server. Free-form
+# on purpose — the curated shortlist is a starting point, and the Ollama library
+# holds far more than any list here could track.
+class PullModelBody(BaseModel):
+ model: str = Field(default="", max_length=200)
+
+
# Phase 3: selectable Computer-Use model per provider. CU runs on the provider's
# main ``model`` by default; a pinned ``cu_model`` lets the user run CU on a
# different (e.g. stronger) model than chat. ``cu_model == ""`` means "use my
@@ -419,6 +426,21 @@ def _installed_local_models(provider_id: str, models: list[Any]) -> list[Any]:
return kept
+def _pull_capable_ids() -> frozenset[str]:
+ """Provider ids whose server has a native model-download API.
+
+ Lazy + defensive: the provider list must render even if the pull module
+ cannot be imported on this install.
+ """
+ try:
+ from jarvis.brain.ollama_pull import PULL_CAPABLE_PROVIDERS
+
+ return PULL_CAPABLE_PROVIDERS
+ except Exception as exc: # noqa: BLE001 — the provider list must never 500
+ log.debug("Pull-capability lookup failed (%s); no card offers downloads.", exc)
+ return frozenset()
+
+
def _spec_to_payload(
spec: ProviderSpec,
*,
@@ -546,6 +568,10 @@ def _spec_to_payload(
"supports_base_url": spec.supports_base_url,
"default_base_url": spec.default_base_url,
"base_url": _stored_base_url(spec),
+ # Whether this card's server can be TOLD to fetch a model
+ # (POST /providers/{id}/pull). A capability flag, so the UI renders the
+ # download panel without knowing a provider name (AP-21).
+ "supports_model_pull": spec.id in _pull_capable_ids(),
# Maintainer-recommended pick for this tier (UI badge) + the model it
# points at. Presentation only — never gates behavior (AP-21).
"recommended": spec.recommended,
@@ -2547,6 +2573,71 @@ async def get_local_install_status(provider_id: str) -> dict[str, Any]:
return result
+def _require_pull_capable(provider_id: str) -> None:
+ """404 for an unknown card, 400 for one whose server cannot be told to pull.
+
+ Not a preference: a generic OpenAI-compatible server has no standard "fetch
+ this model" call, so the honest answer is that this card cannot download for
+ you — never a silent no-op.
+ """
+ if get_spec(provider_id) is None:
+ raise HTTPException(status_code=404, detail=f"Unknown provider: {provider_id}")
+ from jarvis.brain.ollama_pull import PULL_CAPABLE_PROVIDERS
+
+ if provider_id not in PULL_CAPABLE_PROVIDERS:
+ raise HTTPException(
+ status_code=400,
+ detail=(
+ f"'{provider_id}' has no download API — load the model in the "
+ "server itself, then it appears in the model picker."
+ ),
+ )
+
+
[email protected]("/providers/{provider_id}/pullable-models")
+async def list_pullable_models(provider_id: str) -> dict[str, Any]:
+ """Curated local models to download, annotated for THIS machine.
+
+ Answers the question a keyless install actually has — "which model should I
+ get, and will it run here?" — with the shortlist, each entry's approximate
+ size, whether it is already installed, and a memory verdict from the host's
+ own RAM. Advisory, never a block: Ollama offloads to GPU memory this probe
+ cannot see.
+ """
+ _require_pull_capable(provider_id)
+ from jarvis.brain.ollama_pull import recommendations
+
+ return await recommendations()
+
+
[email protected]("/providers/{provider_id}/pull")
+async def start_model_pull(provider_id: str, body: PullModelBody) -> dict[str, Any]:
+ """Download a model into the local server (§3: recoverable in-app).
+
+ Any name the library knows may be pulled, not only the curated ones. Returns
+ immediately with a ``state`` the UI polls — a synchronous route would hold
+ the request open for the length of a multi-gigabyte download — and a second
+ call while a pull is in flight joins it instead of duplicating it.
+ """
+ _require_pull_capable(provider_id)
+ from jarvis.brain.ollama_pull import start_pull
+
+ return await start_pull(body.model)
+
+
[email protected]("/providers/{provider_id}/pull/status")
+async def get_model_pull_status(provider_id: str, model: str) -> dict[str, Any]:
+ """Progress of one model download, checked against the server's inventory.
+
+ The inventory wins over this process's own bookkeeping: a model pulled from
+ the CLI or a previous app run reads as installed rather than "idle".
+ """
+ _require_pull_capable(provider_id)
+ from jarvis.brain.ollama_pull import pull_status
+
+ return await pull_status(model)
+
+
@router.get("/providers/{provider_id}/cu-model")
async def get_cu_model(provider_id: str, request: Request) -> CuModelResponse:
"""Return the per-provider Computer-Use model selection (Phase 3).
diff --git a/tests/integration/test_provider_routes.py b/tests/integration/test_provider_routes.py
index 8e857e3652..0c801cdd19 100644
--- a/tests/integration/test_provider_routes.py
+++ b/tests/integration/test_provider_routes.py
@@ -905,3 +905,83 @@ def test_login_status_logged_in_false_when_creds_missing(
with TestClient(server_with_brain.app) as client:
resp = client.get("/api/providers/openclaw/login/status")
assert resp.status_code == 404
+
+
+# ----------------------------------------------------------------------
+# /api/providers/{pid}/pullable-models + /pull (in-app local downloads)
+# ----------------------------------------------------------------------
+
+
+def fake_pull(monkeypatch: pytest.MonkeyPatch) -> dict[str, Any]:
+ """Stub the pull module so the routes never touch a real Ollama server."""
+ from jarvis.brain import ollama_pull
+
+ calls: dict[str, Any] = {"started": [], "status": []}
+
+ async def _recommendations() -> dict[str, Any]:
+ return {
+ "server": "http://localhost:11434",
+ "server_reachable": True,
+ "message": "",
+ "memory_gb": 32.0,
+ "models": [{"id": "qwen3-vl", "installed": False, "fit": "comfortable"}],
+ "installed": [],
+ }
+
+ async def _start_pull(model: str) -> dict[str, Any]:
+ calls["started"].append(model)
+ return {"state": "running", "model": model, "message": "Starting…"}
+
+ async def _pull_status(model: str) -> dict[str, Any]:
+ calls["status"].append(model)
+ return {"state": "running", "model": model, "percent": 12.5}
+
+ monkeypatch.setattr(ollama_pull, "recommendations", _recommendations)
+ monkeypatch.setattr(ollama_pull, "start_pull", _start_pull)
+ monkeypatch.setattr(ollama_pull, "pull_status", _pull_status)
+ return calls
+
+
+def test_pullable_models_lists_the_shortlist(
+ server_with_brain: WebServer, fake_pull: dict[str, Any]
+) -> None:
+ with TestClient(server_with_brain.app) as client:
+ resp = client.get("/api/providers/ollama/pullable-models")
+ assert resp.status_code == 200
+ body = resp.json()
+ assert body["server_reachable"] is True
+ assert body["models"][0]["id"] == "qwen3-vl"
+
+
+def test_pull_starts_a_download_and_reports_progress(
+ server_with_brain: WebServer, fake_pull: dict[str, Any]
+) -> None:
+ with TestClient(server_with_brain.app) as client:
+ started = client.post("/api/providers/ollama/pull", json={"model": "qwen3-vl"})
+ assert started.status_code == 200
+ assert started.json()["state"] == "running"
+ status = client.get("/api/providers/ollama/pull/status", params={"model": "qwen3-vl"})
+ assert status.status_code == 200
+ assert status.json()["percent"] == 12.5
+ assert fake_pull["started"] == ["qwen3-vl"]
+
+
+def test_pull_rejects_a_provider_whose_server_cannot_be_told_to_fetch(
+ server_with_brain: WebServer, fake_pull: dict[str, Any]
+) -> None:
+ """A generic OpenAI-compatible server has no download API — the honest
+ answer is 400 with the reason, never a silent no-op."""
+ with TestClient(server_with_brain.app) as client:
+ resp = client.post("/api/providers/local-openai/pull", json={"model": "x"})
+ assert resp.status_code == 400
+ assert "no download API" in resp.json()["detail"]
+ assert fake_pull["started"] == []
+
+
+def test_pull_on_an_unknown_provider_is_404(
+ server_with_brain: WebServer, fake_pull: dict[str, Any]
+) -> None:
+ with TestClient(server_with_brain.app) as client:
+ resp = client.get("/api/providers/nope/pullable-models")
+ assert resp.status_code == 404
diff --git a/tests/unit/brain/test_ollama_pull.py b/tests/unit/brain/test_ollama_pull.py
new file mode 100644
index 0000000000..c2b5a375c3
--- /dev/null
+++ b/tests/unit/brain/test_ollama_pull.py
@@ -0,0 +1,292 @@
+"""In-app Ollama model downloads: honest fit verdicts, honest progress.
+
+The point of this module is §3's "recoverable in-app" contract: a keyless
+install whose server holds no models used to dead-end at "run: ollama pull …",
+a terminal instruction in an app with no terminal. These tests pin the parts
+that would silently lie if they broke — a model reported ready that the server
+does not list, a fit verdict invented from an unreadable memory probe, a
+duplicate multi-gigabyte download.
+"""
+
+from __future__ import annotations
+
+import asyncio
+from typing import Any
+
+import httpx
+import pytest
+
+import jarvis.brain.ollama_pull as pull
+import jarvis.core.config as cfg
+from jarvis.core.config import JarvisConfig
+
+
[email protected](autouse=True)
+def _clean_runs(monkeypatch):
+ """No ambient config, no OLLAMA_HOST, no leftover runs between tests."""
+ monkeypatch.setattr(cfg, "load_config", lambda: JarvisConfig())
+ monkeypatch.delenv("OLLAMA_HOST", raising=False)
+ pull._runs.clear()
+ yield
+ pull._runs.clear()
+
+
+# ── Fit verdict ──────────────────────────────────────────────────────────
+def test_fit_is_comfortable_with_headroom() -> None:
+ verdict, note = pull.fit_verdict(5.2, 32.0)
+ assert verdict == "comfortable"
+ assert "32" in note
+
+
+def test_fit_is_tight_but_never_forbidden() -> None:
+ """A GPU box runs models the RAM rule calls tight — the verdict informs the
+ choice, it does not forbid it."""
+ verdict, note = pull.fit_verdict(18.0, 16.0)
+ assert verdict == "tight"
+ assert "will" in note.lower()
+
+
+def test_fit_is_unknown_when_memory_cannot_be_read() -> None:
+ """An unreadable host must not produce an invented number that would make a
+ 9 GB model look safe on a 4 GB box."""
+ verdict, _note = pull.fit_verdict(9.0, None)
+ assert verdict == "unknown"
+
+
+def test_total_memory_survives_a_broken_probe(monkeypatch) -> None:
+ import psutil
+
+ def _boom() -> None:
+ raise OSError("no /proc")
+
+ monkeypatch.setattr(psutil, "virtual_memory", _boom)
+ assert pull.total_memory_gb() is None
+
+
+# ── Installed-model bookkeeping ──────────────────────────────────────────
+ ("model", "installed", "expected"),
+ [
+ ("qwen3.5:4b", {"qwen3.5:4b"}, True),
+ # ``ollama pull qwen3.5`` installs qwen3.5:latest — a literal compare
+ # would offer a pull the user already completed.
+ ("qwen3.5", {"qwen3.5:latest"}, True),
+ ("qwen3.5", {"qwen3.5:4b"}, False),
+ ("qwen3-vl", set(), False),
+ ],
+)
+def test_installed_matching_understands_the_latest_tag(
+ model: str, installed: set[str], expected: bool
+) -> None:
+ assert pull._is_installed(model, installed) is expected
+
+
+class _FakeTagsClient:
+ payload: dict[str, Any] = {}
+ fail: bool = False
+
+ def __init__(self, **kwargs: Any) -> None:
+ pass
+
+ async def __aenter__(self) -> _FakeTagsClient:
+ return self
+
+ async def __aexit__(self, *exc: Any) -> None:
+ return None
+
+ async def get(self, url: str) -> Any:
+ if _FakeTagsClient.fail:
+ raise httpx.ConnectError("connection refused")
+
+ class _Resp:
+ @staticmethod
+ def raise_for_status() -> None:
+ return None
+
+ @staticmethod
+ def json() -> dict[str, Any]:
+ return _FakeTagsClient.payload
+
+ return _Resp()
+
+
+def fake_tags(monkeypatch):
+ monkeypatch.setattr(httpx, "AsyncClient", _FakeTagsClient)
+ _FakeTagsClient.fail = False
+ _FakeTagsClient.payload = {}
+ return _FakeTagsClient
+
+
+async def test_installed_models_excludes_cloud_references(fake_tags) -> None:
+ """``:cloud`` entries are ollama.com-proxied, not local weights — the same
+ rule the brain applies when it picks a model."""
+ fake_tags.payload = {
+ "models": [
+ {"name": "qwen3.5:latest"},
+ {"name": "kimi-k2.5:cloud"},
+ {"name": "other", "remote": True},
+ ]
+ }
+ installed, error = await pull.installed_models()
+ assert installed == {"qwen3.5:latest"}
+ assert error is None
+
+
+async def test_unreachable_server_reports_a_sentence_not_an_empty_list(fake_tags) -> None:
+ """An empty list would read as "you have nothing installed" — which is a
+ different problem with a different fix."""
+ fake_tags.fail = True
+ installed, error = await pull.installed_models()
+ assert installed == set()
+ assert error and "ollama.com/download" in error
+
+
+async def test_recommendations_mark_what_is_already_there(fake_tags) -> None:
+ fake_tags.payload = {"models": [{"name": "qwen3.5:latest"}]}
+ result = await pull.recommendations()
+ by_id = {m["id"]: m for m in result["models"]}
+ assert by_id["qwen3.5"]["installed"] is True
+ assert by_id["qwen3-vl"]["installed"] is False
+ # The vision entry must be findable AS the vision entry — it is the one
+ # that makes Screen Context work on a local-only install.
+ assert by_id["qwen3-vl"]["vision"] is True
+ assert result["server_reachable"] is True
+
+
+async def test_recommendations_stay_usable_when_the_server_is_down(fake_tags) -> None:
+ fake_tags.fail = True
+ result = await pull.recommendations()
+ assert result["server_reachable"] is False
+ assert result["message"]
+ assert [m["id"] for m in result["models"]], "the shortlist is still worth showing"
+
+
+# ── Pull lifecycle ───────────────────────────────────────────────────────
+async def test_pull_of_an_installed_model_is_a_no_op(fake_tags) -> None:
+ fake_tags.payload = {"models": [{"name": "qwen3.5:latest"}]}
+ result = await pull.start_pull("qwen3.5")
+ assert result["state"] == "done"
+ assert result["already"] is True
+
+
+async def test_second_pull_joins_the_running_one(fake_tags, monkeypatch) -> None:
+ """A duplicate multi-gigabyte download is the one mistake this route must
+ never make."""
+ fake_tags.payload = {"models": []}
+ started: list[str] = []
+
+ async def _never_finishes(model: str) -> None:
+ started.append(model)
+ await asyncio.Event().wait()
+
+ monkeypatch.setattr(pull, "_run_pull", _never_finishes)
+ first = await pull.start_pull("qwen3-vl")
+ second = await pull.start_pull("qwen3-vl")
+ assert first["state"] == "running"
+ assert second["state"] == "running"
+ await asyncio.sleep(0)
+ assert started == ["qwen3-vl"]
+ run = pull._run_for("qwen3-vl")
+ assert run.task is not None
+ run.task.cancel()
+
+
+async def test_empty_model_name_is_rejected() -> None:
+ result = await pull.start_pull(" ")
+ assert result["state"] == "error"
+
+
+async def test_status_trusts_the_server_over_local_bookkeeping(fake_tags) -> None:
+ """A model pulled from the CLI or a previous app run reads as installed,
+ not as "idle"."""
+ fake_tags.payload = {"models": [{"name": "qwen3-vl:latest"}]}
+ status = await pull.pull_status("qwen3-vl")
+ assert status["state"] == "done"
+ assert status["installed"] is True
+ assert status["percent"] == 100.0
+
+
+async def test_status_reports_real_progress(fake_tags) -> None:
+ fake_tags.payload = {"models": []}
+ run = pull._run_for("qwen3-vl")
+ run.state = "running"
+ run.completed = 250
+ run.total = 1000
+ status = await pull.pull_status("qwen3-vl")
+ assert status["state"] == "running"
+ assert status["percent"] == 25.0
+
+
+class _FakeStream:
+ """Minimal ``client.stream`` context manager over canned NDJSON lines."""
+
+ def __init__(self, lines: list[str], status_code: int = 200) -> None:
+ self._lines = lines
+ self.status_code = status_code
+
+ async def __aenter__(self) -> _FakeStream:
+ return self
+
+ async def __aexit__(self, *exc: Any) -> None:
+ return None
+
+ def raise_for_status(self) -> None:
+ if self.status_code >= 400:
+ raise httpx.HTTPStatusError("boom", request=None, response=None) # type: ignore[arg-type]
+
+ async def aiter_lines(self):
+ for line in self._lines:
+ yield line
+
+
+def _streaming_client(stream: _FakeStream, tags_payload: dict[str, Any]) -> type:
+ class _Client(_FakeTagsClient):
+ def stream(self, method: str, url: str, **kwargs: Any) -> _FakeStream:
+ assert url.endswith("/api/pull")
+ return stream
+
+ _FakeTagsClient.payload = tags_payload
+ return _Client
+
+
+async def test_finished_pull_is_verified_against_the_inventory(monkeypatch) -> None:
+ """A pull can end cleanly and still leave nothing usable; "ready" over a
+ missing model is exactly the lie this check exists to prevent."""
+ stream = _FakeStream(['{"status":"pulling"}', '{"status":"success"}'])
+ monkeypatch.setattr(httpx, "AsyncClient", _streaming_client(stream, {"models": []}))
+ await pull._run_pull("qwen3-vl")
+ run = pull._run_for("qwen3-vl")
+ assert run.state == "error"
+ assert "not listed" in run.message
+
+
+async def test_successful_pull_reports_ready(monkeypatch) -> None:
+ stream = _FakeStream(
+ ['{"status":"pulling","completed":50,"total":100}', '{"status":"success"}']
+ )
+ monkeypatch.setattr(
+ httpx, "AsyncClient", _streaming_client(stream, {"models": [{"name": "qwen3-vl:latest"}]})
+ )
+ await pull._run_pull("qwen3-vl")
+ run = pull._run_for("qwen3-vl")
+ assert run.state == "done"
+ assert "ready" in run.message
+
+
+async def test_unknown_model_name_points_at_the_library(monkeypatch) -> None:
+ stream = _FakeStream([], status_code=404)
+ monkeypatch.setattr(httpx, "AsyncClient", _streaming_client(stream, {"models": []}))
+ await pull._run_pull("no-such-model")
+ run = pull._run_for("no-such-model")
+ assert run.state == "error"
+ assert "ollama.com/library" in run.message
+
+
+async def test_stream_error_line_becomes_an_error_state(monkeypatch) -> None:
+ stream = _FakeStream(['{"error":"file does not exist"}'])
+ monkeypatch.setattr(httpx, "AsyncClient", _streaming_client(stream, {"models": []}))
+ await pull._run_pull("qwen3-vl")
+ run = pull._run_for("qwen3-vl")
+ assert run.state == "error"
+ assert "file does not exist" in run.message