Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
feat(local-models): the overview is a grid of model cards, then the server that runs them
rubenluetke10-beepfd534d2b39ea
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 581b702d10..ed41c8f918 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@@ -1,5 +1,36 @@{"local_models": {+ "jobs": {+ "chat_purpose": "Antwortet, wenn du tippst.",+ "tools_screen_purpose": "Liest den Bildschirm und bedient die Werkzeuge.",+ "deep_purpose": "Übernimmt die langen Aufgaben: Code, Planung, Recherche.",+ "embedding_purpose": "Macht deine Notizen durchsuchbar.",+ "voice_purpose": "Antwortet im Gespräch. Wird im Sprachserver gesetzt.",+ "voice_absent": "Noch kein Sprachserver — ein Anruf wird vom Chat-Modell beantwortet.",+ "empty": "Noch kein Modell",+ "not_on_disk": "Gesetzt, aber nicht heruntergeladen",+ "no_facts": "Größe unbekannt",+ "memory_share": "{percent} % von {gb} GB Grafikspeicher",+ "memory_over": "Größer als die {gb} GB Grafikspeicher — läuft teilweise auf dem Prozessor",+ "memory_unknown": "Grafikspeicher unbekannt",+ "memory_aria": "Belegt {percent} % des Grafikspeichers",+ "switch_to": "Auf {model} wechseln"+ },+ "launch": {+ "aria": "Server einrichten",+ "nothing_picked": "Wähle für jeden Job ein Modell — oder lass es diesen Knopf tun",+ "partly_picked": "{filled} von {total} Jobs haben ein Modell",+ "all_picked": "Jeder Job hat ein Modell",+ "total_on_disk": "{size} auf der Festplatte",+ "largest_fits": "größtes ist {size} und passt in {gb} GB Grafikspeicher",+ "largest_over": "größtes ist {size} — mehr als die {gb} GB Grafikspeicher",+ "server_running": "{server} {version} läuft",+ "server_stopped": "{server} läuft nicht",+ "server_absent": "{server} ist noch nicht installiert",+ "action_start": "{server} aufsetzen",+ "action_install": "{server} installieren und aufsetzen",+ "action_rerun": "Übernehmen und testen"+ },"title": "Lokale Modelle","subtitle": "Modelle, die auf diesem Rechner oder auf einem Server deiner Wahl laufen.","back": "API-Keys",@@ -193,32 +224,15 @@"status_unreachable": "{server} nicht erreichbar","status_remote": "{server} entfernt unter {url}","status_checking": "Server wird geprüft…",- "status_gpu": "{gb} GB Grafikspeicher",- "status_gpu_unknown": "Grafikspeicher unbekannt","status_brain_other": "{server} ist nicht dein aktives Gehirn ({brain} antwortet)","status_brain_active": "{server} ist dein aktives Gehirn",- "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","gpu_in_use": "{gb} belegt","gpu_in_use_none": "nichts belegt","loaded_expires": "läuft in {when} ab","checking": "Wird geprüft…","action_setup": "Alles einrichten",- "action_setup_hint": "Besetzt jede Rolle mit dem besten installierten Modell; lädt nur, was fehlt.","action_setup_install": "{server} installieren und alles einrichten",- "action_setup_install_hint": "Installiert den Server aus dem offiziellen Download und besetzt dann jede Rolle.","setup_planning": "Liest, was installiert ist…","setup_server_starting": "{server} wird gestartet…","setup_server_installing": "{server} wird installiert…",@@ -247,6 +261,7 @@"subtitle": "{count} Downloads · {size} auf der Platte","subtitle_one": "1 Download · {size} auf der Platte","manage": "Verwalten",+ "browse": "Modelle durchsuchen","list_label": "Installierte Modelle","empty": "Noch ist nichts installiert.","loading": "Liest die Downloads…",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 c4f850da98..8a9f960f8c 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@@ -1,5 +1,36 @@{"local_models": {+ "jobs": {+ "chat_purpose": "Answers when you type.",+ "tools_screen_purpose": "Reads the screen and works the tools.",+ "deep_purpose": "Takes the long jobs: coding, planning, research.",+ "embedding_purpose": "Turns your notes into something searchable.",+ "voice_purpose": "Answers a call. Set in the voice server.",+ "voice_absent": "No voice server yet — a call is answered by the chat model.",+ "empty": "No model yet",+ "not_on_disk": "Set, but not downloaded",+ "no_facts": "Size unknown",+ "memory_share": "{percent} % of {gb} GB graphics memory",+ "memory_over": "Larger than the {gb} GB graphics memory — runs partly on the processor",+ "memory_unknown": "Graphics memory unknown",+ "memory_aria": "Uses {percent} % of the graphics memory",+ "switch_to": "Switch to {model}"+ },+ "launch": {+ "aria": "Set up the server",+ "nothing_picked": "Pick a model for each job, or let this button do it",+ "partly_picked": "{filled} of {total} jobs have a model",+ "all_picked": "Every job has a model",+ "total_on_disk": "{size} on disk",+ "largest_fits": "largest is {size} and fits the {gb} GB graphics memory",+ "largest_over": "largest is {size}, over the {gb} GB graphics memory",+ "server_running": "{server} {version} is running",+ "server_stopped": "{server} is not running",+ "server_absent": "{server} is not installed yet",+ "action_start": "Set up {server}",+ "action_install": "Install {server} and set up",+ "action_rerun": "Apply and test"+ },"title": "Local models","subtitle": "Models that run on this machine or on a server you name.","back": "API Keys",@@ -193,32 +224,15 @@"status_unreachable": "{server} unreachable","status_remote": "{server} remote at {url}","status_checking": "Checking the server…",- "status_gpu": "{gb} GB graphics memory",- "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",- "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","gpu_in_use": "{gb} in use","gpu_in_use_none": "nothing in use","loaded_expires": "expires in {when}","checking": "Checking…","action_setup": "Set up everything",- "action_setup_hint": "Fills every role with the best installed model; downloads only what is missing.","action_setup_install": "Install {server} and set everything up",- "action_setup_install_hint": "Installs the server from its official download, then fills every role.","setup_planning": "Reading what is installed…","setup_server_starting": "Starting {server}…","setup_server_installing": "Installing {server}…",@@ -247,6 +261,7 @@"subtitle": "{count} downloads · {size} on disk","subtitle_one": "1 download · {size} on disk","manage": "Manage",+ "browse": "Browse models","list_label": "Installed models","empty": "Nothing is installed yet.","loading": "Reading the downloads…",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 81b2b678d2..49ce18242c 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@@ -1,5 +1,36 @@{"local_models": {+ "jobs": {+ "chat_purpose": "Responde cuando escribes.",+ "tools_screen_purpose": "Lee la pantalla y maneja las herramientas.",+ "deep_purpose": "Se ocupa de las tareas largas: código, planificación, investigación.",+ "embedding_purpose": "Convierte tus notas en algo que se puede buscar.",+ "voice_purpose": "Responde en una llamada. Se define en el servidor de voz.",+ "voice_absent": "Aún no hay servidor de voz: la llamada la responde el modelo de chat.",+ "empty": "Aún sin modelo",+ "not_on_disk": "Definido, pero no descargado",+ "no_facts": "Tamaño desconocido",+ "memory_share": "{percent} % de {gb} GB de memoria gráfica",+ "memory_over": "Mayor que los {gb} GB de memoria gráfica: se ejecuta en parte en el procesador",+ "memory_unknown": "Memoria gráfica desconocida",+ "memory_aria": "Ocupa el {percent} % de la memoria gráfica",+ "switch_to": "Cambiar a {model}"+ },+ "launch": {+ "aria": "Configurar el servidor",+ "nothing_picked": "Elige un modelo para cada tarea, o deja que este botón lo haga",+ "partly_picked": "{filled} de {total} tareas tienen modelo",+ "all_picked": "Cada tarea tiene modelo",+ "total_on_disk": "{size} en disco",+ "largest_fits": "el mayor ocupa {size} y cabe en {gb} GB de memoria gráfica",+ "largest_over": "el mayor ocupa {size}, más que los {gb} GB de memoria gráfica",+ "server_running": "{server} {version} está en marcha",+ "server_stopped": "{server} no está en marcha",+ "server_absent": "{server} aún no está instalado",+ "action_start": "Configurar {server}",+ "action_install": "Instalar {server} y configurar",+ "action_rerun": "Aplicar y probar"+ },"title": "Modelos locales","subtitle": "Modelos que se ejecutan en esta máquina o en un servidor que tú indiques.","back": "Claves API",@@ -193,32 +224,15 @@"status_unreachable": "{server} inaccesible","status_remote": "{server} remoto en {url}","status_checking": "Comprobando el servidor…",- "status_gpu": "{gb} GB de memoria gráfica",- "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",- "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","gpu_in_use": "{gb} en uso","gpu_in_use_none": "nada en uso","loaded_expires": "caduca en {when}","checking": "Comprobando…","action_setup": "Configurar todo",- "action_setup_hint": "Llena cada rol con el mejor modelo instalado; descarga solo lo que falta.","action_setup_install": "Instalar {server} y configurar todo",- "action_setup_install_hint": "Instala el servidor desde su descarga oficial y luego llena cada rol.","setup_planning": "Leyendo lo que está instalado…","setup_server_starting": "Iniciando {server}…","setup_server_installing": "Instalando {server}…",@@ -247,6 +261,7 @@"subtitle": "{count} descargas · {size} en disco","subtitle_one": "1 descarga · {size} en disco","manage": "Gestionar",+ "browse": "Explorar modelos","list_label": "Modelos instalados","empty": "Todavía no hay nada instalado.","loading": "Leyendo las descargas…",diff --git a/jarvis/ui/web/frontend/src/views/local-models/InstalledPanel.tsx b/jarvis/ui/web/frontend/src/views/local-models/InstalledPanel.tsxindex dcac88d3ea..2e1cfd1204 100644--- a/jarvis/ui/web/frontend/src/views/local-models/InstalledPanel.tsx+++ b/jarvis/ui/web/frontend/src/views/local-models/InstalledPanel.tsx@@ -11,7 +11,7 @@* Tune, Use-for, Unload and Delete.*/import { useMemo, type ReactNode } from "react";-import { Database } from "lucide-react";+import { Database, Search } from "lucide-react";import {Panel,@@ -35,11 +35,8 @@ 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;+ /** Opens the catalogue; the button hides without it. */+ onBrowse?: () => void;}/** The capabilities a role is gated on; the rest is noise on a one-liner. */@@ -79,7 +76,7 @@ export function InstalledPanel({loading = false,error = null,onManage,- bare = false,+ onBrowse,}: InstalledPanelProps) {const t = useT();const k = (key: string) => t(`local_models.installed.${key}`);@@ -119,11 +116,18 @@ export function InstalledPanel({size: formatGb(diskBytes),});- 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} />+ 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} />+ <div className="flex flex-wrap items-center gap-1.5">+ {onBrowse && (+ <SoftButton onClick={onBrowse} ariaLabel={k("browse")}>+ <Search className="h-3.5 w-3.5" />+ {k("browse")}+ </SoftButton>+ )}{onManage && models.length > 0 && (<SoftButton onClick={onManage} ariaLabel={k("manage")}><Database className="h-3.5 w-3.5" />@@ -131,7 +135,7 @@ export function InstalledPanel({</SoftButton>)}</div>- )}+ </div>{error && (<p@@ -213,8 +217,7 @@ export function InstalledPanel({})}</ul>)}- </div>+ </div>+ </Panel>);- if (bare) return body;- return <Panel className="p-4">{body}</Panel>;}diff --git a/jarvis/ui/web/frontend/src/views/local-models/ModelCard.tsx b/jarvis/ui/web/frontend/src/views/local-models/ModelCard.tsxnew file mode 100644index 0000000000..c2eb11e8f4--- /dev/null+++ b/jarvis/ui/web/frontend/src/views/local-models/ModelCard.tsx@@ -0,0 +1,289 @@+/**+ * One job, one card, one model.+ *+ * A local setup is not a sequence of steps — chat, tools, deep and+ * embeddings are four peers, and numbering them would claim an order that+ * does not exist. So the page is a grid of equals, and this is one tile:+ * what the job is, in a sentence a non-developer recognises; the model doing+ * it right now; and the picker that changes it.+ *+ * The card's signature is the memory bar. Every other model picker in the+ * world shows a list of names; the question that actually decides a local+ * setup is "does this fit on my graphics card". The bar answers it before+ * the download starts: the model's size against the accelerator this machine+ * reported, amber once the model is larger than the card can hold.+ *+ * `state` is derived, never passed: a card is `ready` when its model is set+ * AND on disk, `missing` when a tag is configured that is not installed,+ * `empty` when nothing is set. The border carries it, so a glance across the+ * grid says what is left to do without reading a word.+ */+import { Download, Loader2, SlidersHorizontal } from "lucide-react";++import { SoftButton } from "@/components/extensions/primitives";+import type { LocalModelRow, RoleRow } from "@/hooks/useLocalModels";+import { fill, useT } from "@/i18n";+import { cn } from "@/lib/utils";++import { formatGb } from "./localModelsFormat";+import { RolePicker } from "./RolePicker";+import type { RoleProgress } from "./useRoleActions";++export type ModelCardState = "ready" | "missing" | "empty" | "blocked";++export interface ModelCardProps {+ row: RoleRow;+ /** Every download the inventory knows; empty while the server is silent. */+ models: LocalModelRow[];+ /** Graphics memory this machine reported, in GB; 0 = unknown. */+ acceleratorGb: number;+ progress: RoleProgress;+ busy: boolean;+ onPick: (model: string) => void;+ onUseRecommended: () => void;+ /** Advanced only: opens the Tune sheet for the model on this card. */+ onTune?: (model: string) => void;+ /** Adds the required-capability badges and the Tune button. */+ advanced?: boolean;+}++/** The capabilities a job is gated on, as one short phrase. */+function capabilityLine(row: LocalModelRow | null): string {+ if (!row || !row.probed) return "";+ return row.capabilities.filter((c) => c !== "completion").join(" · ");+}++export function cardState(row: RoleRow): ModelCardState {+ // A job served by something other than Ollama says so and offers nothing.+ if (!row.writable) return "blocked";+ if (!row.current) return "empty";+ return row.installed ? "ready" : "missing";+}++const RING: Record<ModelCardState, string> = {+ ready: "border-border",+ // Amber and emerald carry meanings the token set has no name for, and each+ // needs its own value per theme — the same pairing StatTile uses.+ missing: "border-amber-500/50",+ empty: "border-dashed border-border",+ blocked: "border-border/60",+};++export function ModelCard({+ row,+ models,+ acceleratorGb,+ progress,+ busy,+ onPick,+ onUseRecommended,+ onTune,+ advanced = false,+}: ModelCardProps) {+ const t = useT();+ const state = cardState(row);+ const current = models.find((m) => m.name === row.current) ?? null;+ const sizeBytes = current?.size_bytes ?? 0;+ const budgetBytes = acceleratorGb * 1024 ** 3;+ const share = budgetBytes > 0 && sizeBytes > 0 ? sizeBytes / budgetBytes : 0;+ const overBudget = share > 1;+ const caps = capabilityLine(current);++ const canUseRecommended =+ row.writable && row.recommended !== "" && row.recommended !== row.current;+ const recommendedInstalled = models.some((m) => m.name === row.recommended);++ return (+ <article+ className={cn(+ "flex flex-col rounded-2xl border bg-card/50 p-4 transition-colors",+ RING[state],+ )}+ data-testid={`model-card-${row.id}`}+ data-state={state}+ aria-label={t(row.label_key)}+ >+ {/* The job. An eyebrow, because the job is the category and the model+ below it is the value — not the other way round. */}+ <div className="flex items-start justify-between gap-2">+ <p className="text-[11px] font-medium uppercase tracking-[0.18em] text-muted-foreground">+ {t(row.label_key)}+ </p>+ {advanced && row.required.length > 0 && (+ <div className="flex shrink-0 flex-wrap justify-end gap-1">+ {row.required.map((cap) => (+ <span+ key={cap}+ className="rounded border border-border px-1 py-px text-[10px] uppercase tracking-wider text-muted-foreground"+ >+ {cap}+ </span>+ ))}+ </div>+ )}+ </div>+ <p className="mt-1 text-xs leading-relaxed text-muted-foreground">+ {t(`local_models.jobs.${row.id}_purpose`)}+ </p>++ {/* The model. The largest thing on the card, because it is the answer+ the card exists to give. */}+ <div className="mt-3.5 min-h-[3.25rem]">+ {row.current ? (+ <>+ <p+ className="truncate font-mono text-[15px] font-medium text-foreground"+ title={row.current}+ data-testid={`model-card-current-${row.id}`}+ >+ {row.current}+ </p>+ <p className="mt-0.5 truncate text-[11px] text-muted-foreground">+ {state === "missing"+ ? t("local_models.jobs.not_on_disk")+ : [sizeBytes ? formatGb(sizeBytes) : "", caps]+ .filter(Boolean)+ .join(" · ") || t("local_models.jobs.no_facts")}+ </p>+ </>+ ) : (+ <p className="text-sm text-muted-foreground">+ {row.writable+ ? t("local_models.jobs.empty")+ : row.note || t("local_models.roles.read_only")}+ </p>+ )}+ </div>++ {/* The memory bar: this model against this machine's graphics memory. */}+ {row.writable && (+ <div className="mt-2.5" data-testid={`model-card-memory-${row.id}`}>+ <div+ className="h-1.5 overflow-hidden rounded-full bg-sheen/[0.08]"+ role="img"+ aria-label={+ share > 0+ ? fill(t("local_models.jobs.memory_aria"), {+ percent: Math.round(share * 100),+ })+ : t("local_models.jobs.memory_unknown")+ }+ >+ <div+ className={cn(+ "h-full rounded-full transition-[width] duration-500 ease-out",+ overBudget ? "bg-amber-500" : "bg-primary",+ )}+ style={{ width: `${Math.min(100, Math.round(share * 100))}%` }}+ data-testid={`model-card-memory-fill-${row.id}`}+ />+ </div>+ <p className="mt-1 text-[10px] tabular-nums text-muted-foreground">+ {share > 0+ ? overBudget+ ? fill(t("local_models.jobs.memory_over"), {+ gb: acceleratorGb.toFixed(1),+ })+ : fill(t("local_models.jobs.memory_share"), {+ percent: Math.round(share * 100),+ gb: acceleratorGb.toFixed(1),+ })+ : t("local_models.jobs.memory_unknown")}+ </p>+ </div>+ )}++ {/* The control. Always present, always the same shape. */}+ <div className="mt-3.5 space-y-2">+ {row.writable ? (+ <RolePicker+ row={row}+ models={models}+ disabled={busy}+ onPick={onPick}+ />+ ) : null}++ {canUseRecommended && (+ <SoftButton+ onClick={onUseRecommended}+ disabled={busy}+ className="h-8 w-full justify-center"+ >+ {busy ? (+ <Loader2 className="h-3.5 w-3.5 animate-spin" />+ ) : (+ <Download className="h-3.5 w-3.5" />+ )}+ {recommendedInstalled+ ? fill(t("local_models.jobs.switch_to"), {+ model: row.recommended,+ })+ : fill(t("local_models.roles.download_recommended"), {+ model: row.recommended,+ })}+ </SoftButton>+ )}++ {advanced && onTune && row.current && row.installed && (+ <SoftButton+ onClick={() => onTune(row.current)}+ disabled={busy}+ className="h-8 w-full justify-center"+ >+ <SlidersHorizontal className="h-3.5 w-3.5" />+ {t("local_models.roles.tune")}+ </SoftButton>+ )}+ </div>++ <CardProgress progress={progress} t={t} />+ </article>+ );+}++/** What the card is doing, or what it just did. One line, no chrome. */+function CardProgress({+ progress,+ t,+}: {+ progress: RoleProgress;+ t: (key: string) => string;+}) {+ if (progress.phase === "idle") return null;+ let text: string;+ let tone = "text-muted-foreground";+ switch (progress.phase) {+ case "pulling": {+ const pct =+ typeof progress.percent === "number"+ ? `${Math.round(progress.percent)} %`+ : "";+ text =+ `${t("local_models.roles.progress_pulling")} ${pct} ${progress.message ?? ""}`.trim();+ break;+ }+ case "assigning":+ text = t("local_models.roles.progress_assigning");+ break;+ case "tuning":+ text = t("local_models.roles.progress_tuning");+ break;+ case "done":+ tone = "text-emerald-600 dark:text-emerald-400";+ text = progress.readback ?? t("local_models.roles.progress_done");+ break;+ default:+ tone = "text-destructive";+ text =+ `${t("local_models.roles.progress_error")} ${progress.message ?? ""}`.trim();+ }+ return (+ <p+ className={cn("mt-2.5 text-[11px] leading-snug", tone)}+ data-testid="role-progress"+ >+ {text}+ </p>+ );+}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 997cd463e5..dfe165d0fe 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@@ -36,6 +36,7 @@ import {OverviewPanel,formatGigabytes,} from "@/views/local-models/OverviewPanel";+import { footprint } from "@/views/local-models/ServerLaunch";import type { OverviewResponse } from "@/hooks/useLocalModels";import {snapshotKey,@@ -92,6 +93,13 @@ const ROLES = [role({id: "voice",label_key: "local_models.role_voice",+ current: "qwen3.5:4b",+ installed: true,+ qualifying: ["qwen3.5:4b"],+ }),+ role({+ id: "ack",+ label_key: "local_models.role_ack",writable: false,advanced: true,current: "qwen3.5:4b",@@ -125,7 +133,7 @@ const SERVER = {interface Fixture {roles?: unknown[];- models?: Array<{ name: string }>;+ models?: Array<{ name: string; size_bytes?: number; capabilities?: string[] }>;server?: Record<string, unknown>;accelerator_gb?: number;/** "404" = a backend without the route (the four legacy reads compose);@@ -136,14 +144,14 @@ interface Fixture {function installFetchMock(fx: Fixture = {}) {const models = (fx.models ?? [{ name: "qwen3.5:4b" }]).map((m) => ({name: m.name,- size_bytes: 1,+ size_bytes: m.size_bytes ?? 1,digest: "",modified_at: "",family: "",parameter_size: "",quantization_level: "",context_length: null,- capabilities: ["completion"],+ capabilities: m.capabilities ?? ["completion"],license: "",probed: true,used_by: [],@@ -331,8 +339,28 @@ describe("formatGigabytes", () => {});});+describe("footprint", () => {+ it("counts one model once, however many jobs use it", () => {+ const models = [+ { name: "a:1", size_bytes: 4 * 1024 ** 3 },+ { name: "b:1", size_bytes: 9 * 1024 ** 3 },+ ] as Parameters<typeof footprint>[1];+ const rows = [+ { id: "chat", current: "a:1" },+ { id: "deep", current: "b:1" },+ { id: "tools_screen", current: "a:1" },+ { id: "embedding", current: "" },+ ] as Parameters<typeof footprint>[0];+ const { totalBytes, largestBytes, distinct } = footprint(rows, models);+ expect(distinct).toBe(2);+ expect(totalBytes).toBe(13 * 1024 ** 3);+ // The largest is what must sit in memory at once — not the sum.+ expect(largestBytes).toBe(9 * 1024 ** 3);+ });+});+describe("OverviewPanel paint-first", () => {- it("paints the tiles synchronously from the snapshot while the fetch never answers", () => {+ it("paints the grid synchronously from the snapshot while the fetch never answers", () => {writeOverviewSnapshot("ollama", snapshotPayload());vi.stubGlobal("fetch",@@ -341,19 +369,18 @@ describe("OverviewPanel paint-first", () => {renderPanel();// No await: the snapshot is on screen in the first render.- const disk = screen.getByRole("group", {- name: "local_models.overview.disk",- });- expect(disk.textContent).toContain("80 GB");- expect(screen.getByTestId("step-server").textContent).toContain(- "local_models.overview.status_runningOllama|0.32.15",+ expect(screen.getByTestId("model-card-chat")).toBeDefined();+ expect(screen.getByTestId("model-card-current-chat").textContent).toBe(+ "qwen3.5:4b",+ );+ expect(screen.getByTestId("server-launch").textContent).toContain(+ "local_models.launch.server_runningOllama|0.32.15",);- expect(screen.getByTestId("role-row-chat")).toBeDefined();// The refresh is underway, the snapshot is what is shown -> "Checking…".expect(screen.getByTestId("overview-checking")).toBeDefined();});- it("drops 'Checking…' and writes the snapshot once live data arrives", async () => {+ it("drops the checking line and writes the snapshot once live data arrives", async () => {writeOverviewSnapshot("ollama", snapshotPayload());installFetchMock({ overview: "live" });renderPanel();@@ -361,10 +388,6 @@ describe("OverviewPanel paint-first", () => {await waitFor(() =>expect(screen.queryByTestId("overview-checking")).toBeNull(),);- const disk = screen.getByRole("group", {- name: "local_models.overview.disk",- });- expect(disk.textContent).toContain("12 GB");const stored = JSON.parse(String(window.localStorage.getItem(snapshotKey("ollama"))),);@@ -375,7 +398,7 @@ describe("OverviewPanel paint-first", () => {const fetchMock = installFetchMock({ overview: "live" });renderPanel();- await screen.findByTestId("role-row-chat");+ await screen.findByTestId("model-card-chat");const urls = fetchMock.mock.calls.map(([u]) => String(u));expect(urls).toContain(`${BASE}/overview`);expect(urls).not.toContain(`${BASE}/roles`);@@ -386,7 +409,7 @@ describe("OverviewPanel paint-first", () => {const fetchMock = installFetchMock({ overview: "404" });renderPanel();- await screen.findByTestId("role-row-chat");+ await screen.findByTestId("model-card-chat");const urls = fetchMock.mock.calls.map(([u]) => String(u));expect(urls).toContain(`${BASE}/overview`);expect(urls).toContain(`${BASE}/roles`);@@ -396,181 +419,89 @@ describe("OverviewPanel paint-first", () => {});});-describe("OverviewPanel", () => {- it("step 1 says whether the server runs, on what hardware, and who the brain is", async () => {+describe("OverviewPanel grid", () => {+ it("shows the four jobs as peers, in reading order, each with its own picker", async () => {installFetchMock();renderPanel();- 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("16.0 GB");- expect(status.textContent).toContain(- "local_models.overview.status_brain_activeOllama",+ await screen.findByTestId("model-card-chat");+ const grid = screen.getByTestId("model-card-grid");+ const cards = [...grid.querySelectorAll("[data-testid^='model-card-']")].filter(+ (el) => el.tagName === "ARTICLE",);- // A running server satisfies step 1: the marker is a check, not a "1".- expect(status.getAttribute("data-state")).toBe("done");+ expect(cards.map((c) => c.getAttribute("data-testid"))).toEqual([+ "model-card-chat",+ "model-card-tools_screen",+ "model-card-deep",+ "model-card-embedding",+ ]);+ for (const job of ["chat", "tools_screen", "deep", "embedding"])+ expect(screen.getByTestId(`role-picker-${job}`)).toBeDefined();});- it("names the other brain in the status sentence when Ollama is not active", async () => {- installFetchMock();- mockProviders.providers = [- { id: "ollama", label: "Ollama", tier: "brain", active: false },- { id: "openrouter", label: "OpenRouter", tier: "brain", active: true },- ];+ it("carries each job's state on the card so the grid reads at a glance", async () => {+ installFetchMock({+ roles: ROLES.map((r) =>+ r.id === "deep" ? { ...r, current: "gone:7b", installed: false } : r,+ ),+ });renderPanel();- const clause = await screen.findByTestId("overview-brain-clause");- expect(clause.textContent).toBe(- "local_models.overview.status_brain_otherOllama|OpenRouter",+ await screen.findByTestId("model-card-chat");+ expect(screen.getByTestId("model-card-chat").dataset.state).toBe("ready");+ expect(screen.getByTestId("model-card-deep").dataset.state).toBe("missing");+ expect(screen.getByTestId("model-card-embedding").dataset.state).toBe(+ "empty",);- });-- it("browsing the catalogue is step 2's action", async () => {- installFetchMock();- const onBrowse = vi.fn();- renderPanel({ onBrowse });-- const models = await screen.findByTestId("step-models");- fireEvent.click(- within(models).getByRole("button", {- name: "local_models.overview.action_browse",- }),+ expect(screen.getByTestId("model-card-deep").textContent).toContain(+ "local_models.jobs.not_on_disk",);- expect(onBrowse).toHaveBeenCalledTimes(1);- });-- it("the detail level adds detail to the jobs but never takes the picker away", async () => {- installFetchMock();- 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, 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("step-server");- expect(- screen.queryByRole("button", {- name: "local_models.overview.action_browse",- }),- ).toBeNull();- expect(- screen.getByRole("button", { name: "local_models.overview.action_setup" }),- ).toBeDefined();});- it("names the install on the setup button when the server is not installed", async () => {- installFetchMock({ server: { ...SERVER, installed: false, running: false } });- renderPanel();- // The label follows the server facts, so it settles with the data.- expect(- await screen.findByRole("button", {- name: "local_models.overview.action_setup_installOllama",- }),- ).toBeDefined();- });-- it("shows the three tiles: downloads on disk, graphics memory in use, loaded now", async () => {- installFetchMock();+ it("sizes the memory bar from the model against this machine's graphics memory", async () => {+ installFetchMock({+ models: [{ name: "qwen3.5:4b", size_bytes: 4 * 1024 ** 3 }],+ accelerator_gb: 16,+ });renderPanel();- const disk = await screen.findByRole("group", {- name: "local_models.overview.disk",- });- await waitFor(() => expect(disk.textContent).toContain("12 GB"));- expect(disk.textContent).toContain("/home/x/.ollama/models");- // How many downloads there are is step 2's own status line.+ await screen.findByTestId("model-card-chat");+ const bar = screen.getByTestId("model-card-memory-chat");+ // 4 of 16 GB.+ await waitFor(() =>+ expect(bar.textContent).toContain("local_models.jobs.memory_share25|16.0"),+ );expect(- (await screen.findByTestId("step-models")).textContent,- ).toContain("local_models.overview.models_one");-- const gpu = screen.getByRole("group", {- name: "local_models.overview.gpu",- });- expect(gpu.textContent).toContain("16.0 GB");- expect(gpu.textContent).toContain("local_models.overview.gpu_in_use2.8 GB");-- const loaded = screen.getByRole("group", {- name: "local_models.overview.loaded",- });- expect(loaded.textContent).toContain("1");- expect(loaded.textContent).toContain("qwen3.5:4b");+ (screen.getByTestId("model-card-memory-fill-chat") as HTMLElement).style.width,+ ).toBe("25%");});- it("says 'unknown' for graphics memory when the probe read 0", async () => {+ it("warns on the card when the model is larger than the graphics memory", async () => {installFetchMock({- accelerator_gb: 0,- server: { ...SERVER, running: false },+ models: [{ name: "qwen3.5:4b", size_bytes: 20 * 1024 ** 3 }],+ accelerator_gb: 8,});renderPanel();- const status = await screen.findByTestId("step-server");+ await screen.findByTestId("model-card-chat");+ const bar = screen.getByTestId("model-card-memory-chat");await waitFor(() =>- expect(status.textContent).toContain(- "local_models.overview.status_stoppedOllama",- ),+ expect(bar.textContent).toContain("local_models.jobs.memory_over8.0"),);- // 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("gives every job its picker straight away, listing more than the qualifying models", async () => {- installFetchMock();- renderPanel({ advanced: true, onTune: vi.fn() });-- 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();-- // 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");+ // Clamped, not spilling out of its track.expect(- screen.getByText("local_models.roles.download_recommendedqwen3-embedding:4b"),- ).toBeDefined();-- fireEvent.click(screen.getByText("local_models.roles.more_roles"));- expect(screen.getByText("local_models.role_voice")).toBeDefined();+ (screen.getByTestId("model-card-memory-fill-chat") as HTMLElement).style.width,+ ).toBe("100%");});- it("writes the pick through PUT roles/{role}", async () => {+ it("writes a pick through PUT roles/{role}", async () => {const fetchMock = installFetchMock();renderPanel();- await screen.findByTestId("role-row-deep");- const select = screen.getByLabelText(- "local_models.roles.pick_labellocal_models.role_deep",- );- fireEvent.change(select, { target: { value: "qwen3.5:4b" } });+ await screen.findByTestId("model-card-deep");+ fireEvent.change(screen.getByTestId("role-picker-deep"), {+ target: { value: "qwen3.5:4b" },+ });await waitFor(() => {const put = fetchMock.mock.calls.find(@@ -585,11 +516,11 @@ describe("OverviewPanel", () => {});});- it("'Use recommended' pulls a missing model, assigns it, tunes silently and reads back", async () => {+ it("downloads, assigns and tunes the recommendation from the card", async () => {const fetchMock = installFetchMock();renderPanel();- await screen.findByTestId("role-row-chat");+ await screen.findByTestId("model-card-chat");// qwen3.8:27b is recommended for chat but not installed -> download label.fireEvent.click(screen.getByText("local_models.roles.download_recommendedqwen3.8:27b"),@@ -604,53 +535,103 @@ describe("OverviewPanel", () => {expect(urls).toContain(`PUT ${BASE}/models/qwen3.8%3A27b/options`);});- it("offers one setup button when nothing is installed and fills all four rows", async () => {- const fetchMock = installFetchMock({- models: [],- roles: ROLES.map((r) => ({- ...r,- current: "",- installed: false,- qualifying: [],- })),- });+ it("keeps speech out of the grid and says where it is set", async () => {+ installFetchMock();renderPanel();- await screen.findByTestId("roles-empty");- fireEvent.click(screen.getByText("local_models.roles.setup_button"));+ await screen.findByTestId("model-card-chat");+ expect(screen.queryByTestId("model-card-voice")).toBeNull();+ const voice = await screen.findByTestId("voice-row");+ expect(voice.textContent).toContain("local_models.role_voice");+ expect(voice.textContent).toContain("local_models.jobs.voice_purpose");+ });- await waitFor(() => {- const puts = fetchMock.mock.calls- .filter(- ([u, i]) =>- String(u).startsWith(`${BASE}/roles/`) &&- (i as RequestInit)?.method === "PUT",- )- .map(([u]) => String(u).split("/").pop());- expect(puts.sort()).toEqual([- "chat",- "deep",- "embedding",- "tools_screen",- ]);+ it("the detail level adds detail, never takes the picker away", async () => {+ installFetchMock();+ const { unmount } = renderPanel({ onTune: vi.fn() });+ await screen.findByTestId("model-card-chat");+ expect(screen.getByTestId("role-picker-chat")).toBeDefined();+ expect(screen.queryByText("tools")).toBeNull();+ expect(screen.queryByText("local_models.roles.tune")).toBeNull();+ expect(screen.queryByTestId("roles-more")).toBeNull();+ unmount();++ installFetchMock();+ renderPanel({ advanced: true, onTune: vi.fn() });+ await screen.findByTestId("model-card-chat");+ expect(screen.getByTestId("role-picker-chat")).toBeDefined();+ expect(screen.getAllByText("tools").length).toBeGreaterThan(0);+ expect(+ screen.getAllByText("local_models.roles.tune").length,+ ).toBeGreaterThan(0);+ // The jobs that follow another card's pick.+ expect(screen.getByTestId("roles-more").textContent).toContain(+ "local_models.role_ack",+ );+ });+});++describe("OverviewPanel launch bar", () => {+ it("adds up what the picks cost and names the largest against the card", async () => {+ installFetchMock({+ models: [+ { name: "qwen3.5:4b", size_bytes: 3 * 1024 ** 3 },+ { name: "qwen3-embedding:4b", size_bytes: 2 * 1024 ** 3 },+ ],+ accelerator_gb: 16,+ roles: ROLES.map((r) =>+ r.id === "embedding"+ ? { ...r, current: "qwen3-embedding:4b", installed: true }+ : r.id === "tools_screen" || r.id === "deep"+ ? { ...r, current: "qwen3.5:4b", installed: true }+ : r,+ ),});- const pulls = fetchMock.mock.calls- .filter(- ([u, i]) =>- String(u) === "/api/providers/ollama/pull" &&- (i as RequestInit)?.method === "POST",- )- .map(([, i]) => JSON.parse(String((i as RequestInit).body)).model);- // Every role's own pick is fetched — nothing falls back to the chat pick.- expect(pulls.sort()).toEqual([- "qwen3-embedding:4b",- "qwen3.5:4b",- "qwen3.8:27b",- ]);- await screen.findByText("local_models.overview.setup_done");+ renderPanel();++ const facts = await screen.findByTestId("launch-facts");+ // chat + tools + deep share qwen3.5:4b, embedding adds 2 GB -> 5 GB.+ await waitFor(() =>+ expect(facts.textContent).toContain(+ "local_models.launch.total_on_disk5.0 GB",+ ),+ );+ expect(facts.textContent).toContain(+ "local_models.launch.largest_fits3.0 GB|16.0",+ );+ expect(screen.getByTestId("server-launch").textContent).toContain(+ "local_models.launch.all_picked",+ );});- it("'Set up everything' keeps a role on its pick, writes the rest, then offers the brain switch", async () => {+ it("says how many jobs are still open without blocking the button", async () => {+ installFetchMock();+ renderPanel();++ const launch = await screen.findByTestId("server-launch");+ // Only chat is set in the fixture: 1 of 4.+ await waitFor(() =>+ expect(launch.textContent).toContain(+ "local_models.launch.partly_picked1|4",+ ),+ );+ const button = within(screen.getByTestId("launch-run")).getByRole("button");+ // Filling the rest is exactly what this button is for.+ expect(button.hasAttribute("disabled")).toBe(false);+ });++ it("names the install when the server is not there yet", async () => {+ installFetchMock({ server: { ...SERVER, installed: false, running: false } });+ renderPanel();++ expect(+ await screen.findByRole("button", {+ name: /local_models\.launch\.action_installOllama/,+ }),+ ).toBeDefined();+ });++ it("runs the flow, reports what it did, then offers the brain switch", async () => {const fetchMock = installFetchMock({roles: ROLES.map((r) =>r.id === "tools_screen"@@ -664,30 +645,22 @@ describe("OverviewPanel", () => {];renderPanel();- await screen.findByTestId("step-server");+ await screen.findByTestId("launch-run");fireEvent.click(- screen.getByRole("button", { name: "local_models.overview.action_setup" }),+ within(screen.getByTestId("launch-run")).getByRole("button"),);const progress = await screen.findByTestId("setup-progress");await screen.findByText("local_models.overview.setup_done");- // Chat moved to the recommended download, tools & screen kept its pick.expect(progress.textContent).toContain("local_models.overview.setup_assignedlocal_models.role_chat|qwen3.8:27b",);expect(progress.textContent).toContain("local_models.overview.setup_kept_one",);- // The proof and the boot switch are part of "done".expect(progress.textContent).toContain("local_models.verify.server — local_models.verify.ok · local_models.verify.ms12",);- expect(progress.textContent).toContain(- "local_models.verify.chat — local_models.verify.ok · qwen3.8:27b · 1.8 s",- );- expect(progress.textContent).toContain(- "local_models.verify.embedding — local_models.verify.skipped · No embedding role is configured.",- );expect(progress.textContent).toContain("local_models.overview.setup_autostart_on",);@@ -716,31 +689,40 @@ describe("OverviewPanel", () => {).toBe(true);expect(mockProviders.refetch).toHaveBeenCalled();});+});++describe("OverviewPanel notices", () => {+ it("names the active brain when it is not the local server", async () => {+ installFetchMock();+ mockProviders.providers = [+ { id: "gemini", label: "Gemini", tier: "brain", active: true },+ ];+ renderPanel({ onOpenApiKeys: vi.fn() });++ const clause = await screen.findByTestId("overview-brain-clause");+ expect(clause.textContent).toContain(+ "local_models.overview.status_brain_other" ++ "local_models.overview.status_generic_server|Gemini",+ );+ expect(clause.textContent).toContain("local_models.roles.other_brain_link");+ });++ it("does not claim the server was silent when it answered with nothing", async () => {+ installFetchMock({ models: [] });+ renderPanel();+ await screen.findByTestId("model-card-chat");+ expect(screen.queryByTestId("roles-server-silent")).toBeNull();+ });- it("lists every installed model with what uses it and what it is recommended for", async () => {+ it("lists every installed model, and offers Browse and Manage", async () => {installFetchMock({models: [{ name: "qwen3.5:4b" }, { name: "qwen3-embedding:4b" }],- roles: ROLES.map((r) =>- r.id === "embedding"- ? { ...r, recommended: "qwen3-embedding:4b" }- : r,- ),});const onManage = vi.fn();- renderPanel({ onManage });+ const onBrowse = vi.fn();+ renderPanel({ onManage, onBrowse });- await screen.findByTestId("local-models-installed");await screen.findByTestId("installed-qwen3.5:4b");- // 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(- screen.getByTestId("installed-recommended-qwen3.5:4b").textContent,- ).toContain("local_models.role_tools_screen, local_models.role_deep");expect(screen.getByTestId("installed-recommended-qwen3-embedding:4b").textContent,).toContain("local_models.role_embedding");@@ -749,18 +731,9 @@ describe("OverviewPanel", () => {screen.getByRole("button", { name: "local_models.installed.manage" }),);expect(onManage).toHaveBeenCalledTimes(1);- });-- it("names the active brain when it is not the local server", async () => {- installFetchMock();- mockProviders.providers = [- { id: "gemini", label: "Gemini", tier: "brain", active: true },- ];- const onOpenApiKeys = vi.fn();- renderPanel({ onOpenApiKeys });-- await screen.findByTestId("roles-other-brain");- fireEvent.click(screen.getByText("local_models.roles.other_brain_link"));- expect(onOpenApiKeys).toHaveBeenCalledTimes(1);+ fireEvent.click(+ screen.getByRole("button", { name: "local_models.installed.browse" }),+ );+ expect(onBrowse).toHaveBeenCalledTimes(1);});});diff --git a/jarvis/ui/web/frontend/src/views/local-models/OverviewPanel.tsx b/jarvis/ui/web/frontend/src/views/local-models/OverviewPanel.tsxindex d59713d461..ae12a1cec7 100644--- a/jarvis/ui/web/frontend/src/views/local-models/OverviewPanel.tsx+++ b/jarvis/ui/web/frontend/src/views/local-models/OverviewPanel.tsx@@ -1,34 +1,34 @@/**- * Overview — the front page of the Local models section, written as three- * steps rather than a dashboard.+ * Local models, front page: a grid of jobs, then the server that runs them.*- * 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).+ * The page answers one question — "which model does what on my machine" —+ * and it answers it the way the machine is actually shaped. Chat, tools &+ * screen, deep & coding and embeddings are four PEERS, not four steps: you+ * can fill them in any order, and a number beside each would claim a+ * sequence that does not exist. So they are a grid of equal cards+ * (`ModelCard`), each carrying its own model, its own memory bar and its own+ * picker. Speech sits below them, on its own, because it is the one job+ * served by a different server and cannot be filled from here.*- * 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.+ * Under the grid, `ServerLaunch` adds up what the picks cost and offers the+ * one button that puts a working server behind them.+ *+ * `advanced` adds capability badges, per-model Tune and the read-only jobs.+ * It never removes a control — the picker is on every card at every detail+ * level, which is half of what BUG-188 was about.** Props take `providerId` — the id of the card that declares* `supports_model_pull` — never a provider name.*/-import { useCallback, useEffect, useRef, useState, type ReactNode } from "react";-import { Cpu, HardDrive, Layers, Loader2, Search, Sparkles } from "lucide-react";+import { useCallback, useEffect, useMemo, useRef, useState } from "react";+import { Loader2 } from "lucide-react";+import { SoftButton, StatusDot } from "@/components/extensions/primitives";import {- FactRows,- SoftButton,- StatTile,- StatusDot,-} from "@/components/extensions/primitives";-import { useOverview, type LocalModelRole } from "@/hooks/useLocalModels";+ useOverview,+ type LocalModelRole,+ type RoleRow,+} from "@/hooks/useLocalModels";import { switchBrainProvider, useProviders } from "@/hooks/useProviders";import { fill, useT } from "@/i18n";import {@@ -38,26 +38,41 @@ import {import { cn } from "@/lib/utils";import { InstalledPanel } from "./InstalledPanel";-import { formatExpiry } from "./localModelsFormat";+import { canonical } from "./localSetup";import type { SetupStep, SetupSummary } from "./localSetup";-import { RolesPanel, type RolesPanelProps } from "./RolesPanel";-import { StepCard, type StepState } from "./StepCard";+import { ModelCard } from "./ModelCard";+import { ServerLaunch } from "./ServerLaunch";import { useLocalSetup } from "./useLocalSetup";+import { useRoleActions, IDLE } from "./useRoleActions";import { verifyLines } from "./verifyLines";-export interface OverviewPanelProps extends RolesPanelProps {- /** Opens the catalogue ("Browse models"); the button hides without it. */+export interface OverviewPanelProps {+ /** Id of the pull-capable provider card (found via `supports_model_pull`). */+ providerId: string;+ /** Opens the Tune sheet for one installed model; the button hides without it. */+ onTune?: (model: string) => void;+ /** Navigates to the API Keys section; shown when another brain is active. */+ onOpenApiKeys?: () => void;+ /** Opens the catalogue ("Browse models"); the link hides without it. */onBrowse?: () => void;/** Opens the full installed ledger (Advanced → Models). */onManage?: () => void;- /**- * Detail level. The switch beside the rail must change what is on screen- * HERE too, or it reads as a dead control: Advanced adds the capability- * badges, the Tune buttons and the read-only jobs.- */+ /** Adds capability badges, Tune and the read-only jobs. */advanced?: boolean;}+/**+ * The jobs the grid shows, in reading order. Four, because these are the+ * four a local server can fill on its own — speech needs the managed voice+ * server and is handled apart, and `ack`/`polish` follow other cards.+ */+export const GRID_JOBS: readonly LocalModelRole[] = [+ "chat",+ "tools_screen",+ "deep",+ "embedding",+];+/** Bytes to a short gigabyte figure ("12.4 GB"); "0 GB" below a megabyte. */export function formatGigabytes(bytes: number): string {const gb = bytes / 1024 ** 3;@@ -79,14 +94,11 @@ export function OverviewPanel({const { providers, refetch: refetchProviders } = useProviders();const setup = useLocalSetup(providerId);- // 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 inventory = overview.data?.inventory;+ const models = useMemo(() => inventory?.models ?? [], [inventory]);+ const acceleratorGb = overview.data?.recommended?.accelerator_gb ?? 0;+ const serverSilent = Boolean(inventory?.error);const marked = useRef(false);useEffect(() => {@@ -94,184 +106,142 @@ export function OverviewPanel({marked.current = true;markLocalModels(LOCAL_MODELS_MARK_FIRST_DATA);}, [overview.data]);- const remote = s?.host_kind === "remote";- const serverLabel =- providers.find((p) => p.id === providerId)?.label ||- t("local_models.overview.status_generic_server");- // --- step 1: the server ----------------------------------------------- let serverClause = t("local_models.overview.status_checking");- let serverTone: "ok" | "warn" | "error" | "busy" = "busy";- if (s) {- if (s.running) {- serverClause = s.version- ? fill(t("local_models.overview.status_running"), {- server: serverLabel,- version: s.version,- })- : fill(t("local_models.overview.status_running_noversion"), {- server: serverLabel,- });- if (remote)- serverClause = fill(t("local_models.overview.status_remote"), {- server: serverLabel,- url: s.base_url,- });- serverTone = "ok";- } else if (remote) {- serverClause = fill(t("local_models.overview.status_unreachable"), {- server: serverLabel,- });- serverTone = "warn";- } else if (!s.installed) {- serverClause = fill(t("local_models.overview.status_not_installed"), {- server: serverLabel,- });- serverTone = "warn";- } else {- serverClause = fill(t("local_models.overview.status_stopped"), {- server: serverLabel,- });- serverTone = "warn";- }- } else if (server.isError) {- serverClause = fill(t("local_models.overview.status_unreachable"), {- server: serverLabel,- });- serverTone = "error";- }+ const installedNames = useMemo(() => {+ const names = new Set<string>();+ for (const m of models) names.add(canonical(m.name));+ return names;+ }, [models]);+ const actions = useRoleActions(providerId, installedNames);- const acceleratorGb = shortlist.data?.accelerator_gb ?? 0;- const acceleratorSource = shortlist.data?.accelerator_source ?? "";+ const allRows = overview.data?.roles.roles ?? [];+ const byId = useMemo(() => {+ const map = new Map<string, RoleRow>();+ for (const row of allRows) map.set(row.id, row);+ return map;+ }, [allRows]);+ const gridRows = useMemo(+ () => GRID_JOBS.map((id) => byId.get(id)).filter((r): r is RoleRow => !!r),+ [byId],+ );+ const voiceRow = byId.get("voice") ?? null;+ // Speech has its own row above; whatever else is advanced follows another+ // card's pick and belongs in the quiet list at the bottom.+ const followerRows = allRows.filter((r) => r.advanced && r.id !== "voice");- // The brain clause only renders once the provider list is here — no gate.+ const serverLabel =+ providers.find((p) => p.id === providerId)?.label ||+ t("local_models.overview.status_generic_server");const activeBrain =providers.find((p) => p.tier === "brain" && p.active) ?? null;const otherBrainActive =activeBrain !== null && activeBrain.id !== providerId;- // --- 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`- : t("local_models.overview.gpu_unknown");- const loadedVram = s?.loaded_vram_bytes ?? 0;- const gpuHint =- acceleratorGb > 0- ? loadedVram > 0- ? fill(t("local_models.overview.gpu_in_use"), {- gb: formatGigabytes(loadedVram),- })- : t("local_models.overview.gpu_in_use_none")- : acceleratorSource- ? fill(t("local_models.overview.gpu_source"), {- source: acceleratorSource,- })- : t("local_models.overview.gpu_unknown_hint");-- const loaded = s?.running_models ?? [];- const firstExpiry = loaded.length > 0 ? formatExpiry(loaded[0].expires_at) : "";- const loadedHint =- loaded.length > 0- ? [- loaded.map((m) => m.name).join(", "),- firstExpiry- ? fill(t("local_models.overview.loaded_expires"), {- when: firstExpiry,- })- : "",- ]- .filter(Boolean)- .join(" · ")- : t("local_models.overview.loaded_none");-- // --- 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],+ (role: LocalModelRole) => t(byId.get(role)?.label_key ?? `local_models.role_${role}`),+ [byId, 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";-- // 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);- const setupLabel = needsInstall- ? fill(t("local_models.overview.action_setup_install"), {- server: serverLabel,- })- : t("local_models.overview.action_setup");+ const checking = overview.isFetching && overview.data?.source === "cache";return (<div className="space-y-4" data-testid="local-models-overview-panel">- {/* ── 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>- }- 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" />- )}- {setupLabel}- </SoftButton>- }+ {/* One line of context, never a banner: what is off, if anything is. */}+ {(otherBrainActive || serverSilent || overview.isError || checking) && (+ <div className="space-y-1.5" data-testid="overview-notices">+ {checking && (+ <span data-testid="overview-checking">+ <StatusDot+ tone="busy"+ pulse+ label={t("local_models.overview.checking")}+ />+ </span>+ )}+ {serverSilent && (+ <p+ className="text-sm text-amber-700 dark:text-amber-400"+ data-testid="roles-server-silent"+ >+ {t("local_models.roles.server_silent")}+ </p>+ )}+ {overview.isError && (+ <p className="text-sm text-destructive">+ {overview.error instanceof Error+ ? overview.error.message+ : String(overview.error)}+ </p>+ )}+ {otherBrainActive && (+ <p+ className="text-sm text-amber-700 dark:text-amber-400"+ data-testid="overview-brain-clause"+ >+ {fill(t("local_models.overview.status_brain_other"), {+ server: serverLabel,+ 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>+ )}+ </div>+ )}++ {/* The grid. Four peers, two columns on a wide pane. */}+ <div+ className="grid grid-cols-1 gap-3 md:grid-cols-2 xl:grid-cols-4"+ data-testid="model-card-grid"+ >+ {gridRows.length === 0 && overview.isLoading+ ? GRID_JOBS.map((id) => <CardSkeleton key={id} />)+ : gridRows.map((row) => (+ <ModelCard+ key={row.id}+ row={row}+ models={models}+ acceleratorGb={acceleratorGb}+ progress={actions.progress[row.id] ?? IDLE}+ busy={actions.isBusy(row.id)}+ onPick={(model) => actions.pick(row.id, model)}+ onUseRecommended={() => actions.useRecommended(row)}+ onTune={onTune}+ advanced={advanced}+ />+ ))}+ </div>++ {actions.writeError && (+ <p className="text-sm text-destructive">{actions.writeError}</p>+ )}++ {/* Speech: its own row, because it is served by its own server. */}+ {voiceRow && (+ <VoiceRow+ row={voiceRow}+ onTune={advanced ? onTune : undefined}+ t={t}+ />+ )}++ <ServerLaunch+ rows={gridRows}+ models={models}+ acceleratorGb={acceleratorGb}+ server={s}+ serverLabel={serverLabel}+ running={Boolean(s?.running)}+ busy={setup.busy}+ onRun={setup.run}>- <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><SetupProgressstep={setup.step}serverLabel={serverLabel}@@ -283,171 +253,132 @@ export function OverviewPanel({}}t={t}/>- <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",+ </ServerLaunch>++ <InstalledPanel+ models={models}+ roles={allRows}+ diskBytes={inventory?.disk_bytes ?? s?.disk_bytes ?? 0}+ loading={overview.isLoading}+ error={inventory?.error ?? null}+ onManage={onManage}+ onBrowse={onBrowse}+ />++ {advanced && followerRows.length > 0 && (+ <FollowerJobs rows={followerRows} t={t} />+ )}+ </div>+ );+}++/** A card-shaped placeholder so the grid does not jump when data lands. */+function CardSkeleton() {+ return (+ <div+ className="h-[15rem] animate-pulse rounded-2xl border border-dashed border-border bg-card/30"+ data-testid="model-card-skeleton"+ />+ );+}++/**+ * Speech. Read-only from here: the model is baked into the voice server's+ * launch command, so the row says what answers a call and where to change it+ * rather than offering a picker that would fail.+ */+function VoiceRow({+ row,+ onTune,+ t,+}: {+ row: RoleRow;+ onTune?: (model: string) => void;+ t: (key: string) => string;+}) {+ const missing = row.current !== "" && !row.installed;+ return (+ <div+ className="flex flex-wrap items-center justify-between gap-x-4 gap-y-2 rounded-xl border border-border/70 bg-card/40 px-4 py-3"+ data-testid="voice-row"+ >+ <div className="min-w-0">+ <p className="text-[11px] font-medium uppercase tracking-[0.18em] text-muted-foreground">+ {t(row.label_key)}+ </p>+ <div className="mt-1">+ {row.current ? (+ <StatusDot+ tone={missing ? "warn" : "ok"}+ label={+ <span className="font-mono text-xs text-foreground/85">+ {row.current}+ {missing && (+ <span className="ml-2 font-sans text-muted-foreground">+ {t("local_models.roles.not_installed")}+ </span>)}- 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>- ) : (- ""- ),- },- ]}- />- </StepCard>+ }+ />+ ) : (+ <span className="text-sm text-muted-foreground">+ {row.note || t("local_models.jobs.voice_absent")}+ </span>+ )}+ </div>+ </div>+ <div className="flex items-center gap-3">+ <p className="text-xs text-muted-foreground">+ {t("local_models.jobs.voice_purpose")}+ </p>+ {onTune && row.current && row.installed && (+ <SoftButton onClick={() => onTune(row.current)} className="h-8">+ {t("local_models.roles.tune")}+ </SoftButton>+ )}+ </div>+ </div>+ );+}- {/* ── 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>+/** The jobs that follow another card's pick; read-only, Advanced only. */+function FollowerJobs({+ rows,+ t,+}: {+ rows: RoleRow[];+ t: (key: string) => string;+}) {+ return (+ <div+ className="divide-y divide-border/70 overflow-hidden rounded-xl border border-border/70 bg-card/40"+ data-testid="roles-more"+ >+ {rows.map((row) => (+ <div+ key={row.id}+ className="grid gap-1 px-4 py-2.5 sm:grid-cols-[minmax(0,1fr)_minmax(0,2fr)] sm:items-center"+ >+ <span className="text-sm text-foreground">{t(row.label_key)}</span>+ <span 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 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}- />+ </span></div>- </StepCard>-- {/* ── 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>);}/**- * The set-up flow's one line under the actions: what is happening now, or- * — once it ended — what was done, in the user's words (role → model), plus+ * The set-up flow's line inside the launch bar: what is happening now, or+ * — once it ended — what was done, in the user's words (job → model), plus* the one decision the flow leaves to the user: making this server the* active brain when another one answers right now.*/@@ -470,7 +401,6 @@ function SetupProgress({const [brain, setBrain] = useState<{ state: "idle" } | { state: "switching" } | { state: "done" } | { state: "error"; message: string }>({ state: "idle" });- // A new run resets the brain line.useEffect(() => {if (step && step.phase !== "done") setBrain({ state: "idle" });}, [step]);@@ -576,7 +506,10 @@ function SetupProgress({}return (- <div className="mt-2 space-y-1 text-xs" data-testid="setup-progress">+ <div+ className="mt-3 space-y-1 border-t border-border/70 pt-3 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">@@ -615,61 +548,20 @@ function SetupProgress({{fill(k("setup_brain_button"), { server: serverLabel })}</SoftButton>{brain.state === "error" && (- <span className="text-destructive">+ <span className={cn("text-destructive")}>{fill(k("setup_brain_failed"), { message: brain.message })}</span>)}</div>)}{step.phase === "done" && brain.state === "done" && (- <p className="ml-4 text-emerald-600 dark:text-emerald-400" data-testid="setup-brain-done">+ <p+ className="ml-4 text-emerald-600 dark:text-emerald-400"+ data-testid="setup-brain-done"+ >{fill(k("setup_brain_switched"), { server: serverLabel })}</p>)}</div>);}--/** A 44 px SoftButton with icon, label and a one-line hint underneath. */-export function ActionButton({- icon,- label,- hint,- onClick,- primary,- disabled,- testId,-}: {- icon: ReactNode;- label: string;- hint: string;- onClick: () => void;- primary?: boolean;- disabled?: boolean;- testId?: string;-}) {- return (- <span data-testid={testId}>- <SoftButton- primary={primary}- onClick={onClick}- disabled={disabled}- ariaLabel={label}- className="h-11 px-3.5 text-left"- >- <span className="shrink-0">{icon}</span>- <span className="flex min-w-0 flex-col leading-tight">- <span className="text-xs font-medium">{label}</span>- <span- className={cn(- "truncate text-[11px] font-normal",- primary ? "text-primary-foreground/80" : "text-muted-foreground",- )}- >- {hint}- </span>- </span>- </SoftButton>- </span>- );-}diff --git a/jarvis/ui/web/frontend/src/views/local-models/RolesPanel.tsx b/jarvis/ui/web/frontend/src/views/local-models/RolesPanel.tsxdeleted file mode 100644index 1431db8a79..0000000000--- a/jarvis/ui/web/frontend/src/views/local-models/RolesPanel.tsx+++ /dev/null@@ -1,547 +0,0 @@-/**- * 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), 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".- *- * 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.- */-import { useCallback, useEffect, useMemo, useRef, useState } from "react";-import { ChevronDown, Loader2, SlidersHorizontal, Sparkles } from "lucide-react";--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";-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 {- /** Id of the pull-capable provider card (found via `supports_model_pull`). */- providerId: string;- /** Opens the Tune sheet for one installed model; the button hides without it. */- onTune?: (model: string) => void;- /** Navigates to the API Keys section; shown when another brain is active. */- onOpenApiKeys?: () => void;- /** 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. */- setupBusy?: boolean;-}--type Phase = "idle" | "pulling" | "assigning" | "tuning" | "done" | "error";--interface Progress {- phase: Phase;- percent?: number;- message?: string;- /** The one-sentence readback after the silent tune. */- readback?: string;-}--const WRITABLE: readonly LocalModelRole[] = [- "chat",- "voice",- "tools_screen",- "deep",- "embedding",-];--/** Human window size: 16384 -> "16k". */-function contextLabel(numCtx: number): string {- return numCtx >= 1024 ? `${Math.round(numCtx / 1024)}k` : String(numCtx);-}--export function RolesPanel({- providerId,- onTune,- onOpenApiKeys,- advanced = false,- onSetup,- setupBusy = false,-}: RolesPanelProps) {- const t = useT();- // Roles and inventory come from the one overview round-trip (painted- // first from the snapshot); the shapes below keep the rest of the panel- // reading as before.- const overview = useOverview(providerId);- const roles = {- data: overview.data?.roles,- isLoading: overview.isLoading,- isError: overview.isError,- error: overview.error,- };- const inventory = { data: overview.data?.inventory };- const { providers } = useProviders();- const setRoleMutation = useSetRole(providerId);- const invalidate = useInvalidateLocalModels(providerId);-- const [progress, setProgress] = useState<Record<string, Progress>>({});- const [moreOpen, setMoreOpen] = useState(false);-- // Async flows outlive a tab switch; nothing is written to state afterwards.- const mounted = useRef(true);- useEffect(() => {- mounted.current = true;- return () => {- mounted.current = false;- };- }, []);- 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 models) names.add(canonical(m.name));- return names;- }, [models]);- const isInstalled = useCallback(- (name: string) => installed.has(canonical(name)),- [installed],- );-- const rows = roles.data?.roles ?? [];- const primary = 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 =- providers.find((p) => p.tier === "brain" && p.active) ?? null;- const otherBrainActive =- activeBrain !== null && activeBrain.id !== providerId;-- const patch = useCallback((roleId: string, next: Progress) => {- if (!mounted.current) return;- setProgress((prev) => ({ ...prev, [roleId]: next }));- }, []);-- /** Suggested options in, one sentence out. Never fails the flow. */- const tuneSilently = useSilentTune(providerId);-- const useRecommended = useCallback(- async (row: RoleRow) => {- const model = row.recommended;- if (!model || !WRITABLE.includes(row.id as LocalModelRole)) return;- try {- if (!isInstalled(model)) {- patch(row.id, { phase: "pulling", percent: 0, message: "" });- await waitForPull(- providerId,- model,- (p) => patch(row.id, { phase: "pulling", ...p }),- alive,- );- if (!alive()) return;- }- patch(row.id, { phase: "assigning" });- await setRole(providerId, row.id as LocalModelRole, model);- patch(row.id, { phase: "tuning" });- const readback = await tuneSilently(model);- patch(row.id, { phase: "done", readback });- } catch (err) {- patch(row.id, {- phase: "error",- message: err instanceof Error ? err.message : String(err),- });- } finally {- invalidate();- }- },- [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 && !serverSilent && models.length === 0;-- return (- <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>- )}-- {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>- )}-- {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>- )}-- {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- }- advanced={advanced}- onPick={(model) =>- setRoleMutation.mutate({- role: row.id as LocalModelRole,- model,- })- }- 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>- )}-- {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"- >- {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 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>- );-}--/**- * 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,- 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;- 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;-- return (- <div- 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">- <div className="flex flex-wrap items-center gap-2">- <span className="text-sm font-medium text-foreground">- {t(row.label_key)}- </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>- <div className="mt-1 text-sm">- {row.current ? (- <StatusDot- tone={currentMissing ? "warn" : "ok"}- label={- <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-muted-foreground">- {row.note || t("local_models.roles.discovery")}- </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 ? (- <RolePicker- row={row}- models={models}- disabled={saving || running}- onPick={onPick}- />- ) : (- <span className="text-xs text-muted-foreground">- {t("local_models.roles.read_only")}- </span>- )}- {canUseRecommended && row.recommended_reason && (- <p- className="mt-1.5 text-xs text-muted-foreground"- data-testid="role-recommended-reason"- >- <span className="font-mono text-foreground/85">- {row.recommended}- </span>- {" — "}- {row.recommended_reason}- </p>- )}- </div>-- <div className="flex flex-wrap items-center gap-1.5 lg: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>- )}- {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>- )}- </div>- </div>- );-}--/** The inline progress / readback line under a row or the setup button. */-function ProgressLine({- progress,- t,- className,-}: {- progress: Progress;- t: (key: string) => string;- className?: string;-}) {- if (progress.phase === "idle") return null;- let text: string;- let tone: "busy" | "ok" | "error" = "busy";- switch (progress.phase) {- case "pulling": {- const pct =- typeof progress.percent === "number"- ? `${Math.round(progress.percent)} %`- : "";- text =- `${t("local_models.roles.progress_pulling")} ${pct} ${progress.message ?? ""}`.trim();- break;- }- case "assigning":- text = t("local_models.roles.progress_assigning");- break;- case "tuning":- text = t("local_models.roles.progress_tuning");- break;- case "done":- tone = "ok";- text = progress.readback ?? t("local_models.roles.progress_done");- break;- default:- tone = "error";- text =- `${t("local_models.roles.progress_error")} ${progress.message ?? ""}`.trim();- }- return (- <div- className={cn("flex items-center text-xs", className)}- data-testid="role-progress"- >- <StatusDot tone={tone} pulse={tone === "busy"} label={text} />- </div>- );-}diff --git a/jarvis/ui/web/frontend/src/views/local-models/ServerLaunch.tsx b/jarvis/ui/web/frontend/src/views/local-models/ServerLaunch.tsxnew file mode 100644index 0000000000..523ddced12--- /dev/null+++ b/jarvis/ui/web/frontend/src/views/local-models/ServerLaunch.tsx@@ -0,0 +1,161 @@+/**+ * The bar under the grid: what the four picks add up to, and the one button+ * that puts the server behind them.+ *+ * It closes the page the way the grid opens it. The cards ask "which model+ * for this job"; this answers "and can this machine run all of them" — the+ * total on disk, the largest single model against the graphics memory,+ * because that largest one is what has to fit at once. Then one button:+ * install or start the server, download whatever a job still needs, assign+ * every pick, tune it, prove it answers, and remember the autostart.+ *+ * The button never disables itself for an unfinished grid. A job with no+ * model is exactly what the flow is for — refusing to run until the user has+ * done the flow's own job by hand would be backwards. It only waits while a+ * run is underway.+ */+import { Loader2, Play, RotateCw } from "lucide-react";++import { SoftButton, StatusDot } from "@/components/extensions/primitives";+import type { LocalModelRow, RoleRow, ServerResponse } from "@/hooks/useLocalModels";+import { fill, useT } from "@/i18n";++import { formatGb } from "./localModelsFormat";++export interface ServerLaunchProps {+ /** The writable jobs shown in the grid. */+ rows: RoleRow[];+ models: LocalModelRow[];+ acceleratorGb: number;+ server: ServerResponse | undefined;+ /** Label of the pull-capable card ("Ollama"). */+ serverLabel: string;+ running: boolean;+ busy: boolean;+ onRun: () => void;+ children?: React.ReactNode;+}++/** Distinct models across the jobs, so one model on two jobs counts once. */+export function footprint(+ rows: RoleRow[],+ models: LocalModelRow[],+): { totalBytes: number; largestBytes: number; distinct: number } {+ const byName = new Map(models.map((m) => [m.name, m]));+ const seen = new Set<string>();+ let totalBytes = 0;+ let largestBytes = 0;+ for (const row of rows) {+ if (!row.current || seen.has(row.current)) continue;+ seen.add(row.current);+ const size = byName.get(row.current)?.size_bytes ?? 0;+ totalBytes += size;+ largestBytes = Math.max(largestBytes, size);+ }+ return { totalBytes, largestBytes, distinct: seen.size };+}++export function ServerLaunch({+ rows,+ models,+ acceleratorGb,+ server,+ serverLabel,+ running,+ busy,+ onRun,+ children,+}: ServerLaunchProps) {+ const t = useT();+ const k = (key: string) => t(`local_models.launch.${key}`);+ const { totalBytes, largestBytes } = footprint(rows, models);+ const filled = rows.filter((r) => r.current !== "").length;+ const remote = server?.host_kind === "remote";+ const needsInstall = Boolean(server && !server.installed && !remote);++ const headline =+ filled === 0+ ? k("nothing_picked")+ : filled < rows.length+ ? fill(k("partly_picked"), { filled, total: rows.length })+ : k("all_picked");++ // The largest model is what must be resident at once; the total is what the+ // downloads cost on disk. Two different questions, so two different figures.+ const budgetGb = acceleratorGb;+ const largestGb = largestBytes / 1024 ** 3;+ const fits = budgetGb > 0 && largestGb > 0 ? largestGb <= budgetGb : null;+ const facts = [+ totalBytes > 0 ? fill(k("total_on_disk"), { size: formatGb(totalBytes) }) : "",+ largestBytes > 0 && budgetGb > 0+ ? fill(k(fits ? "largest_fits" : "largest_over"), {+ size: formatGb(largestBytes),+ gb: budgetGb.toFixed(1),+ })+ : "",+ ].filter(Boolean);++ const label = needsInstall+ ? fill(k("action_install"), { server: serverLabel })+ : running+ ? k("action_rerun")+ : fill(k("action_start"), { server: serverLabel });++ return (+ <section+ className="rounded-2xl border border-border bg-card/50 p-4"+ data-testid="server-launch"+ aria-label={k("aria")}+ >+ <div className="flex flex-wrap items-start justify-between gap-x-6 gap-y-3">+ <div className="min-w-0">+ <p className="font-display text-[15px] font-semibold tracking-tight text-foreground">+ {headline}+ </p>+ {facts.length > 0 && (+ <p+ className="mt-1 text-xs text-muted-foreground"+ data-testid="launch-facts"+ >+ {facts.join(" · ")}+ </p>+ )}+ <div className="mt-1.5">+ <StatusDot+ tone={running ? "ok" : needsInstall ? "warn" : "off"}+ label={+ running+ ? fill(k("server_running"), {+ server: serverLabel,+ version: server?.version ?? "",+ }).trim()+ : needsInstall+ ? fill(k("server_absent"), { server: serverLabel })+ : fill(k("server_stopped"), { server: serverLabel })+ }+ />+ </div>+ </div>++ <span className="shrink-0" data-testid="launch-run">+ <SoftButton+ primary+ onClick={onRun}+ disabled={busy}+ className="h-11 px-5 text-sm"+ >+ {busy ? (+ <Loader2 className="h-4 w-4 animate-spin" />+ ) : running ? (+ <RotateCw className="h-4 w-4" />+ ) : (+ <Play className="h-4 w-4" />+ )}+ {label}+ </SoftButton>+ </span>+ </div>+ {children}+ </section>+ );+}diff --git a/jarvis/ui/web/frontend/src/views/local-models/StepCard.tsx b/jarvis/ui/web/frontend/src/views/local-models/StepCard.tsxdeleted file mode 100644index cd02c23eed..0000000000--- a/jarvis/ui/web/frontend/src/views/local-models/StepCard.tsx+++ /dev/null@@ -1,87 +0,0 @@-/**- * 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/jarvis/ui/web/frontend/src/views/local-models/useRoleActions.ts b/jarvis/ui/web/frontend/src/views/local-models/useRoleActions.tsnew file mode 100644index 0000000000..4f3a367517--- /dev/null+++ b/jarvis/ui/web/frontend/src/views/local-models/useRoleActions.ts@@ -0,0 +1,154 @@+/**+ * The two writes a model card can make, and the progress line they report.+ *+ * Picking a model is one PUT. "Use recommended" is a small flow — download+ * the pick when it is missing, assign it, then write the suggested options+ * silently and read back one sentence — and it has to survive the card+ * unmounting mid-download, so it lives here rather than inside the card.+ *+ * Extracted from the old roles ledger unchanged in behaviour: the cards+ * replaced the rows, the writes did not change.+ */+import { useCallback, useEffect, useRef, useState } from "react";++import {+ setRole,+ useInvalidateLocalModels,+ useSetRole,+ type LocalModelRole,+ type RoleRow,+} from "@/hooks/useLocalModels";++import { canonical, waitForPull } from "./localSetup";+import { useSilentTune } from "./useLocalSetup";++export type RolePhase =+ | "idle"+ | "pulling"+ | "assigning"+ | "tuning"+ | "done"+ | "error";++export interface RoleProgress {+ phase: RolePhase;+ percent?: number;+ message?: string;+ /** The one-sentence readback after the silent tune. */+ readback?: string;+}++export const IDLE: RoleProgress = { phase: "idle" };++/** The roles a user may write from a card. */+const WRITABLE: readonly LocalModelRole[] = [+ "chat",+ "voice",+ "tools_screen",+ "deep",+ "embedding",+];++export interface RoleActions {+ /** Progress per role id; missing means idle. */+ progress: Record<string, RoleProgress>;+ /** True while that role's flow runs — the card's controls wait. */+ isBusy: (roleId: string) => boolean;+ /** Assign a model the user picked. */+ pick: (roleId: string, model: string) => void;+ /** Download the shortlist's pick when missing, assign it, tune it. */+ useRecommended: (row: RoleRow) => void;+ /** A failed PUT, as one sentence; "" when the last write went through. */+ writeError: string;+}++export function useRoleActions(+ providerId: string,+ installedNames: ReadonlySet<string>,+): RoleActions {+ const [progress, setProgress] = useState<Record<string, RoleProgress>>({});+ const setRoleMutation = useSetRole(providerId);+ const invalidate = useInvalidateLocalModels(providerId);+ const tuneSilently = useSilentTune(providerId);++ // A download outlives a tab switch; nothing is written to state afterwards.+ const mounted = useRef(true);+ useEffect(() => {+ mounted.current = true;+ return () => {+ mounted.current = false;+ };+ }, []);+ const alive = useCallback(() => mounted.current, []);++ const patch = useCallback((roleId: string, next: RoleProgress) => {+ if (!mounted.current) return;+ setProgress((prev) => ({ ...prev, [roleId]: next }));+ }, []);++ const isInstalled = useCallback(+ (name: string) => installedNames.has(canonical(name)),+ [installedNames],+ );++ const pick = useCallback(+ (roleId: string, model: string) => {+ setRoleMutation.mutate({ role: roleId as LocalModelRole, model });+ },+ [setRoleMutation],+ );++ const useRecommended = useCallback(+ (row: RoleRow) => {+ const model = row.recommended;+ if (!model || !WRITABLE.includes(row.id as LocalModelRole)) return;+ void (async () => {+ try {+ if (!isInstalled(model)) {+ patch(row.id, { phase: "pulling", percent: 0, message: "" });+ await waitForPull(+ providerId,+ model,+ (p) => patch(row.id, { phase: "pulling", ...p }),+ alive,+ );+ if (!alive()) return;+ }+ patch(row.id, { phase: "assigning" });+ await setRole(providerId, row.id as LocalModelRole, model);+ patch(row.id, { phase: "tuning" });+ const readback = await tuneSilently(model);+ patch(row.id, { phase: "done", readback });+ } catch (err) {+ patch(row.id, {+ phase: "error",+ message: err instanceof Error ? err.message : String(err),+ });+ } finally {+ invalidate();+ }+ })();+ },+ [alive, invalidate, isInstalled, patch, providerId, tuneSilently],+ );++ const isBusy = useCallback(+ (roleId: string) => {+ const phase = progress[roleId]?.phase;+ const running =+ phase === "pulling" || phase === "assigning" || phase === "tuning";+ const saving =+ setRoleMutation.isPending && setRoleMutation.variables?.role === roleId;+ return running || saving;+ },+ [progress, setRoleMutation.isPending, setRoleMutation.variables],+ );++ const writeError = setRoleMutation.isError+ ? setRoleMutation.error instanceof Error+ ? setRoleMutation.error.message+ : String(setRoleMutation.error)+ : "";++ return { progress, isBusy, pick, useRecommended, writeError };+}