Skip to content

Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.

feat(local-models): the model ledger and the Tune sheet

rubenluetke10-beep72d19ba17950
diff --git a/jarvis/ui/web/frontend/src/views/local-models/InventoryPanel.test.tsx b/jarvis/ui/web/frontend/src/views/local-models/InventoryPanel.test.tsx
new file mode 100644
index 0000000000..693f7f6bf9
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/views/local-models/InventoryPanel.test.tsx
@@ -0,0 +1,385 @@
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import {
+ cleanup,
+ fireEvent,
+ render,
+ screen,
+ waitFor,
+ within,
+} from "@testing-library/react";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+vi.mock("@/i18n", () => ({
+ // Identity translator: assertions match the keys themselves.
+ useT: () => (key: string) => key,
+ useUiLanguage: () => "en",
+ // Keys carry no placeholders, so the variables are appended instead — that
+ // keeps two "Use for …" entries distinguishable by their role.
+ fill: (template: string, vars: Record<string, string | number>) =>
+ `${template} ${Object.values(vars).join(" ")}`.trim(),
+}));
+
+// The sheet has its own tests; here only its mount matters.
+vi.mock("./TuneSheet", () => ({
+ TuneSheet: ({ model }: { model: { name: string } }) => (
+ <div data-testid={`tune-stub-${model.name}`} />
+ ),
+}));
+
+import { InventoryPanel } from "./InventoryPanel";
+
+interface RouteResult {
+ status?: number;
+ body: unknown;
+}
+
+type Handler = (
+ method: string,
+ url: string,
+ body: unknown,
+) => RouteResult | undefined;
+
+const calls: { url: string; method: string; body: unknown }[] = [];
+
+function installFetch(handler: Handler) {
+ calls.length = 0;
+ const fetchMock = vi.fn(
+ async (input: RequestInfo | URL, init?: RequestInit) => {
+ const url = String(input);
+ const method = (init?.method ?? "GET").toUpperCase();
+ let body: unknown = null;
+ if (typeof init?.body === "string") body = JSON.parse(init.body);
+ calls.push({ url, method, body });
+ const res = handler(method, url, body);
+ if (!res) throw new Error(`unexpected fetch ${method} ${url}`);
+ const status = res.status ?? 200;
+ return {
+ ok: status >= 200 && status < 300,
+ status,
+ json: async () => res.body,
+ text: async () => JSON.stringify(res.body),
+ } as Response;
+ },
+ );
+ (globalThis as unknown as { fetch: typeof fetch }).fetch =
+ fetchMock as unknown as typeof fetch;
+}
+
+const ROW = {
+ name: "qwen3.5:4b",
+ size_bytes: 3 * 1024 ** 3,
+ digest: "abcdef0123456789",
+ modified_at: "2026-08-20T10:00:00Z",
+ family: "qwen3",
+ parameter_size: "4.0B",
+ quantization_level: "Q4_K_M",
+ context_length: 131072,
+ capabilities: ["completion", "tools", "thinking"],
+ license: "Apache-2.0",
+ probed: true,
+ used_by: ["chat"],
+ loaded: true,
+ size_vram_bytes: 2 * 1024 ** 3,
+ expires_at: new Date(Date.now() + 5 * 60_000).toISOString(),
+ running_context_length: 16384,
+};
+
+const EMBED = {
+ ...ROW,
+ name: "embeddinggemma:latest",
+ family: "gemma",
+ parameter_size: "300M",
+ capabilities: ["embedding"],
+ used_by: [],
+ loaded: false,
+ size_vram_bytes: 0,
+ expires_at: "",
+ size_bytes: 600 * 1024 ** 2,
+};
+
+function inventoryBody(models = [ROW, EMBED]) {
+ return {
+ provider: "ollama",
+ server: "http://127.0.0.1:11434",
+ models,
+ running: models
+ .filter((m) => m.loaded)
+ .map((m) => ({
+ name: m.name,
+ size_bytes: m.size_bytes,
+ size_vram_bytes: m.size_vram_bytes,
+ expires_at: m.expires_at,
+ context_length: m.running_context_length,
+ digest: m.digest,
+ })),
+ disk_bytes: 3.6 * 1024 ** 3,
+ loaded_vram_bytes: 2 * 1024 ** 3,
+ error: null,
+ };
+}
+
+function renderPanel() {
+ const qc = new QueryClient({ defaultOptions: { queries: { retry: false } } });
+ return render(
+ <QueryClientProvider client={qc}>
+ <InventoryPanel providerId="ollama" />
+ </QueryClientProvider>,
+ );
+}
+
+const BASE = "/api/providers/ollama/local-models";
+
+beforeEach(() => {
+ installFetch((method, url) => {
+ if (method === "GET" && url === `${BASE}/inventory`)
+ return { body: inventoryBody() };
+ return undefined;
+ });
+});
+
+afterEach(() => {
+ cleanup();
+ vi.clearAllMocks();
+});
+
+async function openMenu(name: string) {
+ // The identity translator gives every row the same menu label, so scope
+ // the lookup to the row itself.
+ const row = await screen.findByRole("row", { name });
+ fireEvent.click(
+ within(row).getByRole("button", {
+ name: `local_models.inventory.menu_label ${name}`,
+ }),
+ );
+}
+
+describe("InventoryPanel", () => {
+ it("renders every download with its facts, the loaded state and the stat tiles", async () => {
+ renderPanel();
+
+ const row = await screen.findByRole("row", { name: "qwen3.5:4b" });
+ expect(row.textContent).toContain("qwen3");
+ expect(row.textContent).toContain("4.0B");
+ expect(row.textContent).toContain("Q4_K_M");
+ expect(row.textContent).toContain("128k");
+ expect(row.textContent).toContain("3.0 GB");
+ expect(row.textContent).toContain("tools");
+ // Loaded: VRAM, share of everything loaded, expiry.
+ expect(row.textContent).toContain("2.0 GB · 100% · 5 min");
+ // Used-by badge for the chat role.
+ expect(row.textContent).toContain("local_models.inventory.role_chat");
+
+ const embed = screen.getByRole("row", { name: "embeddinggemma:latest" });
+ expect(embed.textContent).toContain("local_models.inventory.not_loaded");
+
+ // Footer tiles.
+ expect(
+ screen.getByRole("group", { name: "local_models.inventory.stat_disk" })
+ .textContent,
+ ).toContain("3.6 GB");
+ expect(
+ screen.getByRole("group", { name: "local_models.inventory.stat_loaded" })
+ .textContent,
+ ).toContain("2.0 GB");
+ expect(
+ screen.getByRole("group", { name: "local_models.inventory.stat_total" })
+ .textContent,
+ ).toContain("2");
+ });
+
+ it("assigns a role from the menu and disables roles the model cannot serve", async () => {
+ installFetch((method, url) => {
+ if (method === "GET" && url === `${BASE}/inventory`)
+ return { body: inventoryBody() };
+ if (method === "PUT" && url === `${BASE}/roles/deep`)
+ return {
+ body: {
+ ok: true,
+ role: "deep",
+ model: "qwen3.5:4b",
+ config_key: "x",
+ message: "Deep now uses qwen3.5:4b.",
+ },
+ };
+ return undefined;
+ });
+ renderPanel();
+ await openMenu("qwen3.5:4b");
+
+ // Already the chat pick, no embedding capability -> both disabled.
+ expect(
+ (
+ screen.getByRole("menuitem", {
+ name: "local_models.inventory.use_for local_models.inventory.role_chat",
+ }) as HTMLButtonElement
+ ).disabled,
+ ).toBe(true);
+ expect(
+ (
+ screen.getByRole("menuitem", {
+ name: "local_models.inventory.use_for local_models.inventory.role_embedding",
+ }) as HTMLButtonElement
+ ).disabled,
+ ).toBe(true);
+
+ fireEvent.click(
+ screen.getByRole("menuitem", {
+ name: "local_models.inventory.use_for local_models.inventory.role_deep",
+ }),
+ );
+ await waitFor(() =>
+ expect(screen.getByTestId("inventory-notice").textContent).toBe(
+ "Deep now uses qwen3.5:4b.",
+ ),
+ );
+ const put = calls.find((c) => c.method === "PUT");
+ expect(put?.url).toBe(`${BASE}/roles/deep`);
+ expect(put?.body).toEqual({ model: "qwen3.5:4b" });
+ });
+
+ it("unloads a loaded model and opens Details and Tune inline", async () => {
+ installFetch((method, url) => {
+ if (method === "GET" && url === `${BASE}/inventory`)
+ return { body: inventoryBody() };
+ if (method === "GET" && url === `${BASE}/inventory/qwen3.5%3A4b`)
+ return {
+ body: {
+ ...ROW,
+ parameters: "num_ctx 8192",
+ template: "{{ .Prompt }}",
+ },
+ };
+ if (method === "POST" && url === `${BASE}/inventory/qwen3.5%3A4b/unload`)
+ return {
+ body: { ok: true, model: "qwen3.5:4b", message: "Unloaded." },
+ };
+ return undefined;
+ });
+ renderPanel();
+
+ await openMenu("qwen3.5:4b");
+ fireEvent.click(
+ screen.getByRole("menuitem", {
+ name: "local_models.inventory.action_details",
+ }),
+ );
+ const details = await screen.findByTestId("details-qwen3.5:4b");
+ expect(details.textContent).toContain("Apache-2.0");
+ await waitFor(() => expect(details.textContent).toContain("num_ctx 8192"));
+
+ await openMenu("qwen3.5:4b");
+ fireEvent.click(
+ screen.getByRole("menuitem", {
+ name: "local_models.inventory.action_tune",
+ }),
+ );
+ expect(screen.getByTestId("tune-stub-qwen3.5:4b")).toBeDefined();
+ expect(screen.queryByTestId("details-qwen3.5:4b")).toBeNull();
+
+ await openMenu("qwen3.5:4b");
+ fireEvent.click(
+ screen.getByRole("menuitem", {
+ name: "local_models.inventory.action_unload",
+ }),
+ );
+ await waitFor(() =>
+ expect(screen.getByTestId("inventory-notice").textContent).toBe(
+ "Unloaded.",
+ ),
+ );
+ expect(
+ calls.some((c) => c.method === "POST" && c.url.endsWith("/unload")),
+ ).toBe(true);
+ });
+
+ it("deletes in two steps and turns a 409 into the sentence plus a reassign picker", async () => {
+ let deletes = 0;
+ installFetch((method, url) => {
+ if (method === "GET" && url === `${BASE}/inventory`)
+ return { body: inventoryBody() };
+ if (
+ method === "DELETE" &&
+ url.startsWith(`${BASE}/inventory/embeddinggemma%3Alatest`)
+ ) {
+ deletes += 1;
+ return {
+ status: 409,
+ body: {
+ detail: "The embedding role still points at embeddinggemma:latest.",
+ },
+ };
+ }
+ return undefined;
+ });
+ renderPanel();
+
+ await openMenu("embeddinggemma:latest");
+ fireEvent.click(
+ screen.getByRole("menuitem", {
+ name: "local_models.inventory.action_delete",
+ }),
+ );
+ // Nothing was deleted yet: the confirm drawer is the first step.
+ expect(deletes).toBe(0);
+ const drawer = await screen.findByTestId("delete-embeddinggemma:latest");
+ expect(drawer.textContent).toContain(
+ "local_models.inventory.delete_confirm",
+ );
+ expect(screen.queryByTestId("delete-reassign")).toBeNull();
+
+ fireEvent.click(
+ screen.getByRole("button", { name: "local_models.inventory.delete_do" }),
+ );
+ await waitFor(() => expect(deletes).toBe(1));
+ expect(
+ (await screen.findByTestId("delete-conflict")).textContent,
+ ).toContain("still points at");
+ // The sentence unlocks the reassign picker, and the button waits for a pick.
+ expect(screen.getByTestId("delete-reassign")).toBeDefined();
+ expect(
+ (
+ screen.getByRole("button", {
+ name: "local_models.inventory.delete_do",
+ }) as HTMLButtonElement
+ ).disabled,
+ ).toBe(true);
+
+ // A model still in use needs the pick before the first attempt.
+ fireEvent.click(
+ screen.getByRole("button", { name: "local_models.inventory.cancel" }),
+ );
+ await openMenu("qwen3.5:4b");
+ fireEvent.click(
+ screen.getByRole("menuitem", {
+ name: "local_models.inventory.action_delete",
+ }),
+ );
+ await screen.findByTestId("delete-qwen3.5:4b");
+ expect(
+ (
+ screen.getByRole("button", {
+ name: "local_models.inventory.delete_do",
+ }) as HTMLButtonElement
+ ).disabled,
+ ).toBe(true);
+ expect(screen.getByTestId("delete-reassign")).toBeDefined();
+ });
+
+ it("shows the backend sentence when the server is down", async () => {
+ installFetch((method, url) => {
+ if (method === "GET" && url === `${BASE}/inventory`)
+ return {
+ body: {
+ ...inventoryBody([]),
+ error: "Ollama is not answering on http://127.0.0.1:11434.",
+ },
+ };
+ return undefined;
+ });
+ renderPanel();
+ expect(
+ (await screen.findByTestId("inventory-server-error")).textContent,
+ ).toContain("not answering");
+ expect(screen.getByText("local_models.inventory.empty")).toBeDefined();
+ });
+});
diff --git a/jarvis/ui/web/frontend/src/views/local-models/InventoryPanel.tsx b/jarvis/ui/web/frontend/src/views/local-models/InventoryPanel.tsx
new file mode 100644
index 0000000000..7ca555f868
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/views/local-models/InventoryPanel.tsx
@@ -0,0 +1,588 @@
+/**
+ * Inventory panel — every model on the local server as one hairline ledger.
+ *
+ * Props: `providerId` — the pull-capable card ("ollama" today). The panel
+ * reads `GET .../inventory` (polled by the hook), and offers per row: Details
+ * (an inline fact sheet), Tune (the `TuneSheet` inline), Use for the four
+ * writable roles, Unload and Delete. Delete is two-step; a 409 (a role still
+ * points at the model) shows the backend's sentence and a reassign picker.
+ * Three stat tiles close the ledger: disk, loaded memory, model count.
+ *
+ * Columns: name · family · params · quant · context · size · capabilities ·
+ * modified · loaded · used by. The table scrolls inside its own container on
+ * a narrow pane; the page never scrolls sideways.
+ */
+import { useMemo, useState } from "react";
+import { Database, HardDrive, Layers, MoreHorizontal } from "lucide-react";
+import { cn } from "@/lib/utils";
+import { fill, useT, useUiLanguage } from "@/i18n";
+import {
+ ActionMenu,
+ Cell,
+ type Column,
+ DetailHeader,
+ EmptyRow,
+ FactRows,
+ IconButton,
+ type MenuAction,
+ SoftButton,
+ StatTile,
+ StatusDot,
+ Table,
+ TableHead,
+ TableRow,
+ formatShortDate,
+} from "@/components/extensions/primitives";
+import { BrandedSelect } from "@/components/ui/select";
+import {
+ useDeleteModel,
+ useInventory,
+ useInventoryModel,
+ useSetRole,
+ useUnloadModel,
+ type LocalModelRole,
+ type LocalModelRow,
+} from "@/hooks/useLocalModels";
+import { TuneSheet } from "./TuneSheet";
+import {
+ formatContext,
+ formatExpiry,
+ formatGb,
+ share,
+} from "./localModelsFormat";
+
+export interface InventoryPanelProps {
+ providerId: string;
+}
+
+const WRITABLE_ROLES: LocalModelRole[] = [
+ "chat",
+ "tools_screen",
+ "deep",
+ "embedding",
+];
+
+/** Which capability a role needs; mirrors `ollama_roles.ROLES.required`. */
+const ROLE_NEEDS: Record<LocalModelRole, string | null> = {
+ chat: null,
+ tools_screen: "tools",
+ deep: null,
+ embedding: "embedding",
+};
+
+type Drawer = { kind: "details" | "tune" | "delete"; name: string } | null;
+
+function Badge({
+ children,
+ tone = "muted",
+}: {
+ children: React.ReactNode;
+ tone?: "muted" | "primary";
+}) {
+ return (
+ <span
+ className={cn(
+ "inline-flex shrink-0 items-center rounded-full px-1.5 py-0.5 text-[10px] font-medium",
+ tone === "primary"
+ ? "bg-primary/10 text-primary"
+ : "bg-sheen/[0.08] text-muted-foreground",
+ )}
+ >
+ {children}
+ </span>
+ );
+}
+
+function DetailsDrawer({
+ providerId,
+ row,
+ t,
+}: {
+ providerId: string;
+ row: LocalModelRow;
+ t: (key: string) => string;
+}) {
+ const k = (key: string) => t(`local_models.inventory.${key}`);
+ const detail = useInventoryModel(providerId, row.name);
+ const params = detail.data?.parameters ?? "";
+ const template = detail.data?.template ?? "";
+ return (
+ <div
+ className="space-y-4 rounded-xl border border-border bg-card/60 p-4"
+ data-testid={`details-${row.name}`}
+ >
+ <DetailHeader
+ title={row.name}
+ byline={[row.family, row.parameter_size, row.quantization_level]
+ .filter(Boolean)
+ .join(" · ")}
+ />
+ <FactRows
+ rows={[
+ { label: k("fact_license"), value: row.license || k("unknown") },
+ {
+ label: k("fact_capabilities"),
+ value: row.probed ? row.capabilities.join(", ") : k("unknown"),
+ },
+ {
+ label: k("fact_context"),
+ value: formatContext(row.context_length),
+ },
+ {
+ label: k("fact_digest"),
+ value: <code className="text-xs">{row.digest.slice(0, 12)}</code>,
+ },
+ {
+ label: k("fact_parameters"),
+ value: detail.isLoading ? (
+ k("loading")
+ ) : params ? (
+ <pre className="whitespace-pre-wrap font-mono text-xs">
+ {params}
+ </pre>
+ ) : (
+ k("fact_none")
+ ),
+ },
+ {
+ label: k("fact_template"),
+ value: template ? (
+ <pre className="max-h-40 overflow-auto whitespace-pre-wrap font-mono text-xs">
+ {template}
+ </pre>
+ ) : null,
+ },
+ ]}
+ />
+ </div>
+ );
+}
+
+function DeleteDrawer({
+ row,
+ others,
+ busy,
+ conflict,
+ onConfirm,
+ onCancel,
+ t,
+}: {
+ row: LocalModelRow;
+ others: LocalModelRow[];
+ busy: boolean;
+ conflict: string | null;
+ onConfirm: (reassign?: string) => void;
+ onCancel: () => void;
+ t: (key: string) => string;
+}) {
+ const k = (key: string) => t(`local_models.inventory.${key}`);
+ const [reassign, setReassign] = useState("");
+ const used = row.used_by.length > 0;
+ return (
+ <div
+ className="space-y-3 rounded-xl border border-destructive/40 bg-card/60 p-4"
+ data-testid={`delete-${row.name}`}
+ >
+ <p className="text-sm text-foreground">
+ {fill(k("delete_confirm"), {
+ model: row.name,
+ size: formatGb(row.size_bytes),
+ })}
+ </p>
+ {conflict && (
+ <p
+ className="text-sm text-amber-600 dark:text-amber-400"
+ data-testid="delete-conflict"
+ >
+ {conflict}
+ </p>
+ )}
+ {(conflict || used) && others.length > 0 && (
+ <div className="flex flex-wrap items-center gap-2">
+ <span className="text-xs text-muted-foreground">
+ {k("delete_reassign")}
+ </span>
+ <BrandedSelect
+ value={reassign}
+ onValueChange={setReassign}
+ ariaLabel={k("delete_reassign")}
+ placeholder={k("delete_reassign_pick")}
+ options={others.map((o) => ({ value: o.name, label: o.name }))}
+ testId="delete-reassign"
+ />
+ </div>
+ )}
+ <div className="flex items-center gap-2">
+ <SoftButton
+ primary
+ disabled={
+ busy ||
+ ((conflict !== null || used) && others.length > 0 && !reassign)
+ }
+ onClick={() => onConfirm(reassign || undefined)}
+ ariaLabel={k("delete_do")}
+ >
+ {busy ? k("deleting") : k("delete_do")}
+ </SoftButton>
+ <SoftButton onClick={onCancel} ariaLabel={k("cancel")}>
+ {k("cancel")}
+ </SoftButton>
+ </div>
+ </div>
+ );
+}
+
+export function InventoryPanel({ providerId }: InventoryPanelProps) {
+ const t = useT();
+ const locale = useUiLanguage();
+ const k = (key: string) => t(`local_models.inventory.${key}`);
+
+ const inventory = useInventory(providerId);
+ const setRole = useSetRole(providerId);
+ const unload = useUnloadModel(providerId);
+ const remove = useDeleteModel(providerId);
+
+ const [drawer, setDrawer] = useState<Drawer>(null);
+ const [notice, setNotice] = useState<{
+ tone: "ok" | "error";
+ text: string;
+ } | null>(null);
+ const [conflict, setConflict] = useState<string | null>(null);
+
+ const models = inventory.data?.models ?? [];
+ const totalVram = useMemo(
+ () =>
+ (inventory.data?.running ?? []).reduce(
+ (sum, r) => sum + r.size_vram_bytes,
+ 0,
+ ),
+ [inventory.data],
+ );
+
+ const roleLabel = (role: LocalModelRole) => k(`role_${role}`);
+
+ const openDrawer = (kind: "details" | "tune" | "delete", name: string) => {
+ setConflict(null);
+ setDrawer((cur) =>
+ cur && cur.kind === kind && cur.name === name ? null : { kind, name },
+ );
+ };
+
+ const assign = (row: LocalModelRow, role: LocalModelRole) => {
+ setNotice(null);
+ setRole.mutate(
+ { role, model: row.name },
+ {
+ onSuccess: (res) =>
+ setNotice({
+ tone: "ok",
+ text:
+ res.message ||
+ fill(k("assigned"), { model: row.name, role: roleLabel(role) }),
+ }),
+ onError: (err) =>
+ setNotice({
+ tone: "error",
+ text: err instanceof Error ? err.message : String(err),
+ }),
+ },
+ );
+ };
+
+ const doUnload = (row: LocalModelRow) => {
+ setNotice(null);
+ unload.mutate(row.name, {
+ onSuccess: (res) =>
+ setNotice({
+ tone: "ok",
+ text: res.message || fill(k("unloaded"), { model: row.name }),
+ }),
+ onError: (err) =>
+ setNotice({
+ tone: "error",
+ text: err instanceof Error ? err.message : String(err),
+ }),
+ });
+ };
+
+ const doDelete = (row: LocalModelRow, reassign?: string) => {
+ setNotice(null);
+ setConflict(null);
+ remove.mutate(
+ { name: row.name, reassign },
+ {
+ onSuccess: (res) => {
+ setDrawer(null);
+ setNotice({
+ tone: "ok",
+ text: res.message || fill(k("deleted"), { model: row.name }),
+ });
+ },
+ onError: (err) => {
+ // A 409 carries the backend's sentence naming the role(s); the
+ // drawer keeps it beside the reassign picker.
+ setConflict(err instanceof Error ? err.message : String(err));
+ },
+ },
+ );
+ };
+
+ const columns: Column[] = [
+ { id: "name", label: k("col_name"), width: "minmax(180px, 2fr)" },
+ { id: "family", label: k("col_family"), width: "90px" },
+ { id: "params", label: k("col_params"), width: "70px", align: "right" },
+ { id: "quant", label: k("col_quant"), width: "80px" },
+ { id: "context", label: k("col_context"), width: "70px", align: "right" },
+ { id: "size", label: k("col_size"), width: "70px", align: "right" },
+ { id: "caps", label: k("col_capabilities"), width: "minmax(140px, 1.4fr)" },
+ { id: "modified", label: k("col_modified"), width: "80px" },
+ { id: "loaded", label: k("col_loaded"), width: "120px" },
+ { id: "used", label: k("col_used_by"), width: "minmax(100px, 1fr)" },
+ { id: "actions", label: k("col_actions"), width: "40px", srOnly: true },
+ ];
+
+ const rowActions = (row: LocalModelRow): MenuAction[] => {
+ const roleActions: MenuAction[] = WRITABLE_ROLES.map((role) => {
+ const need = ROLE_NEEDS[role];
+ const lacking =
+ need !== null && row.probed && !row.capabilities.includes(need);
+ return {
+ id: `use-${role}`,
+ label: fill(k("use_for"), { role: roleLabel(role) }),
+ onSelect: () => assign(row, role),
+ disabled: lacking || row.used_by.includes(role),
+ };
+ });
+ return [
+ {
+ id: "details",
+ label: k("action_details"),
+ onSelect: () => openDrawer("details", row.name),
+ },
+ {
+ id: "tune",
+ label: k("action_tune"),
+ onSelect: () => openDrawer("tune", row.name),
+ },
+ { ...roleActions[0], separatorAbove: true },
+ ...roleActions.slice(1),
+ {
+ id: "unload",
+ label: k("action_unload"),
+ onSelect: () => doUnload(row),
+ disabled: !row.loaded,
+ separatorAbove: true,
+ },
+ {
+ id: "delete",
+ label: k("action_delete"),
+ onSelect: () => openDrawer("delete", row.name),
+ destructive: true,
+ },
+ ];
+ };
+
+ return (
+ <div className="space-y-4" data-testid="inventory-panel">
+ {inventory.isError && (
+ <p className="text-sm text-destructive">
+ {inventory.error instanceof Error
+ ? inventory.error.message
+ : k("failed")}
+ </p>
+ )}
+ {inventory.data?.error && (
+ <p
+ className="text-sm text-amber-600 dark:text-amber-400"
+ data-testid="inventory-server-error"
+ >
+ {inventory.data.error}
+ </p>
+ )}
+ {notice && (
+ <p
+ className={cn(
+ "text-sm",
+ notice.tone === "ok"
+ ? "text-emerald-600 dark:text-emerald-400"
+ : "text-destructive",
+ )}
+ data-testid="inventory-notice"
+ >
+ {notice.text}
+ </p>
+ )}
+
+ <div className="overflow-x-auto rounded-xl border border-border bg-card/60">
+ <div className="min-w-[1040px]">
+ <Table label={k("table_label")}>
+ <TableHead columns={columns} />
+ {inventory.isLoading && (
+ <div className="px-3 py-6 text-sm text-muted-foreground">
+ {k("loading")}
+ </div>
+ )}
+ {!inventory.isLoading && models.length === 0 && (
+ <div className="p-3">
+ <EmptyRow>{k("empty")}</EmptyRow>
+ </div>
+ )}
+ {models.map((row) => {
+ const open = drawer?.name === row.name ? drawer.kind : null;
+ const vramShare = share(row.size_vram_bytes, totalVram);
+ const expiry = formatExpiry(row.expires_at);
+ return (
+ <div key={row.name}>
+ <TableRow
+ columns={columns}
+ ariaLabel={row.name}
+ selected={open !== null}
+ >
+ <Cell>
+ <div
+ className="truncate font-medium text-foreground"
+ title={row.name}
+ >
+ {row.name}
+ </div>
+ </Cell>
+ <Cell muted>
+ <span className="truncate">{row.family || "—"}</span>
+ </Cell>
+ <Cell muted align="right" className="tabular-nums">
+ {row.parameter_size || "—"}
+ </Cell>
+ <Cell muted>
+ <span className="truncate">
+ {row.quantization_level || "—"}
+ </span>
+ </Cell>
+ <Cell muted align="right" className="tabular-nums">
+ {formatContext(row.context_length)}
+ </Cell>
+ <Cell muted align="right" className="tabular-nums">
+ {formatGb(row.size_bytes)}
+ </Cell>
+ <Cell>
+ <div className="flex flex-wrap gap-1">
+ {row.probed ? (
+ row.capabilities.map((cap) => (
+ <Badge key={cap}>{cap}</Badge>
+ ))
+ ) : (
+ <Badge>{k("unknown")}</Badge>
+ )}
+ </div>
+ </Cell>
+ <Cell muted className="tabular-nums">
+ {formatShortDate(row.modified_at, locale)}
+ </Cell>
+ <Cell>
+ {row.loaded ? (
+ <StatusDot
+ tone="ok"
+ label={
+ <span className="tabular-nums">
+ {formatGb(row.size_vram_bytes)}
+ {totalVram > 0 ? ` · ${vramShare}%` : ""}
+ {expiry ? ` · ${expiry}` : ""}
+ </span>
+ }
+ />
+ ) : (
+ <StatusDot tone="off" label={k("not_loaded")} />
+ )}
+ </Cell>
+ <Cell>
+ <div className="flex flex-wrap gap-1">
+ {row.used_by.map((role) => (
+ <Badge key={role} tone="primary">
+ {roleLabel(role)}
+ </Badge>
+ ))}
+ </div>
+ </Cell>
+ <Cell align="right" stop>
+ <ActionMenu
+ label={fill(k("menu_label"), { model: row.name })}
+ actions={rowActions(row)}
+ trigger={({ open: menuOpen, toggle }) => (
+ <IconButton
+ label={fill(k("menu_label"), { model: row.name })}
+ onClick={toggle}
+ active={menuOpen}
+ >
+ <MoreHorizontal className="h-4 w-4" />
+ </IconButton>
+ )}
+ />
+ </Cell>
+ </TableRow>
+ {open && (
+ <div className="border-b border-border/70 px-3 py-3 last:border-b-0">
+ {open === "details" && (
+ <DetailsDrawer
+ providerId={providerId}
+ row={row}
+ t={t}
+ />
+ )}
+ {open === "tune" && (
+ <TuneSheet
+ providerId={providerId}
+ model={row}
+ onClose={() => setDrawer(null)}
+ />
+ )}
+ {open === "delete" && (
+ <DeleteDrawer
+ row={row}
+ others={models.filter((m) => m.name !== row.name)}
+ busy={remove.isPending}
+ conflict={conflict}
+ onConfirm={(reassign) => doDelete(row, reassign)}
+ onCancel={() => {
+ setConflict(null);
+ setDrawer(null);
+ }}
+ t={t}
+ />
+ )}
+ </div>
+ )}
+ </div>
+ );
+ })}
+ </Table>
+ </div>
+ </div>
+
+ <div className="grid grid-cols-1 gap-3 sm:grid-cols-3">
+ <StatTile
+ icon={<HardDrive className="h-4 w-4" />}
+ label={k("stat_disk")}
+ value={formatGb(inventory.data?.disk_bytes)}
+ hint={k("stat_disk_hint")}
+ loading={inventory.isLoading}
+ />
+ <StatTile
+ icon={<Layers className="h-4 w-4" />}
+ label={k("stat_loaded")}
+ value={formatGb(inventory.data?.loaded_vram_bytes)}
+ hint={fill(k("stat_loaded_hint"), {
+ count: inventory.data?.running.length ?? 0,
+ })}
+ tone="primary"
+ loading={inventory.isLoading}
+ />
+ <StatTile
+ icon={<Database className="h-4 w-4" />}
+ label={k("stat_total")}
+ value={String(models.length)}
+ hint={k("stat_total_hint")}
+ loading={inventory.isLoading}
+ />
+ </div>
+ </div>
+ );
+}
diff --git a/jarvis/ui/web/frontend/src/views/local-models/TuneSheet.test.tsx b/jarvis/ui/web/frontend/src/views/local-models/TuneSheet.test.tsx
new file mode 100644
index 0000000000..85096e88d5
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/views/local-models/TuneSheet.test.tsx
@@ -0,0 +1,269 @@
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import {
+ cleanup,
+ fireEvent,
+ render,
+ screen,
+ waitFor,
+} from "@testing-library/react";
+import { afterEach, describe, expect, it, vi } from "vitest";
+
+vi.mock("@/i18n", () => ({
+ useT: () => (key: string) => key,
+ fill: (template: string, vars: Record<string, string | number>) =>
+ template.replace(/\{(\w+)\}/g, (m, key: string) =>
+ key in vars ? String(vars[key]) : m,
+ ),
+}));
+
+import { TuneSheet } from "./TuneSheet";
+import type { LocalModelRow } from "@/hooks/useLocalModels";
+
+interface RouteResult {
+ status?: number;
+ body: unknown;
+}
+
+type Handler = (
+ method: string,
+ url: string,
+ body: unknown,
+) => RouteResult | undefined;
+
+const calls: { url: string; method: string; body: unknown }[] = [];
+
+function installFetch(handler: Handler) {
+ calls.length = 0;
+ const fetchMock = vi.fn(
+ async (input: RequestInfo | URL, init?: RequestInit) => {
+ const url = String(input);
+ const method = (init?.method ?? "GET").toUpperCase();
+ let body: unknown = null;
+ if (typeof init?.body === "string") body = JSON.parse(init.body);
+ calls.push({ url, method, body });
+ const res = handler(method, url, body);
+ if (!res) throw new Error(`unexpected fetch ${method} ${url}`);
+ const status = res.status ?? 200;
+ return {
+ ok: status >= 200 && status < 300,
+ status,
+ json: async () => res.body,
+ } as Response;
+ },
+ );
+ (globalThis as unknown as { fetch: typeof fetch }).fetch =
+ fetchMock as unknown as typeof fetch;
+}
+
+const MODEL: LocalModelRow = {
+ name: "qwen3.5:4b",
+ size_bytes: 3 * 1024 ** 3,
+ digest: "abc",
+ modified_at: "2026-08-20T10:00:00Z",
+ family: "qwen3",
+ parameter_size: "4.0B",
+ quantization_level: "Q4_K_M",
+ context_length: 32768,
+ capabilities: ["completion", "tools", "thinking"],
+ license: "Apache-2.0",
+ probed: true,
+ used_by: [],
+ loaded: false,
+ size_vram_bytes: 0,
+ expires_at: "",
+ running_context_length: null,
+};
+
+const BASE = "/api/providers/ollama/local-models/models/qwen3.5%3A4b";
+
+function routes(overrides: Partial<Record<string, RouteResult>> = {}): Handler {
+ return (method, url) => {
+ const key = `${method} ${url}`;
+ if (overrides[key]) return overrides[key];
+ if (key === `GET ${BASE}/options`)
+ return {
+ body: {
+ model: "qwen3.5:4b",
+ options: {},
+ configured: false,
+ profile_alias: null,
+ },
+ };
+ if (key === `GET ${BASE}/suggested-options`)
+ return {
+ body: {
+ model: "qwen3.5:4b",
+ options: { num_ctx: 16384, num_gpu: -1, keep_alive: "30m" },
+ reasons: [
+ "A 16k context fits beside the model.",
+ "The whole model fits on the graphics card.",
+ ],
+ size_gb: 3,
+ native_context: 32768,
+ accelerator_gb: 16,
+ accelerator_source: "nvidia-smi",
+ ram_gb: 32,
+ },
+ };
+ return undefined;
+ };
+}
+
+function renderSheet(model: LocalModelRow = MODEL) {
+ const qc = new QueryClient({ defaultOptions: { queries: { retry: false } } });
+ const onClose = vi.fn();
+ render(
+ <QueryClientProvider client={qc}>
+ <TuneSheet providerId="ollama" model={model} onClose={onClose} />
+ </QueryClientProvider>,
+ );
+ return { onClose };
+}
+
+afterEach(() => {
+ cleanup();
+ vi.clearAllMocks();
+});
+
+describe("TuneSheet", () => {
+ it("lists the machine's reasons, caps the context chips at the native window and applies the suggestion", async () => {
+ installFetch(routes());
+ renderSheet();
+
+ const reasons = await screen.findByTestId("tune-reasons");
+ expect(reasons.textContent).toContain("16k context fits");
+
+ // 4k..16k plus the native 32k; 64k and 128k are beyond the model.
+ expect(screen.getByTestId("tune-ctx-4096")).toBeDefined();
+ expect(screen.getByTestId("tune-ctx-16384")).toBeDefined();
+ expect(screen.getByTestId("tune-ctx-32768").textContent).toContain(
+ "local_models.tune.chip_native",
+ );
+ expect(screen.queryByTestId("tune-ctx-65536")).toBeNull();
+ // Thinking chips are there because the model declares the capability.
+ expect(screen.getByTestId("tune-think-high")).toBeDefined();
+
+ fireEvent.click(
+ screen.getByRole("button", { name: "local_models.tune.suggested_apply" }),
+ );
+ expect(
+ screen.getByTestId("tune-ctx-16384").getAttribute("aria-pressed"),
+ ).toBe("true");
+ expect(
+ screen.getByTestId("tune-gpu-all").getAttribute("aria-pressed"),
+ ).toBe("true");
+ expect(
+ screen.getByTestId("tune-keep-30m").getAttribute("aria-pressed"),
+ ).toBe("true");
+ expect(
+ screen.getByText("local_models.tune.footnote_will_bake"),
+ ).toBeDefined();
+ });
+
+ it("saves the whole compacted set and reads back the alias sentence", async () => {
+ const saved = {
+ model: "qwen3.5:4b",
+ options: { num_ctx: 8192, keep_alive: -1, think: "low" },
+ configured: true,
+ profile_alias: "qwen3.5-4b-jarvis-1a2b3c4d",
+ };
+ let stored: RouteResult | undefined;
+ const base = routes();
+ installFetch((method, url, body) => {
+ if (`${method} ${url}` === `PUT ${BASE}/options`) {
+ // The re-read after the save sees what was written.
+ stored = { body: saved };
+ return stored;
+ }
+ if (`${method} ${url}` === `GET ${BASE}/options` && stored) return stored;
+ return base(method, url, body);
+ });
+ renderSheet();
+ await screen.findByTestId("tune-reasons");
+
+ fireEvent.click(screen.getByTestId("tune-ctx-8192"));
+ fireEvent.click(screen.getByTestId("tune-keep-forever"));
+ fireEvent.click(screen.getByTestId("tune-think-low"));
+ fireEvent.click(
+ screen.getByRole("button", { name: "local_models.tune.save" }),
+ );
+
+ const put = await waitFor(() => {
+ const c = calls.find((x) => x.method === "PUT");
+ if (!c) throw new Error("no PUT yet");
+ return c;
+ });
+ expect(put.url).toBe(`${BASE}/options`);
+ expect(put.body).toEqual({ num_ctx: 8192, keep_alive: -1, think: "low" });
+
+ const readback = await screen.findByTestId("tune-readback");
+ expect(readback.textContent).toBe("local_models.tune.saved_with_alias");
+ await waitFor(() =>
+ expect(
+ screen.getByText("local_models.tune.footnote_alias"),
+ ).toBeDefined(),
+ );
+ });
+
+ it("hides the thinking knob for a model without that capability and resets with DELETE", async () => {
+ installFetch(
+ routes({
+ [`GET ${BASE}/options`]: {
+ body: {
+ model: "qwen3.5:4b",
+ options: { num_ctx: 4096 },
+ configured: true,
+ profile_alias: "qwen3.5-4b-jarvis-deadbeef",
+ },
+ },
+ [`DELETE ${BASE}/options`]: {
+ body: {
+ model: "qwen3.5:4b",
+ options: {},
+ configured: false,
+ profile_alias: null,
+ },
+ },
+ }),
+ );
+ renderSheet({ ...MODEL, capabilities: ["completion"] });
+ await screen.findByTestId("tune-reasons");
+
+ expect(screen.queryByTestId("tune-think-high")).toBeNull();
+ // The stored set arrives in the draft.
+ await waitFor(() =>
+ expect(
+ screen.getByTestId("tune-ctx-4096").getAttribute("aria-pressed"),
+ ).toBe("true"),
+ );
+
+ fireEvent.click(
+ screen.getByRole("button", { name: "local_models.tune.reset" }),
+ );
+ await waitFor(() =>
+ expect(calls.some((c) => c.method === "DELETE")).toBe(true),
+ );
+ expect((await screen.findByTestId("tune-readback")).textContent).toBe(
+ "local_models.tune.reset_done",
+ );
+ });
+
+ it("shows the backend's sentence when a save fails", async () => {
+ installFetch(
+ routes({
+ [`PUT ${BASE}/options`]: {
+ status: 503,
+ body: { detail: "Ollama is not answering." },
+ },
+ }),
+ );
+ renderSheet();
+ await screen.findByTestId("tune-reasons");
+ fireEvent.click(
+ screen.getByRole("button", { name: "local_models.tune.save" }),
+ );
+ expect((await screen.findByTestId("tune-failure")).textContent).toBe(
+ "Ollama is not answering.",
+ );
+ });
+});
diff --git a/jarvis/ui/web/frontend/src/views/local-models/TuneSheet.tsx b/jarvis/ui/web/frontend/src/views/local-models/TuneSheet.tsx
new file mode 100644
index 0000000000..76d7fd162f
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/views/local-models/TuneSheet.tsx
@@ -0,0 +1,607 @@
+/**
+ * Tune sheet — the per-model options of one installed Ollama model.
+ *
+ * Props: `providerId` (the pull-capable card, "ollama" today), `model` (the
+ * inventory row — its size, native context and capabilities shape the
+ * chips) and an optional `onClose`. Mounted inline under the ledger row by
+ * `InventoryPanel`; the roles panel may mount it the same way.
+ *
+ * The sheet edits a draft of `OllamaModelOptions` and writes the whole set
+ * on Save (the backend has REPLACE semantics, so an unset knob is really
+ * unset). Every knob carries one plain sentence; the ranges are the
+ * backend's, which clamps rather than rejects. Knobs that bake into a
+ * derived profile alias are named in the footnote, because the first use
+ * after such a save takes a few seconds while Ollama builds that alias.
+ */
+import { useEffect, useMemo, useState } from "react";
+import { ChevronDown, Sparkles, X } from "lucide-react";
+import { cn } from "@/lib/utils";
+import { fill, useT } from "@/i18n";
+import { IconButton, SoftButton } from "@/components/extensions/primitives";
+import {
+ compactOllamaModelOptions,
+ needsProfileAlias,
+ type OllamaModelOptions,
+ type OllamaThinkLevel,
+} from "@/lib/ollamaModelOptions";
+import {
+ useModelOptions,
+ useResetModelOptions,
+ useSaveModelOptions,
+ useSuggestedOptions,
+ type LocalModelRow,
+} from "@/hooks/useLocalModels";
+import { estimateContextGb, formatContext, toGb } from "./localModelsFormat";
+
+export interface TuneSheetProps {
+ providerId: string;
+ model: LocalModelRow;
+ onClose?: () => void;
+}
+
+/** Context sizes offered as chips; the native window is added when known. */
+const CONTEXT_STEPS = [4096, 8192, 16384, 32768, 65536, 131072] as const;
+
+type KeepAliveChip = { id: string; value: string | number | null };
+
+const KEEP_ALIVE_CHIPS: KeepAliveChip[] = [
+ { id: "default", value: null },
+ { id: "5m", value: "5m" },
+ { id: "30m", value: "30m" },
+ { id: "2h", value: "2h" },
+ { id: "forever", value: -1 },
+ { id: "unload", value: 0 },
+];
+
+const THINK_CHIPS: { id: string; value: boolean | OllamaThinkLevel | null }[] =
+ [
+ { id: "default", value: null },
+ { id: "off", value: false },
+ { id: "low", value: "low" },
+ { id: "medium", value: "medium" },
+ { id: "high", value: "high" },
+ { id: "max", value: "max" },
+ ];
+
+function Chip({
+ active,
+ onClick,
+ children,
+ hint,
+ testId,
+}: {
+ active: boolean;
+ onClick: () => void;
+ children: React.ReactNode;
+ hint?: string;
+ testId?: string;
+}) {
+ return (
+ <button
+ type="button"
+ aria-pressed={active}
+ onClick={onClick}
+ data-testid={testId}
+ className={cn(
+ "inline-flex h-7 items-center gap-1.5 rounded-md border px-2.5 text-xs tabular-nums transition-colors",
+ active
+ ? "border-primary/50 bg-primary/10 font-medium text-foreground"
+ : "border-border text-muted-foreground hover:border-border hover:text-foreground",
+ )}
+ >
+ {children}
+ {hint ? (
+ <span className="text-[10px] text-muted-foreground">{hint}</span>
+ ) : null}
+ </button>
+ );
+}
+
+function Eyebrow({ children }: { children: React.ReactNode }) {
+ return (
+ <div className="text-[11px] uppercase tracking-[0.18em] text-muted-foreground">
+ {children}
+ </div>
+ );
+}
+
+function Knob({
+ label,
+ sentence,
+ children,
+}: {
+ label: string;
+ sentence: string;
+ children: React.ReactNode;
+}) {
+ return (
+ <div className="space-y-1.5">
+ <div className="text-sm font-medium text-foreground">{label}</div>
+ <div className="flex flex-wrap items-center gap-1.5">{children}</div>
+ <p className="text-xs text-muted-foreground">{sentence}</p>
+ </div>
+ );
+}
+
+function NumberField({
+ label,
+ value,
+ onChange,
+ min,
+ max,
+ step,
+ placeholder,
+ testId,
+}: {
+ label: string;
+ value: number | null | undefined;
+ onChange: (v: number | null) => void;
+ min?: number;
+ max?: number;
+ step?: number;
+ placeholder?: string;
+ testId?: string;
+}) {
+ return (
+ <input
+ type="number"
+ aria-label={label}
+ data-testid={testId}
+ value={value ?? ""}
+ min={min}
+ max={max}
+ step={step}
+ placeholder={placeholder}
+ onChange={(e) => {
+ const raw = e.target.value;
+ if (raw === "") return onChange(null);
+ const n = Number(raw);
+ onChange(Number.isFinite(n) ? n : null);
+ }}
+ className="h-7 w-28 rounded-md border border-border bg-background/60 px-2 text-xs tabular-nums placeholder:text-muted-foreground focus:outline-none focus:ring-1 focus:ring-primary"
+ />
+ );
+}
+
+function sameKeepAlive(
+ a: string | number | null | undefined,
+ b: string | number | null,
+): boolean {
+ if (a === undefined || a === null) return b === null;
+ return String(a) === String(b);
+}
+
+export function TuneSheet({ providerId, model, onClose }: TuneSheetProps) {
+ const t = useT();
+ const k = (key: string) => t(`local_models.tune.${key}`);
+
+ const stored = useModelOptions(providerId, model.name);
+ const suggested = useSuggestedOptions(providerId, model.name);
+ const save = useSaveModelOptions(providerId);
+ const reset = useResetModelOptions(providerId);
+
+ const [draft, setDraft] = useState<OllamaModelOptions>({});
+ const [samplingOpen, setSamplingOpen] = useState(false);
+ const [readback, setReadback] = useState<string | null>(null);
+ const [failure, setFailure] = useState<string | null>(null);
+
+ // The draft follows the stored set once it arrives (and after a save/reset
+ // invalidates it); edits in between are the user's and stay.
+ const storedKey = stored.data ? JSON.stringify(stored.data.options) : null;
+ useEffect(() => {
+ if (stored.data) setDraft({ ...stored.data.options });
+ }, [storedKey]); // eslint-disable-line react-hooks/exhaustive-deps
+
+ const canThink = model.capabilities.includes("thinking");
+ const modelGb = toGb(model.size_bytes);
+ const native = model.context_length ?? null;
+
+ const contextChips = useMemo(() => {
+ const steps = CONTEXT_STEPS.filter((n) => native === null || n < native);
+ const list: number[] = [...steps];
+ if (native !== null && !list.includes(native)) list.push(native);
+ return list;
+ }, [native]);
+
+ const set = <K extends keyof OllamaModelOptions>(
+ key: K,
+ value: OllamaModelOptions[K],
+ ) => {
+ setReadback(null);
+ setFailure(null);
+ setDraft((d) => ({ ...d, [key]: value }));
+ };
+
+ const gpuMode: "default" | "all" | "cpu" | "custom" =
+ draft.num_gpu === undefined || draft.num_gpu === null
+ ? "default"
+ : draft.num_gpu === -1
+ ? "all"
+ : draft.num_gpu === 0
+ ? "cpu"
+ : "custom";
+
+ const compact = compactOllamaModelOptions(draft);
+ const knobCount = Object.keys(compact).length;
+ const alias = stored.data?.profile_alias ?? null;
+ const willBake = needsProfileAlias(compact);
+
+ const applySuggested = () => {
+ if (!suggested.data) return;
+ setReadback(null);
+ setFailure(null);
+ setDraft((d) => ({
+ ...d,
+ ...compactOllamaModelOptions(suggested.data.options),
+ }));
+ };
+
+ const onSave = () => {
+ setFailure(null);
+ save.mutate(
+ { name: model.name, options: compact },
+ {
+ onSuccess: (res) => {
+ const count = Object.keys(res.options).length;
+ setReadback(
+ count === 0
+ ? fill(k("saved_cleared"), { model: model.name })
+ : res.profile_alias
+ ? fill(k("saved_with_alias"), {
+ model: model.name,
+ count,
+ alias: res.profile_alias,
+ })
+ : fill(k("saved"), { model: model.name, count }),
+ );
+ },
+ onError: (err) =>
+ setFailure(err instanceof Error ? err.message : String(err)),
+ },
+ );
+ };
+
+ const onReset = () => {
+ setFailure(null);
+ reset.mutate(model.name, {
+ onSuccess: () => {
+ setDraft({});
+ setReadback(fill(k("reset_done"), { model: model.name }));
+ },
+ onError: (err) =>
+ setFailure(err instanceof Error ? err.message : String(err)),
+ });
+ };
+
+ const stopText = (draft.stop ?? []).join("\n");
+
+ return (
+ <section
+ data-testid={`tune-sheet-${model.name}`}
+ aria-label={fill(k("aria"), { model: model.name })}
+ className="space-y-5 rounded-xl border border-border bg-card/60 p-4"
+ >
+ <div className="flex items-start justify-between gap-4">
+ <div className="min-w-0">
+ <Eyebrow>{k("eyebrow")}</Eyebrow>
+ <h3 className="mt-1 truncate font-display text-base font-semibold text-foreground">
+ {model.name}
+ </h3>
+ <p className="mt-0.5 text-xs text-muted-foreground">
+ {fill(k("facts"), {
+ size: modelGb ? `${modelGb.toFixed(1)} GB` : "—",
+ context: formatContext(native),
+ })}
+ </p>
+ </div>
+ {onClose ? (
+ <IconButton label={k("close")} onClick={onClose}>
+ <X className="h-4 w-4" />
+ </IconButton>
+ ) : null}
+ </div>
+
+ {/* Suggested for this machine */}
+ <div className="rounded-lg border border-border/70 bg-background/40 p-3">
+ <div className="flex items-center justify-between gap-3">
+ <div className="flex items-center gap-2 text-sm font-medium text-foreground">
+ <Sparkles className="h-4 w-4 text-primary" />
+ {k("suggested_title")}
+ </div>
+ <SoftButton
+ onClick={applySuggested}
+ disabled={!suggested.data}
+ ariaLabel={k("suggested_apply")}
+ >
+ {k("suggested_apply")}
+ </SoftButton>
+ </div>
+ {suggested.isLoading && (
+ <p className="mt-2 text-xs text-muted-foreground">
+ {k("suggested_loading")}
+ </p>
+ )}
+ {suggested.isError && (
+ <p className="mt-2 text-xs text-amber-600 dark:text-amber-400">
+ {suggested.error instanceof Error
+ ? suggested.error.message
+ : k("suggested_failed")}
+ </p>
+ )}
+ {suggested.data && (
+ <ul
+ className="mt-2 space-y-1 text-xs text-muted-foreground"
+ data-testid="tune-reasons"
+ >
+ {suggested.data.reasons.map((reason) => (
+ <li key={reason}>{reason}</li>
+ ))}
+ </ul>
+ )}
+ </div>
+
+ {/* Context */}
+ <div className="space-y-3">
+ <Eyebrow>{k("group_context")}</Eyebrow>
+ <Knob label={k("num_ctx")} sentence={k("num_ctx_sentence")}>
+ <Chip
+ active={draft.num_ctx === undefined || draft.num_ctx === null}
+ onClick={() => set("num_ctx", null)}
+ >
+ {k("chip_default")}
+ </Chip>
+ {contextChips.map((n) => (
+ <Chip
+ key={n}
+ active={draft.num_ctx === n}
+ onClick={() => set("num_ctx", n)}
+ hint={`~${estimateContextGb(n, modelGb).toFixed(1)} GB`}
+ testId={`tune-ctx-${n}`}
+ >
+ {n === native
+ ? fill(k("chip_native"), { context: formatContext(n) })
+ : formatContext(n)}
+ </Chip>
+ ))}
+ </Knob>
+ </div>
+
+ {/* Placement */}
+ <div className="space-y-3">
+ <Eyebrow>{k("group_placement")}</Eyebrow>
+ <Knob label={k("num_gpu")} sentence={k("num_gpu_sentence")}>
+ <Chip
+ active={gpuMode === "default"}
+ onClick={() => set("num_gpu", null)}
+ >
+ {k("chip_default")}
+ </Chip>
+ <Chip
+ active={gpuMode === "all"}
+ onClick={() => set("num_gpu", -1)}
+ testId="tune-gpu-all"
+ >
+ {k("gpu_all")}
+ </Chip>
+ <Chip
+ active={gpuMode === "cpu"}
+ onClick={() => set("num_gpu", 0)}
+ testId="tune-gpu-cpu"
+ >
+ {k("gpu_cpu")}
+ </Chip>
+ <Chip active={gpuMode === "custom"} onClick={() => set("num_gpu", 1)}>
+ {k("gpu_custom")}
+ </Chip>
+ {gpuMode === "custom" && (
+ <NumberField
+ label={k("gpu_layers")}
+ value={draft.num_gpu}
+ min={1}
+ max={999}
+ onChange={(v) => set("num_gpu", v ?? 1)}
+ testId="tune-gpu-layers"
+ />
+ )}
+ </Knob>
+ <Knob label={k("num_thread")} sentence={k("num_thread_sentence")}>
+ <NumberField
+ label={k("num_thread")}
+ value={draft.num_thread}
+ min={0}
+ max={512}
+ placeholder={k("auto")}
+ onChange={(v) => set("num_thread", v)}
+ testId="tune-threads"
+ />
+ </Knob>
+ </div>
+
+ {/* Session */}
+ <div className="space-y-3">
+ <Eyebrow>{k("group_session")}</Eyebrow>
+ <Knob label={k("keep_alive")} sentence={k("keep_alive_sentence")}>
+ {KEEP_ALIVE_CHIPS.map((chip) => (
+ <Chip
+ key={chip.id}
+ active={sameKeepAlive(draft.keep_alive, chip.value)}
+ onClick={() => set("keep_alive", chip.value)}
+ testId={`tune-keep-${chip.id}`}
+ >
+ {k(`keep_${chip.id}`)}
+ </Chip>
+ ))}
+ </Knob>
+ {canThink && (
+ <Knob label={k("think")} sentence={k("think_sentence")}>
+ {THINK_CHIPS.map((chip) => (
+ <Chip
+ key={chip.id}
+ active={
+ chip.value === null
+ ? draft.think === undefined || draft.think === null
+ : draft.think === chip.value
+ }
+ onClick={() => set("think", chip.value)}
+ testId={`tune-think-${chip.id}`}
+ >
+ {k(`think_${chip.id}`)}
+ </Chip>
+ ))}
+ </Knob>
+ )}
+ </div>
+
+ {/* Sampling, collapsed */}
+ <div className="space-y-3">
+ <button
+ type="button"
+ onClick={() => setSamplingOpen((v) => !v)}
+ aria-expanded={samplingOpen}
+ className="flex items-center gap-1.5 text-[11px] uppercase tracking-[0.18em] text-muted-foreground hover:text-foreground"
+ >
+ {k("group_sampling")}
+ <ChevronDown
+ className={cn(
+ "h-3.5 w-3.5 transition-transform",
+ samplingOpen && "rotate-180",
+ )}
+ />
+ </button>
+ {samplingOpen && (
+ <div className="grid gap-4 sm:grid-cols-2">
+ <Knob label={k("temperature")} sentence={k("temperature_sentence")}>
+ <NumberField
+ label={k("temperature")}
+ value={draft.temperature}
+ min={0}
+ max={2}
+ step={0.1}
+ onChange={(v) => set("temperature", v)}
+ testId="tune-temperature"
+ />
+ </Knob>
+ <Knob label={k("top_p")} sentence={k("top_p_sentence")}>
+ <NumberField
+ label={k("top_p")}
+ value={draft.top_p}
+ min={0}
+ max={1}
+ step={0.05}
+ onChange={(v) => set("top_p", v)}
+ />
+ </Knob>
+ <Knob label={k("top_k")} sentence={k("top_k_sentence")}>
+ <NumberField
+ label={k("top_k")}
+ value={draft.top_k}
+ min={0}
+ max={1000}
+ onChange={(v) => set("top_k", v)}
+ />
+ </Knob>
+ <Knob label={k("min_p")} sentence={k("min_p_sentence")}>
+ <NumberField
+ label={k("min_p")}
+ value={draft.min_p}
+ min={0}
+ max={1}
+ step={0.05}
+ onChange={(v) => set("min_p", v)}
+ />
+ </Knob>
+ <Knob
+ label={k("repeat_penalty")}
+ sentence={k("repeat_penalty_sentence")}
+ >
+ <NumberField
+ label={k("repeat_penalty")}
+ value={draft.repeat_penalty}
+ min={0}
+ max={3}
+ step={0.05}
+ onChange={(v) => set("repeat_penalty", v)}
+ />
+ </Knob>
+ <Knob label={k("seed")} sentence={k("seed_sentence")}>
+ <NumberField
+ label={k("seed")}
+ value={draft.seed}
+ min={0}
+ max={2147483647}
+ onChange={(v) => set("seed", v)}
+ />
+ </Knob>
+ <Knob label={k("num_predict")} sentence={k("num_predict_sentence")}>
+ <NumberField
+ label={k("num_predict")}
+ value={draft.num_predict}
+ min={-2}
+ max={1048576}
+ onChange={(v) => set("num_predict", v)}
+ />
+ </Knob>
+ <Knob label={k("stop")} sentence={k("stop_sentence")}>
+ <textarea
+ aria-label={k("stop")}
+ value={stopText}
+ rows={2}
+ onChange={(e) => {
+ const lines = e.target.value
+ .split("\n")
+ .filter((l) => l.length > 0);
+ set("stop", lines.length ? lines : null);
+ }}
+ className="w-full rounded-md border border-border bg-background/60 px-2 py-1 text-xs placeholder:text-muted-foreground focus:outline-none focus:ring-1 focus:ring-primary"
+ />
+ </Knob>
+ </div>
+ )}
+ </div>
+
+ {/* Footer */}
+ <div className="space-y-2 border-t border-border/70 pt-3">
+ <div className="flex flex-wrap items-center gap-2">
+ <SoftButton
+ primary
+ onClick={onSave}
+ disabled={save.isPending}
+ ariaLabel={k("save")}
+ >
+ {save.isPending ? k("saving") : k("save")}
+ </SoftButton>
+ <SoftButton
+ onClick={onReset}
+ disabled={reset.isPending || !stored.data?.configured}
+ ariaLabel={k("reset")}
+ >
+ {k("reset")}
+ </SoftButton>
+ <span className="text-xs text-muted-foreground tabular-nums">
+ {fill(k("knob_count"), { count: knobCount })}
+ </span>
+ </div>
+ {readback && (
+ <p
+ className="text-sm text-emerald-600 dark:text-emerald-400"
+ data-testid="tune-readback"
+ >
+ {readback}
+ </p>
+ )}
+ {failure && (
+ <p className="text-sm text-destructive" data-testid="tune-failure">
+ {failure}
+ </p>
+ )}
+ <p className="text-xs text-muted-foreground">
+ {alias
+ ? fill(k("footnote_alias"), { alias })
+ : willBake
+ ? k("footnote_will_bake")
+ : k("footnote_no_alias")}
+ </p>
+ </div>
+ </section>
+ );
+}
diff --git a/jarvis/ui/web/frontend/src/views/local-models/localModelsFormat.ts b/jarvis/ui/web/frontend/src/views/local-models/localModelsFormat.ts
new file mode 100644
index 0000000000..609c722cf6
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/views/local-models/localModelsFormat.ts
@@ -0,0 +1,62 @@
+/**
+ * Small, pure formatters shared by the Local-models panels.
+ *
+ * Sizes are shown in GiB with one decimal (the unit the backend's
+ * `accelerator_gb` and `size_gb` already use), context windows as "32k".
+ */
+
+const GIB = 1024 ** 3;
+
+/** "4.7 GB"; "—" for nothing. */
+export function formatGb(bytes: number | null | undefined): string {
+ if (!bytes || bytes <= 0) return "—";
+ const gb = bytes / GIB;
+ return `${gb < 10 ? gb.toFixed(1) : Math.round(gb).toString()} GB`;
+}
+
+/** Bytes → GiB as a number, for estimates. */
+export function toGb(bytes: number | null | undefined): number {
+ return bytes && bytes > 0 ? bytes / GIB : 0;
+}
+
+/** 131072 → "128k", 4096 → "4k", 1500 → "1.5k"; "—" when unknown. */
+export function formatContext(tokens: number | null | undefined): string {
+ if (!tokens || tokens <= 0) return "—";
+ const k = tokens / 1024;
+ if (k < 1) return String(tokens);
+ return `${Number.isInteger(k) ? k : k.toFixed(1)}k`;
+}
+
+/** Percentage of `part` in `whole`, clamped 0..100; 0 when whole is empty. */
+export function share(part: number, whole: number): number {
+ if (!whole || whole <= 0) return 0;
+ return Math.max(0, Math.min(100, Math.round((part / whole) * 100)));
+}
+
+/**
+ * Rough extra memory a context window costs, in GiB: about 0.03 GiB per
+ * 1k tokens per GiB of model size (the same rule of thumb the backend's
+ * suggestion uses). An estimate for a chip label, never a promise.
+ */
+export function estimateContextGb(
+ contextTokens: number,
+ modelGb: number,
+): number {
+ return (contextTokens / 1000) * 0.03 * Math.max(modelGb, 0.5);
+}
+
+/** "in 4 min" / "in 2 h" from an ISO expiry; "" when missing or in the past. */
+export function formatExpiry(
+ iso: string | null | undefined,
+ now: number = Date.now(),
+): string {
+ if (!iso) return "";
+ const at = new Date(iso).getTime();
+ if (Number.isNaN(at) || at <= now) return "";
+ const minutes = Math.round((at - now) / 60_000);
+ if (minutes < 60) return `${Math.max(minutes, 1)} min`;
+ const hours = minutes / 60;
+ if (hours < 48)
+ return `${hours < 10 ? hours.toFixed(1).replace(/\.0$/, "") : Math.round(hours)} h`;
+ return `${Math.round(hours / 24)} d`;
+}