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 setup assistant panel with a one-click proposal
rubenluetke10-beepb6f7682458f9
diff --git a/jarvis/ui/web/frontend/src/components/local-models/AssistantPanel.test.tsx b/jarvis/ui/web/frontend/src/components/local-models/AssistantPanel.test.tsxnew file mode 100644index 0000000000..85677b96ea--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/local-models/AssistantPanel.test.tsx@@ -0,0 +1,215 @@+import { act, cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++vi.mock("@/i18n", () => ({+ useT: () => (key: string) => key,+ fill: (template: string, vars: Record<string, string | number>) =>+ `${template}${Object.values(vars).join("|")}`,+}));++vi.mock("@/store/events", () => ({+ useEventStore: (selector: (s: { assistantName: string }) => unknown) =>+ selector({ assistantName: "Jarvis" }),+}));++// The timeline is covered by its own tests; here only what the panel feeds it matters.+vi.mock("@/components/agentchat/AgentTimeline", () => ({+ AgentTimeline: ({ items }: { items: { type: string }[] }) => (+ <div data-testid="timeline-stub" data-count={items.length} />+ ),+}));++import { AssistantPanel } from "./AssistantPanel";+import { useLocalModelsAssistantStore } from "./assistantStore";+import { EMPTY_TIMELINE } from "@/components/agentchat/reduce";++const BASE = "/api/providers/ollama/local-models/assistant";++interface Call {+ url: string;+ method: string;+ body: Record<string, unknown> | null;+}++/** jsdom's WebSocket would try to reach a real host; a silent stand-in is enough here. */+class FakeSocket {+ onopen: (() => void) | null = null;+ onmessage: ((msg: { data: string }) => void) | null = null;+ onclose: (() => void) | null = null;+ onerror: (() => void) | null = null;+ close() {}+}++function stubFetch(routes: Record<string, (init?: RequestInit) => Response>): Call[] {+ const calls: Call[] = [];+ vi.stubGlobal(+ "fetch",+ vi.fn(async (input: string, init?: RequestInit) => {+ const url = String(input);+ const method = init?.method ?? "GET";+ const body = typeof init?.body === "string" ? (JSON.parse(init.body) as Record<string, unknown>) : null;+ calls.push({ url, method, body });+ const key = `${method} ${url}`;+ const handler = routes[key] ?? routes[url];+ return handler ? handler(init) : new Response(null, { status: 404 });+ }),+ );+ return calls;+}++const reply = (data: unknown, status = 200) =>+ new Response(JSON.stringify(data), { status, headers: { "Content-Type": "application/json" } });++const PROPOSAL_TEXT = `Here is the plan.++\`\`\`jarvis-proposal+{"version":1,"steps":[+ {"id":"s1","kind":"pull","model":"qwen3.5:8b","proven":true,"label":"Download Qwen"},+ {"id":"s2","kind":"set_role","role":"chat","model":"qwen3.5:8b","proven":true,"label":"Use it for Chat"}+],"notes":[]}+\`\`\``;++function finishedTurnWithProposal() {+ return {+ ...EMPTY_TIMELINE,+ lastSeq: 3,+ items: [+ { type: "user" as const, id: "u-1", text: "Help me set up", tsMs: 1 },+ {+ type: "turn" as const,+ id: "t1",+ provider: "openrouter",+ model: "m",+ effort: "",+ runner: "api",+ status: "done" as const,+ blocks: [{ kind: "text" as const, id: "live", text: PROPOSAL_TEXT }],+ startedMs: 1,+ durationMs: 10,+ usage: null,+ liveUsage: null,+ costUsd: null,+ error: null,+ },+ ],+ };+}++beforeEach(() => {+ vi.stubGlobal("WebSocket", FakeSocket);+ useLocalModelsAssistantStore.setState({+ activeSessionId: null,+ activeSession: null,+ timeline: EMPTY_TIMELINE,+ sessions: [],+ busy: false,+ lastError: null,+ });+});++afterEach(() => {+ cleanup();+ vi.unstubAllGlobals();+ vi.clearAllMocks();+});++describe("AssistantPanel", () => {+ it("renders the 409 sentence with a way to the API Keys section", async () => {+ const sentence = "Connect the Jarvis Agents tier first — no usable credential.";+ stubFetch({+ [`GET ${BASE}/session`]: () => reply({ session_id: null, provider: "", model: "", ready: false, reason: "no_credential" }),+ [`GET ${BASE}/health`]: () => reply({}, 404),+ [`POST ${BASE}/run`]: () => reply({ detail: sentence }, 409),+ });+ const onOpenApiKeys = vi.fn();+ render(+ <AssistantPanel+ providerId="ollama"+ serverLabel="Ollama"+ request={{ mode: "setup", token: 1 }}+ onOpenApiKeys={onOpenApiKeys}+ />,+ );++ await waitFor(() => expect(screen.getByTestId("assistant-blocked")).toBeDefined());+ expect(screen.getByTestId("assistant-blocked").textContent).toContain(sentence);+ fireEvent.click(screen.getByRole("button", { name: "local_models.assistant.open_api_keys" }));+ expect(onOpenApiKeys).toHaveBeenCalledTimes(1);+ // The composer stays locked: there is no session to talk to.+ expect((screen.getByTestId("assistant-composer") as HTMLTextAreaElement).disabled).toBe(true);+ });++ it("shows the monitor's last check and a Fix that starts diagnose mode", async () => {+ const calls = stubFetch({+ [`GET ${BASE}/session`]: () => reply({ session_id: null, provider: "", model: "", ready: true, reason: "" }),+ [`GET ${BASE}/health`]: () =>+ reply({ status: "error", reason: "chat role: model not installed", since: 1_700_000_000, last_ok: null, checked_at: 1_700_000_000 }),+ [`POST ${BASE}/run`]: () => reply({ session_id: "s-1", turn_id: "t-1", surface: "local-models" }),+ });+ render(<AssistantPanel providerId="ollama" serverLabel="Ollama" request={null} onOpenApiKeys={() => {}} />);++ await waitFor(() => expect(screen.getByTestId("assistant-health")).toBeDefined());+ expect(screen.getByTestId("assistant-health").textContent).toContain("chat role: model not installed");++ fireEvent.click(screen.getByTestId("assistant-health-fix"));+ await waitFor(() =>+ expect(calls.some((c) => c.method === "POST" && c.url === `${BASE}/run` && c.body?.mode === "diagnose")).toBe(true),+ );+ await waitFor(() => expect(useLocalModelsAssistantStore.getState().activeSessionId).toBe("s-1"));+ });++ it("says so when the backend predates the assistant", async () => {+ stubFetch({});+ render(<AssistantPanel providerId="ollama" serverLabel="Ollama" request={null} onOpenApiKeys={() => {}} />);+ await waitFor(() => expect(screen.getByTestId("assistant-backend-missing")).toBeDefined());+ });++ it("confirms the proposal once and answers the matching approval cards by itself", async () => {+ const calls = stubFetch({+ // The store already holds the open session (set below); the route+ // answering null keeps the panel from re-opening (and resetting) it.+ [`GET ${BASE}/session`]: () => reply({ session_id: null, provider: "openrouter", model: "m", ready: true, reason: "" }),+ [`GET ${BASE}/health`]: () => reply({}, 404),+ "POST /api/agent-chat/sessions/s-1/messages": () => reply({ turn_id: "t2" }),+ "POST /api/agent-chat/sessions/s-1/approvals/a-1": () => reply({}),+ "POST /api/agent-chat/sessions/s-1/approvals/a-2": () => reply({}),+ "GET /api/agent-chat/sessions?limit=500&surface=local-models": () => reply({ sessions: [] }),+ });+ useLocalModelsAssistantStore.setState({ activeSessionId: "s-1", timeline: finishedTurnWithProposal() });+ render(<AssistantPanel providerId="ollama" serverLabel="Ollama" request={null} onOpenApiKeys={() => {}} />);++ await waitFor(() => expect(screen.getByTestId("setup-proposal")).toBeDefined());+ fireEvent.click(screen.getByTestId("proposal-confirm"));+ await waitFor(() =>+ expect(calls.some((c) => c.url.endsWith("/messages") && String(c.body?.text).startsWith("Execute steps: s1, s2 ("))).toBe(true),+ );+ await waitFor(() => expect(screen.getByTestId("proposal-confirmed")).toBeDefined());++ // The runner asks about the confirmed pull: answered without a click.+ const ingest = useLocalModelsAssistantStore.getState().ingest;+ act(() => {+ ingest({ seq: 4, ts_ms: 20, kind: "turn_started", payload: { turn_id: "t2", provider: "openrouter", model: "m" } });+ ingest({+ seq: 5,+ ts_ms: 21,+ kind: "approval_required",+ payload: { turn_id: "t2", approval_id: "a-1", call_id: "c-1", name: "lm_pull", input: { model: "qwen3.5:8b" }, summary: "pull" },+ });+ });+ await waitFor(() =>+ expect(calls.some((c) => c.url.endsWith("/approvals/a-1") && c.body?.decision === "allow")).toBe(true),+ );++ // A question outside the plan stays a question.+ act(() => {+ ingest({+ seq: 6,+ ts_ms: 22,+ kind: "approval_required",+ payload: { turn_id: "t2", approval_id: "a-2", call_id: "c-2", name: "lm_pull", input: { model: "llama4:70b" }, summary: "pull" },+ });+ });+ await new Promise((r) => setTimeout(r, 20));+ expect(calls.some((c) => c.url.endsWith("/approvals/a-2"))).toBe(false);+ });+});diff --git a/jarvis/ui/web/frontend/src/components/local-models/AssistantPanel.tsx b/jarvis/ui/web/frontend/src/components/local-models/AssistantPanel.tsxnew file mode 100644index 0000000000..da5749a080--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/local-models/AssistantPanel.tsx@@ -0,0 +1,419 @@+/**+ * The Local models setup assistant — a guided chat inside the section.+ *+ * Three buttons start a canned turn on the backend (`POST …/assistant/run`+ * with a mode): "Help me set up" plans one complete setup, "Test" runs the+ * end-to-end check, "Something is broken" diagnoses. The conversation itself+ * is an ordinary agent-chat session on the `local-models` surface, so the+ * timeline, streaming, approval cards and cancel are the shared ones; only+ * the store instance is this panel's own (`assistantStore.ts`).+ *+ * When the assistant ends a turn with a ```jarvis-proposal block, the plan+ * is shown as a checklist (`SetupProposalCard`). ONE Confirm sends the+ * "Execute steps: …" message and remembers the steps; every+ * `approval_required` the runner raises for exactly those steps is answered+ * "allow" here, on the client, so the user clicks once. The ToolExecutor still+ * asks (AP-3) — the panel only answers what was already confirmed; anything+ * else keeps its ordinary card.+ *+ * Honest states, never toasts: a 409 from `/run` means the Jarvis Agents tier+ * is not usable and the sentence links to API Keys; a 404 means the backend+ * predates the assistant. The header carries the monitor's last check with a+ * "Fix" that opens diagnose mode.+ */+import { AlertTriangle, FlaskConical, Send, Sparkles, Square, X } from "lucide-react";+import { useCallback, useEffect, useMemo, useRef, useState } from "react";++import { AgentTimeline } from "@/components/agentchat/AgentTimeline";+import type { TextBlock, TurnItem } from "@/components/agentchat/reduce";+import { Panel, SoftButton, StatusDot } from "@/components/extensions/primitives";+import { fill, useT } from "@/i18n";+import type { ApprovalDecision } from "@/lib/agentChatApi";+import { useEventStore } from "@/store/events";+import { cn } from "@/lib/utils";++import {+ AssistantApiError,+ assistantTimestamp,+ getAssistantHealth,+ getAssistantSession,+ runAssistant,+ type AssistantHealth,+ type AssistantMode,+} from "./assistantApi";+import {+ matchesConfirmedStep,+ proposalFromText,+ proposalHash,+ type Proposal,+ type ProposalStep,+} from "./assistantProposal";+import { useLocalModelsAssistantStore } from "./assistantStore";+import { BrainSwitchCard, SetupProposalCard } from "./SetupProposalCard";++/** A request from the section: start this mode; `token` makes repeats distinct. */+export interface AssistantRequest {+ mode: AssistantMode;+ token: number;+}++/** The steps confirmed per session survive a close/reopen of the panel. */+const confirmedBySession = new Map<string, { hash: string; steps: ProposalStep[] }>();++/** The text of the last finished assistant turn — where a proposal lives. */+function lastAssistantText(items: readonly { type: string }[]): { text: string; turnId: string } | null {+ for (let i = items.length - 1; i >= 0; i--) {+ const item = items[i];+ if (item.type !== "turn") continue;+ const turn = item as TurnItem;+ if (turn.status !== "done") return null;+ const text = turn.blocks+ .filter((b): b is TextBlock => b.kind === "text")+ .map((b) => b.text)+ .join("\n");+ return { text, turnId: turn.id };+ }+ return null;+}++function isRunning(items: readonly { type: string }[]): boolean {+ const last = items[items.length - 1];+ return Boolean(last && last.type === "turn" && (last as TurnItem).status === "running");+}++export function AssistantPanel({+ providerId,+ serverLabel,+ request,+ onOpenApiKeys,+ onOpenServerLog,+ onClose,+}: {+ providerId: string;+ /** What the section calls the local server ("Ollama"). */+ serverLabel: string;+ /** The mode the section asked for (Help me set up / Something is not working). */+ request: AssistantRequest | null;+ onOpenApiKeys: () => void;+ /** The old "Something is not working" path: the Server tab with the log open. */+ onOpenServerLog?: () => void;+ onClose?: () => void;+}) {+ const t = useT();+ const assistantName = useEventStore((s) => s.assistantName);+ const items = useLocalModelsAssistantStore((s) => s.timeline.items);+ const pendingApprovals = useLocalModelsAssistantStore((s) => s.timeline.pendingApprovals);+ const activeSessionId = useLocalModelsAssistantStore((s) => s.activeSessionId);+ const busy = useLocalModelsAssistantStore((s) => s.busy);+ const lastError = useLocalModelsAssistantStore((s) => s.lastError);+ const openSession = useLocalModelsAssistantStore((s) => s.openSession);+ const send = useLocalModelsAssistantStore((s) => s.send);+ const cancel = useLocalModelsAssistantStore((s) => s.cancel);+ const decide = useLocalModelsAssistantStore((s) => s.decide);+ const disconnect = useLocalModelsAssistantStore((s) => s.disconnect);++ const [health, setHealth] = useState<AssistantHealth | null>(null);+ const [starting, setStarting] = useState<AssistantMode | null>(null);+ /** The 409 sentence: the Agents tier is not usable. */+ const [blocked, setBlocked] = useState<string | null>(null);+ /** 404 from the assistant routes: the running backend predates this panel. */+ const [backendMissing, setBackendMissing] = useState(false);+ const [runError, setRunError] = useState<string | null>(null);+ const [draft, setDraft] = useState("");+ const [confirmed, setConfirmed] = useState<{ hash: string; steps: ProposalStep[] } | null>(null);+ const answered = useRef<Set<string>>(new Set());++ const running = isRunning(items);++ // The one session per install: open it (and its socket) when the panel mounts.+ useEffect(() => {+ let cancelled = false;+ void (async () => {+ try {+ const s = await getAssistantSession(providerId);+ if (cancelled) return;+ if (s.session_id) openSession(s.session_id);+ } catch (err) {+ if (cancelled) return;+ if (err instanceof AssistantApiError && err.status === 404) setBackendMissing(true);+ }+ })();+ return () => {+ cancelled = true;+ };+ }, [providerId, openSession]);++ useEffect(() => () => disconnect(), [disconnect]);++ const loadHealth = useCallback(async () => {+ try {+ setHealth(await getAssistantHealth(providerId));+ } catch (err) {+ if (err instanceof AssistantApiError && err.status === 404) setBackendMissing(true);+ // No health record yet is a normal state (monitor not run); nothing to show.+ }+ }, [providerId]);++ useEffect(() => {+ void loadHealth();+ }, [loadHealth]);++ useEffect(() => {+ setConfirmed(activeSessionId ? (confirmedBySession.get(activeSessionId) ?? null) : null);+ answered.current = new Set();+ }, [activeSessionId]);++ const run = useCallback(+ async (mode: AssistantMode) => {+ setStarting(mode);+ setBlocked(null);+ setRunError(null);+ try {+ const res = await runAssistant(providerId, mode);+ if (res.session_id !== activeSessionId) openSession(res.session_id);+ } catch (err) {+ if (err instanceof AssistantApiError && err.status === 409) setBlocked(err.message);+ else if (err instanceof AssistantApiError && err.status === 404) setBackendMissing(true);+ else setRunError(err instanceof Error ? err.message : String(err));+ } finally {+ setStarting(null);+ }+ },+ [providerId, activeSessionId, openSession],+ );++ // The section's button click is the request; run it once per token.+ const lastToken = useRef<number | null>(null);+ useEffect(() => {+ if (!request || request.token === lastToken.current) return;+ lastToken.current = request.token;+ void run(request.mode);+ }, [request, run]);++ useEffect(() => {+ if (!running) void loadHealth();+ }, [running, loadHealth]);++ // The plan in the last finished turn, if any.+ const proposal: { value: Proposal; turnId: string } | null = useMemo(() => {+ const last = lastAssistantText(items);+ if (!last) return null;+ const value = proposalFromText(last.text);+ return value ? { value, turnId: last.turnId } : null;+ }, [items]);++ const onConfirm = useCallback(+ async (steps: ProposalStep[], message: string) => {+ if (!proposal || !activeSessionId) return;+ const record = { hash: proposalHash(proposal.value), steps };+ confirmedBySession.set(activeSessionId, record);+ setConfirmed(record);+ await send(message);+ },+ [proposal, activeSessionId, send],+ );++ // One click covers the runner's questions about exactly the confirmed steps.+ useEffect(() => {+ if (!confirmed) return;+ for (const approval of pendingApprovals) {+ if (answered.current.has(approval.approvalId)) continue;+ if (!matchesConfirmedStep({ name: approval.name, input: approval.input }, confirmed.steps)) continue;+ answered.current.add(approval.approvalId);+ void decide(approval.approvalId, "allow");+ }+ }, [pendingApprovals, confirmed, decide]);++ const onDecide = useCallback(+ (approvalId: string, decision: ApprovalDecision) => {+ answered.current.add(approvalId);+ void decide(approvalId, decision);+ },+ [decide],+ );++ const providerLabel = useCallback((id: string) => id, []);++ const submit = useCallback(async () => {+ const text = draft.trim();+ if (!text || !activeSessionId || busy || running) return;+ setDraft("");+ await send(text);+ }, [draft, activeSessionId, busy, running, send]);++ const checkedAt = assistantTimestamp(health?.checked_at);+ const healthTone =+ health?.status === "ok" ? "ok" : health?.status === "unknown" || !health ? "off" : "warn";+ const needsFix = health?.status === "error" || health?.status === "needs_setup";++ return (+ <Panel className="p-4">+ <div className="space-y-4" data-testid="local-models-assistant">+ <div className="flex flex-wrap items-center justify-between gap-2">+ <div className="flex flex-wrap items-center gap-2">+ <SoftButton+ primary+ onClick={() => void run("setup")}+ disabled={starting !== null || running}+ >+ <Sparkles className="h-3.5 w-3.5" />+ {t("local_models.assistant.action_setup")}+ </SoftButton>+ <SoftButton onClick={() => void run("test")} disabled={starting !== null || running}>+ <FlaskConical className="h-3.5 w-3.5" />+ {t("local_models.assistant.action_test")}+ </SoftButton>+ <SoftButton onClick={() => void run("diagnose")} disabled={starting !== null || running}>+ <AlertTriangle className="h-3.5 w-3.5" />+ {t("local_models.assistant.action_diagnose")}+ </SoftButton>+ </div>+ <div className="flex items-center gap-2">+ {running && (+ <SoftButton onClick={() => void cancel()} ariaLabel={t("local_models.assistant.cancel")}>+ <Square className="h-3.5 w-3.5" />+ {t("local_models.assistant.cancel")}+ </SoftButton>+ )}+ {onClose && (+ <SoftButton onClick={onClose} ariaLabel={t("local_models.assistant.close")}>+ <X className="h-3.5 w-3.5" />+ </SoftButton>+ )}+ </div>+ </div>++ {health && checkedAt && (+ <p className="flex flex-wrap items-center gap-3 text-sm" data-testid="assistant-health">+ <StatusDot+ tone={healthTone}+ label={fill(t("local_models.assistant.last_check"), {+ when: checkedAt.toLocaleString(),+ what: health.reason || t(`local_models.assistant.health_${health.status}`),+ })}+ />+ {needsFix && (+ <button+ type="button"+ className="text-sm font-medium text-primary underline-offset-4 hover:underline"+ onClick={() => void run("diagnose")}+ data-testid="assistant-health-fix"+ >+ {t("local_models.assistant.fix")}+ </button>+ )}+ </p>+ )}++ {blocked && (+ <div+ className="flex flex-wrap items-center justify-between gap-3 rounded-lg border border-amber-500/40 bg-amber-500/10 px-3 py-2 text-sm"+ data-testid="assistant-blocked"+ >+ <span>{blocked}</span>+ <SoftButton onClick={onOpenApiKeys}>{t("local_models.assistant.open_api_keys")}</SoftButton>+ </div>+ )}++ {backendMissing && (+ <p className="text-sm text-muted-foreground" data-testid="assistant-backend-missing">+ {t("local_models.assistant.backend_missing")}+ </p>+ )}++ {(runError || lastError) && (+ <p className="text-sm text-destructive" data-testid="assistant-error">+ {runError ?? lastError}+ </p>+ )}++ {items.length === 0 && !blocked && !backendMissing && (+ <p className="text-sm text-muted-foreground">+ {starting ? t("local_models.assistant.starting") : t("local_models.assistant.empty")}+ </p>+ )}++ {items.length > 0 && (+ <div className="flex max-h-[60vh] flex-col gap-5 overflow-y-auto pr-1" data-testid="assistant-timeline">+ <AgentTimeline+ items={items}+ assistantName={assistantName}+ providerLabel={providerLabel}+ onDecide={onDecide}+ />+ </div>+ )}++ {proposal && (+ <SetupProposalCard+ key={proposal.turnId}+ proposal={proposal.value}+ onConfirm={onConfirm}+ busy={running || busy}+ confirmedHash={confirmed?.hash ?? null}+ />+ )}++ {proposal?.value.brain_switch && !running && (+ <BrainSwitchCard+ provider={proposal.value.brain_switch.provider}+ why={proposal.value.brain_switch.why}+ serverLabel={serverLabel}+ />+ )}++ <form+ className="flex items-end gap-2"+ onSubmit={(e) => {+ e.preventDefault();+ void submit();+ }}+ >+ <textarea+ value={draft}+ onChange={(e) => setDraft(e.target.value)}+ onKeyDown={(e) => {+ if (e.key === "Enter" && !e.shiftKey) {+ e.preventDefault();+ void submit();+ }+ }}+ rows={2}+ disabled={!activeSessionId}+ placeholder={+ activeSessionId+ ? t("local_models.assistant.composer_placeholder")+ : t("local_models.assistant.composer_locked")+ }+ aria-label={t("local_models.assistant.composer_placeholder")}+ data-testid="assistant-composer"+ className={cn(+ "min-h-[2.5rem] flex-1 resize-none rounded-lg border border-border bg-background px-3 py-2 text-sm text-foreground",+ "placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-primary/40",+ "disabled:cursor-not-allowed disabled:opacity-60",+ )}+ />+ <SoftButton+ primary+ ariaLabel={t("local_models.assistant.send")}+ onClick={() => void submit()}+ disabled={!activeSessionId || !draft.trim() || busy || running}+ >+ <Send className="h-3.5 w-3.5" />+ </SoftButton>+ </form>++ {onOpenServerLog && (+ <button+ type="button"+ onClick={onOpenServerLog}+ className="text-xs text-muted-foreground underline-offset-4 hover:text-foreground hover:underline"+ data-testid="assistant-open-server-log"+ >+ {t("local_models.assistant.open_server_log")}+ </button>+ )}+ </div>+ </Panel>+ );+}diff --git a/jarvis/ui/web/frontend/src/components/local-models/SetupProposalCard.test.tsx b/jarvis/ui/web/frontend/src/components/local-models/SetupProposalCard.test.tsxnew file mode 100644index 0000000000..1d56c507ee--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/local-models/SetupProposalCard.test.tsx@@ -0,0 +1,90 @@+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}${Object.values(vars).join("|")}`,+}));++const { switchBrainProvider } = vi.hoisted(() => ({+ switchBrainProvider: vi.fn(async (_id: string) => undefined),+}));+vi.mock("@/hooks/useProviders", () => ({ switchBrainProvider }));++import { BrainSwitchCard, SetupProposalCard } from "./SetupProposalCard";+import { proposalHash, type Proposal } from "./assistantProposal";++const PROPOSAL: Proposal = {+ version: 1,+ steps: [+ { id: "s1", kind: "pull", model: "qwen3.5:8b", size_gb: 5.2, proven: "proven", label: "Download Qwen" },+ { id: "s2", kind: "set_role", role: "chat", model: "qwen3.5:8b", proven: "new_little_tested", label: "Use for Chat" },+ { id: "s3", kind: "test", proven: "stale", label: "Test it" },+ ],+ brain_switch: null,+ notes: ["Nothing is deleted."],+};++afterEach(() => {+ cleanup();+ vi.clearAllMocks();+});++describe("SetupProposalCard", () => {+ it("lists every step with its badge and confirms all of them in one click", async () => {+ const onConfirm = vi.fn(async () => undefined);+ render(<SetupProposalCard proposal={PROPOSAL} onConfirm={onConfirm} />);++ expect(screen.getByTestId("proposal-badge-proven")).toBeDefined();+ expect(screen.getByTestId("proposal-badge-new_little_tested")).toBeDefined();+ expect(screen.getByTestId("proposal-badge-stale")).toBeDefined();+ expect(screen.getByText("5.2 GB")).toBeDefined();+ expect(screen.getByText("Nothing is deleted.")).toBeDefined();++ fireEvent.click(screen.getByTestId("proposal-confirm"));+ await waitFor(() => expect(onConfirm).toHaveBeenCalledTimes(1));+ const [steps, message] = onConfirm.mock.calls[0] as unknown as [Proposal["steps"], string];+ expect(steps.map((s) => s.id)).toEqual(["s1", "s2", "s3"]);+ expect(message).toBe(`Execute steps: s1, s2, s3 (proposal v1, hash ${proposalHash(PROPOSAL)})`);+ });++ it("leaves an unticked step out of the confirmation", async () => {+ const onConfirm = vi.fn(async () => undefined);+ render(<SetupProposalCard proposal={PROPOSAL} onConfirm={onConfirm} />);++ fireEvent.click(screen.getByTestId("proposal-step-s2"));+ expect(screen.getByTestId("proposal-confirm").textContent).toContain(+ "local_models.assistant.confirm_some",+ );+ fireEvent.click(screen.getByTestId("proposal-confirm"));+ await waitFor(() => expect(onConfirm).toHaveBeenCalledTimes(1));+ const [steps, message] = onConfirm.mock.calls[0] as unknown as [Proposal["steps"], string];+ expect(steps.map((s) => s.id)).toEqual(["s1", "s3"]);+ expect(message.startsWith("Execute steps: s1, s3 ")).toBe(true);+ });++ it("cannot confirm nothing, and shows the receipt once confirmed", () => {+ const onConfirm = vi.fn(async () => undefined);+ const { rerender } = render(<SetupProposalCard proposal={PROPOSAL} onConfirm={onConfirm} />);+ for (const id of ["s1", "s2", "s3"]) fireEvent.click(screen.getByTestId(`proposal-step-${id}`));+ expect((screen.getByTestId("proposal-confirm") as HTMLButtonElement).disabled).toBe(true);++ rerender(+ <SetupProposalCard proposal={PROPOSAL} onConfirm={onConfirm} confirmedHash={proposalHash(PROPOSAL)} />,+ );+ expect(screen.queryByTestId("proposal-confirm")).toBeNull();+ expect(screen.getByTestId("proposal-confirmed")).toBeDefined();+ });+});++describe("BrainSwitchCard", () => {+ it("switches the brain only on the user's click", async () => {+ render(<BrainSwitchCard provider="ollama" why="Runs locally." serverLabel="Ollama" />);+ expect(switchBrainProvider).not.toHaveBeenCalled();+ fireEvent.click(screen.getByTestId("brain-switch-run"));+ await waitFor(() => expect(switchBrainProvider).toHaveBeenCalledWith("ollama"));+ await waitFor(() => expect(screen.queryByTestId("brain-switch-run")).toBeNull());+ expect(screen.getByText(/brain_switch_done/)).toBeDefined();+ });+});diff --git a/jarvis/ui/web/frontend/src/components/local-models/SetupProposalCard.tsx b/jarvis/ui/web/frontend/src/components/local-models/SetupProposalCard.tsxnew file mode 100644index 0000000000..306fa10961--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/local-models/SetupProposalCard.tsx@@ -0,0 +1,246 @@+/**+ * The assistant's plan as a checklist the user confirms ONCE.+ *+ * Built from the onboarding register (numbered rows separated by hairlines)+ * so it reads as a document, not a dialog: every step is a row with a+ * checkbox, the model it pulls or assigns, a size, and a badge that says how+ * proven the model is. Unchecking a row leaves it out of the confirmation;+ * the one primary action sends "Execute steps: … (proposal v1, hash …)" and+ * the caller remembers the confirmed steps so the runner's approval cards+ * for exactly those steps are answered without another click.+ *+ * A `brain_switch` never runs by itself (the brain provider is the user's+ * lock): it is a separate card whose button calls the ordinary switch route+ * only when the user clicks it.+ */+import { Check, Download, FlaskConical, Mic, Settings2, Terminal, Wand2 } from "lucide-react";+import { useCallback, useMemo, useState, type ReactNode } from "react";++import { Button } from "@/components/agentic/controls";+import { Panel, StatusDot } from "@/components/extensions/primitives";+import { Register, StepFooter, StepSection } from "@/components/onboarding/primitives";+import { switchBrainProvider } from "@/hooks/useProviders";+import { fill, useT } from "@/i18n";+import { cn } from "@/lib/utils";++import {+ confirmationMessage,+ proposalHash,+ type Proposal,+ type ProposalStep,+ type ProposalStepKind,+ type ProvenLabel,+} from "./assistantProposal";++const STEP_ICON: Record<ProposalStepKind, ReactNode> = {+ install_ollama: <Terminal className="h-4 w-4" />,+ pull: <Download className="h-4 w-4" />,+ set_role: <Wand2 className="h-4 w-4" />,+ set_options: <Settings2 className="h-4 w-4" />,+ apply_voice_stack: <Mic className="h-4 w-4" />,+ test: <FlaskConical className="h-4 w-4" />,+};++function ProvenBadge({ proven }: { proven: ProvenLabel | null }) {+ const t = useT();+ if (!proven) return null;+ const tone = proven === "proven" ? "ok" : proven === "stale" ? "warn" : "busy";+ return (+ <span data-testid={`proposal-badge-${proven}`} className="shrink-0">+ <StatusDot tone={tone} label={t(`local_models.assistant.badge_${proven}`)} />+ </span>+ );+}++function formatSize(gb: number | undefined): string | null {+ if (gb === undefined || !Number.isFinite(gb) || gb <= 0) return null;+ return `${gb >= 10 ? Math.round(gb) : gb.toFixed(1)} GB`;+}++export function SetupProposalCard({+ proposal,+ onConfirm,+ busy,+ confirmedHash,+}: {+ proposal: Proposal;+ /** Sends the confirmation message and remembers the checked steps. */+ onConfirm: (steps: ProposalStep[], message: string) => void | Promise<void>;+ /** A turn is running — the plan cannot be confirmed twice. */+ busy?: boolean;+ /** The hash of an already-confirmed plan: the card shows the receipt instead of the button. */+ confirmedHash?: string | null;+}) {+ const t = useT();+ const hash = useMemo(() => proposalHash(proposal), [proposal]);+ const [excluded, setExcluded] = useState<ReadonlySet<string>>(() => new Set());+ const [sending, setSending] = useState(false);+ const confirmed = confirmedHash === hash;++ const toggle = useCallback((id: string) => {+ setExcluded((prev) => {+ const next = new Set(prev);+ if (next.has(id)) next.delete(id);+ else next.add(id);+ return next;+ });+ }, []);++ const chosen = proposal.steps.filter((s) => !excluded.has(s.id));++ const confirm = useCallback(async () => {+ if (chosen.length === 0 || sending) return;+ setSending(true);+ try {+ await onConfirm(chosen, confirmationMessage(proposal, chosen));+ } finally {+ setSending(false);+ }+ }, [chosen, onConfirm, proposal, sending]);++ return (+ <Panel className="p-4">+ <div data-testid="setup-proposal" data-hash={hash} className="space-y-6">+ <StepSection label={t("local_models.assistant.proposal_title")}>+ <p className="text-sm text-muted-foreground">+ {t("local_models.assistant.proposal_hint")}+ </p>+ <Register+ items={proposal.steps.map((step) => {+ const off = excluded.has(step.id);+ const size = formatSize(step.size_gb);+ return {+ key: step.id,+ icon: STEP_ICON[step.kind],+ children: (+ <label+ className={cn(+ "flex cursor-pointer items-start gap-3",+ off && "text-muted-foreground line-through decoration-border",+ )}+ >+ <input+ type="checkbox"+ className="mt-1 h-4 w-4 shrink-0 accent-primary"+ checked={!off && !confirmed}+ disabled={confirmed}+ onChange={() => toggle(step.id)}+ aria-label={step.label}+ data-testid={`proposal-step-${step.id}`}+ />+ <span className="flex min-w-0 flex-1 flex-col gap-1">+ <span className="flex flex-wrap items-center gap-x-3 gap-y-1">+ <span className="font-medium text-foreground">{step.label}</span>+ <ProvenBadge proven={step.proven} />+ </span>+ {(step.model || size || step.fit) && (+ <span className="flex flex-wrap gap-x-3 font-mono text-[12px] text-muted-foreground">+ {step.model && <span>{step.model}</span>}+ {size && <span>{size}</span>}+ {step.fit && <span>{step.fit}</span>}+ </span>+ )}+ </span>+ </label>+ ),+ };+ })}+ />+ {proposal.notes.length > 0 && (+ <ul className="space-y-1 text-sm text-muted-foreground">+ {proposal.notes.map((note, i) => (+ <li key={i}>{note}</li>+ ))}+ </ul>+ )}+ </StepSection>++ {confirmed ? (+ <p+ className="flex items-center gap-2 text-sm text-muted-foreground"+ data-testid="proposal-confirmed"+ >+ <Check className="h-4 w-4 text-primary" />+ {fill(t("local_models.assistant.proposal_confirmed"), { hash })}+ </p>+ ) : (+ <StepFooter+ onBack={null}+ hidePrimaryArrow+ primary={{+ label:+ chosen.length === proposal.steps.length+ ? t("local_models.assistant.confirm_all")+ : fill(t("local_models.assistant.confirm_some"), { count: chosen.length }),+ onClick: () => void confirm(),+ disabled: chosen.length === 0 || Boolean(busy),+ busy: sending,+ testId: "proposal-confirm",+ }}+ />+ )}+ </div>+ </Panel>+ );+}++/**+ * "Make Ollama the active brain" — the one thing the assistant may only+ * propose. The switch happens on this click and nowhere else.+ */+export function BrainSwitchCard({+ provider,+ why,+ serverLabel,+}: {+ provider: string;+ why: string;+ /** What the section calls the local server ("Ollama"). */+ serverLabel: string;+}) {+ const t = useT();+ const [state, setState] = useState<"idle" | "busy" | "done" | "error">("idle");+ const [error, setError] = useState<string>("");++ const run = useCallback(async () => {+ setState("busy");+ setError("");+ try {+ await switchBrainProvider(provider);+ setState("done");+ } catch (err) {+ setState("error");+ setError(err instanceof Error ? err.message : String(err));+ }+ }, [provider]);++ return (+ <Panel className="p-4">+ <div data-testid="brain-switch-card" className="flex flex-wrap items-center justify-between gap-3">+ <div className="min-w-0 space-y-1">+ <p className="font-medium text-foreground">+ {fill(t("local_models.assistant.brain_switch_title"), { server: serverLabel })}+ </p>+ {why && <p className="text-sm text-muted-foreground">{why}</p>}+ {state === "done" && (+ <StatusDot+ tone="ok"+ label={fill(t("local_models.assistant.brain_switch_done"), { server: serverLabel })}+ />+ )}+ {state === "error" && <StatusDot tone="error" label={error} />}+ </div>+ {state !== "done" && (+ <Button+ variant="primary"+ onClick={() => void run()}+ disabled={state === "busy"}+ data-testid="brain-switch-run"+ >+ {t("local_models.assistant.brain_switch_action")}+ </Button>+ )}+ </div>+ </Panel>+ );+}diff --git a/jarvis/ui/web/frontend/src/components/local-models/assistantApi.ts b/jarvis/ui/web/frontend/src/components/local-models/assistantApi.tsnew file mode 100644index 0000000000..c69a631f51--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/local-models/assistantApi.ts@@ -0,0 +1,111 @@+/**+ * Thin client for the setup assistant's routes+ * (`jarvis/ui/web/local_models_assistant_routes.py`, prefix+ * `/api/providers/{id}/local-models/assistant`). Shapes mirror the backend+ * one-to-one; nothing here decides behaviour. A backend that predates the+ * assistant answers 404 — callers show that honestly instead of a spinner.+ */+import type { AgentChatSurface } from "@/lib/agentChatApi";++export type AssistantMode = "setup" | "diagnose" | "test";++export interface AssistantRunResponse {+ session_id: string;+ turn_id: string;+ surface: AgentChatSurface;+}++export interface AssistantSessionResponse {+ session_id: string | null;+ provider: string;+ model: string;+ ready: boolean;+ reason: string;+}++export type AssistantHealthStatus = "ok" | "error" | "needs_setup" | "unknown";++export interface AssistantHealth {+ status: AssistantHealthStatus;+ reason: string;+ /** ISO timestamp or epoch seconds; null when the monitor has not run. */+ since: string | number | null;+ last_ok: string | number | null;+ checked_at: string | number | null;+}++export interface AssistantRoleResult {+ model: string;+ status: string;+ latency_ms: number | null;+ detail: string;+}++export interface AssistantTestReport {+ checked_at: string | number | null;+ server: Record<string, unknown>;+ roles: Record<string, AssistantRoleResult>;+ voice: Record<string, unknown> | null;+ overall: string;+}++export class AssistantApiError extends Error {+ constructor(+ message: string,+ readonly status: number,+ ) {+ super(message);+ this.name = "AssistantApiError";+ }+}++function base(providerId: string): string {+ return `/api/providers/${encodeURIComponent(providerId)}/local-models/assistant`;+}++async function parse<T>(res: Response, what: string): Promise<T> {+ if (!res.ok) {+ let detail = what;+ try {+ const body = (await res.json()) as { detail?: unknown };+ if (typeof body.detail === "string" && body.detail.trim()) detail = body.detail;+ } catch {+ // no JSON body — the generic label stands+ }+ throw new AssistantApiError(detail, res.status);+ }+ return (await res.json()) as T;+}++export async function runAssistant(+ providerId: string,+ mode: AssistantMode,+): Promise<AssistantRunResponse> {+ return parse(+ await fetch(`${base(providerId)}/run`, {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ mode }),+ }),+ "assistant-run-failed",+ );+}++export async function getAssistantSession(providerId: string): Promise<AssistantSessionResponse> {+ return parse(await fetch(`${base(providerId)}/session`, { cache: "no-store" }), "assistant-session-failed");+}++export async function getAssistantHealth(providerId: string): Promise<AssistantHealth> {+ return parse(await fetch(`${base(providerId)}/health`, { cache: "no-store" }), "assistant-health-failed");+}++export async function runAssistantTest(providerId: string): Promise<AssistantTestReport> {+ return parse(await fetch(`${base(providerId)}/test`, { method: "POST" }), "assistant-test-failed");+}++/** Turns the backend's `since` / `checked_at` (ISO or epoch seconds) into a Date, or null. */+export function assistantTimestamp(value: string | number | null | undefined): Date | null {+ if (value === null || value === undefined || value === "") return null;+ const d = typeof value === "number" ? new Date(value * 1000) : new Date(value);+ return Number.isNaN(d.getTime()) ? null : d;+}diff --git a/jarvis/ui/web/frontend/src/components/local-models/assistantProposal.test.ts b/jarvis/ui/web/frontend/src/components/local-models/assistantProposal.test.tsnew file mode 100644index 0000000000..7e282773c6--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/local-models/assistantProposal.test.ts@@ -0,0 +1,116 @@+import { describe, expect, it } from "vitest";++import {+ confirmationMessage,+ matchesConfirmedStep,+ proposalFromText,+ proposalHash,+ type Proposal,+} from "./assistantProposal";++const BLOCK = `{+ "version": 1,+ "steps": [+ {"id": "s1", "kind": "pull", "model": "qwen3.5:8b", "size_gb": 5.2, "fit": "fits in VRAM", "proven": true, "label": "Download Qwen 3.5 8B"},+ {"id": "s2", "kind": "set_role", "role": "chat", "model": "qwen3.5:8b", "proven": "proven", "label": "Use it for Chat"},+ {"id": "s3", "kind": "pull", "model": "nomic-embed-text", "proven": "new_little_tested", "label": "Download the embedding model"},+ {"id": "s4", "kind": "test", "label": "Test the setup"}+ ],+ "brain_switch": {"provider": "ollama", "why": "Everything runs locally now."},+ "notes": ["Nothing is deleted."]+}`;++describe("proposalFromText", () => {+ it("finds a fenced jarvis-proposal block and validates it", () => {+ const p = proposalFromText(`Here is my plan.\n\n\`\`\`jarvis-proposal\n${BLOCK}\n\`\`\`\n`);+ expect(p).not.toBeNull();+ expect(p!.steps.map((s) => s.id)).toEqual(["s1", "s2", "s3", "s4"]);+ expect(p!.steps[0]).toMatchObject({ kind: "pull", model: "qwen3.5:8b", size_gb: 5.2, proven: "proven" });+ expect(p!.steps[2].proven).toBe("new_little_tested");+ expect(p!.steps[3].proven).toBeNull();+ expect(p!.brain_switch).toEqual({ provider: "ollama", why: "Everything runs locally now." });+ expect(p!.notes).toEqual(["Nothing is deleted."]);+ });++ it("takes the LAST block when the assistant corrected itself", () => {+ const first = BLOCK.replace('"id": "s1"', '"id": "old"');+ const text = `\`\`\`jarvis-proposal\n${first}\n\`\`\`\nActually, a better plan:\n\`\`\`jarvis-proposal\n${BLOCK}\n\`\`\``;+ expect(proposalFromText(text)!.steps[0].id).toBe("s1");+ });++ it("tolerates trailing prose and a missing closing fence", () => {+ const text = `\`\`\`jarvis-proposal\n${BLOCK}\nShall I go ahead?`;+ expect(proposalFromText(text)!.steps).toHaveLength(4);+ });++ it("returns null for prose, other fences, malformed JSON, or unknown kinds only", () => {+ expect(proposalFromText("No plan here.")).toBeNull();+ expect(proposalFromText("```json\n{\"version\":1,\"steps\":[]}\n```")).toBeNull();+ expect(proposalFromText("```jarvis-proposal\n{not json\n```")).toBeNull();+ expect(+ proposalFromText('```jarvis-proposal\n{"version":1,"steps":[{"kind":"delete","model":"x"}]}\n```'),+ ).toBeNull();+ });++ it("drops unknown step kinds but keeps the known ones, and de-duplicates ids", () => {+ const p = proposalFromText(+ '```jarvis-proposal\n{"version":1,"steps":[{"id":"a","kind":"pull","model":"m"},{"id":"a","kind":"pull","model":"n"},{"id":"b","kind":"delete"}]}\n```',+ );+ expect(p!.steps.map((s) => s.id)).toEqual(["a", "a-2"]);+ });+});++describe("proposalHash", () => {+ it("is short, stable, and independent of key order and notes", () => {+ const a = proposalFromText(`\`\`\`jarvis-proposal\n${BLOCK}\n\`\`\``)!;+ const reordered: Proposal = {+ ...a,+ notes: [],+ steps: a.steps.map((s) => Object.fromEntries(Object.entries(s).reverse()) as typeof s),+ };+ expect(proposalHash(a)).toMatch(/^[0-9a-f]{8}$/);+ expect(proposalHash(reordered)).toBe(proposalHash(a));+ const changed: Proposal = { ...a, steps: [{ ...a.steps[0], model: "other" }, ...a.steps.slice(1)] };+ expect(proposalHash(changed)).not.toBe(proposalHash(a));+ });++ it("names the chosen steps and the hash in the confirmation", () => {+ const p = proposalFromText(`\`\`\`jarvis-proposal\n${BLOCK}\n\`\`\``)!;+ expect(confirmationMessage(p, [p.steps[0], p.steps[3]])).toBe(+ `Execute steps: s1, s4 (proposal v1, hash ${proposalHash(p)})`,+ );+ });+});++describe("matchesConfirmedStep", () => {+ const p = proposalFromText(`\`\`\`jarvis-proposal\n${BLOCK}\n\`\`\``)!;+ const confirmed = p.steps;++ it("answers pulls and role writes for exactly the confirmed model", () => {+ expect(matchesConfirmedStep({ name: "lm_pull", input: { model: "qwen3.5:8b" } }, confirmed)).toBe(true);+ // Ollama's implicit tag is the same model.+ expect(matchesConfirmedStep({ name: "lm_pull", input: { model: "nomic-embed-text:latest" } }, confirmed)).toBe(true);+ expect(matchesConfirmedStep({ name: "lm_pull", input: { model: "llama4:70b" } }, confirmed)).toBe(false);+ expect(+ matchesConfirmedStep({ name: "lm_set_role", input: { role: "chat", model: "qwen3.5:8b" } }, confirmed),+ ).toBe(true);+ expect(+ matchesConfirmedStep({ name: "lm_set_role", input: { role: "deep", model: "qwen3.5:8b" } }, confirmed),+ ).toBe(false);+ });++ it("covers the server start, the test, and nothing outside the plan", () => {+ expect(matchesConfirmedStep({ name: "lm_start_server", input: {} }, confirmed)).toBe(true);+ expect(matchesConfirmedStep({ name: "lm_test_plan", input: {} }, confirmed)).toBe(true);+ expect(matchesConfirmedStep({ name: "lm_install_ollama", input: {} }, confirmed)).toBe(false);+ expect(matchesConfirmedStep({ name: "lm_apply_voice_stack", input: {} }, confirmed)).toBe(false);+ expect(matchesConfirmedStep({ name: "lm_set_model_options", input: { model: "qwen3.5:8b" } }, confirmed)).toBe(false);+ expect(matchesConfirmedStep({ name: "lm_delete", input: { model: "qwen3.5:8b" } }, confirmed)).toBe(false);+ expect(matchesConfirmedStep({ name: "lm_pull", input: { model: "qwen3.5:8b" } }, [])).toBe(false);+ });++ it("only the steps left ticked count", () => {+ const withoutEmbed = confirmed.filter((s) => s.id !== "s3");+ expect(matchesConfirmedStep({ name: "lm_pull", input: { model: "nomic-embed-text" } }, withoutEmbed)).toBe(false);+ });+});diff --git a/jarvis/ui/web/frontend/src/components/local-models/assistantProposal.ts b/jarvis/ui/web/frontend/src/components/local-models/assistantProposal.tsnew file mode 100644index 0000000000..a9c27ad10e--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/local-models/assistantProposal.ts@@ -0,0 +1,268 @@+/**+ * The setup assistant's proposal contract, on the client side.+ *+ * The assistant (an agent-chat session on the `local-models` surface) ends a+ * planning turn with ONE fenced ```jarvis-proposal JSON block — the plan the+ * user confirms in a single click. This module finds that block in the+ * assistant's prose, validates it into a `Proposal`, hashes it so the+ * confirmation names exactly what was shown, and decides whether a later+ * `approval_required` event asks for something the user already confirmed+ * (so the card can be answered for them). `reduce.ts` is untouched: the+ * proposal is read from the finished text, never from the event stream.+ */++export type ProposalStepKind =+ | "install_ollama"+ | "pull"+ | "set_role"+ | "set_options"+ | "apply_voice_stack"+ | "test";++/** How well-trodden the model behind a step is; `null` when the step has no model. */+export type ProvenLabel = "proven" | "new_little_tested" | "stale";++export interface ProposalStep {+ id: string;+ kind: ProposalStepKind;+ model?: string;+ role?: string;+ options?: Record<string, unknown>;+ size_gb?: number;+ fit?: string;+ proven: ProvenLabel | null;+ label: string;+}++export interface BrainSwitch {+ provider: string;+ why: string;+}++export interface Proposal {+ version: 1;+ steps: ProposalStep[];+ brain_switch: BrainSwitch | null;+ notes: string[];+}++const STEP_KINDS: ReadonlySet<string> = new Set([+ "install_ollama",+ "pull",+ "set_role",+ "set_options",+ "apply_voice_stack",+ "test",+]);++const FENCE_OPEN = /```jarvis-proposal[^\n]*\n/g;++function str(v: unknown): string | undefined {+ return typeof v === "string" && v.trim() ? v.trim() : undefined;+}++function provenOf(v: unknown): ProvenLabel | null {+ if (v === true || v === "proven") return "proven";+ if (v === false || v === "new_little_tested") return "new_little_tested";+ if (v === "stale") return "stale";+ return null;+}++function stepOf(raw: unknown, index: number): ProposalStep | null {+ if (!raw || typeof raw !== "object") return null;+ const r = raw as Record<string, unknown>;+ const kind = str(r.kind);+ if (!kind || !STEP_KINDS.has(kind)) return null;+ const model = str(r.model);+ const role = str(r.role);+ const id = str(r.id) ?? `${kind}-${index + 1}`;+ const label = str(r.label) ?? [kind, role, model].filter(Boolean).join(" ");+ const step: ProposalStep = { id, kind: kind as ProposalStepKind, proven: provenOf(r.proven), label };+ if (model) step.model = model;+ if (role) step.role = role;+ if (r.options && typeof r.options === "object" && !Array.isArray(r.options)) {+ step.options = r.options as Record<string, unknown>;+ }+ if (typeof r.size_gb === "number" && Number.isFinite(r.size_gb)) step.size_gb = r.size_gb;+ const fit = str(r.fit);+ if (fit) step.fit = fit;+ return step;+}++/** Validates one parsed JSON value into a Proposal; null when it is not one. */+export function proposalFromJson(value: unknown): Proposal | null {+ if (!value || typeof value !== "object") return null;+ const v = value as Record<string, unknown>;+ if (v.version !== 1 && v.version !== "1") return null;+ if (!Array.isArray(v.steps)) return null;+ const steps = v.steps+ .map((s, i) => stepOf(s, i))+ .filter((s): s is ProposalStep => s !== null);+ if (steps.length === 0) return null;+ // Duplicate ids would make "Execute steps: …" ambiguous; suffix the repeats.+ const seen = new Set<string>();+ for (const step of steps) {+ let id = step.id;+ let n = 2;+ while (seen.has(id)) id = `${step.id}-${n++}`;+ seen.add(id);+ step.id = id;+ }+ let brain_switch: BrainSwitch | null = null;+ if (v.brain_switch && typeof v.brain_switch === "object") {+ const b = v.brain_switch as Record<string, unknown>;+ const provider = str(b.provider);+ if (provider) brain_switch = { provider, why: str(b.why) ?? "" };+ }+ const notes = Array.isArray(v.notes)+ ? v.notes.filter((n): n is string => typeof n === "string" && n.trim().length > 0)+ : [];+ return { version: 1, steps, brain_switch, notes };+}++/**+ * The JSON text between a fence opener and its closer. A model that forgot+ * the closing fence (or wrote prose after it) still gets parsed: the block+ * ends at the last `}` that makes the object balance.+ */+function jsonBodyAfter(text: string, start: number): string | null {+ const rest = text.slice(start);+ const close = rest.indexOf("```");+ const candidate = close >= 0 ? rest.slice(0, close) : rest;+ const first = candidate.indexOf("{");+ if (first < 0) return null;+ // Walk to the matching brace so trailing prose inside an unclosed fence is+ // dropped rather than breaking JSON.parse.+ let depth = 0;+ let inString = false;+ let escaped = false;+ for (let i = first; i < candidate.length; i++) {+ const ch = candidate[i];+ if (inString) {+ if (escaped) escaped = false;+ else if (ch === "\\") escaped = true;+ else if (ch === '"') inString = false;+ continue;+ }+ if (ch === '"') inString = true;+ else if (ch === "{") depth++;+ else if (ch === "}") {+ depth--;+ if (depth === 0) return candidate.slice(first, i + 1);+ }+ }+ return null;+}++/**+ * Finds the LAST ```jarvis-proposal block in `text` and returns it as a+ * Proposal, or null when there is none or it does not parse. Later blocks+ * win because a corrected plan follows the plan it corrects.+ */+export function proposalFromText(text: string): Proposal | null {+ if (!text) return null;+ const starts: number[] = [];+ for (const m of text.matchAll(FENCE_OPEN)) starts.push(m.index + m[0].length);+ for (let i = starts.length - 1; i >= 0; i--) {+ const body = jsonBodyAfter(text, starts[i]);+ if (!body) continue;+ try {+ const parsed = proposalFromJson(JSON.parse(body) as unknown);+ if (parsed) return parsed;+ } catch {+ // A malformed block is skipped; an earlier valid one may still apply.+ }+ }+ return null;+}++/** Stable key order so the same plan always hashes the same. */+function canonical(value: unknown): string {+ if (Array.isArray(value)) return `[${value.map(canonical).join(",")}]`;+ if (value && typeof value === "object") {+ const entries = Object.entries(value as Record<string, unknown>)+ .filter(([, v]) => v !== undefined)+ .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));+ return `{${entries.map(([k, v]) => `${JSON.stringify(k)}:${canonical(v)}`).join(",")}}`;+ }+ return JSON.stringify(value) ?? "null";+}++/** Short, stable FNV-1a hash (8 hex chars) over the proposal's steps and switch. */+export function proposalHash(p: Proposal): string {+ const text = canonical({ version: p.version, steps: p.steps, brain_switch: p.brain_switch });+ let h = 0x811c9dc5;+ for (let i = 0; i < text.length; i++) {+ h ^= text.charCodeAt(i);+ h = Math.imul(h, 0x01000193) >>> 0;+ }+ return h.toString(16).padStart(8, "0");+}++/** The one-line confirmation the user's click sends to the assistant. */+export function confirmationMessage(p: Proposal, steps: ProposalStep[]): string {+ return `Execute steps: ${steps.map((s) => s.id).join(", ")} (proposal v${p.version}, hash ${proposalHash(p)})`;+}++/** Ollama treats `name` and `name:latest` as the same model; so do we. */+export function normaliseModel(name: string | undefined): string {+ const n = (name ?? "").trim().toLowerCase();+ return n.endsWith(":latest") ? n.slice(0, -":latest".length) : n;+}++function argString(input: unknown, key: string): string | undefined {+ if (!input || typeof input !== "object") return undefined;+ const v = (input as Record<string, unknown>)[key];+ return typeof v === "string" ? v : undefined;+}++/** What an `approval_required` event carries that the matcher looks at. */+export interface ApprovalRequest {+ /** The tool the runner wants to call (`lm_pull`, `lm_set_role`, …). */+ name: string;+ /** Its arguments, as sent by the runner. */+ input: unknown;+}++/**+ * True when the approval asks for something the user confirmed on the+ * proposal card — that model's pull, that role→model write, the install…+ * Anything not covered (a different model, a tool the plan never named)+ * returns false and the ordinary approval card stays on screen.+ */+export function matchesConfirmedStep(+ approval: ApprovalRequest,+ confirmed: readonly ProposalStep[],+): boolean {+ if (confirmed.length === 0) return false;+ const model = normaliseModel(argString(approval.input, "model"));+ const role = (argString(approval.input, "role") ?? "").trim().toLowerCase();+ const has = (kind: ProposalStepKind) => confirmed.some((s) => s.kind === kind);+ switch (approval.name) {+ case "lm_install_ollama":+ return has("install_ollama");+ case "lm_start_server":+ // Starting the server is implied by any confirmed step: nothing in the+ // plan works without it.+ return true;+ case "lm_pull":+ return confirmed.some((s) => s.kind === "pull" && normaliseModel(s.model) === model);+ case "lm_set_role":+ return confirmed.some(+ (s) =>+ s.kind === "set_role" &&+ (s.role ?? "").toLowerCase() === role &&+ normaliseModel(s.model) === model,+ );+ case "lm_set_model_options":+ return confirmed.some((s) => s.kind === "set_options" && normaliseModel(s.model) === model);+ case "lm_apply_voice_stack":+ case "lm_install_voice_server":+ return has("apply_voice_stack");+ case "lm_test_plan":+ case "lm_test":+ return has("test");+ default:+ return false;+ }+}diff --git a/jarvis/ui/web/frontend/src/components/local-models/assistantStore.ts b/jarvis/ui/web/frontend/src/components/local-models/assistantStore.tsnew file mode 100644index 0000000000..97ea34e375--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/local-models/assistantStore.ts@@ -0,0 +1,10 @@+/**+ * The setup assistant's own agent-chat store — surface `local-models`.+ *+ * A separate store instance means a separate socket, session list and draft:+ * the assistant's session never appears in the front page's chat list and+ * the front page's open chat never bleeds into the Local models section.+ */+import { createAgentChatStore } from "@/store/agentChat";++export const useLocalModelsAssistantStore = createAgentChatStore("local-models");diff --git a/jarvis/ui/web/frontend/src/i18n/local-models-i18n-parity.test.ts b/jarvis/ui/web/frontend/src/i18n/local-models-i18n-parity.test.tsindex 8e953e3b97..a71f9901ff 100644--- a/jarvis/ui/web/frontend/src/i18n/local-models-i18n-parity.test.ts+++ b/jarvis/ui/web/frontend/src/i18n/local-models-i18n-parity.test.ts@@ -29,11 +29,15 @@ const keysFor = (loc: Record<string, unknown>): Set<string> =>const SRC = join(__dirname, "..");const PANEL_DIR = join(SRC, "views", "local-models");+const ASSISTANT_DIR = join(SRC, "components", "local-models");+const sources = (dir: string) =>+ readdirSync(dir)+ .filter((f) => f.endsWith(".tsx") && !f.endsWith(".test.tsx"))+ .map((f) => join(dir, f));const SOURCE_FILES = [join(SRC, "views", "LocalModelsView.tsx"),- ...readdirSync(PANEL_DIR)- .filter((f) => f.endsWith(".tsx") && !f.endsWith(".test.tsx"))- .map((f) => join(PANEL_DIR, f)),+ ...sources(PANEL_DIR),+ ...sources(ASSISTANT_DIR),];/** Literal keys only; template keys (`local_models.tune.${key}`) are covereddiff --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 cfbcfc511a..6b9504a0a7 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@@ -202,8 +202,7 @@"action_setup": "Hilf mir beim Einrichten","action_setup_hint": "Eine geführte Einrichtung für diesen Rechner.","action_broken": "Etwas funktioniert nicht",- "action_broken_hint": "Das Server-Protokoll öffnen.",- "assistant_placeholder": "Der Einrichtungsassistent kommt mit dem nächsten Update.",+ "action_broken_hint": "Den Assistenten fragen, was nicht stimmt.","disk_models": "{count} Modelle","disk_model_one": "1 Modell","gpu_in_use": "{gb} belegt",@@ -382,6 +381,38 @@"footnote_no_alias": "Diese Einstellungen gehen mit jeder Anfrage mit; nichts wird neu gebaut.","num_ctx_over_suggested": "Liegt laut Schätzung über dem, was in diesen Rechner passt (empfohlen {context}; das braucht etwa {estimate} GB). Wird trotzdem übernommen — das Modell kann in den Arbeitsspeicher ausweichen, langsam laufen oder nicht laden. Dein Rechner, deine Entscheidung."},- "tune_missing": "Dieses Modell ist nicht mehr installiert, es gibt also nichts einzustellen."+ "tune_missing": "Dieses Modell ist nicht mehr installiert, es gibt also nichts einzustellen.",+ "assistant": {+ "action_setup": "Hilf mir beim Einrichten",+ "action_test": "Testen",+ "action_diagnose": "Etwas ist kaputt",+ "cancel": "Stopp",+ "close": "Schließen",+ "last_check": "Letzte Prüfung {when} — {what}",+ "health_ok": "alles läuft",+ "health_error": "etwas ist fehlgeschlagen",+ "health_needs_setup": "Einrichtung unvollständig",+ "health_unknown": "noch nicht geprüft",+ "fix": "Beheben",+ "open_api_keys": "API-Schlüssel öffnen",+ "backend_missing": "Das laufende Backend kennt den Einrichtungsassistenten noch nicht — starte die App neu, um das Update zu übernehmen.",+ "starting": "Startet…",+ "empty": "Wähle oben eine Aktion oder stelle unten eine Frage.",+ "composer_placeholder": "Frag den Assistenten…",+ "composer_locked": "Beginne mit einer der Aktionen oben.",+ "send": "Senden",+ "open_server_log": "Stattdessen das Server-Protokoll öffnen",+ "proposal_title": "Vorgeschlagene Einrichtung",+ "proposal_hint": "Hake ab, was du nicht willst. Ein Klick führt den Rest aus und testet das Ergebnis.",+ "proposal_confirmed": "Bestätigt (Plan {hash}) — die Schritte laufen oben.",+ "confirm_all": "Bestätigen und ausführen",+ "confirm_some": "{count} Schritte bestätigen",+ "badge_proven": "bewährt",+ "badge_new_little_tested": "neu, wenig getestet",+ "badge_stale": "veraltet",+ "brain_switch_title": "{server} zum aktiven Gehirn machen",+ "brain_switch_action": "Jetzt umschalten",+ "brain_switch_done": "{server} antwortet ab jetzt"+ }}}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 8d9f930947..c9d315ccc5 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@@ -202,8 +202,7 @@"action_setup": "Help me set up","action_setup_hint": "A guided setup for this machine.","action_broken": "Something is not working",- "action_broken_hint": "Open the server log.",- "assistant_placeholder": "The setup assistant arrives with the next update.",+ "action_broken_hint": "Ask the assistant what is wrong.","disk_models": "{count} models","disk_model_one": "1 model","gpu_in_use": "{gb} in use",@@ -382,6 +381,38 @@"footnote_no_alias": "These settings go with each request; nothing is rebuilt.","num_ctx_over_suggested": "Above what fits this machine by estimate (suggested {context}; this needs roughly {estimate} GB). It will still be applied — the model may spill into system memory, run slowly or fail to load. Your machine, your call."},- "tune_missing": "That model is no longer installed, so there is nothing to tune."+ "tune_missing": "That model is no longer installed, so there is nothing to tune.",+ "assistant": {+ "action_setup": "Help me set up",+ "action_test": "Test",+ "action_diagnose": "Something is broken",+ "cancel": "Stop",+ "close": "Close",+ "last_check": "Last check {when} — {what}",+ "health_ok": "everything works",+ "health_error": "something failed",+ "health_needs_setup": "setup incomplete",+ "health_unknown": "not checked yet",+ "fix": "Fix",+ "open_api_keys": "Open API Keys",+ "backend_missing": "The running backend does not know the setup assistant yet — restart the app to pick up the update.",+ "starting": "Starting…",+ "empty": "Pick one of the buttons above, or ask a question below.",+ "composer_placeholder": "Ask the assistant…",+ "composer_locked": "Start with one of the buttons above.",+ "send": "Send",+ "open_server_log": "Open the server log instead",+ "proposal_title": "Proposed setup",+ "proposal_hint": "Untick anything you do not want. One click runs the rest and tests the result.",+ "proposal_confirmed": "Confirmed (plan {hash}) — the steps run above.",+ "confirm_all": "Confirm and run",+ "confirm_some": "Confirm {count} steps",+ "badge_proven": "proven",+ "badge_new_little_tested": "new, little tested",+ "badge_stale": "stale",+ "brain_switch_title": "Make {server} the active brain",+ "brain_switch_action": "Switch now",+ "brain_switch_done": "{server} answers from now on"+ }}}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 3133577cf8..6a9195e37c 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@@ -202,8 +202,7 @@"action_setup": "Ayúdame a configurar","action_setup_hint": "Una configuración guiada para esta máquina.","action_broken": "Algo no funciona",- "action_broken_hint": "Abrir el registro del servidor.",- "assistant_placeholder": "El asistente de configuración llega con la próxima actualización.",+ "action_broken_hint": "Pregunta al asistente qué falla.","disk_models": "{count} modelos","disk_model_one": "1 modelo","gpu_in_use": "{gb} en uso",@@ -382,6 +381,38 @@"footnote_no_alias": "Estos ajustes van con cada solicitud; no se reconstruye nada.","num_ctx_over_suggested": "Según la estimación supera lo que cabe en este equipo (sugerido {context}; esto necesita unos {estimate} GB). Se aplicará igualmente: el modelo puede pasar a la memoria del sistema, ir lento o no cargar. Tu equipo, tu decisión."},- "tune_missing": "Ese modelo ya no está instalado, así que no hay nada que ajustar."+ "tune_missing": "Ese modelo ya no está instalado, así que no hay nada que ajustar.",+ "assistant": {+ "action_setup": "Ayúdame a configurar",+ "action_test": "Probar",+ "action_diagnose": "Algo está roto",+ "cancel": "Detener",+ "close": "Cerrar",+ "last_check": "Última comprobación {when} — {what}",+ "health_ok": "todo funciona",+ "health_error": "algo falló",+ "health_needs_setup": "configuración incompleta",+ "health_unknown": "aún sin comprobar",+ "fix": "Arreglar",+ "open_api_keys": "Abrir claves API",+ "backend_missing": "El backend en ejecución aún no conoce el asistente de configuración: reinicia la app para aplicar la actualización.",+ "starting": "Iniciando…",+ "empty": "Elige una de las acciones de arriba o haz una pregunta abajo.",+ "composer_placeholder": "Pregunta al asistente…",+ "composer_locked": "Empieza con una de las acciones de arriba.",+ "send": "Enviar",+ "open_server_log": "Abrir el registro del servidor en su lugar",+ "proposal_title": "Configuración propuesta",+ "proposal_hint": "Desmarca lo que no quieras. Un clic ejecuta el resto y prueba el resultado.",+ "proposal_confirmed": "Confirmado (plan {hash}): los pasos se ejecutan arriba.",+ "confirm_all": "Confirmar y ejecutar",+ "confirm_some": "Confirmar {count} pasos",+ "badge_proven": "probado",+ "badge_new_little_tested": "nuevo, poco probado",+ "badge_stale": "desactualizado",+ "brain_switch_title": "Hacer de {server} el cerebro activo",+ "brain_switch_action": "Cambiar ahora",+ "brain_switch_done": "{server} responde a partir de ahora"+ }}}diff --git a/jarvis/ui/web/frontend/src/views/LocalModelsView.test.tsx b/jarvis/ui/web/frontend/src/views/LocalModelsView.test.tsxindex c5c5376aa8..63e89c0a6e 100644--- a/jarvis/ui/web/frontend/src/views/LocalModelsView.test.tsx+++ b/jarvis/ui/web/frontend/src/views/LocalModelsView.test.tsx@@ -100,6 +100,30 @@ vi.mock("@/views/local-models/TuneSheet", () => ({</div>),}));+vi.mock("@/components/local-models/AssistantPanel", () => ({+ AssistantPanel: ({+ request,+ onOpenServerLog,+ onClose,+ }: {+ request: { mode: string; token: number } | null;+ onOpenServerLog?: () => void;+ onClose?: () => void;+ }) => (+ <div+ data-testid="local-models-assistant"+ data-mode={request?.mode ?? ""}+ data-token={request?.token ?? 0}+ >+ <button type="button" onClick={onOpenServerLog}>+ server log+ </button>+ <button type="button" onClick={onClose}>+ close assistant+ </button>+ </div>+ ),+}));vi.mock("@/hooks/useLocalModels", () => ({useInventory: () => ({isLoading: false,@@ -258,23 +282,42 @@ describe("LocalModelsView", () => {expect(screen.getByText("local_models.no_provider")).toBeDefined();});- it("wires the overview actions: browse, assistant placeholder, server log", () => {+ it("wires the overview actions: browse, the assistant in setup mode, diagnose mode, server log", () => {render(<LocalModelsView />);+ // "Help me set up" opens the assistant and asks for a setup run; a+ // second click closes it again.fireEvent.click(screen.getByRole("button", { name: "assistant" }));- expect(screen.getByTestId("local-models-assistant")).toBeDefined();+ const panel = screen.getByTestId("local-models-assistant");+ expect(panel.getAttribute("data-mode")).toBe("setup");+ expect(panel.getAttribute("data-token")).toBe("1");fireEvent.click(screen.getByRole("button", { name: "assistant" }));expect(screen.queryByTestId("local-models-assistant")).toBeNull();fireEvent.click(screen.getByRole("button", { name: "browse" }));expect(screen.getByTestId("catalogue-panel")).toBeDefined();+ // "Something is not working" opens the assistant in diagnose mode and+ // stays on the overview; the server log is one link away inside it.fireEvent.click(screen.getByRole("tab", { name: "local_models.tab_overview" }),);fireEvent.click(screen.getByRole("button", { name: "broken" }));+ const diagnose = screen.getByTestId("local-models-assistant");+ expect(diagnose.getAttribute("data-mode")).toBe("diagnose");+ expect(diagnose.getAttribute("data-token")).toBe("2");+ expect(screen.queryByTestId("server-panel")).toBeNull();++ fireEvent.click(screen.getByRole("button", { name: "server log" }));expect(screen.getByTestId("server-panel").getAttribute("data-log-open"),).toBe("yes");});++ it("closes the assistant from its own close button", () => {+ render(<LocalModelsView />);+ fireEvent.click(screen.getByRole("button", { name: "assistant" }));+ fireEvent.click(screen.getByRole("button", { name: "close assistant" }));+ expect(screen.queryByTestId("local-models-assistant")).toBeNull();+ });});diff --git a/jarvis/ui/web/frontend/src/views/LocalModelsView.tsx b/jarvis/ui/web/frontend/src/views/LocalModelsView.tsxindex e67195a138..29c189a23e 100644--- a/jarvis/ui/web/frontend/src/views/LocalModelsView.tsx+++ b/jarvis/ui/web/frontend/src/views/LocalModelsView.tsx@@ -35,6 +35,10 @@ import {readLocalModelsSeed,writeLocalModelsSeed,} from "@/lib/localModelsSeed";+import {+ AssistantPanel,+ type AssistantRequest,+} from "@/components/local-models/AssistantPanel";import { CataloguePanel } from "@/views/local-models/CataloguePanel";import { HuggingFacePanel } from "@/views/local-models/HuggingFacePanel";import { InventoryPanel } from "@/views/local-models/InventoryPanel";@@ -142,14 +146,29 @@ export function LocalModelsView() {const [tab, setTab] = useState<LocalModelsTab>("overview");// The model whose Tune sheet is open under the overview ("" = none).const [tuneModel, setTuneModel] = useState<string>("");- // The setup assistant panel under the action row (Part D plugs the real- // panel into `assistantSlot`; until then a one-sentence placeholder).+ // The setup assistant panel under the action row. "Help me set up" toggles+ // it and asks for a setup run; "Something is not working" opens it in+ // diagnose mode (the Server tab with the log stays one link away inside+ // the panel). The token makes a repeated click a repeated request.const [assistantOpen, setAssistantOpen] = useState(false);- // "Something is not working" lands on the Server tab with the log open.+ const [assistantRequest, setAssistantRequest] =+ useState<AssistantRequest | null>(null);const [serverLogOpen, setServerLogOpen] = useState(false);const openBrowse = useCallback(() => setTab("catalogue"), []);- const openAssistant = useCallback(() => setAssistantOpen((v) => !v), []);+ const openAssistant = useCallback(() => {+ setAssistantOpen((open) => {+ if (!open) {+ setAssistantRequest((r) => ({ mode: "setup", token: (r?.token ?? 0) + 1 }));+ }+ return !open;+ });+ }, []);+ const closeAssistant = useCallback(() => setAssistantOpen(false), []);const reportProblem = useCallback(() => {+ setAssistantOpen(true);+ setAssistantRequest((r) => ({ mode: "diagnose", token: (r?.token ?? 0) + 1 }));+ }, []);+ const openServerLog = useCallback(() => {setServerLogOpen(true);setTab("server");}, []);@@ -238,14 +257,14 @@ export function LocalModelsView() {onReportProblem={reportProblem}assistantSlot={assistantOpen ? (- <Panel className="p-4">- <p- className="text-sm text-muted-foreground"- data-testid="local-models-assistant"- >- {t("local_models.overview.assistant_placeholder")}- </p>- </Panel>+ <AssistantPanel+ providerId={providerId}+ serverLabel={descriptor?.label ?? "Ollama"}+ request={assistantRequest}+ onOpenApiKeys={openApiKeys}+ onOpenServerLog={openServerLog}+ onClose={closeAssistant}+ />) : null}/>