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
refactor(local-models): retire the setup helper — the section keeps its panels and the quiet self-check
rubenluetke10-beep698a39f3ae1c
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 886ff798d6..9f258a0c91 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -9,6 +9,17 @@ versioning per [SemVer](https://semver.org/).## [Unreleased]+### Removed++- **The Local models setup helper.** The "Setup helper" tab — a chat that+ proposed a setup, ran it through its own `lm_*` tools and tested the+ result — is gone, along with its "Help me set up" and "Something is not+ working" buttons on the overview, the `local-models` chat surface, the+ `/api/providers/{id}/local-models/assistant/*` routes and the+ `jarvis local-models assistant ...` commands. The section keeps everything+ else: the overview, the catalogue, the server tab, the Tune sheet, and the+ quiet six-hourly self-check behind the sidebar badge.+---## [1.6.0] — 2026-08-25diff --git a/docs/jarvis-cli-reference.md b/docs/jarvis-cli-reference.mdindex e18266d2ea..dad7834a96 100644--- a/docs/jarvis-cli-reference.md+++ b/docs/jarvis-cli-reference.md@@ -113,12 +113,6 @@ _Generated from the curated command tree by `scripts/ci/gen_cli_reference.py`## local-models-- `jarvis local-models assistant benchmarks --refresh --provider` — The benchmark table behind the proven / new labels (cached seven days).-- `jarvis local-models assistant diagnose --provider` — Ask the assistant what is broken and how to fix it.-- `jarvis local-models assistant health --provider` — The last self-check: status, reason, since when, last ok.-- `jarvis local-models assistant session --provider` — The assistant's session and whether the Agents tier can run it.-- `jarvis local-models assistant setup --provider` — Start a guided setup turn; answers with the session and turn ids.-- `jarvis local-models assistant test --role --provider` — Run the end-to-end setup test and print the per-role table.- `jarvis local-models catalog recommended --provider` — The curated shortlist ranked for this machine, with its review date.- `jarvis local-models catalog search <query> --sort --capability --limit --provider` — Browse the library; offline is reported as a sentence, not a failure.- `jarvis local-models catalog tags <name> --provider` — Every tag of one library model with size, quantization, context and fit.diff --git a/docs/jarvis-cli.md b/docs/jarvis-cli.mdindex 8dfc4d5f6f..3340cc3f50 100644--- a/docs/jarvis-cli.md+++ b/docs/jarvis-cli.md@@ -138,10 +138,6 @@ jarvis local-models hf search "llama 3.1 gguf"jarvis local-models hf files bartowski Llama-3.1-8B-Instruct-GGUFjarvis local-models hf pull bartowski Llama-3.1-8B-Instruct-GGUF --quant Q4_K_Mjarvis local-models server status-jarvis local-models assistant setup # the setup assistant proposes one complete setup-jarvis local-models assistant diagnose # names what is broken and the smallest fix-jarvis local-models assistant test # end-to-end test: one line per role, ok / error-jarvis local-models assistant health # the last self-check (status, reason, since)jarvis local-models server test http://127.0.0.1:11434jarvis local-models server log --lines 80jarvis local-models server env-guide --os linuxdiff --git a/jarvis/agent_chat/store.py b/jarvis/agent_chat/store.pyindex a60abeceff..df7f73d373 100644--- a/jarvis/agent_chat/store.py+++ b/jarvis/agent_chat/store.py@@ -73,7 +73,7 @@ _PREVIEW_MAX_CHARS = 120#: ``CreateSessionBody.surface`` in ``jarvis/ui/web/agent_chat_routes.py`` —#: ``tests/unit/agent_chat/test_agent_chat_surface_parity.py`` keeps the three#: in step (AP-4).-SURFACES: Final[tuple[str, ...]] = ("jarvis", "agent", "local-models")+SURFACES: Final[tuple[str, ...]] = ("jarvis", "agent")DEFAULT_SURFACE: Final[str] = "agent"diff --git a/jarvis/agent_chat/surface_kits.py b/jarvis/agent_chat/surface_kits.pyindex 4ebdde1f36..2535c9fbde 100644--- a/jarvis/agent_chat/surface_kits.py+++ b/jarvis/agent_chat/surface_kits.py@@ -1,10 +1,9 @@"""What a chat surface brings to a turn: the runner, the ladder, the hands.-A *surface* is one place a person types to Jarvis: the front page (``jarvis``),-the Agentic IDE's chat mode (``agent``), and the Local models section's setup-assistant (``local-models``). They share the session store, the WebSocket-stream and the approval card; they differ in what answers and with which-tools. Before this module those differences were ``if surface == "jarvis"``+A *surface* is one place a person types to Jarvis: the front page (``jarvis``)+and the Agentic IDE's chat mode (``agent``). They share the session store, the+WebSocket stream and the approval card; they differ in what answers and with+which tools. Before this module those differences were ``if surface == "jarvis"``branches in four files. Now each surface is one :class:`SurfaceKit` here andthe four call sites do one lookup each — a new surface is a new kit, not fournew branches.@@ -18,6 +17,7 @@ from __future__ import annotationsimport loggingfrom collections.abc import Awaitable, Callablefrom dataclasses import dataclass+from pathlib import Pathfrom typing import Any, Finalfrom jarvis.core.protocols import Tool@@ -25,16 +25,10 @@ from jarvis.core.protocols import Toollog = logging.getLogger(__name__)__all__ = [- "LOCAL_MODELS_SURFACE",- "LOCAL_MODELS_TOOL_ORIGIN","SurfaceKit","kit_for",- "local_models_search_fn",]-LOCAL_MODELS_SURFACE: Final[str] = "local-models"-LOCAL_MODELS_TOOL_ORIGIN: Final[str] = "local-models-assistant"-#: The ladder key of the Jarvis ladder (``permissions.JARVIS_LADDER``) —#: spelled here so the kit table does not import the permissions module._JARVIS_LADDER: Final[str] = "jarvis"@@ -64,15 +58,13 @@ class SurfaceKit:``tool_origin`` / ``credential_scope`` / ``max_turns``What the tool context and the override carry; ``max_turns=None``keeps the runner's default.+ ``workspace_dir``+ Where a new session starts when nobody picked a folder; ``None`` =+ the service's own fallback."""surface: strbrain_runner: bool = False- #: Every provider is driven by the brain runner, CLI seats included. A- #: coding agent's own loop has none of this surface's tools, so a seat- #: whose provider also ships a brain plugin (antigravity, codex, claude)- #: must run through Jarvis' brain here rather than its vendor CLI.- brain_only: bool = Falseladder: str | None = Noneuses_stance: bool = Falsetools: ToolsBuilder | None = None@@ -84,85 +76,18 @@ class SurfaceKit:#: surface that only ever needs its own hands keeps the request small#: and free of foreign schemas a provider may refuse. ``None`` = all.tool_filter: Callable[[dict[str, Tool]], dict[str, Tool]] | None = None+ #: The folder a new session of this surface starts in when the person+ #: picked none. ``None`` = the service's fallback (the home directory),+ #: which is what the IDE's chat wants: a coding agent is pointed at a+ #: project, and its composer shows the folder chip so it can be moved.+ workspace_dir: Callable[[], Path] | None = None-# ── local-models builders ─────────────────────────────────────────────────---def _config_of(cfg: Any, brain: Any) -> Any:- if cfg is not None:- return cfg- live = getattr(brain, "_config", None)- if live is not None:- return live- from jarvis.core.config import load_config-- return load_config()---def local_models_search_fn(brain: Any) -> Callable[[str], Awaitable[list[dict[str, Any]]]] | None:- """``search_web`` as a plain ``query -> [{title, url, snippet}]`` call.-- Read off the brain's attached tool surface — the same key-free tool a- voice turn uses — so the benchmark refresh has no search backend of its- own. ``None`` when the brain has no such tool (the table is read-only then).- """- tools = getattr(brain, "_tools", None) or {}- tool = tools.get("search_web") if isinstance(tools, dict) else None- if tool is None or not callable(getattr(tool, "execute", None)):- return None-- async def _search(query: str) -> list[dict[str, Any]]:- import uuid-- from jarvis.core.protocols import ExecutionContext-- ctx = ExecutionContext(- trace_id=uuid.uuid4(), user_utterance=query, config={}, memory_read=None- )- result = await tool.execute({"query": query, "max_results": 8}, ctx)- output = getattr(result, "output", None)- rows = output.get("results") if isinstance(output, dict) else None- return [r for r in rows if isinstance(r, dict)] if isinstance(rows, list) else []-- return _search-+def _chat_workspace() -> Path:+ """The Jarvis chat's own working folder — imported lazily (AP-26)."""+ from jarvis.core.paths import chat_workspace_dir-def _local_models_tools(cfg: Any, brain: Any) -> dict[str, Tool]:- from jarvis.brain.ollama_pull import server_root- from jarvis.local_models.assistant_tools import build_tools-- return build_tools(- _config_of(cfg, brain), root=server_root(), search_fn=local_models_search_fn(brain)- )---async def _local_models_extra(cfg: Any, brain: Any) -> str:- from jarvis.brain.ollama_pull import server_root- from jarvis.local_models.assistant_prompt import build_system_extra-- try:- return await build_system_extra(_config_of(cfg, brain), root=server_root())- except Exception as exc: # noqa: BLE001 — a turn without the briefing beats no turn- log.warning("local-models assistant: briefing not built: %s", exc, exc_info=True)- return (- "LOCAL MODELS SETUP ASSISTANT\nThe machine briefing could not be built "- f"({type(exc).__name__}); read everything with the lm_* tools first."- )---def _local_models_filter(tools: dict[str, Tool]) -> dict[str, Tool]:- """Only the assistant's own hands and web search.-- The router's full surface is 100+ declarations, some with schema shapes- (``oneOf``) the Gemini SDK rejects outright — one such tool failed every- turn of this surface on 2026-08-25. The assistant never needs them.- """- return {- name: tool- for name, tool in tools.items()- if name.startswith("lm_") or name in ("search_web", "search-web")- }+ return chat_workspace_dir()# ── the table ─────────────────────────────────────────────────────────────@@ -174,20 +99,12 @@ _KITS: Final[dict[str, SurfaceKit]] = {brain_runner=True,ladder=_JARVIS_LADDER,uses_stance=True,- ),- LOCAL_MODELS_SURFACE: SurfaceKit(- surface=LOCAL_MODELS_SURFACE,- brain_runner=True,- brain_only=True,- ladder=_JARVIS_LADDER,- uses_stance=True,- tools=_local_models_tools,- system_extra=_local_models_extra,- tool_origin=LOCAL_MODELS_TOOL_ORIGIN,- tool_filter=_local_models_filter,- # A guided run pulls, sets five roles, tunes and tests: more tool- # rounds than a chat answer needs.- max_turns=40,+ # Not the home directory: this surface hands out the folder tools, and+ # the read-only four are tier ``safe`` — they run without a card. The+ # composer hides the chip here (a person talks to Jarvis, they do not+ # point it at a checkout), so the default is also the only folder most+ # of these chats ever see. It has to be a small one.+ workspace_dir=_chat_workspace,),}diff --git a/jarvis/brain/turn_override.py b/jarvis/brain/turn_override.pyindex ca281de54d..ad7811a3e0 100644--- a/jarvis/brain/turn_override.py+++ b/jarvis/brain/turn_override.py@@ -103,8 +103,8 @@ class TurnOverride:``system_extra``A per-turn addendum to the system prompt, appended after themanager's own ``_system_prompt_extra``. Empty leaves the prompt- byte-identical; a surface with its own briefing (the local-models- setup assistant) sets it for its turns only.+ byte-identical; a surface with its own briefing sets it for its+ turns only."""provider: strdiff --git a/jarvis/cli_ctl/command_index.py b/jarvis/cli_ctl/command_index.pyindex 44a9ca96a3..48893a5d6b 100644--- a/jarvis/cli_ctl/command_index.py+++ b/jarvis/cli_ctl/command_index.py@@ -155,12 +155,6 @@ COMMAND_INDEX: dict[str, tuple[str, ...]] = {"server test <url>","server log [--lines]","server env-guide [--os]",- "assistant setup",- "assistant diagnose",- "assistant test [--role]",- "assistant benchmarks [--refresh]",- "assistant health",- "assistant session",),"marketplace": ("install <id>",diff --git a/jarvis/cli_ctl/commands/local_models.py b/jarvis/cli_ctl/commands/local_models.pyindex ee1e9ae7e2..8e290e71a2 100644--- a/jarvis/cli_ctl/commands/local_models.py+++ b/jarvis/cli_ctl/commands/local_models.py@@ -402,69 +402,3 @@ def server_env_guide("""Copyable per-OS commands for the server's environment variables."""params = {"os": os_name.strip()} if os_name.strip() else Noneinvoke.run("GET", f"{_base(provider)}/server/env-guide", params=params)---# -----------------------------------------------------------------------# assistant-# ------------------------------------------------------------------------assistant_app = typer.Typer(- no_args_is_help=True,- help="The setup assistant: guided setup, diagnosis, the end-to-end test, benchmarks, health.",-)-app.add_typer(assistant_app, name="assistant")---_ROLE_FILTER = typer.Option(- [],- "--role",- help="Restrict to a role (repeatable): chat, voice, tools_screen, deep, embedding.",-)---def _assistant(provider: str) -> str:- return f"{_base(provider)}/assistant"---@assistant_app.command("setup")-def assistant_setup(provider: str = _PROVIDER) -> None:- """Start a guided setup turn; answers with the session and turn ids."""- invoke.run("POST", f"{_assistant(provider)}/run", body={"mode": "setup"}, dangerous=False)---@assistant_app.command("diagnose")-def assistant_diagnose(provider: str = _PROVIDER) -> None:- """Ask the assistant what is broken and how to fix it."""- invoke.run("POST", f"{_assistant(provider)}/run", body={"mode": "diagnose"}, dangerous=False)---@assistant_app.command("test")-def assistant_test(- roles: list[str] = _ROLE_FILTER,- provider: str = _PROVIDER,-) -> None:- """Run the end-to-end setup test and print the per-role table."""- body = {"roles": list(roles)} if roles else None- invoke.run("POST", f"{_assistant(provider)}/test", body=body, dangerous=False)---@assistant_app.command("benchmarks")-def assistant_benchmarks(- refresh: bool = typer.Option(False, "--refresh", help="Rebuild the table from the web."),- provider: str = _PROVIDER,-) -> None:- """The benchmark table behind the proven / new labels (cached seven days)."""- params = {"refresh": "1"} if refresh else None- invoke.run("GET", f"{_assistant(provider)}/benchmarks", params=params)---@assistant_app.command("health")-def assistant_health(provider: str = _PROVIDER) -> None:- """The last self-check: status, reason, since when, last ok."""- invoke.run("GET", f"{_assistant(provider)}/health")---@assistant_app.command("session")-def assistant_session(provider: str = _PROVIDER) -> None:- """The assistant's session and whether the Agents tier can run it."""- invoke.run("GET", f"{_assistant(provider)}/session")diff --git a/jarvis/local_models/__init__.py b/jarvis/local_models/__init__.pyindex 5755fb6826..f93de01baa 100644--- a/jarvis/local_models/__init__.py+++ b/jarvis/local_models/__init__.py@@ -1,10 +1,9 @@-"""The local-models setup assistant: test runner, benchmarks, tools and prompt.+"""The local-models self-check: the health monitor behind the section badge.-Everything the "Help me set up" panel of the Local models section runs on,-kept apart from :mod:`jarvis.brain.ollama_*` (which own the server, the-inventory and the roles) and from :mod:`jarvis.agent_chat` (which owns the-chat surface). Nothing here runs at import time (AP-26); every module-imports its heavy neighbours lazily inside the function that needs them.+Kept apart from :mod:`jarvis.brain.ollama_*` (which own the server, the+inventory and the roles). Nothing here runs at import time (AP-26); the+module imports its heavy neighbours lazily inside the function that needs+them."""from __future__ import annotationsdiff --git a/jarvis/local_models/assistant_prompt.py b/jarvis/local_models/assistant_prompt.pydeleted file mode 100644index fd6e182a66..0000000000--- a/jarvis/local_models/assistant_prompt.py+++ /dev/null@@ -1,308 +0,0 @@-"""The setup assistant's briefing: a per-turn system-prompt addendum.--Rendered fresh for every turn of the ``local-models`` chat surface and-handed to the brain through ``TurnOverride.system_extra`` — the machine's-facts, what is installed, which role runs what (and under which config-key), the curated shortlist with fit verdicts and proven / new labels, the-benchmark table from the cache, the hard rules, and the output contract the-panel parses (a fenced ``jarvis-proposal`` JSON block). Budget: about 2.5k-tokens, so lists are capped rather than complete.--The three canned openers are what the panel's buttons send as the user-turn (D6): ``SETUP_OPENER``, ``DIAGNOSE_OPENER``, ``TEST_OPENER``.-"""--from __future__ import annotations--import asyncio-import datetime as _dt-import logging-from typing import Any, Final--log = logging.getLogger(__name__)--__all__ = [- "DIAGNOSE_OPENER",- "PROPOSAL_FENCE",- "SETUP_OPENER",- "TEST_OPENER",- "build_system_extra",-]--PROPOSAL_FENCE: Final[str] = "jarvis-proposal"--#: Rough budget guard: characters, not tokens (≈ 4 chars per token).-_MAX_CHARS = 10_000-_MAX_INVENTORY_ROWS = 30-_MAX_BENCHMARK_ROWS = 40--SETUP_OPENER: Final[str] = (- "Help me set up local models on this machine. Check the hardware and the server, then "- "propose ONE complete setup for the five roles (chat, voice, tools_screen, deep, "- "embedding) using the best proven models that fit, as a jarvis-proposal block. "- "Do not execute anything until I confirm."-)--DIAGNOSE_OPENER: Final[str] = (- "Something is not working with my local models. Find out what is broken (server, "- "roles, downloads, voice server), name the cause in one or two sentences, and propose "- "the smallest fix as a jarvis-proposal block. Do not execute anything until I confirm."-)--TEST_OPENER: Final[str] = (- "Run the end-to-end test of my local setup (lm_test_plan) and report the result as a "- "short table: one line per role with ok / error and the reason. Propose a fix as a "- "jarvis-proposal block only for roles that failed."-)--_RULES: Final[str] = """\-HARD RULES-- Never delete a model; there is no tool for it and you must not suggest one.-- Never change the active brain provider yourself. When Ollama should answer the voice and \-the chat, put a `brain_switch` entry in the proposal — the person clicks it.-- Installs, downloads, role picks, option writes and voice-stack changes happen only after \-the person confirmed the proposal; in that run, call the tools in the proposal's order.-- Never touch BIOS, OS, driver or firewall settings; point to the OLLAMA_* guide instead.-- Prefer models labelled `proven` whose fit is `comfortable`; a `new_little_tested` model is \-never a default; a `stale` label means the shortlist needs a refresh — say so.-- When a step fails, say exactly what failed (the tool's own sentence) and what to do next.-- Answer in the person's language; keep prose short, the proposal block carries the plan.-- Written delivery: this is a chat panel, not a voice reply — tables and lists are fine."""--_CONTRACT: Final[str] = """\-OUTPUT CONTRACT-When you propose or revise a setup, end the message with exactly one fenced block:-```jarvis-proposal-{"version": 1,- "steps": [- {"id": "s1", "kind": "install_ollama", "label": "Install Ollama"},- {"id": "s2", "kind": "pull", "model": "qwen3.5:4b", "size_gb": 3.4, "fit": "comfortable",- "proven": true, "label": "Download Qwen 3.5 4B"},- {"id": "s3", "kind": "set_role", "role": "chat", "model": "qwen3.5:4b", "label": "..."},- {"id": "s4", "kind": "set_options", "model": "qwen3.5:4b", "options": {"num_ctx": 16384},- "label": "..."},- {"id": "s5", "kind": "apply_voice_stack", "model": "qwen3.5:4b", "options":- {"voice_model": "..."}, "label": "..."},- {"id": "s6", "kind": "test", "label": "Test every role"}- ],- "brain_switch": {"provider": "ollama", "why": "one sentence"},- "notes": ["one sentence per caveat"]}-```-`kind` is one of install_ollama | pull | set_role | set_options | apply_voice_stack | test. \-`brain_switch` and `notes` are optional; `steps` may be empty when nothing needs doing."""---# ── data gathering ────────────────────────────────────────────────────────---def _provider(cfg: Any, name: str) -> Any:- providers = getattr(getattr(cfg, "brain", None), "providers", None) or {}- return providers.get(name) if isinstance(providers, dict) else None---async def _machine(cfg: Any) -> dict[str, Any]:- import platform-- from jarvis.brain.ollama_pull import accelerator_gb, total_memory_gb-- (accel, source), ram = await asyncio.gather(- asyncio.to_thread(accelerator_gb), asyncio.to_thread(total_memory_gb)- )- brain = getattr(cfg, "brain", None)- worker = getattr(brain, "worker", None)- return {- "os": f"{platform.system()} {platform.release()} ({platform.machine()})",- "ram_gb": ram,- "accelerator_gb": round(accel, 1),- "accelerator_source": source,- "active_brain": str(getattr(brain, "primary", "") or ""),- "assistant_tier": (- f"{getattr(worker, 'provider', '') or ''} / {getattr(worker, 'model', '') or ''}"- ).strip(" /"),- }---async def _inventory(root: str, transport: Any) -> tuple[list[Any], str | None]:- from jarvis.brain import ollama_inventory as inventory-- try:- return await inventory.list_models(root, transport=transport), None- except inventory.OllamaServerError as exc:- return [], str(exc)---def _roles(cfg: Any, installed_names: list[str]) -> list[dict[str, Any]]:- from jarvis.brain.ollama_inventory import same_model- from jarvis.brain.ollama_roles import ROLES, current_pick-- rows: list[dict[str, Any]] = []- for spec in ROLES:- if not spec.writable:- continue- current, note = current_pick(cfg, spec.id)- rows.append(- {- "role": spec.id,- "config_key": spec.config_key,- "required": list(spec.required),- "current": current,- "installed": bool(current) and any(same_model(n, current) for n in installed_names),- "note": note,- }- )- return rows---def _curated(- machine: dict[str, Any], installed_names: list[str], table: Any, today: _dt.date-) -> list[dict[str, Any]]:- from jarvis.brain.ollama_inventory import same_model- from jarvis.brain.ollama_pull import RECOMMENDED_MODELS, fit_verdict- from jarvis.local_models.benchmarks import label_for-- rows: list[dict[str, Any]] = []- for entry in RECOMMENDED_MODELS:- verdict, _note = fit_verdict(- entry.size_gb, machine.get("ram_gb"), float(machine.get("accelerator_gb") or 0.0)- )- rows.append(- {- "id": entry.id,- "role": entry.role,- "size_gb": entry.size_gb,- "tools": entry.tools,- "vision": entry.vision,- "fit": verdict,- "installed": any(same_model(n, entry.id) for n in installed_names),- "label": label_for(entry, table, today),- "purpose": entry.purpose,- }- )- return rows---# ── rendering ─────────────────────────────────────────────────────────────---def _yn(value: bool) -> str:- return "yes" if value else "no"---def _render_machine(machine: dict[str, Any], server: dict[str, Any], root: str) -> str:- ram = machine.get("ram_gb")- lines = [- "MACHINE",- f"- OS: {machine['os']}",- f"- RAM: {ram:g} GB" if ram is not None else "- RAM: unknown",- f"- Graphics memory usable for models: {machine['accelerator_gb']:g} GB "- f"(source: {machine['accelerator_source']})",- f"- Ollama server: {root} — "- + (- f"running, version {server.get('version')}"- if server.get("ok")- else f"not answering ({server.get('detail')})"- ),- f"- Active brain provider: {machine['active_brain'] or 'unset'} "- "(only the person may change it)",- f"- You run on the Tool Model (billed through its key): {machine['assistant_tier'] or 'unknown'}",- ]- return "\n".join(lines)---def _render_inventory(models: list[Any], error: str | None) -> str:- if error:- return f"INSTALLED MODELS\n- unavailable: {error}"- if not models:- return "INSTALLED MODELS\n- none"- lines = ["INSTALLED MODELS (name · size · capabilities · context)"]- for m in models[:_MAX_INVENTORY_ROWS]:- caps = ",".join(m.capabilities) or "unknown"- ctx = f"{m.context_length}" if m.context_length else "?"- lines.append(f"- {m.name} · {m.size_bytes / (1024**3):.1f} GB · {caps} · ctx {ctx}")- if len(models) > _MAX_INVENTORY_ROWS:- lines.append(f"- … and {len(models) - _MAX_INVENTORY_ROWS} more (lm_inventory)")- return "\n".join(lines)---def _render_roles(rows: list[dict[str, Any]], voice_command: str) -> str:- lines = ["ROLES (role · needs · current pick · installed · config key)"]- for r in rows:- pick = r["current"] or "not set"- extra = f" — {r['note']}" if r["note"] else ""- lines.append(- f"- {r['role']} · {'+'.join(r['required'])} · {pick} · "- f"{_yn(r['installed']) if r['current'] else '-'} · {r['config_key']}{extra}"- )- managed = "--model_name" in voice_command- lines.append(- "- managed voice server: "- + ("installed (apply_voice_stack may change its models)" if managed else "not installed")- )- return "\n".join(lines)---def _render_curated(rows: list[dict[str, Any]], reviewed_on: _dt.date) -> str:- lines = [- f"CURATED SHORTLIST (reviewed {reviewed_on.isoformat()}; id · role · GB · fit · "- "label · installed)"- ]- for r in rows:- caps = "tools" if r["tools"] else "-"- if r["vision"]:- caps += "+vision"- lines.append(- f"- {r['id']} · {r['role']} · {r['size_gb']:g} · {r['fit']} · {r['label']} · "- f"{_yn(r['installed'])} · {caps} — {r['purpose']}"- )- return "\n".join(lines)---def _render_benchmarks(table: Any) -> str:- if table is None:- return "BENCHMARKS\n- no cached table (lm_benchmarks refresh=true inside a guided run)"- lines = [f"BENCHMARKS (source: {table.source}; fetched {table.fetched_at or 'n/a'})"]- if table.note:- lines.append(f"- note: {table.note}")- for row in table.rows[:_MAX_BENCHMARK_ROWS]:- lines.append(f"- {row.family} · {row.source} · {row.metric} = {row.value:g}")- for family, facts in list(table.library.items())[:_MAX_BENCHMARK_ROWS]:- upd = f"{facts.updated_days} d ago" if facts.updated_days is not None else "?"- lines.append(f"- {family} · library · pulls {facts.pulls:,} · updated {upd}")- if len(lines) == 1:- lines.append("- no rows")- return "\n".join(lines)---async def build_system_extra(cfg: Any, *, root: str, transport: Any = None) -> str:- """The addendum for one turn of the local-models assistant (≈ 2.5k tokens)."""- from jarvis.brain.ollama_pull import CURATED_REVIEWED_ON- from jarvis.brain.ollama_runtime import probe_host- from jarvis.local_models.benchmarks import load_cached-- machine, server, (models, inv_error) = await asyncio.gather(- _machine(cfg), probe_host(root, transport=transport), _inventory(root, transport)- )- installed_names = [m.name for m in models]- table = load_cached()- today = _dt.datetime.now(_dt.UTC).date()- voice_command = str(getattr(_provider(cfg, "local-realtime"), "launch_command", "") or "")-- sections = [- "LOCAL MODELS SETUP ASSISTANT\n"- "You help this person set up, test and repair local models (Ollama) on THIS machine, "- "inside the Local models section. Read with the lm_* tools before you propose; "- "act only through them, and only after confirmation.",- _render_machine(machine, server, root),- _render_inventory(models, inv_error),- _render_roles(_roles(cfg, installed_names), voice_command),- _render_curated(_curated(machine, installed_names, table, today), CURATED_REVIEWED_ON),- _render_benchmarks(table),- _RULES,- _CONTRACT,- ]- text = "\n\n".join(sections)- if len(text) > _MAX_CHARS:- log.info("local-models prompt: %d chars, trimming the benchmark section", len(text))- sections[5] = "BENCHMARKS\n- table too long for the briefing; use lm_benchmarks"- text = "\n\n".join(sections)- return textdiff --git a/jarvis/local_models/assistant_session.py b/jarvis/local_models/assistant_session.pydeleted file mode 100644index 587b9ef8d4..0000000000--- a/jarvis/local_models/assistant_session.py+++ /dev/null@@ -1,352 +0,0 @@-"""Session policy of the setup assistant: one chat per install, on the Agents tier.--The assistant is a ``local-models`` agent-chat session. It runs on the-Jarvis-Agents tier (``[brain.worker]`` provider / model, the fallback pair-when the primary is unknown to the chat) — never on the voice brain, so a-person whose voice runs on Ollama still gets a capable cloud model to set-Ollama up. There is ONE session per install: the routes reuse the newest-``local-models`` session and re-create it only when the worker tier moved.--No usable Agents-tier credential → an honest refusal (:data:`NOT_READY`),-never a silent fallback onto another tier.-"""--from __future__ import annotations--import logging-from collections.abc import Awaitable, Callable-from dataclasses import dataclass-from typing import Any, Final--log = logging.getLogger(__name__)--__all__ = [- "NOT_READY",- "SURFACE",- "AgentsTier",- "agents_tier",- "ensure_session",- "session_state",-]--SURFACE: Final[str] = "local-models"-NOT_READY: Final[str] = (- "Pick a Tool Model with an API key first (API Keys → Tool Model) — the setup "- "assistant runs on it, billed through that key."-)-#: The tier is connected but every provider in its chain drives a vendor CLI-#: on a flat prompt (Antigravity, for one) and cannot call the assistant's-#: tools; a fallback with an API key fixes it.-NO_TOOLS: Final[str] = (- "The picked Tool Model cannot call tools here (a CLI-only provider such as "- "Antigravity). Pick an API provider — Gemini, OpenAI, Vertex or OpenRouter — "- "under API Keys → Tool Model and try again."-)---@dataclass(frozen=True, slots=True)-class AgentsTier:- provider: str- model: str- ready: bool- reason: str---def _known(provider: str) -> bool:- from jarvis.agent_chat.catalog import provider_row- from jarvis.agent_chat.runner_api import supports_api_runner-- return provider_row(provider) is not None or supports_api_runner(provider)---def _tool_capable(provider: str) -> bool:- """Whether ``provider``'s brain plugin can call tools inside the brain loop.-- Read from the plugin itself (``can_call_tools`` / ``supports_tools``) via- the ``jarvis.brain`` entry point, never from the name (AP-21). A plugin- that cannot be loaded here answers True: the turn then fails honestly- instead of a healthy provider being skipped by a probe glitch.- """- from importlib.metadata import entry_points-- try:- eps = [ep for ep in entry_points(group="jarvis.brain") if ep.name == provider]- if not eps:- return True- cls = eps[0].load()- try:- brain = cls()- except TypeError:- brain = cls(model=None)- probe = getattr(brain, "can_call_tools", None)- if callable(probe):- return bool(probe())- return bool(getattr(brain, "supports_tools", True))- except Exception: # noqa: BLE001 — a probe glitch must not hide a working provider- log.debug("agents tier: tool-capability probe for %s failed", provider, exc_info=True)- return True---def _default_usable(provider: str) -> bool:- """A credential exists: the provider's own key (the Tool Model bills- through it) or the Agents-tier secret for the fallback chain."""- from jarvis.core.config import get_jarvis_agent_secret-- try:- if get_jarvis_agent_secret(provider):- return True- except Exception: # noqa: BLE001 — no credential readable counts as none- log.debug("agents tier: credential lookup for %s failed", provider, exc_info=True)- try:- from jarvis.brain.app_control import is_credential_present- from jarvis.ui.web.provider_spec import get_spec-- spec = get_spec(provider)- return spec is not None and bool(is_credential_present(spec))- except Exception: # noqa: BLE001 — same: unreadable is "none"- log.debug("agents tier: main credential lookup for %s failed", provider, exc_info=True)- return False---def _tool_model_pair(cfg: Any) -> tuple[str, str] | None:- """The user's Tool Model pick, ``None`` when it is ``auto``.-- The same reader the Tool Model tab and the IDE's prompt writer use- (``resolver._tool_model_selection``), so the assistant runs on exactly the- model the user pointed that tab at — and is billed through that key.- """- from jarvis.brain.resolver import _tool_model_selection-- try:- provider, model = _tool_model_selection(cfg)- except Exception: # noqa: BLE001 — a malformed section reads as unset, logged- log.debug("agents tier: tool-model selection unreadable", exc_info=True)- return None- if not provider or provider == "auto":- return None- return provider, str(model or "").strip()---def _chain(cfg: Any) -> list[tuple[str, str]]:- """The Tool Model first; the Agents-tier chain only as a fallback."""- out: list[tuple[str, str]] = []- pinned = _tool_model_pair(cfg)- if pinned is not None:- out.append(pinned)- brain = getattr(cfg, "brain", None)- worker = getattr(brain, "worker", None)- if worker is None:- return out- pairs = [- ("provider", "model"),- ("fallback_provider", "fallback_model"),- ("fallback_provider_2", "fallback_model_2"),- ]- for p_key, m_key in pairs:- provider = str(getattr(worker, p_key, "") or "").strip()- model = str(getattr(worker, m_key, "") or "").strip()- if provider and (provider, model) not in out:- out.append((provider, model))- return out---def chain_candidates(- cfg: Any,- *,- usable: Callable[[str], bool] | None = None,- tool_capable: Callable[[str], bool] | None = None,-) -> list[tuple[str, str]]:- """The worker pairs worth a live probe: known, tool-capable, credentialed."""- can_tools = tool_capable or _tool_capable- probe = usable or _default_usable- out: list[tuple[str, str]] = []- for provider, model in _chain(cfg):- if not _known(provider) or not can_tools(provider):- continue- try:- if probe(provider):- out.append((provider, model))- except Exception: # noqa: BLE001 — a failing probe is "not ready", with the reason logged- log.info("agents tier: usability probe for %s failed", provider, exc_info=True)- return out---#: (provider, model) -> (ok, reason, monotonic) — one real call per pair per-#: ten minutes; a run and the session read share it.-_LIVE_CACHE: dict[tuple[str, str], tuple[bool, str, float]] = {}-_LIVE_TTL_S: Final[float] = 600.0---def _reset_for_tests() -> None:- _LIVE_CACHE.clear()---async def probe_live(- cfg: Any,- pairs: list[tuple[str, str]],- *,- timeout_s: float = 20.0,- tester: Callable[..., Awaitable[Any]] | None = None,-) -> dict[tuple[str, str], tuple[bool, str]]:- """One real one-token generation per pair, classified like the API-keys- page's "Test" (``provider_test``): a key that authenticates but is refused- for quota or billing is NOT usable here, and the sentence says so."""- import time-- from jarvis.brain import provider_test- from jarvis.ui.web.provider_spec import get_spec-- out: dict[tuple[str, str], tuple[bool, str]] = {}- now = time.monotonic()- for provider, model in pairs:- hit = _LIVE_CACHE.get((provider, model))- if hit is not None and now - hit[2] < _LIVE_TTL_S:- out[(provider, model)] = (hit[0], hit[1])- continue- spec = get_spec(provider)- if spec is None:- out[(provider, model)] = (False, f"{provider} is not a provider this build knows.")- continue- run = tester or provider_test.run_provider_test- try:- result = await run(spec, cfg, model=model or None, timeout_s=timeout_s)- ok = result.status == provider_test.OK- reason = "" if ok else _plain_reason(provider, model, result)- except Exception as exc: # noqa: BLE001 — a probe crash is "not usable", logged- log.warning("agents tier: live probe of %s/%s crashed: %s", provider, model, exc)- ok, reason = False, f"{provider} ({model}): probe failed — {exc}"- _LIVE_CACHE[(provider, model)] = (ok, reason, time.monotonic())- out[(provider, model)] = (ok, reason)- return out---_PLAIN_BY_STATUS: Final[dict[str, str]] = {- "no_credits": "the account has no credit or quota left for this model",- "rate_limited": "the provider is rate-limiting this key right now",- "bad_key": "the key was refused",- "model_unavailable": "the provider no longer offers this model",- "unreachable": "the provider could not be reached",- "not_configured": "no key is stored for it",-}---def _plain_reason(provider: str, model: str, result: Any) -> str:- """One readable sentence, never a dumped error body.-- The status vocabulary is the API-keys page's; the provider's own text is- kept only when it is short and free of JSON braces (a 404 body is not- something a person should have to read in a status line).- """- status = str(getattr(result, "status", "") or "error")- head = f"{provider} ({model or 'default model'}): "- plain = _PLAIN_BY_STATUS.get(status)- detail = str(getattr(result, "detail", "") or "").strip()- if plain:- return head + plain + "."- if detail and "{" not in detail and len(detail) <= 140:- return head + detail- return head + status.replace("_", " ") + "."---def agents_tier(- cfg: Any,- *,- usable: Callable[[str], bool] | None = None,- tool_capable: Callable[[str], bool] | None = None,- live: dict[tuple[str, str], tuple[bool, str]] | None = None,-) -> AgentsTier:- """The pair the assistant runs on and whether it can run right now.-- Walks the worker chain (primary, fallback, fallback 2) and takes the first- provider that is known, can call tools, has a credential and — when a- ``live`` map from :func:`probe_live` is given — answered a real call.- ``usable`` is the credential / login probe (the routes pass the- provider-agnostic worker check the API-keys page uses; the default reads- the Agents-tier secret); ``tool_capable`` defaults to asking the plugin.- """- chain = _chain(cfg)- if not chain:- return AgentsTier("", "", False, NOT_READY)- known = [(p, m) for p, m in chain if _known(p)]- if not known:- return AgentsTier(chain[0][0], "", False, NOT_READY)- can_tools = tool_capable or _tool_capable- handy = [(p, m) for p, m in known if can_tools(p)]- if not handy:- return AgentsTier(known[0][0], known[0][1], False, NO_TOOLS)- probe = usable or _default_usable- last_reason = NOT_READY- for provider, model in handy:- try:- ok = bool(probe(provider))- except Exception: # noqa: BLE001 — a failing probe is "not ready", with the reason logged- log.info("agents tier: usability probe for %s failed", provider, exc_info=True)- ok = False- if not ok:- continue- if live is not None and (provider, model) in live:- alive, reason = live[(provider, model)]- if not alive:- last_reason = reason or NOT_READY- continue- return AgentsTier(provider, model, True, "")- return AgentsTier(handy[0][0], handy[0][1], False, last_reason)---def _current(svc: Any) -> Any | None:- sessions = svc.store.list_sessions(limit=1, surface=SURFACE)- return sessions[0] if sessions else None---def session_state(- svc: Any,- cfg: Any,- *,- usable: Callable[[str], bool] | None = None,- live: dict[tuple[str, str], tuple[bool, str]] | None = None,-) -> dict:- """``GET /session``: the session id (or null), the pair, readiness, reason."""- tier = agents_tier(cfg, usable=usable, live=live)- current = _current(svc)- matches = (- current is not None- and current.provider == tier.provider- and (not tier.model or current.model == tier.model)- )- return {- "session_id": current.session_id if matches and current is not None else None,- "surface": SURFACE,- "provider": tier.provider,- "model": tier.model,- "ready": tier.ready,- "reason": tier.reason,- }---def ensure_session(- svc: Any,- cfg: Any,- *,- usable: Callable[[str], bool] | None = None,- live: dict[tuple[str, str], tuple[bool, str]] | None = None,-) -> Any:- """The one ``local-models`` session, created or re-created for the current pair.-- Raises ``PermissionError(reason)`` when the Agents tier cannot run.- """- tier = agents_tier(cfg, usable=usable, live=live)- if not tier.ready:- raise PermissionError(tier.reason or NOT_READY)- current = _current(svc)- if (- current is not None- and current.provider == tier.provider- and (not tier.model or current.model == tier.model)- ):- return current- return svc.create_session(- provider=tier.provider,- model=tier.model,- title="Local models setup",- surface=SURFACE,- )diff --git a/jarvis/local_models/assistant_test.py b/jarvis/local_models/assistant_test.pydeleted file mode 100644index c43ffbf238..0000000000--- a/jarvis/local_models/assistant_test.py+++ /dev/null@@ -1,399 +0,0 @@-"""The end-to-end test of a local setup: does every configured role actually answer?--A role that is *configured* proves nothing — the model may have been deleted,-the server may be down, a "tools + vision" pick may declare neither. So this-runner asks the server (``probe_host``), then makes one REAL call per-configured role: a 1-token generation for the chat / deep / tools_screen-roles (through :func:`jarvis.brain.provider_test.run_provider_test`, so the-status vocabulary is the one the API-keys cards already speak), a-capability assertion on top for ``tools_screen``, an embedding round trip-for the embedding role, and — only when the managed voice server is-configured — the voice smoke probe. The report is persisted to-``DATA_DIR/state/local_models_health.json`` so the section badge and the-health monitor read the same file.-"""--from __future__ import annotations--import asyncio-import datetime as _dt-import json-import logging-import os-import uuid-from collections.abc import Awaitable, Callable-from dataclasses import dataclass-from pathlib import Path-from typing import Any--log = logging.getLogger(__name__)--__all__ = [- "HEALTH_FILE_NAME",- "NOT_SET",- "OVERALL_STATUSES",- "RoleCheck",- "TestReport",- "health_path",- "load_last_report",- "run_setup_test",-]--#: Status of a role nobody configured — it is not an error, there is simply-#: nothing to test. Alongside :data:`PROVIDER_TEST_STATUSES` in ``status``.-NOT_SET = "not_set"--#: ``overall`` vocabulary — the same the health monitor (D7) writes.-OVERALL_STATUSES: tuple[str, ...] = ("ok", "error", "needs_setup", "unknown")--HEALTH_FILE_NAME = "local_models_health.json"--#: The generation-tested roles and the role whose pick embeds.-_GENERATION_ROLES: tuple[str, ...] = ("chat", "tools_screen", "deep")-_EMBEDDING_ROLE = "embedding"-_VOICE_ROLE = "voice"--_DEFAULT_TIMEOUT_S = 90.0-_VOICE_DEFAULT_URL = "http://127.0.0.1:8765"---@dataclass(frozen=True, slots=True)-class _OllamaSpec:- """The three fields :func:`run_provider_test` reads from a provider spec."""-- id: str = "ollama"- tier: str = "brain"- auth_mode: str = "none"---@dataclass(frozen=True, slots=True)-class RoleCheck:- """One role's verdict."""-- model: str- #: :data:`PROVIDER_TEST_STATUSES` value or :data:`NOT_SET`.- status: str- latency_ms: float- detail: str-- def to_payload(self) -> dict[str, Any]:- return {- "model": self.model,- "status": self.status,- "latency_ms": round(self.latency_ms, 1),- "detail": self.detail,- }---@dataclass(frozen=True, slots=True)-class TestReport:- """The whole run, as the panel's table and the health file show it."""-- #: Not a pytest class, whatever the name suggests.- __test__ = False-- checked_at: str- server: dict[str, Any]- roles: dict[str, RoleCheck]- #: The voice smoke probe's payload, ``None`` when no managed voice server exists.- voice: dict[str, Any] | None- #: One of :data:`OVERALL_STATUSES`.- overall: str-- def to_payload(self) -> dict[str, Any]:- return {- "checked_at": self.checked_at,- "server": dict(self.server),- "roles": {role: check.to_payload() for role, check in self.roles.items()},- "voice": dict(self.voice) if self.voice is not None else None,- "overall": self.overall,- # The badge keys the health monitor writes as well (D7), so one- # reader serves both writers.- "status": self.overall,- "reason": self.reason(),- }-- def reason(self) -> str:- """One sentence naming the first failure, or ``""`` when all is well."""- if not self.server.get("ok"):- return str(self.server.get("detail") or "Ollama did not answer.")- for role, check in self.roles.items():- if check.status not in ("ok", NOT_SET):- return f"{role}: {check.detail or check.status}"- if self.voice is not None and not self.voice.get("ok", False):- return f"voice: {self.voice.get('detail') or 'the voice probe failed'}"- return ""---def health_path() -> Path:- """``DATA_DIR/state/local_models_health.json`` — resolved at call time."""- from jarvis.core import config as cfg_mod # lazy: DATA_DIR is monkeypatched by tests-- return Path(cfg_mod.DATA_DIR) / "state" / HEALTH_FILE_NAME---def _atomic_write_json(path: Path, payload: dict[str, Any]) -> bool:- temporary = path.with_name(f".{path.name}.{os.getpid()}.{uuid.uuid4().hex}.tmp")- try:- path.parent.mkdir(parents=True, exist_ok=True)- temporary.write_text(json.dumps(payload, indent=2), encoding="utf-8")- os.replace(temporary, path)- return True- except OSError:- log.warning("local-models: health file %s not written", path, exc_info=True)- return False- finally:- try:- temporary.unlink(missing_ok=True)- except OSError:- log.debug("local-models: temporary health file cleanup failed", exc_info=True)---def load_last_report() -> dict[str, Any] | None:- """The persisted payload of the last run, or ``None`` when none / unreadable."""- path = health_path()- try:- payload = json.loads(path.read_text(encoding="utf-8"))- except FileNotFoundError:- return None- except (OSError, ValueError):- log.info("local-models: health file %s unreadable", path, exc_info=True)- return None- return payload if isinstance(payload, dict) else None---# ── Reading the config ────────────────────────────────────────────────────---def _voice_launch_command(cfg: Any) -> str:- providers = getattr(getattr(cfg, "brain", None), "providers", None) or {}- voice = providers.get("local-realtime") if isinstance(providers, dict) else None- return str(getattr(voice, "launch_command", "") or "")---def _voice_base_url(cfg: Any) -> str:- providers = getattr(getattr(cfg, "brain", None), "providers", None) or {}- voice = providers.get("local-realtime") if isinstance(providers, dict) else None- return str(getattr(voice, "base_url", "") or "") or _VOICE_DEFAULT_URL---def _server_root(cfg: Any) -> str:- providers = getattr(getattr(cfg, "brain", None), "providers", None) or {}- ollama = providers.get("ollama") if isinstance(providers, dict) else None- override = str(getattr(ollama, "base_url", "") or "")- if override:- from jarvis.plugins.brain.ollama import normalize_server_root-- return normalize_server_root(override)- from jarvis.brain.ollama_pull import server_root-- return server_root()---# ── The checks ────────────────────────────────────────────────────────────---async def _generation_check(- cfg: Any,- model: str,- *,- timeout_s: float,- brain_probe: Callable[[str, str], Awaitable[Any]] | None,-) -> RoleCheck:- from jarvis.brain import provider_test-- result = await provider_test.run_provider_test(- _OllamaSpec(), cfg, model=model, timeout_s=timeout_s, brain_probe=brain_probe- )- return RoleCheck(- model=model,- status=result.status,- latency_ms=float(result.latency_ms),- detail=result.detail or ("Answered." if result.status == "ok" else ""),- )---async def _capability_check(root: str, check: RoleCheck, *, transport: Any) -> RoleCheck:- """``tools_screen`` must DECLARE tools + vision, not only answer a prompt."""- from jarvis.brain import ollama_inventory as inventory- from jarvis.brain.provider_test import ERROR, MODEL_UNAVAILABLE-- if check.status != "ok":- return check- try:- info = await inventory.get_model(root, check.model, transport=transport)- except inventory.OllamaModelNotFound as exc:- return RoleCheck(check.model, MODEL_UNAVAILABLE, check.latency_ms, str(exc))- except inventory.OllamaServerError as exc:- return RoleCheck(check.model, ERROR, check.latency_ms, str(exc))- missing = [c for c in ("tools", "vision") if c not in info.capabilities]- if missing:- return RoleCheck(- check.model,- ERROR,- check.latency_ms,- f"{check.model} answers, but does not declare {' + '.join(missing)} — "- "it cannot read the screen or call tools for Jarvis.",- )- return RoleCheck(check.model, "ok", check.latency_ms, "Answered; declares tools + vision.")---async def _embedding_check(root: str, model: str, *, transport: Any) -> RoleCheck:- import time-- from jarvis.brain import ollama_inventory as inventory- from jarvis.brain.provider_test import ERROR, MODEL_UNAVAILABLE, UNREACHABLE-- started = time.perf_counter()- try:- dim = await inventory.embed_probe(root, model, transport=transport)- except inventory.OllamaModelNotFound as exc:- return RoleCheck(model, MODEL_UNAVAILABLE, _ms(started), str(exc))- except inventory.OllamaServerError as exc:- text = str(exc)- status = UNREACHABLE if "No Ollama" in text or "unreachable" in text.lower() else ERROR- return RoleCheck(model, status, _ms(started), text)- if dim <= 0:- return RoleCheck(model, ERROR, _ms(started), f"{model} returned no embedding vector.")- return RoleCheck(model, "ok", _ms(started), f"Embeds ({dim} dimensions).")---async def _voice_check(- cfg: Any,- *,- timeout_s: float,- voice_probe: Callable[[str], Awaitable[dict[str, Any]]] | None,-) -> dict[str, Any] | None:- """The voice smoke probe — only for the Jarvis-managed server (``--model_name``)."""- command = _voice_launch_command(cfg)- if "--model_name" not in command:- return None- base_url = _voice_base_url(cfg)- try:- if voice_probe is not None:- payload = await asyncio.wait_for(voice_probe(base_url), timeout=timeout_s)- else:- from jarvis.realtime.local_server.smoke import probe_voice_roundtrip-- payload = await probe_voice_roundtrip(base_url, timeout_s=timeout_s)- except TimeoutError:- return {"ok": False, "detail": f"The voice probe timed out after {timeout_s:.0f} s."}- except Exception as exc: # noqa: BLE001 — the report names the failure, never raises- log.info("local-models: voice probe failed", exc_info=True)- return {"ok": False, "detail": f"{type(exc).__name__}: {exc}"}- out = dict(payload or {})- out.setdefault("ok", True)- out.setdefault("detail", "Voice round trip answered with audio.")- return out---def _ms(started: float) -> float:- import time-- return (time.perf_counter() - started) * 1000.0---def _overall(server: dict[str, Any], roles: dict[str, RoleCheck], voice: Any) -> str:- configured = [c for c in roles.values() if c.status != NOT_SET]- if not server.get("ok"):- return "needs_setup" if not configured else "error"- if not configured and voice is None:- return "needs_setup"- if any(c.status != "ok" for c in configured):- return "error"- if voice is not None and not voice.get("ok", False):- return "error"- return "ok"---# ── The runner ────────────────────────────────────────────────────────────---async def run_setup_test(- cfg: Any,- roles: tuple[str, ...] | None = None,- *,- transport: Any = None,- brain_probe: Callable[[str, str], Awaitable[Any]] | None = None,- voice_probe: Callable[[str], Awaitable[dict[str, Any]]] | None = None,- timeout_s: float = _DEFAULT_TIMEOUT_S,- persist: bool = True,-) -> TestReport:- """Test the configured local setup end to end and persist the report.-- ``roles`` restricts the run to those writable role ids (default: all of- them). ``transport`` is the httpx test seam for the Ollama calls;- ``brain_probe`` / ``voice_probe`` are the seams for the generation and- voice probes (production wiring when ``None``). Never raises for a- failing check — every failure is a row in the report.- """- from jarvis.brain.ollama_roles import WRITABLE_ROLE_IDS, current_pick- from jarvis.brain.ollama_runtime import probe_host- from jarvis.brain.provider_test import UNREACHABLE-- wanted = tuple(roles) if roles else WRITABLE_ROLE_IDS- unknown = [r for r in wanted if r not in WRITABLE_ROLE_IDS]- if unknown:- raise ValueError(f"Unknown role(s): {', '.join(unknown)}")-- root = _server_root(cfg)- server = await probe_host(root, transport=transport)- server["base_url"] = root-- checks: dict[str, RoleCheck] = {}- for role in wanted:- if role == _VOICE_ROLE:- continue # the voice role is judged by the smoke probe below- model, note = current_pick(cfg, role)- if not model:- checks[role] = RoleCheck("", NOT_SET, 0.0, note or "No model set.")- continue- if not server.get("ok"):- checks[role] = RoleCheck(model, UNREACHABLE, 0.0, str(server.get("detail") or ""))- continue- if role == _EMBEDDING_ROLE:- checks[role] = await _embedding_check(root, model, transport=transport)- elif role in _GENERATION_ROLES:- check = await _generation_check(- cfg, model, timeout_s=timeout_s, brain_probe=brain_probe- )- if role == "tools_screen":- check = await _capability_check(root, check, transport=transport)- checks[role] = check-- voice: dict[str, Any] | None = None- if _VOICE_ROLE in wanted:- voice = await _voice_check(cfg, timeout_s=timeout_s, voice_probe=voice_probe)- voice_model, voice_note = current_pick(cfg, _VOICE_ROLE)- if voice is None:- checks[_VOICE_ROLE] = RoleCheck(- voice_model, NOT_SET, 0.0, voice_note or "No managed voice server."- )- else:- checks[_VOICE_ROLE] = RoleCheck(- voice_model,- "ok" if voice.get("ok") else "error",- float(voice.get("first_audio_ms") or voice.get("latency_ms") or 0.0),- str(voice.get("detail") or ""),- )-- report = TestReport(- checked_at=_dt.datetime.now(_dt.UTC).isoformat(timespec="seconds"),- server=server,- roles=checks,- voice=voice,- overall=_overall(server, checks, voice),- )- if persist:- payload = report.to_payload()- previous = load_last_report() or {}- payload["since"] = (- previous.get("since")- if previous.get("status") == report.overall and previous.get("since")- else report.checked_at- )- payload["last_ok"] = (- report.checked_at if report.overall == "ok" else previous.get("last_ok")- )- _atomic_write_json(health_path(), payload)- return reportdiff --git a/jarvis/local_models/assistant_tools.py b/jarvis/local_models/assistant_tools.pydeleted file mode 100644index d8eb17b73b..0000000000--- a/jarvis/local_models/assistant_tools.py+++ /dev/null@@ -1,785 +0,0 @@-"""The setup assistant's hands: Jarvis tools over the local-models functions.--Every tool here wraps a function the Local models section already calls-(``ollama_runtime``, ``ollama_inventory``, ``ollama_roles``, ``ollama_pull``,-``ollama_library``, the managed voice server) as a-:class:`jarvis.core.protocols.Tool`, the way :mod:`jarvis.agent_chat.folder_tools`-wraps the chat's folder tools — so every call goes through ``ToolExecutor``-with its risk tiers, blacklist, audit log and approval card (AP-3), on the-``local-models`` chat surface exactly as on the voice path.--Tiers: reads are ``safe``; everything that installs, starts, stops, downloads-or writes config is ``ask`` (the panel auto-answers the cards of a confirmed-proposal, the executor still asks); ``lm_unload`` is ``monitor``. There is-deliberately **no delete tool** and nothing that writes ``brain.primary`` —-the provider lock stays with the user's click.-"""--from __future__ import annotations--import asyncio-import logging-import platform-import time-from collections.abc import Awaitable, Callable-from dataclasses import dataclass-from typing import Any, Final--from jarvis.core.protocols import ExecutionContext, RiskTier, Tool, ToolResult--log = logging.getLogger(__name__)--__all__ = [- "ACTION_TOOLS",- "ALLOWED_TIERS",- "LocalModelsTool",- "READ_TOOLS",- "TOOL_PREFIX",- "build_tools",- "tool_specs",-]--TOOL_PREFIX: Final[str] = "lm_"--#: Every tier a local-models tool may carry. ``block`` is not on the list on-#: purpose: a tool that must never run is a tool that must not exist here.-ALLOWED_TIERS: Final[tuple[RiskTier, ...]] = ("safe", "monitor", "ask")--Handler = Callable[[dict[str, Any], "_Env"], Awaitable[Any]]--#: How long ``lm_pull`` follows a download before handing back a "still-#: running" answer (the panel keeps polling ``lm_pull_status``).-PULL_FOLLOW_MAX_S = 1800.0-PULL_POLL_S = 1.0---@dataclass(frozen=True, slots=True)-class _Env:- """What every handler needs: the live config, the server root, the seams."""-- cfg: Any- root: str- transport: Any = None- search_fn: Callable[[str], Any] | None = None---@dataclass(frozen=True, slots=True)-class ToolSpec:- name: str- description: str- schema: dict[str, Any]- risk_tier: RiskTier- handler: Handler- summary: Callable[[dict[str, Any]], str] | None = None---class LocalModelsTool:- """One spec as a Jarvis ``Tool`` bound to a config + server root."""-- def __init__(self, spec: ToolSpec, env: _Env) -> None:- self.name: str = spec.name- self.description: str = spec.description- self.schema: dict[str, Any] = dict(spec.schema)- self.risk_tier: RiskTier = spec.risk_tier- self._spec = spec- self._env = env-- async def execute(self, args: dict[str, Any], ctx: ExecutionContext) -> ToolResult:- try:- output = await self._spec.handler(dict(args or {}), self._env)- except Exception as exc: # noqa: BLE001 — the model reads the failure, the log keeps it- log.info("local-models tool %s failed: %s", self.name, exc, exc_info=True)- return ToolResult(success=False, output=str(exc), error=f"{type(exc).__name__}: {exc}")- return ToolResult(success=True, output=output)-- def describe_args(self, args: dict[str, Any]) -> dict[str, str]:- """The one-line summary the approval card shows."""- if self._spec.summary is None:- return {}- try:- text = self._spec.summary(dict(args or {}))- except Exception: # noqa: BLE001 — a summary must never break the card- log.debug("local-models tool %s: summary failed", self.name, exc_info=True)- return {}- return {"summary": text} if text else {}-- def __repr__(self) -> str: # pragma: no cover — debugging aid- return f"LocalModelsTool({self.name!r}, tier={self.risk_tier!r})"---# ── schema helpers ────────────────────────────────────────────────────────---def _obj(props: dict[str, Any] | None = None, required: tuple[str, ...] = ()) -> dict[str, Any]:- schema: dict[str, Any] = {"type": "object", "properties": dict(props or {})}- if required:- schema["required"] = list(required)- return schema---_MODEL = {"type": "string", "description": "An Ollama model tag, e.g. qwen3.5:4b."}-_ROLE = {- "type": "string",- "description": "A writable role id: chat, voice, tools_screen, deep or embedding.",-}---def _str(args: dict[str, Any], key: str) -> str:- return str(args.get(key) or "").strip()---# ── read handlers (safe) ──────────────────────────────────────────────────---async def _hardware(_args: dict[str, Any], _env: _Env) -> dict[str, Any]:- from jarvis.brain.ollama_pull import accelerator_gb, total_memory_gb-- (accel, source), ram = await asyncio.gather(- asyncio.to_thread(accelerator_gb), asyncio.to_thread(total_memory_gb)- )- import os-- return {- "os": platform.system(),- "os_version": platform.release(),- "machine": platform.machine(),- "cpu_threads": os.cpu_count() or 0,- "ram_gb": ram,- "accelerator_gb": round(accel, 1),- "accelerator_source": source,- }---async def _server_status(_args: dict[str, Any], env: _Env) -> dict[str, Any]:- from jarvis.brain import ollama_runtime-- status, probe = await asyncio.gather(- asyncio.to_thread(ollama_runtime.runtime_status),- ollama_runtime.probe_host(env.root, transport=env.transport),- )- out: dict[str, Any] = {- "runtime": status,- "probe": probe,- "install": ollama_runtime.install_snapshot(),- "base_url": env.root,- }- command = _voice_command(env.cfg)- if "--model_name" in command:- from jarvis.realtime.local_server import install as voice_install- from jarvis.realtime.local_server.preflight import report_payload, run_preflight-- voice_status = await asyncio.to_thread(voice_install.server_status)- preflight = await asyncio.to_thread(run_preflight, voice_install.install_root())- out["voice"] = {- "launch_command": command,- "status": voice_status,- "preflight": report_payload(preflight),- }- else:- out["voice"] = {"launch_command": command, "status": None, "preflight": None}- return out---async def _inventory(_args: dict[str, Any], env: _Env) -> dict[str, Any]:- from jarvis.brain import ollama_inventory as inventory-- models, running = await asyncio.gather(- inventory.list_models(env.root, transport=env.transport),- inventory.running_models(env.root, transport=env.transport),- )- return {- "models": [- {- "name": m.name,- "size_gb": round(m.size_bytes / (1024**3), 2),- "family": m.family,- "parameter_size": m.parameter_size,- "quantization": m.quantization_level,- "context_length": m.context_length,- "capabilities": list(m.capabilities),- "modified_at": m.modified_at,- }- for m in models- ],- "running": [- {- "name": r.name,- "size_vram_gb": round(r.size_vram_bytes / (1024**3), 2),- "context_length": r.context_length,- "expires_at": r.expires_at,- }- for r in running- ],- "disk_gb": round(sum(m.size_bytes for m in models) / (1024**3), 1),- }---def _role_row(state: Any) -> dict[str, Any]:- spec = state.spec- return {- "role": spec.id,- "config_key": spec.config_key,- "writable": spec.writable,- "required_capabilities": list(spec.required),- "current": state.current,- "installed": state.installed,- "qualifying": list(state.qualifying),- "recommended": state.recommended,- "note": state.note,- "context_tokens": state.context_tokens,- }---async def _roles(_args: dict[str, Any], env: _Env) -> dict[str, Any]:- from jarvis.brain.ollama_roles import list_roles-- states, error = await list_roles(env.root, env.cfg, transport=env.transport)- return {"roles": [_role_row(s) for s in states], "error": error}---async def _recommendations(_args: dict[str, Any], _env: _Env) -> dict[str, Any]:- import datetime as _dt-- from jarvis.brain.ollama_pull import recommendations- from jarvis.local_models import benchmarks-- payload = await recommendations()- table = benchmarks.load_cached()- today = _dt.datetime.now(_dt.UTC).date()- for row in payload.get("models") or []:- row["label"] = benchmarks.label_for(str(row.get("id") or ""), table, today)- payload["benchmark_source"] = table.source if table is not None else "curated"- return payload---async def _catalog_search(args: dict[str, Any], _env: _Env) -> dict[str, Any]:- from jarvis.brain.ollama_library import search_library-- return await search_library(- _str(args, "query"),- sort=_str(args, "sort") or "popular",- capability=_str(args, "capability") or None,- limit=int(args.get("limit") or 20),- )---async def _catalog_tags(args: dict[str, Any], _env: _Env) -> dict[str, Any]:- from jarvis.brain.ollama_library import library_tags-- return await library_tags(_str(args, "model"))---async def _hf_search(args: dict[str, Any], _env: _Env) -> dict[str, Any]:- from jarvis.brain import hf_gguf # lazy: only an install that switched HF on imports it-- return await hf_gguf.search(- _str(args, "query"),- sort=_str(args, "sort") or "downloads",- limit=int(args.get("limit") or 20),- )---async def _benchmarks(args: dict[str, Any], env: _Env) -> dict[str, Any]:- from jarvis.local_models import benchmarks-- table: benchmarks.BenchmarkTable | None- if bool(args.get("refresh")) and env.search_fn is not None:- table = await benchmarks.refresh_benchmarks(env.search_fn)- else:- table = benchmarks.load_cached()- if table is None:- note = (- "No benchmark cache yet; pass refresh=true to build one."- if env.search_fn is not None- else "No benchmark cache and no web search on this surface; curated list only."- )- table = benchmarks.curated_only(note)- return table.to_payload()---async def _pull_status(args: dict[str, Any], _env: _Env) -> dict[str, Any]:- from jarvis.brain.ollama_pull import pull_status-- return await pull_status(_str(args, "model"))---async def _server_log(args: dict[str, Any], _env: _Env) -> dict[str, Any]:- from jarvis.brain.ollama_runtime import tail_log-- lines = max(1, min(int(args.get("lines") or 40), 200))- return {"lines": await asyncio.to_thread(tail_log, lines)}---async def _env_guide(_args: dict[str, Any], _env: _Env) -> dict[str, Any]:- from jarvis.brain.ollama_runtime import env_guide-- return {"entries": env_guide()}---async def _suggest(model: str, env: _Env) -> tuple[dict[str, Any], list[str], dict[str, Any]]:- from jarvis.brain import ollama_inventory as inventory- from jarvis.brain import ollama_profiles- from jarvis.brain.ollama_pull import accelerator_gb, total_memory_gb-- info = await inventory.get_model(env.root, model, transport=env.transport)- (accel, source), ram = await asyncio.gather(- asyncio.to_thread(accelerator_gb), asyncio.to_thread(total_memory_gb)- )- size_gb = round(info.size_bytes / (1024**3), 2)- opts, reasons = ollama_profiles.suggest_options(- size_gb=size_gb,- native_context=info.context_length,- accelerator_gb=accel,- source=source,- ram_gb=ram,- )- facts = {- "model": info.name,- "size_gb": size_gb,- "native_context": info.context_length,- "accelerator_gb": round(accel, 1),- "ram_gb": ram,- }- return opts.model_dump(exclude_none=True), reasons, facts---async def _suggested_options(args: dict[str, Any], env: _Env) -> dict[str, Any]:- options, reasons, facts = await _suggest(_str(args, "model"), env)- return {**facts, "options": options, "reasons": reasons}---async def _test_plan(args: dict[str, Any], env: _Env) -> dict[str, Any]:- from jarvis.local_models.assistant_test import run_setup_test-- raw = args.get("roles")- roles = tuple(str(r) for r in raw) if isinstance(raw, list) and raw else None- report = await run_setup_test(env.cfg, roles, transport=env.transport)- return report.to_payload()---# ── action handlers (ask / monitor) ───────────────────────────────────────---async def _install_ollama(_args: dict[str, Any], _env: _Env) -> dict[str, Any]:- from jarvis.brain import ollama_runtime-- ok, detail = await asyncio.to_thread(ollama_runtime.start_install)- return {"started": ok, "detail": detail, "install": ollama_runtime.install_snapshot()}---async def _start_server(_args: dict[str, Any], _env: _Env) -> dict[str, Any]:- from jarvis.brain.ollama_runtime import start_server-- ok, detail = await asyncio.to_thread(start_server)- return {"ok": ok, "detail": detail}---async def _stop_server(_args: dict[str, Any], _env: _Env) -> dict[str, Any]:- from jarvis.brain.ollama_runtime import stop_server-- ok, detail = await asyncio.to_thread(stop_server)- return {"ok": ok, "detail": detail}---async def _pull(args: dict[str, Any], _env: _Env) -> dict[str, Any]:- """Start (or join) a download and follow it, reporting progress lines."""- from jarvis.brain.ollama_pull import pull_status, start_pull-- model = _str(args, "model")- state = await start_pull(model)- lines: list[str] = [str(state.get("message") or "")]- if state.get("state") != "running":- return {**state, "progress": lines}- max_wait = float(args.get("max_wait_s") or PULL_FOLLOW_MAX_S)- started = time.monotonic()- last_pct = -1- while time.monotonic() - started < max_wait:- await asyncio.sleep(PULL_POLL_S)- state = await pull_status(model)- total = int(state.get("total") or 0)- done = int(state.get("completed") or 0)- pct = int(done * 100 / total) if total else -1- if pct >= 0 and pct // 10 > last_pct // 10:- last_pct = pct- lines.append(f"{model}: {pct}% ({done / 1e9:.1f} of {total / 1e9:.1f} GB)")- if state.get("state") != "running":- lines.append(str(state.get("message") or ""))- return {**state, "progress": lines}- lines.append(f"{model}: still downloading — check lm_pull_status for progress.")- return {**state, "progress": lines}---async def _set_role(args: dict[str, Any], env: _Env) -> dict[str, Any]:- from jarvis.brain.ollama_roles import set_role-- result = dict(set_role(_str(args, "role"), _str(args, "model"), cfg=env.cfg))- if result.get("drift_guarded") is False:- result["warning"] = (- "The pick was written, but the drift baseline could not be updated — "- "the drift guard may revert it within minutes. Check the config baseline."- )- return result---async def _set_model_options(args: dict[str, Any], env: _Env) -> dict[str, Any]:- """Write ONLY keys the suggestion for this model returned — nothing else."""- from jarvis.core import config_writer-- model = _str(args, "model")- wanted = args.get("options")- if not isinstance(wanted, dict) or not wanted:- raise ValueError("options must be a non-empty object.")- suggested, _reasons, _facts = await _suggest(model, env)- allowed = set(suggested)- rejected = sorted(k for k in wanted if k not in allowed)- if rejected:- raise ValueError(- f"Only the suggested keys may be set for {model} ({', '.join(sorted(allowed))}); "- f"refused: {', '.join(rejected)}."- )- written = await asyncio.to_thread(- config_writer.set_ollama_model_options, model, {k: wanted[k] for k in wanted}- )- provider = _ollama_provider(env.cfg)- models = getattr(provider, "models", None)- if isinstance(models, dict):- from jarvis.core.config import OllamaModelOptions-- try:- models[model] = OllamaModelOptions.model_validate(written)- except (TypeError, ValueError):- log.info("local-models: in-memory options for %s not updated", model, exc_info=True)- return {"model": model, "written": written}---async def _install_voice_server(args: dict[str, Any], _env: _Env) -> dict[str, Any]:- from jarvis.realtime.local_server import install as voice_install-- ok, detail = await asyncio.to_thread(- lambda: voice_install.start_install(- confirmed_brain="ollama",- brain_model=_str(args, "brain_model"),- voice_model=_str(args, "voice_model"),- )- )- return {"started": ok, "detail": detail, "install": voice_install.snapshot()}---async def _apply_voice_stack(args: dict[str, Any], env: _Env) -> dict[str, Any]:- from jarvis.realtime.local_server.configure import ManagedSetupError, apply_and_test_stack-- command = _voice_command(env.cfg)- if "--model_name" not in command:- raise ValueError("Install the managed voice server first (lm_install_voice_server).")- try:- result = await apply_and_test_stack(- base_url=_voice_base_url(env.cfg),- current_command=command,- brain_model=_str(args, "brain_model"),- voice_model=_str(args, "voice_model"),- language=_str(args, "language") or "en",- )- except ManagedSetupError as exc:- # The function rolled back (or says it could not) — report, never hide.- return {"ok": False, "rolled_back": "restored" in str(exc), "detail": str(exc)}- voice = _voice_provider(env.cfg)- if voice is not None and result.get("launch_command"):- voice.launch_command = str(result["launch_command"])- return dict(result)---async def _unload(args: dict[str, Any], env: _Env) -> dict[str, Any]:- from jarvis.brain import ollama_inventory as inventory-- model = _str(args, "model")- await inventory.unload_model(env.root, model, transport=env.transport)- return {"model": model, "unloaded": True}---# ── config readers ────────────────────────────────────────────────────────---def _ollama_provider(cfg: Any) -> Any:- providers = getattr(getattr(cfg, "brain", None), "providers", None) or {}- return providers.get("ollama") if isinstance(providers, dict) else None---def _voice_provider(cfg: Any) -> Any:- providers = getattr(getattr(cfg, "brain", None), "providers", None) or {}- return providers.get("local-realtime") if isinstance(providers, dict) else None---def _voice_command(cfg: Any) -> str:- return str(getattr(_voice_provider(cfg), "launch_command", "") or "")---def _voice_base_url(cfg: Any) -> str:- return str(getattr(_voice_provider(cfg), "base_url", "") or "") or "http://127.0.0.1:8765"---# ── the specs ─────────────────────────────────────────────────────────────---def _s(- name: str,- description: str,- schema: dict[str, Any],- tier: RiskTier,- handler: Handler,- summary: Callable[[dict[str, Any]], str] | None = None,-) -> ToolSpec:- return ToolSpec(name, description, schema, tier, handler, summary)---READ_TOOLS: Final[tuple[ToolSpec, ...]] = (- _s(- "lm_hardware",- "This machine's memory: RAM, usable graphics memory and where that figure comes from.",- _obj(),- "safe",- _hardware,- ),- _s(- "lm_server_status",- "Is Ollama installed and running, which version, and the state of the managed voice "- "server (status + preflight) when one exists.",- _obj(),- "safe",- _server_status,- ),- _s(- "lm_inventory",- "Every downloaded model with size, capabilities and context length, plus what is "- "loaded in memory right now.",- _obj(),- "safe",- _inventory,- ),- _s(- "lm_roles",- "The five roles (chat, voice, tools_screen, deep, embedding): current pick, its config "- "key, whether it is installed, which downloads qualify and the recommendation.",- _obj(),- "safe",- _roles,- ),- _s(- "lm_recommendations",- "The curated shortlist ranked for this machine with fit verdicts and the "- "proven / new_little_tested / stale label per entry.",- _obj(),- "safe",- _recommendations,- ),- _s(- "lm_catalog_search",- "Search the public Ollama library (ollama.com).",- _obj(- {- "query": {"type": "string"},- "sort": {"type": "string", "enum": ["popular", "newest"]},- "capability": {- "type": "string",- "enum": ["tools", "vision", "embedding", "thinking"],- },- "limit": {"type": "integer", "minimum": 1, "maximum": 50},- }- ),- "safe",- _catalog_search,- ),- _s(- "lm_catalog_tags",- "Every tag of one library model with its size and fit verdict for this machine.",- _obj({"model": _MODEL}, ("model",)),- "safe",- _catalog_tags,- ),- _s(- "lm_hf_search",- "Search GGUF repositories on Hugging Face (only when the user enabled it).",- _obj(- {- "query": {"type": "string"},- "sort": {"type": "string", "enum": ["downloads", "lastModified", "trendingScore"]},- "limit": {"type": "integer", "minimum": 1, "maximum": 100},- }- ),- "safe",- _hf_search,- ),- _s(- "lm_benchmarks",- "The benchmark table behind the proven / new labels (cached seven days). "- "refresh=true rebuilds it from the web inside a guided run.",- _obj({"refresh": {"type": "boolean"}}),- "safe",- _benchmarks,- ),- _s(- "lm_pull_status",- "Progress of one download.",- _obj({"model": _MODEL}, ("model",)),- "safe",- _pull_status,- ),- _s(- "lm_server_log",- "The last lines of the Ollama server log Jarvis writes.",- _obj({"lines": {"type": "integer", "minimum": 1, "maximum": 200}}),- "safe",- _server_log,- ),- _s(- "lm_env_guide",- "The OLLAMA_* environment variables that matter (models dir, host, keep-alive) and how "- "to set each on this OS — advice only, nothing is applied.",- _obj(),- "safe",- _env_guide,- ),- _s(- "lm_suggested_options",- "An advisory option profile (num_ctx, num_gpu, …) for one installed model on this "- "machine, with one reason per knob. Only these keys may be set with "- "lm_set_model_options.",- _obj({"model": _MODEL}, ("model",)),- "safe",- _suggested_options,- ),- _s(- "lm_test_plan",- "Run the end-to-end test: server probe, one real generation per configured role, an "- "embedding round trip, the voice probe when a managed voice server exists. Returns a "- "per-role table with ok / error statuses.",- _obj(- {- "roles": {- "type": "array",- "items": {"type": "string"},- "description": "Subset of chat, voice, tools_screen, deep, embedding.",- }- }- ),- "safe",- _test_plan,- ),-)--ACTION_TOOLS: Final[tuple[ToolSpec, ...]] = (- _s(- "lm_install_ollama",- "Install Ollama on this machine (winget / installer / install.sh). Starts in the "- "background; follow it with lm_server_status.",- _obj(),- "ask",- _install_ollama,- lambda _a: "Install Ollama",- ),- _s(- "lm_start_server",- "Start the Ollama server.",- _obj(),- "ask",- _start_server,- lambda _a: "Start the Ollama server",- ),- _s(- "lm_stop_server",- "Stop the Ollama server Jarvis started (never one started elsewhere).",- _obj(),- "ask",- _stop_server,- lambda _a: "Stop the Ollama server",- ),- _s(- "lm_pull",- "Download a model and follow the download, returning progress lines. Long downloads "- "hand back 'still downloading'; poll lm_pull_status then.",- _obj({"model": _MODEL, "max_wait_s": {"type": "number"}}, ("model",)),- "ask",- _pull,- lambda a: f"Download {a.get('model', '')}",- ),- _s(- "lm_set_role",- "Persist which installed model serves a role. Reports drift_guarded=false when the "- "config baseline could not be updated (the pick may then be reverted).",- _obj({"role": _ROLE, "model": _MODEL}, ("role", "model")),- "ask",- _set_role,- lambda a: f"Use {a.get('model', '')} for {a.get('role', '')}",- ),- _s(- "lm_set_model_options",- "Persist per-model options — only keys lm_suggested_options returned for that model.",- _obj(- {- "model": _MODEL,- "options": {"type": "object", "description": "num_ctx, num_gpu, … values."},- },- ("model", "options"),- ),- "ask",- _set_model_options,- lambda a: f"Tune {a.get('model', '')}",- ),- _s(- "lm_install_voice_server",- "Install the Jarvis-managed local voice server (background; follow with lm_server_status).",- _obj({"brain_model": _MODEL, "voice_model": {"type": "string"}}),- "ask",- _install_voice_server,- lambda _a: "Install the local voice server",- ),- _s(- "lm_apply_voice_stack",- "Switch the managed voice server to a brain + voice model pair, run the voice test and "- "persist only on success; reports a rollback otherwise.",- _obj(- {- "brain_model": _MODEL,- "voice_model": {"type": "string", "description": "A voice profile id."},- "language": {"type": "string"},- },- ("brain_model", "voice_model"),- ),- "ask",- _apply_voice_stack,- lambda a: f"Voice stack: {a.get('brain_model', '')} + {a.get('voice_model', '')}",- ),- _s(- "lm_unload",- "Free the memory a loaded model holds (it reloads on the next request).",- _obj({"model": _MODEL}, ("model",)),- "monitor",- _unload,- lambda a: f"Unload {a.get('model', '')}",- ),-)---def tool_specs(cfg: Any) -> tuple[ToolSpec, ...]:- """The specs offered for ``cfg`` — HF search only when the user enabled it."""- from jarvis.core.config import ollama_hf_enabled-- hf = ollama_hf_enabled(cfg) if cfg is not None else False- reads = tuple(s for s in READ_TOOLS if hf or s.name != "lm_hf_search")- return reads + ACTION_TOOLS---def build_tools(- cfg: Any,- *,- root: str,- transport: Any = None,- search_fn: Callable[[str], Any] | None = None,-) -> dict[str, Tool]:- """The assistant's tools for one turn, keyed by name.-- ``root`` is the Ollama server root the section talks to; ``transport``- the httpx test seam; ``search_fn`` (the ``search_web`` call) lets- ``lm_benchmarks`` refresh the table — without it the table is read-only.- """- env = _Env(cfg=cfg, root=root, transport=transport, search_fn=search_fn)- return {spec.name: LocalModelsTool(spec, env) for spec in tool_specs(cfg)}diff --git a/jarvis/local_models/benchmarks.py b/jarvis/local_models/benchmarks.pydeleted file mode 100644index 4570030f7b..0000000000--- a/jarvis/local_models/benchmarks.py+++ /dev/null@@ -1,511 +0,0 @@-"""Benchmarks and freshness for the curated shortlist: proven, new, or stale?--The setup assistant must prefer the best *proven* local models and never-pick a brand-new one as a default. "Proven" is decided here from two-sources, both tolerant of being unreachable:--* public benchmark pages (Artificial Analysis, LMArena, the Open LLM- Leaderboard) reached through a caller-supplied ``search_fn`` (the- key-free ``search_web`` tool in production) — the snippets are mined with- tolerant regexes into ``{family, source, metric, value, url, seen_at}``- rows;-* the Ollama library (``ollama_library.search_library``) for pulls and the- last update of each family.--The result is cached at ``DATA_DIR/state/local_models_benchmarks.json`` for-seven days; the assistant refreshes it only inside a guided run or on an-explicit "Refresh shortlist". Offline, the cache or a curated-only table-(with a note saying so) is the answer — never an error.--:func:`label_for` is the pure labelling rule the proposal card renders and-the tests pin.-"""--from __future__ import annotations--import asyncio-import datetime as _dt-import inspect-import json-import logging-import os-import re-import uuid-from collections.abc import Awaitable, Callable, Iterable-from dataclasses import dataclass-from pathlib import Path-from typing import Any--log = logging.getLogger(__name__)--__all__ = [- "BENCHMARK_FILE_NAME",- "CACHE_TTL_DAYS",- "LABELS",- "BenchmarkRow",- "BenchmarkTable",- "LibraryFacts",- "extract_rows",- "family_of",- "label_for",- "load_cached",- "parse_pulls",- "parse_updated_days",- "refresh_benchmarks",-]--BENCHMARK_FILE_NAME = "local_models_benchmarks.json"-CACHE_TTL_DAYS = 7--#: The three labels, in the order the card explains them.-LABELS: tuple[str, ...] = ("proven", "new_little_tested", "stale")--#: Library facts that make a family "proven" without a benchmark row.-PROVEN_MIN_PULLS = 100_000-#: A family updated more recently than this is "new" whatever the numbers say.-NEW_MAX_AGE_DAYS = 60--#: Query templates, one per source; ``{family}`` is the curated family name.-QUERY_TEMPLATES: tuple[tuple[str, str], ...] = (- ("artificial_analysis", "{family} Artificial Analysis intelligence index"),- ("lmarena", "{family} LMArena text arena score"),- ("open_llm_leaderboard", "{family} Open LLM Leaderboard average score"),-)--#: Result host → source id, so a snippet from LMArena found via the-#: Artificial-Analysis query is still filed under LMArena.-_SOURCE_HOSTS: tuple[tuple[str, str], ...] = (- ("artificialanalysis.ai", "artificial_analysis"),- ("lmarena.ai", "lmarena"),- ("lmsys.org", "lmarena"),- ("huggingface.co", "open_llm_leaderboard"),-)--#: (metric id, tolerant pattern). Values are the first capture group.-_METRIC_PATTERNS: tuple[tuple[str, re.Pattern[str]], ...] = (- (- "intelligence_index",- re.compile(r"intelligence\s+index(?:\s+of)?\s*[:=]?\s*(\d{1,3}(?:\.\d+)?)", re.I),- ),- (- "arena_score",- re.compile(r"(?:arena|elo)\s*(?:score|rating)?\s*(?:of|[:=])?\s*(\d{3,4})\b", re.I),- ),- (- "leaderboard_average",- re.compile(- r"(?:average|avg\.?)\s*(?:score)?\s*(?:of|[:=])?\s*(\d{1,3}(?:\.\d+)?)\s*%?", re.I- ),- ),- (- "mmlu",- re.compile(r"MMLU(?:-Pro)?\s*(?:score)?\s*(?:of|[:=])?\s*(\d{1,3}(?:\.\d+)?)\s*%?", re.I),- ),- (- "gpqa",- re.compile(r"GPQA(?:\s+Diamond)?\s*(?:score)?\s*(?:of|[:=])?\s*(\d{1,3}(?:\.\d+)?)", re.I),- ),-)--SearchFn = Callable[[str], Any]---@dataclass(frozen=True, slots=True)-class BenchmarkRow:- family: str- source: str- metric: str- value: float- url: str- seen_at: str-- def to_payload(self) -> dict[str, Any]:- return {- "family": self.family,- "source": self.source,- "metric": self.metric,- "value": self.value,- "url": self.url,- "seen_at": self.seen_at,- }---@dataclass(frozen=True, slots=True)-class LibraryFacts:- family: str- pulls: int- #: Days since the library's "Updated … ago"; ``None`` when unknown.- updated_days: int | None-- def to_payload(self) -> dict[str, Any]:- return {"family": self.family, "pulls": self.pulls, "updated_days": self.updated_days}---@dataclass(frozen=True, slots=True)-class BenchmarkTable:- fetched_at: str- rows: tuple[BenchmarkRow, ...]- library: dict[str, LibraryFacts]- #: ``live`` | ``cache`` | ``curated`` — where the numbers came from.- source: str- #: One sentence when the table is not live ("" otherwise).- note: str = ""-- def rows_for(self, family: str) -> tuple[BenchmarkRow, ...]:- return tuple(r for r in self.rows if r.family == family)-- def to_payload(self) -> dict[str, Any]:- return {- "fetched_at": self.fetched_at,- "source": self.source,- "note": self.note,- "rows": [r.to_payload() for r in self.rows],- "library": {f: facts.to_payload() for f, facts in self.library.items()},- }-- @classmethod- def from_payload(cls, payload: dict[str, Any], *, source: str | None = None) -> BenchmarkTable:- rows: list[BenchmarkRow] = []- for raw in payload.get("rows") or []:- try:- rows.append(- BenchmarkRow(- family=str(raw["family"]),- source=str(raw.get("source") or ""),- metric=str(raw.get("metric") or ""),- value=float(raw.get("value") or 0.0),- url=str(raw.get("url") or ""),- seen_at=str(raw.get("seen_at") or ""),- )- )- except (KeyError, TypeError, ValueError):- log.debug("benchmarks: dropping malformed row %r", raw)- library: dict[str, LibraryFacts] = {}- for family, raw in (payload.get("library") or {}).items():- try:- updated = raw.get("updated_days")- library[str(family)] = LibraryFacts(- family=str(family),- pulls=int(raw.get("pulls") or 0),- updated_days=None if updated is None else int(updated),- )- except (AttributeError, TypeError, ValueError):- log.debug("benchmarks: dropping malformed library facts %r", raw)- return cls(- fetched_at=str(payload.get("fetched_at") or ""),- rows=tuple(rows),- library=library,- source=source or str(payload.get("source") or "cache"),- note=str(payload.get("note") or ""),- )---# ── Small pure helpers ────────────────────────────────────────────────────---def family_of(model_id: str) -> str:- """``qwen3.5:4b`` → ``qwen3.5``; ``hf.co/u/r:Q4`` keeps its path."""- return (model_id or "").strip().partition(":")[0]---def _entry_id(entry: Any) -> str:- """The model id of a curated entry or a bare id string."""- return str(getattr(entry, "id", None) or entry or "")---def curated_families(entries: Iterable[Any] | None = None) -> tuple[str, ...]:- """The distinct families of the curated shortlist, in list order."""- if entries is None:- from jarvis.brain.ollama_pull import RECOMMENDED_MODELS-- entries = tuple(RECOMMENDED_MODELS)- seen: list[str] = []- for entry in entries:- family = family_of(_entry_id(entry))- if family and family not in seen:- seen.append(family)- return tuple(seen)---_PULLS_FACTOR = {"": 1, "K": 1_000, "M": 1_000_000, "B": 1_000_000_000}---def parse_pulls(text: str) -> int:- """``"17.2M"`` → ``17200000``; anything unreadable → ``0``."""- match = re.fullmatch(r"\s*([\d.,]+)\s*([KMB]?)\s*", (text or "").upper())- if not match:- return 0- try:- return int(float(match.group(1).replace(",", "")) * _PULLS_FACTOR[match.group(2)])- except ValueError:- return 0---_UNIT_DAYS = {- "second": 0,- "minute": 0,- "hour": 0,- "day": 1,- "week": 7,- "month": 30,- "year": 365,-}---def parse_updated_days(text: str) -> int | None:- """``"2 weeks ago"`` → ``14``, ``"yesterday"`` → ``1``; unknown → ``None``."""- t = (text or "").strip().lower()- if not t:- return None- if t in ("yesterday",):- return 1- if t in ("today", "just now"):- return 0- match = re.match(r"(a|an|\d+)\s+(second|minute|hour|day|week|month|year)s?\s+ago", t)- if not match:- return None- count = 1 if match.group(1) in ("a", "an") else int(match.group(1))- return count * _UNIT_DAYS[match.group(2)]---def _source_for(url: str, fallback: str) -> str:- low = (url or "").lower()- for host, source in _SOURCE_HOSTS:- if host in low:- return source- return fallback---def extract_rows(- family: str, results: Iterable[dict[str, Any]], *, source: str, seen_at: str-) -> list[BenchmarkRow]:- """Mine benchmark numbers out of search snippets — tolerant, never raising.-- A snippet counts only when it names the family (case-insensitive,- ``qwen3.5`` also matches ``Qwen 3.5``) AND carries a number one of the- metric patterns understands. One row per (source, metric) per family.- """- needle = re.escape(family.lower()).replace(r"\.", r"\.?").replace(r"\-", r"[\s-]?")- needle = re.sub(r"([a-z])(\d)", r"\1\\s?\2", needle)- family_re = re.compile(needle, re.I)- rows: dict[tuple[str, str], BenchmarkRow] = {}- for result in results:- if not isinstance(result, dict):- continue- text = f"{result.get('title') or ''} {result.get('snippet') or ''}"- if not family_re.search(text):- continue- url = str(result.get("url") or "")- row_source = _source_for(url, source)- for metric, pattern in _METRIC_PATTERNS:- match = pattern.search(text)- if not match:- continue- try:- value = float(match.group(1))- except ValueError:- continue- key = (row_source, metric)- if key not in rows:- rows[key] = BenchmarkRow(family, row_source, metric, value, url, seen_at)- return list(rows.values())---# ── The labelling rule ────────────────────────────────────────────────────---def label_for(entry: Any, table: BenchmarkTable | None, today: _dt.date) -> str:- """``proven`` | ``new_little_tested`` | ``stale`` for one curated entry.-- In order:-- 1. ``stale`` — the curated list was last reviewed more than a year before- ``today`` (nothing on it may be called proven any more).- 2. ``new_little_tested`` — the library updated the family less than- :data:`NEW_MAX_AGE_DAYS` ago (a brand-new build is never a default,- whatever last month's numbers said).- 3. ``proven`` — at least one benchmark row, or :data:`PROVEN_MIN_PULLS`- pulls in the library.- 4. Otherwise ``new_little_tested`` (no row, no pull count to speak of).-- ``entry`` is a curated :class:`~jarvis.brain.ollama_pull.RecommendedModel`- or a model id string; ``table`` may be ``None`` (curated-only mode).- """- from jarvis.brain.ollama_pull import CURATED_MAX_AGE_DAYS, CURATED_REVIEWED_ON-- if (today - CURATED_REVIEWED_ON).days > CURATED_MAX_AGE_DAYS:- return "stale"- family = family_of(_entry_id(entry))- facts = table.library.get(family) if table is not None else None- updated_days = facts.updated_days if facts is not None else None- if updated_days is not None and updated_days < NEW_MAX_AGE_DAYS:- return "new_little_tested"- if table is not None and table.rows_for(family):- return "proven"- if facts is not None and facts.pulls >= PROVEN_MIN_PULLS:- return "proven"- return "new_little_tested"---# ── Cache ─────────────────────────────────────────────────────────────────---def cache_path() -> Path:- from jarvis.core import config as cfg_mod # lazy: DATA_DIR is monkeypatched by tests-- return Path(cfg_mod.DATA_DIR) / "state" / BENCHMARK_FILE_NAME---def _atomic_write_json(path: Path, payload: dict[str, Any]) -> bool:- temporary = path.with_name(f".{path.name}.{os.getpid()}.{uuid.uuid4().hex}.tmp")- try:- path.parent.mkdir(parents=True, exist_ok=True)- temporary.write_text(json.dumps(payload, indent=2), encoding="utf-8")- os.replace(temporary, path)- return True- except OSError:- log.warning("benchmarks: cache %s not written", path, exc_info=True)- return False- finally:- try:- temporary.unlink(missing_ok=True)- except OSError:- log.debug("benchmarks: temporary cache cleanup failed", exc_info=True)---def load_cached(- *, max_age_days: int | None = CACHE_TTL_DAYS, now: _dt.datetime | None = None-) -> BenchmarkTable | None:- """The cached table when it exists and is younger than ``max_age_days``.-- ``max_age_days=None`` returns whatever is on disk, however old — the- offline fallback prefers a stale table over none.- """- path = cache_path()- try:- payload = json.loads(path.read_text(encoding="utf-8"))- except FileNotFoundError:- return None- except (OSError, ValueError):- log.info("benchmarks: cache %s unreadable", path, exc_info=True)- return None- if not isinstance(payload, dict):- return None- table = BenchmarkTable.from_payload(payload, source="cache")- if max_age_days is not None:- fetched = _parse_iso(table.fetched_at)- current = now or _dt.datetime.now(_dt.UTC)- if fetched is None or (current - fetched).days >= max_age_days:- return None- return table---def _parse_iso(text: str) -> _dt.datetime | None:- try:- value = _dt.datetime.fromisoformat(text)- except (TypeError, ValueError):- return None- return value if value.tzinfo is not None else value.replace(tzinfo=_dt.UTC)---def curated_only(note: str = "") -> BenchmarkTable:- """An empty table that says so — the honest offline answer."""- return BenchmarkTable(- fetched_at="",- rows=(),- library={},- source="curated",- note=note or "No benchmark data reachable; showing the curated shortlist only.",- )---# ── Refresh ───────────────────────────────────────────────────────────────---async def _call(fn: Callable[..., Any], *args: Any, **kwargs: Any) -> Any:- """Call a sync or async seam uniformly."""- result = fn(*args, **kwargs)- if inspect.isawaitable(result):- return await result- return result---async def _library_facts(- family: str, library_fn: Callable[[str], Awaitable[dict[str, Any]]]-) -> LibraryFacts | None:- try:- payload = await library_fn(family)- except Exception: # noqa: BLE001 — the library is advisory; log and go on- log.info("benchmarks: library lookup for %s failed", family, exc_info=True)- return None- if not isinstance(payload, dict) or payload.get("error"):- return None- for entry in payload.get("models") or []:- if isinstance(entry, dict) and str(entry.get("name") or "") == family:- return LibraryFacts(- family=family,- pulls=parse_pulls(str(entry.get("pulls") or "")),- updated_days=parse_updated_days(str(entry.get("updated") or "")),- )- return None---async def _default_library_fn(family: str) -> dict[str, Any]:- from jarvis.brain.ollama_library import search_library-- return await search_library(family, limit=10)---async def refresh_benchmarks(- search_fn: SearchFn,- *,- families: Iterable[str] | None = None,- library_fn: Callable[[str], Awaitable[dict[str, Any]]] | None = None,- now: _dt.datetime | None = None,- persist: bool = True,-) -> BenchmarkTable:- """Rebuild the table: three concurrent searches per family plus the library.-- ``search_fn(query)`` returns (or resolves to) a list of- ``{title, url, snippet}`` dicts; one failing query loses only its rows.- When EVERY query failed or answered nothing and the library is silent too,- the cached table (any age) or a curated-only table is returned with a- note — the shortlist must render offline.- """- fams = tuple(families) if families is not None else curated_families()- stamp = (now or _dt.datetime.now(_dt.UTC)).isoformat(timespec="seconds")- lib_fn = library_fn or _default_library_fn-- async def _search(family: str, source: str, template: str) -> list[BenchmarkRow]:- query = template.format(family=family)- try:- results = await _call(search_fn, query)- except Exception: # noqa: BLE001 — one failed query loses only its rows- log.info("benchmarks: search %r failed", query, exc_info=True)- return []- if not isinstance(results, list):- return []- return extract_rows(family, results, source=source, seen_at=stamp)-- searches = [- _search(family, source, template) for family in fams for source, template in QUERY_TEMPLATES- ]- lookups = [_library_facts(family, lib_fn) for family in fams]- search_results, library_results = await asyncio.gather(- asyncio.gather(*searches), asyncio.gather(*lookups)- )-- rows: list[BenchmarkRow] = [row for batch in search_results for row in batch]- library = {facts.family: facts for facts in library_results if facts is not None}-- if not rows and not library:- cached = load_cached(max_age_days=None)- if cached is not None:- note = "Benchmark sources unreachable; showing the cached table."- return BenchmarkTable(cached.fetched_at, cached.rows, cached.library, "cache", note)- return curated_only()-- table = BenchmarkTable(fetched_at=stamp, rows=tuple(rows), library=library, source="live")- if persist:- _atomic_write_json(cache_path(), table.to_payload())- return tablediff --git a/jarvis/local_models/health_monitor.py b/jarvis/local_models/health_monitor.pyindex e6f0676e97..6ac31954fa 100644--- a/jarvis/local_models/health_monitor.py+++ b/jarvis/local_models/health_monitor.py@@ -4,9 +4,8 @@ Started from the web server's lifespan next to the marketplace refreshscheduler: first run ten minutes after boot, then every``[brain.providers.ollama].health_check_hours`` (default 6). Nothing hereruns on the boot path (AP-26) and nothing toasts: the result is one record-in ``DATA_DIR/state/local_models_health.json`` (the same file the setup test-writes), which the sidebar badge and ``GET /api/providers/section-health``-read.+in ``DATA_DIR/state/local_models_health.json``, which the sidebar badge and+``GET /api/providers/section-health`` read.One check: skip entirely when the server is down AND no role is configured(nothing to watch yet); otherwise ``probe_host`` plus one real 1-token chat@@ -19,8 +18,13 @@ from __future__ import annotationsimport asyncioimport datetime as _dt+import jsonimport logging+import os+import uuidfrom collections.abc import Awaitable, Callable+from dataclasses import dataclass+from pathlib import Pathfrom typing import Anylog = logging.getLogger(__name__)@@ -29,9 +33,12 @@ __all__ = ["DEFAULT_INTERVAL_HOURS","FIRST_RUN_DELAY_S","GENERATION_CAP_S",+ "HEALTH_FILE_NAME","HealthMonitor","check_once",+ "health_path","interval_hours",+ "load_last_report","read_health_record","write_health_record",]@@ -42,10 +49,21 @@ GENERATION_CAP_S = 30.0#: Never spin faster than this, whatever the config says.MIN_INTERVAL_S = 60.0+HEALTH_FILE_NAME = "local_models_health.json"+ProbeFn = Callable[[str], Awaitable[dict[str, Any]]]GenerateFn = Callable[[Any, str], Awaitable[Any]]+@dataclass(frozen=True, slots=True)+class _OllamaSpec:+ """The three fields :func:`run_provider_test` reads from a provider spec."""++ id: str = "ollama"+ tier: str = "brain"+ auth_mode: str = "none"++# ── config + record ───────────────────────────────────────────────────────@@ -60,10 +78,45 @@ def interval_hours(cfg: Any) -> float:return hours if hours > 0 else DEFAULT_INTERVAL_HOURS+def health_path() -> Path:+ """``DATA_DIR/state/local_models_health.json`` — resolved at call time."""+ from jarvis.core import config as cfg_mod # lazy: DATA_DIR is monkeypatched by tests++ return Path(cfg_mod.DATA_DIR) / "state" / HEALTH_FILE_NAME+++def _atomic_write_json(path: Path, payload: dict[str, Any]) -> bool:+ temporary = path.with_name(f".{path.name}.{os.getpid()}.{uuid.uuid4().hex}.tmp")+ try:+ path.parent.mkdir(parents=True, exist_ok=True)+ temporary.write_text(json.dumps(payload, indent=2), encoding="utf-8")+ os.replace(temporary, path)+ return True+ except OSError:+ log.warning("local-models: health file %s not written", path, exc_info=True)+ return False+ finally:+ try:+ temporary.unlink(missing_ok=True)+ except OSError:+ log.debug("local-models: temporary health file cleanup failed", exc_info=True)+++def load_last_report() -> dict[str, Any] | None:+ """The persisted payload of the last check, or ``None`` when none / unreadable."""+ path = health_path()+ try:+ payload = json.loads(path.read_text(encoding="utf-8"))+ except FileNotFoundError:+ return None+ except (OSError, ValueError):+ log.info("local-models: health file %s unreadable", path, exc_info=True)+ return None+ return payload if isinstance(payload, dict) else None++def read_health_record() -> dict[str, Any]:"""The badge record: ``{status, reason, since, last_ok, checked_at}`` (file only)."""- from jarvis.local_models.assistant_test import load_last_report-payload = load_last_report() or {}return {"status": str(payload.get("status") or "unknown"),@@ -75,13 +128,7 @@ def read_health_record() -> dict[str, Any]:def write_health_record(status: str, reason: str, *, checked_at: str | None = None) -> bool:- """Merge the badge keys into the health file, keeping the last test's table."""- from jarvis.local_models.assistant_test import (- _atomic_write_json,- health_path,- load_last_report,- )-+ """Merge the badge keys into the health file; ``since`` holds while the status does."""stamp = checked_at or _dt.datetime.now(_dt.UTC).isoformat(timespec="seconds")previous = load_last_report() or {}payload = dict(previous)@@ -101,6 +148,19 @@ def write_health_record(status: str, reason: str, *, checked_at: str | None = No# ── one check ─────────────────────────────────────────────────────────────+def _server_root(cfg: Any) -> str:+ providers = getattr(getattr(cfg, "brain", None), "providers", None) or {}+ ollama = providers.get("ollama") if isinstance(providers, dict) else None+ override = str(getattr(ollama, "base_url", "") or "")+ if override:+ from jarvis.plugins.brain.ollama import normalize_server_root++ return normalize_server_root(override)+ from jarvis.brain.ollama_pull import server_root++ return server_root()++def _configured_roles(cfg: Any) -> dict[str, str]:from jarvis.brain.ollama_roles import WRITABLE_ROLE_IDS, current_pick@@ -124,7 +184,6 @@ async def _default_probe(root: str) -> dict[str, Any]:async def _default_generate(cfg: Any, model: str) -> Any:from jarvis.brain import provider_test- from jarvis.local_models.assistant_test import _OllamaSpecreturn await provider_test.run_provider_test(_OllamaSpec(), cfg, model=model, timeout_s=GENERATION_CAP_S@@ -140,8 +199,6 @@ async def check_once(persist: bool = True,) -> dict[str, Any] | None:"""One self-check; returns the record written, or ``None`` when skipped."""- from jarvis.local_models.assistant_test import _server_root-root = root or _server_root(cfg)roles = _configured_roles(cfg)server = await (probe or _default_probe)(root)diff --git a/jarvis/ui/web/frontend/src/components/local-models/AssistantContext.tsx b/jarvis/ui/web/frontend/src/components/local-models/AssistantContext.tsxdeleted file mode 100644index 50b0c04eb4..0000000000--- a/jarvis/ui/web/frontend/src/components/local-models/AssistantContext.tsx+++ /dev/null@@ -1,306 +0,0 @@-/**- * The setup helper's context rail — who is answering, and what runs locally.- *- * The section is called "Local models", but the helper itself is NOT one: it- * runs on the Agents-tier Tool Model, in the cloud, billed through that key- * (`jarvis/local_models/assistant_session.py`). Every step it narrates- * ("Downloaded ornith:9b") is about a model on this machine. Without naming- * both, a reader cannot tell who is speaking from what is being installed —- * so the rail names the brain at the top and the machine's roles underneath,- * in that order.- *- * Nothing here is new data: the pair comes from the `/session` response the- * panel already fetches, the roles and the server from the same two queries- * the Overview tab runs (one React-Query cache, so switching tabs re-fetches- * nothing).- *- * On a narrow window the rail is gone and `AssistantOriginChip` carries the- * same answer in the header — one line instead of three blocks.- */-import { useMemo } from "react";--import { ProviderLogo } from "@/components/providers/ProviderLogo";-import { useRoles, useServer } from "@/hooks/useLocalModels";-import { fill, useT } from "@/i18n";-import { cn } from "@/lib/utils";--import type { AssistantHealth, AssistantSessionResponse } from "./assistantApi";-import { assistantTimestamp } from "./assistantApi";--/** The tone a health record draws with — shared by the rail and the timeline. */-export function healthTone(- health: AssistantHealth | null,-): "ok" | "off" | "warn" | "error" {- if (!health) return "off";- if (health.status === "ok") return "ok";- if (health.status === "unknown") return "off";- return "warn";-}--/** "gemini" -> "Gemini" when nothing better is known; the resolver wins. */-export function providerDisplayName(- providerId: string,- resolve?: (id: string) => string,-): string {- const resolved = resolve?.(providerId);- if (resolved && resolved !== providerId) return resolved;- return providerId ? providerId[0].toUpperCase() + providerId.slice(1) : "";-}--export interface AssistantContextProps {- /** The local server's card id — the roles and server queries hang off it. */- providerId: string;- /** What the section calls that server ("Ollama"). */- serverLabel: string;- /** `/session`: the Agents-tier pair plus whether it can run right now. */- session: AssistantSessionResponse | null;- health: AssistantHealth | null;- onOpenApiKeys: () => void;- /** Starts a diagnose run — the Fix beside a failing health record. */- onDiagnose: () => void;- /** Provider id -> display label, from the section's provider list. */- providerLabel?: (id: string) => string;-}--/** The one-line answer to "who is writing this?", for narrow windows. */-export function AssistantOriginChip({- session,- providerLabel,- onOpenApiKeys,-}: {- session: AssistantSessionResponse | null;- providerLabel?: (id: string) => string;- onOpenApiKeys: () => void;-}) {- const t = useT();- if (!session?.provider) return null;- const label = providerDisplayName(session.provider, providerLabel);- return (- <button- type="button"- onClick={onOpenApiKeys}- title={t("local_models.assistant.origin_cloud")}- data-testid="assistant-origin-chip"- className={cn(- "inline-flex max-w-[18rem] items-center gap-1.5 rounded-full border border-border bg-card px-2.5 py-1",- "text-[11.5px] text-muted-foreground transition-colors hover:text-foreground",- "focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring",- )}- >- <ProviderLogo providerId={session.provider} label={label} size="sm" />- <span className="truncate">- {label}- {session.model ? ` · ${session.model}` : ""}- </span>- {!session.ready && (- <span className="h-1.5 w-1.5 shrink-0 rounded-full bg-amber-500" aria-hidden />- )}- </button>- );-}--export function AssistantContext({- providerId,- serverLabel,- session,- health,- onOpenApiKeys,- onDiagnose,- providerLabel,-}: AssistantContextProps) {- const t = useT();- const roles = useRoles(providerId);- const server = useServer(providerId);-- // The primary slots only — the read-only advanced ones live in the Roles- // panel behind "More roles" and would turn a rail into a ledger.- const rows = useMemo(- () => (roles.data?.roles ?? []).filter((r) => !r.advanced),- [roles.data],- );-- const checkedAt = assistantTimestamp(health?.checked_at);- const needsFix = health?.status === "error" || health?.status === "needs_setup";- const brandLabel = session?.provider- ? providerDisplayName(session.provider, providerLabel)- : "";-- return (- <aside- className="hidden w-[19rem] shrink-0 flex-col gap-7 overflow-y-auto border-l border-border/70 bg-card/30 px-5 py-6 xl:flex"- data-testid="assistant-context"- >- {/* ── who is answering ─────────────────────────────────────────── */}- <section data-testid="assistant-origin">- <RailTitle>{t("local_models.assistant.origin_title")}</RailTitle>- {brandLabel ? (- <>- <div className="mt-2.5 flex items-center gap-2">- <ProviderLogo- providerId={session?.provider ?? ""}- label={brandLabel}- size="sm"- />- <span className="truncate text-[13.5px] font-medium text-foreground">- {brandLabel}- </span>- </div>- <p- className="mt-1 break-all font-mono text-[11.5px] leading-snug text-muted-foreground"- data-testid="assistant-origin-model"- >- {session?.model || t("local_models.assistant.origin_default_model")}- </p>- </>- ) : (- <p className="mt-2.5 text-[12.5px] text-muted-foreground">- {t("local_models.assistant.origin_unset")}- </p>- )}-- {session && !session.ready && session.reason ? (- <p- className="mt-3 rounded-lg border border-amber-500/40 bg-amber-500/10 px-2.5 py-2 text-[12px] leading-relaxed"- data-testid="assistant-origin-blocked"- >- {session.reason}- </p>- ) : (- <p className="mt-3 text-[12px] leading-relaxed text-muted-foreground">- {t("local_models.assistant.origin_cloud")}- </p>- )}-- <button- type="button"- onClick={onOpenApiKeys}- className="mt-2 text-[12px] font-medium text-primary underline-offset-4 hover:underline"- data-testid="assistant-origin-change"- >- {t("local_models.assistant.origin_change")}- </button>- </section>-- {/* ── what runs here ───────────────────────────────────────────── */}- <section data-testid="assistant-machine">- <RailTitle>{t("local_models.assistant.machine_title")}</RailTitle>- <div className="mt-2.5">- <RailStatus tone={server.data?.running ? "ok" : "off"}>- {fill(- t(- server.data?.running- ? "local_models.assistant.machine_server_running"- : "local_models.assistant.machine_server_stopped",- ),- { server: serverLabel },- )}- </RailStatus>- </div>-- {rows.length > 0 ? (- <dl className="mt-3 flex flex-col gap-2">- {rows.map((row) => {- // Configured but gone from the server: the run will fail on it,- // so it reads as a warning here rather than as a plain name.- const missing = row.current !== "" && !row.installed;- return (- <div key={row.id} className="flex flex-col gap-0.5">- <dt className="text-[11.5px] text-muted-foreground">- {t(row.label_key)}- </dt>- <dd- className={cn(- "break-all font-mono text-[11.5px] leading-snug",- row.current ? "text-foreground" : "text-muted-foreground/70",- missing && "text-amber-500",- )}- data-testid={`assistant-machine-${row.id}`}- >- {row.current || t("local_models.assistant.machine_unset")}- {missing && (- <span className="ml-1 font-sans text-[11px]">- ({t("local_models.assistant.machine_missing")})- </span>- )}- </dd>- </div>- );- })}- </dl>- ) : (- <p className="mt-3 text-[12px] text-muted-foreground">- {roles.isLoading- ? t("local_models.assistant.machine_loading")- : (roles.data?.error ?? "")}- </p>- )}- </section>-- {/* ── the monitor's verdict, parked instead of scrolling away ──── */}- {health && checkedAt && (- <section data-testid="assistant-health-rail">- <RailStatus tone={healthTone(health)}>- {fill(t("local_models.assistant.last_check"), {- when: checkedAt.toLocaleString(),- what:- health.reason ||- t(`local_models.assistant.health_${health.status}`),- })}- </RailStatus>- {needsFix && (- <button- type="button"- onClick={onDiagnose}- className="mt-1.5 text-[12px] font-medium text-primary underline-offset-4 hover:underline"- data-testid="assistant-health-rail-fix"- >- {t("local_models.assistant.fix")}- </button>- )}- </section>- )}- </aside>- );-}--/**- * A dot and a sentence that WRAPS.- *- * Not the shared `StatusDot`: that one is an `inline-flex` whose label is- * `truncate`, so a health sentence keeps its full single-line width, pushes- * the rail's scrollWidth past 600px in a 293px column and gets clipped. A- * column this narrow needs the text to break, not to be cut.- */-function RailStatus({- tone,- children,-}: {- tone: "ok" | "off" | "warn" | "error";- children: React.ReactNode;-}) {- const color = {- ok: "bg-emerald-500",- off: "bg-muted-foreground/40",- warn: "bg-amber-500",- error: "bg-destructive",- }[tone];- return (- <span className="flex items-start gap-2">- <span- aria-hidden- className={cn("mt-[0.32rem] h-2 w-2 shrink-0 rounded-full", color)}- />- <span className="min-w-0 flex-1 text-[12px] leading-relaxed text-muted-foreground">- {children}- </span>- </span>- );-}--function RailTitle({ children }: { children: React.ReactNode }) {- return (- <h4 className="text-[10.5px] font-semibold uppercase tracking-[0.14em] text-muted-foreground/80">- {children}- </h4>- );-}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.tsxdeleted file mode 100644index 06e4d16f22..0000000000--- a/jarvis/ui/web/frontend/src/components/local-models/AssistantPanel.test.tsx+++ /dev/null@@ -1,270 +0,0 @@-import { QueryClient, QueryClientProvider } from "@tanstack/react-query";-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", attachments: [], 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,- },- ],- };-}--/** The rail reads the roles and the server through React Query. */-function renderPanel(props: Record<string, unknown> = {}) {- const client = new QueryClient({- defaultOptions: { queries: { retry: false, gcTime: 0 } },- });- return render(- <QueryClientProvider client={client}>- <AssistantPanel- providerId="ollama"- serverLabel="Ollama"- request={null}- onOpenApiKeys={() => {}}- {...props}- />- </QueryClientProvider>,- );-}--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();- renderPanel({ request: { mode: "setup", token: 1 }, 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" }),- });- renderPanel();-- 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({});- renderPanel();- 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() });- renderPanel();-- await waitFor(() => expect(screen.getByTestId("setup-proposal")).toBeDefined());- // The turn names who wrote it — read from the turn, not from config.- expect(screen.getByTestId("assistant-turn-origin").textContent).toContain("\u00b7 m");- 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);- });- it("names the brain that answers and marks it as the cloud one", async () => {- stubFetch({- [`GET ${BASE}/session`]: () =>- reply({ session_id: null, provider: "gemini", model: "gemini-3-pro", ready: true, reason: "" }),- [`GET ${BASE}/health`]: () => reply({}, 404),- });- renderPanel();-- await waitFor(() =>- expect(screen.getByTestId("assistant-origin-model").textContent).toBe("gemini-3-pro"),- );- expect(screen.getByTestId("assistant-origin").textContent).toContain("Gemini");- // Ready: the explaining sentence, not a warning.- expect(screen.queryByTestId("assistant-origin-blocked")).toBeNull();- expect(screen.getByTestId("assistant-origin").textContent).toContain(- "local_models.assistant.origin_cloud",- );- // The same answer travels to a narrow window as one chip.- expect(screen.getByTestId("assistant-origin-chip").textContent).toContain("gemini-3-pro");- });-- it("says BEFORE the first click when no Tool Model can run the helper", async () => {- const why = "Pick a Tool Model with an API key first — the helper runs on it.";- stubFetch({- [`GET ${BASE}/session`]: () =>- reply({ session_id: null, provider: "gemini", model: "", ready: false, reason: why }),- [`GET ${BASE}/health`]: () => reply({}, 404),- });- const onOpenApiKeys = vi.fn();- renderPanel({ onOpenApiKeys });-- await waitFor(() =>- expect(screen.getByTestId("assistant-origin-blocked").textContent).toBe(why),- );- // No model of its own: the pair falls back to the provider's default.- expect(screen.getByTestId("assistant-origin-model").textContent).toBe(- "local_models.assistant.origin_default_model",- );- fireEvent.click(screen.getByTestId("assistant-origin-change"));- expect(onOpenApiKeys).toHaveBeenCalledTimes(1);- });-});diff --git a/jarvis/ui/web/frontend/src/components/local-models/AssistantPanel.tsx b/jarvis/ui/web/frontend/src/components/local-models/AssistantPanel.tsxdeleted file mode 100644index 677b83506d..0000000000--- a/jarvis/ui/web/frontend/src/components/local-models/AssistantPanel.tsx+++ /dev/null@@ -1,781 +0,0 @@-/**- * The Local models setup assistant — a plain chat that shows its work.- *- * 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- * streaming, approvals and cancel are the shared ones; only the store instance- * is this panel's own (`assistantStore.ts`).- *- * Three deliberate departures from the coding-agent chat:- *- * 1. **The conversation scrolls inside itself.** The panel fills the height it- * is given (`h-full`, never a `100vh` sum guessed from the chrome above it)- * with the composer pinned to its floor, so opening the helper never turns- * the section into a page thousands of pixels tall — and never stacks a- * page scrollbar on top of the conversation's own.- * 2. **Only the current run is shown.** Every click on a mode button starts a- * new run; the ones before collapse behind one "earlier messages" line- * instead of stacking five identical setups on top of each other.- * 3. **Steps read as sentences** (`AssistantSteps`), not as tool names — this- * reader wants to follow what is being done to their machine.- *- * The conversation keeps a reading measure; the width left over on a wide- * window goes to `AssistantContext`, which answers the question the prose- * cannot: the helper runs on a CLOUD Tool Model while every model it installs- * runs locally. Below `xl` the rail is gone and the header's origin chip says- * the same thing in one line.- *- * When a turn ends 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 own inline question.- *- * Honest states, never toasts: a 409 from `/run` means the Tool Model (or its- * Agents-tier fallback) is not usable and the sentence links to API Keys; a 404- * means the backend predates the assistant.- */-import { AlertTriangle, FlaskConical, History, Send, Sparkles, Square } from "lucide-react";-import { useCallback, useEffect, useMemo, useRef, useState } from "react";--import type { TextBlock, TimelineItem, TurnItem } from "@/components/agentchat/reduce";-import { SoftButton, StatusDot } from "@/components/extensions/primitives";-import { ProviderLogo } from "@/components/providers/ProviderLogo";-import { fill, useT } from "@/i18n";-import type { ApprovalDecision } from "@/lib/agentChatApi";-import { cn } from "@/lib/utils";--import {- AssistantApiError,- assistantTimestamp,- getAssistantHealth,- getAssistantSession,- runAssistant,- type AssistantHealth,- type AssistantMode,- type AssistantSessionResponse,-} from "./assistantApi";-import {- AssistantContext,- AssistantOriginChip,- healthTone,- providerDisplayName,-} from "./AssistantContext";-import { AssistantSteps } from "./AssistantSteps";-import {- matchesConfirmedStep,- proposalFromText,- proposalHash,- stripProposalBlocks,- type Proposal,- type ProposalStep,-} from "./assistantProposal";-import { renderInline } from "./assistantText";-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[] }>();--function turnText(turn: TurnItem): string {- return turn.blocks- .filter((b): b is TextBlock => b.kind === "text")- .map((b) => b.text)- .join("\n");-}--/** The text of the last finished assistant turn — where a proposal lives. */-function lastAssistantText(items: readonly TimelineItem[]): { text: string; turnId: string } | null {- for (let i = items.length - 1; i >= 0; i--) {- const item = items[i];- if (item.type !== "turn") continue;- // A turn still streaming has no plan yet; the previous finished one keeps- // its card instead of the card blinking out for the length of a follow-up.- if (item.status !== "done") continue;- return { text: turnText(item), turnId: item.id };- }- return null;-}--function isRunning(items: readonly TimelineItem[]): boolean {- const last = items[items.length - 1];- return Boolean(last && last.type === "turn" && last.status === "running");-}--/**- * Where the current run begins.- *- * Anchored on the turn id `/run` answered with, never on a count: the socket- * snapshot of an existing conversation can land AFTER the click, and an index- * captured before it would put the whole history inside "the current run" —- * which is exactly how five identical setups ended up stacked on one screen.- * The user message that started the turn belongs to the run, hence the step- * back. Without an id (the panel just opened), the last user message starts it.- */-function runStartIndex(items: readonly TimelineItem[], turnId: string | null): number {- if (turnId) {- const at = items.findIndex((it) => it.type === "turn" && it.id === turnId);- if (at > 0 && items[at - 1].type === "user") return at - 1;- if (at >= 0) return at;- }- for (let i = items.length - 1; i >= 0; i--) {- if (items[i].type === "user") return i;- }- return 0;-}--export function AssistantPanel({- providerId,- serverLabel,- request,- onOpenApiKeys,- onOpenServerLog,- providerLabel,- className,-}: {- 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 Server tab with the log open — one link for the reader who wants it raw. */- onOpenServerLog?: () => void;- /**- * Brain provider id -> display label, from the section's provider list. The- * panel does not fetch a catalog of its own for one word; without it the id- * is title-cased, which is honest if less pretty.- */- providerLabel?: (id: string) => string;- className?: string;-}) {- const t = useT();- 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);- /** The whole `/session` answer: the pair the helper runs on, and readiness. */- const [session, setSession] = useState<AssistantSessionResponse | null>(null);- const [starting, setStarting] = useState<AssistantMode | null>(null);- /** The 409 sentence: no usable Tool Model or Agents-tier fallback. */- 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);- /** The turn `/run` started; everything before it is "earlier". */- const [runTurnId, setRunTurnId] = useState<string | null>(null);- const [showEarlier, setShowEarlier] = useState(false);- const answered = useRef<Set<string>>(new Set());- const scroller = useRef<HTMLDivElement | null>(null);- /** Whether the reader is parked at the end — the only time we may scroll. */- const atBottom = useRef(true);-- const running = isRunning(items);- const start = runStartIndex(items, runTurnId);- const current = items.slice(Math.min(start, items.length));- const earlier = items.slice(0, Math.min(start, items.length));- const shown = showEarlier ? items : current;-- /**- * The `/session` record: the pair the helper runs on and whether it can run.- * Reading it is not optional bookkeeping — it is the only place the UI can- * learn WHICH brain answers, and it says so before the first click instead- * of leaving the reader to discover it as a 409.- */- const loadSession = useCallback(async (): Promise<AssistantSessionResponse | null> => {- try {- const s = await getAssistantSession(providerId);- setSession(s);- return s;- } catch (err) {- if (err instanceof AssistantApiError && err.status === 404) setBackendMissing(true);- return null;- }- }, [providerId]);-- // The one session per install: open it (and its socket) when the panel mounts.- useEffect(() => {- let cancelled = false;- void (async () => {- const s = await loadSession();- if (cancelled || !s?.session_id) return;- openSession(s.session_id);- })();- return () => {- cancelled = true;- };- }, [loadSession, 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]);-- // Follow the conversation while it writes, the way a chat does — but only- // for a reader who is actually at the end. Scrolling unconditionally yanks- // someone who scrolled up to re-read a step back down on the next token.- useEffect(() => {- const el = scroller.current;- if (el && atBottom.current) el.scrollTop = el.scrollHeight;- }, [items, shown.length]);-- const onScroll = useCallback(() => {- const el = scroller.current;- if (!el) return;- // A small slack: a sub-pixel layout or a half-scrolled wheel tick must- // still count as "at the end", or following stops for no visible reason.- atBottom.current = el.scrollHeight - el.scrollTop - el.clientHeight < 80;- }, []);-- const run = useCallback(- async (mode: AssistantMode) => {- setStarting(mode);- setBlocked(null);- setRunError(null);- setShowEarlier(false);- // A run the reader asked for is a run they want to watch start.- atBottom.current = true;- try {- const res = await runAssistant(providerId, mode);- // Everything before this turn becomes "earlier": a second setup run is- // a fresh start, not a fifth copy stacked under the fourth.- setRunTurnId(res.turn_id);- if (res.session_id !== activeSessionId) openSession(res.session_id);- } catch (err) {- if (err instanceof AssistantApiError && err.status === 409) {- setBlocked(err.message);- // The refusal and the rail must agree on why; re-read the record.- void loadSession();- } 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, loadSession],- );-- // 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]);-- // A finished run can have changed the tier (a fallback took over, a key was- // fixed mid-conversation). Re-read it then — and only then, so the mount's- // own read is not doubled.- const wasRunning = useRef(false);- useEffect(() => {- if (wasRunning.current && !running) void loadSession();- wasRunning.current = running;- }, [running, loadSession]);-- // The plan in the last finished turn of the current run, if any.- const proposal: { value: Proposal; turnId: string } | null = useMemo(() => {- const last = lastAssistantText(current);- if (!last) return null;- const value = proposalFromText(last.text);- return value ? { value, turnId: last.turnId } : null;- }, [current]);-- 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 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 needsFix = health?.status === "error" || health?.status === "needs_setup";- const brandName = useCallback(- (id: string) => providerDisplayName(id, providerLabel),- [providerLabel],- );-- // One line that says what the helper is doing right now.- const statusLine = running- ? t("local_models.assistant.status_working")- : starting- ? t("local_models.assistant.status_starting")- : proposal- ? t("local_models.assistant.status_plan_ready")- : items.length > 0- ? t("local_models.assistant.status_idle")- : t("local_models.assistant.status_empty");-- const busyNow = starting !== null || running;-- return (- <div- className={cn(- // A chat is a room, not a form: its own ground, a header and a- // composer pinned to the edges, and the conversation scrolling- // between them. The height is whatever the section hands down- // (`h-full`) — never a `100vh` minus a hand-measured chrome height,- // which stops being true the moment that chrome wraps and leaves two- // scrollbars stacked on each other.- "flex h-full min-h-0 flex-col overflow-hidden rounded-xl border border-border",- // Token colours only: `--card` and friends are HSL triplets, not- // colours, so a color-mix() on them is invalid CSS and the room would- // render with no ground at all. The conversation sits a shade off the- // page, the two bars a shade above it.- "bg-card/40",- className,- )}- data-testid="local-models-assistant"- >- {/* ── header ─────────────────────────────────────────────────────── */}- {/* Full width, unlike the conversation: a title band constrained to the- reading measure leaves its buttons floating in mid-screen with empty- bar on both sides, which reads as a broken layout rather than a calm- one. Only prose wants a measure. */}- <div className="shrink-0 border-b border-border/70 bg-card px-5 py-3">- <div className="flex w-full flex-wrap items-center justify-between gap-x-4 gap-y-2">- <div className="flex min-w-0 items-center gap-3">- <div className="min-w-0">- <h3 className="text-[14px] font-semibold leading-tight tracking-[-0.01em]">- {t("local_models.assistant.title")}- </h3>- <p- className="mt-0.5 text-[12.5px] text-muted-foreground"- data-testid="assistant-status"- >- {statusLine}- </p>- </div>- {/* Below xl there is no rail, so the answer moves here. */}- <div className="xl:hidden">- <AssistantOriginChip- session={session}- providerLabel={providerLabel}- onOpenApiKeys={onOpenApiKeys}- />- </div>- </div>- <div className="flex flex-wrap items-center gap-1.5">- <ChipButton primary onClick={() => void run("setup")} disabled={busyNow}>- <Sparkles className="h-3.5 w-3.5" />- {t("local_models.assistant.action_setup")}- </ChipButton>- <ChipButton onClick={() => void run("test")} disabled={busyNow}>- <FlaskConical className="h-3.5 w-3.5" />- {t("local_models.assistant.action_test")}- </ChipButton>- <ChipButton onClick={() => void run("diagnose")} disabled={busyNow}>- <AlertTriangle className="h-3.5 w-3.5" />- {t("local_models.assistant.action_diagnose")}- </ChipButton>- {running && (- <ChipButton onClick={() => void cancel()}>- <Square className="h-3.5 w-3.5" />- {t("local_models.assistant.cancel")}- </ChipButton>- )}- </div>- </div>- </div>-- {/* ── conversation + context ─────────────────────────────────────── */}- <div className="flex min-h-0 flex-1">- <div- ref={scroller}- onScroll={onScroll}- className="min-w-0 flex-1 overflow-y-auto"- data-testid="assistant-timeline"- >- <div className="mx-auto flex min-h-full w-full max-w-[48rem] flex-col px-5 py-6">- <div- className={cn(- // A short conversation rests on the composer instead of- // hanging from the ceiling with a screen of void beneath it.- // `mt-auto`, not `justify-end`: an auto margin collapses to- // zero once the content outgrows the box, so a long run can- // still be scrolled back to its own first line.- "flex flex-col gap-8",- items.length === 0 ? "my-auto" : "mt-auto",- )}- >- {/* The rail carries this above xl; here it would be a second copy. */}- {health && checkedAt && (- <p- className="flex flex-wrap items-center gap-3 text-[12.5px] xl:hidden"- data-testid="assistant-health"- >- <StatusDot- tone={healthTone(health)}- 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="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-xl border border-amber-500/40 bg-amber-500/10 px-4 py-3 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 && (- <div className="flex flex-1 flex-col items-center justify-center gap-5 py-12 text-center">- <span className="flex h-11 w-11 items-center justify-center rounded-full bg-primary/12 text-primary">- <Sparkles className="h-5 w-5" />- </span>- <p className="max-w-[38ch] text-[15px] leading-relaxed text-muted-foreground">- {t("local_models.assistant.empty")}- </p>- <div className="flex flex-wrap justify-center gap-2">- {["ask_1", "ask_2", "ask_3"].map((key) => {- const text = t(`local_models.assistant.${key}`);- return (- <button- key={key}- type="button"- disabled={!activeSessionId || busyNow}- onClick={() => void send(text)}- className={cn(- "rounded-full border border-border bg-card px-3.5 py-2 text-[13px] text-muted-foreground",- "transition-colors hover:border-primary/50 hover:text-foreground",- "disabled:cursor-not-allowed disabled:opacity-50",- "focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring",- )}- >- {text}- </button>- );- })}- </div>- </div>- )}-- {earlier.length > 0 && (- <button- type="button"- onClick={() => setShowEarlier((v) => !v)}- className={cn(- "mx-auto inline-flex items-center gap-1.5 rounded-full border border-border bg-card/60 px-3 py-1",- "text-[11.5px] text-muted-foreground hover:text-foreground",- "focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring",- )}- data-testid="assistant-earlier"- >- <History className="h-3 w-3" />- {showEarlier- ? t("local_models.assistant.earlier_hide")- : fill(t("local_models.assistant.earlier_show"), { n: String(earlier.length) })}- </button>- )}-- {shown.map((item) => {- if (item.type === "user") {- return (- <div key={item.id} className="flex justify-end">- <p- className="max-w-[85%] rounded-3xl rounded-br-lg bg-muted px-4 py-2.5 text-[14.5px] leading-relaxed text-foreground"- data-testid="assistant-you"- >- {item.text}- </p>- </div>- );- }- if (item.type === "error") {- return (- <p key={item.id} className="text-sm text-destructive">- {item.text}- </p>- );- }- const answer = stripProposalBlocks(turnText(item));- const live = item.status === "running";- return (- // The assistant wears no bubble: its words are the page, the way- // a reader expects an answer to be. Only the mark and the left- // gutter say who is speaking.- <div key={item.id} className="flex gap-3">- <span- aria-hidden="true"- className={cn(- "mt-0.5 flex h-7 w-7 shrink-0 items-center justify-center rounded-full",- live- ? "animate-pulse bg-primary/15 text-primary"- : "bg-muted text-muted-foreground",- )}- >- <Sparkles className="h-3.5 w-3.5" />- </span>- <div className="flex min-w-0 flex-1 flex-col gap-3">- {/* Who wrote this turn — read from the turn itself, not from- the configuration, so a fallback that took over is named- instead of the pick that failed. */}- {item.provider && (- <span- className="flex items-center gap-1.5 text-[11px] text-muted-foreground/70"- data-testid="assistant-turn-origin"- >- <ProviderLogo- providerId={item.provider}- label={brandName(item.provider)}- size="sm"- />- <span className="truncate">- {brandName(item.provider)}- {item.model ? ` · ${item.model}` : ""}- </span>- </span>- )}- <AssistantSteps blocks={item.blocks} live={live} onDecide={onDecide} />- {answer && (- <div- className="flex flex-col gap-3 text-[15px] leading-[1.7] text-foreground"- data-testid="assistant-answer"- >- {answer.split(/\n{2,}/).map((para, k) => (- <p key={k} className="whitespace-pre-wrap">- {renderInline(para)}- </p>- ))}- </div>- )}- {item.status === "error" && item.error && (- <p className="text-sm text-destructive">{item.error}</p>- )}- {proposal?.turnId === item.id && (- <>- <SetupProposalCard- 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}- />- )}- </>- )}- </div>- </div>- );- })}- </div>- </div>- </div>-- <AssistantContext- providerId={providerId}- serverLabel={serverLabel}- session={session}- health={health}- onOpenApiKeys={onOpenApiKeys}- onDiagnose={() => void run("diagnose")}- providerLabel={providerLabel}- />- </div>-- {/* ── composer ───────────────────────────────────────────────────── */}- <div className="shrink-0 border-t border-border/70 bg-card px-5 py-3">- <div className="mx-auto w-full max-w-[48rem]">- <form- className={cn(- "flex items-end gap-2 rounded-2xl border border-border bg-background px-2.5 py-2 shadow-sm",- "transition-colors focus-within:border-primary/60",- !activeSessionId && "opacity-60",- )}- 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={1}- 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(- "max-h-40 min-h-[1.75rem] flex-1 resize-none bg-transparent px-1.5 py-1 text-[14.5px] leading-relaxed text-foreground",- "placeholder:text-muted-foreground focus:outline-none disabled:cursor-not-allowed",- )}- />- <button- type="submit"- aria-label={t("local_models.assistant.send")}- disabled={!activeSessionId || !draft.trim() || busy || running}- className={cn(- "flex h-8 w-8 shrink-0 items-center justify-center rounded-full bg-primary text-primary-foreground",- "transition-opacity hover:opacity-90 disabled:opacity-30",- "focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring",- )}- >- <Send className="h-3.5 w-3.5" />- </button>- </form>- <div className="mt-1.5 flex items-center justify-between gap-3 px-1">- <span className="text-[11px] text-muted-foreground/70">- {t("local_models.assistant.composer_hint")}- </span>- {onOpenServerLog && (- <button- type="button"- onClick={onOpenServerLog}- className="text-[11px] text-muted-foreground/70 underline-offset-4 hover:text-foreground hover:underline"- data-testid="assistant-open-server-log"- >- {t("local_models.assistant.open_server_log")}- </button>- )}- </div>- </div>- </div>- </div>- );-}--/** A small header action: the three runs and Stop, sized for a title bar. */-function ChipButton({- children,- onClick,- disabled,- primary,-}: {- children: React.ReactNode;- onClick: () => void;- disabled?: boolean;- primary?: boolean;-}) {- return (- <button- type="button"- onClick={onClick}- disabled={disabled}- className={cn(- "inline-flex items-center gap-1.5 rounded-full px-3 py-1.5 text-[12.5px] font-medium",- "transition-colors disabled:cursor-not-allowed disabled:opacity-45",- "focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring",- primary- ? "bg-primary text-primary-foreground hover:opacity-90"- : "border border-border text-muted-foreground hover:text-foreground",- )}- >- {children}- </button>- );-}diff --git a/jarvis/ui/web/frontend/src/components/local-models/AssistantSteps.tsx b/jarvis/ui/web/frontend/src/components/local-models/AssistantSteps.tsxdeleted file mode 100644index 0d4e9b7d65..0000000000--- a/jarvis/ui/web/frontend/src/components/local-models/AssistantSteps.tsx+++ /dev/null@@ -1,285 +0,0 @@-/**- * The assistant's work, readable — and out of the way once it is done.- *- * The shared `AgentTimeline` is built for a coding agent: it shows a tool call- * as its raw name (`lm_inventory`) and a JSON body, which is the right answer- * when the reader writes code and the wrong one here — this panel is opened by- * someone who wants to know what the helper is doing to their machine.- *- * So every step gets one plain sentence ("Read the installed models"), a mark- * that carries its state, and its duration. While the turn runs the list is- * open, because watching it is the point; once the turn is finished it folds- * into one line ("Checked 5 things · 2.6s") so the answer, not the machinery,- * is what the finished conversation reads as. The raw call and result stay one- * click away for the reader who does want them.- *- * A question the runner asks that no confirmed plan covers is the one step- * that can act: it renders its two buttons inline and keeps the group open.- */-import { useEffect, useState } from "react";-import { Check, ChevronRight, Loader2, X } from "lucide-react";--import type { ReasoningBlock, ToolBlock, TurnBlock } from "@/components/agentchat/reduce";-import { fill, useT } from "@/i18n";-import type { ApprovalDecision } from "@/lib/agentChatApi";-import { cn } from "@/lib/utils";--/** Tool name → i18n key of its sentence. Unknown tools fall back to the name. */-const STEP_KEYS: Record<string, string> = {- lm_hardware: "hardware",- lm_server_status: "server_status",- lm_inventory: "inventory",- lm_roles: "roles",- lm_recommendations: "recommendations",- lm_catalog_search: "catalog_search",- lm_catalog_tags: "catalog_tags",- lm_hf_search: "hf_search",- lm_benchmarks: "benchmarks",- lm_pull_status: "pull_status",- lm_server_log: "server_log",- lm_env_guide: "env_guide",- lm_suggested_options: "suggested_options",- lm_test_plan: "test_plan",- lm_install_ollama: "install_ollama",- lm_start_server: "start_server",- lm_stop_server: "stop_server",- lm_pull: "pull",- lm_set_role: "set_role",- lm_set_model_options: "set_options",- lm_unload: "unload",- lm_install_voice_server: "install_voice",- lm_apply_voice_stack: "apply_voice",- search_web: "search_web",-};--type Tone = "run" | "done" | "fail" | "ask";--function argOf(input: unknown, key: string): string {- if (!input || typeof input !== "object") return "";- const value = (input as Record<string, unknown>)[key];- return typeof value === "string" ? value : "";-}--/** Seconds with one decimal, so a fast step does not read as "0". */-function seconds(ms: number | null): string {- if (ms === null) return "";- return `${(ms / 1000).toFixed(1)}s`;-}--function toneOf(block: TurnBlock): Tone {- if (block.kind === "reasoning") return block.live ? "run" : "done";- if (block.kind !== "tool") return "done";- if (block.approval && !block.approval.decision) return "ask";- if (block.isError) return "fail";- return block.output === null ? "run" : "done";-}--function Mark({ tone }: { tone: Tone }) {- if (tone === "run") return <Loader2 className="h-3 w-3 animate-spin text-primary" />;- if (tone === "fail") return <X className="h-3 w-3 text-destructive" />;- if (tone === "ask")- return <span className="h-1.5 w-1.5 rounded-full bg-amber-500 dark:bg-amber-400" />;- return <Check className="h-3 w-3 text-emerald-600 dark:text-emerald-400" />;-}--function StepRow({- tone,- label,- meta,- detail,- children,-}: {- tone: Tone;- label: string;- meta?: string;- detail?: string;- children?: React.ReactNode;-}) {- const t = useT();- const [open, setOpen] = useState(false);- const hasDetail = Boolean(detail && detail.trim());- return (- <li className="group/step" data-testid="assistant-step" data-tone={tone}>- <div className="flex items-baseline gap-2">- <span className="flex h-4 w-4 shrink-0 translate-y-[2px] items-center justify-center">- <Mark tone={tone} />- </span>- <span- className={cn(- "text-[13px] leading-5",- tone === "fail" ? "text-destructive" : "text-foreground/90",- )}- >- {label}- </span>- {meta && (- <span className="font-mono text-[10.5px] tabular-nums text-muted-foreground/70">- {meta}- </span>- )}- {hasDetail && (- <button- type="button"- onClick={() => setOpen((v) => !v)}- className={cn(- "ml-auto shrink-0 rounded px-1 text-[10.5px] uppercase tracking-[0.08em] text-muted-foreground/0",- "transition-colors group-hover/step:text-muted-foreground hover:!text-foreground",- "focus-visible:text-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring",- open && "!text-muted-foreground",- )}- >- {open ? t("local_models.assistant.steps.hide") : t("local_models.assistant.steps.show")}- </button>- )}- </div>- {open && hasDetail && (- <pre className="ml-6 mt-1.5 max-h-56 overflow-auto rounded-md border border-border/70 bg-muted/40 p-2.5 font-mono text-[11px] leading-relaxed text-muted-foreground">- {detail}- </pre>- )}- {children}- </li>- );-}--function ToolStep({- block,- onDecide,-}: {- block: ToolBlock;- onDecide?: (approvalId: string, decision: ApprovalDecision) => void;-}) {- const t = useT();- const key = STEP_KEYS[block.name];- const label = key- ? fill(t(`local_models.assistant.steps.${key}`), {- model: argOf(block.input, "model") || argOf(block.input, "name"),- role: argOf(block.input, "role"),- query: argOf(block.input, "q") || argOf(block.input, "query"),- })- .replace(/\s{2,}/g, " ")- .trim()- : block.name;-- const tone = toneOf(block);- const detail = [- block.input && Object.keys(block.input as object).length- ? JSON.stringify(block.input, null, 1)- : "",- block.output ?? "",- ]- .filter(Boolean)- .join("\n\n");-- return (- <StepRow tone={tone} label={label} meta={seconds(block.durationMs)} detail={detail}>- {tone === "ask" && block.approval && onDecide && (- <div className="ml-6 mt-2 flex flex-wrap items-center gap-3 rounded-lg border border-amber-500/40 bg-amber-500/[0.07] px-3 py-2">- <span className="text-[13px] text-foreground">{block.approval.summary}</span>- <div className="ml-auto flex gap-1.5">- <button- type="button"- onClick={() => onDecide(block.approval!.approvalId, "allow")}- className="rounded-md bg-primary px-2.5 py-1 text-[12px] font-medium text-primary-foreground hover:opacity-90 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring"- >- {t("local_models.assistant.steps.allow")}- </button>- <button- type="button"- onClick={() => onDecide(block.approval!.approvalId, "deny")}- className="rounded-md border border-border px-2.5 py-1 text-[12px] hover:bg-muted focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring"- >- {t("local_models.assistant.steps.deny")}- </button>- </div>- </div>- )}- </StepRow>- );-}--function ThinkingStep({ block }: { block: ReasoningBlock }) {- const t = useT();- const label = block.live- ? t("local_models.assistant.steps.thinking_live")- : fill(t("local_models.assistant.steps.thinking"), { s: seconds(block.durationMs) || "—" });- return <StepRow tone={block.live ? "run" : "done"} label={label} detail={block.text} />;-}--/**- * The work of one turn: open while it happens, one summary line once it is- * done. Text blocks are NOT rendered here — the answer is the panel's own- * prose, so the steps stay a list of work and the words stay words.- */-export function AssistantSteps({- blocks,- live,- onDecide,-}: {- blocks: readonly TurnBlock[];- /** The turn is still running: the group stays open and cannot be folded. */- live?: boolean;- onDecide?: (approvalId: string, decision: ApprovalDecision) => void;-}) {- const t = useT();- const steps = blocks.filter((b) => b.kind !== "text");- const asking = steps.some((b) => toneOf(b) === "ask");- const failed = steps.some((b) => toneOf(b) === "fail");- const [open, setOpen] = useState(true);-- // Fold when the turn ends — unless something still wants the reader's eye.- useEffect(() => {- if (!live && !asking && !failed) setOpen(false);- if (live || asking || failed) setOpen(true);- }, [live, asking, failed]);-- if (steps.length === 0) return null;-- const total = steps.reduce((ms, b) => ms + (b.durationMs ?? 0), 0);- const pinned = Boolean(live || asking || failed);- const summary = fill(t("local_models.assistant.steps.summary"), {- n: String(steps.length),- s: seconds(total) || "—",- });-- return (- <div data-testid="assistant-steps" data-open={open ? "yes" : "no"}>- {/* Collapsed, this is one quiet line the eye can skip — the answer is- what the finished conversation is for. Open, the rail carries the- work so it reads as a sequence rather than a paragraph of nouns. */}- <button- type="button"- onClick={() => !pinned && setOpen((v) => !v)}- aria-expanded={open}- disabled={pinned}- className={cn(- "-mx-1 inline-flex items-center gap-1.5 rounded-md px-1 py-0.5",- "text-[12.5px] text-muted-foreground",- "focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring",- !pinned && "hover:text-foreground",- )}- >- <ChevronRight- className={cn(- "h-3.5 w-3.5 shrink-0 transition-transform",- open && "rotate-90",- pinned && "hidden",- )}- />- {live && <Loader2 className="h-3 w-3 shrink-0 animate-spin text-primary" />}- <span>{live ? t("local_models.assistant.steps.working") : summary}</span>- </button>- {open && (- <ul className="mt-2 flex flex-col gap-2 border-l border-border/70 pl-3.5">- {steps.map((block) =>- block.kind === "tool" ? (- <ToolStep key={block.callId} block={block} onDecide={onDecide} />- ) : (- <ThinkingStep key={block.id} block={block as ReasoningBlock} />- ),- )}- </ul>- )}- </div>- );-}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.tsxdeleted file mode 100644index 1d56c507ee..0000000000--- a/jarvis/ui/web/frontend/src/components/local-models/SetupProposalCard.test.tsx+++ /dev/null@@ -1,90 +0,0 @@-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.tsxdeleted file mode 100644index 306fa10961..0000000000--- a/jarvis/ui/web/frontend/src/components/local-models/SetupProposalCard.tsx+++ /dev/null@@ -1,246 +0,0 @@-/**- * 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.tsdeleted file mode 100644index c69a631f51..0000000000--- a/jarvis/ui/web/frontend/src/components/local-models/assistantApi.ts+++ /dev/null@@ -1,111 +0,0 @@-/**- * 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.tsdeleted file mode 100644index 012c9c0877..0000000000--- a/jarvis/ui/web/frontend/src/components/local-models/assistantProposal.test.ts+++ /dev/null@@ -1,127 +0,0 @@-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);- });-});---describe("stripProposalBlocks", () => {- it("removes the fenced plan and keeps the words around it", async () => {- const { stripProposalBlocks } = await import("./assistantProposal");- const text = 'Here is the plan:\n\n```jarvis-proposal\n{"version":1,"steps":[]}\n```\n\nGeorge';- expect(stripProposalBlocks(text)).toBe("Here is the plan:\n\nGeorge");- expect(stripProposalBlocks("no plan here")).toBe("no plan here");- expect(stripProposalBlocks('cut ```jarvis-proposal\n{"ver')).toBe("cut");- });-});diff --git a/jarvis/ui/web/frontend/src/components/local-models/assistantProposal.ts b/jarvis/ui/web/frontend/src/components/local-models/assistantProposal.tsdeleted file mode 100644index 24a7b66446..0000000000--- a/jarvis/ui/web/frontend/src/components/local-models/assistantProposal.ts+++ /dev/null@@ -1,278 +0,0 @@-/**- * 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;- }-}--/**- * `text` without its ```jarvis-proposal block(s): the plan is shown as the- * checklist card, so the raw JSON has no business in the chat bubble. A block- * with no closing fence (a cut-off stream) is stripped to the end of the text.- */-export function stripProposalBlocks(text: string): string {- const re = /```jarvis-proposal[^\n]*\n[\s\S]*?(?:```|$)/g;- return text.replace(re, "").replace(/\n{3,}/g, "\n\n").trim();-}diff --git a/jarvis/ui/web/frontend/src/components/local-models/assistantStore.ts b/jarvis/ui/web/frontend/src/components/local-models/assistantStore.tsdeleted file mode 100644index 97ea34e375..0000000000--- a/jarvis/ui/web/frontend/src/components/local-models/assistantStore.ts+++ /dev/null@@ -1,10 +0,0 @@-/**- * 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/components/local-models/assistantText.test.ts b/jarvis/ui/web/frontend/src/components/local-models/assistantText.test.tsdeleted file mode 100644index bc30c6f4e0..0000000000--- a/jarvis/ui/web/frontend/src/components/local-models/assistantText.test.ts+++ /dev/null@@ -1,28 +0,0 @@-/** The inline formatting a chat answer actually uses. */-import { describe, expect, it } from "vitest";--import { renderInline } from "./assistantText";--function textOf(nodes: unknown[]): string {- return nodes- .map((n) =>- typeof n === "string"- ? n- : ((n as { props?: { children?: string } }).props?.children ?? ""),- )- .join("");-}--describe("renderInline", () => {- it("turns the model's emphasis into elements, never printed asterisks", () => {- const nodes = renderInline("I propose **Gemma 4 12B** and ++Ornith 9B++ today.");- expect(textOf(nodes)).toBe("I propose Gemma 4 12B and Ornith 9B today.");- expect(nodes.filter((n) => typeof n !== "string")).toHaveLength(2);- });-- it("keeps inline code as code and leaves plain prose alone", () => {- const code = renderInline("Run `ollama pull qwen3.5` first.");- expect(textOf(code)).toBe("Run ollama pull qwen3.5 first.");- expect(renderInline("nothing to format")).toEqual(["nothing to format"]);- });-});diff --git a/jarvis/ui/web/frontend/src/components/local-models/assistantText.tsx b/jarvis/ui/web/frontend/src/components/local-models/assistantText.tsxdeleted file mode 100644index 6e7a8afbb9..0000000000--- a/jarvis/ui/web/frontend/src/components/local-models/assistantText.tsx+++ /dev/null@@ -1,52 +0,0 @@-/**- * The little bit of formatting a chat answer actually uses.- *- * A model writes `**bold**` and `` `code` `` in prose whatever you tell it, and- * a panel that prints the asterisks reads as broken. This is deliberately NOT a- * markdown renderer: the assistant's answer is a paragraph or three of prose,- * so bold, italic and inline code are the whole vocabulary. Anything else- * (headings, tables, links) is left as written rather than half-supported.- *- * `++text++` is folded into bold too — Gemini's own emphasis marker, seen in- * every setup answer on 2026-08-25 and meaningless to a reader.- */-import type { ReactNode } from "react";--/** `**a**`, `++a++`, `` `a` `` and `*a*` — in that order of precedence. */-const TOKEN = /(\*\*[^*]+\*\*|\+\+[^+]+\+\+|`[^`]+`|\*[^*\n]+\*)/g;--export function renderInline(text: string): ReactNode[] {- const out: ReactNode[] = [];- let last = 0;- let key = 0;- for (const match of text.matchAll(TOKEN)) {- const at = match.index ?? 0;- if (at > last) out.push(text.slice(last, at));- const token = match[0];- if (token.startsWith("**") || token.startsWith("++")) {- out.push(- <strong key={key++} className="font-semibold">- {token.slice(2, -2)}- </strong>,- );- } else if (token.startsWith("`")) {- out.push(- <code- key={key++}- className="rounded bg-muted px-1 py-0.5 font-mono text-[12.5px] text-foreground"- >- {token.slice(1, -1)}- </code>,- );- } else {- out.push(- <em key={key++} className="italic">- {token.slice(1, -1)}- </em>,- );- }- last = at + token.length;- }- if (last < text.length) out.push(text.slice(last));- return out;-}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 a71f9901ff..26a1573a59 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,7 +29,6 @@ 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"))@@ -37,7 +36,6 @@ const sources = (dir: string) =>const SOURCE_FILES = [join(SRC, "views", "LocalModelsView.tsx"),...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 473d838372..86fb5b8383 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@@ -199,10 +199,6 @@"actions_label": "Nächste Schritte","action_browse": "Modelle durchsuchen","action_browse_hint": "Einen Download aus dem Katalog wählen.",- "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": "Den Assistenten fragen, was nicht stimmt.","disk_models": "{count} Modelle","disk_model_one": "1 Modell","gpu_in_use": "{gb} belegt",@@ -381,96 +377,6 @@"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.",- "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": "Fang mit „Hilf mir einzurichten“ an oder stell 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",- "title": "Einrichtungshilfe",- "status_empty": "Bereit. Wähle, was sie tun soll.",- "status_starting": "Startet…",- "status_working": "Arbeitet — jeder Schritt steht unten.",- "status_plan_ready": "Der Plan steht. Sieh ihn dir an und bestätige.",- "status_idle": "Fertig. Stell eine Frage oder starte einen neuen Lauf.",- "earlier_show": "{n} frühere Nachrichten zeigen",- "earlier_hide": "Frühere Nachrichten ausblenden",- "steps": {- "show": "Details",- "hide": "ausblenden",- "allow": "Erlauben",- "deny": "Überspringen",- "thinking": "Hat nachgedacht · {s}",- "thinking_live": "Denkt nach…",- "hardware": "Hat deine Hardware angesehen",- "server_status": "Hat den lokalen Server geprüft",- "inventory": "Hat die installierten Modelle gelesen",- "roles": "Hat gelesen, welches Modell welche Aufgabe hat",- "recommendations": "Hat die Empfehlungen auf diesen Rechner abgestimmt",- "catalog_search": "Hat den Katalog nach {query} durchsucht",- "catalog_tags": "Hat die Versionen von {model} aufgelistet",- "hf_search": "Hat Hugging Face nach {query} durchsucht",- "benchmarks": "Hat nachgesehen, wie gut diese Modelle abschneiden",- "pull_status": "Hat den Download von {model} geprüft",- "server_log": "Hat das Server-Protokoll gelesen",- "env_guide": "Hat die Umgebungsanleitung gelesen",- "suggested_options": "Hat die Einstellungen für {model} berechnet",- "test_plan": "Hat jede Rolle komplett getestet",- "install_ollama": "Hat den lokalen Server installiert",- "start_server": "Hat den lokalen Server gestartet",- "stop_server": "Hat den lokalen Server gestoppt",- "pull": "Hat {model} heruntergeladen",- "set_role": "Hat {model} für {role} gesetzt",- "set_options": "Hat die Einstellungen für {model} gespeichert",- "unload": "Hat {model} aus dem Speicher entladen",- "install_voice": "Hat den Sprachserver installiert",- "apply_voice": "Hat den Sprach-Stack eingerichtet und getestet",- "search_web": "Hat im Web nach {query} gesucht",- "summary": "{n} Dinge geprüft · {s}",- "working": "Arbeitet…"- },- "ask_1": "Welches Modell soll meine Chats beantworten?",- "ask_2": "Schafft meine Grafikkarte ein 27B-Modell?",- "ask_3": "Speicherplatz freimachen",- "composer_hint": "Enter sendet · Umschalt+Enter für eine neue Zeile",- "origin_title": "Antwortet gerade",- "origin_cloud": "Die Hilfe selbst läuft auf deinem Tool Model in der Cloud und wird über dessen Schlüssel abgerechnet. Die Modelle darunter laufen auf deinem Rechner.",- "origin_change": "In den API-Keys ändern",- "origin_default_model": "Standardmodell des Anbieters",- "origin_unset": "Es ist noch kein Tool Model gewählt.",- "machine_title": "Auf diesem Rechner",- "machine_unset": "nicht gesetzt",- "machine_missing": "nicht installiert",- "machine_server_running": "{server} läuft",- "machine_server_stopped": "{server} läuft nicht",- "machine_loading": "Rollen werden gelesen…"- },- "tab_assistant": "Einrichtungshilfe"+ "tune_missing": "Dieses Modell ist nicht mehr installiert, es gibt also nichts einzustellen."}}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 b2d25e6013..ec54917303 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@@ -199,10 +199,6 @@"actions_label": "Next steps","action_browse": "Browse models","action_browse_hint": "Pick a download from the catalogue.",- "action_setup": "Help me set up",- "action_setup_hint": "A guided setup for this machine.",- "action_broken": "Something is not working",- "action_broken_hint": "Ask the assistant what is wrong.","disk_models": "{count} models","disk_model_one": "1 model","gpu_in_use": "{gb} in use",@@ -381,96 +377,6 @@"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.",- "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": "Start with “Help me set up”, 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",- "title": "Setup helper",- "status_empty": "Ready. Pick what you want it to do.",- "status_starting": "Starting…",- "status_working": "Working — every step it takes is listed below.",- "status_plan_ready": "The plan is ready. Look it over, then confirm.",- "status_idle": "Done for now. Ask a question or start another run.",- "earlier_show": "Show {n} earlier messages",- "earlier_hide": "Hide earlier messages",- "steps": {- "show": "details",- "hide": "hide",- "allow": "Allow",- "deny": "Skip",- "thinking": "Thought it through · {s}",- "thinking_live": "Thinking…",- "hardware": "Looked at your hardware",- "server_status": "Checked the local server",- "inventory": "Read the installed models",- "roles": "Read which model does which job",- "recommendations": "Matched the shortlist to this machine",- "catalog_search": "Searched the catalogue for {query}",- "catalog_tags": "Listed the versions of {model}",- "hf_search": "Searched Hugging Face for {query}",- "benchmarks": "Looked up how these models score",- "pull_status": "Checked the download of {model}",- "server_log": "Read the server log",- "env_guide": "Read the environment guide",- "suggested_options": "Worked out the settings for {model}",- "test_plan": "Tested every role end to end",- "install_ollama": "Installed the local server",- "start_server": "Started the local server",- "stop_server": "Stopped the local server",- "pull": "Downloaded {model}",- "set_role": "Set {model} for {role}",- "set_options": "Saved the settings for {model}",- "unload": "Unloaded {model} from memory",- "install_voice": "Installed the voice server",- "apply_voice": "Set up and tested the voice stack",- "search_web": "Searched the web for {query}",- "summary": "Checked {n} things · {s}",- "working": "Working…"- },- "ask_1": "Which model should answer my chats?",- "ask_2": "Can my graphics card run a 27B model?",- "ask_3": "Free up some disk space",- "composer_hint": "Enter sends · Shift+Enter for a new line",- "origin_title": "Answering now",- "origin_cloud": "The helper itself runs on your Tool Model in the cloud, billed through that key. The models below run on your machine.",- "origin_change": "Change in API Keys",- "origin_default_model": "the provider’s default model",- "origin_unset": "No Tool Model is picked yet.",- "machine_title": "On this machine",- "machine_unset": "not set",- "machine_missing": "not installed",- "machine_server_running": "{server} is running",- "machine_server_stopped": "{server} is not running",- "machine_loading": "Reading the roles…"- },- "tab_assistant": "Setup helper"+ "tune_missing": "That model is no longer installed, so there is nothing to tune."}}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 0bb9cda2d3..d6ad82c5d9 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@@ -199,10 +199,6 @@"actions_label": "Siguientes pasos","action_browse": "Explorar modelos","action_browse_hint": "Elige una descarga del catálogo.",- "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": "Pregunta al asistente qué falla.","disk_models": "{count} modelos","disk_model_one": "1 modelo","gpu_in_use": "{gb} en uso",@@ -381,96 +377,6 @@"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.",- "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": "Empieza con «Ayúdame a configurar» o 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",- "title": "Asistente de configuración",- "status_empty": "Listo. Elige qué debe hacer.",- "status_starting": "Iniciando…",- "status_working": "Trabajando: cada paso aparece abajo.",- "status_plan_ready": "El plan está listo. Revísalo y confirma.",- "status_idle": "Terminado. Haz una pregunta o inicia otra ejecución.",- "earlier_show": "Mostrar {n} mensajes anteriores",- "earlier_hide": "Ocultar mensajes anteriores",- "steps": {- "show": "detalles",- "hide": "ocultar",- "allow": "Permitir",- "deny": "Omitir",- "thinking": "Lo pensó · {s}",- "thinking_live": "Pensando…",- "hardware": "Revisó tu hardware",- "server_status": "Comprobó el servidor local",- "inventory": "Leyó los modelos instalados",- "roles": "Leyó qué modelo hace cada tarea",- "recommendations": "Ajustó las recomendaciones a esta máquina",- "catalog_search": "Buscó {query} en el catálogo",- "catalog_tags": "Listó las versiones de {model}",- "hf_search": "Buscó {query} en Hugging Face",- "benchmarks": "Consultó qué puntuación tienen estos modelos",- "pull_status": "Comprobó la descarga de {model}",- "server_log": "Leyó el registro del servidor",- "env_guide": "Leyó la guía de entorno",- "suggested_options": "Calculó los ajustes para {model}",- "test_plan": "Probó cada función de principio a fin",- "install_ollama": "Instaló el servidor local",- "start_server": "Inició el servidor local",- "stop_server": "Detuvo el servidor local",- "pull": "Descargó {model}",- "set_role": "Asignó {model} a {role}",- "set_options": "Guardó los ajustes de {model}",- "unload": "Descargó {model} de la memoria",- "install_voice": "Instaló el servidor de voz",- "apply_voice": "Configuró y probó la pila de voz",- "search_web": "Buscó {query} en la web",- "summary": "{n} cosas comprobadas · {s}",- "working": "Trabajando…"- },- "ask_1": "¿Qué modelo debe responder mis chats?",- "ask_2": "¿Mi tarjeta gráfica puede con un modelo de 27B?",- "ask_3": "Liberar espacio en disco",- "composer_hint": "Enter envía · Mayús+Enter para una línea nueva",- "origin_title": "Responde ahora",- "origin_cloud": "El asistente funciona con tu Tool Model en la nube y se factura con esa clave. Los modelos de abajo se ejecutan en tu equipo.",- "origin_change": "Cambiar en API Keys",- "origin_default_model": "modelo predeterminado del proveedor",- "origin_unset": "Todavía no hay un Tool Model elegido.",- "machine_title": "En este equipo",- "machine_unset": "sin definir",- "machine_missing": "no instalado",- "machine_server_running": "{server} está en marcha",- "machine_server_stopped": "{server} no está en marcha",- "machine_loading": "Leyendo los roles…"- },- "tab_assistant": "Asistente de configuración"+ "tune_missing": "Ese modelo ya no está instalado, así que no hay nada que ajustar."}}diff --git a/jarvis/ui/web/frontend/src/views/LocalModelsView.test.tsx b/jarvis/ui/web/frontend/src/views/LocalModelsView.test.tsxindex 05ea3d84e3..bcfbdc64fd 100644--- a/jarvis/ui/web/frontend/src/views/LocalModelsView.test.tsx+++ b/jarvis/ui/web/frontend/src/views/LocalModelsView.test.tsx@@ -36,17 +36,11 @@ vi.mock("@/views/local-models/OverviewPanel", () => ({onTune,onOpenApiKeys,onBrowse,- onOpenAssistant,- onReportProblem,- assistantSlot,}: {providerId: string;onTune?: (model: string) => void;onOpenApiKeys?: () => void;onBrowse?: () => void;- onOpenAssistant?: () => void;- onReportProblem?: () => void;- assistantSlot?: React.ReactNode;}) => (<div data-testid="overview-panel" data-provider={providerId}><button type="button" onClick={() => onTune?.("qwen3.5:4b")}>@@ -58,13 +52,6 @@ vi.mock("@/views/local-models/OverviewPanel", () => ({<button type="button" onClick={() => onBrowse?.()}>browse</button>- <button type="button" onClick={() => onOpenAssistant?.()}>- assistant- </button>- <button type="button" onClick={() => onReportProblem?.()}>- broken- </button>- {assistantSlot}</div>),}));@@ -78,12 +65,7 @@ vi.mock("@/views/local-models/HuggingFacePanel", () => ({HuggingFacePanel: () => <div data-testid="huggingface-panel" />,}));vi.mock("@/views/local-models/ServerPanel", () => ({- ServerPanel: ({ initialLogOpen }: { initialLogOpen?: boolean }) => (- <div- data-testid="server-panel"- data-log-open={initialLogOpen ? "yes" : "no"}- />- ),+ ServerPanel: () => <div data-testid="server-panel" />,}));vi.mock("@/views/local-models/TuneSheet", () => ({TuneSheet: ({@@ -100,25 +82,6 @@ vi.mock("@/views/local-models/TuneSheet", () => ({</div>),}));-vi.mock("@/components/local-models/AssistantPanel", () => ({- AssistantPanel: ({- request,- onOpenServerLog,- }: {- request: { mode: string; token: number } | null;- onOpenServerLog?: () => void;- }) => (- <div- data-testid="local-models-assistant"- data-mode={request?.mode ?? ""}- data-token={request?.token ?? 0}- >- <button type="button" onClick={onOpenServerLog}>- server log- </button>- </div>- ),-}));vi.mock("@/hooks/useLocalModels", () => ({useInventory: () => ({isLoading: false,@@ -277,72 +240,10 @@ describe("LocalModelsView", () => {expect(screen.getByText("local_models.no_provider")).toBeDefined();});- it("the helper is an area of its own, and the rail stays reachable from it", () => {+ it("'Browse models' on the overview opens the catalogue tab", () => {render(<LocalModelsView />);-- // "Help me set up" switches to the helper's area with a setup run.- fireEvent.click(screen.getByRole("button", { name: "assistant" }));- const panel = screen.getByTestId("local-models-assistant");- expect(panel.getAttribute("data-mode")).toBe("setup");- expect(panel.getAttribute("data-token")).toBe("1");- // The overview is no longer underneath it — this is a separate screen.- expect(screen.queryByTestId("overview-panel")).toBeNull();-- // The user's complaint: from the helper, the catalogue is ONE click away.- fireEvent.click(- screen.getByRole("tab", { name: "local_models.tab_catalogue" }),- );+ fireEvent.click(screen.getByRole("button", { name: "browse" }));expect(screen.getByTestId("catalogue-panel")).toBeDefined();- expect(screen.queryByTestId("local-models-assistant")).toBeNull();-- // "Something is not working" opens the same area in diagnose mode.- 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("hands the helper the leftover height and folds the page header away", () => {- render(<LocalModelsView />);- fireEvent.click(screen.getByRole("button", { name: "assistant" }));-- // Title, subtitle and the detail level describe the panels, not the- // conversation — a chat that starts a fifth of the way down the window- // reads as a widget rather than a screen.- expect(screen.queryByText("local_models.title")).toBeNull();- expect(- screen.queryByRole("tab", { name: "local_models.mode_simple" }),- ).toBeNull();- // What still steers something stays: the way out, and the rail.- expect(- screen.getByRole("button", { name: "local_models.back" }),- ).toBeDefined();- expect(- screen.getByRole("tab", { name: "local_models.tab_overview" }),- ).toBeDefined();-- // The helper's area is a flex child that fills what is left, so the panel- // never has to guess the chrome height above it.- const area = screen.getByTestId("local-models-assistant-tab");- expect(area.className).toContain("flex-1");- expect(area.className).toContain("min-h-0");-- // Back on a panel tab the full header returns.- fireEvent.click(- screen.getByRole("tab", { name: "local_models.tab_overview" }),- );- expect(screen.getByText("local_models.title")).toBeDefined();- expect(- screen.getByRole("tab", { name: "local_models.mode_simple" }),- ).toBeDefined();+ expect(screen.queryByTestId("overview-panel")).toBeNull();});});diff --git a/jarvis/ui/web/frontend/src/views/LocalModelsView.tsx b/jarvis/ui/web/frontend/src/views/LocalModelsView.tsxindex e5c3450bfe..e75b0c79cd 100644--- a/jarvis/ui/web/frontend/src/views/LocalModelsView.tsx+++ b/jarvis/ui/web/frontend/src/views/LocalModelsView.tsx@@ -35,10 +35,6 @@ 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";@@ -47,11 +43,10 @@ import { ServerPanel } from "@/views/local-models/ServerPanel";import { TuneSheet } from "@/views/local-models/TuneSheet";import { useEventStore } from "@/store/events";import { useLocaleChunk, useT } from "@/i18n";-import { cn } from "@/lib/utils";export type LocalModelsMode = "simple" | "advanced";export type LocalModelsTab =- "overview" | "assistant" | "models" | "catalogue" | "huggingface" | "server";+ "overview" | "models" | "catalogue" | "huggingface" | "server";/** Browser-local preference; a private window simply starts on Simple. */export const LOCAL_MODELS_MODE_KEY = "jarvis.localModels.mode";@@ -147,29 +142,7 @@ 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. "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 [assistantRequest, setAssistantRequest] =- useState<AssistantRequest | null>(null);- const [serverLogOpen, setServerLogOpen] = useState(false);const openBrowse = useCallback(() => setTab("catalogue"), []);- // The helper is an area of its own, not a block that pushes the overview- // down: the rail stays on screen, so "Browse models" is always one click- // away and the page never grows to a scroll of thousands of pixels.- const openAssistant = useCallback(() => {- setTab("assistant");- setAssistantRequest((r) => ({ mode: "setup", token: (r?.token ?? 0) + 1 }));- }, []);- const reportProblem = useCallback(() => {- setTab("assistant");- setAssistantRequest((r) => ({ mode: "diagnose", token: (r?.token ?? 0) + 1 }));- }, []);- const openServerLog = useCallback(() => {- setServerLogOpen(true);- setTab("server");- }, []);const openApiKeys = useCallback(() => setActiveSection("apikeys"),[setActiveSection],@@ -181,20 +154,6 @@ export function LocalModelsView() {storeMode(next);}, []);- /**- * Display name for a BRAIN provider id — the cloud model the helper runs- * on, not the local server. The list is already here for the capability- * lookup, so naming "gemini" as "Gemini" costs no request of its own.- */- const brainLabel = useCallback(- (id: string) => providers.find((p) => p.id === id)?.label ?? id,- [providers],- );-- // The helper is a conversation, and a conversation is a screen: it gets the- // window's leftover height instead of a slot inside the page scroller.- const chatMode = tab === "assistant";-// Leaving Advanced while on an Advanced-only tab must not strand the user on// a tab the rail no longer shows.useEffect(() => {@@ -204,7 +163,6 @@ export function LocalModelsView() {const tabs = useMemo(() => {const all: { id: LocalModelsTab; label: string }[] = [{ id: "overview", label: t("local_models.tab_overview") },- { id: "assistant", label: t("local_models.tab_assistant") },{ id: "models", label: t("local_models.tab_models") },{ id: "catalogue", label: t("local_models.tab_catalogue") },{ id: "huggingface", label: t("local_models.tab_huggingface") },@@ -217,170 +175,112 @@ export function LocalModelsView() {return (<div className="flex h-full min-h-0 w-full flex-col">- {/* The section header. On the helper's own area it collapses to the one- row that still steers something — the rail. The title, the subtitle- and the Simple/Advanced switch describe (and change) the panels, not- the conversation, and a chat that starts a fifth of the way down the- window reads as a widget rather than a screen. */}- <div- className={cn(- "flex w-full shrink-0 flex-col gap-4 px-8",- chatMode ? "pb-3 pt-4" : "py-6",- )}- >- {!chatMode && (- <>- <BackLink- label={t("local_models.back")}- onClick={() => setActiveSection("apikeys")}- />- <PanelHeader- title={t("local_models.title")}- subtitle={t("local_models.subtitle")}- />- </>- )}+ <div className="flex w-full shrink-0 flex-col gap-4 px-8 py-6">+ <BackLink+ label={t("local_models.back")}+ onClick={() => setActiveSection("apikeys")}+ />+ <PanelHeader+ title={t("local_models.title")}+ subtitle={t("local_models.subtitle")}+ />{/* The rail and the detail level belong together: the switch adds twoareas to this very row (and detail to the rows below), so it sitsbeside what it changes instead of alone in the header. */}<div className="flex flex-wrap items-center justify-between gap-3">- <div className="flex min-w-0 flex-wrap items-center gap-3">- {chatMode && (- <BackLink- label={t("local_models.back")}- onClick={() => setActiveSection("apikeys")}- />- )}- <SegmentedFilter<LocalModelsTab>- label={t("local_models.tabs_label")}- value={tab}- onChange={setTab}- options={tabs}+ <SegmentedFilter<LocalModelsTab>+ label={t("local_models.tabs_label")}+ value={tab}+ onChange={setTab}+ options={tabs}+ />+ <div className="flex items-center gap-2">+ <span className="text-[11px] uppercase tracking-[0.14em] text-muted-foreground">+ {t("local_models.mode_label")}+ </span>+ <SegmentedFilter<LocalModelsMode>+ label={t("local_models.mode_label")}+ value={mode}+ onChange={changeMode}+ options={[+ { id: "simple", label: t("local_models.mode_simple") },+ { id: "advanced", label: t("local_models.mode_advanced") },+ ]}/></div>- {!chatMode && (- <div className="flex items-center gap-2">- <span className="text-[11px] uppercase tracking-[0.14em] text-muted-foreground">- {t("local_models.mode_label")}- </span>- <SegmentedFilter<LocalModelsMode>- label={t("local_models.mode_label")}- value={mode}- onChange={changeMode}- options={[- { id: "simple", label: t("local_models.mode_simple") },- { id: "advanced", label: t("local_models.mode_advanced") },- ]}- />- </div>- )}</div></div>- {/* The helper is a screen of its own: it is handed the leftover height- and measures nothing itself. Every other tab is a document and keeps- the page scroller. */}- {chatMode ? (- <div- className="min-h-0 flex-1 px-8 pb-6"- data-testid="local-models-assistant-tab"- >- {providerId ? (- <AssistantPanel- providerId={providerId}- serverLabel={descriptor?.label ?? "Ollama"}- request={assistantRequest}- onOpenApiKeys={openApiKeys}- onOpenServerLog={openServerLog}- providerLabel={brainLabel}- />- ) : (+ <ScrollArea className="min-h-0 flex-1">+ <div className="flex w-full flex-col gap-4 px-8 pb-6">+ {loading && !providerId && (+ <p className="text-sm text-muted-foreground">+ {t("local_models.loading")}+ </p>+ )}++ {!loading && !providerId && (<Panel className="p-4"><p className="text-sm text-muted-foreground">- {loading- ? t("local_models.loading")- : t("local_models.no_provider")}+ {t("local_models.no_provider")}</p></Panel>)}- </div>- ) : (- <ScrollArea className="min-h-0 flex-1">- <div className="flex w-full flex-col gap-4 px-8 pb-6">- {loading && !providerId && (- <p className="text-sm text-muted-foreground">- {t("local_models.loading")}- </p>- )}-- {!loading && !providerId && (- <Panel className="p-4">- <p className="text-sm text-muted-foreground">- {t("local_models.no_provider")}- </p>- </Panel>- )}- {providerId && tab === "overview" && (- <div className="space-y-4" data-testid="local-models-overview">- <OverviewPanel+ {providerId && tab === "overview" && (+ <div className="space-y-4" data-testid="local-models-overview">+ <OverviewPanel+ providerId={providerId}+ onTune={setTuneModel}+ onOpenApiKeys={openApiKeys}+ onBrowse={openBrowse}+ advanced={mode === "advanced"}+ />+ {tuneModel && (+ <RoleTuneDrawerproviderId={providerId}- onTune={setTuneModel}- onOpenApiKeys={openApiKeys}- onBrowse={openBrowse}- onOpenAssistant={openAssistant}- onReportProblem={reportProblem}- advanced={mode === "advanced"}+ model={tuneModel}+ onClose={closeTune}/>- {tuneModel && (- <RoleTuneDrawer- providerId={providerId}- model={tuneModel}- onClose={closeTune}- />- )}- </div>- )}-- {providerId && tab === "models" && (- <div data-testid="local-models-models">- <InventoryPanel providerId={providerId} />- </div>- )}-- {providerId && tab === "catalogue" && (- <Panel className="p-4">- <div className="space-y-3" data-testid="local-models-catalogue">- <PanelHeader- title={t("local_models.catalogue_title")}- subtitle={t("local_models.catalogue_subtitle")}- />- <CataloguePanel providerId={providerId} />- </div>- </Panel>- )}+ )}+ </div>+ )}- {providerId && tab === "huggingface" && (- <Panel className="p-4">- <div className="space-y-3" data-testid="local-models-huggingface">- <PanelHeader title={t("local_models.huggingface_title")} />- <HuggingFacePanel providerId={providerId} />- </div>- </Panel>- )}+ {providerId && tab === "models" && (+ <div data-testid="local-models-models">+ <InventoryPanel providerId={providerId} />+ </div>+ )}- {providerId && tab === "server" && (- <div data-testid="local-models-server">- <ServerPanel- providerId={providerId}- initialLogOpen={serverLogOpen}+ {providerId && tab === "catalogue" && (+ <Panel className="p-4">+ <div className="space-y-3" data-testid="local-models-catalogue">+ <PanelHeader+ title={t("local_models.catalogue_title")}+ subtitle={t("local_models.catalogue_subtitle")}/>+ <CataloguePanel providerId={providerId} /></div>- )}- </div>- </ScrollArea>- )}+ </Panel>+ )}++ {providerId && tab === "huggingface" && (+ <Panel className="p-4">+ <div className="space-y-3" data-testid="local-models-huggingface">+ <PanelHeader title={t("local_models.huggingface_title")} />+ <HuggingFacePanel providerId={providerId} />+ </div>+ </Panel>+ )}++ {providerId && tab === "server" && (+ <div data-testid="local-models-server">+ <ServerPanel providerId={providerId} />+ </div>+ )}+ </div>+ </ScrollArea></div>);}diff --git a/jarvis/ui/web/frontend/src/views/local-models/OverviewPanel.test.tsx b/jarvis/ui/web/frontend/src/views/local-models/OverviewPanel.test.tsxindex 6784d94802..a666f0554e 100644--- a/jarvis/ui/web/frontend/src/views/local-models/OverviewPanel.test.tsx+++ b/jarvis/ui/web/frontend/src/views/local-models/OverviewPanel.test.tsx@@ -403,30 +403,16 @@ describe("OverviewPanel", () => {);});- it("offers three actions: browse, help me set up, something is not working", async () => {+ it("offers one action: browse the catalogue", async () => {installFetchMock();const onBrowse = vi.fn();- const onOpenAssistant = vi.fn();- const onReportProblem = vi.fn();- renderPanel({- onBrowse,- onOpenAssistant,- onReportProblem,- });+ renderPanel({ onBrowse });await screen.findByTestId("overview-actions");fireEvent.click(screen.getByRole("button", { name: "local_models.overview.action_browse" }),);- fireEvent.click(- screen.getByRole("button", { name: "local_models.overview.action_setup" }),- );- fireEvent.click(- screen.getByRole("button", { name: "local_models.overview.action_broken" }),- );expect(onBrowse).toHaveBeenCalledTimes(1);- expect(onOpenAssistant).toHaveBeenCalledTimes(1);- expect(onReportProblem).toHaveBeenCalledTimes(1);});it("the detail level changes the roles on this very screen", async () => {diff --git a/jarvis/ui/web/frontend/src/views/local-models/OverviewPanel.tsx b/jarvis/ui/web/frontend/src/views/local-models/OverviewPanel.tsxindex d8d6b3e138..8d55eb4071 100644--- a/jarvis/ui/web/frontend/src/views/local-models/OverviewPanel.tsx+++ b/jarvis/ui/web/frontend/src/views/local-models/OverviewPanel.tsx@@ -3,28 +3,17 @@* so it reads like a plan rather than a dashboard.** Top to bottom: one status sentence ("Ollama 0.32 running · 16 GB graphics- * memory · Ollama is not your active brain (OpenRouter answers)"), a row of- * three primary actions (Browse models / Help me set up / Something is not- * working), the headline tiles (downloads on disk, graphics memory, loaded- * now), and the roles as a checklist. Nothing here writes; the roles part is- * `RolesPanel`, mounted underneath so the integration wires one component.- *- * The setup assistant is NOT rendered here: "Help me set up" and "Something is- * not working" switch the section to the helper's own area, so the overview- * never becomes a page thousands of pixels tall with the roles at the bottom.+ * memory · Ollama is not your active brain (OpenRouter answers)"), the+ * primary action (Browse models), the headline tiles (downloads on disk,+ * graphics memory, loaded now), and the roles as a checklist. Nothing here+ * writes; the roles part is `RolesPanel`, mounted underneath so the+ * integration wires one component.** Props take `providerId` — the id of the card that declares* `supports_model_pull` — never a provider name.*/import { useEffect, useRef, type ReactNode } from "react";-import {- AlertCircle,- Cpu,- HardDrive,- Layers,- Search,- Sparkles,-} from "lucide-react";+import { Cpu, HardDrive, Layers, Search } from "lucide-react";import {SoftButton,@@ -46,10 +35,6 @@ import { RolesPanel, type RolesPanelProps } from "./RolesPanel";export interface OverviewPanelProps extends RolesPanelProps {/** Opens the catalogue ("Browse models"); the button hides without it. */onBrowse?: () => void;- /** Opens the setup assistant — its own area, not a block inside this one. */- onOpenAssistant?: () => void;- /** "Something is not working" — opens the assistant in diagnose mode. */- onReportProblem?: () => void;/*** Detail level. The switch beside the rail must change what is on screen* HERE too, or it reads as a dead control: Simple keeps the roles a@@ -71,8 +56,6 @@ export function OverviewPanel({onTune,onOpenApiKeys,onBrowse,- onOpenAssistant,- onReportProblem,advanced = false,}: OverviewPanelProps) {const t = useT();@@ -258,39 +241,20 @@ export function OverviewPanel({)}</p>- {(onBrowse || onOpenAssistant || onReportProblem) && (+ {onBrowse && (<divclassName="flex flex-wrap gap-2"role="group"aria-label={t("local_models.overview.actions_label")}data-testid="overview-actions">- {onBrowse && (- <ActionButton- primary- icon={<Search className="h-4 w-4" />}- label={t("local_models.overview.action_browse")}- hint={t("local_models.overview.action_browse_hint")}- onClick={onBrowse}- />- )}- {onOpenAssistant && (- <ActionButton- icon={<Sparkles className="h-4 w-4" />}- label={t("local_models.overview.action_setup")}- hint={t("local_models.overview.action_setup_hint")}- onClick={onOpenAssistant}- />- )}- {onReportProblem && (- <ActionButton- quiet- icon={<AlertCircle className="h-4 w-4" />}- label={t("local_models.overview.action_broken")}- hint={t("local_models.overview.action_broken_hint")}- onClick={onReportProblem}- />- )}+ <ActionButton+ primary+ icon={<Search className="h-4 w-4" />}+ label={t("local_models.overview.action_browse")}+ hint={t("local_models.overview.action_browse_hint")}+ onClick={onBrowse}+ /></div>)}@@ -338,24 +302,19 @@ function ActionButton({hint,onClick,primary,- quiet,}: {icon: ReactNode;label: string;hint: string;onClick: () => void;primary?: boolean;- quiet?: boolean;}) {return (<SoftButtonprimary={primary}onClick={onClick}ariaLabel={label}- className={cn(- "h-11 px-3.5 text-left",- quiet && "bg-transparent text-muted-foreground hover:text-foreground",- )}+ className="h-11 px-3.5 text-left"><span className="shrink-0">{icon}</span><span className="flex min-w-0 flex-col leading-tight">diff --git a/jarvis/ui/web/local_models_assistant_routes.py b/jarvis/ui/web/local_models_assistant_routes.pydeleted file mode 100644index 9ab78481f4..0000000000--- a/jarvis/ui/web/local_models_assistant_routes.py+++ /dev/null@@ -1,202 +0,0 @@-"""REST for the Local models setup assistant.-- POST /api/providers/{provider_id}/local-models/assistant/run start a guided turn- GET /api/providers/{provider_id}/local-models/assistant/session the one session + tier- POST /api/providers/{provider_id}/local-models/assistant/test end-to-end setup test- GET /api/providers/{provider_id}/local-models/assistant/benchmarks the proven/new table- GET /api/providers/{provider_id}/local-models/assistant/health the badge record--The assistant is a ``local-models`` agent-chat session (the timeline, the-WebSocket stream and the approval cards are the agent chat's — see-``agent_chat_routes.py``); these routes only start it with the canned opener-of a mode and expose the runner, the benchmark table and the health file.-Every handler sits behind the pull-capability gate the section uses-(``provider_routes._require_pull_capable``). ``/run`` answers 409 with one-English sentence when the Jarvis-Agents tier cannot run — never a silent-fallback.-"""--from __future__ import annotations--import logging-from typing import Any, Literal--from fastapi import APIRouter, HTTPException, Request-from pydantic import BaseModel, Field--from jarvis.ui.web.agent_chat_routes import _service_from_state-from jarvis.ui.web.provider_routes import (- _require_pull_capable,- _resolve_cfg,- _worker_flagged_dead,- _worker_usable,-)--log = logging.getLogger(__name__)--router = APIRouter(- prefix="/api/providers/{provider_id}/local-models/assistant",- tags=["local-models-assistant"],-)--Mode = Literal["setup", "diagnose", "test"]---class RunBody(BaseModel):- mode: Mode = "setup"---class RunResponse(BaseModel):- session_id: str- turn_id: str- surface: str = "local-models"---class SessionResponse(BaseModel):- session_id: str | None- surface: str = "local-models"- provider: str- model: str- ready: bool- reason: str---class TestBody(BaseModel):- roles: list[str] | None = Field(default=None, description="Subset of the writable roles.")---class HealthResponse(BaseModel):- status: str- reason: str- since: str | None = None- last_ok: str | None = None- checked_at: str | None = None---def _opener(mode: str) -> str:- from jarvis.local_models.assistant_prompt import (- DIAGNOSE_OPENER,- SETUP_OPENER,- TEST_OPENER,- )-- return {"setup": SETUP_OPENER, "diagnose": DIAGNOSE_OPENER, "test": TEST_OPENER}[mode]---def _usable(provider: str) -> bool:- """The provider-agnostic worker check the API-keys page uses."""- from jarvis.local_models.assistant_session import _default_usable-- return (_worker_usable(provider) or _default_usable(provider)) and not _worker_flagged_dead(- provider- )---async def _live(cfg: Any) -> dict[tuple[str, str], tuple[bool, str]]:- """One real call per candidate pair (cached ten minutes): a key that- authenticates but is refused for quota is not a working assistant."""- from jarvis.local_models.assistant_session import chain_candidates, probe_live-- return await probe_live(cfg, chain_candidates(cfg, usable=_usable))---def _svc(request: Request) -> Any:- svc = _service_from_state(request.app.state)- if svc is None:- raise HTTPException(status_code=503, detail="agent-chat-unavailable")- return svc---def _cfg(request: Request) -> Any:- cfg = _resolve_cfg(request)- if cfg is None:- raise HTTPException(status_code=503, detail="Configuration is unavailable (headless mode?)")- return cfg--[email protected]("/run", response_model=RunResponse)-async def post_run(provider_id: str, body: RunBody, request: Request) -> RunResponse:- """Start a guided turn: ensure the one session, send the mode's opener."""- from jarvis.agent_chat.service import SessionBusy- from jarvis.local_models.assistant_session import ensure_session-- _require_pull_capable(provider_id)- cfg = _cfg(request)- svc = _svc(request)- live = await _live(cfg)- try:- session = ensure_session(svc, cfg, usable=_usable, live=live)- except PermissionError as exc:- raise HTTPException(status_code=409, detail=str(exc)) from exc- except ValueError as exc:- raise HTTPException(status_code=409, detail=str(exc)) from exc- try:- turn_id = await svc.send(session.session_id, _opener(body.mode))- except SessionBusy as exc:- raise HTTPException(- status_code=409, detail="The assistant is still answering; wait for that turn."- ) from exc- return RunResponse(session_id=session.session_id, turn_id=turn_id)--[email protected]("/session", response_model=SessionResponse)-async def get_session(provider_id: str, request: Request) -> SessionResponse:- """The one ``local-models`` session (or null) and whether the tier can run."""- from jarvis.local_models.assistant_session import session_state-- _require_pull_capable(provider_id)- cfg = _cfg(request)- svc = _svc(request)- live = await _live(cfg)- return SessionResponse(**session_state(svc, cfg, usable=_usable, live=live))--[email protected]("/test")-async def post_test(provider_id: str, request: Request, body: TestBody | None = None) -> dict:- """Run the end-to-end setup test and persist the report."""- from jarvis.local_models.assistant_test import run_setup_test-- _require_pull_capable(provider_id)- cfg = _cfg(request)- roles = tuple(body.roles) if body is not None and body.roles else None- try:- report = await run_setup_test(cfg, roles)- except ValueError as exc:- raise HTTPException(status_code=400, detail=str(exc)) from exc- return report.to_payload()--[email protected]("/benchmarks")-async def get_benchmarks(provider_id: str, request: Request, refresh: bool = False) -> dict:- """The benchmark table; ``refresh=1`` rebuilds it through the brain's web search."""- from jarvis.local_models import benchmarks-- _require_pull_capable(provider_id)- table: benchmarks.BenchmarkTable | None- if refresh:- from jarvis.agent_chat.runner_brain import brain_manager- from jarvis.agent_chat.surface_kits import local_models_search_fn-- search_fn = local_models_search_fn(brain_manager())- if search_fn is None:- raise HTTPException(- status_code=503, detail="Web search is not available yet; try again shortly."- )- table = await benchmarks.refresh_benchmarks(search_fn)- else:- table = benchmarks.load_cached() or benchmarks.curated_only(- "No benchmark cache yet; refresh=1 builds one."- )- return table.to_payload()--[email protected]("/health", response_model=HealthResponse)-async def get_health(provider_id: str) -> HealthResponse:- """The persisted badge record — a file read, no live call."""- from jarvis.local_models.health_monitor import read_health_record-- _require_pull_capable(provider_id)- return HealthResponse(**read_health_record())---__all__ = ["router"]diff --git a/jarvis/ui/web/server.py b/jarvis/ui/web/server.pyindex ea622d5bcb..3bcd9f07fd 100644--- a/jarvis/ui/web/server.py+++ b/jarvis/ui/web/server.py@@ -364,7 +364,6 @@ class WebServer:from .friends_routes import router as friends_routerfrom .frontier_routes import router as frontier_routerfrom .grok_build_routes import router as grok_build_router- from .local_models_assistant_routes import router as local_models_assistant_routerfrom .local_models_routes import router as local_models_routerfrom .marketplace_publish_routes import router as marketplace_publish_routerfrom .marketplace_routes import router as marketplace_router@@ -434,8 +433,6 @@ class WebServer:# Local models section: inventory / unload / delete behind the# pull-capable card (same capability gate as the pull routes).app.include_router(local_models_router)- # Its setup assistant: run / session / test / benchmarks / health.- app.include_router(local_models_assistant_router)app.include_router(antigravity_router)app.include_router(claude_router)app.include_router(grok_build_router)diff --git a/tests/unit/agent_chat/test_agent_chat_surface_parity.py b/tests/unit/agent_chat/test_agent_chat_surface_parity.pyindex 73b2fd9570..f882c7360a 100644--- a/tests/unit/agent_chat/test_agent_chat_surface_parity.py+++ b/tests/unit/agent_chat/test_agent_chat_surface_parity.py@@ -1,8 +1,7 @@"""The session's ``surface`` — one enum in three languages, and the migration.``"jarvis"`` is the front page's chat (Jarvis with a keyboard), ``"agent"`` a-plain coding-agent session (the Agentic IDE's chat mode), ``"local-models"``-the Local models section's setup assistant. The value crosses+plain coding-agent session (the Agentic IDE's chat mode). The value crossesPython -> SQLite -> Pydantic -> TypeScript, so the four spellings are pinnedagainst each other here (AP-4) instead of trusted to stay in step by hand."""@@ -39,13 +38,6 @@ def test_typescript_spells_the_surface_the_same():match = re.search(r"export type AgentChatSurface\s*=\s*([^;]+);", text)assert match, "agentChatApi.ts must export `AgentChatSurface`"members = set(re.findall(r'"([a-z-]+)"', match.group(1)))- if "local-models" in SURFACES and "local-models" not in members:- import pytest-- pytest.xfail(- "frontend has not added 'local-models' to AgentChatSurface yet "- "(owned by the assistant-ui chunk, D8)"- )assert members == set(SURFACES)diff --git a/tests/unit/agent_chat/test_surface_kits.py b/tests/unit/agent_chat/test_surface_kits.pyindex 3a53ee22c8..8a2ae4b611 100644--- a/tests/unit/agent_chat/test_surface_kits.py+++ b/tests/unit/agent_chat/test_surface_kits.py@@ -1,18 +1,19 @@-"""Surface kits: one lookup per call site, and the local-models surface's recipe."""+"""Surface kits: one lookup per call site, and what a kit hands a turn."""from __future__ import annotationsfrom pathlib import Pathfrom typing import Any+import pytest+from jarvis.agent_chat import surface_kitsfrom jarvis.agent_chat.permissions import JARVIS_LADDER, ladder_keyfrom jarvis.agent_chat.runner_brain import build_override, kit_payloadfrom jarvis.agent_chat.service import resolve_runnerfrom jarvis.agent_chat.store import SURFACES, AgentChatSession-from jarvis.agent_chat.surface_kits import LOCAL_MODELS_SURFACE, kit_for-from jarvis.core.config import BrainProviderConfig, JarvisConfig-from jarvis.core.protocols import ExecutionContext, ToolResult+from jarvis.agent_chat.surface_kits import SurfaceKit, kit_for+from jarvis.core.protocols import Tooldef _session(surface: str) -> AgentChatSession:@@ -33,49 +34,53 @@ def _session(surface: str) -> AgentChatSession:)-class _SearchWeb:- name = "search_web"-+class _Brain:def __init__(self) -> None:- self.queries: list[str] = []+ self._config = object()- async def execute(self, args: dict[str, Any], ctx: ExecutionContext) -> ToolResult:- self.queries.append(str(args["query"]))- return ToolResult(- success=True,- output={"results": [{"title": "t", "url": "u", "snippet": "s"}, "junk"]},- )+def _probe_kit(monkeypatch: pytest.MonkeyPatch) -> SurfaceKit:+ """A throwaway surface with its own hands and briefing, registered for one test."""-class _Brain:- def __init__(self, cfg: JarvisConfig, tools: dict[str, Any]) -> None:- self._config = cfg- self._tools = tools+ def _tools(cfg: Any, brain: Any) -> dict[str, Tool]:+ return {"probe_read": object()} # type: ignore[dict-item]+ async def _extra(cfg: Any, brain: Any) -> str:+ return "BRIEFING"-def _cfg() -> JarvisConfig:- cfg = JarvisConfig()- cfg.brain.providers["ollama"] = BrainProviderConfig(model="qwen3.5:4b")- return cfg+ kit = SurfaceKit(+ surface="probe",+ brain_runner=True,+ ladder=JARVIS_LADDER,+ uses_stance=True,+ tools=_tools,+ system_extra=_extra,+ tool_origin="probe-origin",+ tool_filter=lambda tools: {n: t for n, t in tools.items() if n.startswith("probe_")},+ max_turns=7,+ )+ monkeypatch.setitem(surface_kits._KITS, "probe", kit)+ return kitdef test_every_surface_has_a_kit_and_the_table_matches_the_store() -> None:assert set(surface_kits._KITS) == set(SURFACES)assert kit_for("nope").surface == "agent"- assert kit_for("jarvis").brain_runner and kit_for(LOCAL_MODELS_SURFACE).brain_runner+ assert kit_for("jarvis").brain_runnerassert not kit_for("agent").brain_runnerdef test_the_four_call_sites_read_the_kit() -> None:- assert resolve_runner("openai", surface=LOCAL_MODELS_SURFACE) == "brain"+ assert resolve_runner("openai", surface="jarvis") == "brain"assert resolve_runner("openai", surface="agent") == "api"- assert ladder_key(LOCAL_MODELS_SURFACE, "brain") == JARVIS_LADDER+ assert ladder_key("jarvis", "brain") == JARVIS_LADDERassert ladder_key("agent", "api") == "api"-def test_build_override_uses_the_kit_tools_and_briefing() -> None:- session = _session(LOCAL_MODELS_SURFACE)- tools = {"lm_inventory": object()}+def test_build_override_uses_the_kit_tools_and_briefing(monkeypatch: pytest.MonkeyPatch) -> None:+ _probe_kit(monkeypatch)+ session = _session("probe")+ tools = {"probe_read": object()}override = build_override(session,brain=None,@@ -85,61 +90,37 @@ def test_build_override_uses_the_kit_tools_and_briefing() -> None:kit_tools=tools, # type: ignore[arg-type]system_extra="BRIEFING",)- assert set(override.tools_extra) == {"lm_inventory"}+ assert set(override.tools_extra) == {"probe_read"}assert override.system_extra == "BRIEFING"- assert override.tool_context["tool_origin"] == "local-models-assistant"+ assert override.tool_context["tool_origin"] == "probe-origin"assert override.tool_context["approval_surface"] == "interactive"- assert override.max_turns == 40+ assert override.max_turns == 7plain = build_override(_session("jarvis"), brain=None, stance="ask", cwd=Path("."), ref="r")assert "Read" in plain.tools_extra and plain.system_extra == ""assert plain.tool_context["tool_origin"] == "agent-chat"-async def test_kit_payload_builds_lm_tools_and_the_briefing() -> None:- search = _SearchWeb()- brain = _Brain(_cfg(), {"search_web": search})- tools, extra = await kit_payload(_session(LOCAL_MODELS_SURFACE), brain)- assert tools is not None and "lm_test_plan" in tools and "lm_pull" in tools- assert all(name.startswith("lm_") for name in tools)- assert "LOCAL MODELS SETUP ASSISTANT" in extra- assert "```jarvis-proposal" in extra+async def test_kit_payload_builds_the_kit_tools_and_the_briefing(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ _probe_kit(monkeypatch)+ tools, extra = await kit_payload(_session("probe"), _Brain())+ assert tools is not None and set(tools) == {"probe_read"}+ assert extra == "BRIEFING"- none_tools, none_extra = await kit_payload(_session("jarvis"), brain)+ none_tools, none_extra = await kit_payload(_session("jarvis"), _Brain())assert none_tools is None and none_extra == ""-async def test_search_fn_wraps_the_brains_search_web_tool() -> None:- search = _SearchWeb()- fn = surface_kits.local_models_search_fn(_Brain(_cfg(), {"search_web": search}))- assert fn is not None- rows = await fn("qwen3.5 LMArena")- assert rows == [{"title": "t", "url": "u", "snippet": "s"}]- assert search.queries == ["qwen3.5 LMArena"]- assert surface_kits.local_models_search_fn(_Brain(_cfg(), {})) is None---def test_local_models_surface_drives_cli_seats_through_the_brain() -> None:- """A coding agent's loop has none of the lm_* tools, so a seat whose- provider also ships a brain plugin runs through Jarvis' brain here."""- from jarvis.agent_chat.service import resolve_runner-- assert resolve_runner("antigravity", surface="local-models") == "brain"- assert resolve_runner("gemini", surface="local-models") == "brain"- # The Jarvis surface keeps the vendor CLI for a subscription seat.- assert resolve_runner("antigravity", surface="jarvis") != "brain"---def test_local_models_surface_keeps_only_its_own_hands_and_web_search() -> None:- """The router's 100+ declarations (some with schemas Gemini refuses) never- reach this surface: only lm_* and web search survive the kit filter."""- from jarvis.agent_chat.surface_kits import kit_for+def test_a_kit_filter_keeps_only_its_own_hands(monkeypatch: pytest.MonkeyPatch) -> None:+ kit = _probe_kit(monkeypatch)class _T:def __init__(self, name: str) -> None:self.name = name- tools = {n: _T(n) for n in ("lm_hardware", "search_web", "patch", "spawn-worker", "lm_pull")}- kept = kit_for("local-models").tool_filter(tools) # type: ignore[misc]- assert sorted(kept) == ["lm_hardware", "lm_pull", "search_web"]+ tools = {n: _T(n) for n in ("probe_read", "search_web", "patch", "spawn-worker")}+ assert kit.tool_filter is not None+ assert sorted(kit.tool_filter(tools)) == ["probe_read"] # type: ignore[arg-type]assert kit_for("jarvis").tool_filter is Nonediff --git a/tests/unit/cli_ctl/test_commands_local_models_assistant.py b/tests/unit/cli_ctl/test_commands_local_models_assistant.pydeleted file mode 100644index 379f4de0dd..0000000000--- a/tests/unit/cli_ctl/test_commands_local_models_assistant.py+++ /dev/null@@ -1,58 +0,0 @@-"""`jarvis local-models assistant ...` hits the assistant routes with the exact bodies."""--from __future__ import annotations--import pytest-from typer.testing import CliRunner--from jarvis.cli_ctl.__main__ import app--runner = CliRunner()-_BASE = "/api/providers/ollama/local-models/assistant"---def _one(capture_api) -> dict:- assert len(capture_api["calls"]) == 1, capture_api["calls"]- return capture_api["calls"][0]--[email protected]("mode", ["setup", "diagnose"])-def test_run_modes_post_without_a_confirmation(capture_api, mode: str) -> None:- res = runner.invoke(app, ["local-models", "assistant", mode])- assert res.exit_code == 0, res.output- call = _one(capture_api)- assert (call["method"], call["path"]) == ("POST", f"{_BASE}/run")- assert call["body"] == {"mode": mode}---def test_test_posts_the_role_filter(capture_api) -> None:- argv = ["local-models", "assistant", "test", "--role", "chat", "--role", "deep"]- res = runner.invoke(app, argv)- assert res.exit_code == 0, res.output- call = _one(capture_api)- assert (call["method"], call["path"]) == ("POST", f"{_BASE}/test")- assert call["body"] == {"roles": ["chat", "deep"]}---def test_test_without_roles_sends_no_body(capture_api) -> None:- res = runner.invoke(app, ["local-models", "assistant", "test"])- assert res.exit_code == 0, res.output- assert _one(capture_api)["body"] is None---def test_benchmarks_health_and_session_are_gets(capture_api) -> None:- res = runner.invoke(app, ["local-models", "assistant", "benchmarks", "--refresh"])- assert res.exit_code == 0, res.output- call = _one(capture_api)- assert (call["method"], call["path"]) == ("GET", f"{_BASE}/benchmarks")- assert call["query"] == {"refresh": "1"}-- capture_api["calls"].clear()- res = runner.invoke(app, ["local-models", "assistant", "health", "--provider", "llamacpp"])- assert res.exit_code == 0, res.output- assert _one(capture_api)["path"] == "/api/providers/llamacpp/local-models/assistant/health"-- capture_api["calls"].clear()- res = runner.invoke(app, ["local-models", "assistant", "session"])- assert res.exit_code == 0, res.output- assert (_one(capture_api)["method"], _one(capture_api)["path"]) == ("GET", f"{_BASE}/session")diff --git a/tests/unit/local_models/test_assistant_session.py b/tests/unit/local_models/test_assistant_session.pydeleted file mode 100644index f4fbffad37..0000000000--- a/tests/unit/local_models/test_assistant_session.py+++ /dev/null@@ -1,149 +0,0 @@-"""Session policy: the Agents-tier pair, one session per install, an honest refusal."""--from __future__ import annotations--import pytest--from jarvis.agent_chat.service import AgentChatService-from jarvis.agent_chat.store import AgentChatStore-from jarvis.core.config import BrainProviderConfig, BrainTierConfig, JarvisConfig-from jarvis.local_models import assistant_session as policy---def _cfg(provider: str = "openai", model: str = "gpt-x", **fallback: str) -> JarvisConfig:- cfg = JarvisConfig()- cfg.brain.worker = BrainTierConfig(provider=provider, model=model, **fallback)- return cfg---def _svc() -> AgentChatService:- return AgentChatService(AgentChatStore(":memory:"))---def test_tier_is_the_worker_pair_and_ready_only_with_a_credential() -> None:- ready = policy.agents_tier(_cfg(), usable=lambda p: p == "openai")- assert (ready.provider, ready.model, ready.ready, ready.reason) == ("openai", "gpt-x", True, "")- blocked = policy.agents_tier(_cfg(), usable=lambda _p: False)- assert blocked.ready is False and blocked.reason == policy.NOT_READY---def test_unknown_primary_falls_back_to_the_fallback_pair() -> None:- cfg = _cfg("some-cli-only-thing", "m", fallback_provider="gemini", fallback_model="g-2")- tier = policy.agents_tier(cfg, usable=lambda _p: True)- assert (tier.provider, tier.model) == ("gemini", "g-2")---def test_a_cli_only_primary_yields_to_the_tool_capable_fallback() -> None:- """Antigravity drives a CLI on a flat prompt and drops every tool; the- assistant needs its lm_* tools, so the chain moves on to a fallback that- can call them — and says why when none can."""- cfg = _cfg("antigravity", "gemini-3.5-flash", fallback_provider="gemini", fallback_model="g-2")- tier = policy.agents_tier(- cfg, usable=lambda _p: True, tool_capable=lambda p: p != "antigravity"- )- assert (tier.provider, tier.model, tier.ready) == ("gemini", "g-2", True)- stuck = policy.agents_tier(cfg, usable=lambda _p: True, tool_capable=lambda _p: False)- assert stuck.ready is False and stuck.reason == policy.NO_TOOLS---def test_the_real_antigravity_plugin_reports_no_tools() -> None:- assert policy._tool_capable("antigravity") is False- assert policy._tool_capable("gemini") is True---def test_no_worker_tier_is_not_ready() -> None:- cfg = JarvisConfig()- cfg.brain.worker = None- tier = policy.agents_tier(cfg, usable=lambda _p: True)- assert tier.ready is False and tier.reason == policy.NOT_READY---def test_ensure_session_creates_once_and_recreates_when_the_tier_moves() -> None:- svc = _svc()- cfg = _cfg()- first = policy.ensure_session(svc, cfg, usable=lambda _p: True)- again = policy.ensure_session(svc, cfg, usable=lambda _p: True)- assert first.session_id == again.session_id- assert first.surface == "local-models" and first.provider == "openai"- assert first.permission_mode == "ask"-- moved = policy.ensure_session(svc, _cfg(model="gpt-y"), usable=lambda _p: True)- assert moved.session_id != first.session_id and moved.model == "gpt-y"- assert len(svc.store.list_sessions(surface="local-models")) == 2---def test_ensure_session_refuses_without_the_tier() -> None:- svc = _svc()- with pytest.raises(PermissionError, match="Pick a Tool Model with an API key first"):- policy.ensure_session(svc, _cfg(), usable=lambda _p: False)- assert svc.store.list_sessions(surface="local-models") == []---def test_session_state_shape() -> None:- svc = _svc()- cfg = _cfg()- assert policy.session_state(svc, cfg, usable=lambda _p: True) == {- "session_id": None,- "surface": "local-models",- "provider": "openai",- "model": "gpt-x",- "ready": True,- "reason": "",- }- session = policy.ensure_session(svc, cfg, usable=lambda _p: True)- state = policy.session_state(svc, cfg, usable=lambda _p: False)- assert state["session_id"] == session.session_id- assert state["ready"] is False and state["reason"] == policy.NOT_READY---def test_a_pair_the_live_probe_refuses_yields_to_the_next_and_names_the_reason() -> None:- cfg = _cfg("gemini", "g-pro", fallback_provider="openai", fallback_model="o-1")- live = {- ("gemini", "g-pro"): (False, "gemini (g-pro): no credits — quota 0"),- ("openai", "o-1"): (True, ""),- }- tier = policy.agents_tier(cfg, usable=lambda _p: True, tool_capable=lambda _p: True, live=live)- assert (tier.provider, tier.model, tier.ready) == ("openai", "o-1", True)- live[("openai", "o-1")] = (False, "openai (o-1): bad key")- stuck = policy.agents_tier(cfg, usable=lambda _p: True, tool_capable=lambda _p: True, live=live)- assert stuck.ready is False and stuck.reason == "openai (o-1): bad key"---async def test_probe_live_classifies_with_the_provider_test_and_caches() -> None:- from jarvis.brain.provider_test import ProviderTestResult-- policy._reset_for_tests()- calls: list[tuple[str, str | None]] = []-- async def _tester(spec, cfg, *, model=None, timeout_s=20.0):- calls.append((spec.id, model))- status = "no_credits" if spec.id == "gemini" else "ok"- return ProviderTestResult(provider=spec.id, status=status, detail="quota 0")-- cfg = _cfg("gemini", "g-pro", fallback_provider="openai", fallback_model="o-1")- pairs = policy.chain_candidates(cfg, usable=lambda _p: True, tool_capable=lambda _p: True)- out = await policy.probe_live(cfg, pairs, tester=_tester)- assert out[("gemini", "g-pro")] == (- False,- "gemini (g-pro): the account has no credit or quota left for this model.",- )- assert out[("openai", "o-1")] == (True, "")- again = await policy.probe_live(cfg, pairs, tester=_tester)- assert again == out and len(calls) == 2 # cached, no second real call---def test_the_tool_model_comes_first_and_the_agents_chain_is_the_fallback() -> None:- """The user answers "which model does my own work" once, in the Tool- Model tab; the assistant honours that pick and bills through its key."""- cfg = _cfg("openai", "gpt-x")- cfg.brain.tool_model = BrainTierConfig(provider="vertex")- cfg.brain.providers["vertex"] = BrainProviderConfig(tool_model="gemini-3.6-flash")- assert policy._chain(cfg)[0] == ("vertex", "gemini-3.6-flash")- tier = policy.agents_tier(cfg, usable=lambda _p: True, tool_capable=lambda _p: True)- assert (tier.provider, tier.model) == ("vertex", "gemini-3.6-flash")- # An unusable Tool Model falls back to the Agents chain, honestly.- tier = policy.agents_tier(cfg, usable=lambda p: p != "vertex", tool_capable=lambda _p: True)- assert (tier.provider, tier.model) == ("openai", "gpt-x")- cfg.brain.tool_model = BrainTierConfig(provider="auto")- assert policy._chain(cfg)[0] == ("openai", "gpt-x")diff --git a/tests/unit/local_models/test_assistant_test.py b/tests/unit/local_models/test_assistant_test.pydeleted file mode 100644index 44f4b8924f..0000000000--- a/tests/unit/local_models/test_assistant_test.py+++ /dev/null@@ -1,202 +0,0 @@-"""The setup test runner: one real call per configured role, an honest table.--Fakes only: the Ollama server is :class:`tests.fakes.fake_ollama_server.FakeOllamaServer`-over ``httpx.MockTransport``; the 1-token generation and the voice probe go-through the runner's injectable seams.-"""--from __future__ import annotations--import json-from pathlib import Path-from typing import Any--import pytest--from jarvis.brain import ollama_inventory as inventory-from jarvis.core import config as cfg_mod-from jarvis.core.config import BrainProviderConfig, JarvisConfig-from jarvis.local_models import assistant_test-from jarvis.local_models.assistant_test import NOT_SET, run_setup_test-from tests.fakes.fake_ollama_server import FakeOllamaServer---class _HealthResult:- def __init__(self, ok: bool, error: str | None) -> None:- self.ok = ok- self.error = error- self.duration_ms = 12.0---class _Probe:- """Records the generation probes and answers ok unless told otherwise."""-- def __init__(self, failing: dict[str, str] | None = None) -> None:- self.calls: list[tuple[str, str]] = []- self.failing = failing or {}-- async def __call__(self, provider: str, model: str) -> Any:- self.calls.append((provider, model))- return _HealthResult(model not in self.failing, self.failing.get(model))---def _cfg(**picks: str) -> JarvisConfig:- cfg = JarvisConfig()- cfg.brain.providers["ollama"] = BrainProviderConfig(- model=picks.get("chat", ""),- tool_model=picks.get("tools_screen", ""),- deep_model=picks.get("deep", ""),- base_url="http://fake-ollama:11434",- )- cfg.ultrawiki.embedding_provider = "ollama"- cfg.ultrawiki.embedding_model = picks.get("embedding", "")- return cfg---def _server() -> FakeOllamaServer:- fake = FakeOllamaServer()- fake.add("qwen3.5:4b", capabilities=("completion", "tools", "vision"))- fake.add("chatonly:7b", capabilities=("completion",))- fake.add("embeddinggemma", capabilities=("embedding",), embed_dim=768)- return fake--[email protected](autouse=True)-def _data_dir(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:- monkeypatch.setattr(cfg_mod, "DATA_DIR", tmp_path)- return tmp_path---async def test_embed_probe_returns_the_vector_length() -> None:- fake = _server()- dim = await inventory.embed_probe("http://x", "embeddinggemma", transport=fake.transport())- assert dim == 768- assert ("POST", "/api/embed", {"model": "embeddinggemma", "input": "ping"}) in fake.calls- with pytest.raises(inventory.OllamaModelNotFound):- await inventory.embed_probe("http://x", "nope", transport=fake.transport())---async def test_full_setup_answers_ok_per_role_and_persists(tmp_path: Path) -> None:- fake = _server()- probe = _Probe()- cfg = _cfg(- chat="qwen3.5:4b", tools_screen="qwen3.5:4b", deep="qwen3.5:4b", embedding="embeddinggemma"- )- report = await run_setup_test(cfg, transport=fake.transport(), brain_probe=probe)-- assert isinstance(report, assistant_test.TestReport)- assert report.server["ok"] is True and report.server["version"] == "0.32.15"- assert {r: c.status for r, c in report.roles.items()} == {- "chat": "ok",- "tools_screen": "ok",- "deep": "ok",- "embedding": "ok",- "voice": NOT_SET,- }- assert report.voice is None- assert report.overall == "ok"- # Exactly one real generation per generation role, on the Ollama provider.- assert probe.calls == [("ollama", "qwen3.5:4b")] * 3- # Persisted to the state file with the badge keys the monitor also writes.- written = json.loads((tmp_path / "state" / "local_models_health.json").read_text("utf-8"))- assert written["status"] == "ok" and written["overall"] == "ok"- assert written["roles"]["embedding"]["detail"] == "Embeds (768 dimensions)."- assert written["last_ok"] == written["checked_at"] == report.checked_at- assert report.to_payload()["roles"]["chat"]["model"] == "qwen3.5:4b"---async def test_tools_screen_needs_declared_tools_and_vision() -> None:- fake = _server()- cfg = _cfg(tools_screen="chatonly:7b")- report = await run_setup_test(- cfg, ("tools_screen",), transport=fake.transport(), brain_probe=_Probe()- )- check = report.roles["tools_screen"]- assert check.status == "error"- assert "tools + vision" in check.detail- assert report.overall == "error"- assert report.reason().startswith("tools_screen:")---async def test_nothing_configured_is_needs_setup_not_error() -> None:- fake = _server()- report = await run_setup_test(_cfg(), transport=fake.transport(), brain_probe=_Probe())- assert all(c.status == NOT_SET for c in report.roles.values())- assert report.overall == "needs_setup"- assert report.reason() == ""---async def test_server_down_marks_every_configured_role_unreachable() -> None:- fake = _server()- fake.offline = True- probe = _Probe()- cfg = _cfg(chat="qwen3.5:4b", embedding="embeddinggemma")- report = await run_setup_test(cfg, transport=fake.transport(), brain_probe=probe)- assert report.server["ok"] is False- assert report.roles["chat"].status == "unreachable"- assert report.roles["embedding"].status == "unreachable"- assert probe.calls == [], "no generation is attempted against a dead server"- assert report.overall == "error"---async def test_generation_failure_is_classified_with_the_provider_vocabulary() -> None:- fake = _server()- cfg = _cfg(chat="qwen3.5:4b")- probe = _Probe(failing={"qwen3.5:4b": "model 'qwen3.5:4b' not found (404)"})- report = await run_setup_test(cfg, ("chat",), transport=fake.transport(), brain_probe=probe)- assert report.roles["chat"].status == "model_unavailable"---async def test_voice_probe_runs_only_for_the_managed_server() -> None:- fake = _server()- seen: list[str] = []-- async def voice_probe(base_url: str) -> dict[str, Any]:- seen.append(base_url)- return {"ok": True, "first_audio_ms": 640}-- cfg = _cfg(chat="qwen3.5:4b")- cfg.brain.providers["local-realtime"] = BrainProviderConfig(- launch_command="python server.py --model_name qwen3.5:4b --port 8765",- base_url="http://127.0.0.1:8765",- )- report = await run_setup_test(- cfg,- ("chat", "voice"),- transport=fake.transport(),- brain_probe=_Probe(),- voice_probe=voice_probe,- )- assert seen == ["http://127.0.0.1:8765"]- assert report.voice == {- "ok": True,- "first_audio_ms": 640,- "detail": "Voice round trip answered with audio.",- }- assert report.roles["voice"].status == "ok"- assert report.roles["voice"].latency_ms == 640- assert report.overall == "ok"-- # A bring-your-own command (no --model_name) is never probed.- cfg.brain.providers["local-realtime"].launch_command = "my-own-server --port 8765"- report = await run_setup_test(- cfg, ("voice",), transport=fake.transport(), brain_probe=_Probe(), voice_probe=voice_probe- )- assert seen == ["http://127.0.0.1:8765"]- assert report.voice is None and report.roles["voice"].status == NOT_SET---async def test_unknown_role_is_refused() -> None:- with pytest.raises(ValueError, match="Unknown role"):- await run_setup_test(_cfg(), ("chat", "ack"), transport=_server().transport())---async def test_since_is_kept_while_the_status_holds() -> None:- fake = _server()- cfg = _cfg(chat="qwen3.5:4b")- first = await run_setup_test(cfg, ("chat",), transport=fake.transport(), brain_probe=_Probe())- second = await run_setup_test(cfg, ("chat",), transport=fake.transport(), brain_probe=_Probe())- written = assistant_test.load_last_report()- assert written is not None- assert written["since"] == first.checked_at- assert written["checked_at"] == second.checked_atdiff --git a/tests/unit/local_models/test_assistant_tools.py b/tests/unit/local_models/test_assistant_tools.pydeleted file mode 100644index 4529a6197f..0000000000--- a/tests/unit/local_models/test_assistant_tools.py+++ /dev/null@@ -1,284 +0,0 @@-"""The assistant's tools: allowed tiers only, no delete, ask-tier through the executor.--Every action tool is exercised through a REAL ``ToolExecutor`` (bus, tier-evaluator, approval workflow — no mocks) on the ``interactive`` surface, so-the approval card the panel auto-answers is a genuine ticket, not a-convention.-"""--from __future__ import annotations--import asyncio-import inspect-from pathlib import Path-from uuid import uuid4--import pytest--from jarvis.core import config as cfg_mod-from jarvis.core.bus import EventBus-from jarvis.core.config import BrainProviderConfig, JarvisConfig, SafetyConfig-from jarvis.core.events import ActionApprovalRequired, ActionDenied, ActionExecuted-from jarvis.core.protocols import ExecutionContext-from jarvis.local_models import assistant_prompt, assistant_tools-from jarvis.local_models.assistant_tools import ALLOWED_TIERS, TOOL_PREFIX, build_tools-from jarvis.safety.approval import ApprovalWorkflow-from jarvis.safety.approval_surface import INTERACTIVE-from jarvis.safety.risk_tier import RiskTierEvaluator-from jarvis.safety.tool_executor import APPROVAL_DENIED_PREFIX, ToolExecutor-from tests.fakes.fake_ollama_server import FakeOllamaServer--ROOT = "http://fake-ollama:11434"--ASK_TOOLS = {- "lm_install_ollama",- "lm_start_server",- "lm_stop_server",- "lm_pull",- "lm_set_role",- "lm_set_model_options",- "lm_install_voice_server",- "lm_apply_voice_stack",-}---def _cfg(*, hf: bool = False, **picks: str) -> JarvisConfig:- cfg = JarvisConfig()- cfg.brain.providers["ollama"] = BrainProviderConfig(- model=picks.get("chat", ""),- tool_model=picks.get("tools_screen", ""),- deep_model=picks.get("deep", ""),- base_url=ROOT,- hf_enabled=hf,- )- cfg.ultrawiki.embedding_provider = "ollama"- cfg.ultrawiki.embedding_model = picks.get("embedding", "")- return cfg---def _server() -> FakeOllamaServer:- fake = FakeOllamaServer()- fake.add("qwen3.5:4b", size=3_400_000_000, capabilities=("completion", "tools", "vision"))- fake.add("embeddinggemma", size=600_000_000, capabilities=("embedding",), embed_dim=768)- fake.load("qwen3.5:4b")- return fake---def _ctx() -> ExecutionContext:- return ExecutionContext(trace_id=uuid4(), user_utterance="", config={}, memory_read=None)---def _executor(timeout_s: float = 5.0) -> tuple[ToolExecutor, EventBus]:- bus = EventBus()- executor = ToolExecutor(- bus,- RiskTierEvaluator(SafetyConfig()),- ApprovalWorkflow(bus, timeout_s=timeout_s),- default_timeout_s=timeout_s,- )- return executor, bus--[email protected](autouse=True)-def _data_dir(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:- monkeypatch.setattr(cfg_mod, "DATA_DIR", tmp_path)- return tmp_path---# ------------------------------------------------------------ the tool set---def test_every_tool_has_an_allowed_tier_and_the_prefix() -> None:- tools = build_tools(_cfg(hf=True), root=ROOT)- assert tools, "no tools built"- for name, tool in tools.items():- assert name == tool.name- assert name.startswith(TOOL_PREFIX), name- assert tool.risk_tier in ALLOWED_TIERS, (name, tool.risk_tier)- assert tool.schema.get("type") == "object"- assert tool.description- assert {n for n, t in tools.items() if t.risk_tier == "ask"} == ASK_TOOLS- assert {n for n, t in tools.items() if t.risk_tier == "monitor"} == {"lm_unload"}- assert "lm_test_plan" in tools and tools["lm_test_plan"].risk_tier == "safe"---def test_no_delete_tool_and_nothing_writes_the_brain_primary() -> None:- tools = build_tools(_cfg(hf=True), root=ROOT)- for name in tools:- assert not any(word in name for word in ("delete", "remove", "rm_", "uninstall")), name- source = inspect.getsource(assistant_tools)- assert "set_brain_primary" not in source- assert "delete_model" not in source- assert "switch_provider" not in source---def test_hf_search_is_offered_only_when_enabled() -> None:- assert "lm_hf_search" not in build_tools(_cfg(hf=False), root=ROOT)- assert "lm_hf_search" in build_tools(_cfg(hf=True), root=ROOT)---def test_describe_args_is_the_card_summary() -> None:- tools = build_tools(_cfg(), root=ROOT)- assert tools["lm_pull"].describe_args({"model": "qwen3.5:4b"}) == { # type: ignore[attr-defined]- "summary": "Download qwen3.5:4b"- }- assert tools["lm_set_role"].describe_args({"role": "chat", "model": "x"}) == { # type: ignore[attr-defined]- "summary": "Use x for chat"- }- assert tools["lm_inventory"].describe_args({}) == {} # type: ignore[attr-defined]---# ------------------------------------------------------------ reads through the executor---async def test_safe_reads_run_through_the_executor_on_the_fake_server() -> None:- fake = _server()- tools = build_tools(_cfg(), root=ROOT, transport=fake.transport())- executor, _bus = _executor()-- inventory = await executor.execute(- tools["lm_inventory"], args={}, config_snapshot={"approval_surface": INTERACTIVE}- )- assert inventory.success, inventory.error- names = {row["name"] for row in inventory.output["models"]}- assert names == {"qwen3.5:4b", "embeddinggemma"}- assert [r["name"] for r in inventory.output["running"]] == ["qwen3.5:4b"]-- status = await executor.execute(tools["lm_server_status"], args={})- assert status.success, status.error- assert status.output["probe"]["ok"] is True- assert status.output["voice"]["status"] is None---async def test_test_plan_tool_reports_per_role() -> None:- fake = _server()- tools = build_tools(_cfg(embedding="embeddinggemma"), root=ROOT, transport=fake.transport())- executor, _bus = _executor()- result = await executor.execute(tools["lm_test_plan"], args={"roles": ["embedding"]})- assert result.success, result.error- assert result.output["roles"]["embedding"]["status"] == "ok"- assert result.output["overall"] == "ok"---async def test_a_failing_handler_is_an_honest_tool_error_not_an_exception() -> None:- fake = _server()- fake.offline = True- tools = build_tools(_cfg(), root=ROOT, transport=fake.transport())- result = await tools["lm_inventory"].execute({}, _ctx())- assert result.success is False- assert result.error and "OllamaServerError" in result.error---# ------------------------------------------------------------ ask tier = a real ticket--[email protected]("name", sorted(ASK_TOOLS))-async def test_ask_tools_raise_an_interactive_ticket_and_stop_on_denial(name: str) -> None:- fake = _server()- tools = build_tools(_cfg(), root=ROOT, transport=fake.transport())- executor, bus = _executor(timeout_s=5.0)- cards: list[ActionApprovalRequired] = []- executed: list[ActionExecuted] = []-- async def _on_card(event: ActionApprovalRequired) -> None:- cards.append(event)- await bus.publish(ActionDenied(trace_id=event.trace_id, reason="user_vetoed"))-- async def _on_executed(event: ActionExecuted) -> None:- executed.append(event)-- bus.subscribe(ActionApprovalRequired, _on_card)- bus.subscribe(ActionExecuted, _on_executed)-- args = {- "model": "qwen3.5:4b",- "role": "chat",- "options": {"num_ctx": 4096},- "brain_model": "qwen3.5:4b",- "voice_model": "kokoro",- }- result = await asyncio.wait_for(- executor.execute(tools[name], args=args, config_snapshot={"approval_surface": INTERACTIVE}),- timeout=4.0,- )-- assert len(cards) == 1, "exactly one approval card"- card = cards[0]- assert card.tool_name == name and card.risk_tier == "ask" and card.reason == "risk_tier"- assert card.expires_at_ns > 0, "an interactive card has a real window"- assert result.success is False- assert result.error == f"{APPROVAL_DENIED_PREFIX} (user_vetoed)"- assert executed == [], "a denied action never runs"- # Nothing reached the server for a denied action.- assert not any(path in ("/api/pull", "/api/generate") for _m, path, _b in fake.calls)---async def test_monitor_tool_runs_without_a_card() -> None:- fake = _server()- tools = build_tools(_cfg(), root=ROOT, transport=fake.transport())- executor, bus = _executor()- cards: list[ActionApprovalRequired] = []-- async def _on_card(event: ActionApprovalRequired) -> None:- cards.append(event)-- bus.subscribe(ActionApprovalRequired, _on_card)- result = await executor.execute(- tools["lm_unload"],- args={"model": "qwen3.5:4b"},- config_snapshot={"approval_surface": INTERACTIVE},- )- assert result.success, result.error- assert cards == []- assert fake.models["qwen3.5:4b"].loaded is False---async def test_set_model_options_refuses_keys_the_suggestion_did_not_return() -> None:- fake = _server()- tools = build_tools(_cfg(), root=ROOT, transport=fake.transport())- suggested = await tools["lm_suggested_options"].execute({"model": "qwen3.5:4b"}, _ctx())- assert suggested.success, suggested.error- assert set(suggested.output["options"]) <= set(cfg_mod.OLLAMA_MODEL_OPTION_KEYS)-- result = await tools["lm_set_model_options"].execute(- {"model": "qwen3.5:4b", "options": {"not_a_knob": 1}}, _ctx()- )- assert result.success is False- assert "refused: not_a_knob" in (result.error or "")---# ------------------------------------------------------------ the prompt---async def test_prompt_renders_with_the_fake_server_and_carries_the_contract() -> None:- fake = _server()- cfg = _cfg(chat="qwen3.5:4b", embedding="embeddinggemma")- text = await assistant_prompt.build_system_extra(cfg, root=ROOT, transport=fake.transport())-- assert len(text) < 10_000, len(text)- assert "Ollama server: http://fake-ollama:11434 — running, version 0.32.15" in text- assert "- qwen3.5:4b · 3.2 GB · completion,tools,vision · ctx 262144" in text- assert "chat · completion · qwen3.5:4b · yes · brain.providers.ollama.model" in text- assert "embedding · embedding · embeddinggemma · yes · ultrawiki.embedding_model" in text- assert "tools_screen · tools+vision · not set" in text- assert "CURATED SHORTLIST (reviewed " in text- assert "qwen3.5:4b · chat · 3.4 · " in text and "· yes · tools+vision" in text- assert "new_little_tested" in text or "proven" in text- assert "```jarvis-proposal" in text- assert "Never delete a model" in text- assert "brain_switch" in text---async def test_prompt_is_honest_when_the_server_is_down() -> None:- fake = _server()- fake.offline = True- text = await assistant_prompt.build_system_extra(_cfg(), root=ROOT, transport=fake.transport())- assert "not answering" in text- assert "INSTALLED MODELS\n- unavailable:" in text---def test_openers_name_the_contract_and_never_execute_unasked() -> None:- for opener in (assistant_prompt.SETUP_OPENER, assistant_prompt.DIAGNOSE_OPENER):- assert "jarvis-proposal" in opener- assert "until I confirm" in opener- assert "lm_test_plan" in assistant_prompt.TEST_OPENERdiff --git a/tests/unit/local_models/test_benchmarks.py b/tests/unit/local_models/test_benchmarks.pydeleted file mode 100644index e97a3066cb..0000000000--- a/tests/unit/local_models/test_benchmarks.py+++ /dev/null@@ -1,240 +0,0 @@-"""Benchmarks + freshness: canned snippets in, honest labels out, offline safe."""--from __future__ import annotations--import datetime as _dt-import json-from pathlib import Path-from typing import Any--import pytest--from jarvis.brain.ollama_pull import CURATED_REVIEWED_ON, RECOMMENDED_MODELS-from jarvis.core import config as cfg_mod-from jarvis.local_models import benchmarks as bm--pytestmark = pytest.mark.asyncio--TODAY = CURATED_REVIEWED_ON + _dt.timedelta(days=1)-NOW = _dt.datetime(TODAY.year, TODAY.month, TODAY.day, 12, 0, tzinfo=_dt.UTC)--SNIPPETS: dict[str, list[dict[str, Any]]] = {- "qwen3.5 Artificial Analysis intelligence index": [- {- "title": "Qwen 3.5 27B — Artificial Analysis",- "url": "https://artificialanalysis.ai/models/qwen3-5-27b",- "snippet": "Qwen3.5 27B scores an Intelligence Index of 48 across our evaluations.",- },- {- "title": "Unrelated blog",- "url": "https://example.com/blog",- "snippet": "Gemma 4 has an intelligence index of 99 (this is not about qwen).",- },- ],- "qwen3.5 LMArena text arena score": [- {- "title": "LMArena leaderboard",- "url": "https://lmarena.ai/leaderboard/text",- "snippet": "qwen3.5-27b-instruct: Arena score 1312, rank 18.",- }- ],- "qwen3.5 Open LLM Leaderboard average score": [],- "gemma4 Artificial Analysis intelligence index": [- {- "title": "Gemma 4 — page without numbers",- "url": "https://artificialanalysis.ai/models/gemma-4",- "snippet": "Gemma 4 is Google's open model family.",- }- ],- "gemma4 LMArena text arena score": [],- "gemma4 Open LLM Leaderboard average score": [],-}---class _Search:- def __init__(self, table: dict[str, list[dict[str, Any]]] | None = None, *, fail: bool = False):- self.table = table if table is not None else SNIPPETS- self.fail = fail- self.queries: list[str] = []-- async def __call__(self, query: str) -> list[dict[str, Any]]:- self.queries.append(query)- if self.fail:- raise ConnectionError("offline")- return self.table.get(query, [])---def _library(entries: dict[str, dict[str, str]], *, fail: bool = False):- async def _fn(family: str) -> dict[str, Any]:- if fail:- raise ConnectionError("offline")- entry = entries.get(family)- return {"models": [dict(name=family, **entry)] if entry else [], "error": None}-- return _fn--[email protected](autouse=True)-def _data_dir(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:- monkeypatch.setattr(cfg_mod, "DATA_DIR", tmp_path)- return tmp_path---# ------------------------------------------------------------ pure helpers---def test_family_and_pulls_and_updated_parsers() -> None:- assert bm.family_of("qwen3.5:4b") == "qwen3.5"- assert bm.family_of("gemma4:26b-a4b-it-qat") == "gemma4"- assert bm.family_of("embeddinggemma") == "embeddinggemma"- assert bm.parse_pulls("17.2M") == 17_200_000- assert bm.parse_pulls("845.3K") == 845_300- assert bm.parse_pulls("1,204") == 1204- assert bm.parse_pulls("") == 0 and bm.parse_pulls("lots") == 0- assert bm.parse_updated_days("2 weeks ago") == 14- assert bm.parse_updated_days("a month ago") == 30- assert bm.parse_updated_days("yesterday") == 1- assert bm.parse_updated_days("3 hours ago") == 0- assert bm.parse_updated_days("") is None and bm.parse_updated_days("soon") is None---def test_extract_rows_is_tolerant_and_keyed_by_source_and_metric() -> None:- results = (- SNIPPETS["qwen3.5 Artificial Analysis intelligence index"]- + SNIPPETS["qwen3.5 LMArena text arena score"]- )- rows = bm.extract_rows("qwen3.5", results, source="artificial_analysis", seen_at="t")- by_key = {(r.source, r.metric): r for r in rows}- assert by_key[("artificial_analysis", "intelligence_index")].value == 48.0- # The LMArena snippet is filed under LMArena by its host, whatever query found it.- assert by_key[("lmarena", "arena_score")].value == 1312.0- assert by_key[("lmarena", "arena_score")].url == "https://lmarena.ai/leaderboard/text"- # The unrelated snippet (no family mention) contributed nothing.- assert all(r.value != 99.0 for r in rows)- assert bm.extract_rows("qwen3.5", [None, "junk", {}], source="x", seen_at="t") == [] # type: ignore[list-item]---def test_curated_families_come_from_the_shortlist() -> None:- families = bm.curated_families()- assert families[0] == bm.family_of(RECOMMENDED_MODELS[0].id)- assert len(families) == len(set(families))- assert bm.curated_families(("qwen3.5:4b", "qwen3.5:27b")) == ("qwen3.5",)---# ------------------------------------------------------------ labelling---def _table(- rows: tuple[bm.BenchmarkRow, ...] = (), library: dict[str, bm.LibraryFacts] | None = None-) -> bm.BenchmarkTable:- return bm.BenchmarkTable(- fetched_at=NOW.isoformat(), rows=rows, library=library or {}, source="live"- )---def test_label_proven_needs_a_row_or_100k_pulls() -> None:- row = bm.BenchmarkRow("qwen3.5", "lmarena", "arena_score", 1312.0, "u", "t")- assert bm.label_for("qwen3.5:4b", _table((row,)), TODAY) == "proven"- popular = {"gemma4": bm.LibraryFacts("gemma4", pulls=2_000_000, updated_days=120)}- assert bm.label_for("gemma4:12b-it-qat", _table((), popular), TODAY) == "proven"- quiet = {"gemma4": bm.LibraryFacts("gemma4", pulls=5_000, updated_days=120)}- assert bm.label_for("gemma4:12b-it-qat", _table((), quiet), TODAY) == "new_little_tested"- assert bm.label_for("gemma4:12b-it-qat", None, TODAY) == "new_little_tested"---def test_label_new_when_the_library_updated_it_recently_even_with_rows() -> None:- row = bm.BenchmarkRow("qwen3.5", "lmarena", "arena_score", 1312.0, "u", "t")- fresh = {"qwen3.5": bm.LibraryFacts("qwen3.5", pulls=9_000_000, updated_days=3)}- assert bm.label_for("qwen3.5:4b", _table((row,), fresh), TODAY) == "new_little_tested"- settled = {"qwen3.5": bm.LibraryFacts("qwen3.5", pulls=9_000_000, updated_days=60)}- assert bm.label_for("qwen3.5:4b", _table((row,), settled), TODAY) == "proven"---def test_label_stale_when_the_review_is_older_than_a_year() -> None:- row = bm.BenchmarkRow("qwen3.5", "lmarena", "arena_score", 1312.0, "u", "t")- a_year_later = CURATED_REVIEWED_ON + _dt.timedelta(days=366)- assert bm.label_for(RECOMMENDED_MODELS[0], _table((row,)), a_year_later) == "stale"- assert bm.label_for(RECOMMENDED_MODELS[0], _table((row,)), TODAY) in bm.LABELS---# ------------------------------------------------------------ refresh + cache---async def test_refresh_runs_three_queries_per_family_and_caches(tmp_path: Path) -> None:- search = _Search()- library = _library({"qwen3.5": {"pulls": "17.2M", "updated": "3 months ago"}})- table = await bm.refresh_benchmarks(- search, families=("qwen3.5", "gemma4"), library_fn=library, now=NOW- )- assert table.source == "live" and table.note == ""- assert sorted(search.queries) == sorted(SNIPPETS)- assert {(r.source, r.metric, r.value) for r in table.rows_for("qwen3.5")} == {- ("artificial_analysis", "intelligence_index", 48.0),- ("lmarena", "arena_score", 1312.0),- }- assert table.rows_for("gemma4") == ()- assert table.library["qwen3.5"] == bm.LibraryFacts("qwen3.5", 17_200_000, 90)- assert "gemma4" not in table.library-- written = json.loads((tmp_path / "state" / "local_models_benchmarks.json").read_text("utf-8"))- assert written["fetched_at"] == NOW.isoformat(timespec="seconds")- assert len(written["rows"]) == 2-- cached = bm.load_cached(now=NOW + _dt.timedelta(days=6))- assert cached is not None and cached.source == "cache"- assert cached.rows == table.rows and cached.library == table.library- assert bm.load_cached(now=NOW + _dt.timedelta(days=7)) is None, "TTL is seven days"- assert bm.load_cached(max_age_days=None, now=NOW + _dt.timedelta(days=400)) is not None---async def test_one_failing_query_loses_only_its_rows() -> None:- class _Flaky(_Search):- async def __call__(self, query: str) -> list[dict[str, Any]]:- if "LMArena" in query:- raise TimeoutError("slow")- return await super().__call__(query)-- table = await bm.refresh_benchmarks(- _Flaky(), families=("qwen3.5",), library_fn=_library({}), now=NOW, persist=False- )- assert [r.metric for r in table.rows] == ["intelligence_index"]---async def test_offline_prefers_the_cache_then_the_curated_note(tmp_path: Path) -> None:- # No cache at all → curated-only, with the note.- table = await bm.refresh_benchmarks(- _Search(fail=True), families=("qwen3.5",), library_fn=_library({}, fail=True), now=NOW- )- assert table.source == "curated" and table.rows == () and "curated" in table.note- assert not (tmp_path / "state" / "local_models_benchmarks.json").exists()-- # A cache (however old) beats curated-only.- await bm.refresh_benchmarks(- _Search(), families=("qwen3.5",), library_fn=_library({}), now=NOW - _dt.timedelta(days=30)- )- table = await bm.refresh_benchmarks(- _Search(fail=True), families=("qwen3.5",), library_fn=_library({}, fail=True), now=NOW- )- assert table.source == "cache" and len(table.rows) == 2 and "cached" in table.note---async def test_sync_search_fn_is_accepted() -> None:- def search(query: str) -> list[dict[str, Any]]:- return SNIPPETS.get(query, [])-- table = await bm.refresh_benchmarks(- search, families=("qwen3.5",), library_fn=_library({}), now=NOW, persist=False- )- assert len(table.rows) == 2---def test_from_payload_drops_malformed_entries() -> None:- table = bm.BenchmarkTable.from_payload(- {- "fetched_at": "2026-08-25T12:00:00+00:00",- "rows": [{"family": "a", "value": "x"}, {"family": "b", "value": 1}],- "library": {"a": {"pulls": "nope"}, "b": {"pulls": 5, "updated_days": None}},- }- )- assert [r.family for r in table.rows] == ["b"]- assert table.library == {"b": bm.LibraryFacts("b", 5, None)}diff --git a/tests/unit/ui/web/test_local_models_assistant_routes.py b/tests/unit/ui/web/test_local_models_assistant_routes.pydeleted file mode 100644index 25536b1478..0000000000--- a/tests/unit/ui/web/test_local_models_assistant_routes.py+++ /dev/null@@ -1,204 +0,0 @@-"""The assistant routes: run / session / test / benchmarks / health behind the pull gate.--The agent-chat service is real (in-memory store); the brain turn is not run-— ``send`` is observed through the service's own store events. The Ollama-server is the fake; the Agents-tier check is injected by patching the routes'-``_usable`` seam (a plain function, not a mock library).-"""--from __future__ import annotations--import json-from pathlib import Path--import httpx-import pytest-from fastapi.testclient import TestClient--from jarvis.agent_chat.service import AgentChatService-from jarvis.agent_chat.store import AgentChatStore-from jarvis.brain import ollama_inventory, ollama_runtime-from jarvis.core import config as cfg_mod-from jarvis.core.bus import EventBus-from jarvis.core.config import BrainProviderConfig, BrainTierConfig, JarvisConfig-from jarvis.local_models.assistant_prompt import DIAGNOSE_OPENER, SETUP_OPENER-from jarvis.local_models.assistant_session import NOT_READY-from jarvis.ui.web import local_models_assistant_routes as routes-from jarvis.ui.web.server import WebServer-from tests.fakes.fake_ollama_server import FakeOllamaServer--BASE = "/api/providers/ollama/local-models/assistant"---def fake(monkeypatch: pytest.MonkeyPatch) -> FakeOllamaServer:- server = FakeOllamaServer()- server.add("embeddinggemma", capabilities=("embedding",), embed_dim=768)-- def _client(transport: httpx.AsyncBaseTransport | None = None) -> httpx.AsyncClient:- return httpx.AsyncClient(transport=server.transport(), timeout=5.0)-- monkeypatch.setattr(ollama_inventory, "_make_client", _client)-- real_probe = ollama_runtime.probe_host-- async def _probe(base_url: str, *, transport=None) -> dict:- return await real_probe(base_url, transport=server.transport())-- monkeypatch.setattr(ollama_runtime, "probe_host", _probe)- return server--[email protected](autouse=True)-def live_probe_is_a_fake(monkeypatch: pytest.MonkeyPatch) -> None:- """The routes ask every candidate pair for one real generation; a unit- test answers "alive" for all of them instead of calling a vendor."""- from jarvis.local_models import assistant_session-- async def _alive(cfg, pairs, *, timeout_s=20.0, tester=None):- return {pair: (True, "") for pair in pairs}-- assistant_session._reset_for_tests()- monkeypatch.setattr(assistant_session, "probe_live", _alive)---def server(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> WebServer:- monkeypatch.setenv("JARVIS_DATA_DIR", str(tmp_path))- monkeypatch.setattr(cfg_mod, "DATA_DIR", tmp_path)- cfg = JarvisConfig()- cfg.ui.dev_mode = True- cfg.brain.providers["ollama"] = BrainProviderConfig(base_url="http://fake:11434")- cfg.brain.worker = BrainTierConfig(provider="openai", model="gpt-x")- cfg.ultrawiki.embedding_provider = "ollama"- cfg.ultrawiki.embedding_model = "embeddinggemma"- srv = WebServer(cfg, bus=EventBus())- srv.app.state.config = cfg- srv.app.state.agent_chat = AgentChatService(AgentChatStore(":memory:"))- return srv---def ready(monkeypatch: pytest.MonkeyPatch) -> None:- monkeypatch.setattr(routes, "_usable", lambda _p: True)---def test_routes_sit_behind_the_pull_gate(server: WebServer) -> None:- with TestClient(server.app) as client:- assert client.get("/api/providers/openai/local-models/assistant/health").status_code == 400- assert client.get("/api/providers/nope/local-models/assistant/session").status_code == 404---def test_session_is_null_until_a_run_and_names_the_tier(server: WebServer, ready: None) -> None:- with TestClient(server.app) as client:- body = client.get(f"{BASE}/session").json()- assert body == {- "session_id": None,- "surface": "local-models",- "provider": "openai",- "model": "gpt-x",- "ready": True,- "reason": "",- }---def test_run_refuses_honestly_without_the_agents_tier(- server: WebServer, monkeypatch: pytest.MonkeyPatch-) -> None:- monkeypatch.setattr(routes, "_usable", lambda _p: False)- with TestClient(server.app) as client:- resp = client.post(f"{BASE}/run", json={"mode": "setup"})- assert resp.status_code == 409- assert resp.json()["detail"] == NOT_READY- assert client.get(f"{BASE}/session").json()["ready"] is False- assert server.app.state.agent_chat.store.list_sessions(surface="local-models") == []---def test_run_creates_one_session_and_sends_the_mode_opener(- server: WebServer, ready: None, monkeypatch: pytest.MonkeyPatch-) -> None:- svc: AgentChatService = server.app.state.agent_chat- sent: list[tuple[str, str]] = []-- async def fake_send(session_id: str, text: str) -> str:- sent.append((session_id, text))- return "turn-1"-- monkeypatch.setattr(svc, "send", fake_send)- with TestClient(server.app) as client:- first = client.post(f"{BASE}/run", json={"mode": "setup"})- assert first.status_code == 200, first.text- assert first.json() == {- "session_id": first.json()["session_id"],- "turn_id": "turn-1",- "surface": "local-models",- }- second = client.post(f"{BASE}/run", json={"mode": "diagnose"})- assert second.json()["session_id"] == first.json()["session_id"]- state = client.get(f"{BASE}/session").json()- assert state["session_id"] == first.json()["session_id"]- assert client.post(f"{BASE}/run", json={"mode": "bogus"}).status_code == 422- assert [text for _sid, text in sent] == [SETUP_OPENER, DIAGNOSE_OPENER]- sessions = svc.store.list_sessions(surface="local-models")- assert len(sessions) == 1 and sessions[0].provider == "openai"---def test_run_answers_409_while_a_turn_is_running(- server: WebServer, ready: None, monkeypatch: pytest.MonkeyPatch-) -> None:- from jarvis.agent_chat.service import SessionBusy-- svc: AgentChatService = server.app.state.agent_chat-- async def busy(session_id: str, text: str) -> str:- raise SessionBusy(session_id)-- monkeypatch.setattr(svc, "send", busy)- with TestClient(server.app) as client:- resp = client.post(f"{BASE}/run", json={"mode": "test"})- assert resp.status_code == 409 and "still answering" in resp.json()["detail"]---def test_test_route_runs_the_setup_test_and_health_reads_the_file(- server: WebServer, fake: FakeOllamaServer, tmp_path: Path-) -> None:- with TestClient(server.app) as client:- before = client.get(f"{BASE}/health").json()- assert before == {- "status": "unknown",- "reason": "",- "since": None,- "last_ok": None,- "checked_at": None,- }- resp = client.post(f"{BASE}/test", json={"roles": ["embedding"]})- assert resp.status_code == 200, resp.text- report = resp.json()- assert report["roles"]["embedding"]["status"] == "ok"- assert report["overall"] == "ok"- assert client.post(f"{BASE}/test", json={"roles": ["ack"]}).status_code == 400- after = client.get(f"{BASE}/health").json()- assert after["status"] == "ok" and after["checked_at"] == report["checked_at"]- assert after["since"] == after["last_ok"] == report["checked_at"]- written = json.loads((tmp_path / "state" / "local_models_health.json").read_text("utf-8"))- assert written["overall"] == "ok"---def test_benchmarks_without_a_cache_is_curated_only(server: WebServer) -> None:- with TestClient(server.app) as client:- body = client.get(f"{BASE}/benchmarks").json()- assert body["source"] == "curated" and body["rows"] == [] and body["note"]---def test_section_health_carries_the_local_models_badge_from_the_file(- server: WebServer, fake: FakeOllamaServer-) -> None:- from jarvis.local_models.health_monitor import write_health_record-- write_health_record("error", "chat: model not found")- with TestClient(server.app) as client:- resp = client.get("/api/providers/section-health?refresh=true")- assert resp.status_code == 200, resp.text- section = resp.json()["sections"]["local_models"]- assert section["status"] == "error"- assert section["detail"] == "chat: model not found"