Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
fix(local-models): an offline sweep no longer poisons the cache, and every job keeps a picker
rubenluetke10-beepdde30c43e18b
diff --git a/docs/BUGS.md b/docs/BUGS.mdindex 4cf2c19522..f97b193070 100644--- a/docs/BUGS.md+++ b/docs/BUGS.md@@ -13124,3 +13124,75 @@ only what is true in it.about the OUTCOME. Every tool that acts without being able to look owes themodel the difference in a field it cannot miss — a note in prose is a caveatthe model will politely paraphrase after the good news.+## BUG-188: Local models says every model is "not installed" and a job cannot be changed — one sweep taken while Ollama was still booting became the cache both ends read from (HIGH, FIXED 2026-08-27)++**Symptom (maintainer, 2026-08-27 10:09).** The Local models section showed+`ornith:9b` with a trailing `(not installed)`, and under it the sentence+"Nothing installed fits this job yet; this download is the pick." Picking a+different model in the dropdown appeared to do nothing — "it always switches+back to that odd one, even when you choose something else." Fifteen models+were on the server at that moment, `ornith:9b` among them.++**What was actually true.** Nothing was broken in the write path. Read live+during the investigation, the backend was correct on every count:++```+GET …/local-models/overview?fresh=1 source: live+ inventory error: None models: 11+ chat current='ornith:9b' installed=True qualifying=[10 tags]+PUT …/local-models/roles/chat {"model":"qwen3.5:4b"} -> ok+ jarvis.toml brain.providers.ollama.model = "qwen3.5:4b"+ scripts/config-soll.json brain.providers.ollama.model = "qwen3.5:4b"+```++The pick was written, the drift baseline followed it, and a re-read answered+the new value. The screen was simply not showing the server.++**Cause — a truthful answer cached as a lasting one.** `build_overview` runs+its sweep whatever the server's state; when Ollama does not answer it returns+a payload with an empty inventory and `inventory.error` set. That is the right+answer to "what can I see right now" and a ruinous one to keep, and it was+kept twice over:++* `ollama_overview._refresh` handed every payload to `save_snapshot`, so the+ offline sweep replaced the good file in `data/local_models_snapshot.json`.+ `get_overview` paints a disk snapshot for `STALE_AFTER_S` — 24 hours.+* `useOverview` mirrored every payload into `localStorage`, and reads it back+ as react-query's `initialData` — which survives a failed refetch, so it+ outlives the outage that produced it.++Opening the section while Ollama is still booting is enough. Everything+downstream then follows from an empty inventory: `RoleState.qualifying` is+empty, so each role reads `installed: false` and its shortlist falls back to+"nothing installed fits this job yet".++**Why the dropdown looked stuck.** `RoleLedgerRow` built its options from+`row.qualifying` plus the configured tag. With `qualifying` empty that list+holds exactly ONE entry — the tag already configured. There was nothing else+to select; the "reset" the maintainer saw was a picker that had never offered+an alternative. An unprobed download (`probed: false`, no capabilities) fell+out of the list the same silent way. The Simple page compounded it: the+picker lived behind a "Change" button, two clicks from the row.++**Fix.**++1. `ollama_overview.is_paintable()` — a payload whose inventory carries an+ error is never written to the snapshot, and one already on disk is dropped+ on read instead of painted. The previous, honest snapshot stays.+2. `localModelsSnapshot.isPaintable()` — the same guard on the browser side,+ on both write and read.+3. `RolePicker` offers EVERY installed download, grouped "Fits this job" /+ "Other installed models", so there is always something to pick and an+ unprobed model is visible rather than dropped.+4. The picker is on screen for every job at every detail level; `advanced`+ adds capability badges, Tune and the read-only jobs, it never removes a+ control.+5. A "Refresh" button in the section header clears the painted snapshot and+ every cached answer, then reads the server again — the recovery a user can+ reach without knowing what a cache is.++**Lesson.** A cache entry is a claim that outlives the moment it was taken.+"The server did not answer" is true when measured and false ten seconds+later, so it may be returned but never stored. And a control whose options+come from a filtered list needs an answer for the empty case: offering one+option is indistinguishable, to the person using it, from ignoring the click.diff --git a/jarvis/brain/ollama_overview.py b/jarvis/brain/ollama_overview.pyindex 7bc5f443f1..260d4a2c84 100644--- a/jarvis/brain/ollama_overview.py+++ b/jarvis/brain/ollama_overview.py@@ -53,6 +53,7 @@ __all__ = ["forget","get_overview","inventory_payload",+ "is_paintable","load_snapshot","model_row","role_row",@@ -325,13 +326,40 @@ def load_snapshot(path: Path | None = None) -> dict[str, Any] | None:return data+def is_paintable(payload: dict[str, Any]) -> bool:+ """Whether ``payload`` may be cached as the next open's head start.++ A sweep taken while the server was unreachable — Ollama still booting,+ a stopped service, a remote host off the network — is a truthful answer+ to "what can I see right now", but a ruinous thing to paint later: its+ inventory is empty, so every role reads "not installed", every shortlist+ reads "nothing installed fits this job yet", and each role's picker+ offers only the tag already configured. Keeping the previous, honest+ snapshot instead means the next open paints stale facts rather than a+ machine that looks wiped (BUG-188).++ Only that one condition disqualifies a payload: this is a guard against a+ known lie, not a schema check, so anything else is cached as before.+ """+ inv = payload.get("inventory")+ return not (isinstance(inv, dict) and inv.get("error"))++def save_snapshot(root: str, payload: dict[str, Any], path: Path | None = None) -> None:"""Persist ``payload`` atomically (``.part`` + ``os.replace``).A crash mid-write leaves the previous snapshot intact; a write failureis logged and swallowed on purpose — the overview was already answered- live, the cache is only the next open's head start.+ live, the cache is only the next open's head start. A payload that fails+ :func:`is_paintable` is not written at all."""+ if not is_paintable(payload):+ log.info(+ "local-models: not caching the overview for %s — the server was "+ "unreachable, so its inventory is empty; the previous snapshot stays",+ root,+ )+ returntarget = path or snapshot_path()part = target.with_suffix(target.suffix + ".part")data = {"root": root, "fetched_at": float(payload.get("fetched_at") or time.time())}@@ -351,6 +379,9 @@ def save_snapshot(root: str, payload: dict[str, Any], path: Path | None = None)# ── Stale-while-revalidate ───────────────────────────────────────────────_memo: dict[str, tuple[float, dict[str, Any]]] = {} # root -> (monotonic, payload)+#: Roots whose memo was dropped by a write and whose disk snapshot is+#: therefore known-stale: the next open builds live instead of painting it.+_dirty: set[str] = set()#: The one background refresh per root; the reference is kept so the task#: cannot be garbage-collected mid-flight, and a second open joins it._refresh_tasks: dict[str, asyncio.Task[dict[str, Any]]] = {}@@ -360,6 +391,7 @@ def _reset_for_tests() -> None:"""Drop the in-memory overview memo and refresh bookkeeping (tests only)."""_memo.clear()_refresh_tasks.clear()+ _dirty.clear()def forget(root: str) -> None:@@ -368,10 +400,13 @@ def forget(root: str) -> None:A role pick, a tune, an unload or a delete changes what the next openmust show; without this the memo answered the OLD payload for up to:data:`DEFAULT_MAX_AGE_S` after the write and the row the user had just- changed stayed where it was. The disk snapshot is left alone — the next- live build overwrites it.+ changed stayed where it was. The disk snapshot is known-stale from here+ on too, so the next plain read builds live rather than painting it —+ every client sees the write, not only one that asks for ``fresh``."""- _memo.pop(normalize_server_root(root), None)+ key = normalize_server_root(root)+ _memo.pop(key, None)+ _dirty.add(key)def _fresh(root: str, max_age_s: float) -> dict[str, Any] | None:@@ -385,6 +420,7 @@ async def _refresh(root: str, cfg: Any, provider_id: str) -> dict[str, Any]:"""Build live, memoise, save to disk (off-loop); returns the payload."""payload = await build_overview(root, cfg, provider_id=provider_id)_memo[root] = (time.monotonic(), payload)+ _dirty.discard(root)await asyncio.to_thread(save_snapshot, root, payload)return payload@@ -431,12 +467,22 @@ async def get_overview("""root = normalize_server_root(root)disk: dict[str, Any] | None = None- if not fresh:+ # After a write (`forget`) both the memo and the disk snapshot are known+ # stale, so a plain read goes straight to the live build as well.+ if not fresh and root not in _dirty:if (hit := _fresh(root, max_age_s)) is not None:return hit, "live"disk = await asyncio.to_thread(load_snapshot)if disk is not None and disk.get("root") != root:disk = None+ # A snapshot written before `is_paintable` existed can still hold an+ # offline sweep; painting it would show an empty machine for up to+ # STALE_AFTER_S. Build live instead and let that answer replace it.+ if disk is not None and not is_paintable(disk["payload"]):+ log.info(+ "local-models: the saved overview for %s is an offline sweep; rebuilding", root+ )+ disk = Noneif disk is not None and time.time() - float(disk["fetched_at"]) < STALE_AFTER_S:_schedule_refresh(root, cfg, provider_id)return dict(disk["payload"]), "cache"diff --git a/jarvis/ui/web/frontend/src/hooks/useLocalModels.ts b/jarvis/ui/web/frontend/src/hooks/useLocalModels.tsindex 0035186545..9785a6fced 100644--- a/jarvis/ui/web/frontend/src/hooks/useLocalModels.ts+++ b/jarvis/ui/web/frontend/src/hooks/useLocalModels.ts@@ -19,6 +19,7 @@ import {import { useEffect, useMemo } from "react";import {+ clearOverviewSnapshot,readOverviewSnapshot,writeOverviewSnapshot,} from "../lib/localModelsSnapshot";@@ -1081,22 +1082,57 @@ export function useEnvGuide(providerId: string | undefined, os?: EnvGuideOs) {* next poll. `?fresh=1` skips the cache; the answer replaces the cached* payload under the same key, so every panel repaints from it.*/-export function refetchOverviewFresh(+export async function refetchOverviewFresh(qc: QueryClient,providerId: string,): Promise<OverviewResponse | undefined> {- return qc- .fetchQuery({- queryKey: localModelsKeys.overview(providerId),+ const queryKey = localModelsKeys.overview(providerId);+ try {+ // A poll may be in flight with the cache-first answer; `fetchQuery`+ // would join it instead of running the fresh read and the stale payload+ // would land AFTER the write. Cancel it first, then read live.+ await qc.cancelQueries({ queryKey });+ return await qc.fetchQuery({+ queryKey,queryFn: () => getOverview(providerId, true),staleTime: 0,- })- .catch((err: unknown) => {- // The write already landed; a failed re-read only delays the repaint- // until the next poll, so it is logged rather than surfaced.- console.warn("[local-models] fresh overview failed", err);- return undefined;});+ } catch (err) {+ // The write already landed; a failed re-read only delays the repaint+ // until the next poll, so it is logged rather than surfaced.+ console.warn("[local-models] fresh overview failed", err);+ return undefined;+ }+}++/** "qwen3.5" and "qwen3.5:latest" are the same download. */+export function canonicalModelName(name: string): string {+ return name.endsWith(":latest") ? name.slice(0, -":latest".length) : name;+}++/**+ * The overview as it will read once `role` is on `model` — the optimistic+ * shape a pick shows while the write and the fresh read are underway.+ */+export function withRolePick(+ overview: OverviewResponse,+ role: LocalModelRole,+ model: string,+): OverviewResponse {+ const installed =+ model !== "" &&+ overview.inventory.models.some(+ (m) => canonicalModelName(m.name) === canonicalModelName(model),+ );+ return {+ ...overview,+ roles: {+ ...overview.roles,+ roles: overview.roles.roles.map((r) =>+ r.id === role ? { ...r, current: model, installed } : r,+ ),+ },+ };}export function useInvalidateLocalModels(providerId: string | undefined) {@@ -1114,13 +1150,51 @@ export function useInvalidateLocalModels(providerId: string | undefined) {};}+/**+ * Throw away everything the section has cached and read it again from the+ * server — the "Refresh" button behind the section header.+ *+ * `useInvalidateLocalModels` refetches, but it cannot help against the one+ * state a user actually gets stuck in: a painted snapshot taken while the+ * server was silent. That snapshot is `initialData`, so it survives a+ * refetch failure and keeps a wiped-looking machine on screen. Clearing it+ * first makes the button mean what it says (BUG-188).+ */+export function useReloadLocalModels(providerId: string | undefined) {+ const qc = useQueryClient();+ return async () => {+ const id = providerId ?? "";+ if (!id) return;+ clearOverviewSnapshot(id);+ await qc.cancelQueries({ queryKey: ["local-models", id] });+ qc.removeQueries({ queryKey: ["local-models", id] });+ await refetchOverviewFresh(qc, id);+ };+}+export function useSetRole(providerId: string | undefined) {const qc = useQueryClient();+ const id = providerId ?? "";+ const overviewKey = localModelsKeys.overview(id);return useMutation({mutationFn: ({ role, model }: { role: LocalModelRole; model: string }) =>setRole(providerId as string, role, model),- onSuccess: () => {- const id = providerId ?? "";+ // The picker is a controlled input bound to the overview. Without this+ // it snapped back to the OLD model the instant a pick was made and+ // stayed there until the fresh read landed (one to three seconds on a+ // live build) — which reads as "my pick was thrown away". The cache+ // shows the pick at once; a refused write rolls it back.+ onMutate: async ({ role, model }) => {+ await qc.cancelQueries({ queryKey: overviewKey });+ const previous = qc.getQueryData<OverviewResponse>(overviewKey);+ if (previous)+ qc.setQueryData(overviewKey, withRolePick(previous, role, model));+ return { previous };+ },+ onError: (_err, _vars, context) => {+ if (context?.previous) qc.setQueryData(overviewKey, context.previous);+ },+ onSettled: () => {void qc.invalidateQueries({ queryKey: localModelsKeys.roles(id) });void qc.invalidateQueries({ queryKey: localModelsKeys.inventory(id) });void refetchOverviewFresh(qc, id);diff --git a/jarvis/ui/web/frontend/src/i18n/locales/local_models/de.json b/jarvis/ui/web/frontend/src/i18n/locales/local_models/de.jsonindex 264c5579b6..581b702d10 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/local_models/de.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/local_models/de.json@@ -6,6 +6,7 @@"mode_label": "Detailgrad","mode_simple": "Einfach","mode_advanced": "Erweitert",+ "reload": "Aktualisieren","tabs_label": "Bereiche der lokalen Modelle","tab_overview": "Überblick","tab_models": "Modelle",@@ -196,11 +197,20 @@"status_gpu_unknown": "Grafikspeicher unbekannt","status_brain_other": "{server} ist nicht dein aktives Gehirn ({brain} antwortet)","status_brain_active": "{server} ist dein aktives Gehirn",- "actions_label": "Nächste Schritte",+ "step_server_title": "Server",+ "step_server_subtitle": "Das Programm, das die Modelle auf diesem Rechner ausführt.",+ "step_models_title": "Modelle",+ "step_models_subtitle": "Die Downloads auf dem Server. Jeder Job wählt aus diesen aus.",+ "step_jobs_title": "Jobs",+ "step_jobs_subtitle": "Welches Modell welchen Job übernimmt. Hier änderst du jeden davon.",+ "models_count": "{count} Modelle · {size} auf der Festplatte",+ "models_one": "1 Modell · {size} auf der Festplatte",+ "models_unknown": "Der Server hat nicht geantwortet; was installiert ist, ist gerade unbekannt.",+ "jobs_filled": "{filled} von {total} Jobs laufen auf einem installierten Modell",+ "fact_version": "Version",+ "fact_address": "Adresse",+ "fact_brain": "Gehirn","action_browse": "Modelle durchsuchen",- "action_browse_hint": "Einen Download aus dem Katalog wählen.",- "disk_models": "{count} Modelle",- "disk_model_one": "1 Modell","gpu_in_use": "{gb} belegt","gpu_in_use_none": "nichts belegt","loaded_expires": "läuft in {when} ab",@@ -274,6 +284,9 @@"pick_discovery": "Jarvis wählen lassen","pick_none": "Modell wählen","pick_missing_suffix": "(nicht installiert)",+ "pick_group_fits": "Passt zu diesem Job",+ "pick_group_others": "Weitere installierte Modelle",+ "server_silent": "Der Server hat nicht geantwortet, daher kann diese Liste unvollständig sein. Aktualisiere, sobald er läuft.","use_recommended": "Empfehlung nutzen","download_recommended": "{model} herunterladen","tune": "Einstellen",@@ -290,10 +303,7 @@"readback_defaults": "Läuft mit den eigenen Vorgaben des Modells.","tune_skipped": "Zugewiesen; die Einstellungen bleiben bei den Vorgaben des Modells.","voice_context_auto": "Läuft mit {context} Kontext — nach dem Speicher dieses Rechners bemessen. Über „Abstimmen“ selbst festlegen.",- "voice_context_manual": "Läuft mit {context} Kontext — von dir unter „Abstimmen“ festgelegt.",- "checklist_not_set": "nicht gesetzt",- "checklist_change": "Ändern",- "checklist_done": "Fertig"+ "voice_context_manual": "Läuft mit {context} Kontext — von dir unter „Abstimmen“ festgelegt."},"server": {"host_eyebrow": "Host",diff --git a/jarvis/ui/web/frontend/src/i18n/locales/local_models/en.json b/jarvis/ui/web/frontend/src/i18n/locales/local_models/en.jsonindex 380a3a0f5d..c4f850da98 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/local_models/en.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/local_models/en.json@@ -6,6 +6,7 @@"mode_label": "Detail level","mode_simple": "Simple","mode_advanced": "Advanced",+ "reload": "Refresh","tabs_label": "Local model areas","tab_overview": "Overview","tab_models": "Models",@@ -196,11 +197,20 @@"status_gpu_unknown": "graphics memory unknown","status_brain_other": "{server} is not your active brain ({brain} answers)","status_brain_active": "{server} is your active brain",- "actions_label": "Next steps",+ "step_server_title": "Server",+ "step_server_subtitle": "The program that runs the models on this machine.",+ "step_models_title": "Models",+ "step_models_subtitle": "The downloads on the server. Every job picks from these.",+ "step_jobs_title": "Jobs",+ "step_jobs_subtitle": "Which model answers for which job. Change any of them here.",+ "models_count": "{count} models · {size} on disk",+ "models_one": "1 model · {size} on disk",+ "models_unknown": "The server did not answer, so what is installed is unknown right now.",+ "jobs_filled": "{filled} of {total} jobs are on an installed model",+ "fact_version": "Version",+ "fact_address": "Address",+ "fact_brain": "Brain","action_browse": "Browse models",- "action_browse_hint": "Pick a download from the catalogue.",- "disk_models": "{count} models",- "disk_model_one": "1 model","gpu_in_use": "{gb} in use","gpu_in_use_none": "nothing in use","loaded_expires": "expires in {when}",@@ -274,6 +284,9 @@"pick_discovery": "Let Jarvis pick","pick_none": "Choose a model","pick_missing_suffix": "(not installed)",+ "pick_group_fits": "Fits this job",+ "pick_group_others": "Other installed models",+ "server_silent": "The server did not answer, so this list may be incomplete. Refresh once it is running.","use_recommended": "Use recommended","download_recommended": "Download {model}","tune": "Tune",@@ -290,10 +303,7 @@"readback_defaults": "Runs with the model's own defaults.","tune_skipped": "Assigned; the settings stay at the model's defaults.","voice_context_auto": "Runs with a {context} context — sized from this machine's memory. Tune to set it yourself.",- "voice_context_manual": "Runs with a {context} context — set by you in Tune.",- "checklist_not_set": "not set",- "checklist_change": "Change",- "checklist_done": "Done"+ "voice_context_manual": "Runs with a {context} context — set by you in Tune."},"server": {"host_eyebrow": "Host",diff --git a/jarvis/ui/web/frontend/src/i18n/locales/local_models/es.json b/jarvis/ui/web/frontend/src/i18n/locales/local_models/es.jsonindex dec5d1d2e2..81b2b678d2 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/local_models/es.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/local_models/es.json@@ -6,6 +6,7 @@"mode_label": "Nivel de detalle","mode_simple": "Sencillo","mode_advanced": "Avanzado",+ "reload": "Actualizar","tabs_label": "Áreas de modelos locales","tab_overview": "Resumen","tab_models": "Modelos",@@ -196,11 +197,20 @@"status_gpu_unknown": "memoria gráfica desconocida","status_brain_other": "{server} no es tu cerebro activo (responde {brain})","status_brain_active": "{server} es tu cerebro activo",- "actions_label": "Siguientes pasos",+ "step_server_title": "Servidor",+ "step_server_subtitle": "El programa que ejecuta los modelos en este equipo.",+ "step_models_title": "Modelos",+ "step_models_subtitle": "Las descargas en el servidor. Cada tarea elige entre estas.",+ "step_jobs_title": "Tareas",+ "step_jobs_subtitle": "Qué modelo responde a cada tarea. Cambia cualquiera aquí.",+ "models_count": "{count} modelos · {size} en disco",+ "models_one": "1 modelo · {size} en disco",+ "models_unknown": "El servidor no respondió, así que ahora se desconoce qué hay instalado.",+ "jobs_filled": "{filled} de {total} tareas usan un modelo instalado",+ "fact_version": "Versión",+ "fact_address": "Dirección",+ "fact_brain": "Cerebro","action_browse": "Explorar modelos",- "action_browse_hint": "Elige una descarga del catálogo.",- "disk_models": "{count} modelos",- "disk_model_one": "1 modelo","gpu_in_use": "{gb} en uso","gpu_in_use_none": "nada en uso","loaded_expires": "caduca en {when}",@@ -274,6 +284,9 @@"pick_discovery": "Dejar que Jarvis elija","pick_none": "Elige un modelo","pick_missing_suffix": "(no instalado)",+ "pick_group_fits": "Encaja con esta tarea",+ "pick_group_others": "Otros modelos instalados",+ "server_silent": "El servidor no respondió, así que esta lista puede estar incompleta. Actualiza cuando esté en marcha.","use_recommended": "Usar el recomendado","download_recommended": "Descargar {model}","tune": "Ajustar",@@ -290,10 +303,7 @@"readback_defaults": "Corre con los valores propios del modelo.","tune_skipped": "Asignado; los ajustes se quedan en los valores del modelo.","voice_context_auto": "Funciona con un contexto de {context}, dimensionado según la memoria de este equipo. Ajústalo tú en «Ajustar».",- "voice_context_manual": "Funciona con un contexto de {context}, fijado por ti en «Ajustar».",- "checklist_not_set": "sin definir",- "checklist_change": "Cambiar",- "checklist_done": "Listo"+ "voice_context_manual": "Funciona con un contexto de {context}, fijado por ti en «Ajustar»."},"server": {"host_eyebrow": "Host",diff --git a/jarvis/ui/web/frontend/src/lib/localModelsSnapshot.test.ts b/jarvis/ui/web/frontend/src/lib/localModelsSnapshot.test.tsindex 32a5d596d2..5a162d07d4 100644--- a/jarvis/ui/web/frontend/src/lib/localModelsSnapshot.test.ts+++ b/jarvis/ui/web/frontend/src/lib/localModelsSnapshot.test.ts@@ -61,6 +61,32 @@ describe("localModelsSnapshot", () => {expect(readOverviewSnapshot("ollama")).toBeNull();});+ it("neither stores nor reads a sweep taken while the server was silent", () => {+ // Ollama still booting: the payload is truthful now and ruinous later —+ // an empty inventory paints a machine that looks wiped, and each role's+ // picker then offers only the tag already configured (BUG-188).+ const offline = payload({+ inventory: {+ models: [],+ error: "Ollama is not answering on http://localhost:11434.",+ } as unknown as OverviewResponse["inventory"],+ });+ expect(writeOverviewSnapshot("ollama", offline)).toBe(false);+ expect(readOverviewSnapshot("ollama")).toBeNull();++ // A good snapshot already on disk survives the offline sweep.+ writeOverviewSnapshot("ollama", payload());+ expect(writeOverviewSnapshot("ollama", offline)).toBe(false);+ expect(readOverviewSnapshot("ollama")?.fetched_at).toBe(1_700_000_000);++ // One written by an older build is dropped on read rather than painted.+ window.localStorage.setItem(+ snapshotKey("ollama"),+ JSON.stringify({ v: SNAPSHOT_VERSION, data: offline }),+ );+ expect(readOverviewSnapshot("ollama")).toBeNull();+ });+it("keeps one entry per provider", () => {writeOverviewSnapshot("ollama", payload());expect(readOverviewSnapshot("other")).toBeNull();diff --git a/jarvis/ui/web/frontend/src/lib/localModelsSnapshot.ts b/jarvis/ui/web/frontend/src/lib/localModelsSnapshot.tsindex 6320469b48..49b1647ca1 100644--- a/jarvis/ui/web/frontend/src/lib/localModelsSnapshot.ts+++ b/jarvis/ui/web/frontend/src/lib/localModelsSnapshot.ts@@ -30,6 +30,21 @@ export function snapshotKey(providerId: string): string {return `${KEY_PREFIX}${providerId}`;}+/**+ * Whether a payload is safe to paint from later.+ *+ * A sweep taken while the server was unreachable — still booting, stopped,+ * a remote host off the network — carries an empty inventory. Painting that+ * on the next open shows a machine that looks wiped: every role reads "not+ * installed", every shortlist reads "nothing installed fits this job yet",+ * and each role's picker offers only the tag already configured, so no other+ * model can be chosen at all. Such a payload is neither stored nor read back;+ * the previous, honest snapshot stays (BUG-188).+ */+export function isPaintable(data: OverviewResponse): boolean {+ return !data.inventory?.error;+}+/*** Synchronously read the last overview for `providerId`; `null` when there* is none, the version does not match, the JSON is broken or storage is@@ -53,6 +68,7 @@ export function readOverviewSnapshot(!data.recommended)return null;+ if (!isPaintable(data)) return null;return { ...data, source: "cache" };} catch {return null;@@ -60,14 +76,16 @@ export function readOverviewSnapshot(}/**- * Persist an overview for the next paint. Oversized payloads and blocked- * storage are silent no-ops — the section still works, it just paints a- * beat later next time.+ * Persist an overview for the next paint. Oversized payloads, a sweep taken+ * while the server was unreachable (see `isPaintable`) and blocked storage+ * are silent no-ops — the section still works, it just paints a beat later+ * next time.*/export function writeOverviewSnapshot(providerId: string,data: OverviewResponse,): boolean {+ if (!isPaintable(data)) return false;try {const env: Envelope = { v: SNAPSHOT_VERSION, data };const json = JSON.stringify(env);diff --git a/jarvis/ui/web/frontend/src/views/LocalModelsView.test.tsx b/jarvis/ui/web/frontend/src/views/LocalModelsView.test.tsxindex bcfbdc64fd..4ef1d187ce 100644--- a/jarvis/ui/web/frontend/src/views/LocalModelsView.test.tsx+++ b/jarvis/ui/web/frontend/src/views/LocalModelsView.test.tsx@@ -82,11 +82,14 @@ vi.mock("@/views/local-models/TuneSheet", () => ({</div>),}));+const mockReload = vi.fn(async () => {});+vi.mock("@/hooks/useLocalModels", () => ({useInventory: () => ({isLoading: false,data: { models: [{ name: "qwen3.5:4b" }] },}),+ useReloadLocalModels: () => mockReload,}));import {@@ -246,4 +249,12 @@ describe("LocalModelsView", () => {expect(screen.getByTestId("catalogue-panel")).toBeDefined();expect(screen.queryByTestId("overview-panel")).toBeNull();});++ it("Refresh throws the section's cached answers away and reads again", () => {+ render(<LocalModelsView />);+ fireEvent.click(+ screen.getByRole("button", { name: "local_models.reload" }),+ );+ expect(mockReload).toHaveBeenCalledTimes(1);+ });});diff --git a/jarvis/ui/web/frontend/src/views/LocalModelsView.tsx b/jarvis/ui/web/frontend/src/views/LocalModelsView.tsxindex a49e87b99a..2bf5e93a9f 100644--- a/jarvis/ui/web/frontend/src/views/LocalModelsView.tsx+++ b/jarvis/ui/web/frontend/src/views/LocalModelsView.tsx@@ -17,14 +17,16 @@* for `/api/providers`; the list still resolves and corrects the seed.*/import { useCallback, useEffect, useMemo, useState } from "react";+import { Loader2, RefreshCw } from "lucide-react";import { ScrollArea } from "@/components/ui/scroll-area";import {BackLink,Panel,PanelHeader,SegmentedFilter,+ SoftButton,} from "@/components/extensions/primitives";-import { useInventory } from "@/hooks/useLocalModels";+import { useInventory, useReloadLocalModels } from "@/hooks/useLocalModels";import { useProviders } from "@/hooks/useProviders";import {LOCAL_MODELS_MARK_MOUNT,@@ -153,6 +155,17 @@ export function LocalModelsView() {setMode(next);storeMode(next);}, []);++ // Refresh: drops the painted snapshot and every cached answer, then reads+ // the server again. The one recovery from a snapshot taken while the+ // server was silent, which otherwise paints a wiped machine (BUG-188).+ const reload = useReloadLocalModels(providerId ?? undefined);+ const [reloading, setReloading] = useState(false);+ const onReload = useCallback(() => {+ if (reloading) return;+ setReloading(true);+ void reload().finally(() => setReloading(false));+ }, [reload, reloading]);// "Manage" on the overview's installed list: the full ledger lives on the// Advanced-only Models tab, so the switch flips along with the tab.const openManage = useCallback(() => {@@ -202,6 +215,19 @@ export function LocalModelsView() {options={tabs}/><div className="flex items-center gap-2">+ <SoftButton+ onClick={onReload}+ disabled={!providerId || reloading}+ ariaLabel={t("local_models.reload")}+ className="h-8"+ >+ {reloading ? (+ <Loader2 className="h-3.5 w-3.5 animate-spin" />+ ) : (+ <RefreshCw className="h-3.5 w-3.5" />+ )}+ {t("local_models.reload")}+ </SoftButton><span className="text-[11px] uppercase tracking-[0.14em] text-muted-foreground">{t("local_models.mode_label")}</span>diff --git a/jarvis/ui/web/frontend/src/views/local-models/InstalledPanel.tsx b/jarvis/ui/web/frontend/src/views/local-models/InstalledPanel.tsxindex 6b88135532..dcac88d3ea 100644--- a/jarvis/ui/web/frontend/src/views/local-models/InstalledPanel.tsx+++ b/jarvis/ui/web/frontend/src/views/local-models/InstalledPanel.tsx@@ -35,6 +35,11 @@ export interface InstalledPanelProps {error?: string | null;/** Opens the full ledger (Advanced → Models); the button hides without it. */onManage?: () => void;+ /**+ * Drop the card frame and the title row: the caller already draws both+ * (the overview's `StepCard`), and a card inside a card reads as clutter.+ */+ bare?: boolean;}/** The capabilities a role is gated on; the rest is noise on a one-liner. */@@ -74,6 +79,7 @@ export function InstalledPanel({loading = false,error = null,onManage,+ bare = false,}: InstalledPanelProps) {const t = useT();const k = (key: string) => t(`local_models.installed.${key}`);@@ -113,18 +119,19 @@ export function InstalledPanel({size: formatGb(diskBytes),});- return (- <Panel className="p-4">- <div className="space-y-3" data-testid="local-models-installed">- <div className="flex flex-wrap items-start justify-between gap-3">- <PanelHeader title={k("title")} subtitle={subtitle} />- {onManage && models.length > 0 && (- <SoftButton onClick={onManage} ariaLabel={k("manage")}>- <Database className="h-3.5 w-3.5" />- {k("manage")}- </SoftButton>- )}- </div>+ const body = (+ <div className="space-y-3" data-testid="local-models-installed">+ {!bare && (+ <div className="flex flex-wrap items-start justify-between gap-3">+ <PanelHeader title={k("title")} subtitle={subtitle} />+ {onManage && models.length > 0 && (+ <SoftButton onClick={onManage} ariaLabel={k("manage")}>+ <Database className="h-3.5 w-3.5" />+ {k("manage")}+ </SoftButton>+ )}+ </div>+ )}{error && (<p@@ -206,7 +213,8 @@ export function InstalledPanel({})}</ul>)}- </div>- </Panel>+ </div>);+ if (bare) return body;+ return <Panel className="p-4">{body}</Panel>;}diff --git a/jarvis/ui/web/frontend/src/views/local-models/OverviewPanel.test.tsx b/jarvis/ui/web/frontend/src/views/local-models/OverviewPanel.test.tsxindex b3bb5e70c5..997cd463e5 100644--- a/jarvis/ui/web/frontend/src/views/local-models/OverviewPanel.test.tsx+++ b/jarvis/ui/web/frontend/src/views/local-models/OverviewPanel.test.tsx@@ -345,7 +345,7 @@ describe("OverviewPanel paint-first", () => {name: "local_models.overview.disk",});expect(disk.textContent).toContain("80 GB");- expect(screen.getByTestId("overview-status").textContent).toContain(+ expect(screen.getByTestId("step-server").textContent).toContain("local_models.overview.status_runningOllama|0.32.15",);expect(screen.getByTestId("role-row-chat")).toBeDefined();@@ -397,22 +397,22 @@ describe("OverviewPanel paint-first", () => {});describe("OverviewPanel", () => {- it("opens with one status sentence: server, graphics memory, active brain", async () => {+ it("step 1 says whether the server runs, on what hardware, and who the brain is", async () => {installFetchMock();renderPanel();- const status = await screen.findByTestId("overview-status");+ const status = await screen.findByTestId("step-server");await waitFor(() =>expect(status.textContent).toContain("local_models.overview.status_runningOllama|0.32.15",),);- expect(status.textContent).toContain(- "local_models.overview.status_gpu16.0",- );+ expect(status.textContent).toContain("16.0 GB");expect(status.textContent).toContain("local_models.overview.status_brain_activeOllama",);+ // A running server satisfies step 1: the marker is a check, not a "1".+ expect(status.getAttribute("data-state")).toBe("done");});it("names the other brain in the status sentence when Ollama is not active", async () => {@@ -429,35 +429,42 @@ describe("OverviewPanel", () => {);});- it("offers one action: browse the catalogue", async () => {+ it("browsing the catalogue is step 2's action", async () => {installFetchMock();const onBrowse = vi.fn();renderPanel({ onBrowse });- await screen.findByTestId("overview-actions");+ const models = await screen.findByTestId("step-models");fireEvent.click(- screen.getByRole("button", { name: "local_models.overview.action_browse" }),+ within(models).getByRole("button", {+ name: "local_models.overview.action_browse",+ }),);expect(onBrowse).toHaveBeenCalledTimes(1);});- it("the detail level changes the roles on this very screen", async () => {+ it("the detail level adds detail to the jobs but never takes the picker away", async () => {installFetchMock();- const { unmount } = renderPanel();- const simple = await screen.findByTestId("local-models-roles");- expect(simple.getAttribute("data-variant")).toBe("checklist");+ const { unmount } = renderPanel({ onTune: vi.fn() });+ await screen.findByTestId("role-row-chat");+ // Simple: the picker is there, the capability badges and Tune are not.+ expect(screen.getByTestId("role-picker-chat")).toBeDefined();+ expect(screen.queryByText("tools")).toBeNull();+ expect(screen.queryByText("local_models.roles.tune")).toBeNull();unmount();installFetchMock();- renderPanel({ advanced: true });- const advanced = await screen.findByTestId("local-models-roles");- expect(advanced.getAttribute("data-variant")).not.toBe("checklist");+ renderPanel({ advanced: true, onTune: vi.fn() });+ await screen.findByTestId("role-row-chat");+ expect(screen.getByTestId("role-picker-chat")).toBeDefined();+ expect(screen.getAllByText("tools").length).toBeGreaterThan(0);+ expect(screen.getByText("local_models.roles.tune")).toBeDefined();});it("keeps 'Set up everything' even when no browse handler is wired", async () => {installFetchMock();renderPanel();- await screen.findByTestId("overview-status");+ await screen.findByTestId("step-server");expect(screen.queryByRole("button", {name: "local_models.overview.action_browse",@@ -487,10 +494,11 @@ describe("OverviewPanel", () => {name: "local_models.overview.disk",});await waitFor(() => expect(disk.textContent).toContain("12 GB"));- await waitFor(() =>- expect(disk.textContent).toContain("local_models.overview.disk_model_one"),- );expect(disk.textContent).toContain("/home/x/.ollama/models");+ // How many downloads there are is step 2's own status line.+ expect(+ (await screen.findByTestId("step-models")).textContent,+ ).toContain("local_models.overview.models_one");const gpu = screen.getByRole("group", {name: "local_models.overview.gpu",@@ -512,67 +520,53 @@ describe("OverviewPanel", () => {});renderPanel();- const status = await screen.findByTestId("overview-status");+ const status = await screen.findByTestId("step-server");await waitFor(() =>expect(status.textContent).toContain("local_models.overview.status_stoppedOllama",),);- expect(screen.getByText("local_models.overview.gpu_unknown")).toBeDefined();+ // Named in step 1's facts and again on step 2's tile.+ expect(+ screen.getAllByText(/local_models\.overview\.gpu_unknown/).length,+ ).toBeGreaterThan(0);});- it("renders the roles as a checklist, expands one row to the full ledger row and folds it back", async () => {+ it("gives every job its picker straight away, listing more than the qualifying models", async () => {installFetchMock();- renderPanel({ onTune: vi.fn() });+ renderPanel({ advanced: true, onTune: vi.fn() });- const chat = await screen.findByTestId("role-row-chat");- expect(chat.getAttribute("data-variant")).toBe("checklist");+ await screen.findByTestId("role-row-chat");expect(screen.getByTestId("role-row-tools_screen")).toBeDefined();expect(screen.getByTestId("role-row-deep")).toBeDefined();expect(screen.getByTestId("role-row-embedding")).toBeDefined();expect(screen.queryByText("local_models.role_voice")).toBeNull();- // Compact rows: the model, "not set", no badges, no picker, no Tune.- // (Scoped to the ledger: the installed list below names the model too.)- expect(- within(screen.getByTestId("roles-ledger")).getByText("qwen3.5:4b", {- selector: "span",- }),- ).toBeDefined();- expect(- screen.getAllByText("local_models.roles.checklist_not_set").length,- ).toBe(3);- expect(screen.queryByText("tools")).toBeNull();- expect(screen.queryByText("local_models.roles.tune")).toBeNull();- // Embedding has no recommendation applied yet -> "Download ..."; the- // trailing action is exactly one per row.- expect(- screen.getByText("local_models.roles.download_recommendedqwen3-embedding:4b"),- ).toBeDefined();- // Expand chat via its line -> the full row with badges, picker, Tune, Done.- fireEvent.click(- screen.getByRole("button", { name: /local_models.role_chat/ }),- );- expect(screen.getAllByText("tools").length).toBeGreaterThan(0);- expect(screen.getByText("local_models.roles.tune")).toBeDefined();+ // No expanding: the control that changes a job is on screen for each one.+ for (const role of ["chat", "tools_screen", "deep", "embedding"])+ expect(screen.getByTestId(`role-picker-${role}`)).toBeDefined();++ // Embedding qualifies for nothing installed, yet its picker still offers+ // the installed downloads — the state that used to leave a user with a+ // single option and no way to change it (BUG-188).+ const embedding = screen.getByTestId(+ "role-picker-embedding",+ ) as HTMLSelectElement;+ const offered = [...embedding.options].map((o) => o.value);+ expect(offered).toContain("qwen3.5:4b");expect(- screen.getByLabelText("local_models.roles.pick_labellocal_models.role_chat"),+ screen.getByText("local_models.roles.download_recommendedqwen3-embedding:4b"),).toBeDefined();- fireEvent.click(screen.getByText("local_models.roles.checklist_done"));- expect(screen.queryByText("local_models.roles.tune")).toBeNull();fireEvent.click(screen.getByText("local_models.roles.more_roles"));expect(screen.getByText("local_models.role_voice")).toBeDefined();});- it("writes the pick through PUT roles/{role} from the expanded row", async () => {+ it("writes the pick through PUT roles/{role}", async () => {const fetchMock = installFetchMock();renderPanel();await screen.findByTestId("role-row-deep");- fireEvent.click(- screen.getByRole("button", { name: /local_models.role_deep/ }),- );const select = screen.getByLabelText("local_models.roles.pick_labellocal_models.role_deep",);@@ -670,7 +664,7 @@ describe("OverviewPanel", () => {];renderPanel();- await screen.findByTestId("overview-actions");+ await screen.findByTestId("step-server");fireEvent.click(screen.getByRole("button", { name: "local_models.overview.action_setup" }),);@@ -735,9 +729,13 @@ describe("OverviewPanel", () => {const onManage = vi.fn();renderPanel({ onManage });- const list = await screen.findByTestId("local-models-installed");+ await screen.findByTestId("local-models-installed");await screen.findByTestId("installed-qwen3.5:4b");- expect(list.textContent).toContain("local_models.installed.subtitle2|");+ // How many downloads and how much disk is step 2's status line; the list+ // itself no longer repeats it inside the card.+ expect(+ (await screen.findByTestId("step-models")).textContent,+ ).toContain("local_models.overview.models_count2|");// Each line says which roles it is the pick for (the fixture's rows// carry no used_by, so the markers are the recommendations).expect(diff --git a/jarvis/ui/web/frontend/src/views/local-models/OverviewPanel.tsx b/jarvis/ui/web/frontend/src/views/local-models/OverviewPanel.tsxindex af5682b49d..d59713d461 100644--- a/jarvis/ui/web/frontend/src/views/local-models/OverviewPanel.tsx+++ b/jarvis/ui/web/frontend/src/views/local-models/OverviewPanel.tsx@@ -1,16 +1,20 @@/**- * Overview — the Simple-mode front page of the Local models section, written- * so it reads like a plan rather than a dashboard.+ * Overview — the front page of the Local models section, written as three+ * steps rather than a dashboard.*- * Top to bottom: one status sentence ("Ollama 0.32 running · 16 GB graphics- * memory · Ollama is not your active brain (OpenRouter answers)"), the- * actions — "Set up everything" first (the one click that starts the server,- * fills every role with the best installed download and fetches only what- * is missing; `useLocalSetup`), then "Browse models" — with the flow's- * progress line underneath, the headline tiles (downloads on disk, graphics- * memory, loaded now), the roles as a checklist, and every installed model- * as one line (`InstalledPanel`), so "what do I have?" never needs the- * Advanced switch.+ * Running a model on your own machine is three questions in a fixed order:+ * is there a server, are there models on it, and which model answers for+ * which job. The page is those three questions, one numbered `StepCard`+ * each, whose marker turns into a check once the step is satisfied — so+ * "what is still missing" is a glance. Each card carries at most one primary+ * action, and step 1 carries the one that does everything (`useLocalSetup`:+ * install or start the server, fill every job with the best installed+ * download, fetch only what is missing, verify, and remember the autostart).+ *+ * Every job's picker is on screen at every detail level. The Simple page used+ * to fold them away behind a "Change" button, which is half of why the+ * section read as "it keeps resetting my model" (BUG-188). `advanced` adds+ * capability badges, Tune and the read-only jobs; it never removes a control.** Props take `providerId` — the id of the card that declares* `supports_model_pull` — never a provider name.@@ -19,6 +23,7 @@ import { useCallback, useEffect, useRef, useState, type ReactNode } from "react"import { Cpu, HardDrive, Layers, Loader2, Search, Sparkles } from "lucide-react";import {+ FactRows,SoftButton,StatTile,StatusDot,@@ -36,6 +41,7 @@ import { InstalledPanel } from "./InstalledPanel";import { formatExpiry } from "./localModelsFormat";import type { SetupStep, SetupSummary } from "./localSetup";import { RolesPanel, type RolesPanelProps } from "./RolesPanel";+import { StepCard, type StepState } from "./StepCard";import { useLocalSetup } from "./useLocalSetup";import { verifyLines } from "./verifyLines";@@ -46,8 +52,8 @@ export interface OverviewPanelProps extends RolesPanelProps {onManage?: () => void;/*** Detail level. The switch beside the rail must change what is on screen- * HERE too, or it reads as a dead control: Simple keeps the roles a- * checklist, Advanced opens every row to its picker, capabilities and Tune.+ * HERE too, or it reads as a dead control: Advanced adds the capability+ * badges, the Tune buttons and the read-only jobs.*/advanced?: boolean;}@@ -73,11 +79,13 @@ export function OverviewPanel({const { providers, refetch: refetchProviders } = useProviders();const setup = useLocalSetup(providerId);- // One round-trip (or the painted snapshot) feeds every tile.+ // One round-trip (or the painted snapshot) feeds every card.const s = overview.data?.server;const shortlist = { data: overview.data?.recommended };const inventory = { data: overview.data?.inventory };const server = { isLoading: overview.isLoading, isError: overview.isError };+ // Painted from the snapshot while the live read runs: say so rather than+ // present a cached machine as the current one.const checking = overview.isFetching && overview.data?.source === "cache";const marked = useRef(false);@@ -91,7 +99,7 @@ export function OverviewPanel({providers.find((p) => p.id === providerId)?.label ||t("local_models.overview.status_generic_server");- // --- status sentence --------------------------------------------------+ // --- step 1: the server ----------------------------------------------let serverClause = t("local_models.overview.status_checking");let serverTone: "ok" | "warn" | "error" | "busy" = "busy";if (s) {@@ -135,32 +143,17 @@ export function OverviewPanel({const acceleratorGb = shortlist.data?.accelerator_gb ?? 0;const acceleratorSource = shortlist.data?.accelerator_source ?? "";- const gpuClause =- acceleratorGb > 0- ? fill(t("local_models.overview.status_gpu"), {- gb: acceleratorGb.toFixed(1),- })- : shortlist.data- ? t("local_models.overview.status_gpu_unknown")- : "";- // The third clause only renders once the provider list is here — no gate.+ // The brain clause only renders once the provider list is here — no gate.const activeBrain =providers.find((p) => p.tier === "brain" && p.active) ?? null;const otherBrainActive =activeBrain !== null && activeBrain.id !== providerId;- const brainClause = activeBrain- ? activeBrain.id === providerId- ? fill(t("local_models.overview.status_brain_active"), {- server: serverLabel,- })- : fill(t("local_models.overview.status_brain_other"), {- server: serverLabel,- brain: activeBrain.label,- })- : "";- // --- tiles ------------------------------------------------------------+ // --- step 2: the models ----------------------------------------------+ const models = inventory.data?.models ?? [];+ const modelCount = models.length;+ const serverSilent = Boolean(inventory.data?.error);const gpuValue =acceleratorGb > 0? `${acceleratorGb.toFixed(1)} GB`@@ -179,18 +172,6 @@ export function OverviewPanel({}): t("local_models.overview.gpu_unknown_hint");- const modelCount = inventory.data?.models.length ?? null;- const diskHint = [- modelCount === null- ? ""- : modelCount === 1- ? t("local_models.overview.disk_model_one")- : fill(t("local_models.overview.disk_models"), { count: modelCount }),- s?.models_dir ?? "",- ]- .filter(Boolean)- .join(" · ");-const loaded = s?.running_models ?? [];const firstExpiry = loaded.length > 0 ? formatExpiry(loaded[0].expires_at) : "";const loadedHint =@@ -207,14 +188,41 @@ export function OverviewPanel({.join(" · "): t("local_models.overview.loaded_none");- const dotClass = {- ok: "bg-emerald-500",- warn: "bg-amber-500",- error: "bg-destructive",- busy: "bg-primary animate-pulse",- }[serverTone];+ // --- step 3: the jobs -------------------------------------------------+ const roleRows = overview.data?.roles.roles ?? [];+ const writableRows = roleRows.filter((r) => !r.advanced && r.writable);+ const filledRows = writableRows.filter((r) => r.current !== "" && r.installed);+ const roleLabel = useCallback(+ (role: LocalModelRole) => {+ const row = roleRows.find((r) => r.id === role);+ return t(row?.label_key ?? `local_models.role_${role}`);+ },+ [roleRows, t],+ );++ // --- step states ------------------------------------------------------+ // "Checking" is busy, not a verdict; a step only claims done on facts.+ const serverState: StepState = !s+ ? server.isError+ ? "attention"+ : "busy"+ : s.running+ ? "done"+ : "attention";+ const modelsState: StepState = !inventory.data+ ? "busy"+ : serverSilent+ ? "attention"+ : modelCount > 0+ ? "done"+ : "attention";+ const jobsState: StepState =+ writableRows.length === 0+ ? "busy"+ : filledRows.length === writableRows.length+ ? "done"+ : "attention";- // --- actions ----------------------------------------------------------// A server that is not installed gets a button that NAMES the install:// the click is the consent the dangerous-flagged install route asks for.const needsInstall = Boolean(s && !s.installed && !remote);@@ -223,146 +231,216 @@ export function OverviewPanel({server: serverLabel,}): t("local_models.overview.action_setup");- const setupHint = needsInstall- ? t("local_models.overview.action_setup_install_hint")- : t("local_models.overview.action_setup_hint");-- const roleRows = overview.data?.roles.roles ?? [];- const roleLabel = useCallback(- (role: LocalModelRole) => {- const row = roleRows.find((r) => r.id === role);- return t(row?.label_key ?? `local_models.role_${role}`);- },- [roleRows, t],- );return (<div className="space-y-4" data-testid="local-models-overview-panel">- <p- className="flex flex-wrap items-center gap-x-2 gap-y-1 text-sm text-foreground"- data-testid="overview-status"- >- <span className={cn("h-2 w-2 shrink-0 rounded-full", dotClass)} />- <span>{serverClause}</span>- {gpuClause && (- <>- <span className="text-muted-foreground">·</span>- <span className="text-muted-foreground">{gpuClause}</span>- </>- )}- {brainClause && (- <>- <span className="text-muted-foreground">·</span>- <span- className={cn(- activeBrain?.id === providerId- ? "text-muted-foreground"- : "text-amber-700 dark:text-amber-400",- )}- data-testid="overview-brain-clause"- >- {brainClause}- </span>- </>- )}- {checking && (- <span className="ml-1" data-testid="overview-checking">- <StatusDot- tone="busy"- pulse- label={t("local_models.overview.checking")}- />+ {/* ── 1 · Server ────────────────────────────────────────────────── */}+ <StepCard+ step={1}+ title={t("local_models.overview.step_server_title")}+ subtitle={t("local_models.overview.step_server_subtitle")}+ state={serverState}+ testId="step-server"+ status={+ <span className="flex flex-wrap items-center gap-x-3 gap-y-1">+ <StatusDot tone={serverTone} pulse={serverTone === "busy"} label={serverClause} />+ {checking && (+ <span data-testid="overview-checking">+ <StatusDot tone="busy" pulse label={t("local_models.overview.checking")} />+ </span>+ )}</span>- )}- </p>-- <div- className="flex flex-wrap gap-2"- role="group"- aria-label={t("local_models.overview.actions_label")}- data-testid="overview-actions"- >- <ActionButton- primary- icon={- setup.busy ? (+ }+ action={+ <SoftButton+ primary+ onClick={setup.run}+ disabled={setup.busy}+ className="h-9"+ >+ {setup.busy ? (<Loader2 className="h-4 w-4 animate-spin" />) : (<Sparkles className="h-4 w-4" />- )- }- label={setupLabel}- hint={setupHint}- onClick={setup.run}- disabled={setup.busy}- testId="overview-setup"- />- {onBrowse && (- <ActionButton- icon={<Search className="h-4 w-4" />}- label={t("local_models.overview.action_browse")}- hint={t("local_models.overview.action_browse_hint")}- onClick={onBrowse}- />- )}- </div>-- <SetupProgress- step={setup.step}- serverLabel={serverLabel}- roleLabel={roleLabel}- otherBrain={otherBrainActive ? (activeBrain?.label ?? "") : ""}- onSwitchBrain={async () => {- await switchBrainProvider(providerId);- await refetchProviders();- }}- t={t}- />-- <div className="grid grid-cols-1 gap-3 sm:grid-cols-3">- <StatTile- icon={<HardDrive className="h-3.5 w-3.5" />}- label={t("local_models.overview.disk")}- value={formatGigabytes(s?.disk_bytes ?? 0)}- hint={diskHint}- tone="primary"- loading={server.isLoading}- />- <StatTile- icon={<Cpu className="h-3.5 w-3.5" />}- label={t("local_models.overview.gpu")}- value={gpuValue}- hint={gpuHint}- tone="primary"- loading={server.isLoading}+ )}+ {setupLabel}+ </SoftButton>+ }+ >+ <p className="text-xs text-muted-foreground" data-testid="setup-hint">+ {needsInstall+ ? t("local_models.overview.action_setup_install_hint")+ : t("local_models.overview.action_setup_hint")}+ </p>+ <SetupProgress+ step={setup.step}+ serverLabel={serverLabel}+ roleLabel={roleLabel}+ otherBrain={otherBrainActive ? (activeBrain?.label ?? "") : ""}+ onSwitchBrain={async () => {+ await switchBrainProvider(providerId);+ await refetchProviders();+ }}+ t={t}/>- <StatTile- icon={<Layers className="h-3.5 w-3.5" />}- label={t("local_models.overview.loaded")}- value={String(loaded.length)}- hint={loadedHint}- tone="primary"- loading={server.isLoading}+ <FactRows+ className="mt-3 !text-sm"+ rows={[+ {+ label: t("local_models.overview.fact_version"),+ value: s?.version || t("local_models.overview.server_unknown"),+ },+ {+ label: t("local_models.overview.fact_address"),+ value: s?.base_url ? (+ <span className="font-mono text-xs">{s.base_url}</span>+ ) : (+ ""+ ),+ },+ {+ label: t("local_models.overview.gpu"),+ value: (+ <span>+ {gpuValue}+ <span className="ml-2 text-xs text-muted-foreground">{gpuHint}</span>+ </span>+ ),+ },+ {+ label: t("local_models.overview.fact_brain"),+ value: activeBrain ? (+ <span+ className={cn(+ otherBrainActive && "text-amber-700 dark:text-amber-400",+ )}+ data-testid="overview-brain-clause"+ >+ {otherBrainActive+ ? fill(t("local_models.overview.status_brain_other"), {+ server: serverLabel,+ brain: activeBrain.label,+ })+ : fill(t("local_models.overview.status_brain_active"), {+ server: serverLabel,+ })}+ </span>+ ) : (+ ""+ ),+ },+ ]}/>- </div>+ </StepCard>- <RolesPanel- providerId={providerId}- onTune={onTune}- onOpenApiKeys={onOpenApiKeys}- variant={advanced ? "ledger" : "checklist"}- onSetup={setup.run}- setupBusy={setup.busy}- />+ {/* ── 2 · Models ───────────────────────────────────────────────── */}+ <StepCard+ step={2}+ title={t("local_models.overview.step_models_title")}+ subtitle={t("local_models.overview.step_models_subtitle")}+ state={modelsState}+ testId="step-models"+ status={+ <StatusDot+ tone={modelsState === "done" ? "ok" : modelsState === "busy" ? "busy" : "warn"}+ pulse={modelsState === "busy"}+ label={+ serverSilent+ ? t("local_models.overview.models_unknown")+ : modelCount === 1+ ? fill(t("local_models.overview.models_one"), {+ size: formatGigabytes(inventory.data?.disk_bytes ?? 0),+ })+ : fill(t("local_models.overview.models_count"), {+ count: modelCount,+ size: formatGigabytes(inventory.data?.disk_bytes ?? 0),+ })+ }+ />+ }+ action={+ <>+ {onBrowse && (+ <SoftButton onClick={onBrowse} className="h-9">+ <Search className="h-4 w-4" />+ {t("local_models.overview.action_browse")}+ </SoftButton>+ )}+ {onManage && modelCount > 0 && (+ <SoftButton onClick={onManage} className="h-9">+ {t("local_models.installed.manage")}+ </SoftButton>+ )}+ </>+ }+ >+ <div className="grid grid-cols-1 gap-3 sm:grid-cols-3">+ <StatTile+ icon={<HardDrive className="h-3.5 w-3.5" />}+ label={t("local_models.overview.disk")}+ value={formatGigabytes(s?.disk_bytes ?? 0)}+ hint={s?.models_dir ?? ""}+ tone="primary"+ loading={server.isLoading}+ />+ <StatTile+ icon={<Cpu className="h-3.5 w-3.5" />}+ label={t("local_models.overview.gpu")}+ value={gpuValue}+ hint={gpuHint}+ tone="primary"+ loading={server.isLoading}+ />+ <StatTile+ icon={<Layers className="h-3.5 w-3.5" />}+ label={t("local_models.overview.loaded")}+ value={String(loaded.length)}+ hint={loadedHint}+ tone="primary"+ loading={server.isLoading}+ />+ </div>+ <div className="mt-3">+ <InstalledPanel+ bare+ models={models}+ roles={roleRows}+ diskBytes={inventory.data?.disk_bytes ?? s?.disk_bytes ?? 0}+ loading={overview.isLoading}+ error={inventory.data?.error ?? null}+ onManage={onManage}+ />+ </div>+ </StepCard>- <InstalledPanel- models={inventory.data?.models ?? []}- roles={roleRows}- diskBytes={inventory.data?.disk_bytes ?? s?.disk_bytes ?? 0}- loading={overview.isLoading}- error={inventory.data?.error ?? null}- onManage={onManage}- />+ {/* ── 3 · Jobs ─────────────────────────────────────────────────── */}+ <StepCard+ step={3}+ title={t("local_models.overview.step_jobs_title")}+ subtitle={t("local_models.overview.step_jobs_subtitle")}+ state={jobsState}+ testId="step-jobs"+ status={+ writableRows.length > 0 ? (+ <StatusDot+ tone={jobsState === "done" ? "ok" : "warn"}+ label={fill(t("local_models.overview.jobs_filled"), {+ filled: filledRows.length,+ total: writableRows.length,+ })}+ />+ ) : null+ }+ >+ <RolesPanel+ providerId={providerId}+ onTune={onTune}+ onOpenApiKeys={onOpenApiKeys}+ advanced={advanced}+ onSetup={setup.run}+ setupBusy={setup.busy}+ />+ </StepCard></div>);}@@ -498,7 +576,7 @@ function SetupProgress({}return (- <div className="space-y-1 text-xs" data-testid="setup-progress">+ <div className="mt-2 space-y-1 text-xs" data-testid="setup-progress"><StatusDot tone={tone} pulse={tone === "busy"} label={text} />{lines.map((line, i) => (<p key={i} className="ml-4 text-muted-foreground">@@ -553,7 +631,7 @@ function SetupProgress({}/** A 44 px SoftButton with icon, label and a one-line hint underneath. */-function ActionButton({+export function ActionButton({icon,label,hint,diff --git a/jarvis/ui/web/frontend/src/views/local-models/RolePicker.test.tsx b/jarvis/ui/web/frontend/src/views/local-models/RolePicker.test.tsxnew file mode 100644index 0000000000..4d90d65d95--- /dev/null+++ b/jarvis/ui/web/frontend/src/views/local-models/RolePicker.test.tsx@@ -0,0 +1,138 @@+/**+ * The role picker's job is to always have something to pick.+ *+ * `qualifying` alone leaves a user stranded twice over — an unreachable+ * server empties it, and an unprobed download reports no capabilities — and+ * both read as "my pick jumped back" (BUG-188). These tests pin the two+ * groups and the fact that neither list can swallow an installed model.+ */+import { fireEvent, render, screen } from "@testing-library/react";+import { describe, expect, it, vi } from "vitest";++import type { LocalModelRow, RoleRow } from "@/hooks/useLocalModels";++import { RolePicker, splitChoices } from "./RolePicker";++vi.mock("@/i18n", () => ({+ useT: () => (key: string) => key,+ fill: (template: string, values: Record<string, string>) =>+ `${template}${Object.values(values).join("|")}`,+}));++function role(extra: Partial<RoleRow> = {}): RoleRow {+ return {+ id: "chat",+ label_key: "local_models.role_chat",+ config_key: "brain.providers.ollama.model",+ current: "",+ installed: false,+ required: [],+ recommended_capabilities: [],+ qualifying: [],+ recommended: "",+ writable: true,+ advanced: false,+ note: "",+ ...extra,+ } as RoleRow;+}++const model = (name: string): LocalModelRow =>+ ({ name, capabilities: [], probed: true, used_by: [] }) as unknown as LocalModelRow;++describe("splitChoices", () => {+ it("puts the qualifying models first and every other download after them", () => {+ const { fits, others } = splitChoices(+ role({ qualifying: ["gemma4:12b", "qwen3.5:4b"] }),+ [model("gemma4:12b"), model("qwen3.5:4b"), model("deepseek-r1:14b")],+ );+ expect(fits).toEqual(["gemma4:12b", "qwen3.5:4b"]);+ expect(others).toEqual(["deepseek-r1:14b"]);+ });++ it("still offers the installed models when nothing qualifies", () => {+ // The state the section used to get stuck in: no shortlist, so the only+ // option was the tag already configured.+ const { fits, others } = splitChoices(+ role({ current: "ornith:9b", qualifying: [] }),+ [model("gemma4:12b"), model("qwen3.5:4b"), model("ornith:9b")],+ );+ expect(fits).toEqual([]);+ expect(others).toEqual(["gemma4:12b", "qwen3.5:4b", "ornith:9b"]);+ });++ it("keeps a configured tag that is gone from disk, exactly once", () => {+ const { fits, others } = splitChoices(+ role({ current: "removed:7b", qualifying: ["qwen3.5:4b"] }),+ [model("qwen3.5:4b")],+ );+ expect(fits).toEqual(["qwen3.5:4b"]);+ expect(others).toEqual(["removed:7b"]);+ });++ it("treats a bare tag and its :latest as one download", () => {+ const { fits, others } = splitChoices(+ role({ current: "bge-m3", qualifying: ["bge-m3:latest"] }),+ [model("bge-m3:latest")],+ );+ expect(fits).toEqual(["bge-m3:latest"]);+ expect(others).toEqual([]);+ });+});++describe("RolePicker", () => {+ it("groups the options and reports the pick", () => {+ const onPick = vi.fn();+ render(+ <RolePicker+ row={role({ current: "gemma4:12b", qualifying: ["gemma4:12b"] })}+ models={[model("gemma4:12b"), model("deepseek-r1:14b")]}+ onPick={onPick}+ />,+ );+ const select = screen.getByTestId("role-picker-chat") as HTMLSelectElement;+ expect([...select.options].map((o) => o.value)).toEqual([+ "",+ "gemma4:12b",+ "deepseek-r1:14b",+ ]);+ expect(+ [...select.querySelectorAll("optgroup")].map((g) => g.label),+ ).toEqual([+ "local_models.roles.pick_group_fits",+ "local_models.roles.pick_group_others",+ ]);++ fireEvent.change(select, { target: { value: "deepseek-r1:14b" } });+ expect(onPick).toHaveBeenCalledWith("deepseek-r1:14b");+ });++ it("marks a configured model that is no longer on the server", () => {+ render(+ <RolePicker+ row={role({ current: "removed:7b" })}+ models={[model("qwen3.5:4b")]}+ onPick={vi.fn()}+ />,+ );+ const select = screen.getByTestId("role-picker-chat") as HTMLSelectElement;+ const gone = [...select.options].find((o) => o.value === "removed:7b");+ expect(gone?.textContent).toContain(+ "local_models.roles.pick_missing_suffix",+ );+ });++ it("offers no discovery option for the embedding role once one is set", () => {+ render(+ <RolePicker+ row={role({ id: "embedding", current: "bge-m3:latest" })}+ models={[model("bge-m3:latest")]}+ onPick={vi.fn()}+ />,+ );+ const select = screen.getByTestId(+ "role-picker-embedding",+ ) as HTMLSelectElement;+ expect([...select.options].map((o) => o.value)).toEqual(["bge-m3:latest"]);+ });+});diff --git a/jarvis/ui/web/frontend/src/views/local-models/RolePicker.tsx b/jarvis/ui/web/frontend/src/views/local-models/RolePicker.tsxnew file mode 100644index 0000000000..761b3e0d1b--- /dev/null+++ b/jarvis/ui/web/frontend/src/views/local-models/RolePicker.tsx@@ -0,0 +1,121 @@+/**+ * The model picker of one role row.+ *+ * It used to list `row.qualifying` only — the installed downloads that+ * declare every capability the job requires — plus the configured tag when+ * that had gone missing. Two ways that leaves a user stuck with a value they+ * did not choose (BUG-188):+ *+ * * the sweep behind the payload found no server, so `qualifying` is empty+ * and the list holds exactly one entry: the tag already configured;+ * * a download Jarvis could not probe (`probed: false`) reports no+ * capabilities, so it silently never appears — even though it runs.+ *+ * Both read as "I picked something else and it jumped back". The picker+ * therefore offers EVERY installed download, in two groups: the ones that+ * fit the job first, the rest under "Other installed models" with the+ * consequence spelled out rather than hidden. Choosing one is a real choice+ * a user is allowed to make; the section says what it costs, it does not+ * decide for them.+ */+import { useMemo } from "react";++import { canonicalModelName, type LocalModelRow, type RoleRow } from "@/hooks/useLocalModels";+import { fill, useT } from "@/i18n";+import { cn } from "@/lib/utils";++export interface RolePickerProps {+ row: RoleRow;+ /** Every download the inventory knows; empty while the server is silent. */+ models: LocalModelRow[];+ /** True while a write for this row is in flight. */+ disabled?: boolean;+ onPick: (model: string) => void;+ className?: string;+}++/** `qualifying`, then every other installed tag, each list de-duplicated. */+export function splitChoices(+ row: RoleRow,+ models: LocalModelRow[],+): { fits: string[]; others: string[] } {+ const seen = new Set<string>();+ const fits: string[] = [];+ const others: string[] = [];+ const take = (name: string, into: string[]) => {+ const key = canonicalModelName(name);+ if (!name || seen.has(key)) return;+ seen.add(key);+ into.push(name);+ };+ for (const name of row.qualifying) take(name, fits);+ for (const m of models) take(m.name, others);+ // A configured tag that is gone from disk still belongs in the list, or+ // the row would silently show a value the picker cannot express.+ if (row.current) take(row.current, others);+ return { fits, others };+}++export function RolePicker({+ row,+ models,+ disabled,+ onPick,+ className,+}: RolePickerProps) {+ const t = useT();+ const { fits, others } = useMemo(() => splitChoices(row, models), [row, models]);+ const installed = useMemo(() => {+ const names = new Set<string>();+ for (const m of models) names.add(canonicalModelName(m.name));+ return names;+ }, [models]);++ const label = (name: string) =>+ installed.has(canonicalModelName(name))+ ? name+ : `${name} ${t("local_models.roles.pick_missing_suffix")}`;++ return (+ <select+ aria-label={fill(t("local_models.roles.pick_label"), {+ role: t(row.label_key),+ })}+ value={row.current}+ disabled={disabled}+ onChange={(e) => onPick(e.target.value)}+ data-testid={`role-picker-${row.id}`}+ className={cn(+ "h-9 w-full rounded-lg border border-border bg-background/60 px-2.5 text-sm text-foreground",+ "transition-colors hover:border-border/80 focus:outline-none focus:ring-1 focus:ring-primary",+ "disabled:cursor-not-allowed disabled:opacity-50",+ className,+ )}+ >+ {row.id !== "embedding" && (+ <option value="">{t("local_models.roles.pick_discovery")}</option>+ )}+ {row.id === "embedding" && !row.current && (+ <option value="">{t("local_models.roles.pick_none")}</option>+ )}+ {fits.length > 0 && (+ <optgroup label={t("local_models.roles.pick_group_fits")}>+ {fits.map((name) => (+ <option key={name} value={name}>+ {label(name)}+ </option>+ ))}+ </optgroup>+ )}+ {others.length > 0 && (+ <optgroup label={t("local_models.roles.pick_group_others")}>+ {others.map((name) => (+ <option key={name} value={name}>+ {label(name)}+ </option>+ ))}+ </optgroup>+ )}+ </select>+ );+}diff --git a/jarvis/ui/web/frontend/src/views/local-models/RolesPanel.tsx b/jarvis/ui/web/frontend/src/views/local-models/RolesPanel.tsxindex 668f2fd62a..1431db8a79 100644--- a/jarvis/ui/web/frontend/src/views/local-models/RolesPanel.tsx+++ b/jarvis/ui/web/frontend/src/views/local-models/RolesPanel.tsx@@ -1,48 +1,37 @@/**- * Roles — the four model slots Jarvis fills from the local server, one row- * each, one primary action each.+ * Jobs — which download answers for which job, one row each.** Chat & voice, Tools & screen, Deep & coding and Embeddings come from* `GET roles`; every row shows the configured pick (or the discovery- * sentence), the capabilities the slot requires, a picker over the installed- * models that qualify, and "Use recommended" — which downloads the pick when- * it is missing, assigns it, then writes the suggested options silently and- * reads back one sentence. The read-only advanced roles hide under- * "More roles". When nothing is installed at all, the ledger shows one- * "Set up the recommended models" button that runs the overview's set-up- * flow (`useLocalSetup`).+ * sentence), a picker over the installed models (`RolePicker`) and, when the+ * shortlist has a better one, "Use recommended" — which downloads that pick+ * when it is missing, assigns it, then writes the suggested options silently+ * and reads back one sentence. The read-only advanced roles hide under+ * "More roles".*- * Two variants: `ledger` (the full rows: picker, badges, Tune) and- * `checklist` — one compact line per writable role (dot, label, model or- * "not set", ONE trailing action: "Use recommended" when the shortlist has a- * better pick, otherwise "Change"), where Change expands that line into the- * full ledger row in place. The Overview uses the checklist.+ * The picker is on screen for every row at every detail level. It used to be+ * folded away behind a "Change" button on the Simple page, which — together+ * with a shortlist that could come back empty — is what made the section+ * read as "it keeps resetting my model" (BUG-188): the one control that+ * changes a role was two clicks away and then offered nothing to pick.+ * `advanced` now adds detail (capability badges, Tune, the read-only roles),+ * it never takes the control away.*+ * The panel draws no frame of its own — the caller's `StepCard` is the frame.* Props take `providerId` (the pull-capable card's id) rather than the whole- * descriptor so the panel can be mounted from anywhere the id is known. The- * "Tune" button only calls `onTune(model)` — the sheet belongs to the caller.+ * descriptor so the panel can be mounted from anywhere the id is known.*/import { useCallback, useEffect, useMemo, useRef, useState } from "react";-import {- ChevronDown,- ChevronRight,- Loader2,- SlidersHorizontal,- Sparkles,-} from "lucide-react";+import { ChevronDown, Loader2, SlidersHorizontal, Sparkles } from "lucide-react";-import {- Panel,- PanelHeader,- SoftButton,- StatusDot,-} from "@/components/extensions/primitives";+import { SoftButton, StatusDot } from "@/components/extensions/primitives";import {setRole,useInvalidateLocalModels,useOverview,useSetRole,type LocalModelRole,+ type LocalModelRow,type RoleRow,} from "@/hooks/useLocalModels";import { useProviders } from "@/hooks/useProviders";@@ -50,6 +39,7 @@ import { fill, useT } from "@/i18n";import { cn } from "@/lib/utils";import { canonical, waitForPull } from "./localSetup";+import { RolePicker } from "./RolePicker";import { useSilentTune } from "./useLocalSetup";export interface RolesPanelProps {@@ -59,8 +49,8 @@ export interface RolesPanelProps {onTune?: (model: string) => void;/** Navigates to the API Keys section; shown when another brain is active. */onOpenApiKeys?: () => void;- /** `ledger` = full rows (default); `checklist` = compact rows that expand. */- variant?: "ledger" | "checklist";+ /** Adds capability badges, Tune and the read-only roles. Never removes the picker. */+ advanced?: boolean;/** Runs the overview's "Set up everything" flow (the empty state's button). */onSetup?: () => void;/** That flow is underway: the empty state's button waits. */@@ -94,7 +84,7 @@ export function RolesPanel({providerId,onTune,onOpenApiKeys,- variant = "ledger",+ advanced = false,onSetup,setupBusy = false,}: RolesPanelProps) {@@ -116,16 +106,6 @@ export function RolesPanel({const [progress, setProgress] = useState<Record<string, Progress>>({});const [moreOpen, setMoreOpen] = useState(false);- // Checklist rows the user expanded into the full ledger row.- const [expanded, setExpanded] = useState<Set<string>>(() => new Set());- const toggleExpanded = useCallback((roleId: string) => {- setExpanded((prev) => {- const next = new Set(prev);- if (next.has(roleId)) next.delete(roleId);- else next.add(roleId);- return next;- });- }, []);// Async flows outlive a tab switch; nothing is written to state afterwards.const mounted = useRef(true);@@ -137,11 +117,15 @@ export function RolesPanel({}, []);const alive = useCallback(() => mounted.current, []);+ const models: LocalModelRow[] = useMemo(+ () => inventory.data?.models ?? [],+ [inventory.data],+ );const installed = useMemo(() => {const names = new Set<string>();- for (const m of inventory.data?.models ?? []) names.add(canonical(m.name));+ for (const m of models) names.add(canonical(m.name));return names;- }, [inventory.data]);+ }, [models]);const isInstalled = useCallback((name: string) => installed.has(canonical(name)),[installed],@@ -149,7 +133,7 @@ export function RolesPanel({const rows = roles.data?.roles ?? [];const primary = rows.filter((r) => !r.advanced);- const advanced = rows.filter((r) => r.advanced);+ const advancedRows = rows.filter((r) => r.advanced);// The brain switch stays a user-only decision; the panel only says so.const activeBrain =@@ -197,206 +181,197 @@ export function RolesPanel({[alive, invalidate, isInstalled, patch, providerId, tuneSilently],);+ // "Nothing is installed" is only true when the server actually answered.+ // While it is silent the inventory is empty for a different reason, and+ // saying "download something" there sends the user after the wrong problem.+ const serverSilent = Boolean(inventory.data?.error);const nothingInstalled =- inventory.data !== undefined &&- !inventory.data.error &&- inventory.data.models.length === 0;+ inventory.data !== undefined && !serverSilent && models.length === 0;return (- <Panel className="p-4">- <div className="space-y-3" data-testid="local-models-roles" data-variant={variant}>- <PanelHeader- title={t("local_models.roles.title")}- subtitle={t("local_models.roles.subtitle")}- />+ <div className="space-y-3" data-testid="local-models-roles">+ {otherBrainActive && (+ <p+ className="text-sm text-amber-700 dark:text-amber-400"+ data-testid="roles-other-brain"+ >+ {fill(t("local_models.roles.other_brain"), {+ brain: activeBrain?.label ?? "",+ })}{" "}+ {onOpenApiKeys && (+ <button+ type="button"+ onClick={onOpenApiKeys}+ className="font-medium text-primary hover:underline"+ >+ {t("local_models.roles.other_brain_link")}+ </button>+ )}+ </p>+ )}- {otherBrainActive && (- <p- className="text-sm text-amber-700 dark:text-amber-400"- data-testid="roles-other-brain"- >- {fill(t("local_models.roles.other_brain"), {- brain: activeBrain?.label ?? "",- })}{" "}- {onOpenApiKeys && (- <button- type="button"- onClick={onOpenApiKeys}- className="font-medium text-primary hover:underline"- >- {t("local_models.roles.other_brain_link")}- </button>- )}- </p>- )}+ {serverSilent && (+ <p+ className="text-sm text-amber-700 dark:text-amber-400"+ data-testid="roles-server-silent"+ >+ {t("local_models.roles.server_silent")}+ </p>+ )}+ {roles.data?.error && (+ <p className="text-sm text-amber-700 dark:text-amber-400">+ {roles.data.error}+ </p>+ )}+ {roles.isError && (+ <p className="text-sm text-destructive">+ {roles.error instanceof Error+ ? roles.error.message+ : String(roles.error)}+ </p>+ )}+ {roles.isLoading && (+ <p className="text-sm text-muted-foreground">+ {t("local_models.roles.loading")}+ </p>+ )}- {roles.data?.error && (- <p className="text-sm text-amber-700 dark:text-amber-400">- {roles.data.error}- </p>- )}- {roles.isError && (- <p className="text-sm text-destructive">- {roles.error instanceof Error- ? roles.error.message- : String(roles.error)}- </p>- )}- {roles.isLoading && (+ {nothingInstalled && rows.length > 0 && onSetup && (+ <div+ className="rounded-lg border border-dashed border-border px-6 py-8 text-center"+ data-testid="roles-empty"+ ><p className="text-sm text-muted-foreground">- {t("local_models.roles.loading")}+ {t("local_models.roles.empty_body")}</p>- )}-- {nothingInstalled && rows.length > 0 && onSetup && (- <div- className="rounded-lg border border-dashed border-border px-6 py-8 text-center"- data-testid="roles-empty"- >- <p className="text-sm text-muted-foreground">- {t("local_models.roles.empty_body")}- </p>- <div className="mt-4 flex justify-center">- <SoftButton primary onClick={onSetup} disabled={setupBusy}>- {setupBusy ? (- <Loader2 className="h-3.5 w-3.5 animate-spin" />- ) : (- <Sparkles className="h-3.5 w-3.5" />- )}- {t("local_models.roles.setup_button")}- </SoftButton>- </div>+ <div className="mt-4 flex justify-center">+ <SoftButton primary onClick={onSetup} disabled={setupBusy}>+ {setupBusy ? (+ <Loader2 className="h-3.5 w-3.5 animate-spin" />+ ) : (+ <Sparkles className="h-3.5 w-3.5" />+ )}+ {t("local_models.roles.setup_button")}+ </SoftButton></div>- )}+ </div>+ )}- {primary.length > 0 && (- <div- className="divide-y divide-border/70 overflow-hidden rounded-xl border border-border bg-card/60"- data-testid="roles-ledger"- >- {primary.map((row) => {- const rowProgress = progress[row.id] ?? { phase: "idle" };- const saving =+ {primary.length > 0 && (+ <div+ className="divide-y divide-border/70 overflow-hidden rounded-lg border border-border/70"+ data-testid="roles-ledger"+ >+ {primary.map((row) => (+ <RoleRowView+ key={row.id}+ row={row}+ models={models}+ progress={progress[row.id] ?? { phase: "idle" }}+ installed={isInstalled}+ saving={setRoleMutation.isPending &&- setRoleMutation.variables?.role === row.id;- const onPick = (model: string) =>+ setRoleMutation.variables?.role === row.id+ }+ advanced={advanced}+ onPick={(model) =>setRoleMutation.mutate({role: row.id as LocalModelRole,model,- });- if (variant === "checklist" && !expanded.has(row.id)) {- return (- <RoleChecklistRow- key={row.id}- row={row}- progress={rowProgress}- installed={isInstalled}- saving={saving}- onUseRecommended={() => void useRecommended(row)}- onExpand={() => toggleExpanded(row.id)}- t={t}- />- );+ })}- return (- <RoleLedgerRow- key={row.id}- row={row}- progress={rowProgress}- installed={isInstalled}- saving={saving}- onPick={onPick}- onUseRecommended={() => void useRecommended(row)}- onTune={onTune}- onCollapse={- variant === "checklist"- ? () => toggleExpanded(row.id)- : undefined- }- t={t}- />- );- })}- </div>- )}+ onUseRecommended={() => void useRecommended(row)}+ onTune={onTune}+ t={t}+ />+ ))}+ </div>+ )}- {setRoleMutation.isError && (- <p className="text-sm text-destructive">- {setRoleMutation.error instanceof Error- ? setRoleMutation.error.message- : String(setRoleMutation.error)}- </p>- )}+ {setRoleMutation.isError && (+ <p className="text-sm text-destructive">+ {setRoleMutation.error instanceof Error+ ? setRoleMutation.error.message+ : String(setRoleMutation.error)}+ </p>+ )}- {advanced.length > 0 && (- <div>- <button- type="button"- onClick={() => setMoreOpen((v) => !v)}- aria-expanded={moreOpen}- className="inline-flex items-center gap-1.5 text-xs font-medium text-muted-foreground transition-colors hover:text-foreground"+ {advanced && advancedRows.length > 0 && (+ <div>+ <button+ type="button"+ onClick={() => setMoreOpen((v) => !v)}+ aria-expanded={moreOpen}+ className="inline-flex items-center gap-1.5 text-xs font-medium text-muted-foreground transition-colors hover:text-foreground"+ >+ <ChevronDown+ className={cn(+ "h-3.5 w-3.5 transition-transform",+ moreOpen && "rotate-180",+ )}+ />+ {t("local_models.roles.more_roles")}+ </button>+ {moreOpen && (+ <div+ className="mt-2 divide-y divide-border/70 overflow-hidden rounded-lg border border-border/70"+ data-testid="roles-more">- <ChevronDown- className={cn(- "h-3.5 w-3.5 transition-transform",- moreOpen && "rotate-180",- )}- />- {t("local_models.roles.more_roles")}- </button>- {moreOpen && (- <div- className="mt-2 divide-y divide-border/70 overflow-hidden rounded-xl border border-border bg-card/60"- data-testid="roles-more"- >- {advanced.map((row) => (- <div- key={row.id}- className="grid gap-1 px-3.5 py-3 sm:grid-cols-[minmax(0,1fr)_minmax(0,2fr)] sm:items-center"- >- <div className="text-sm text-foreground">- {t(row.label_key)}- </div>- <div className="text-sm text-muted-foreground">- {row.current ? (- <span className="font-mono text-xs text-foreground/85">- {row.current}- </span>- ) : (- row.note || t("local_models.roles.follows_chat")- )}- </div>+ {advancedRows.map((row) => (+ <div+ key={row.id}+ className="grid gap-1 px-3.5 py-3 sm:grid-cols-[minmax(0,1fr)_minmax(0,2fr)] sm:items-center"+ >+ <div className="text-sm text-foreground">+ {t(row.label_key)}</div>- ))}- </div>- )}- </div>- )}- </div>- </Panel>+ <div className="text-sm text-muted-foreground">+ {row.current ? (+ <span className="font-mono text-xs text-foreground/85">+ {row.current}+ </span>+ ) : (+ row.note || t("local_models.roles.follows_chat")+ )}+ </div>+ </div>+ ))}+ </div>+ )}+ </div>+ )}+ </div>);}-function RoleLedgerRow({+/**+ * One job: what it is, what answers it now, and the picker that changes it.+ *+ * Three columns on a wide pane — name and state, picker, actions — so the+ * pickers line up as a column a user can run down. Below `lg` they stack in+ * the same order.+ */+function RoleRowView({row,+ models,progress,installed,saving,+ advanced,onPick,onUseRecommended,onTune,- onCollapse,t,}: {row: RoleRow;+ models: LocalModelRow[];progress: Progress;installed: (name: string) => boolean;saving: boolean;+ advanced: boolean;onPick: (model: string) => void;onUseRecommended: () => void;onTune?: (model: string) => void;- /** Checklist only: folds the row back into its compact line. */- onCollapse?: () => void;t: (key: string) => string;}) {const running =@@ -406,17 +381,10 @@ function RoleLedgerRow({const currentMissing = row.current !== "" && !row.installed;const canUseRecommended =row.writable && row.recommended !== "" && row.recommended !== row.current;- // The picker lists every qualifying download, plus the configured one when- // it is gone, so the gap is visible rather than silently replaced.- const choices = useMemo(() => {- const list = [...row.qualifying];- if (row.current && !list.includes(row.current)) list.unshift(row.current);- return list;- }, [row.current, row.qualifying]);return (<div- className="grid gap-3 px-3.5 py-3 lg:grid-cols-[minmax(0,1.2fr)_minmax(0,1fr)_auto] lg:items-center"+ className="grid gap-3 px-3.5 py-3 lg:grid-cols-[minmax(0,1fr)_minmax(0,1fr)_auto] lg:items-start"data-testid={`role-row-${row.id}`}><div className="min-w-0">@@ -424,30 +392,16 @@ function RoleLedgerRow({<span className="text-sm font-medium text-foreground">{t(row.label_key)}</span>- {row.required.map((cap) => (- <span- key={cap}- className="rounded-md border border-border px-1.5 py-0.5 text-[11px] uppercase tracking-[0.18em] text-muted-foreground"- >- {cap}- </span>- ))}+ {advanced &&+ row.required.map((cap) => (+ <span+ key={cap}+ className="rounded-md border border-border px-1.5 py-0.5 text-[11px] uppercase tracking-[0.18em] text-muted-foreground"+ >+ {cap}+ </span>+ ))}</div>- {row.id === "voice" && row.context_tokens ? (- <p- className="mt-1 text-xs text-muted-foreground"- data-testid="voice-context"- >- {fill(- t(- row.context_source === "manual"- ? "local_models.roles.voice_context_manual"- : "local_models.roles.voice_context_auto",- ),- { context: contextLabel(row.context_tokens) },- )}- </p>- ) : null}<div className="mt-1 text-sm">{row.current ? (<StatusDot@@ -469,35 +423,32 @@ function RoleLedgerRow({</span>)}</div>+ {row.id === "voice" && row.context_tokens ? (+ <p+ className="mt-1 text-xs text-muted-foreground"+ data-testid="voice-context"+ >+ {fill(+ t(+ row.context_source === "manual"+ ? "local_models.roles.voice_context_manual"+ : "local_models.roles.voice_context_auto",+ ),+ { context: contextLabel(row.context_tokens) },+ )}+ </p>+ ) : null}<ProgressLine progress={progress} t={t} className="mt-1.5" /></div><div className="min-w-0">{row.writable ? (- <select- aria-label={fill(t("local_models.roles.pick_label"), {- role: t(row.label_key),- })}- value={row.current}+ <RolePicker+ row={row}+ models={models}disabled={saving || running}- onChange={(e) => onPick(e.target.value)}- className="h-8 w-full rounded-md border border-border bg-background/60 px-2 text-sm text-foreground focus:outline-none focus:ring-1 focus:ring-primary disabled:opacity-50"- >- {row.id !== "embedding" && (- <option value="">{t("local_models.roles.pick_discovery")}</option>- )}- {row.id === "embedding" && !row.current && (- <option value="">{t("local_models.roles.pick_none")}</option>- )}- {choices.map((name) => (- <option key={name} value={name}>- {name}- {installed(name)- ? ""- : ` ${t("local_models.roles.pick_missing_suffix")}`}- </option>- ))}- </select>+ onPick={onPick}+ />) : (<span className="text-xs text-muted-foreground">{t("local_models.roles.read_only")}@@ -505,7 +456,7 @@ function RoleLedgerRow({)}{canUseRecommended && row.recommended_reason && (<p- className="mt-1 text-xs text-muted-foreground"+ className="mt-1.5 text-xs text-muted-foreground"data-testid="role-recommended-reason"><span className="font-mono text-foreground/85">@@ -517,7 +468,7 @@ function RoleLedgerRow({)}</div>- <div className="flex items-center gap-1.5 lg:justify-end">+ <div className="flex flex-wrap items-center gap-1.5 lg:justify-end">{canUseRecommended && (<SoftButtonprimary@@ -536,119 +487,13 @@ function RoleLedgerRow({})}</SoftButton>)}- {onTune && row.current && row.installed && (+ {advanced && onTune && row.current && row.installed && (<SoftButton onClick={() => onTune(row.current)} disabled={running}><SlidersHorizontal className="h-3.5 w-3.5" />{t("local_models.roles.tune")}</SoftButton>)}- {onCollapse && (- <SoftButton onClick={onCollapse} ariaExpanded>- <ChevronDown className="h-3.5 w-3.5" />- {t("local_models.roles.checklist_done")}- </SoftButton>- )}- </div>- </div>- );-}--/**- * The compact checklist line: dot + label + model (or "not set") + ONE- * trailing action. The line itself is a button that expands to the full row;- * the trailing action is "Use recommended" when the shortlist has a better- * pick, otherwise "Change" (which expands too).- */-function RoleChecklistRow({- row,- progress,- installed,- saving,- onUseRecommended,- onExpand,- t,-}: {- row: RoleRow;- progress: Progress;- installed: (name: string) => boolean;- saving: boolean;- onUseRecommended: () => void;- onExpand: () => void;- t: (key: string) => string;-}) {- const running =- progress.phase === "pulling" ||- progress.phase === "assigning" ||- progress.phase === "tuning";- const currentMissing = row.current !== "" && !row.installed;- const canUseRecommended =- row.writable && row.recommended !== "" && row.recommended !== row.current;- const tone: "ok" | "warn" | "off" = row.current- ? currentMissing- ? "warn"- : "ok"- : "off";- return (- <div- className="grid gap-2 px-3.5 py-2.5 sm:grid-cols-[minmax(0,1fr)_auto] sm:items-center"- data-testid={`role-row-${row.id}`}- data-variant="checklist"- >- <button- type="button"- onClick={onExpand}- aria-expanded={false}- className="flex min-w-0 items-center gap-2 text-left"- >- <ChevronRight className="h-3.5 w-3.5 shrink-0 text-muted-foreground" />- <span className="text-sm font-medium text-foreground">- {t(row.label_key)}- </span>- <StatusDot- tone={tone}- label={- row.current ? (- <span className="font-mono text-xs text-foreground/85">- {row.current}- {currentMissing && (- <span className="ml-2 font-sans text-muted-foreground">- {t("local_models.roles.not_installed")}- </span>- )}- </span>- ) : (- <span className="text-xs">- {t("local_models.roles.checklist_not_set")}- </span>- )- }- />- </button>- <div className="flex items-center gap-1.5 sm:justify-end">- {canUseRecommended ? (- <SoftButton- primary- onClick={onUseRecommended}- disabled={running || saving}- >- {running ? (- <Loader2 className="h-3.5 w-3.5 animate-spin" />- ) : (- <Sparkles className="h-3.5 w-3.5" />- )}- {installed(row.recommended)- ? t("local_models.roles.use_recommended")- : fill(t("local_models.roles.download_recommended"), {- model: row.recommended,- })}- </SoftButton>- ) : (- <SoftButton onClick={onExpand} disabled={running || saving}>- {t("local_models.roles.checklist_change")}- </SoftButton>- )}</div>- <ProgressLine progress={progress} t={t} className="sm:col-span-2" /></div>);}diff --git a/jarvis/ui/web/frontend/src/views/local-models/StepCard.tsx b/jarvis/ui/web/frontend/src/views/local-models/StepCard.tsxnew file mode 100644index 0000000000..cd02c23eed--- /dev/null+++ b/jarvis/ui/web/frontend/src/views/local-models/StepCard.tsx@@ -0,0 +1,87 @@+/**+ * A numbered step card — the shape the Local models overview is built from.+ *+ * The section answers one question in three moves: is there a server, are+ * there models, and which model does which job. Written as a dashboard that+ * reads as a wall of equal tiles, a newcomer has no idea where to start; so+ * each move is one card that carries its own ordinal, its own state and at+ * most one primary action. The ordinal turns into a check once the step is+ * satisfied, which makes "what is still missing" a glance rather than a read.+ *+ * `state` drives the ordinal only. A card is never hidden or disabled by it:+ * step 3 stays open while step 1 is unsatisfied, because someone reinstalling+ * a server still wants to see which model each job is on.+ */+import type { ReactNode } from "react";+import { Check } from "lucide-react";++import { cn } from "@/lib/utils";++export type StepState = "done" | "attention" | "todo" | "busy";++export interface StepCardProps {+ /** 1-based ordinal shown in the marker; replaced by a check when done. */+ step: number;+ title: string;+ /** One plain sentence saying what this step is for. */+ subtitle: string;+ state: StepState;+ /** The step's status line, right of the title on a wide pane. */+ status?: ReactNode;+ /** The one primary action, rendered in the header. */+ action?: ReactNode;+ children: ReactNode;+ testId?: string;+}++const MARKER: Record<StepState, string> = {+ // Emerald carries "finished cleanly" here exactly as it does in StatTile —+ // the token set has no name for it, and it needs its own value per theme.+ done: "border-emerald-500/40 bg-emerald-500/10 text-emerald-600 dark:text-emerald-400",+ attention: "border-amber-500/40 bg-amber-500/10 text-amber-600 dark:text-amber-400",+ busy: "border-primary/40 bg-primary/10 text-primary",+ todo: "border-border bg-sheen/[0.06] text-muted-foreground",+};++export function StepCard({+ step,+ title,+ subtitle,+ state,+ status,+ action,+ children,+ testId,+}: StepCardProps) {+ return (+ <section+ className="overflow-hidden rounded-xl border border-border bg-card/50"+ aria-label={title}+ data-testid={testId}+ data-step={step}+ data-state={state}+ >+ <header className="flex flex-wrap items-start gap-x-4 gap-y-3 border-b border-border/70 px-4 py-3.5">+ <span+ aria-hidden+ className={cn(+ "mt-0.5 flex h-7 w-7 shrink-0 items-center justify-center rounded-full border",+ "font-display text-[13px] font-semibold tabular-nums",+ MARKER[state],+ )}+ >+ {state === "done" ? <Check className="h-3.5 w-3.5" /> : step}+ </span>+ <div className="min-w-0 flex-1">+ <h3 className="font-display text-[15px] font-semibold tracking-tight text-foreground">+ {title}+ </h3>+ <p className="mt-0.5 text-xs text-muted-foreground">{subtitle}</p>+ {status ? <div className="mt-1.5 text-sm">{status}</div> : null}+ </div>+ {action ? <div className="flex shrink-0 items-center gap-2">{action}</div> : null}+ </header>+ <div className="px-4 py-3.5">{children}</div>+ </section>+ );+}diff --git a/tests/unit/brain/test_ollama_overview.py b/tests/unit/brain/test_ollama_overview.pyindex e9c280b234..97e6f19555 100644--- a/tests/unit/brain/test_ollama_overview.py+++ b/tests/unit/brain/test_ollama_overview.py@@ -115,20 +115,51 @@ async def test_the_disk_snapshot_paints_at_once_and_one_refresh_runs(fake, tmp_passert time.perf_counter() - started < 0.5task = ollama_overview._refresh_tasks.get(ROOT)assert task is not None and not task.done()- # A second open while the refresh runs joins it — no second task.- again, source_again = await ollama_overview.get_overview(ROOT, _cfg())- assert source_again == "cache"- assert ollama_overview._refresh_tasks.get(ROOT) is taskrefreshed = await taskassert refreshed["server"]["running"] is Falseassert "did not answer" in refreshed["inventory"]["error"]assert ROOT not in ollama_overview._refresh_tasks- # The refreshed payload is now the memo, and it reached the disk.+ # The refreshed payload is now the memo...memo, memo_source = await ollama_overview.get_overview(ROOT, _cfg())assert memo_source == "live" and memo is refreshed+ # ...but it did NOT reach the disk: a sweep with no server behind it+ # would paint a wiped machine on the next open (BUG-188), so the good+ # snapshot from the first open stays.saved = ollama_overview.load_snapshot()- assert saved is not None and saved["payload"]["server"]["running"] is False+ assert saved is not None and saved["payload"]["server"]["running"] is True+ assert [m["name"] for m in saved["payload"]["inventory"]["models"]]+++async def test_a_second_open_during_a_refresh_joins_it(fake, monkeypatch) -> None:+ """One refresh per root: a second open while one runs must not start a+ second sweep of the same server."""+ await ollama_overview.get_overview(ROOT, _cfg())+ ollama_overview._reset_for_tests()+ ollama_inventory._reset_for_tests()++ # Hold the refresh open, so "while one runs" is a fact and not a race.+ release = asyncio.Event()+ real_build = ollama_overview.build_overview++ async def _slow_build(*args: object, **kwargs: object) -> dict:+ await release.wait()+ return await real_build(*args, **kwargs) # type: ignore[arg-type]++ monkeypatch.setattr(ollama_overview, "build_overview", _slow_build)++ _payload, source = await ollama_overview.get_overview(ROOT, _cfg())+ assert source == "cache"+ task = ollama_overview._refresh_tasks.get(ROOT)+ assert task is not None and not task.done()++ _again, source_again = await ollama_overview.get_overview(ROOT, _cfg())+ assert source_again == "cache"+ assert ollama_overview._refresh_tasks.get(ROOT) is task++ release.set()+ await task+ assert ROOT not in ollama_overview._refresh_tasksasync def test_a_day_old_snapshot_is_replaced_by_a_live_build(fake) -> None:@@ -196,3 +227,57 @@ async def test_a_failing_refresh_is_logged_not_lost(fake, monkeypatch, caplog) -await asyncio.sleep(0) # let the done-callback runassert ROOT not in ollama_overview._refresh_tasksassert any("background refresh" in r.getMessage() for r in caplog.records)+++async def test_an_offline_sweep_never_becomes_the_next_open_s_snapshot(fake) -> None:+ """A sweep taken while the server is down must not replace a good one.++ What would lie if it broke: the next open paints an empty inventory, so+ every role reads "not installed", every shortlist reads "nothing fits+ this job yet", and each role's picker offers only the tag already+ configured — the machine looks wiped and nothing can be changed+ (BUG-188).+ """+ good, source = await ollama_overview.get_overview(ROOT, _cfg())+ assert source == "live"+ assert good["inventory"]["models"]+ saved_before = ollama_overview.load_snapshot()+ assert saved_before is not None++ fake.offline = True+ ollama_overview._reset_for_tests()+ ollama_inventory._reset_for_tests()+ offline, source = await ollama_overview.get_overview(ROOT, _cfg(), fresh=True)+ assert source == "live"+ # The live answer is honest about the outage...+ assert offline["inventory"]["error"]+ assert offline["inventory"]["models"] == []+ # ...and the snapshot on disk is still the one that holds real models.+ saved_after = ollama_overview.load_snapshot()+ assert saved_after == saved_before+++async def test_an_offline_snapshot_from_an_older_build_is_rebuilt_not_painted(fake) -> None:+ """A poisoned snapshot already on disk is dropped on read.++ What would lie if it broke: a file written before the guard existed keeps+ painting a wiped machine for up to STALE_AFTER_S — a day.+ """+ await ollama_overview.get_overview(ROOT, _cfg())+ poisoned = ollama_overview.load_snapshot()+ assert poisoned is not None+ poisoned["payload"]["inventory"] = {"models": [], "error": "Ollama is not answering."}+ # Straight past the guard, the way an older build wrote it.+ ollama_overview.snapshot_path().write_text(json.dumps(poisoned), encoding="utf-8")+ ollama_overview._reset_for_tests()+ ollama_inventory._reset_for_tests()++ payload, source = await ollama_overview.get_overview(ROOT, _cfg())+ assert source == "live"+ assert [m["name"] for m in payload["inventory"]["models"]]+++def test_is_paintable_only_rejects_an_inventory_error() -> None:+ assert ollama_overview.is_paintable({"inventory": {"models": [], "error": None}})+ assert ollama_overview.is_paintable({"fetched_at": 1.0}) # not a schema check+ assert not ollama_overview.is_paintable({"inventory": {"models": [], "error": "down"}})