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): overview and roles — the four slots, one button each
rubenluetke10-beepb17637a94e96
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.tsxnew file mode 100644index 0000000000..0f556ce8dd--- /dev/null+++ b/jarvis/ui/web/frontend/src/views/local-models/OverviewPanel.test.tsx@@ -0,0 +1,390 @@+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import {+ cleanup,+ fireEvent,+ render,+ screen,+ waitFor,+} from "@testing-library/react";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++const { mockProviders } = vi.hoisted(() => ({+ mockProviders: {+ providers: [] as Array<Record<string, unknown>>,+ loading: false,+ error: null as string | null,+ refetch: vi.fn(async () => undefined),+ },+}));++vi.mock("@/i18n", () => ({+ // Identity translator: assertions match the keys themselves.+ useT: () => (key: string) => key,+ fill: (template: string, vars: Record<string, string | number>) =>+ `${template}${Object.values(vars).join("|")}`,+}));++// Keep the real pull helpers (they go through the faked fetch); only the+// provider list is scripted.+vi.mock("@/hooks/useProviders", async (importOriginal) => ({+ ...(await importOriginal<typeof import("@/hooks/useProviders")>()),+ useProviders: () => mockProviders,+}));++import {+ OverviewPanel,+ formatGigabytes,+} from "@/views/local-models/OverviewPanel";++const BASE = "/api/providers/ollama/local-models";++function role(overrides: Partial<Record<string, unknown>>) {+ return {+ id: "chat",+ label_key: "local_models.role_chat",+ config_key: "brain.providers.ollama.model",+ current: "",+ installed: false,+ required: ["tools"],+ recommended_capabilities: [],+ qualifying: [],+ recommended: "",+ writable: true,+ advanced: false,+ note: "",+ ...overrides,+ };+}++const ROLES = [+ role({+ id: "chat",+ current: "qwen3.5:4b",+ installed: true,+ qualifying: ["qwen3.5:4b"],+ recommended: "qwen3.8:27b",+ }),+ role({+ id: "tools_screen",+ label_key: "local_models.role_tools_screen",+ required: ["tools", "vision"],+ recommended: "qwen3.5:4b",+ qualifying: ["qwen3.5:4b"],+ }),+ role({+ id: "deep",+ label_key: "local_models.role_deep",+ recommended: "qwen3.5:4b",+ qualifying: ["qwen3.5:4b"],+ }),+ role({+ id: "embedding",+ label_key: "local_models.role_embedding",+ required: ["embedding"],+ recommended: "qwen3-embedding:4b",+ }),+ role({+ id: "voice",+ label_key: "local_models.role_voice",+ writable: false,+ advanced: true,+ current: "qwen3.5:4b",+ installed: true,+ }),+];++const SERVER = {+ installed: true,+ binary: "ollama",+ running: true,+ version: "0.32.15",+ detail: "",+ base_url: "http://127.0.0.1:11434",+ host_kind: "local",+ models_dir: "/home/x/.ollama/models",+ running_models: [+ {+ name: "qwen3.5:4b",+ size_bytes: 1,+ size_vram_bytes: 3_000_000_000,+ expires_at: "",+ context_length: 8192,+ digest: "",+ },+ ],+ disk_bytes: 12 * 1024 ** 3,+ loaded_vram_bytes: 3_000_000_000,+ error: null,+};++interface Fixture {+ roles?: unknown[];+ models?: Array<{ name: string }>;+ server?: Record<string, unknown>;+ accelerator_gb?: number;+}++function installFetchMock(fx: Fixture = {}) {+ const models = (fx.models ?? [{ name: "qwen3.5:4b" }]).map((m) => ({+ name: m.name,+ size_bytes: 1,+ digest: "",+ modified_at: "",+ family: "",+ parameter_size: "",+ quantization_level: "",+ context_length: null,+ capabilities: ["completion"],+ license: "",+ probed: true,+ used_by: [],+ loaded: false,+ size_vram_bytes: 0,+ expires_at: "",+ running_context_length: null,+ }));+ const ok = (body: unknown) =>+ ({ ok: true, status: 200, json: async () => body }) as Response;+ const fetchMock = vi.fn(+ async (input: RequestInfo | URL, init?: RequestInit) => {+ const url = String(input);+ const method = init?.method ?? "GET";+ if (url === `${BASE}/roles`)+ return ok({+ provider: "ollama",+ server: "",+ roles: fx.roles ?? ROLES,+ error: null,+ });+ if (url === `${BASE}/inventory`)+ return ok({+ provider: "ollama",+ server: "",+ models,+ running: [],+ disk_bytes: 0,+ loaded_vram_bytes: 0,+ error: null,+ });+ if (url === `${BASE}/server`) return ok(fx.server ?? SERVER);+ if (url === `${BASE}/catalog/recommended`)+ return ok({+ server: "",+ server_reachable: true,+ message: "",+ memory_gb: 32,+ accelerator_gb: fx.accelerator_gb ?? 16,+ accelerator_source: "nvidia-smi",+ models: [],+ installed: [],+ curated_reviewed_on: "2026-08-24",+ });+ if (url.startsWith(`${BASE}/roles/`) && method === "PUT")+ return ok({+ ok: true,+ role: url.split("/").pop(),+ model: JSON.parse(String(init?.body)).model,+ config_key: "",+ message: "",+ });+ if (url === "/api/providers/ollama/pull" && method === "POST")+ return ok({+ state: "running",+ model: JSON.parse(String(init?.body)).model,+ message: "",+ });+ if (url.startsWith("/api/providers/ollama/pull/status"))+ return ok({ state: "done", model: "", message: "", percent: 100 });+ if (url.endsWith("/suggested-options"))+ return ok({+ model: "",+ options: { num_ctx: 16384, num_gpu: 999, keep_alive: "30m" },+ reasons: ["fits"],+ size_gb: 3.4,+ native_context: 262144,+ accelerator_gb: 16,+ accelerator_source: "nvidia-smi",+ ram_gb: 32,+ });+ if (url.endsWith("/options") && method === "PUT")+ return ok({+ model: "",+ options: JSON.parse(String(init?.body)),+ configured: true,+ profile_alias: null,+ });+ throw new Error(`unexpected fetch: ${method} ${url}`);+ },+ );+ vi.stubGlobal("fetch", fetchMock);+ return fetchMock;+}++function renderPanel(props: Partial<Parameters<typeof OverviewPanel>[0]> = {}) {+ const qc = new QueryClient({ defaultOptions: { queries: { retry: false } } });+ return render(+ <QueryClientProvider client={qc}>+ <OverviewPanel providerId="ollama" {...props} />+ </QueryClientProvider>,+ );+}++beforeEach(() => {+ mockProviders.providers = [+ { id: "ollama", label: "Ollama", tier: "brain", active: true },+ ];+});++afterEach(() => {+ cleanup();+ vi.unstubAllGlobals();+ vi.clearAllMocks();+});++describe("formatGigabytes", () => {+ it("rounds sensibly", () => {+ expect(formatGigabytes(0)).toBe("0 GB");+ expect(formatGigabytes(12 * 1024 ** 3)).toBe("12 GB");+ expect(formatGigabytes(3.45 * 1024 ** 3)).toBe("3.5 GB");+ expect(formatGigabytes(50 * 1024 ** 2)).toBe("50 MB");+ });+});++describe("OverviewPanel", () => {+ it("shows the four tiles from the server and the shortlist", async () => {+ installFetchMock();+ renderPanel();++ await screen.findByText("local_models.overview.server_running");+ expect(screen.getByText("16.0 GB")).toBeDefined();+ expect(screen.getByText("12 GB")).toBeDefined();+ const loaded = screen.getByRole("group", {+ name: "local_models.overview.loaded",+ });+ expect(loaded.textContent).toContain("1");+ expect(loaded.textContent).toContain("qwen3.5:4b");+ });++ it("says 'unknown' for graphics memory when the probe read 0", async () => {+ installFetchMock({+ accelerator_gb: 0,+ server: { ...SERVER, running: false },+ });+ renderPanel();++ await screen.findByText("local_models.overview.server_stopped");+ expect(screen.getByText("local_models.overview.gpu_unknown")).toBeDefined();+ });++ it("renders the four writable rows, badges, and hides the read-only ones under More roles", async () => {+ installFetchMock();+ renderPanel({ 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();+ expect(screen.getByText("qwen3.5:4b", { selector: "span" })).toBeDefined();+ expect(screen.getAllByText("tools").length).toBeGreaterThan(0);+ expect(screen.getByText("local_models.roles.tune")).toBeDefined();++ fireEvent.click(screen.getByText("local_models.roles.more_roles"));+ expect(screen.getByText("local_models.role_voice")).toBeDefined();+ });++ it("writes the pick through PUT roles/{role}", 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 waitFor(() => {+ const put = fetchMock.mock.calls.find(+ ([u, i]) =>+ String(u) === `${BASE}/roles/deep` &&+ (i as RequestInit)?.method === "PUT",+ );+ expect(put).toBeDefined();+ expect(JSON.parse(String((put![1] as RequestInit).body))).toEqual({+ model: "qwen3.5:4b",+ });+ });+ });++ it("'Use recommended' pulls a missing model, assigns it, tunes silently and reads back", async () => {+ const fetchMock = installFetchMock();+ renderPanel();++ await screen.findByTestId("role-row-chat");+ // qwen3.8:27b is recommended for chat but not installed -> download label.+ fireEvent.click(+ screen.getByText("local_models.roles.download_recommendedqwen3.8:27b"),+ );++ await screen.findByText("local_models.roles.readback_gpu16k");+ const urls = fetchMock.mock.calls.map(+ ([u, i]) => `${(i as RequestInit)?.method ?? "GET"} ${String(u)}`,+ );+ expect(urls).toContain("POST /api/providers/ollama/pull");+ expect(urls).toContain(`PUT ${BASE}/roles/chat`);+ 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: [],+ })),+ });+ renderPanel();++ await screen.findByTestId("roles-empty");+ fireEvent.click(screen.getByText("local_models.roles.setup_button"));++ 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",+ ]);+ });+ 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);+ expect(pulls.sort()).toEqual(["qwen3-embedding:4b", "qwen3.8:27b"]);+ });++ 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);+ });+});diff --git a/jarvis/ui/web/frontend/src/views/local-models/OverviewPanel.tsx b/jarvis/ui/web/frontend/src/views/local-models/OverviewPanel.tsxnew file mode 100644index 0000000000..2a6ac329dd--- /dev/null+++ b/jarvis/ui/web/frontend/src/views/local-models/OverviewPanel.tsx@@ -0,0 +1,147 @@+/**+ * Overview — the Simple-mode front page of the Local models section.+ *+ * Four headline tiles (server state, graphics memory, disk used by models,+ * what is loaded right now) over the Roles ledger. The tiles read `GET server`+ * and the shortlist's accelerator facts; nothing here writes. The roles part+ * is `RolesPanel`, mounted underneath so the integration wires one component.+ *+ * Props take `providerId` — the id of the card that declares+ * `supports_model_pull` — never a provider name.+ */+import { Cpu, HardDrive, Layers, Server } from "lucide-react";++import { StatTile } from "@/components/extensions/primitives";+import { useCatalogRecommended, useServer } from "@/hooks/useLocalModels";+import { fill, useT } from "@/i18n";++import { RolesPanel, type RolesPanelProps } from "./RolesPanel";++export type OverviewPanelProps = RolesPanelProps;++/** 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;+ if (gb >= 10) return `${gb.toFixed(0)} GB`;+ if (gb >= 0.1) return `${gb.toFixed(1)} GB`;+ return bytes > 0 ? `${(bytes / 1024 ** 2).toFixed(0)} MB` : "0 GB";+}++export function OverviewPanel({+ providerId,+ onTune,+ onOpenApiKeys,+}: OverviewPanelProps) {+ const t = useT();+ const server = useServer(providerId);+ const shortlist = useCatalogRecommended(providerId);++ const s = server.data;+ const remote = s?.host_kind === "remote";+ let serverValue = t("local_models.overview.server_unknown");+ let serverHint: string = s?.detail ?? "";+ let serverTone: "ok" | "warn" | "danger" | "primary" | "success" = "primary";+ if (s) {+ if (s.running) {+ serverValue = remote+ ? t("local_models.overview.server_remote")+ : t("local_models.overview.server_running");+ serverHint = [+ s.version+ ? fill(t("local_models.overview.server_version"), {+ version: s.version,+ })+ : "",+ s.base_url,+ ]+ .filter(Boolean)+ .join(" · ");+ serverTone = "success";+ } else if (remote) {+ serverValue = t("local_models.overview.server_unreachable");+ serverHint = s.error ?? s.detail ?? s.base_url;+ serverTone = "warn";+ } else if (!s.installed) {+ serverValue = t("local_models.overview.server_not_installed");+ serverTone = "warn";+ } else {+ serverValue = t("local_models.overview.server_stopped");+ serverTone = "warn";+ }+ } else if (server.isError) {+ serverValue = t("local_models.overview.server_unreachable");+ serverHint =+ server.error instanceof Error+ ? server.error.message+ : String(server.error);+ serverTone = "danger";+ }++ const acceleratorGb = shortlist.data?.accelerator_gb ?? 0;+ const acceleratorSource = shortlist.data?.accelerator_source ?? "";+ const gpuValue =+ acceleratorGb > 0+ ? `${acceleratorGb.toFixed(1)} GB`+ : t("local_models.overview.gpu_unknown");+ const gpuHint =+ acceleratorGb > 0 && acceleratorSource+ ? fill(t("local_models.overview.gpu_source"), {+ source: acceleratorSource,+ })+ : t("local_models.overview.gpu_unknown_hint");++ const loaded = s?.running_models ?? [];+ const loadedHint =+ loaded.length > 0+ ? loaded.map((m) => m.name).join(", ")+ : t("local_models.overview.loaded_none");++ return (+ <div className="space-y-4" data-testid="local-models-overview-panel">+ <div className="grid grid-cols-2 gap-3 xl:grid-cols-4">+ <StatTile+ icon={<Server className="h-3.5 w-3.5" />}+ label={t("local_models.overview.server")}+ value={serverValue}+ hint={serverHint}+ tone={serverTone}+ 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={shortlist.isLoading}+ />+ <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={<Layers className="h-3.5 w-3.5" />}+ label={t("local_models.overview.loaded")}+ value={String(loaded.length)}+ hint={+ loaded.length > 0+ ? `${loadedHint} · ${formatGigabytes(s?.loaded_vram_bytes ?? 0)}`+ : loadedHint+ }+ tone="primary"+ loading={server.isLoading}+ />+ </div>++ <RolesPanel+ providerId={providerId}+ onTune={onTune}+ onOpenApiKeys={onOpenApiKeys}+ />+ </div>+ );+}diff --git a/jarvis/ui/web/frontend/src/views/local-models/RolesPanel.tsx b/jarvis/ui/web/frontend/src/views/local-models/RolesPanel.tsxnew file mode 100644index 0000000000..6d7bc5a2eb--- /dev/null+++ b/jarvis/ui/web/frontend/src/views/local-models/RolesPanel.tsx@@ -0,0 +1,635 @@+/**+ * Roles — the four model slots Jarvis fills from the local server, one row+ * each, one primary action each.+ *+ * Chat & voice, Tools & screen, Deep & coding and Embeddings come from+ * `GET roles`; every row shows the configured pick (or the discovery+ * sentence), the capabilities the slot requires, a picker over the installed+ * models that qualify, and "Use recommended" — which downloads the pick when+ * it is missing, assigns it, then writes the suggested options silently and+ * reads back one sentence. The read-only advanced roles hide under+ * "More roles". When nothing is installed at all, the ledger collapses into a+ * single "Set up the recommended models" button.+ *+ * Props take `providerId` (the pull-capable card's id) rather than the whole+ * descriptor so the panel can be mounted from anywhere the id is known. The+ * "Tune" button only calls `onTune(model)` — the sheet belongs to the caller.+ */+import { useCallback, useEffect, useMemo, useRef, useState } from "react";+import {+ ChevronDown,+ Loader2,+ SlidersHorizontal,+ Sparkles,+} from "lucide-react";++import {+ Panel,+ PanelHeader,+ SoftButton,+ StatusDot,+} from "@/components/extensions/primitives";+import {+ getSuggestedOptions,+ modelPullStatus,+ saveModelOptions,+ setRole,+ startModelPull,+ useInvalidateLocalModels,+ useInventory,+ useRoles,+ useSetRole,+ type LocalModelRole,+ type RoleRow,+ type SuggestedOptionsResponse,+} from "@/hooks/useLocalModels";+import { useProviders } from "@/hooks/useProviders";+import { fill, useT } from "@/i18n";+import { cn } from "@/lib/utils";++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;+}++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",+ "tools_screen",+ "deep",+ "embedding",+];+const POLL_MS = 2000;++/** "qwen3.5" and "qwen3.5:latest" are the same download. */+function canonical(name: string): string {+ return name.endsWith(":latest") ? name.slice(0, -":latest".length) : name;+}++/** Poll one download until the server reports it done; throws on error. */+async function waitForPull(+ providerId: string,+ model: string,+ onProgress: (p: { percent?: number; message: string }) => void,+ alive: () => boolean,+): Promise<void> {+ await startModelPull(providerId, model);+ for (;;) {+ if (!alive()) return;+ const pull = await modelPullStatus(providerId, model);+ if (pull.state === "done") return;+ if (pull.state === "error")+ throw new Error(pull.message || "download failed");+ onProgress({ percent: pull.percent, message: pull.message });+ await new Promise((resolve) => window.setTimeout(resolve, POLL_MS));+ }+}++/** 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,+}: RolesPanelProps) {+ const t = useT();+ const roles = useRoles(providerId);+ const inventory = useInventory(providerId);+ const { providers } = useProviders();+ const setRoleMutation = useSetRole(providerId);+ const invalidate = useInvalidateLocalModels(providerId);++ const [progress, setProgress] = useState<Record<string, Progress>>({});+ const [setup, setSetup] = useState<Progress>({ phase: "idle" });+ 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 installed = useMemo(() => {+ const names = new Set<string>();+ for (const m of inventory.data?.models ?? []) names.add(canonical(m.name));+ return names;+ }, [inventory.data]);+ const isInstalled = useCallback(+ (name: string) => installed.has(canonical(name)),+ [installed],+ );++ const rows = roles.data?.roles ?? [];+ const primary = rows.filter((r) => !r.advanced);+ const advanced = 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 readbackFor = useCallback(+ (s: SuggestedOptionsResponse): string => {+ const ctx = s.options.num_ctx;+ if (typeof ctx === "number") {+ const key =+ s.options.num_gpu != null+ ? "local_models.roles.readback_gpu"+ : "local_models.roles.readback_ctx";+ return fill(t(key), { ctx: contextLabel(ctx) });+ }+ return s.reasons[0] ?? t("local_models.roles.readback_defaults");+ },+ [t],+ );++ 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 = useCallback(+ async (model: string): Promise<string> => {+ try {+ const suggested = await getSuggestedOptions(providerId, model);+ await saveModelOptions(providerId, model, suggested.options);+ return readbackFor(suggested);+ } catch (err) {+ // The slot is already assigned; a failed tune only loses the readback.+ console.warn(+ "[local-models] suggested options not applied",+ model,+ err,+ );+ return t("local_models.roles.tune_skipped");+ }+ },+ [providerId, readbackFor, t],+ );++ 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],+ );++ /** Empty state: the chat pick and the embedding pick, then all four rows. */+ const setupRecommended = useCallback(async () => {+ const byId = new Map(primary.map((r) => [r.id, r]));+ const chatPick = byId.get("chat")?.recommended ?? "";+ const embedPick = byId.get("embedding")?.recommended ?? "";+ const pulls = Array.from(new Set([chatPick, embedPick].filter(Boolean)));+ if (pulls.length === 0) return;+ const setSafe = (next: Progress) => {+ if (mounted.current) setSetup(next);+ };+ try {+ for (const model of pulls) {+ if (isInstalled(model)) continue;+ setSafe({ phase: "pulling", percent: 0, message: model });+ await waitForPull(+ providerId,+ model,+ (p) =>+ setSafe({+ phase: "pulling",+ percent: p.percent,+ message: `${model} ${p.message}`.trim(),+ }),+ alive,+ );+ if (!alive()) return;+ }+ setSafe({ phase: "assigning" });+ const readbacks: string[] = [];+ for (const roleId of WRITABLE) {+ const row = byId.get(roleId);+ if (!row) continue;+ const fallback = roleId === "embedding" ? embedPick : chatPick;+ const model =+ row.recommended && pulls.includes(row.recommended)+ ? row.recommended+ : fallback;+ if (!model) continue;+ await setRole(providerId, roleId, model);+ }+ setSafe({ phase: "tuning" });+ for (const model of pulls)+ readbacks.push(`${model}: ${await tuneSilently(model)}`);+ setSafe({ phase: "done", readback: readbacks.join(" ") });+ } catch (err) {+ setSafe({+ phase: "error",+ message: err instanceof Error ? err.message : String(err),+ });+ } finally {+ invalidate();+ }+ }, [alive, invalidate, isInstalled, primary, providerId, tuneSilently]);++ const nothingInstalled =+ inventory.data !== undefined &&+ !inventory.data.error &&+ inventory.data.models.length === 0;+ const busy =+ setup.phase === "pulling" ||+ setup.phase === "assigning" ||+ setup.phase === "tuning";++ return (+ <Panel className="p-4">+ <div className="space-y-3" data-testid="local-models-roles">+ <PanelHeader+ title={t("local_models.roles.title")}+ subtitle={t("local_models.roles.subtitle")}+ />++ {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>+ )}++ {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 && (+ <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={() => void setupRecommended()}+ disabled={busy}+ >+ {busy ? (+ <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>+ <ProgressLine+ progress={setup}+ t={t}+ className="mt-3 justify-center"+ />+ </div>+ )}++ {primary.length > 0 && (+ <div+ className="divide-y divide-border/70 overflow-hidden rounded-xl border border-border bg-card/60"+ data-testid="roles-ledger"+ >+ {primary.map((row) => (+ <RoleLedgerRow+ key={row.id}+ row={row}+ progress={progress[row.id] ?? { phase: "idle" }}+ installed={isInstalled}+ saving={+ setRoleMutation.isPending &&+ setRoleMutation.variables?.role === row.id+ }+ 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.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-xl border border-border bg-card/60"+ data-testid="roles-more"+ >+ {advanced.map((row) => (+ <div+ key={row.id}+ className="grid gap-1 px-3.5 py-3 sm:grid-cols-[minmax(0,1fr)_minmax(0,2fr)] sm:items-center"+ >+ <div className="text-sm text-foreground">+ {t(row.label_key)}+ </div>+ <div className="text-sm text-muted-foreground">+ {row.current ? (+ <span className="font-mono text-xs text-foreground/85">+ {row.current}+ </span>+ ) : (+ row.note || t("local_models.roles.follows_chat")+ )}+ </div>+ </div>+ ))}+ </div>+ )}+ </div>+ )}+ </div>+ </Panel>+ );+}++function RoleLedgerRow({+ row,+ progress,+ installed,+ saving,+ onPick,+ onUseRecommended,+ onTune,+ t,+}: {+ row: RoleRow;+ progress: Progress;+ installed: (name: string) => boolean;+ saving: 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;+ // The picker lists every qualifying download, plus the configured one when+ // it is gone, so the gap is visible rather than silently replaced.+ const choices = useMemo(() => {+ const list = [...row.qualifying];+ if (row.current && !list.includes(row.current)) list.unshift(row.current);+ return list;+ }, [row.current, row.qualifying]);++ return (+ <div+ className="grid gap-3 px-3.5 py-3 lg:grid-cols-[minmax(0,1.2fr)_minmax(0,1fr)_auto] lg:items-center"+ 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>+ {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>+ <ProgressLine progress={progress} t={t} className="mt-1.5" />+ </div>++ <div className="min-w-0">+ {row.writable ? (+ <select+ aria-label={fill(t("local_models.roles.pick_label"), {+ role: t(row.label_key),+ })}+ value={row.current}+ disabled={saving || running}+ onChange={(e) => onPick(e.target.value)}+ className="h-8 w-full rounded-md border border-border bg-background/60 px-2 text-sm text-foreground focus:outline-none focus:ring-1 focus:ring-primary disabled:opacity-50"+ >+ {row.id !== "embedding" && (+ <option value="">{t("local_models.roles.pick_discovery")}</option>+ )}+ {row.id === "embedding" && !row.current && (+ <option value="">{t("local_models.roles.pick_none")}</option>+ )}+ {choices.map((name) => (+ <option key={name} value={name}>+ {name}+ {installed(name)+ ? ""+ : ` ${t("local_models.roles.pick_missing_suffix")}`}+ </option>+ ))}+ </select>+ ) : (+ <span className="text-xs text-muted-foreground">+ {t("local_models.roles.read_only")}+ </span>+ )}+ </div>++ <div className="flex 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>+ )}+ {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>+ );+}