Skip to content

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

fix(local-realtime): the voice server no longer cancels the model load it is waiting for

rubenluetke10-beep84f3aff46b89
diff --git a/docs/architecture-overview.md b/docs/architecture-overview.md
index 24d7127ed5..fb807012a9 100644
--- a/docs/architecture-overview.md
+++ b/docs/architecture-overview.md
@@ -120,7 +120,7 @@ Ack-Brain (`jarvis/brain/ack_brain/`) emits a sub-second butler-style preamble b
**Persona / custom system prompt:** the live persona comes from `jarvis/brain/persona_loader.py`. `base_persona_prompt()` returns an editable override (`data/custom_system_prompt.md`, written atomically via the Settings UI / `settings_routes.py`) when present, else the packaged `JARVIS_PERSONA.md`. `load_effective_persona_prompt()` is what the brains call: the base **plus the active mode's character block**. Edits apply on the **next turn** (no restart); `invalidate_cache()` clears the in-process cache. Never hardcode the persona string elsewhere.
-### The typed chat: two surfaces, three runners (2026-08-26)
+### The typed chat: two surfaces, three runners (2026-08-25)
`jarvis/agent_chat/` serves two chats that look the same and mean different
things — every session carries a `surface` (`store.SURFACES`, mirrored in
@@ -128,21 +128,9 @@ Pydantic and TypeScript, parity-tested):
| Surface | What a typed turn is | Runner per seat | Permission ladder |
|---|---|---|---|
-| `"jarvis"` — the front page's Chat section | **Jarvis with a keyboard**: the same assistant the microphone talks to (soul, persona, profile, identity card, memory, wiki, skills, ALL tools through the risk tiers) on the model the composer picked for THIS chat | EVERY seat → `runner_brain` (`BrainManager.generate` + a `TurnOverride`). No CLI seats at all (`SurfaceKit.cli_seats = False`) | ONE ladder in Claude Code's words — `ask` / `accept-edits` / `bypass` + `plan` |
+| `"jarvis"` — the front page's Chat section | **Jarvis with a keyboard**: the same assistant the microphone talks to (soul, persona, profile, identity card, memory, wiki, skills, ALL tools through the risk tiers) on the model the composer picked for THIS chat | API-key / local rows → `runner_brain` (`BrainManager.generate` + a `TurnOverride`); subscription CLIs → `runner_cli` with the Jarvis identity | ONE ladder in Claude Code's words — `ask` / `accept-edits` / `bypass` + `plan` — folded onto each CLI's own spelling |
| `"agent"` — the Agentic IDE's chat mode | a plain coding-agent session in a folder | `runner_api` (tool loop) or a plain `runner_cli` | the vendor's own ladder |
-**Which providers a surface may be seated on** is `catalog.rows_for(surface)`,
-and it gates on the capability, never on a name (AP-21): a surface with CLI
-seats gets every row; one without gets only the rows a brain plugin drives
-(`runner_api.BRAIN_BY_PROVIDER`). The front page is the second case
-(maintainer, 2026-08-26) — one pipeline, one place the model is picked, one
-usage ledger, and a model change is a `TurnOverride` rather than a different
-vendor process. Its `claude-api` row therefore always resolves to the
-Anthropic endpoint, Claude Code installed or not. Chats seated on a CLI
-before the change move to the API row of the same brand once per database
-(`service._retire_cli_seats`, marked by SQLite's `user_version`), keeping
-their transcript and dropping only a model id the endpoint cannot take.
-
**The per-turn override contract (binding).** A chat's pick of provider /
model / effort NEVER moves the live brain: `BrainManager.generate(turn_override=…)`
carries it in a ContextVar (`jarvis/brain/turn_override.py`), read in exactly
@@ -171,14 +159,9 @@ handler) turns the stance into a decision: `ask` cards everything consequential,
gate itself; `plan` offers reading hands only. The blacklist is never reached
from here in any stance.
-**A CLI seat as Jarvis** (built, currently unreachable). No surface seats a
-CLI as Jarvis any more — the front page dropped its CLI seats on 2026-08-26
-and the IDE's chat runs a plain coding agent — so `run_cli_turn(identity=…)`
-is False on every turn today. The machinery stays wired to the kit
-(`kit.brain_runner and kit.cli_seats`) rather than to a surface name, so a
-surface that wants both works without a rebuild. How it works, when reached:
-a subscription CLI keeps its own loop (that is what the subscription pays
-for; only the vendor's official binary spends it) but runs with Jarvis' head: `BrainManager.render_surface_prompt` renders the
+**A CLI seat as Jarvis.** A subscription CLI keeps its own loop (that is what
+the subscription pays for; only the vendor's official binary spends it) but
+runs with Jarvis' head: `BrainManager.render_surface_prompt` renders the
voice turn's prompt layers read-only, `jarvis_harness.build_identity` adds the
chat's transcript on a fresh conversation and the surface addendum, and each
CLI takes it the way it can (Claude Code: `--append-system-prompt-file`; Codex
diff --git a/jarvis/agent_chat/__init__.py b/jarvis/agent_chat/__init__.py
index 650adfbad3..c3a49d8298 100644
--- a/jarvis/agent_chat/__init__.py
+++ b/jarvis/agent_chat/__init__.py
@@ -5,14 +5,12 @@ One package, two surfaces (``store.SURFACES``):
* ``"jarvis"`` — the front page's chat. What you type is input to Jarvis:
the same assistant the microphone talks to, on the model the composer
picked for THIS chat (:mod:`.runner_brain` — ``BrainManager.generate``
- with a per-turn override; the live voice brain is never switched). Every
- seat here is a provider API behind a key — no vendor CLI runs this chat
- (``surface_kits.SurfaceKit.cli_seats``, maintainer 2026-08-26), so one
- pipeline answers, one place picks the model and one ledger counts the
- cost. The folder chip is Jarvis' working folder (:mod:`.folder_tools`),
- and the one permission ladder — Ask / Auto-accept edits / Bypass, plus
- Plan — decides what asks through a clickable card
- (:mod:`.approval_bridge`).
+ with a per-turn override; the live voice brain is never switched). A
+ subscription CLI seat (Claude Code, Codex, …) runs as Jarvis through
+ :mod:`.runner_cli` + :mod:`.jarvis_harness`, so the subscription pays.
+ The folder chip is Jarvis' working folder (:mod:`.folder_tools`), and the
+ one permission ladder — Ask / Auto-accept edits / Bypass, plus Plan —
+ decides what asks through a clickable card (:mod:`.approval_bridge`).
* ``"agent"`` — a plain coding-agent session in a folder, the Claude Code
shape, which the Agentic IDE's chat mode runs: a vendor CLI or the API tool
loop, with the vendor's own permission ladder.
@@ -22,8 +20,7 @@ The pieces:
* :mod:`.effort` — which effort levels each provider family offers and how
a picked level maps onto what a provider actually accepts;
* :mod:`.catalog` — the provider rows the picker shows (labels, runner
- family, curated model lists for the CLI-backed providers) and which of
- them each surface may be seated on (``rows_for``);
+ family, curated model lists for the CLI-backed providers);
* :mod:`.tools` — the hands of the in-process agent (Read / Write / Edit /
Ls / Glob / Grep / RunCommand) scoped to the session's working directory;
* :mod:`.events` — the one event vocabulary both the store and the live
diff --git a/jarvis/agent_chat/attachments.py b/jarvis/agent_chat/attachments.py
deleted file mode 100644
index bc84f8a635..0000000000
--- a/jarvis/agent_chat/attachments.py
+++ /dev/null
@@ -1,221 +0,0 @@
-"""Files dropped, pasted or picked into a chat composer.
-
-The typed chats — the front page and the Agentic IDE's chat mode — take a
-sentence and nothing else. Someone with a screenshot of a broken layout has to
-describe it in words, which is the one thing a screenshot exists to avoid. The
-IDE's TERMINAL panes have taken dropped files since 2026-08 (``drops`` +
-``drop_analysis``); the chats were never wired to any of it, so a drop landed
-on a bare ``<textarea>`` and the browser navigated away to the file.
-
-This module is that wiring, and it is deliberately thin: everything hard was
-already solved one layer down and is reused rather than rewritten.
-
-* :mod:`jarvis.agentic_ide.drops` writes the bytes into the chat's own working
- directory (``.jarvis/drops``, self-ignoring) and hands back a reference the
- agent can open.
-* :mod:`jarvis.agentic_ide.drop_analysis` has a vision-capable model describe
- an image and extracts a document's text.
-* :func:`jarvis.agentic_ide.prompt_blueprint.attachment_block` lays the result
- out for whatever answers the turn.
-
-Why the description travels with the message rather than the file alone: a
-chat can be answered by a coding CLI, by a provider's own API loop, or by
-Jarvis' brain, and several of those cannot open an image at all. Sending only
-a path means the person drops a picture, types "what is wrong here", and the
-model receives a filename and a pronoun. The description is what makes the
-gesture work on every seat instead of the maintainer's.
-
-Import-light on purpose (AP-26): the heavy halves are imported inside the
-functions, so a boot that never sees an attachment pays nothing for this.
-"""
-
-from __future__ import annotations
-
-import asyncio
-import logging
-from pathlib import Path
-from typing import Any
-
-log = logging.getLogger(__name__)
-
-__all__ = [
- "MAX_TOTAL_BYTES",
- "AttachmentError",
- "compose",
- "ingest",
- "to_analysis",
-]
-
-#: Total cap for one attach gesture, shared with the terminal drop path so the
-#: two surfaces cannot disagree about what is too large.
-MAX_TOTAL_BYTES = 100 * 1024 * 1024
-
-
-class AttachmentError(RuntimeError):
- """The attach carried nothing usable, or the copies could not be written."""
-
-
-async def ingest(
- cwd: str | Path,
- *,
- paths: list[str] | None = None,
- uploads: list[tuple[str, bytes]] | None = None,
- provider: str = "",
-) -> list[Any]:
- """Store what was dropped in ``cwd`` and read what is in it.
-
- ``paths`` are real locations the browser managed to hand over (an Explorer
- or Finder drag usually carries them, and inside the desktop shell the host
- resolves them for every drop). ``uploads`` are ``(name, bytes)`` for
- everything with no path at all — a pasted screenshot, an image dragged off
- a web page.
-
- A path already inside ``cwd`` is referenced where it lies; anything else is
- copied in, because an agent's reach outside its working directory is
- neither guaranteed nor silent.
-
- Returns ``drop_analysis.DropAnalysis`` entries — one per file, in the order
- they arrived. Raises :class:`AttachmentError` when nothing usable was
- carried; an analysis that fails costs the description and nothing else, so
- the file still travels.
- """
- from jarvis.agentic_ide import drops
-
- folder = Path(cwd).expanduser() # noqa: ASYNC240 — string work; the stat below is threaded
- if not await asyncio.to_thread(folder.is_dir):
- raise AttachmentError(f"Not a folder: {folder}")
-
- references: list[str] = []
- # (name, bytes, reference) for everything attached — the reference travels
- # with the bytes so a description can never drift onto another file.
- readable: list[tuple[str, bytes, str]] = []
- to_copy: list[tuple[str, bytes]] = []
-
- for raw in paths or []:
- candidate = (raw or "").strip()
- if not candidate:
- continue
- inside = drops.within_workspace(candidate, folder)
- if inside is not None:
- reference = drops.reference(inside, agent=provider)
- references.append(reference)
- try:
- body = await asyncio.to_thread((folder / inside).read_bytes)
- except OSError as exc:
- # The reference still ships; the file simply goes undescribed.
- log.info("chat attach: %r not readable for analysis (%s)", inside, exc)
- else:
- readable.append((Path(inside).name, body, reference))
- continue
- # expanduser() is string work; the read itself goes to a worker thread
- # (a dropped file may live on a slow network share).
- resolved = Path(candidate).expanduser() # noqa: ASYNC240
- try:
- data = await asyncio.to_thread(resolved.read_bytes)
- except OSError as exc:
- log.info("chat attach: unreadable dropped path %r (%s)", candidate, exc)
- continue
- to_copy.append((resolved.name, data))
-
- total = sum(len(data) for _name, data in to_copy)
- for name, data in uploads or []:
- total += len(data)
- if total > MAX_TOTAL_BYTES:
- megabytes = MAX_TOTAL_BYTES // (1024 * 1024)
- raise AttachmentError(f"That attachment is too large (max {megabytes} MB in total).")
- if data:
- to_copy.append((name or "file", data))
-
- # ``store`` skips empty entries silently, so they are dropped HERE instead —
- # that keeps ``stored[i]`` paired with ``to_copy[i]`` positionally.
- to_copy = [(name, data) for name, data in to_copy if data]
-
- if to_copy:
- try:
- stored = await asyncio.to_thread(drops.store, folder, to_copy)
- except drops.DropError as exc:
- raise AttachmentError(str(exc)) from exc
- for item, (_original, data) in zip(stored, to_copy, strict=True):
- reference = drops.reference(item.relative_path, agent=provider)
- references.append(reference)
- readable.append((item.name, data, reference))
-
- if not references:
- raise AttachmentError("That attachment carried nothing this chat could use.")
-
- return await _analyze(readable)
-
-
-async def _analyze(readable: list[tuple[str, bytes, str]]) -> list[Any]:
- """Describe images and extract documents. Never raises — this is a bonus.
-
- The files are already stored and referenced by the time this runs, so a
- provider outage here must cost the description and nothing more.
- """
- import mimetypes
-
- from jarvis.agentic_ide import drop_analysis
- from jarvis.brain.drop_context import DroppedItem
-
- if not readable:
- return []
- items = [
- (
- DroppedItem(
- name=name,
- mime=mimetypes.guess_type(name)[0] or "application/octet-stream",
- data=data,
- ),
- reference,
- )
- for name, data, reference in readable
- ]
- try:
- return await drop_analysis.analyze(items)
- except Exception as exc: # noqa: BLE001 — the attach itself already succeeded
- log.info("chat attach: analysis failed (%s)", exc)
- return []
-
-
-def to_analysis(raw: list[dict[str, Any]] | None) -> list[Any]:
- """Rebuild the analyses a composer hands back on the wire.
-
- The client holds what :func:`ingest` returned while the person finishes
- typing, then posts it with the message. It is request data, so nothing here
- may assume a shape: a malformed entry becomes an empty-detail attachment
- rather than a 500 on a message somebody is waiting to send.
- """
- from jarvis.agentic_ide import drop_analysis
-
- out: list[Any] = []
- for entry in raw or []:
- if not isinstance(entry, dict):
- continue
- item = drop_analysis.DropAnalysis.from_dict(entry)
- if item.name:
- out.append(item)
- return out
-
-
-def compose(text: str, attachments: list[Any] | None) -> str:
- """The message as the turn will actually receive it.
-
- The person's sentence first, then what was attached — the sentence is the
- task, the files are context for it, and a model reads the instruction
- better when it is not buried under a page of extracted PDF.
-
- Returns ``text`` unchanged when nothing is attached, so an ordinary message
- is never reshaped by a feature it did not use.
- """
- from jarvis.agentic_ide.prompt_blueprint import attachment_block
-
- said = (text or "").strip()
- block = attachment_block(list(attachments or []))
- if not block:
- return said
- lead = (
- "Files the user attached to this message are below. Their contents are "
- "given in full because the file itself may not be openable from here — "
- "read them as part of the message."
- )
- return "\n\n".join(part for part in (said, lead, block) if part)
diff --git a/jarvis/agent_chat/catalog.py b/jarvis/agent_chat/catalog.py
index 8f5b92319a..cbd6bc3ffd 100644
--- a/jarvis/agent_chat/catalog.py
+++ b/jarvis/agent_chat/catalog.py
@@ -29,21 +29,14 @@ Two kinds of runner sit behind the rows:
the Jarvis surface (the front page's chat), where the typed turn is
Jarvis rather than a coding agent.
-``claude-api`` is the one dual row: on a surface with CLI seats, a Claude
-subscription login makes the ``claude`` CLI run the session (Claude Code
-proper — tools, skills, the Max plan's included usage); otherwise the
-Anthropic API answers, through the API runner or the brain one. The route
-decides per request by probing; this module only carries the static shape.
-
-Not every row reaches every surface: a surface whose kit has no CLI seats
-(``SurfaceKit.cli_seats``, the front page's chat) is offered only the rows
-with a brain plugin behind them — :func:`rows_for` is the one place that
-narrowing happens, and it gates on the capability, never on a provider name
-(AP-21).
+``claude-api`` is the one dual row: with a Claude subscription login the
+``claude`` CLI runs the session (Claude Code proper — tools, skills, the
+Max plan's included usage); with only an Anthropic API key the API runner
+does (the brain runner on the Jarvis surface). The route decides per request
+by probing; this module only carries the static shape.
Presentation data only — nothing here decides behaviour (AP-21); the rows
exist so the picker can show a provider before a key is typed.
-
"""
from __future__ import annotations
@@ -259,56 +252,3 @@ def provider_row(provider_id: str) -> ProviderRow | None:
def known_provider_ids() -> tuple[str, ...]:
return tuple(row.id for row in PROVIDER_ROWS)
-
-
-def rows_for(surface: str) -> tuple[ProviderRow, ...]:
- """The rows ``surface`` may pick from.
-
- A surface with CLI seats sees all of them. One without (the front page's
- chat) sees only the rows a brain plugin can drive — the providers whose
- own API answers behind a key, so the turn runs through Jarvis' harness
- and its model pick is one ``TurnOverride`` rather than a vendor process.
- Decided by asking the runner whether it can drive the provider at all,
- never from a list of names (AP-21).
- """
- from jarvis.agent_chat.surface_kits import kit_for
-
- if kit_for(surface).cli_seats:
- return PROVIDER_ROWS
- from jarvis.agent_chat.runner_api import supports_api_runner
-
- return tuple(row for row in PROVIDER_ROWS if supports_api_runner(row.id))
-
-
-def offers(surface: str, provider_id: str) -> bool:
- """Whether ``provider_id`` is one of ``surface``'s rows."""
- pid = (provider_id or "").strip().lower()
- return any(row.id == pid for row in rows_for(surface))
-
-
-#: A CLI-only row and the API row of the same brand. A chat that was seated
-#: on a vendor CLI before the front page dropped its CLI seats moves across
-#: this map instead of being stranded on a provider its picker no longer
-#: lists — same brand, same key page, now the provider's own endpoint.
-API_TWIN: Final[dict[str, str]] = {
- "openai-codex": "openai",
- "antigravity": "gemini",
- "grok-build": "grok",
-}
-
-
-def api_seat(provider: str, model: str) -> tuple[str, str]:
- """Where a CLI-seated ``(provider, model)`` lands on an API-only surface.
-
- The provider moves to its API twin; the model is kept only when the
- provider's own catalog knows it. A CLI's model ids are the CLI's own —
- ``opusplan``, ``best``, ``claude-opus-5[1m]``, ``gpt-5.6-sol`` as Codex
- spells it — and sending one to the provider's endpoint is an error, not
- a near miss. An unknown id therefore becomes ``""``: the provider's
- default, which the picker shows as "Default" and the person can change
- in one click.
- """
- pid = (provider or "").strip().lower()
- seat = API_TWIN.get(pid, pid)
- known = {m.id for m in CURATED_MODELS.get(seat, ())}
- return seat, (model if model in known else "")
diff --git a/jarvis/agent_chat/effort.py b/jarvis/agent_chat/effort.py
index 717be29b41..de699c0ad6 100644
--- a/jarvis/agent_chat/effort.py
+++ b/jarvis/agent_chat/effort.py
@@ -35,13 +35,9 @@ ORDER: Final[tuple[str, ...]] = (
# "Default" in the picker; it is only used for providers whose models vary
# too much to pick one honest default (OpenRouter, NVIDIA NIM, local servers).
_LADDERS: Final[dict[str, tuple[tuple[str, ...], str]]] = {
- # Anthropic low/medium/high/xhigh/max — one ladder for both runners.
- # Claude Code takes it as ``--effort``; the API takes it as
- # ``output_config.effort`` plus adaptive thinking on the models that
- # have it (``_anthropic_base.reasoning_kwargs``, which snaps a level a
- # model does not offer down to its nearest one). So the pick means the
- # same thing on the front page's chat, where the API always answers, as
- # it does on a Claude Code seat in the IDE's.
+ # Anthropic: the Claude Code CLI ladder (low/medium/high/xhigh/max). The
+ # API path has no effort knob today; the CLI is the preferred runner for
+ # a subscription login, so the ladder shown is the CLI's.
"claude-api": (("low", "medium", "high", "xhigh", "max"), "high"),
# OpenAI reasoning.effort for the GPT-5 family (``max`` since GPT-5.6;
# ``minimal`` only on the older 5.x — the plugin retries without a level
diff --git a/jarvis/agent_chat/jarvis_harness.py b/jarvis/agent_chat/jarvis_harness.py
index 6d23827012..cf1a9da8fc 100644
--- a/jarvis/agent_chat/jarvis_harness.py
+++ b/jarvis/agent_chat/jarvis_harness.py
@@ -25,12 +25,6 @@ official binary ever spends the subscription (maintainer, 2026-08-25).
This surface is deliberately additive: a CLI that cannot mount MCP servers, an
app whose tool gateway is not up yet, or a brain that has not finished building
simply runs with less. Nothing here is allowed to make a turn fail.
-
-Currently unreachable, on purpose. No surface seats a CLI as Jarvis since the
-front page's chat went API-only (2026-08-26, ``SurfaceKit.cli_seats``), so
-``run_cli_turn(identity=…)`` is False on every turn today. The service asks the
-kit — ``brain_runner and cli_seats`` — rather than a surface name, so a surface
-that wants both picks this up without a change here. Keep it working.
"""
from __future__ import annotations
diff --git a/jarvis/agent_chat/runner_brain.py b/jarvis/agent_chat/runner_brain.py
index 482ac4403c..39c7adbabc 100644
--- a/jarvis/agent_chat/runner_brain.py
+++ b/jarvis/agent_chat/runner_brain.py
@@ -1,12 +1,11 @@
"""The Jarvis surface's runner: Jarvis' own brain, driven by text.
-This is what the front page's chat runs on — every seat of it, since that
-surface gave up its CLI seats (2026-08-26): a provider API behind a key, or
-a server on this machine. A typed turn is the same turn a spoken one is —
-``BrainManager.generate`` with its router, its tools, its memory, its wiki
-and its safety tiers — with the keyboard in place of the microphone. Nothing
-here spawns a coding CLI or a second agent loop; there is one assistant in
-this app and this is how you type at it (maintainer, 2026-08-25).
+This is what the front page's chat runs on for an API-key or local seat. A
+typed turn is the same turn a spoken one is — ``BrainManager.generate`` with
+its router, its tools, its memory, its wiki and its safety tiers — with the
+keyboard in place of the microphone. Nothing here spawns a coding CLI or a
+second agent loop; there is one assistant in this app and this is how you
+type at it (maintainer, 2026-08-25).
What the composer's pick changes is which model Jarvis thinks with FOR THIS
CHAT, and how hard: provider, model and effort travel as a
diff --git a/jarvis/agent_chat/service.py b/jarvis/agent_chat/service.py
index e2c53689fa..273a039657 100644
--- a/jarvis/agent_chat/service.py
+++ b/jarvis/agent_chat/service.py
@@ -25,23 +25,17 @@ import shutil
import uuid
from collections.abc import Callable
from pathlib import Path
-from typing import Any, Final
+from typing import Any
-from jarvis.agent_chat import attachments as chat_attachments
from jarvis.agent_chat.approval_bridge import ChatApprovalBridge
-from jarvis.agent_chat.catalog import PROVIDER_ROWS, api_seat, offers, provider_row
+from jarvis.agent_chat.catalog import provider_row
from jarvis.agent_chat.effort import normalize_effort
from jarvis.agent_chat.events import make_event
from jarvis.agent_chat.permissions import ladder_key, normalize_permission
from jarvis.agent_chat.runner_api import TurnHandle, run_api_turn, supports_api_runner
from jarvis.agent_chat.runner_brain import run_brain_turn
from jarvis.agent_chat.runner_cli import run_cli_turn, supports_cli_runner
-from jarvis.agent_chat.store import (
- DEFAULT_SURFACE,
- SURFACES,
- AgentChatSession,
- AgentChatStore,
-)
+from jarvis.agent_chat.store import DEFAULT_SURFACE, AgentChatSession, AgentChatStore
from jarvis.agent_chat.surface_kits import kit_for
log = logging.getLogger(__name__)
@@ -71,21 +65,20 @@ def resolve_runner(provider: str, *, surface: str = "agent") -> str:
On the Jarvis surface the API path is Jarvis' own brain (``brain``): the
same set of providers, driven by ``BrainManager.generate`` instead of the
- coding agent's tool loop. That surface has no CLI seats at all
- (``SurfaceKit.cli_seats``, maintainer 2026-08-26), so a vendor CLI never
- answers there — not even the dual Claude row, which runs on the Anthropic
- API behind its key like every other seat.
+ coding agent's tool loop. The CLI seats keep their CLI runner there — a
+ subscription only pays for the vendor's own loop — and run as Jarvis
+ (see :mod:`jarvis.agent_chat.jarvis_harness`).
"""
kit = kit_for(surface)
api_runner = "brain" if kit.brain_runner else "api"
row = provider_row(provider)
+ if kit.brain_only:
+ # The surface's tools only exist inside the brain loop: a CLI seat
+ # (agy-cli, codex-cli, claude-cli) would run the vendor's coding agent
+ # without them, so any provider the brain knows is driven by the brain.
+ return "brain" if row is not None or supports_api_runner(provider) else "unknown"
if row is None:
return api_runner if supports_api_runner(provider) else "unknown"
- if not kit.cli_seats:
- # No vendor process here: the provider's own API answers, or nothing
- # does. ``rows_for`` keeps the picker to the same set, so "unknown"
- # is only reachable through a stale session or a hand-made request.
- return api_runner if supports_api_runner(row.id) else "unknown"
if row.id == "claude-api":
return "claude-cli" if _claude_cli_installed() else api_runner
if row.runner == "api":
@@ -93,13 +86,6 @@ def resolve_runner(provider: str, *, surface: str = "agent") -> str:
return row.runner
-#: ``AgentChatStore.data_version`` after the front page's chat gave up its
-#: CLI seats (2026-08-26) and its sessions moved to the API row of the same
-#: brand. Bump — and add a branch in ``_retire_cli_seats``' caller — only for
-#: another migration that rewrites what a person picked.
-_CLI_SEATS_RETIRED: Final[int] = 1
-
-
class _Running:
__slots__ = ("task", "cancel", "turn_id")
@@ -142,71 +128,11 @@ class AgentChatService:
# no word for "auto" and flipping to bypass would silence every later
# card, a mail send included.
self._always_allowed: dict[str, set[str]] = {}
- self._retire_cli_seats()
-
- def _retire_cli_seats(self) -> None:
- """Move chats off a CLI seat their surface no longer offers.
-
- The front page's chat runs on provider APIs only (``cli_seats``).
- A session opened before that — a Codex or Antigravity seat, or a
- Claude one carrying a Claude Code model id — would otherwise show a
- provider its own picker does not list, or send the endpoint a model
- name only the CLI understands. It moves to the API row of the same
- brand instead (``catalog.api_seat``), keeping its title, its folder,
- its permission mode and its whole transcript.
-
- Once per database, not once per boot (``data_version``): it rewrites
- a pick, and a pick made afterwards — a live model id the curated
- list does not carry — must survive every later start untouched.
- """
- if self.store.data_version() >= _CLI_SEATS_RETIRED:
- return
- for surface in SURFACES:
- if kit_for(surface).cli_seats:
- continue
- for row in PROVIDER_ROWS:
- # Rows that were always an API seat have nothing to migrate.
- if row.runner == "api":
- continue
- for session in self.store.sessions_on(surface, row.id):
- provider, model = api_seat(session.provider, session.model)
- if (provider, model) == (session.provider, session.model):
- continue
- self.store.reseat_session(session.session_id, provider=provider, model=model)
- log.info(
- "agent chat: %s left the %s CLI seat for %s %s",
- session.session_id,
- row.id,
- provider,
- f"({model})" if model else "(its default model)",
- )
- self.store.set_data_version(_CLI_SEATS_RETIRED)
# ------------------------------------------------------------ sessions
- def default_cwd(self, surface: str = DEFAULT_SURFACE) -> str:
- """Where a new ``surface`` session starts when nobody picked a folder.
-
- A surface that brings its own workspace (the Jarvis chat) gets that
- directory, created on first use. One that cannot be created — a
- read-only install, no writable app data — falls back to the service
- default rather than handing a chat a folder it cannot work in.
- """
- workspace = kit_for(surface).workspace_dir
- if workspace is None:
- return self._default_cwd()
- folder = workspace()
- try:
- folder.mkdir(parents=True, exist_ok=True)
- except OSError as exc:
- log.warning(
- "chat workspace %s could not be created (%s) — starting in the "
- "fallback folder instead",
- folder,
- exc,
- )
- return self._default_cwd()
- return str(folder)
+ def default_cwd(self) -> str:
+ return self._default_cwd()
def _bridge_for(self, bus: Any | None) -> ChatApprovalBridge | None:
"""The approval bridge, built on the first Jarvis turn that has a bus."""
@@ -230,11 +156,6 @@ class AgentChatService:
row = provider_row(provider)
if row is None and not supports_api_runner(provider):
raise ValueError(f"Unknown agent-chat provider: {provider!r}")
- if row is not None and not offers(surface, provider):
- raise ValueError(
- f"Provider {provider!r} is not offered on the {surface!r} chat. "
- "That chat runs on a provider API behind a key, not on a vendor CLI."
- )
ladder = ladder_key(surface, resolve_runner(provider, surface=surface))
permission_mode = normalize_permission(ladder, permission_mode)
eff = normalize_effort(provider, effort) if effort is not None else ""
@@ -246,7 +167,7 @@ class AgentChatService:
provider=provider,
model=model or (row.default_model if row else ""),
effort=eff,
- cwd=cwd or self.default_cwd(surface),
+ cwd=cwd or self.default_cwd(),
permission_mode=permission_mode,
title=title,
surface=surface,
@@ -287,37 +208,16 @@ class AgentChatService:
# ---------------------------------------------------------------- turns
- async def send(
- self,
- session_id: str,
- text: str,
- attachments: list[dict[str, Any]] | None = None,
- ) -> str:
- """Persist the person's message and start the turn. Returns turn_id.
-
- ``attachments`` are what the composer already had read for this message
- (``jarvis.agent_chat.attachments``): a described screenshot, an
- extracted document. Their contents go INTO the message the turn
- receives, because a chat may be answered by a coding CLI or a
- text-only model that cannot open the file itself.
-
- A message with attachments may carry no sentence at all — dropping a
- picture and pressing Enter is a complete gesture — but an empty message
- with nothing attached is still refused.
- """
+ async def send(self, session_id: str, text: str) -> str:
+ """Persist the person's message and start the turn. Returns turn_id."""
session = self.store.get_session(session_id)
if session is None:
raise NoSuchSession(session_id)
if self.is_running(session_id):
raise SessionBusy(session_id)
- kit = kit_for(session.surface)
text = text.strip()
- attached = chat_attachments.to_analysis(attachments)
- if not text and not attached:
+ if not text:
raise ValueError("empty message")
- # What the turn receives; ``text`` stays what the person typed so the
- # timeline shows their sentence rather than a page of extracted PDF.
- prompt = chat_attachments.compose(text, attached)
turn_id = uuid.uuid4().hex
cancel = asyncio.Event()
@@ -325,37 +225,7 @@ class AgentChatService:
self._running[session_id] = run
history = self.store.list_events(session_id)
- await self._emit(
- session_id,
- make_event(
- "user_message",
- {
- # The full prompt: this is what was actually sent, and the
- # API runner rebuilds the conversation from these events —
- # storing only the sentence would lose the picture on the
- # NEXT turn (runner_api.messages_from_events).
- "text": prompt,
- # What the person typed, when it differs from the prompt.
- # Absent on an ordinary message, so nothing changes there.
- **({"typed": text} if attached else {}),
- **(
- {
- "attachments": [
- {
- "name": item.name,
- "kind": item.kind,
- "described_by": item.described_by,
- "note": item.note,
- }
- for item in attached
- ]
- }
- if attached
- else {}
- ),
- },
- ),
- )
+ await self._emit(session_id, make_event("user_message", {"text": text}))
runner = resolve_runner(session.provider, surface=session.surface)
await self._emit(
session_id,
@@ -365,12 +235,13 @@ class AgentChatService:
"turn_id": turn_id,
"provider": session.provider,
"model": session.model,
- # The effort the turn RUNS with. It is the session's own
- # pick: no surface overrides it any more (the kit's
- # `effort` went with the setup helper), so reading one off
- # the kit would only be a way to raise an AttributeError
- # on every turn.
- "effort": normalize_effort(session.provider, session.effort),
+ # The effort the turn RUNS with: a surface may ask for more
+ # than the session's own pick (the setup helper does), and
+ # the timeline must not report the stale one.
+ "effort": normalize_effort(
+ session.provider,
+ kit_for(session.surface).effort or session.effort,
+ ),
"runner": runner,
"surface": session.surface,
},
@@ -390,7 +261,7 @@ class AgentChatService:
assistant_name=self._assistant_name(),
bus=bus,
surface=session.surface,
- stance=session.permission_mode if kit.uses_stance else "",
+ stance=session.permission_mode if kit_for(session.surface).uses_stance else "",
)
async def _body() -> None:
@@ -404,20 +275,12 @@ class AgentChatService:
always_allowed=self.always_allowed(session_id),
)
elif supports_cli_runner(runner):
- # A CLI runs AS Jarvis — its own tools over MCP, its calls
- # answered by the chat's approval card — only where the
- # surface both is Jarvis and seats a CLI at all. The front
- # page is the first and the second is now false there, so
- # today this is every CLI turn running as a plain coding
- # agent. Asked of the kit rather than the surface name, so
- # a surface that combines the two keeps working.
- as_jarvis = kit.brain_runner and kit.cli_seats
vendor = await run_cli_turn(
handle,
text,
runner,
- identity=as_jarvis,
- bridge=self._bridge_for(bus) if as_jarvis else None,
+ identity=(session.surface == "jarvis"),
+ bridge=self._bridge_for(bus) if session.surface == "jarvis" else None,
always_allowed=self.always_allowed(session_id),
)
if vendor and vendor != session.vendor_session:
diff --git a/jarvis/agentic_ide/folders.py b/jarvis/agentic_ide/folders.py
index 67b7a8ebc9..ab93404f0e 100644
--- a/jarvis/agentic_ide/folders.py
+++ b/jarvis/agentic_ide/folders.py
@@ -429,14 +429,7 @@ def search_folders(
if budget <= 0:
break
name = item.name
- if name in _SKIP_DIRS:
- continue
- # Hidden folders are matched only when the query itself
- # starts with a dot (".claude", ".config") — that is the
- # one time a person means one — and are never walked into:
- # ".cache" alone can hold more entries than the budget.
- hidden = _is_hidden(name)
- if hidden and not needle.startswith("."):
+ if name in _SKIP_DIRS or _is_hidden(name):
continue
try:
if not item.is_dir(follow_symlinks=False):
@@ -462,7 +455,7 @@ def search_folders(
),
)
)
- if depth < max_depth and not hidden:
+ if depth < max_depth:
queue.append((child, depth + 1))
except (PermissionError, OSError):
continue
@@ -471,50 +464,6 @@ def search_folders(
return [entry for _t, _k, _n, entry in hits[:limit]]
-def create_folder(parent: str | Path | None, name: str) -> tuple[FolderEntry | None, str | None]:
- """Make one new folder called ``name`` inside ``parent``.
-
- Returns ``(entry, error_message)``. Without a parent the folder goes into
- the home directory — the one place that exists on every machine.
-
- One segment only: a name carrying a separator would silently create a tree
- the person never saw, so it is refused rather than honoured. The parent must
- already exist for the same reason. A folder that is already there is handed
- back as it is — the person wanted that folder, and it now exists; whether
- it was made just now is not something they need to be told twice.
- """
- cleaned = name.strip()
- if not cleaned or cleaned in {".", ".."}:
- return None, "Give the new folder a name first."
- if any(sep in cleaned for sep in ("/", "\\", "\x00")):
- return None, "A folder name cannot contain slashes. Type just the name."
-
- base = Path(parent).expanduser() if parent else Path.home()
- try:
- if not base.is_dir():
- return None, (f"There is no folder called {base}, so nothing can be created inside it.")
- except OSError as exc:
- return None, f"Could not open {base}: {exc}"
-
- target = base / cleaned
- try:
- if target.is_dir():
- is_project, is_repo = _looks_like_project(target)
- return (
- FolderEntry(name=cleaned, path=str(target), is_project=is_project, is_repo=is_repo),
- None,
- )
- if target.exists():
- return None, f"{target} already exists and is a file, not a folder."
- target.mkdir()
- except PermissionError:
- return None, f"Jarvis is not allowed to create folders inside {base}."
- except OSError as exc:
- return None, f"Could not create {target}: {exc}"
-
- return FolderEntry(name=cleaned, path=str(target), is_project=False, is_repo=False), None
-
-
def _git_branch(root: Path) -> str | None:
"""Current branch from ``.git/HEAD`` — no subprocess, no git required."""
head = root / ".git" / "HEAD"
@@ -636,7 +585,6 @@ __all__ = [
"ProjectProfile",
"WorkspaceEntry",
"WorkspaceListing",
- "create_folder",
"list_dir",
"list_workspace_dir",
"probe_project",
diff --git a/jarvis/brain/manager.py b/jarvis/brain/manager.py
index 2d229e3ece..27816ef9e2 100644
--- a/jarvis/brain/manager.py
+++ b/jarvis/brain/manager.py
@@ -10575,7 +10575,16 @@ class BrainManager:
_TURN_HISTORY_OVERRIDE.reset(history_token)
_PUBLISH_RESPONSE_EVENT.reset(token)
- async def _generate(
+ async def _generate(self, user_text: str, *args: Any, **kwargs: Any) -> str:
+ """A voice turn. Its spend is published on ``BrainTurnCompleted`` with
+ the realtime/tool/pipeline split, so the ledger row the metered
+ provider writes underneath is tagged and not counted a second time."""
+ from jarvis.costs.ledger import usage_context
+
+ with usage_context("voice-turn"):
+ return await self._generate_untagged(user_text, *args, **kwargs)
+
+ async def _generate_untagged(
self,
user_text: str,
*,
diff --git a/jarvis/brain/turn_override.py b/jarvis/brain/turn_override.py
index ad7811a3e0..ca281de54d 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 the
manager's own ``_system_prompt_extra``. Empty leaves the prompt
- byte-identical; a surface with its own briefing sets it for its
- turns only.
+ byte-identical; a surface with its own briefing (the local-models
+ setup assistant) sets it for its turns only.
"""
provider: str
diff --git a/jarvis/local_models/__init__.py b/jarvis/local_models/__init__.py
index f93de01baa..5755fb6826 100644
--- a/jarvis/local_models/__init__.py
+++ b/jarvis/local_models/__init__.py
@@ -1,9 +1,10 @@
-"""The local-models self-check: the health monitor behind the section badge.
+"""The local-models setup assistant: test runner, benchmarks, tools and prompt.
-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.
+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.
"""
from __future__ import annotations
diff --git a/jarvis/mcp/adapter.py b/jarvis/mcp/adapter.py
index 48171346e4..688f6f4399 100644
--- a/jarvis/mcp/adapter.py
+++ b/jarvis/mcp/adapter.py
@@ -237,10 +237,6 @@ class MCPToolAdapter:
)
# Flag for the tool-use-loop guard: MCP tools are always action-centric.
self.is_action_tool: bool = True
- # Flag for the context-window fit (BrainManager._fit_tools_to_brain):
- # a connected server's tools are the first to leave a surface that
- # does not fit a small local model's window.
- self.is_mcp_tool: bool = True
self.risk_tier: RiskTier = risk_tier
# Register with the global CapabilityRegistry so the voice path
diff --git a/jarvis/plugins/brain/gemini.py b/jarvis/plugins/brain/gemini.py
index 677b6f725f..30ea5c809d 100644
--- a/jarvis/plugins/brain/gemini.py
+++ b/jarvis/plugins/brain/gemini.py
@@ -19,7 +19,6 @@ import logging
import os
import re
from collections.abc import AsyncIterator
-from functools import lru_cache
from typing import Any
from uuid import uuid4
@@ -400,97 +399,35 @@ def _convert_exclusive_bounds(schema: dict[str, Any]) -> dict[str, Any]:
return out
-# The documented Gemini schema subset, used when the installed google-genai
-# cannot be introspected. Field names AND their JSON aliases, because a tool
-# schema arrives in either spelling.
-_GEMINI_SCHEMA_KEYS_FALLBACK: frozenset[str] = frozenset({
- "additionalProperties", "additional_properties", "anyOf", "any_of",
- "default", "defs", "description", "enum", "example", "format", "items",
- "maxItems", "max_items", "maxLength", "max_length", "maxProperties",
- "max_properties", "maximum", "minItems", "min_items", "minLength",
- "min_length", "minProperties", "min_properties", "minimum", "nullable",
- "pattern", "properties", "propertyOrdering", "property_ordering", "ref",
- "required", "title", "type",
-})
-
-
-@lru_cache(maxsize=1)
-def _gemini_schema_keys() -> frozenset[str]:
- """Every key google-genai's ``types.Schema`` accepts, names and aliases.
-
- Read off the installed library rather than spelled out here, because that
- model IS the validator that rejects the request (``extra="forbid"``): its
- own field set is the only honest answer, and a library version that gains
- a keyword gains it here in the same step. A library that cannot be
- introspected falls back to the documented subset above — never to "allow
- everything", which is the failure this exists to prevent.
- """
- try:
- from google.genai import types
-
- fields = types.Schema.model_fields
- keys = set(fields)
- keys.update(f.alias for f in fields.values() if f.alias)
- if keys:
- return frozenset(keys)
- except Exception as exc: # noqa: BLE001 — the fallback list is the answer
- log.debug("gemini: schema field set not introspectable (%s) — using the fallback", exc)
- return _GEMINI_SCHEMA_KEYS_FALLBACK
-
-
-#: Keys whose value is one nested schema.
-_GEMINI_SCHEMA_VALUED: frozenset[str] = frozenset({"items"})
-#: Keys whose value maps FREE names to schemas. Their keys are property names
-#: chosen by whoever wrote the tool ("owner", "repo") and must never be judged
-#: against the allow-list — only their values are schemas.
-_GEMINI_SCHEMA_MAP_VALUED: frozenset[str] = frozenset({"properties", "defs"})
-#: Keys whose value is a list of schemas.
-_GEMINI_SCHEMA_LIST_VALUED: frozenset[str] = frozenset({"anyOf", "any_of"})
-
-
def _sanitize_for_gemini(schema: dict[str, Any]) -> dict[str, Any]:
- """Reduce a JSON schema to the subset google-genai's Schema model accepts.
-
- Gemini validates ``Tool.functionDeclarations.parameters`` through Pydantic
- with ``extra="forbid"``: ONE unknown key anywhere in ONE tool's schema
- fails the WHOLE GenerateContent request, so the brain dies and the turn
- falls through the entire provider chain. This has now happened four times
- with a different key each time — OpenAI's ``strict``, Pydantic's ``$defs``,
- an MCP tool's ``propertyNames``, and the GitHub MCP server's
- ``x-mcp-header`` (live 2026-08-26: 81 validation errors, gemini down,
- the front page's chat answered "I can't reach my provider").
-
- So this keeps an ALLOW-list, not a block-list: a key the library does not
- know is dropped whatever it is called. A block-list can never be complete
- — any connected MCP server may ship any extension key it likes — and
- every one of those four outages was a block-list that was.
-
- The walk is schema-aware, which the allow-list makes mandatory: under
- ``properties`` the keys are property NAMES a tool author chose, and
- judging those against the allow-list would delete the parameters
- themselves. Values that are data rather than schemas (``example``,
- ``default``, ``enum``) are passed through untouched.
+ """Recursively removes OpenAI-specific fields from a JSON schema.
+
+ Gemini's google-genai SDK validates Tool.functionDeclarations.parameters
+ via Pydantic with `extra="forbid"`. Fields like `strict`/`input_examples`
+ are OpenAI tool-use conventions and not allowed in Gemini's schema
+ subset. Instead of delivering a tool call without tools, we strip those
+ fields out — the tools themselves keep working unchanged, only the
+ OpenAI-specific hints are gone.
Exclusive numeric bounds (``exclusiveMinimum``/``exclusiveMaximum`` from
Pydantic ``Field(gt=...)``/``Field(lt=...)``) are first converted to the
- inclusive ``minimum``/``maximum`` Gemini accepts, then dropped.
- ``_GEMINI_FORBIDDEN_SCHEMA_KEYS`` still runs in front of the allow-list,
- for the keys the model accepts but the API does not.
+ inclusive ``minimum``/``maximum`` Gemini accepts, then the exclusive key is
+ stripped via ``_GEMINI_FORBIDDEN_SCHEMA_KEYS``.
"""
if not isinstance(schema, dict):
return schema
schema = _convert_exclusive_bounds(schema)
- allowed = _gemini_schema_keys()
out: dict[str, Any] = {}
for k, v in schema.items():
- if k in _GEMINI_FORBIDDEN_SCHEMA_KEYS or k not in allowed:
+ if k in _GEMINI_FORBIDDEN_SCHEMA_KEYS:
continue
- if k in _GEMINI_SCHEMA_MAP_VALUED and isinstance(v, dict):
- out[k] = {name: _sanitize_for_gemini(sub) for name, sub in v.items()}
- elif k in _GEMINI_SCHEMA_LIST_VALUED and isinstance(v, list):
- out[k] = [_sanitize_for_gemini(sub) if isinstance(sub, dict) else sub for sub in v]
- elif k in _GEMINI_SCHEMA_VALUED and isinstance(v, dict):
+ if isinstance(v, dict):
out[k] = _sanitize_for_gemini(v)
+ elif isinstance(v, list):
+ out[k] = [
+ _sanitize_for_gemini(item) if isinstance(item, dict) else item
+ for item in v
+ ]
else:
out[k] = v
return out
diff --git a/jarvis/plugins/tool/youtube_music_rest.py b/jarvis/plugins/tool/youtube_music_rest.py
index 575f42692d..da8b60ccb8 100644
--- a/jarvis/plugins/tool/youtube_music_rest.py
+++ b/jarvis/plugins/tool/youtube_music_rest.py
@@ -404,10 +404,6 @@ class YouTubeMusicRestTool:
self._player = player
self._playback_mode = playback_mode or _default_playback_mode
self._player_confirm_timeout_s = player_confirm_timeout_s
- # Whether the last blind media key this tool sent was a pause — the
- # only state in which a blind "play" is a resume rather than a guess
- # (``_control_blind``).
- self._blind_pause_sent = False
self._pool = HttpClientPool(transport=transport)
# search.list is the rationed call (100/day). Same words → same answer
# within a session, so a repeat costs nothing.
@@ -562,12 +558,7 @@ class YouTubeMusicRestTool:
ok, why = False, str(exc)
if ok:
try:
- out = await self._play_in_player(url, started)
- # Only a player that reported "playing" counts as done;
- # a cookie wall, a paused page or a page still loading
- # is an attempt the voice must not sell as a result.
- out["verified"] = bool(out.get("playback_confirmed"))
- return out
+ return await self._play_in_player(url, started)
except Exception as exc: # noqa: BLE001 — player unusable → browser, and say so
log.info("background player unusable, opening the browser: %s", exc)
why = f"The background player could not start ({exc})."
@@ -832,12 +823,7 @@ class YouTubeMusicRestTool:
return {"error": f"The background player did not accept '{verb}': {exc}"}
if not ok:
return {"error": f"The background player did not accept '{verb}'."}
- via_player: dict[str, Any] = {
- "ok": True,
- "action": verb,
- "app": _PLAYER_APP,
- "verified": True,
- }
+ via_player: dict[str, Any] = {"ok": True, "action": verb, "app": _PLAYER_APP}
if verb in ("next", "previous"):
await asyncio.sleep(1.2)
after = await self._player_state()
@@ -851,62 +837,27 @@ class YouTubeMusicRestTool:
cap = await media.capability()
if not cap.can_control:
return {"error": "This machine cannot control playback. " + (cap.note or "")}
- if not cap.can_read:
- return await self._control_blind(media, verb, cap.note)
- before = await media.now_playing()
- if before is None:
+ before = await media.now_playing() if cap.can_read else None
+ if cap.can_read and before is None:
return {"error": _NO_SESSION_READ}
ok = bool(await getattr(media, verb)())
if not ok:
return {"error": f"The player did not accept '{verb}'."}
- out: dict[str, Any] = {"ok": True, "action": verb, "verified": True, "app": before.app}
- if verb in ("next", "previous"):
- await asyncio.sleep(0.8)
- after = await media.now_playing()
- if after is not None:
- out["now"] = after.as_dict()
- else:
- out["track"] = before.title
- out["artist"] = before.artist
+ out: dict[str, Any] = {"ok": True, "action": verb}
+ if before is not None:
+ out["app"] = before.app
+ if verb in ("next", "previous"):
+ await asyncio.sleep(0.8)
+ after = await media.now_playing()
+ if after is not None:
+ out["now"] = after.as_dict()
+ else:
+ out["track"] = before.title
+ out["artist"] = before.artist
+ elif cap.backend == "media-keys":
+ out["note"] = "Sent as a media key: this toggles play/pause blindly."
return out
- async def _control_blind(self, media: Any, verb: str, note: str | None) -> dict[str, Any]:
- """Steer through media keys on a machine that cannot read its media
- session (Windows without the ``winrt`` extras).
-
- A media key reaches whatever player the OS considers current and
- reports nothing back, so the result is an ATTEMPT and says so
- (``verified: false``): the realtime bridge turns that into a spoken
- caveat, never a completion. ``play`` is the one verb refused outright
- unless this tool itself paused something the same way — the key is
- the play/pause TOGGLE, so with nothing known to be paused it starts a
- random tab or stops a running one. Live 2026-08-26 19:50: "play some
- cool music" arrived without a title, this path pressed the toggle,
- answered ``ok: true, resumed: true``, and the voice said "I've just
- started some cool music on YouTube Music" over a silent machine.
- """
- if verb == "play" and not self._blind_pause_sent:
- return {
- "error": (
- "Nothing is known to be paused, and this machine cannot see "
- "what is playing, so play was not pressed."
- )
- }
- ok = bool(await getattr(media, verb)())
- if not ok:
- return {"error": f"The player did not accept '{verb}'."}
- self._blind_pause_sent = verb == "pause"
- return {
- "ok": True,
- "action": verb,
- "verified": False,
- "note": (
- "Sent as a media key to whichever player is current; this machine "
- "cannot confirm that anything changed. "
- + (note or "")
- ).strip(),
- }
-
async def pause(self) -> dict[str, Any]:
return await self._control("pause")
@@ -976,23 +927,12 @@ class YouTubeMusicRestTool:
confirmed = True
break
out["playback_confirmed"] = confirmed
- out["verified"] = confirmed
if not confirmed:
out["note"] = (
"YouTube Music opened, but the browser has not reported playback "
"yet — if it stays silent, press play once (browsers block "
"autoplay on a site until it has been used there)."
)
- else:
- # The page opened; whether it plays is beyond what this machine
- # can see, so the result is an attempt (``verified: false``),
- # never "it is playing".
- out["playback_confirmed"] = False
- out["verified"] = False
- out["note"] = (
- "YouTube Music opened in the browser; this machine cannot confirm "
- "that playback started. " + (cap.note or "")
- ).strip()
return out
async def play(
diff --git a/jarvis/realtime/local_server/boot_progress.py b/jarvis/realtime/local_server/boot_progress.py
index df85d5b236..3f5ba77a0b 100644
--- a/jarvis/realtime/local_server/boot_progress.py
+++ b/jarvis/realtime/local_server/boot_progress.py
@@ -169,13 +169,32 @@ def parse_boot_stage(lines: list[str], *, spawned_at: float) -> tuple[str, str]
return best[1], best[2]
-def crash_tail(lines: list[str]) -> list[str]:
+def crash_tail(lines: list[str], *, since: float | None = None) -> list[str]:
"""The substantive end of the server log, bounded for the desktop log.
Readiness polling produces hundreds of identical ``GET /v1/pool`` lines
that would drown the one traceback worth keeping (a real crashed
generation's tail was 100% polling noise, live 2026-08-10 18:41).
+
+ ``since`` is the spawn time of the generation that died. The server log is
+ append-only across generations, so without that gate a child which exits
+ saying nothing inherits the last traceback in the file — on 2026-08-27 a
+ crash at 18:11 was reported with a stack from 11:44 and sent the diagnosis
+ seven hours off. Lines are gated exactly as in :func:`parse_boot_stage`:
+ untimestamped output (uvicorn, bare prints) belongs to the last timestamped
+ line above it.
"""
+ if since is not None:
+ threshold = since - 5.0
+ in_generation = False
+ current: list[str] = []
+ for line in lines:
+ stamp = _line_epoch(line)
+ if stamp is not None:
+ in_generation = stamp >= threshold
+ if in_generation:
+ current.append(line)
+ lines = current
kept = [
line[:CRASH_TAIL_MAX_LINE_CHARS]
for line in lines
diff --git a/jarvis/realtime/local_server/supervisor.py b/jarvis/realtime/local_server/supervisor.py
index d147102cf0..bfc06a41dc 100644
--- a/jarvis/realtime/local_server/supervisor.py
+++ b/jarvis/realtime/local_server/supervisor.py
@@ -107,6 +107,17 @@ BRAIN_REWARM_INTERVAL_S = 45 * 60.0
#: be read (30 min). 0 = never release.
DEFAULT_IDLE_RELEASE_S = 30 * 60.0
+#: Ceiling for the request that anchors a cold Ollama load (see
+#: :func:`anchor_brain_load`). Generous enough for a large model on a
+#: contended, paging host, bounded so a wedged Ollama cannot pin the thread
+#: for the life of the process.
+BRAIN_ANCHOR_TIMEOUT_S = 600.0
+
+#: Ollama endpoints with a load anchor in flight, so a burst of spawns cannot
+#: pile request on request for the same weights.
+_BRAIN_ANCHORS: set[tuple[str, str]] = set()
+_BRAIN_ANCHOR_LOCK = threading.Lock()
+
def idle_release_s() -> float:
"""Seconds of voice idleness after which the local stack frees the accelerator.
@@ -859,7 +870,11 @@ def _log_crash_tail() -> None:
try:
from jarvis.realtime.local_server import boot_progress # lazy (AP-26)
- tail = boot_progress.crash_tail(boot_progress.read_log_tail(_server_log()))
+ record = _read_pidfile() or {}
+ spawned_at = _json_float(record.get("spawned_at"))
+ tail = boot_progress.crash_tail(
+ boot_progress.read_log_tail(_server_log()), since=spawned_at
+ )
if tail:
log.warning(
"local-realtime monitor: owned server process exited "
@@ -869,7 +884,7 @@ def _log_crash_tail() -> None:
else:
log.warning(
"local-realtime monitor: owned server process exited "
- "unexpectedly and left no substantive log tail"
+ "unexpectedly and left no substantive log tail of its own"
)
except Exception: # noqa: BLE001 - forensics must never break recovery
log.debug("supervisor: crash-tail capture failed", exc_info=True)
@@ -1297,6 +1312,11 @@ def ensure_running(
exc,
)
return "refused:brain-context-profile"
+ # The child gives its own LLM warm-up 20 s per attempt and cancels
+ # the Ollama load when that expires, which on a slow first load is
+ # a loop that can never converge. Hold that load open from here
+ # instead; the thread outlives this call and nobody waits for it.
+ anchor_brain_load(launch_command=command)
clear_pidfile()
spawned_pid = _spawn(command, reason=reason)
if spawned_pid is None:
@@ -1391,6 +1411,10 @@ def replace_idle_managed_runtime(
)
return "refused:brain-context-profile"
+ # A model switch is the one spawn whose brain is COLD by definition,
+ # so this path needs the load anchor at least as much as the other.
+ anchor_brain_load(launch_command=command)
+
clear_pidfile()
spawned_pid = _spawn(command, reason=reason)
if spawned_pid is None:
@@ -2126,6 +2150,94 @@ def _kill_by_install_root(root: Path) -> tuple[int, int]:
# ── Brain warm-up ────────────────────────────────────────────────────────
+def anchor_brain_load(*, launch_command: str) -> bool:
+ """Hold a cold Ollama load open while the voice server boots into it.
+
+ Ollama ties a model load to the requests waiting on it: the moment the
+ last client hangs up it logs ``aborting load``, answers 499 and throws
+ the partly loaded weights away. The pinned speech-to-speech warm-up gives
+ its first completion 20 s and retries six times, so on a host where the
+ brain needs longer than that — a 9B model at 32k context on a box whose
+ RAM is nearly spent — every attempt kills the very load it is waiting
+ for, and the child dies with ``APITimeoutError`` before it ever serves a
+ turn. Respawning cannot help: each new generation restarts a load that
+ the next timeout aborts again.
+
+ So the spawn path starts one request that simply never hangs up. Its
+ prompt is empty, which makes it a pure load: Ollama answers
+ ``done_reason: "load"`` the instant the weights are resident. It runs in
+ a daemon thread nobody waits for, so :func:`ensure_running` stays as
+ quick as it was and a call that cannot be served still fails fast with
+ its spoken reason. The child's impatient attempts may still time out; the
+ load now survives them, and the next attempt finds a resident model.
+
+ Measured against Ollama on 2026-08-27: three clients aborting at 3 s left
+ the load running to completion while one patient client stayed connected.
+
+ Best-effort and idempotent — a non-Ollama brain, an unusable endpoint or
+ an anchor already in flight for the same model all answer ``False``.
+ """
+ launch_command = _effective_owned_launch_command(launch_command)
+ model, brain_url = _brain_endpoint(launch_command)
+ if not model or not brain_url:
+ return False
+ root = brain_url[: -len("/v1")] if brain_url.endswith("/v1") else brain_url
+ url = f"{root}/api/generate"
+ if not url.startswith(("http://", "https://")):
+ return False
+
+ key = (root, model)
+ with _BRAIN_ANCHOR_LOCK:
+ if key in _BRAIN_ANCHORS:
+ return False
+ _BRAIN_ANCHORS.add(key)
+
+ keep_alive = _brain_keep_alive(idle_release_s())
+ payload = json.dumps(
+ {"model": model, "prompt": "", "keep_alive": keep_alive, "stream": False}
+ ).encode("utf-8")
+
+ def _hold() -> None:
+ import urllib.error
+ import urllib.request
+
+ started = time.monotonic()
+ request = urllib.request.Request( # noqa: S310 — scheme checked above
+ url, data=payload, headers={"Content-Type": "application/json"}
+ )
+ try:
+ with urllib.request.urlopen(request, timeout=BRAIN_ANCHOR_TIMEOUT_S): # noqa: S310
+ pass
+ except (urllib.error.URLError, OSError, ValueError):
+ log.debug("supervisor: brain load anchor for %s failed", model, exc_info=True)
+ return
+ finally:
+ with _BRAIN_ANCHOR_LOCK:
+ _BRAIN_ANCHORS.discard(key)
+ log.info(
+ "local-realtime supervisor: brain model %s resident after %.1f s "
+ "(its load was anchored through the server warm-up, keep_alive=%s)",
+ model,
+ time.monotonic() - started,
+ keep_alive,
+ )
+
+ thread = threading.Thread(target=_hold, name="local-realtime-brain-anchor", daemon=True)
+ try:
+ thread.start()
+ except RuntimeError:
+ with _BRAIN_ANCHOR_LOCK:
+ _BRAIN_ANCHORS.discard(key)
+ log.debug("supervisor: could not start the brain load anchor", exc_info=True)
+ return False
+ log.info(
+ "local-realtime supervisor: anchoring the load of brain model %s so the "
+ "server warm-up cannot abandon it",
+ model,
+ )
+ return True
+
+
def warm_brain(*, launch_command: str, timeout: float = 5.0) -> bool:
"""Make the Ollama brain model resident BEFORE the first turn needs it.
@@ -2422,6 +2534,8 @@ def _reset_for_tests() -> None:
global _last_spawn_at, _monitor_thread, _monitor_stop, _monitor_key
_last_spawn_at = float("-inf")
_prepared_voice_models.clear()
+ with _BRAIN_ANCHOR_LOCK:
+ _BRAIN_ANCHORS.clear()
with _MONITOR_LOCK:
if _monitor_stop is not None:
_monitor_stop.set()
diff --git a/jarvis/realtime/session.py b/jarvis/realtime/session.py
index b4a6834d94..334e11dfed 100644
--- a/jarvis/realtime/session.py
+++ b/jarvis/realtime/session.py
@@ -881,9 +881,7 @@ _HYBRID_ROLE_DIRECTIVE = (
"however heavy the topic sounds. Never claim that an action or mission "
"was started, completed, saved, opened, or changed unless a successful "
"function result explicitly supports that claim; a promise or an "
- "intention is not a result, and a result marked unverified is an attempt, "
- "not a confirmation — say what was tried and that you cannot confirm it. "
- "When a request names SEVERAL targets, report "
+ "intention is not a result. When a request names SEVERAL targets, report "
"ONLY the ones a result actually names as done. If a function returns a "
"spoken confirmation question, ask the user and call the same function "
"again only after a clear affirmative answer. jarvis_action returns "
diff --git a/jarvis/realtime/tools.py b/jarvis/realtime/tools.py
index 199d8e0b6c..07a105da83 100644
--- a/jarvis/realtime/tools.py
+++ b/jarvis/realtime/tools.py
@@ -131,41 +131,16 @@ def _json_safe(value: Any) -> Any:
return json.loads(json.dumps(value, ensure_ascii=False, default=str))
-#: Spoken-outcome contract for a tool that acted but could not check the
-#: effect (``output["verified"] is False``). The system prompt already forbids
-#: claiming an outcome no successful result supports; this makes the result
-#: itself say "attempt, not outcome", in the field the model reads for
-#: confirmation questions too. Live 2026-08-26 19:50: a blind media-key
-#: "play" came back ``ok: true`` and the voice said "I've just started some
-#: cool music on YouTube Music" while nothing played.
-_UNVERIFIED_OUTCOME_INSTRUCTION = (
- "This result is an ATTEMPT, not a confirmed outcome: the tool acted but "
- "could not verify that anything changed. Tell the user in one short "
- "sentence what was tried and that you cannot confirm it from here; never "
- "say it is done, playing, running, or started. Offer the next step in the "
- "same breath instead of asking them to wait."
-)
-
-
-def _outcome_unverified(output: Any) -> bool:
- """Whether a tool explicitly marked its own outcome as unchecked."""
- return isinstance(output, dict) and output.get("verified") is False
-
-
def _bounded_result(success: bool, output: Any, error: str | None) -> dict[str, Any]:
- payload: dict[str, Any] = {
+ payload = {
"success": bool(success),
"output": _json_safe(output),
"error": str(error) if error else None,
}
- unverified = success and _outcome_unverified(output)
- if unverified:
- payload["unverified"] = True
- payload["instruction"] = _UNVERIFIED_OUTCOME_INSTRUCTION
serialized = json.dumps(payload, ensure_ascii=False, default=str)
if len(serialized) <= _MAX_RESULT_CHARS:
return payload
- truncated: dict[str, Any] = {
+ return {
"success": bool(success),
"output": serialized[:_MAX_RESULT_CHARS],
"error": (
@@ -174,10 +149,6 @@ def _bounded_result(success: bool, output: Any, error: str | None) -> dict[str,
),
"truncated": True,
}
- if unverified:
- truncated["unverified"] = True
- truncated["instruction"] = _UNVERIFIED_OUTCOME_INSTRUCTION
- return truncated
def _compact_text(text: str, limit: int) -> str:
diff --git a/jarvis/ui/web/frontend/src/components/LiveCore.tsx b/jarvis/ui/web/frontend/src/components/LiveCore.tsx
deleted file mode 100644
index e947202038..0000000000
--- a/jarvis/ui/web/frontend/src/components/LiveCore.tsx
+++ /dev/null
@@ -1,27 +0,0 @@
-import { cn } from "@/lib/utils";
-
-/**
- * The mark that says work is happening right now: an accent core inside two
- * rings that expand and fade away.
- *
- * It is the ONE live mark the product owns. The agent chat used to spin a
- * borrowed CLI asterisk instead (maintainer, 2026-08-25: "dieses komische
- * Denksymbol"), which read as a foreign glyph next to the home chat's core —
- * two answers to the same question on two screens of the same app.
- *
- * Under reduced motion the rings stand still behind the core, which still
- * reads as "in progress" beside the ticking clock (index.css).
- */
-export function LiveCore({ className }: { className?: string }) {
- return (
- <span
- className={cn("relative flex h-2.5 w-2.5 shrink-0", className)}
- aria-hidden
- data-testid="live-core"
- >
- <span className="thinking-ring absolute inline-flex h-full w-full rounded-full bg-primary/50" />
- <span className="thinking-ring absolute inline-flex h-full w-full rounded-full bg-primary/50 [animation-delay:0.9s]" />
- <span className="thinking-core relative inline-flex h-2.5 w-2.5 rounded-full bg-primary" />
- </span>
- );
-}
diff --git a/jarvis/ui/web/frontend/src/components/ThinkingTrace.tsx b/jarvis/ui/web/frontend/src/components/ThinkingTrace.tsx
index 658a1e65b7..f9aec8b3b7 100644
--- a/jarvis/ui/web/frontend/src/components/ThinkingTrace.tsx
+++ b/jarvis/ui/web/frontend/src/components/ThinkingTrace.tsx
@@ -31,7 +31,6 @@ import type {
} from "@/lib/thinkingSteps";
import { cn } from "@/lib/utils";
import { useT } from "@/i18n";
-import { LiveCore } from "@/components/LiveCore";
/** Rows visible in the live card — older ones collapse into a "+N" row. */
const VISIBLE_STEPS = 5;
@@ -166,6 +165,17 @@ function StepRail({
);
}
+/** Pulsing gold core in the card header — two expanding rings + glow dot. */
+function CoreOrb() {
+ return (
+ <span className="relative flex h-2.5 w-2.5 shrink-0" aria-hidden>
+ <span className="thinking-ring absolute inline-flex h-full w-full rounded-full bg-primary/50" />
+ <span className="thinking-ring absolute inline-flex h-full w-full rounded-full bg-primary/50 [animation-delay:0.9s]" />
+ <span className="thinking-core relative inline-flex h-2.5 w-2.5 rounded-full bg-primary" />
+ </span>
+ );
+}
+
/** The live card rendered in the transcript while `chatThinking` is true. */
export function ThinkingTrace() {
const t = useT();
@@ -192,7 +202,7 @@ export function ThinkingTrace() {
/>
<div className="relative flex items-center gap-2">
- <LiveCore />
+ <CoreOrb />
<span className="font-mono text-[10px] uppercase tracking-[0.14em] text-primary">
{assistantName}
</span>
diff --git a/jarvis/ui/web/frontend/src/components/agentchat/ChatAttachmentStrip.tsx b/jarvis/ui/web/frontend/src/components/agentchat/ChatAttachmentStrip.tsx
deleted file mode 100644
index 28cd05cc03..0000000000
--- a/jarvis/ui/web/frontend/src/components/agentchat/ChatAttachmentStrip.tsx
+++ /dev/null
@@ -1,92 +0,0 @@
-import { FileText, ImageIcon, Loader2, X } from "lucide-react";
-
-import type { ChatAttachment } from "@/lib/agentChatApi";
-import { fill, useT } from "@/i18n";
-
-/**
- * The files waiting to go in with the next message.
- *
- * Each chip says what was actually LEARNED from the file, not merely that one
- * is attached. That distinction is the whole feature: "screenshot.png" tells
- * the person nothing about whether the model will be able to see it, while
- * "described" and "not described" are the two outcomes they need to tell apart
- * BEFORE pressing Send — and the second happens for real, on any install whose
- * providers cannot see images.
- *
- * A near-twin of the Agentic IDE's terminal strip
- * (components/agentic/PromptAttachments) and deliberately not shared with it:
- * that one is hardcoded English, which is right inside a terminal composer
- * whose every other label is too, and wrong in a chat that speaks the app's
- * language everywhere else.
- */
-export function ChatAttachmentStrip({
- attachments,
- analyzing,
- onRemove,
-}: {
- attachments: ChatAttachment[];
- analyzing: number;
- onRemove: (name: string) => void;
-}) {
- const t = useT();
- if (attachments.length === 0 && analyzing === 0) return null;
- return (
- <div
- data-testid="chat-attachments"
- className="flex max-h-20 shrink-0 flex-wrap items-center gap-1.5 overflow-y-auto px-1 scrollbar-jarvis"
- >
- {attachments.map((item) => {
- const read = item.described_by !== "none" && item.detail.length > 0;
- return (
- <span
- key={item.name}
- data-testid={`chat-attachment-${item.name}`}
- title={
- read
- ? `${item.detail.slice(0, 400)}${item.detail.length > 400 ? "…" : ""}`
- : item.note || item.name
- }
- className={
- "flex items-center gap-1.5 rounded-md border px-2 py-1 text-[11px] " +
- (read
- ? "border-primary/40 bg-primary/10 text-foreground"
- : "border-border text-muted-foreground")
- }
- >
- {item.kind === "image" ? (
- <ImageIcon className="h-3 w-3 shrink-0" aria-hidden />
- ) : (
- <FileText className="h-3 w-3 shrink-0" aria-hidden />
- )}
- <span className="max-w-[12rem] truncate font-mono">{item.name}</span>
- <span className="shrink-0 text-[10px] text-muted-foreground">
- {read
- ? item.described_by === "vision"
- ? t("agent_chat.attach_described")
- : t("agent_chat.attach_text_read")
- : t("agent_chat.attach_not_described")}
- </span>
- <button
- type="button"
- aria-label={fill(t("agent_chat.attach_remove"), { name: item.name })}
- data-testid={`chat-attachment-remove-${item.name}`}
- onClick={() => onRemove(item.name)}
- className="shrink-0 rounded text-muted-foreground transition-colors hover:text-destructive"
- >
- <X className="h-3 w-3" />
- </button>
- </span>
- );
- })}
- {analyzing > 0 && (
- <span
- data-testid="chat-attachment-working"
- className="flex items-center gap-1.5 rounded-md border border-dashed border-border px-2 py-1 text-[11px] text-muted-foreground"
- >
- <Loader2 className="h-3 w-3 animate-spin" aria-hidden />
- {t("agent_chat.attach_working")}
- </span>
- )}
- </div>
- );
-}
diff --git a/jarvis/ui/web/frontend/src/components/agentchat/chatAttachments.test.tsx b/jarvis/ui/web/frontend/src/components/agentchat/chatAttachments.test.tsx
deleted file mode 100644
index c34c6d8132..0000000000
--- a/jarvis/ui/web/frontend/src/components/agentchat/chatAttachments.test.tsx
+++ /dev/null
@@ -1,302 +0,0 @@
-import { act, cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-
-import { AgentComposer } from "@/components/agentchat/AgentComposer";
-import { AgentChatStoreProvider } from "@/components/agentchat/AgentChatStoreContext";
-import { EMPTY_TIMELINE, reduceEvent } from "@/components/agentchat/reduce";
-import { useFileDropGuard } from "@/hooks/useFileDropGuard";
-import { useAgentChatStore } from "@/store/agentChat";
-import { useEventStore } from "@/store/events";
-import type { AgentChatCatalog } from "@/lib/agentChatApi";
-
-/**
- * Files in the chat composer — the drop, the paste, and what travels with the
- * message.
- *
- * The two chats (the front page and the Agentic IDE's chat mode) share this
- * one composer, so everything asserted here holds for both. What is under test
- * is that a file reaches the backend at all and that its CONTENTS ride along
- * with the sentence: a chat can be answered by a coding CLI or a text-only
- * model, and a bare path leaves those with a filename and a pronoun.
- */
-
-const CATALOG: AgentChatCatalog = {
- default_cwd: "C:\\work",
- shell: "pwsh",
- providers: [
- {
- id: "claude-api",
- label: "Anthropic Claude",
- family: "claude",
- runner: "claude-cli",
- models_source: "curated",
- curated_models: [{ id: "claude-opus-5", label: "Claude Opus 5" }],
- default_model: "",
- keyless: false,
- native_resume: true,
- effort_levels: ["low", "high"],
- default_effort: "high",
- permission_modes: [{ id: "default", label: "Ask before acting", description: "" }],
- default_permission_mode: "default",
- cli_installed: true,
- },
- ],
-};
-
-const ATTACHMENT = {
- name: "shot.png",
- reference: '".jarvis/drops/shot.png"',
- kind: "image" as const,
- detail: "A composer with no attach button.",
- described_by: "vision" as const,
- note: "",
-};
-
-function seed(overrides: Record<string, unknown> = {}) {
- useAgentChatStore.setState({
- catalog: CATALOG,
- connections: [{ jarvis: "claude-api", key_set: true, is_active_brain: true }],
- catalogError: null,
- backendOutdated: false,
- liveModels: {},
- sessions: [],
- activeSessionId: "s-1",
- activeSession: null,
- timeline: EMPTY_TIMELINE,
- draft: {
- provider: "claude-api",
- model: "",
- effort: "high",
- permissionMode: "default",
- buildMode: "default",
- cwd: "C:\\work",
- },
- busy: false,
- lastError: null,
- loadCatalog: async () => {},
- loadSessions: async () => {},
- loadModels: async () => {},
- ...overrides,
- });
-}
-
-function composer() {
- return render(
- <AgentChatStoreProvider store={useAgentChatStore}>
- <AgentComposer />
- </AgentChatStoreProvider>,
- );
-}
-
-/** A DataTransfer stand-in: jsdom's own carries neither files nor types. */
-function transfer(files: File[]) {
- return {
- files,
- items: files.map((file) => ({ kind: "file", type: file.type, getAsFile: () => file })),
- types: files.length ? ["Files"] : [],
- getData: () => "",
- dropEffect: "none",
- };
-}
-
-describe("chat composer attachments", () => {
- let fetchMock: ReturnType<typeof vi.fn>;
-
- beforeEach(() => {
- window.localStorage.clear();
- useEventStore.setState({ connected: true, wsWarming: false, assistantName: "Jarvis" });
- seed();
- fetchMock = vi.fn(async (url: string) => {
- if (String(url).includes("/api/agent-chat/attachments")) {
- return {
- ok: true,
- status: 200,
- json: async () => ({ attachments: [ATTACHMENT], cwd: "C:\\work" }),
- } as Response;
- }
- return { ok: true, status: 200, json: async () => ({ turn_id: "t-1" }) } as Response;
- });
- vi.stubGlobal("fetch", fetchMock);
- });
-
- afterEach(() => {
- cleanup();
- vi.unstubAllGlobals();
- vi.restoreAllMocks();
- });
-
- it("takes a pasted image and shows what was read from it", async () => {
- composer();
- const box = document.querySelector("textarea[data-jarvis-chat-input]") as HTMLTextAreaElement;
- const png = new File([new Uint8Array([1, 2, 3])], "image.png", { type: "image/png" });
-
- await act(async () => {
- fireEvent.paste(box, { clipboardData: transfer([png]) });
- });
-
- await waitFor(() => expect(screen.getByTestId("chat-attachment-shot.png")).toBeDefined());
- // The chip says the model could SEE it — that is the outcome a person has
- // to be able to read before pressing Send.
- expect(screen.getByTestId("chat-attachment-shot.png").textContent).toContain("described");
-
- const [url, init] = fetchMock.mock.calls.find(([u]) =>
- String(u).includes("/attachments"),
- ) as [string, RequestInit];
- expect(url).toContain("/api/agent-chat/attachments");
- expect((init.body as FormData).get("session_id")).toBe("s-1");
- });
-
- it("leaves a pasted TEXT alone so ordinary copy-paste keeps working", async () => {
- composer();
- const box = document.querySelector("textarea[data-jarvis-chat-input]") as HTMLTextAreaElement;
-
- const event = new Event("paste", { bubbles: true, cancelable: true });
- Object.defineProperty(event, "clipboardData", { value: transfer([]) });
- await act(async () => {
- box.dispatchEvent(event);
- });
-
- // Not claimed, not prevented: the browser inserts the text itself.
- expect(event.defaultPrevented).toBe(false);
- expect(fetchMock.mock.calls.some(([u]) => String(u).includes("/attachments"))).toBe(false);
- });
-
- it("takes a dropped file and arms the drop overlay while the drag is over", async () => {
- composer();
- const card = screen.getByTestId("agent-composer");
- const png = new File([new Uint8Array([1])], "shot.png", { type: "image/png" });
-
- fireEvent.dragEnter(card, { dataTransfer: transfer([png]) });
- expect(screen.getByTestId("composer-drop-overlay")).toBeDefined();
-
- await act(async () => {
- fireEvent.drop(card, { dataTransfer: transfer([png]) });
- });
-
- await waitFor(() => expect(screen.getByTestId("chat-attachment-shot.png")).toBeDefined());
- expect(screen.queryByTestId("composer-drop-overlay")).toBeNull();
- });
-
- it("sends the attachments with the sentence and then holds none", async () => {
- const send = vi.fn(async () => {});
- seed({ send });
- composer();
- const box = document.querySelector("textarea[data-jarvis-chat-input]") as HTMLTextAreaElement;
- const png = new File([new Uint8Array([1])], "image.png", { type: "image/png" });
-
- await act(async () => {
- fireEvent.paste(box, { clipboardData: transfer([png]) });
- });
- await waitFor(() => expect(screen.getByTestId("chat-attachment-shot.png")).toBeDefined());
-
- fireEvent.change(box, { target: { value: "what is wrong here" } });
- await act(async () => {
- fireEvent.click(screen.getByTestId("composer-send"));
- });
-
- expect(send).toHaveBeenCalledWith("what is wrong here", [ATTACHMENT]);
- // Cleared on send: the next message must not silently re-send the picture.
- expect(screen.queryByTestId("chat-attachment-shot.png")).toBeNull();
- });
-
- it("lets a picture alone be the whole message", async () => {
- const send = vi.fn(async () => {});
- seed({ send });
- composer();
- const box = document.querySelector("textarea[data-jarvis-chat-input]") as HTMLTextAreaElement;
- const png = new File([new Uint8Array([1])], "image.png", { type: "image/png" });
-
- await act(async () => {
- fireEvent.paste(box, { clipboardData: transfer([png]) });
- });
- await waitFor(() => expect(screen.getByTestId("chat-attachment-shot.png")).toBeDefined());
-
- await act(async () => {
- fireEvent.click(screen.getByTestId("composer-send"));
- });
- expect(send).toHaveBeenCalledWith("", [ATTACHMENT]);
- });
-});
-
-describe("the timeline's receipt for a message that carried files", () => {
- it("shows the sentence that was typed, not the composed prompt", () => {
- const tl = reduceEvent(EMPTY_TIMELINE, {
- seq: 1,
- ts_ms: 10,
- kind: "user_message",
- payload: {
- text: "what is wrong here\n\n<attachment name=\"shot.png\">…</attachment>",
- typed: "what is wrong here",
- attachments: [{ name: "shot.png", kind: "image", described_by: "vision" }],
- },
- });
- const item = tl.items[0];
- expect(item.type).toBe("user");
- if (item.type !== "user") return;
- expect(item.text).toBe("what is wrong here");
- expect(item.attachments).toEqual([
- { name: "shot.png", kind: "image", describedBy: "vision" },
- ]);
- });
-
- it("leaves an ordinary message exactly as it was", () => {
- const tl = reduceEvent(EMPTY_TIMELINE, {
- seq: 1,
- ts_ms: 10,
- kind: "user_message",
- payload: { text: "hello" },
- });
- const item = tl.items[0];
- if (item.type !== "user") throw new Error("expected a user item");
- expect(item.text).toBe("hello");
- expect(item.attachments).toEqual([]);
- });
-});
-
-describe("the app-wide file drop guard", () => {
- function Guarded() {
- useFileDropGuard();
- return <div data-testid="page">nothing here takes files</div>;
- }
-
- afterEach(cleanup);
-
- /** A drop event carrying `types`, with `preventDefault` observable. */
- function dropEvent(types: string[]) {
- const event = new Event("drop", { bubbles: true, cancelable: true });
- Object.defineProperty(event, "dataTransfer", {
- value: { ...transfer([]), types },
- });
- const prevent = vi.spyOn(event, "preventDefault");
- return { event, prevent };
- }
-
- it("swallows a file dropped on chrome that has no drop target", () => {
- render(<Guarded />);
- const { event, prevent } = dropEvent(["Files"]);
- window.dispatchEvent(event);
- // Prevented = the browser will NOT navigate away to the file, which inside
- // the desktop shell would take the whole app with it.
- expect(prevent).toHaveBeenCalled();
- expect(event.defaultPrevented).toBe(true);
- });
-
- it("keeps its hands off a drop a real target already claimed", () => {
- render(<Guarded />);
- const { event, prevent } = dropEvent(["Files"]);
- event.preventDefault(); // what a drop zone does, below window
- prevent.mockClear();
- window.dispatchEvent(event);
- // The guard saw `defaultPrevented` and stood down — it never touches an
- // event a target is already handling.
- expect(prevent).not.toHaveBeenCalled();
- });
-
- it("leaves dragged text and links to the browser", () => {
- render(<Guarded />);
- const { event, prevent } = dropEvent(["text/plain"]);
- window.dispatchEvent(event);
- expect(prevent).not.toHaveBeenCalled();
- expect(event.defaultPrevented).toBe(false);
- });
-});
diff --git a/jarvis/ui/web/frontend/src/components/agentchat/useChatAttachments.ts b/jarvis/ui/web/frontend/src/components/agentchat/useChatAttachments.ts
deleted file mode 100644
index 822455c7be..0000000000
--- a/jarvis/ui/web/frontend/src/components/agentchat/useChatAttachments.ts
+++ /dev/null
@@ -1,166 +0,0 @@
-/**
- * Files waiting to go in with the next chat message — the drop, the paste and
- * the paperclip.
- *
- * The Agentic IDE's terminal composer has taken files since 2026-08
- * (components/agentic/PromptAttachments). The two CHATS — the front page and
- * the IDE's chat mode, which share one composer — never did: a dropped
- * screenshot landed on a bare `<textarea>`, where the browser's own default is
- * to NAVIGATE to the file, replacing the whole app with the picture. A gesture
- * that works one click away and destroys the view here reads as the app being
- * broken, not as two surfaces with different features (maintainer, 2026-08-24).
- *
- * The pieces are deliberately the terminal path's own — the same drag tracking
- * (`usePaneFileDrag`), the same payload extraction (`paneDrop`), the same
- * desktop-shell path resolution (`waitForNativeDrop`) — so the two surfaces
- * cannot drift into disagreeing about what a drop is. Only the endpoint
- * differs: a chat has no pane to type a path into, so the files are HELD here
- * and travel with the sentence when it is sent.
- */
-import { useCallback, useState } from "react";
-
-import {
- extractPaneDrop,
- extractPasteFiles,
- isEmptyPayload,
- nameClipboardFile,
- type PaneDropPayload,
-} from "@/components/agentic/paneDrop";
-import { usePaneFileDrag } from "@/components/agentic/paneFileDrag";
-import { waitForNativeDrop } from "@/lib/nativeDrop";
-import { attachChatFiles, type AgentChatSurface, type ChatAttachment } from "@/lib/agentChatApi";
-
-export interface ChatAttachments {
- /** What will travel with the next message. */
- attachments: ChatAttachment[];
- /** How many files are being read right now — 0 when nothing is in flight. */
- analyzing: number;
- /** True while a file drag hovers the composer; drives the drop styling. */
- dragging: boolean;
- /** Spread onto the element that should accept drops. */
- dragHandlers: ReturnType<typeof usePaneFileDrag>["handlers"];
- /** Attach files chosen by hand (the paperclip) or read off the clipboard. */
- attachFiles: (files: File[]) => void;
- /** Put on the text box: claims a pasted IMAGE, never a pasted text. */
- onPaste: (event: React.ClipboardEvent) => void;
- remove: (name: string) => void;
- clear: () => void;
-}
-
-/**
- * Hold files for one chat's next message.
- *
- * `onProblem` is where the caller puts its own error line — this hook does not
- * decide how a surface reports things. It DOES decide how bad the news is: a
- * drop that carried nothing usable is a warning about what was dragged, while
- * an attach that threw is an error about the app, and collapsing the two
- * buries the second.
- */
-export function useChatAttachments(
- target: {
- sessionId: string | null;
- cwd: string;
- provider: string;
- surface: AgentChatSurface;
- },
- onProblem: (message: string, severity: "warning" | "error") => void,
-): ChatAttachments {
- const [attachments, setAttachments] = useState<ChatAttachment[]>([]);
- const [analyzing, setAnalyzing] = useState(0);
- const { sessionId, cwd, provider, surface } = target;
-
- const attach = useCallback(
- async (payload: PaneDropPayload) => {
- if (isEmptyPayload(payload)) return;
- setAnalyzing((n) => n + 1);
- try {
- const found = await attachChatFiles({
- files: payload.files,
- paths: payload.paths,
- sessionId,
- cwd,
- provider,
- surface,
- });
- if (found.length === 0) {
- onProblem("That drop carried nothing this chat could use.", "warning");
- return;
- }
- // Keyed by name so the same file attached twice is held once — a
- // repeated reference has the model read it again for nothing.
- setAttachments((prev) => [
- ...prev,
- ...found.filter((item) => !prev.some((held) => held.name === item.name)),
- ]);
- } catch (e) {
- onProblem((e as Error).message, "error");
- } finally {
- setAnalyzing((n) => Math.max(0, n - 1));
- }
- },
- [sessionId, cwd, provider, surface, onProblem],
- );
-
- const { dragging, handlers: dragHandlers } = usePaneFileDrag(
- useCallback(
- (dt: DataTransfer) => {
- // Both reads happen BEFORE any await, and they have to: a DataTransfer
- // empties the moment this handler returns, and the desktop shell only
- // answers a listener that was already in place when the drop happened.
- const payload = extractPaneDrop(dt);
- void waitForNativeDrop().then((detail) => {
- if (!detail?.paths.length) return void attach(payload);
- // Inside the desktop shell the host knows where the file really
- // lies. Prefer that over uploading its bytes — same file, no copy —
- // and drop the byte copies the shell just accounted for so nothing
- // is attached twice.
- const named = new Set(detail.names.map((n) => n.toLowerCase()));
- return void attach({
- paths: Array.from(new Set([...payload.paths, ...detail.paths])),
- files: payload.files.filter((f) => !named.has(f.name.toLowerCase())),
- });
- });
- },
- [attach],
- ),
- );
-
- const attachFiles = useCallback(
- (files: File[]) => {
- if (files.length > 0) void attach({ paths: [], files });
- },
- [attach],
- );
-
- const onPaste = useCallback(
- (event: React.ClipboardEvent) => {
- // Text paste belongs to the browser and must keep working — this only
- // claims what a text box would otherwise DISCARD: an image on the
- // clipboard, which is what PrintScreen and Ctrl+V produce.
- const files = extractPasteFiles(event.clipboardData).map((f) =>
- nameClipboardFile(f, "chat"),
- );
- if (files.length === 0) return;
- event.preventDefault();
- void attach({ paths: [], files });
- },
- [attach],
- );
-
- const remove = useCallback((name: string) => {
- setAttachments((prev) => prev.filter((a) => a.name !== name));
- }, []);
-
- const clear = useCallback(() => setAttachments([]), []);
-
- return {
- attachments,
- analyzing,
- dragging,
- dragHandlers,
- attachFiles,
- onPaste,
- remove,
- clear,
- };
-}
diff --git a/jarvis/ui/web/frontend/src/components/agentchat/usePasteRescue.test.tsx b/jarvis/ui/web/frontend/src/components/agentchat/usePasteRescue.test.tsx
deleted file mode 100644
index a016ae70c3..0000000000
--- a/jarvis/ui/web/frontend/src/components/agentchat/usePasteRescue.test.tsx
+++ /dev/null
@@ -1,112 +0,0 @@
-import { act, cleanup, fireEvent, render } from "@testing-library/react";
-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-
-import { usePasteRescue } from "@/components/agentchat/usePasteRescue";
-
-/**
- * Ctrl+V where the embedded browser never sends a `paste` event.
- *
- * The behaviour that matters is the NEGATIVE one: in a browser that pastes
- * normally this hook must do nothing at all, or every paste lands twice. So
- * both halves are pinned — the rescue fires when the event is missing, and
- * stays out of the way when it is not.
- */
-
-function Field({ onRescued }: { onRescued?: () => void }) {
- const rescue = usePasteRescue();
- return (
- <textarea
- data-testid="field"
- defaultValue=""
- onKeyDown={(e) => rescue.onKeyDown(e)}
- onPaste={() => {
- rescue.onPaste();
- onRescued?.();
- }}
- />
- );
-}
-
-describe("usePasteRescue", () => {
- let fetchMock: ReturnType<typeof vi.fn>;
-
- beforeEach(() => {
- vi.useFakeTimers();
- fetchMock = vi.fn(async (url: string, init?: RequestInit) => {
- if (String(url).includes("/api/clipboard/text") && (init?.method ?? "GET") === "GET") {
- return { ok: true, status: 200, json: async () => ({ text: "from the clipboard" }) } as Response;
- }
- return { ok: false, status: 404, json: async () => ({}) } as Response;
- });
- vi.stubGlobal("fetch", fetchMock);
- });
-
- afterEach(() => {
- cleanup();
- vi.useRealTimers();
- vi.unstubAllGlobals();
- vi.restoreAllMocks();
- });
-
- it("puts the clipboard text in when no paste event follows the keystroke", async () => {
- const { getByTestId } = render(<Field />);
- const field = getByTestId("field") as HTMLTextAreaElement;
- field.focus();
-
- fireEvent.keyDown(field, { key: "v", ctrlKey: true });
- // No `paste` event — this is the embedded browser that swallows it.
- await act(async () => {
- await vi.advanceTimersByTimeAsync(300);
- });
-
- expect(fetchMock).toHaveBeenCalled();
- expect(field.value).toBe("from the clipboard");
- });
-
- it("does nothing at all when the browser delivers the paste itself", async () => {
- const { getByTestId } = render(<Field />);
- const field = getByTestId("field") as HTMLTextAreaElement;
- field.focus();
-
- fireEvent.keyDown(field, { key: "v", ctrlKey: true });
- fireEvent.paste(field, { clipboardData: { items: [], files: [], types: [] } });
- await act(async () => {
- await vi.advanceTimersByTimeAsync(300);
- });
-
- // Never read the clipboard, never inserted: a second insertion here is
- // exactly the double paste this timing exists to avoid.
- expect(fetchMock).not.toHaveBeenCalled();
- expect(field.value).toBe("");
- });
-
- it("ignores every keystroke that is not Ctrl/Cmd+V", async () => {
- const { getByTestId } = render(<Field />);
- const field = getByTestId("field") as HTMLTextAreaElement;
-
- fireEvent.keyDown(field, { key: "v" });
- fireEvent.keyDown(field, { key: "c", ctrlKey: true });
- fireEvent.keyDown(field, { key: "v", ctrlKey: true, altKey: true });
- await act(async () => {
- await vi.advanceTimersByTimeAsync(300);
- });
-
- expect(fetchMock).not.toHaveBeenCalled();
- });
-
- it("leaves an empty clipboard alone rather than reporting a failure", async () => {
- vi.stubGlobal(
- "fetch",
- vi.fn(async () => ({ ok: true, status: 200, json: async () => ({ text: "" }) }) as Response),
- );
- const { getByTestId } = render(<Field />);
- const field = getByTestId("field") as HTMLTextAreaElement;
- field.focus();
-
- fireEvent.keyDown(field, { key: "v", ctrlKey: true });
- await act(async () => {
- await vi.advanceTimersByTimeAsync(300);
- });
- expect(field.value).toBe("");
- });
-});
diff --git a/jarvis/ui/web/frontend/src/components/agentchat/usePasteRescue.ts b/jarvis/ui/web/frontend/src/components/agentchat/usePasteRescue.ts
deleted file mode 100644
index 7675cf2089..0000000000
--- a/jarvis/ui/web/frontend/src/components/agentchat/usePasteRescue.ts
+++ /dev/null
@@ -1,85 +0,0 @@
-import { useCallback, useEffect, useRef } from "react";
-
-import { robustPaste } from "@/lib/clipboard";
-import { captureEditSnapshot, pasteInto } from "@/lib/editActions";
-
-/**
- * Make Ctrl+V put text in the box even where the embedded browser never sends
- * a `paste` event.
- *
- * In a real browser this hook does nothing at all, and that is the design. A
- * `<textarea>` pastes on its own; nothing here competes with it.
- *
- * The desktop shell is the reason it exists. Its WebView already withholds
- * `clipboard-read` — measured in 2026-07, `navigator.clipboard.readText()`
- * inside it never settles, resolved or rejected, which is why the right-click
- * menu reads the clipboard through the host process instead (lib/clipboard).
- * A build that also declines to deliver the `paste` event leaves Ctrl+V doing
- * nothing whatsoever in a text box, with no error anywhere to explain it.
- *
- * ## How it can tell the difference
- *
- * A real paste delivers its event in the SAME task as the keystroke. So the
- * keystroke arms a one-shot timer and the `paste` event disarms it; if the
- * timer still fires, no paste was delivered and the text is fetched through
- * the host route and inserted at the caret that was saved when the key went
- * down. The window is deliberately short — long enough to outlast a busy main
- * thread, far shorter than a person's next keystroke — because the failure
- * mode to avoid is pasting twice.
- *
- * `pasteInto` goes through `insertText`, so the caret, the undo history and
- * React's controlled value all survive (lib/editActions).
- */
-
-/**
- * How long a real `paste` has to arrive before the keystroke counts as
- * unanswered. Browsers deliver it synchronously; this allows for a main thread
- * busy with a streaming turn.
- */
-const RESCUE_AFTER_MS = 150;
-
-export interface PasteRescue {
- /** Call from the field's `onKeyDown`, before anything else. */
- onKeyDown: (event: React.KeyboardEvent<HTMLElement>) => void;
- /** Call from the field's `onPaste` — this is what proves the event arrives. */
- onPaste: () => void;
-}
-
-export function usePasteRescue(): PasteRescue {
- const timerRef = useRef<number | undefined>(undefined);
-
- const disarm = useCallback(() => {
- if (timerRef.current !== undefined) {
- window.clearTimeout(timerRef.current);
- timerRef.current = undefined;
- }
- }, []);
-
- // A component unmounting mid-window must not paste into a field that is gone.
- useEffect(() => disarm, [disarm]);
-
- const onKeyDown = useCallback(
- (event: React.KeyboardEvent<HTMLElement>) => {
- const key = event.key.toLowerCase();
- if (key !== "v" || !(event.ctrlKey || event.metaKey) || event.altKey) return;
- // Captured now: by the time the timer fires the caret may have moved,
- // and the position the text belongs at is this one.
- const snapshot = captureEditSnapshot(event.currentTarget);
- if (!snapshot.editable) return;
- disarm();
- timerRef.current = window.setTimeout(() => {
- timerRef.current = undefined;
- void (async () => {
- const text = await robustPaste();
- // Null = no route could read the clipboard; empty = nothing on it.
- // Neither is an error worth a message: the person pressed a key and
- // the box stayed as it was, which is what an empty clipboard means.
- if (text) pasteInto(snapshot, text);
- })();
- }, RESCUE_AFTER_MS);
- },
- [disarm],
- );
-
- return { onKeyDown, onPaste: disarm };
-}
diff --git a/jarvis/ui/web/frontend/src/components/agentic/FolderPicker.test.tsx b/jarvis/ui/web/frontend/src/components/agentic/FolderPicker.test.tsx
index 18f63a83cb..ba157e61e3 100644
--- a/jarvis/ui/web/frontend/src/components/agentic/FolderPicker.test.tsx
+++ b/jarvis/ui/web/frontend/src/components/agentic/FolderPicker.test.tsx
@@ -9,7 +9,6 @@ vi.mock("@/lib/agenticIdeApi", () => ({
resolveDroppedFolder: vi.fn(),
fetchNativePickerSupport: vi.fn(),
openNativePicker: vi.fn(),
- createFolder: vi.fn(),
}));
import {
@@ -17,7 +16,6 @@ import {
extractDropPayload,
isAbsolutePath,
joinPath,
- looksLikePath,
normalizeTypedPath,
resolveTypedPath,
separatorOf,
@@ -302,7 +300,7 @@ describe("the system folder window", () => {
await waitFor(() => expect(onSelect).toHaveBeenCalledWith("C:\\work\\shop"));
// And the in-page browser follows it there, so both views agree.
- expect(api.fetchFolders).toHaveBeenCalledWith("C:\\work\\shop", false);
+ expect(api.fetchFolders).toHaveBeenCalledWith("C:\\work\\shop");
});
it("says a window is waiting, because it can open behind the app", async () => {
@@ -500,143 +498,3 @@ describe("typing a path", () => {
expect(onSelect).not.toHaveBeenCalled();
});
});
-
-describe("a path in the search field", () => {
- it("opens that folder instead of searching the machine for its name", async () => {
- // Reported: `C:\Users\me\.claude` typed into the search found nothing —
- // no folder is CALLED that — and the wizard looked broken.
- vi.mocked(api.fetchFolders).mockImplementation(async (target) =>
- target === "C:\\Users\\me\\.claude"
- ? {
- path: "C:\\Users\\me\\.claude",
- parent: "C:\\Users\\me",
- entries: [
- {
- name: "skills",
- path: "C:\\Users\\me\\.claude\\skills",
- is_project: false,
- is_repo: false,
- },
- ],
- device_name: "Box",
- }
- : LISTING,
- );
- const onSelect = vi.fn();
- render(<FolderPicker selected={null} onSelect={onSelect} />);
- await screen.findByText("webshop");
-
- fireEvent.change(screen.getByTestId("folder-search"), {
- target: { value: "C:\\Users\\me\\.claude" },
- });
-
- await waitFor(() => expect(onSelect).toHaveBeenCalledWith("C:\\Users\\me\\.claude"), {
- timeout: 2000,
- });
- expect(api.searchFolders).not.toHaveBeenCalled();
- // A dot-name asks for hidden folders by itself; nobody has to find the switch.
- expect(api.fetchFolders).toHaveBeenCalledWith("C:\\Users\\me\\.claude", true);
- expect(await screen.findByText("skills")).toBeTruthy();
- });
-
- it("reads a pasted prompt as the path inside it", () => {
- expect(normalizeTypedPath("PS C:\\Users\\me\\.claude>")).toBe("C:\\Users\\me\\.claude");
- expect(normalizeTypedPath("C:\\Users\\me\\.claude> ")).toBe("C:\\Users\\me\\.claude");
- expect(looksLikePath("C:\\Users\\me")).toBe(true);
- expect(looksLikePath("Desktop/shop")).toBe(true);
- expect(looksLikePath("~")).toBe(true);
- expect(looksLikePath("shop")).toBe(false);
- });
-
- it("offers to create the folder when the last segment does not exist yet", async () => {
- vi.mocked(api.fetchFolders).mockImplementation(async (target) =>
- target === "/home/ruben/newshop"
- ? {
- path: "/home/ruben/newshop",
- parent: "/home/ruben",
- entries: [],
- error: "There is no folder called /home/ruben/newshop.",
- device_name: "Box",
- }
- : { ...LISTING, path: "/home/ruben", parent: "/home" },
- );
- vi.mocked(api.createFolder).mockResolvedValue({
- folder: { name: "newshop", path: "/home/ruben/newshop", is_project: false, is_repo: false },
- error: null,
- });
- const onSelect = vi.fn();
- render(<FolderPicker selected={null} onSelect={onSelect} />);
- await screen.findByText("webshop");
-
- fireEvent.change(screen.getByTestId("folder-search"), {
- target: { value: "/home/ruben/newshop" },
- });
-
- const offer = await screen.findByTestId("create-offer", {}, { timeout: 2000 });
- expect(offer.textContent).toContain("newshop");
- // Nothing is chosen until the folder exists.
- expect(onSelect).not.toHaveBeenCalled();
-
- fireEvent.click(offer);
- await waitFor(() =>
- expect(api.createFolder).toHaveBeenCalledWith({ parent: "/home/ruben", name: "newshop" }),
- );
- await waitFor(() => expect(onSelect).toHaveBeenCalledWith("/home/ruben/newshop"));
- });
-});
-
-describe("a new folder", () => {
- it("is made in the folder on screen and becomes the selection", async () => {
- vi.mocked(api.fetchFolders).mockResolvedValue({
- ...LISTING,
- path: "/home/ruben",
- parent: "/home",
- });
- vi.mocked(api.createFolder).mockResolvedValue({
- folder: { name: "shop2", path: "/home/ruben/shop2", is_project: false, is_repo: false },
- error: null,
- });
- const onSelect = vi.fn();
- render(<FolderPicker selected={null} onSelect={onSelect} />);
- await screen.findByText("webshop");
-
- fireEvent.click(screen.getByTestId("new-folder"));
- fireEvent.change(screen.getByTestId("new-folder-name"), { target: { value: "shop2" } });
- fireEvent.submit(screen.getByTestId("new-folder-form"));
-
- await waitFor(() =>
- expect(api.createFolder).toHaveBeenCalledWith({ parent: "/home/ruben", name: "shop2" }),
- );
- await waitFor(() => expect(onSelect).toHaveBeenCalledWith("/home/ruben/shop2"));
- });
-
- it("shows why it could not be made and keeps the name for correcting", async () => {
- vi.mocked(api.createFolder).mockResolvedValue({
- folder: null,
- error: "A folder name cannot contain slashes. Type just the name.",
- });
- const onSelect = vi.fn();
- render(<FolderPicker selected={null} onSelect={onSelect} />);
- await screen.findByText("webshop");
-
- fireEvent.click(screen.getByTestId("new-folder"));
- fireEvent.change(screen.getByTestId("new-folder-name"), { target: { value: "a/b" } });
- fireEvent.submit(screen.getByTestId("new-folder-form"));
-
- expect(await screen.findByText(/cannot contain slashes/)).toBeTruthy();
- expect((screen.getByTestId("new-folder-name") as HTMLInputElement).value).toBe("a/b");
- expect(onSelect).not.toHaveBeenCalled();
- });
-});
-
-describe("hidden folders", () => {
- it("are listed only once the switch is on", async () => {
- render(<FolderPicker selected={null} onSelect={vi.fn()} />);
- await screen.findByText("webshop");
- expect(api.fetchFolders).toHaveBeenLastCalledWith(null, false);
-
- fireEvent.click(screen.getByTestId("toggle-hidden"));
-
- await waitFor(() => expect(api.fetchFolders).toHaveBeenLastCalledWith(null, true));
- });
-});
diff --git a/jarvis/ui/web/frontend/src/components/agentic/FolderPicker.tsx b/jarvis/ui/web/frontend/src/components/agentic/FolderPicker.tsx
index ac8ab20de4..bc3e5b3faa 100644
--- a/jarvis/ui/web/frontend/src/components/agentic/FolderPicker.tsx
+++ b/jarvis/ui/web/frontend/src/components/agentic/FolderPicker.tsx
@@ -9,20 +9,13 @@
* 2. **Recents** — the folders opened before, with their previous layout. One
* click and the launcher already knows how many terminals to open.
* 3. **Search** — type a name, get matches from anywhere under home and the
- * usual code directories. Faster than clicking down five levels. The same
- * field reads a PATH as a place, not a name: `C:\Users\me\.claude` opens
- * that folder on the spot instead of searching the disk for a folder called
- * that (which found nothing, and was reported as "search is broken").
- * 4. **Browsing** — the list, projects and repositories sorted first. Hidden
- * folders (`.claude`, `.config`) stay out of the way until asked for.
+ * usual code directories. Faster than clicking down five levels.
+ * 4. **Browsing** — the list, projects and repositories sorted first.
* 5. **Typing a path** — with completion, the way `cd` works in a terminal.
* 6. **Drag and drop** — drop a folder (or a file inside it) anywhere on the
* panel. Inside the desktop shell the host reports the real path
* (`waitForNativeDrop`); in a browser only the NAME is known, and the
* backend searches for it — see `extractDropPayload`.
- * 7. **A new folder** — a project that does not exist yet has nothing to pick.
- * "New folder" makes one inside the folder on screen, and a typed path that
- * is not a folder yet is offered for creation rather than only refused.
*
* The in-page browser is not a fallback for the system window, it is the floor:
* the system window opens on the machine the BACKEND runs on, so it is useless
@@ -52,12 +45,9 @@ import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import {
CornerDownLeft,
CornerLeftUp,
- Eye,
- EyeOff,
Folder,
FolderGit2,
FolderOpen,
- FolderPlus,
Loader2,
RefreshCw,
Search,
@@ -69,7 +59,6 @@ import { waitForNativeDrop } from "@/lib/nativeDrop";
import { useDragSessionEnd } from "./dragSessionEnd";
import { Button, Field, IconButton, SectionLabel } from "./controls";
import {
- createFolder,
fetchFolders,
fetchNativePickerSupport,
fetchRecents,
@@ -172,37 +161,11 @@ export function FolderPicker({
const [nativeOpen, setNativeOpen] = useState(false);
const [nativeNote, setNativeNote] = useState<string | null>(null);
- // Dot-folders are noise in a project list and the one thing someone opening
- // `.claude` needs — so they are a switch, off by default, and a typed name
- // that starts with a dot turns them on for that lookup by itself.
- const [showHidden, setShowHidden] = useState(false);
- const showHiddenRef = useRef(showHidden);
- showHiddenRef.current = showHidden;
-
- // The search field holding a path whose last segment is not a folder (yet):
- // the folder above it is on screen, filtered to names starting with this.
- const [pathLeaf, setPathLeaf] = useState<string | null>(null);
- // Where a folder that does not exist could be made, and what to call it.
- const [createOffer, setCreateOffer] = useState<{
- parent: string | null;
- name: string;
- } | null>(null);
- const [naming, setNaming] = useState(false);
- const [newName, setNewName] = useState("");
- const [creating, setCreating] = useState(false);
- const [createNote, setCreateNote] = useState<string | null>(null);
-
- // Read through a ref by the search effect: the launcher may hand in a fresh
- // callback every render, and an effect keyed on it would re-run — and
- // re-fetch — on each of its own state updates.
- const onSelectRef = useRef(onSelect);
- onSelectRef.current = onSelect;
-
- const load = useCallback(async (target: string | null, hidden?: boolean) => {
+ const load = useCallback(async (target: string | null) => {
setLoading(true);
setError(null);
try {
- const res = await fetchFolders(target, hidden ?? showHiddenRef.current);
+ const res = await fetchFolders(target);
setPath(res.path);
setParent(res.parent);
setEntries(res.entries);
@@ -263,69 +226,9 @@ export function FolderPicker({
.finally(() => setNativeOpen(false));
};
- /**
- * A path typed into the search field is a place to go, not a name to find.
- *
- * The folder is listed and becomes the selection when it exists. When it does
- * not, the folder ABOVE it is listed instead, narrowed to names starting with
- * the last segment — so a half-typed name completes on screen — and, once
- * nothing matches, creating it is offered. Nothing here is relative to the
- * folder that happened to be open: a typed path means exactly what it says.
- */
- const goToTypedPath = useCallback((typed: string) => {
- const { dir, leaf } = splitTypedPath(typed);
- const hidden = showHiddenRef.current || leaf.startsWith(".");
- return fetchFolders(typed, hidden).then(async (res) => {
- if (res.device_name) setDeviceName(res.device_name);
- if (!res.error) {
- setPath(res.path);
- setParent(res.parent);
- setEntries(res.entries);
- setPathLeaf(null);
- setCreateOffer(null);
- setError(null);
- if (res.path) onSelectRef.current(res.path);
- return;
- }
- if (!dir || !leaf) {
- setError(res.error);
- setPathLeaf(null);
- setCreateOffer(null);
- return;
- }
- const above = await fetchFolders(dir, hidden);
- if (above.error) {
- setError(above.error);
- setPathLeaf(null);
- setCreateOffer(null);
- return;
- }
- setPath(above.path);
- setParent(above.parent);
- setEntries(above.entries);
- setError(null);
- setPathLeaf(leaf);
- setCreateOffer({ parent: above.path, name: leaf });
- });
- }, []);
-
// Server-side search once the query is long enough; shorter input just filters
- // the folder list already on screen, which feels instant. A path goes its own
- // way (see `goToTypedPath`) and never reaches the name search.
+ // the folder list already on screen, which feels instant.
useEffect(() => {
- const typed = normalizeTypedPath(query);
- if (looksLikePath(typed)) {
- setSearchHits(null);
- setSearching(true);
- const handle = window.setTimeout(() => {
- goToTypedPath(typed)
- .catch((e) => setError((e as Error).message))
- .finally(() => setSearching(false));
- }, SEARCH_DEBOUNCE_MS);
- return () => window.clearTimeout(handle);
- }
- setPathLeaf(null);
- setCreateOffer(null);
const trimmed = query.trim();
if (trimmed.length < SEARCH_MIN) {
setSearchHits(null);
@@ -340,59 +243,22 @@ export function FolderPicker({
.finally(() => setSearching(false));
}, SEARCH_DEBOUNCE_MS);
return () => window.clearTimeout(handle);
- }, [query, goToTypedPath]);
+ }, [query]);
const visible = useMemo(() => {
if (searchHits !== null) return searchHits;
- if (pathLeaf !== null) {
- const needle = pathLeaf.toLowerCase();
- return entries.filter((e) => e.name.toLowerCase().startsWith(needle));
- }
- const typed = normalizeTypedPath(query);
- // A path on its way to being listed: the folder itself is what is shown,
- // not the list filtered by a string no folder is called.
- if (looksLikePath(typed)) return entries;
const needle = query.trim().toLowerCase();
if (!needle) return entries;
return entries.filter((e) => e.name.toLowerCase().includes(needle));
- }, [entries, query, searchHits, pathLeaf]);
+ }, [entries, query, searchHits]);
const open = (item: FolderItem) => {
onSelect(item.path);
setQuery("");
setSearchHits(null);
- setPathLeaf(null);
- setCreateOffer(null);
void load(item.path);
};
- /** Make the folder, then treat it like any other folder that was clicked. */
- const makeFolder = (parent: string | null, name: string) => {
- if (creating) return;
- setCreating(true);
- setCreateNote(null);
- createFolder({ parent, name })
- .then((res) => {
- if (res.error || !res.folder) {
- setCreateNote(res.error || "Could not create that folder.");
- return;
- }
- setNaming(false);
- setNewName("");
- setError(null);
- open(res.folder);
- })
- .catch((e) => setCreateNote((e as Error).message))
- .finally(() => setCreating(false));
- };
-
- const toggleHidden = () => {
- const next = !showHidden;
- setShowHidden(next);
- showHiddenRef.current = next;
- if (searchHits === null) void load(path, next);
- };
-
/**
* A typed path is checked before it is chosen. The old order — select first,
* then list — let "cd haral\.personal-jarvis" (not a folder anywhere) reach
@@ -405,22 +271,16 @@ export function FolderPicker({
if (!value) return;
setLoading(true);
setError(null);
- const { dir, leaf } = splitTypedPath(value);
- fetchFolders(value, showHiddenRef.current || leaf.startsWith("."))
+ fetchFolders(value)
.then((res) => {
if (res.device_name) setDeviceName(res.device_name);
if (res.error) {
setError(res.error);
- // Not a folder — but it could be one. The offer sits next to the
- // message, so a typo is corrected and a new project is created from
- // the same line.
- setCreateOffer(dir && leaf ? { parent: dir, name: leaf } : null);
return;
}
setPath(res.path);
setParent(res.parent);
setEntries(res.entries);
- setCreateOffer(null);
onSelect(res.path ?? value);
})
.catch((e) => setError((e as Error).message))
@@ -525,8 +385,8 @@ export function FolderPicker({
<Field
value={query}
onChange={(e) => setQuery(e.target.value)}
- placeholder="Search folders by name, or type a path…"
- aria-label="Search folders by name, or type a path"
+ placeholder="Search folders by name…"
+ aria-label="Search folders by name"
data-testid="folder-search"
className="w-full pl-8 pr-7"
spellCheck={false}
@@ -557,38 +417,6 @@ export function FolderPicker({
{nativeOpen ? "Window open…" : "Browse"}
</Button>
)}
- <Button
- onClick={() => {
- setNaming(true);
- setNewName("");
- setCreateNote(null);
- }}
- disabled={naming}
- data-testid="new-folder"
- title={`Make a new folder in ${path ?? "your home folder"}`}
- >
- <FolderPlus className="h-3.5 w-3.5" />
- New folder
- </Button>
- <IconButton
- label={showHidden ? "Hide hidden folders" : "Show hidden folders"}
- title={
- showHidden
- ? "Hidden folders (names starting with a dot) are shown"
- : "Also list hidden folders — names starting with a dot"
- }
- aria-pressed={showHidden}
- onClick={toggleHidden}
- disabled={loading}
- data-testid="toggle-hidden"
- className={cn(showHidden && "text-primary")}
- >
- {showHidden ? (
- <Eye className="h-4 w-4" />
- ) : (
- <EyeOff className="h-4 w-4" />
- )}
- </IconButton>
<IconButton
label="Go up one folder"
onClick={() => void load(parent)}
@@ -642,56 +470,6 @@ export function FolderPicker({
</p>
)}
- {/* --------------------------------------------------------- new folder */}
- {naming && (
- <form
- data-testid="new-folder-form"
- className="flex items-center gap-1.5 px-3 pb-2"
- onSubmit={(e) => {
- e.preventDefault();
- if (newName.trim()) makeFolder(path, newName);
- }}
- >
- <FolderPlus className="h-4 w-4 shrink-0 text-primary" />
- <Field
- autoFocus
- value={newName}
- onChange={(e) => setNewName(e.target.value)}
- onKeyDown={(e) => {
- if (e.key === "Escape") setNaming(false);
- }}
- placeholder={`Name of the new folder in ${path ?? "your home folder"}`}
- aria-label="Name of the new folder"
- data-testid="new-folder-name"
- className="min-w-0 flex-1"
- spellCheck={false}
- autoComplete="off"
- />
- <Button
- type="submit"
- variant="primary"
- disabled={creating || !newName.trim()}
- data-testid="new-folder-create"
- >
- {creating ? (
- <Loader2 className="h-3.5 w-3.5 animate-spin" />
- ) : (
- <FolderPlus className="h-3.5 w-3.5" />
- )}
- Create
- </Button>
- <IconButton
- label="Cancel new folder"
- onClick={() => {
- setNaming(false);
- setCreateNote(null);
- }}
- >
- <X className="h-4 w-4" />
- </IconButton>
- </form>
- )}
-
{/* --------------------------------------------------------------- list */}
<div className="min-h-[16rem] flex-1 overflow-y-auto scrollbar-jarvis border-y border-border/70">
{recents.length > 0 && !searchingMachine && (
@@ -759,42 +537,11 @@ export function FolderPicker({
</>
)}
- {/*
- The typed path's last segment is not a folder in the folder on
- screen, and nothing there starts with it either: the one thing left
- to do with that name is make it.
- */}
- {createOffer && pathLeaf !== null && visible.length === 0 && !searching && (
- <button
- type="button"
- data-testid="create-offer"
- onClick={() => makeFolder(createOffer.parent, createOffer.name)}
- disabled={creating}
- className="flex w-full items-center gap-2.5 px-3 py-2 text-left text-sm text-primary transition-colors hover:bg-secondary/60"
- >
- {creating ? (
- <Loader2 className="h-4 w-4 shrink-0 animate-spin" />
- ) : (
- <FolderPlus className="h-4 w-4 shrink-0" />
- )}
- <span className="min-w-0 flex-1">
- <span className="block truncate">
- Create folder “{createOffer.name}”
- </span>
- <span className="block truncate font-mono text-[10px] text-muted-foreground">
- in {createOffer.parent ?? "your home folder"}
- </span>
- </span>
- </button>
- )}
-
{visible.length === 0 && !loading && !searching ? (
<p className="px-3 py-4 text-sm text-muted-foreground">
{searchingMachine
? "No folder with that name was found."
- : pathLeaf !== null
- ? `No folder here starts with “${pathLeaf}”.`
- : "Nothing to list here — search above, drop a folder, or type its path below."}
+ : "Nothing to list here — search above, drop a folder, or type its path below."}
</p>
) : (
<ul>
@@ -856,37 +603,16 @@ export function FolderPicker({
</div>
{/* ------------------------------------------------------------- typing */}
- <PathInput base={path} showHidden={showHidden} onUse={usePath} />
+ <PathInput base={path} onUse={usePath} />
{/* ---------------------------------------------------------- reporting */}
- {(error || nativeNote || dropNote || createNote) && (
+ {(error || nativeNote || dropNote) && (
<div className="space-y-1 px-3 pb-3">
{error && (
<p className="text-xs text-destructive" role="alert">
{error}
</p>
)}
- {/* The path field's "no such folder", answered: make it. */}
- {error && createOffer && pathLeaf === null && (
- <Button
- onClick={() => makeFolder(createOffer.parent, createOffer.name)}
- disabled={creating}
- data-testid="create-offer"
- className="h-7 text-xs"
- >
- {creating ? (
- <Loader2 className="h-3.5 w-3.5 animate-spin" />
- ) : (
- <FolderPlus className="h-3.5 w-3.5" />
- )}
- Create folder “{createOffer.name}”
- </Button>
- )}
- {createNote && (
- <p className="text-xs text-destructive" role="alert">
- {createNote}
- </p>
- )}
{nativeNote && !nativeOpen && (
<p className="text-xs text-muted-foreground" role="alert">
{nativeNote}
@@ -959,9 +685,6 @@ export function joinPath(base: string, name: string): string {
export function normalizeTypedPath(raw: string): string {
let value = raw.trim();
value = value.replace(/^cd(?:\s+\/d)?(?:\s+|$)/i, "").trim();
- // A prompt copied whole — `PS C:\Users\me>` — is the path with a shell's
- // decoration on both ends; the decoration is not part of the folder.
- value = value.replace(/^PS\s+/, "").replace(/\s*>$/, "").trim();
const quoted = value.match(/^(["'])(.*)\1$/);
if (quoted) value = quoted[2].trim();
return value;
@@ -972,17 +695,6 @@ export function isAbsolutePath(value: string): boolean {
return /^(?:[a-zA-Z]:[\\/]|[\\/]|~)/.test(value);
}
-/**
- * Text that names a PLACE rather than a folder to look for.
- *
- * A root or a separator anywhere is the tell: nobody searches for a folder
- * called `Desktop\shop`, they mean the one at that path. A bare name stays a
- * search, which is what a search field is for.
- */
-export function looksLikePath(value: string): boolean {
- return isAbsolutePath(value) || /[\\/]/.test(value);
-}
-
/**
* The folder a typed path means, given the folder on screen.
*
@@ -1013,11 +725,9 @@ export function resolveTypedPath(raw: string, base: string | null): string {
*/
function PathInput({
base,
- showHidden,
onUse,
}: {
base: string | null;
- showHidden: boolean;
onUse: (value: string) => void;
}) {
const [value, setValue] = useState("");
@@ -1042,9 +752,7 @@ function PathInput({
}
let cancelled = false;
const handle = window.setTimeout(() => {
- // A dot-name completes against hidden folders whether or not they are
- // switched on: typing `.cl` is the request to see `.claude`.
- fetchFolders(lookupDir || null, showHidden || leaf.startsWith("."))
+ fetchFolders(lookupDir || null)
.then((res) => {
if (cancelled) return;
const needle = leaf.toLowerCase();
@@ -1063,7 +771,7 @@ function PathInput({
cancelled = true;
window.clearTimeout(handle);
};
- }, [lookupDir, leaf, value, base, showHidden]);
+ }, [lookupDir, leaf, value, base]);
/** Take a suggestion and leave the cursor ready for the next segment. */
const complete = (item: FolderItem) => {
diff --git a/jarvis/ui/web/frontend/src/components/agentic/PaneActivityPill.test.tsx b/jarvis/ui/web/frontend/src/components/agentic/PaneActivityPill.test.tsx
index 6e1f344499..aafe513ec9 100644
--- a/jarvis/ui/web/frontend/src/components/agentic/PaneActivityPill.test.tsx
+++ b/jarvis/ui/web/frontend/src/components/agentic/PaneActivityPill.test.tsx
@@ -30,13 +30,10 @@ describe("what the badge shows", () => {
expect(badge.getAttribute("data-icon")).toBe("spinner");
});
- it("shows an amber check mark for a pane that was given a job and has finished", () => {
- // A check, not a still dot: beside a row of spinners a dot read as "also
- // busy, just not animated", and the maintainer asked for an indicator
- // that says working or done (2026-08-27).
+ it("shows a still amber dot for a pane that was given a job and has stopped", () => {
const badge = pill({ status: "live", activity: "waiting", worked: true });
expect(badge.textContent).toBe("");
- expect(badge.getAttribute("data-icon")).toBe("check");
+ expect(badge.getAttribute("data-icon")).toBe("dot");
expect(badge.className).toContain("text-amber-400");
});
diff --git a/jarvis/ui/web/frontend/src/components/agentic/PaneActivityPill.tsx b/jarvis/ui/web/frontend/src/components/agentic/PaneActivityPill.tsx
index a36a86f9f9..e5b027dfd8 100644
--- a/jarvis/ui/web/frontend/src/components/agentic/PaneActivityPill.tsx
+++ b/jarvis/ui/web/frontend/src/components/agentic/PaneActivityPill.tsx
@@ -1,4 +1,4 @@
-import { AlertCircle, Check, Loader2 } from "lucide-react";
+import { AlertCircle, Loader2 } from "lucide-react";
import { cn } from "@/lib/utils";
import type { PaneActivity } from "@/lib/agenticIdeApi";
@@ -49,25 +49,18 @@ import type { PaneActivity } from "@/lib/agenticIdeApi";
*
* The two states a person scans this list for — still grinding vs. finished —
* are told apart by SHAPE first, not by hue: a pane that is working shows a
- * turning spinner, and a pane that has finished shows a check mark. That reads
- * at a glance, survives every colour-blindness, and it is why the working state
- * is no longer a pulsing dot: a slow throb and a steady dot are the same
- * silhouette at 8 pixels, so the difference lived entirely in a colour the eye
- * had to compare against its neighbours to judge.
- *
- * The finished state is a CHECK and not a still dot for the same reason. A dot
- * is what every list uses for "online", and beside a row of amber spinners an
- * amber dot read as "also busy, just not animated right now" — the maintainer
- * asked for an indicator that says working or done, looking at a list that
- * already had one (2026-08-27). A check says finished the way a spinner says
- * busy: on its own, without a neighbour to compare against.
+ * turning spinner, and a pane that has stopped shows a still dot. That reads at
+ * a glance, survives every colour-blindness, and it is why the working state is
+ * no longer a pulsing dot: a slow throb and a steady dot are the same silhouette
+ * at 8 pixels, so the difference lived entirely in a colour the eye had to
+ * compare against its neighbours to judge.
*
* Colour then carries the second question — is this pane's stillness news? Amber
- * is the app's own accent and marks a pane holding something for you: a check
- * for a finished job, a hollow ring for one that is merely ready and has done
- * nothing yet. Blue is spent on the one state that wants an action from you
- * right now, a pane stopped on a question. Grey is for a pane with nothing to
- * report, red for a broken one.
+ * is the app's own accent and marks a pane holding something for you: filled for
+ * a finished job, hollow for one that is merely ready and has done nothing yet.
+ * Blue is spent on the one state that wants an action from you right now, a pane
+ * stopped on a question. Grey is for a pane with nothing to report, red for a
+ * broken one.
*/
/**
@@ -94,9 +87,9 @@ type Look = {
state: PaneActivityState;
label: string;
className: string;
- icon: "spinner" | "dot" | "ring" | "alert" | "beacon" | "check";
+ icon: "spinner" | "dot" | "ring" | "alert" | "beacon";
/**
- * A soft halo of the mark's own colour. Spent on exactly one state — a
+ * A soft halo of the dot's own colour. Spent on exactly one state — a
* finished job — so the one row holding something for you glows and the
* grey ones (exited, a plain shell) stay matte.
*/
@@ -163,19 +156,18 @@ const DONE: Look = {
state: "done",
label: "done",
className: "text-amber-400",
- icon: "check",
+ icon: "dot",
glow: true,
hint: "Finished and waiting at its prompt. That it stopped, not that the work is right.",
};
/**
- * Ready, but holding nothing — the same amber, drawn as an empty ring.
+ * Ready, but holding nothing — the same amber, drawn hollow.
*
* A ring rather than a second colour because this is the SAME piece of news as
* `done` with one part missing: the pane is quiet and yours to talk to, it just
- * has no finished job behind it. Reading "nothing here yet" out of an unfilled
- * shape is what a fuel gauge does, and it keeps the accent colour meaning one
- * thing.
+ * has no finished job behind it. Reading "empty" out of an unfilled shape is
+ * what a fuel gauge does, and it keeps the accent colour meaning one thing.
*/
const IDLE: Look = {
state: "idle",
@@ -294,22 +286,12 @@ export function durationLabel(since: number, now: number): string {
return hours === 1 ? "1 hour" : `${hours} hours`;
}
-/** The soft self-coloured halo a mark that holds something for you wears. */
+/** The soft self-coloured halo a dot that holds something for you wears. */
const GLOW = "shadow-[0_0_5px_currentColor]";
-/** The same halo for a stroked icon, where a box shadow would draw a square. */
-const GLOW_STROKE = "drop-shadow-[0_0_3px_currentColor]";
function Icon({ look }: { look: Look }) {
if (look.icon === "spinner")
return <Loader2 className="h-3 w-3 animate-spin motion-reduce:animate-none" />;
- if (look.icon === "check")
- return (
- <Check
- className={cn("h-3.5 w-3.5", look.glow && GLOW_STROKE)}
- strokeWidth={3}
- aria-hidden="true"
- />
- );
if (look.icon === "dot")
return (
<span
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.tsx
new file mode 100644
index 0000000000..85677b96ea
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/local-models/AssistantPanel.test.tsx
@@ -0,0 +1,215 @@
+import { act, cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+vi.mock("@/i18n", () => ({
+ useT: () => (key: string) => key,
+ fill: (template: string, vars: Record<string, string | number>) =>
+ `${template}${Object.values(vars).join("|")}`,
+}));
+
+vi.mock("@/store/events", () => ({
+ useEventStore: (selector: (s: { assistantName: string }) => unknown) =>
+ selector({ assistantName: "Jarvis" }),
+}));
+
+// The timeline is covered by its own tests; here only what the panel feeds it matters.
+vi.mock("@/components/agentchat/AgentTimeline", () => ({
+ AgentTimeline: ({ items }: { items: { type: string }[] }) => (
+ <div data-testid="timeline-stub" data-count={items.length} />
+ ),
+}));
+
+import { AssistantPanel } from "./AssistantPanel";
+import { useLocalModelsAssistantStore } from "./assistantStore";
+import { EMPTY_TIMELINE } from "@/components/agentchat/reduce";
+
+const BASE = "/api/providers/ollama/local-models/assistant";
+
+interface Call {
+ url: string;
+ method: string;
+ body: Record<string, unknown> | null;
+}
+
+/** jsdom's WebSocket would try to reach a real host; a silent stand-in is enough here. */
+class FakeSocket {
+ onopen: (() => void) | null = null;
+ onmessage: ((msg: { data: string }) => void) | null = null;
+ onclose: (() => void) | null = null;
+ onerror: (() => void) | null = null;
+ close() {}
+}
+
+function stubFetch(routes: Record<string, (init?: RequestInit) => Response>): Call[] {
+ const calls: Call[] = [];
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(async (input: string, init?: RequestInit) => {
+ const url = String(input);
+ const method = init?.method ?? "GET";
+ const body = typeof init?.body === "string" ? (JSON.parse(init.body) as Record<string, unknown>) : null;
+ calls.push({ url, method, body });
+ const key = `${method} ${url}`;
+ const handler = routes[key] ?? routes[url];
+ return handler ? handler(init) : new Response(null, { status: 404 });
+ }),
+ );
+ return calls;
+}
+
+const reply = (data: unknown, status = 200) =>
+ new Response(JSON.stringify(data), { status, headers: { "Content-Type": "application/json" } });
+
+const PROPOSAL_TEXT = `Here is the plan.
+
+\`\`\`jarvis-proposal
+{"version":1,"steps":[
+ {"id":"s1","kind":"pull","model":"qwen3.5:8b","proven":true,"label":"Download Qwen"},
+ {"id":"s2","kind":"set_role","role":"chat","model":"qwen3.5:8b","proven":true,"label":"Use it for Chat"}
+],"notes":[]}
+\`\`\``;
+
+function finishedTurnWithProposal() {
+ return {
+ ...EMPTY_TIMELINE,
+ lastSeq: 3,
+ items: [
+ { type: "user" as const, id: "u-1", text: "Help me set up", tsMs: 1 },
+ {
+ type: "turn" as const,
+ id: "t1",
+ provider: "openrouter",
+ model: "m",
+ effort: "",
+ runner: "api",
+ status: "done" as const,
+ blocks: [{ kind: "text" as const, id: "live", text: PROPOSAL_TEXT }],
+ startedMs: 1,
+ durationMs: 10,
+ usage: null,
+ liveUsage: null,
+ costUsd: null,
+ error: null,
+ },
+ ],
+ };
+}
+
+beforeEach(() => {
+ vi.stubGlobal("WebSocket", FakeSocket);
+ useLocalModelsAssistantStore.setState({
+ activeSessionId: null,
+ activeSession: null,
+ timeline: EMPTY_TIMELINE,
+ sessions: [],
+ busy: false,
+ lastError: null,
+ });
+});
+
+afterEach(() => {
+ cleanup();
+ vi.unstubAllGlobals();
+ vi.clearAllMocks();
+});
+
+describe("AssistantPanel", () => {
+ it("renders the 409 sentence with a way to the API Keys section", async () => {
+ const sentence = "Connect the Jarvis Agents tier first — no usable credential.";
+ stubFetch({
+ [`GET ${BASE}/session`]: () => reply({ session_id: null, provider: "", model: "", ready: false, reason: "no_credential" }),
+ [`GET ${BASE}/health`]: () => reply({}, 404),
+ [`POST ${BASE}/run`]: () => reply({ detail: sentence }, 409),
+ });
+ const onOpenApiKeys = vi.fn();
+ render(
+ <AssistantPanel
+ providerId="ollama"
+ serverLabel="Ollama"
+ request={{ mode: "setup", token: 1 }}
+ onOpenApiKeys={onOpenApiKeys}
+ />,
+ );
+
+ await waitFor(() => expect(screen.getByTestId("assistant-blocked")).toBeDefined());
+ expect(screen.getByTestId("assistant-blocked").textContent).toContain(sentence);
+ fireEvent.click(screen.getByRole("button", { name: "local_models.assistant.open_api_keys" }));
+ expect(onOpenApiKeys).toHaveBeenCalledTimes(1);
+ // The composer stays locked: there is no session to talk to.
+ expect((screen.getByTestId("assistant-composer") as HTMLTextAreaElement).disabled).toBe(true);
+ });
+
+ it("shows the monitor's last check and a Fix that starts diagnose mode", async () => {
+ const calls = stubFetch({
+ [`GET ${BASE}/session`]: () => reply({ session_id: null, provider: "", model: "", ready: true, reason: "" }),
+ [`GET ${BASE}/health`]: () =>
+ reply({ status: "error", reason: "chat role: model not installed", since: 1_700_000_000, last_ok: null, checked_at: 1_700_000_000 }),
+ [`POST ${BASE}/run`]: () => reply({ session_id: "s-1", turn_id: "t-1", surface: "local-models" }),
+ });
+ render(<AssistantPanel providerId="ollama" serverLabel="Ollama" request={null} onOpenApiKeys={() => {}} />);
+
+ await waitFor(() => expect(screen.getByTestId("assistant-health")).toBeDefined());
+ expect(screen.getByTestId("assistant-health").textContent).toContain("chat role: model not installed");
+
+ fireEvent.click(screen.getByTestId("assistant-health-fix"));
+ await waitFor(() =>
+ expect(calls.some((c) => c.method === "POST" && c.url === `${BASE}/run` && c.body?.mode === "diagnose")).toBe(true),
+ );
+ await waitFor(() => expect(useLocalModelsAssistantStore.getState().activeSessionId).toBe("s-1"));
+ });
+
+ it("says so when the backend predates the assistant", async () => {
+ stubFetch({});
+ render(<AssistantPanel providerId="ollama" serverLabel="Ollama" request={null} onOpenApiKeys={() => {}} />);
+ await waitFor(() => expect(screen.getByTestId("assistant-backend-missing")).toBeDefined());
+ });
+
+ it("confirms the proposal once and answers the matching approval cards by itself", async () => {
+ const calls = stubFetch({
+ // The store already holds the open session (set below); the route
+ // answering null keeps the panel from re-opening (and resetting) it.
+ [`GET ${BASE}/session`]: () => reply({ session_id: null, provider: "openrouter", model: "m", ready: true, reason: "" }),
+ [`GET ${BASE}/health`]: () => reply({}, 404),
+ "POST /api/agent-chat/sessions/s-1/messages": () => reply({ turn_id: "t2" }),
+ "POST /api/agent-chat/sessions/s-1/approvals/a-1": () => reply({}),
+ "POST /api/agent-chat/sessions/s-1/approvals/a-2": () => reply({}),
+ "GET /api/agent-chat/sessions?limit=500&surface=local-models": () => reply({ sessions: [] }),
+ });
+ useLocalModelsAssistantStore.setState({ activeSessionId: "s-1", timeline: finishedTurnWithProposal() });
+ render(<AssistantPanel providerId="ollama" serverLabel="Ollama" request={null} onOpenApiKeys={() => {}} />);
+
+ await waitFor(() => expect(screen.getByTestId("setup-proposal")).toBeDefined());
+ fireEvent.click(screen.getByTestId("proposal-confirm"));
+ await waitFor(() =>
+ expect(calls.some((c) => c.url.endsWith("/messages") && String(c.body?.text).startsWith("Execute steps: s1, s2 ("))).toBe(true),
+ );
+ await waitFor(() => expect(screen.getByTestId("proposal-confirmed")).toBeDefined());
+
+ // The runner asks about the confirmed pull: answered without a click.
+ const ingest = useLocalModelsAssistantStore.getState().ingest;
+ act(() => {
+ ingest({ seq: 4, ts_ms: 20, kind: "turn_started", payload: { turn_id: "t2", provider: "openrouter", model: "m" } });
+ ingest({
+ seq: 5,
+ ts_ms: 21,
+ kind: "approval_required",
+ payload: { turn_id: "t2", approval_id: "a-1", call_id: "c-1", name: "lm_pull", input: { model: "qwen3.5:8b" }, summary: "pull" },
+ });
+ });
+ await waitFor(() =>
+ expect(calls.some((c) => c.url.endsWith("/approvals/a-1") && c.body?.decision === "allow")).toBe(true),
+ );
+
+ // A question outside the plan stays a question.
+ act(() => {
+ ingest({
+ seq: 6,
+ ts_ms: 22,
+ kind: "approval_required",
+ payload: { turn_id: "t2", approval_id: "a-2", call_id: "c-2", name: "lm_pull", input: { model: "llama4:70b" }, summary: "pull" },
+ });
+ });
+ await new Promise((r) => setTimeout(r, 20));
+ expect(calls.some((c) => c.url.endsWith("/approvals/a-2"))).toBe(false);
+ });
+});
diff --git a/jarvis/ui/web/frontend/src/components/local-models/AssistantPanel.tsx b/jarvis/ui/web/frontend/src/components/local-models/AssistantPanel.tsx
new file mode 100644
index 0000000000..6cdaecf3d2
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/local-models/AssistantPanel.tsx
@@ -0,0 +1,642 @@
+/**
+ * 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 is one screen with
+ * the composer at the bottom, so opening the helper never turns the section
+ * into a page thousands of pixels tall that buries the roles below it.
+ * 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.
+ *
+ * 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 { 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,
+} from "./assistantApi";
+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,
+}: {
+ 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;
+}) {
+ 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);
+ 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);
+
+ 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 one session per install: open it (and its socket) when the panel mounts.
+ useEffect(() => {
+ let cancelled = false;
+ void (async () => {
+ try {
+ const s = await getAssistantSession(providerId);
+ if (cancelled) return;
+ if (s.session_id) openSession(s.session_id);
+ } catch (err) {
+ if (cancelled) return;
+ if (err instanceof AssistantApiError && err.status === 404) setBackendMissing(true);
+ }
+ })();
+ return () => {
+ cancelled = true;
+ };
+ }, [providerId, openSession]);
+
+ useEffect(() => () => disconnect(), [disconnect]);
+
+ const loadHealth = useCallback(async () => {
+ try {
+ setHealth(await getAssistantHealth(providerId));
+ } catch (err) {
+ if (err instanceof AssistantApiError && err.status === 404) setBackendMissing(true);
+ // No health record yet is a normal state (monitor not run); nothing to show.
+ }
+ }, [providerId]);
+
+ useEffect(() => {
+ void loadHealth();
+ }, [loadHealth]);
+
+ useEffect(() => {
+ setConfirmed(activeSessionId ? (confirmedBySession.get(activeSessionId) ?? null) : null);
+ answered.current = new Set();
+ }, [activeSessionId]);
+
+ // Follow the conversation while it writes, the way a chat does.
+ useEffect(() => {
+ const el = scroller.current;
+ if (el) el.scrollTop = el.scrollHeight;
+ }, [items, shown.length]);
+
+ const run = useCallback(
+ async (mode: AssistantMode) => {
+ setStarting(mode);
+ setBlocked(null);
+ setRunError(null);
+ setShowEarlier(false);
+ 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);
+ else if (err instanceof AssistantApiError && err.status === 404) setBackendMissing(true);
+ else setRunError(err instanceof Error ? err.message : String(err));
+ } finally {
+ setStarting(null);
+ }
+ },
+ [providerId, activeSessionId, openSession],
+ );
+
+ // The section's button click is the request; run it once per token.
+ const lastToken = useRef<number | null>(null);
+ useEffect(() => {
+ if (!request || request.token === lastToken.current) return;
+ lastToken.current = request.token;
+ void run(request.mode);
+ }, [request, run]);
+
+ useEffect(() => {
+ if (!running) void loadHealth();
+ }, [running, loadHealth]);
+
+ // The plan in the last finished turn 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 healthTone =
+ health?.status === "ok" ? "ok" : health?.status === "unknown" || !health ? "off" : "warn";
+ const needsFix = health?.status === "error" || health?.status === "needs_setup";
+
+ // 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 the screen's, minus what the section
+ // header and the rail already take.
+ "flex h-[calc(100vh-14.5rem)] min-h-[26rem] 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",
+ )}
+ data-testid="local-models-assistant"
+ >
+ {/* ── header ─────────────────────────────────────────────────────── */}
+ <div className="shrink-0 border-b border-border/70 bg-card px-5 py-3">
+ <div className="mx-auto flex w-full max-w-[46rem] flex-wrap items-center justify-between gap-x-4 gap-y-2">
+ <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>
+ <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 ───────────────────────────────────────────────── */}
+ <div ref={scroller} className="flex-1 overflow-y-auto" data-testid="assistant-timeline">
+ <div className="mx-auto flex w-full max-w-[46rem] flex-col gap-8 px-5 py-6">
+ {health && checkedAt && (
+ <p
+ className="flex flex-wrap items-center gap-3 text-[12.5px]"
+ data-testid="assistant-health"
+ >
+ <StatusDot
+ tone={healthTone}
+ label={fill(t("local_models.assistant.last_check"), {
+ when: checkedAt.toLocaleString(),
+ what: health.reason || t(`local_models.assistant.health_${health.status}`),
+ })}
+ />
+ {needsFix && (
+ <button
+ type="button"
+ className="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">
+ <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>
+
+ {/* ── composer ───────────────────────────────────────────────────── */}
+ <div className="shrink-0 border-t border-border/70 bg-card px-5 py-3">
+ <div className="mx-auto w-full max-w-[46rem]">
+ <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.tsx
new file mode 100644
index 0000000000..0d4e9b7d65
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/local-models/AssistantSteps.tsx
@@ -0,0 +1,285 @@
+/**
+ * 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.tsx
new file mode 100644
index 0000000000..1d56c507ee
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/local-models/SetupProposalCard.test.tsx
@@ -0,0 +1,90 @@
+import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
+import { afterEach, describe, expect, it, vi } from "vitest";
+
+vi.mock("@/i18n", () => ({
+ useT: () => (key: string) => key,
+ fill: (template: string, vars: Record<string, string | number>) =>
+ `${template}${Object.values(vars).join("|")}`,
+}));
+
+const { switchBrainProvider } = vi.hoisted(() => ({
+ switchBrainProvider: vi.fn(async (_id: string) => undefined),
+}));
+vi.mock("@/hooks/useProviders", () => ({ switchBrainProvider }));
+
+import { BrainSwitchCard, SetupProposalCard } from "./SetupProposalCard";
+import { proposalHash, type Proposal } from "./assistantProposal";
+
+const PROPOSAL: Proposal = {
+ version: 1,
+ steps: [
+ { id: "s1", kind: "pull", model: "qwen3.5:8b", size_gb: 5.2, proven: "proven", label: "Download Qwen" },
+ { id: "s2", kind: "set_role", role: "chat", model: "qwen3.5:8b", proven: "new_little_tested", label: "Use for Chat" },
+ { id: "s3", kind: "test", proven: "stale", label: "Test it" },
+ ],
+ brain_switch: null,
+ notes: ["Nothing is deleted."],
+};
+
+afterEach(() => {
+ cleanup();
+ vi.clearAllMocks();
+});
+
+describe("SetupProposalCard", () => {
+ it("lists every step with its badge and confirms all of them in one click", async () => {
+ const onConfirm = vi.fn(async () => undefined);
+ render(<SetupProposalCard proposal={PROPOSAL} onConfirm={onConfirm} />);
+
+ expect(screen.getByTestId("proposal-badge-proven")).toBeDefined();
+ expect(screen.getByTestId("proposal-badge-new_little_tested")).toBeDefined();
+ expect(screen.getByTestId("proposal-badge-stale")).toBeDefined();
+ expect(screen.getByText("5.2 GB")).toBeDefined();
+ expect(screen.getByText("Nothing is deleted.")).toBeDefined();
+
+ fireEvent.click(screen.getByTestId("proposal-confirm"));
+ await waitFor(() => expect(onConfirm).toHaveBeenCalledTimes(1));
+ const [steps, message] = onConfirm.mock.calls[0] as unknown as [Proposal["steps"], string];
+ expect(steps.map((s) => s.id)).toEqual(["s1", "s2", "s3"]);
+ expect(message).toBe(`Execute steps: s1, s2, s3 (proposal v1, hash ${proposalHash(PROPOSAL)})`);
+ });
+
+ it("leaves an unticked step out of the confirmation", async () => {
+ const onConfirm = vi.fn(async () => undefined);
+ render(<SetupProposalCard proposal={PROPOSAL} onConfirm={onConfirm} />);
+
+ fireEvent.click(screen.getByTestId("proposal-step-s2"));
+ expect(screen.getByTestId("proposal-confirm").textContent).toContain(
+ "local_models.assistant.confirm_some",
+ );
+ fireEvent.click(screen.getByTestId("proposal-confirm"));
+ await waitFor(() => expect(onConfirm).toHaveBeenCalledTimes(1));
+ const [steps, message] = onConfirm.mock.calls[0] as unknown as [Proposal["steps"], string];
+ expect(steps.map((s) => s.id)).toEqual(["s1", "s3"]);
+ expect(message.startsWith("Execute steps: s1, s3 ")).toBe(true);
+ });
+
+ it("cannot confirm nothing, and shows the receipt once confirmed", () => {
+ const onConfirm = vi.fn(async () => undefined);
+ const { rerender } = render(<SetupProposalCard proposal={PROPOSAL} onConfirm={onConfirm} />);
+ for (const id of ["s1", "s2", "s3"]) fireEvent.click(screen.getByTestId(`proposal-step-${id}`));
+ expect((screen.getByTestId("proposal-confirm") as HTMLButtonElement).disabled).toBe(true);
+
+ rerender(
+ <SetupProposalCard proposal={PROPOSAL} onConfirm={onConfirm} confirmedHash={proposalHash(PROPOSAL)} />,
+ );
+ expect(screen.queryByTestId("proposal-confirm")).toBeNull();
+ expect(screen.getByTestId("proposal-confirmed")).toBeDefined();
+ });
+});
+
+describe("BrainSwitchCard", () => {
+ it("switches the brain only on the user's click", async () => {
+ render(<BrainSwitchCard provider="ollama" why="Runs locally." serverLabel="Ollama" />);
+ expect(switchBrainProvider).not.toHaveBeenCalled();
+ fireEvent.click(screen.getByTestId("brain-switch-run"));
+ await waitFor(() => expect(switchBrainProvider).toHaveBeenCalledWith("ollama"));
+ await waitFor(() => expect(screen.queryByTestId("brain-switch-run")).toBeNull());
+ expect(screen.getByText(/brain_switch_done/)).toBeDefined();
+ });
+});
diff --git a/jarvis/ui/web/frontend/src/components/local-models/SetupProposalCard.tsx b/jarvis/ui/web/frontend/src/components/local-models/SetupProposalCard.tsx
new file mode 100644
index 0000000000..306fa10961
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/local-models/SetupProposalCard.tsx
@@ -0,0 +1,246 @@
+/**
+ * The assistant's plan as a checklist the user confirms ONCE.
+ *
+ * Built from the onboarding register (numbered rows separated by hairlines)
+ * so it reads as a document, not a dialog: every step is a row with a
+ * checkbox, the model it pulls or assigns, a size, and a badge that says how
+ * proven the model is. Unchecking a row leaves it out of the confirmation;
+ * the one primary action sends "Execute steps: … (proposal v1, hash …)" and
+ * the caller remembers the confirmed steps so the runner's approval cards
+ * for exactly those steps are answered without another click.
+ *
+ * A `brain_switch` never runs by itself (the brain provider is the user's
+ * lock): it is a separate card whose button calls the ordinary switch route
+ * only when the user clicks it.
+ */
+import { Check, Download, FlaskConical, Mic, Settings2, Terminal, Wand2 } from "lucide-react";
+import { useCallback, useMemo, useState, type ReactNode } from "react";
+
+import { Button } from "@/components/agentic/controls";
+import { Panel, StatusDot } from "@/components/extensions/primitives";
+import { Register, StepFooter, StepSection } from "@/components/onboarding/primitives";
+import { switchBrainProvider } from "@/hooks/useProviders";
+import { fill, useT } from "@/i18n";
+import { cn } from "@/lib/utils";
+
+import {
+ confirmationMessage,
+ proposalHash,
+ type Proposal,
+ type ProposalStep,
+ type ProposalStepKind,
+ type ProvenLabel,
+} from "./assistantProposal";
+
+const STEP_ICON: Record<ProposalStepKind, ReactNode> = {
+ install_ollama: <Terminal className="h-4 w-4" />,
+ pull: <Download className="h-4 w-4" />,
+ set_role: <Wand2 className="h-4 w-4" />,
+ set_options: <Settings2 className="h-4 w-4" />,
+ apply_voice_stack: <Mic className="h-4 w-4" />,
+ test: <FlaskConical className="h-4 w-4" />,
+};
+
+function ProvenBadge({ proven }: { proven: ProvenLabel | null }) {
+ const t = useT();
+ if (!proven) return null;
+ const tone = proven === "proven" ? "ok" : proven === "stale" ? "warn" : "busy";
+ return (
+ <span data-testid={`proposal-badge-${proven}`} className="shrink-0">
+ <StatusDot tone={tone} label={t(`local_models.assistant.badge_${proven}`)} />
+ </span>
+ );
+}
+
+function formatSize(gb: number | undefined): string | null {
+ if (gb === undefined || !Number.isFinite(gb) || gb <= 0) return null;
+ return `${gb >= 10 ? Math.round(gb) : gb.toFixed(1)} GB`;
+}
+
+export function SetupProposalCard({
+ proposal,
+ onConfirm,
+ busy,
+ confirmedHash,
+}: {
+ proposal: Proposal;
+ /** Sends the confirmation message and remembers the checked steps. */
+ onConfirm: (steps: ProposalStep[], message: string) => void | Promise<void>;
+ /** A turn is running — the plan cannot be confirmed twice. */
+ busy?: boolean;
+ /** The hash of an already-confirmed plan: the card shows the receipt instead of the button. */
+ confirmedHash?: string | null;
+}) {
+ const t = useT();
+ const hash = useMemo(() => proposalHash(proposal), [proposal]);
+ const [excluded, setExcluded] = useState<ReadonlySet<string>>(() => new Set());
+ const [sending, setSending] = useState(false);
+ const confirmed = confirmedHash === hash;
+
+ const toggle = useCallback((id: string) => {
+ setExcluded((prev) => {
+ const next = new Set(prev);
+ if (next.has(id)) next.delete(id);
+ else next.add(id);
+ return next;
+ });
+ }, []);
+
+ const chosen = proposal.steps.filter((s) => !excluded.has(s.id));
+
+ const confirm = useCallback(async () => {
+ if (chosen.length === 0 || sending) return;
+ setSending(true);
+ try {
+ await onConfirm(chosen, confirmationMessage(proposal, chosen));
+ } finally {
+ setSending(false);
+ }
+ }, [chosen, onConfirm, proposal, sending]);
+
+ return (
+ <Panel className="p-4">
+ <div data-testid="setup-proposal" data-hash={hash} className="space-y-6">
+ <StepSection label={t("local_models.assistant.proposal_title")}>
+ <p className="text-sm text-muted-foreground">
+ {t("local_models.assistant.proposal_hint")}
+ </p>
+ <Register
+ items={proposal.steps.map((step) => {
+ const off = excluded.has(step.id);
+ const size = formatSize(step.size_gb);
+ return {
+ key: step.id,
+ icon: STEP_ICON[step.kind],
+ children: (
+ <label
+ className={cn(
+ "flex cursor-pointer items-start gap-3",
+ off && "text-muted-foreground line-through decoration-border",
+ )}
+ >
+ <input
+ type="checkbox"
+ className="mt-1 h-4 w-4 shrink-0 accent-primary"
+ checked={!off && !confirmed}
+ disabled={confirmed}
+ onChange={() => toggle(step.id)}
+ aria-label={step.label}
+ data-testid={`proposal-step-${step.id}`}
+ />
+ <span className="flex min-w-0 flex-1 flex-col gap-1">
+ <span className="flex flex-wrap items-center gap-x-3 gap-y-1">
+ <span className="font-medium text-foreground">{step.label}</span>
+ <ProvenBadge proven={step.proven} />
+ </span>
+ {(step.model || size || step.fit) && (
+ <span className="flex flex-wrap gap-x-3 font-mono text-[12px] text-muted-foreground">
+ {step.model && <span>{step.model}</span>}
+ {size && <span>{size}</span>}
+ {step.fit && <span>{step.fit}</span>}
+ </span>
+ )}
+ </span>
+ </label>
+ ),
+ };
+ })}
+ />
+ {proposal.notes.length > 0 && (
+ <ul className="space-y-1 text-sm text-muted-foreground">
+ {proposal.notes.map((note, i) => (
+ <li key={i}>{note}</li>
+ ))}
+ </ul>
+ )}
+ </StepSection>
+
+ {confirmed ? (
+ <p
+ className="flex items-center gap-2 text-sm text-muted-foreground"
+ data-testid="proposal-confirmed"
+ >
+ <Check className="h-4 w-4 text-primary" />
+ {fill(t("local_models.assistant.proposal_confirmed"), { hash })}
+ </p>
+ ) : (
+ <StepFooter
+ onBack={null}
+ hidePrimaryArrow
+ primary={{
+ label:
+ chosen.length === proposal.steps.length
+ ? t("local_models.assistant.confirm_all")
+ : fill(t("local_models.assistant.confirm_some"), { count: chosen.length }),
+ onClick: () => void confirm(),
+ disabled: chosen.length === 0 || Boolean(busy),
+ busy: sending,
+ testId: "proposal-confirm",
+ }}
+ />
+ )}
+ </div>
+ </Panel>
+ );
+}
+
+/**
+ * "Make Ollama the active brain" — the one thing the assistant may only
+ * propose. The switch happens on this click and nowhere else.
+ */
+export function BrainSwitchCard({
+ provider,
+ why,
+ serverLabel,
+}: {
+ provider: string;
+ why: string;
+ /** What the section calls the local server ("Ollama"). */
+ serverLabel: string;
+}) {
+ const t = useT();
+ const [state, setState] = useState<"idle" | "busy" | "done" | "error">("idle");
+ const [error, setError] = useState<string>("");
+
+ const run = useCallback(async () => {
+ setState("busy");
+ setError("");
+ try {
+ await switchBrainProvider(provider);
+ setState("done");
+ } catch (err) {
+ setState("error");
+ setError(err instanceof Error ? err.message : String(err));
+ }
+ }, [provider]);
+
+ return (
+ <Panel className="p-4">
+ <div data-testid="brain-switch-card" className="flex flex-wrap items-center justify-between gap-3">
+ <div className="min-w-0 space-y-1">
+ <p className="font-medium text-foreground">
+ {fill(t("local_models.assistant.brain_switch_title"), { server: serverLabel })}
+ </p>
+ {why && <p className="text-sm text-muted-foreground">{why}</p>}
+ {state === "done" && (
+ <StatusDot
+ tone="ok"
+ label={fill(t("local_models.assistant.brain_switch_done"), { server: serverLabel })}
+ />
+ )}
+ {state === "error" && <StatusDot tone="error" label={error} />}
+ </div>
+ {state !== "done" && (
+ <Button
+ variant="primary"
+ onClick={() => void run()}
+ disabled={state === "busy"}
+ data-testid="brain-switch-run"
+ >
+ {t("local_models.assistant.brain_switch_action")}
+ </Button>
+ )}
+ </div>
+ </Panel>
+ );
+}
diff --git a/jarvis/ui/web/frontend/src/components/local-models/assistantApi.ts b/jarvis/ui/web/frontend/src/components/local-models/assistantApi.ts
new file mode 100644
index 0000000000..c69a631f51
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/local-models/assistantApi.ts
@@ -0,0 +1,111 @@
+/**
+ * Thin client for the setup assistant's routes
+ * (`jarvis/ui/web/local_models_assistant_routes.py`, prefix
+ * `/api/providers/{id}/local-models/assistant`). Shapes mirror the backend
+ * one-to-one; nothing here decides behaviour. A backend that predates the
+ * assistant answers 404 — callers show that honestly instead of a spinner.
+ */
+import type { AgentChatSurface } from "@/lib/agentChatApi";
+
+export type AssistantMode = "setup" | "diagnose" | "test";
+
+export interface AssistantRunResponse {
+ session_id: string;
+ turn_id: string;
+ surface: AgentChatSurface;
+}
+
+export interface AssistantSessionResponse {
+ session_id: string | null;
+ provider: string;
+ model: string;
+ ready: boolean;
+ reason: string;
+}
+
+export type AssistantHealthStatus = "ok" | "error" | "needs_setup" | "unknown";
+
+export interface AssistantHealth {
+ status: AssistantHealthStatus;
+ reason: string;
+ /** ISO timestamp or epoch seconds; null when the monitor has not run. */
+ since: string | number | null;
+ last_ok: string | number | null;
+ checked_at: string | number | null;
+}
+
+export interface AssistantRoleResult {
+ model: string;
+ status: string;
+ latency_ms: number | null;
+ detail: string;
+}
+
+export interface AssistantTestReport {
+ checked_at: string | number | null;
+ server: Record<string, unknown>;
+ roles: Record<string, AssistantRoleResult>;
+ voice: Record<string, unknown> | null;
+ overall: string;
+}
+
+export class AssistantApiError extends Error {
+ constructor(
+ message: string,
+ readonly status: number,
+ ) {
+ super(message);
+ this.name = "AssistantApiError";
+ }
+}
+
+function base(providerId: string): string {
+ return `/api/providers/${encodeURIComponent(providerId)}/local-models/assistant`;
+}
+
+async function parse<T>(res: Response, what: string): Promise<T> {
+ if (!res.ok) {
+ let detail = what;
+ try {
+ const body = (await res.json()) as { detail?: unknown };
+ if (typeof body.detail === "string" && body.detail.trim()) detail = body.detail;
+ } catch {
+ // no JSON body — the generic label stands
+ }
+ throw new AssistantApiError(detail, res.status);
+ }
+ return (await res.json()) as T;
+}
+
+export async function runAssistant(
+ providerId: string,
+ mode: AssistantMode,
+): Promise<AssistantRunResponse> {
+ return parse(
+ await fetch(`${base(providerId)}/run`, {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ mode }),
+ }),
+ "assistant-run-failed",
+ );
+}
+
+export async function getAssistantSession(providerId: string): Promise<AssistantSessionResponse> {
+ return parse(await fetch(`${base(providerId)}/session`, { cache: "no-store" }), "assistant-session-failed");
+}
+
+export async function getAssistantHealth(providerId: string): Promise<AssistantHealth> {
+ return parse(await fetch(`${base(providerId)}/health`, { cache: "no-store" }), "assistant-health-failed");
+}
+
+export async function runAssistantTest(providerId: string): Promise<AssistantTestReport> {
+ return parse(await fetch(`${base(providerId)}/test`, { method: "POST" }), "assistant-test-failed");
+}
+
+/** Turns the backend's `since` / `checked_at` (ISO or epoch seconds) into a Date, or null. */
+export function assistantTimestamp(value: string | number | null | undefined): Date | null {
+ if (value === null || value === undefined || value === "") return null;
+ const d = typeof value === "number" ? new Date(value * 1000) : new Date(value);
+ return Number.isNaN(d.getTime()) ? null : d;
+}
diff --git a/jarvis/ui/web/frontend/src/components/local-models/assistantProposal.test.ts b/jarvis/ui/web/frontend/src/components/local-models/assistantProposal.test.ts
new file mode 100644
index 0000000000..012c9c0877
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/local-models/assistantProposal.test.ts
@@ -0,0 +1,127 @@
+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.ts
new file mode 100644
index 0000000000..24a7b66446
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/local-models/assistantProposal.ts
@@ -0,0 +1,278 @@
+/**
+ * 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.ts
new file mode 100644
index 0000000000..97ea34e375
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/local-models/assistantStore.ts
@@ -0,0 +1,10 @@
+/**
+ * The setup assistant's own agent-chat store — surface `local-models`.
+ *
+ * A separate store instance means a separate socket, session list and draft:
+ * the assistant's session never appears in the front page's chat list and
+ * the front page's open chat never bleeds into the Local models section.
+ */
+import { createAgentChatStore } from "@/store/agentChat";
+
+export const useLocalModelsAssistantStore = createAgentChatStore("local-models");
diff --git a/jarvis/ui/web/frontend/src/components/local-models/assistantText.test.ts b/jarvis/ui/web/frontend/src/components/local-models/assistantText.test.ts
new file mode 100644
index 0000000000..bc30c6f4e0
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/local-models/assistantText.test.ts
@@ -0,0 +1,28 @@
+/** 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.tsx
new file mode 100644
index 0000000000..6e7a8afbb9
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/local-models/assistantText.tsx
@@ -0,0 +1,52 @@
+/**
+ * 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/hooks/useFileDropGuard.ts b/jarvis/ui/web/frontend/src/hooks/useFileDropGuard.ts
deleted file mode 100644
index 4ba0c51d9e..0000000000
--- a/jarvis/ui/web/frontend/src/hooks/useFileDropGuard.ts
+++ /dev/null
@@ -1,51 +0,0 @@
-import { useEffect } from "react";
-
-/**
- * Stop a missed file drop from replacing the app with the file.
- *
- * A browser's default action for a file dropped anywhere in a page is to
- * NAVIGATE to it. Inside the desktop shell there is no address bar and no Back
- * button, so a screenshot dropped two centimetres beside the composer does not
- * merely fail — it takes the whole window: every open chat, every terminal in
- * the grid, gone until the app is restarted. The person who did it has no way
- * to read that as "you missed", because nothing about a picture filling the
- * window says a drop was refused.
- *
- * So every drop that no drop zone claimed is swallowed here, and nothing else
- * happens: no toast, no highlight. A drop on empty chrome SHOULD do nothing —
- * this only makes "nothing" true.
- *
- * ## Why this cannot break a real drop target
- *
- * The listeners run in the BUBBLE phase on `window`, which is after React has
- * delivered the event to its own tree (React 18 attaches at the root
- * container, below `window`). A target that took the drop has already called
- * `preventDefault()` by then, and `defaultPrevented` is how this tells the two
- * apart. A handler that did NOT call it was not going to receive the file
- * anyway — that is what the default action being navigation means.
- *
- * `dragover` needs the same treatment: without a `preventDefault()` there the
- * browser refuses the drop before `drop` ever fires, so guarding only `drop`
- * would leave the cursor showing 🚫 over the whole app. Guarding both keeps
- * the page's own targets in charge of the cursor — they preventDefault first,
- * and this one only claims what they left.
- */
-export function useFileDropGuard(): void {
- useEffect(() => {
- const carriesFiles = (event: DragEvent): boolean => {
- const types = event.dataTransfer?.types;
- return types ? Array.from(types).includes("Files") : false;
- };
- const swallow = (event: DragEvent) => {
- if (event.defaultPrevented) return; // a real target took it
- if (!carriesFiles(event)) return; // dragged text/links are the browser's
- event.preventDefault();
- };
- window.addEventListener("dragover", swallow);
- window.addEventListener("drop", swallow);
- return () => {
- window.removeEventListener("dragover", swallow);
- window.removeEventListener("drop", swallow);
- };
- }, []);
-}
diff --git a/jarvis/ui/web/frontend/src/hooks/useWebSocket.test.tsx b/jarvis/ui/web/frontend/src/hooks/useWebSocket.test.tsx
index 1f54f341d2..7fbbe269ac 100644
--- a/jarvis/ui/web/frontend/src/hooks/useWebSocket.test.tsx
+++ b/jarvis/ui/web/frontend/src/hooks/useWebSocket.test.tsx
@@ -204,43 +204,6 @@ describe("useWebSocket VoiceBootStatus handling", () => {
expect(toasts[2].message).toContain("never showed it arriving");
});
- it("hands a pane's activity change to the window, payload intact and without a toast", async () => {
- render(<Harness />);
- await Promise.resolve();
- const seen: unknown[] = [];
- const onActivity = (event: Event) => seen.push((event as CustomEvent).detail);
- window.addEventListener("jarvis:agentic-ide-activity", onActivity);
- try {
- MockWebSocket.last!.deliver(
- envelope("AgenticIdePaneActivity", {
- session_id: "ide_1",
- key: "t3",
- name: "T3",
- status: "live",
- activity: "waiting",
- activity_since: 1787823736,
- worked: true,
- }),
- );
- } finally {
- window.removeEventListener("jarvis:agentic-ide-activity", onActivity);
- }
-
- expect(seen).toEqual([
- {
- session_id: "ide_1",
- key: "t3",
- name: "T3",
- status: "live",
- activity: "waiting",
- activity_since: 1787823736,
- worked: true,
- },
- ]);
- // The bell is the surface for "it finished"; the badge just keeps up.
- expect(useEventStore.getState().toasts).toEqual([]);
- });
-
it("routes native microphone levels outside React state and clears them after listening", async () => {
render(<Harness />);
await Promise.resolve();
diff --git a/jarvis/ui/web/frontend/src/hooks/useWebSocket.ts b/jarvis/ui/web/frontend/src/hooks/useWebSocket.ts
index 4957d4777e..1b9d8ea503 100644
--- a/jarvis/ui/web/frontend/src/hooks/useWebSocket.ts
+++ b/jarvis/ui/web/frontend/src/hooks/useWebSocket.ts
@@ -25,7 +25,6 @@ import {
} from "@/store/commandActivity";
import { useDeckStore } from "@/store/deck";
import { useHomeStore } from "@/store/home";
-import { PANE_ACTIVITY_EVENT } from "@/store/workspacePanes";
import { WSAudioLevel, WSEventEnvelope, WSWelcome } from "@/schema/ws";
import { useI18nStore, hydrateUiLanguage, hydrateReplyLanguage, translate } from "@/i18n";
import { hydrateUiTheme } from "@/hooks/useTheme";
@@ -521,19 +520,6 @@ export function useWebSocket(): void {
}
}
- if (env.event_name === "AgenticIdePaneActivity") {
- // One pane's agent changed state — started, stopped, asked, died.
- // The payload is the activity half of a `/panes` row, so the session
- // list and the grid patch their row in place the moment the sweep
- // decides, instead of showing a spinner over a finished session
- // until their next poll (up to four seconds in the sidebar). No
- // toast: the bell is the surface for "it finished", this is the
- // badge keeping up with the pane.
- window.dispatchEvent(
- new CustomEvent(PANE_ACTIVITY_EVENT, { detail: env.payload }),
- );
- }
-
if (env.event_name === "AgenticIdeComposeProgress") {
// One beat of a brief being written for a pane — the prompt bar
// shows it as a live status line. Deliberately no toast: a single
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.ts
index 26a1573a59..a71f9901ff 100644
--- a/jarvis/ui/web/frontend/src/i18n/local-models-i18n-parity.test.ts
+++ b/jarvis/ui/web/frontend/src/i18n/local-models-i18n-parity.test.ts
@@ -29,6 +29,7 @@ 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"))
@@ -36,6 +37,7 @@ 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 covered
diff --git a/jarvis/ui/web/frontend/src/store/agentChat.test.ts b/jarvis/ui/web/frontend/src/store/agentChat.test.ts
index 26757da377..5c14501e6f 100644
--- a/jarvis/ui/web/frontend/src/store/agentChat.test.ts
+++ b/jarvis/ui/web/frontend/src/store/agentChat.test.ts
@@ -1,7 +1,6 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import type { AgentChatSession } from "@/lib/agentChatApi";
-import { providerKind } from "@/components/agentchat/AgentComposer";
import { createAgentChatStore, draftKey } from "@/store/agentChat";
/**
@@ -136,52 +135,6 @@ describe("agent-chat store surfaces", () => {
vi.unstubAllGlobals();
});
- it("counts a brain seat as connected only when an API KEY is saved", () => {
- // The Agents tab calls a Claude Code login "connected" — right for a row
- // a CLI runs. On the front page's chat the same row is the Anthropic
- // endpoint, where that login buys nothing, so it must read as unconnected
- // until a key is there.
- const row = (runner: string, keyless = false) => ({
- id: "claude-api",
- label: "Anthropic Claude",
- family: "claude",
- runner,
- models_source: "live" as const,
- curated_models: [],
- default_model: "",
- keyless,
- native_resume: true,
- effort_levels: ["low", "high"],
- default_effort: "high",
- permission_modes: [{ id: "ask", label: "ask", description: "" }],
- default_permission_mode: "ask",
- cli_installed: null,
- });
- const seat = (runner: string, conn: Record<string, unknown>) => {
- const store = createAgentChatStore("jarvis");
- store.setState({
- catalog: { providers: [row(runner)], default_cwd: "C:\work", shell: "pwsh" },
- connections: [{ jarvis: "claude-api", is_active_brain: false, ...conn }],
- } as never);
- return store.getState().providerOptions()[0].connected;
- };
- const subscriptionOnly = { key_set: true, api_key_set: false, oauth_connected: true };
- expect(seat("brain", subscriptionOnly)).toBe(false);
- expect(seat("api", subscriptionOnly)).toBe(false);
- // The CLI seat itself is exactly what that login is for.
- expect(seat("claude-cli", subscriptionOnly)).toBe(true);
- expect(seat("brain", { key_set: true, api_key_set: true })).toBe(true);
- // A backend too old to report the finer field still answers as before.
- expect(seat("brain", { key_set: true })).toBe(true);
- });
-
- it("groups a brain seat with the API keys, never with the CLIs", () => {
- expect(providerKind({ runner: "brain", keyless: false })).toBe("api");
- expect(providerKind({ runner: "api", keyless: false })).toBe("api");
- expect(providerKind({ runner: "claude-cli", keyless: false })).toBe("cli");
- expect(providerKind({ runner: "brain", keyless: true })).toBe("local");
- });
-
it("names the front page's draft key as it always was, and gives the IDE its own", () => {
expect(draftKey("jarvis")).toBe("jarvis.agentChat.draft.v2");
expect(draftKey("agent")).toBe("jarvis.agentChat.draft.agent.v1");
diff --git a/jarvis/workspace/agents.py b/jarvis/workspace/agents.py
index db3d6b1b25..5068060b44 100644
--- a/jarvis/workspace/agents.py
+++ b/jarvis/workspace/agents.py
@@ -40,8 +40,6 @@ from typing import Any, Literal
from jarvis.clis.prober import CliStatusProber
from jarvis.clis.spec import AuthConfig, CliSpec, InstallMethods, RiskConfig
from jarvis.terminal.shells import default_shell
-from jarvis.workspace.launch_picks import VALUE as picks_value
-from jarvis.workspace.launch_picks import LaunchPicks, flag_modes
log = logging.getLogger(__name__)
@@ -228,14 +226,6 @@ class WorkspaceAgent:
#: under one binary name. ``None`` when there is only ever one.
generation_probe: Callable[[], str | None] | None = None
- #: How this CLI takes a model / effort / permission pick on its launch argv
- #: (:mod:`jarvis.workspace.launch_picks`). ``None`` means "offers no picks":
- #: a pane of it opens on whatever the binary itself defaults to, and every
- #: picker upstream shows nothing to choose rather than a control that does
- #: nothing. Declaring it is what makes those three picks work for an entry —
- #: no layer above knows any CLI's flag spelling (AP-21).
- launch_picks: LaunchPicks | None = None
-
# --- How it behaves once it is running ----------------------------------
trust: TrustSpec | None = None
account: AccountSpec | None = None
@@ -595,108 +585,10 @@ def glm_spawn_env() -> dict[str, str] | None:
return env
-# ---------------------------------------------------------------- launch picks
-#
-# What each CLI accepts as "run on THIS model, think THIS hard, ask THIS often"
-# when a pane opens. Every flag below was read off the installed binary's own
-# ``--help`` and its rejected-value message, which is the only source that can
-# be trusted here: a wrong word is not a warning but a pane that dies on the
-# command line. The mode NAMES stay the agent chat's ladder vocabulary
-# (jarvis/agent_chat/permissions.py) even where the binary spells one
-# differently, so one word means one stance across the whole app.
-
-_CLAUDE_PICKS = LaunchPicks(
- provider="claude-api",
- model_args=("--model", picks_value),
- effort_args=("--effort", picks_value),
- # ``default`` is this CLI's ask-first mode. Recent builds call the same
- # stance ``manual`` in their help text and still accept ``default``
- # (verified on 2.1.247), so the older word is the one that runs on both.
- permission_args=flag_modes(
- "--permission-mode",
- "default",
- "acceptEdits",
- "plan",
- "auto",
- "dontAsk",
- "bypassPermissions",
- ),
-)
-
-#: GLM drives the Claude Code binary, so it takes the same permission words —
-#: but its models are Z.ai's own and this app ships no list of them, and the
-#: effort flag belongs to Anthropic's endpoint rather than Z.ai's. Offering
-#: neither is what keeps a picker from listing choices the endpoint refuses.
-_GLM_PICKS = LaunchPicks(provider="claude-api", permission_args=_CLAUDE_PICKS.permission_args)
-
-_CODEX_PICKS = LaunchPicks(
- provider="openai-codex",
- model_args=("--model", picks_value),
- # A ``-c`` override, not a flag of its own. The value is parsed as TOML and
- # falls back to the literal string, so the level goes in bare — quoting it
- # here would put the quote characters themselves into the setting.
- effort_args=("-c", f"model_reasoning_effort={picks_value}"),
- permission_args=(
- ("read-only", ("--sandbox", "read-only")),
- ("approve-for-me", ("--approve-for-me",)),
- ("auto", ("--sandbox", "workspace-write")),
- ("full-access", ("--dangerously-bypass-approvals-and-sandbox",)),
- ),
-)
-
-_AGY_PICKS = LaunchPicks(
- provider="antigravity",
- model_args=("--model", picks_value),
- effort_args=("--effort", picks_value),
- permission_args=(
- ("accept-edits", ("--mode", "accept-edits")),
- ("plan", ("--mode", "plan")),
- ("skip-permissions", ("--dangerously-skip-permissions",)),
- ),
- # A base Gemini id is an error without a level beside it.
- effort_required=True,
-)
-
-_GROK_PICKS = LaunchPicks(
- provider="grok-build",
- model_args=("--model", picks_value),
- effort_args=("--reasoning-effort", picks_value),
- # The binary also takes ``auto`` and ``dontAsk``; they are left out because
- # this app has no sentence describing what they mean for Grok Build, and a
- # picker entry nobody can explain is worse than one fewer choice.
- permission_args=flag_modes(
- "--permission-mode",
- "default",
- "acceptEdits",
- "plan",
- "bypassPermissions",
- ),
-)
-
-#: OpenCode and Kimi bring their own accounts and their own model aliases, so
-#: neither publishes a list this app could offer — the pick is whatever the
-#: person has configured, and the shape check in ``launch_picks`` is what
-#: stands in for a list. Their one permission flag is described by the shared
-#: API ladder, which has the right sentence for "everything runs without
-#: asking" already.
-_OPENCODE_PICKS = LaunchPicks(
- model_args=("--model", picks_value),
- permission_args=(("auto", ("--auto",)),),
- ladder="api",
-)
-
-_KIMI_PICKS = LaunchPicks(
- model_args=("--model", picks_value),
- permission_args=(("auto", ("--auto",)),),
- ladder="api",
-)
-
-
_AGENTS: dict[str, WorkspaceAgent] = {
"claude": make_cli_agent(
"claude",
"Claude Code",
- launch_picks=_CLAUDE_PICKS,
binary="claude",
npm_package="@anthropic-ai/claude-code",
homepage="https://claude.com/claude-code",
@@ -730,7 +622,6 @@ _AGENTS: dict[str, WorkspaceAgent] = {
"codex": make_cli_agent(
"codex",
"Codex",
- launch_picks=_CODEX_PICKS,
binary="codex",
npm_package="@openai/codex",
homepage="https://github.com/openai/codex",
@@ -753,7 +644,6 @@ _AGENTS: dict[str, WorkspaceAgent] = {
"opencode": make_cli_agent(
"opencode",
"OpenCode",
- launch_picks=_OPENCODE_PICKS,
binary="opencode",
homepage="https://opencode.ai",
description="Open-source terminal coding agent — bring your own model.",
@@ -788,7 +678,6 @@ _AGENTS: dict[str, WorkspaceAgent] = {
"kimi": make_cli_agent(
"kimi",
"Kimi Code",
- launch_picks=_KIMI_PICKS,
binary="kimi",
npm_package="@moonshot-ai/kimi-code",
homepage="https://moonshotai.github.io/kimi-code/en/",
@@ -839,7 +728,6 @@ _AGENTS: dict[str, WorkspaceAgent] = {
"glm": make_cli_agent(
"glm",
"GLM Coding Plan",
- launch_picks=_GLM_PICKS,
# The whole design of this entry: the binary IS Claude Code. Z.ai ships
# no CLI of its own — its own documentation says to run Anthropic's
# binary against a different endpoint — so detection, the install
@@ -861,7 +749,6 @@ _AGENTS: dict[str, WorkspaceAgent] = {
"grok-build": make_cli_agent(
"grok-build",
"Grok Build",
- launch_picks=_GROK_PICKS,
binary="grok",
homepage="https://x.ai/cli",
description="xAI's terminal coding agent — SuperGrok or X Premium+.",
@@ -888,7 +775,6 @@ _AGENTS: dict[str, WorkspaceAgent] = {
"antigravity": make_cli_agent(
"antigravity",
"Antigravity",
- launch_picks=_AGY_PICKS,
binary="agy",
homepage="https://antigravity.google",
description="Google's terminal coding agent — billed against the Google subscription.",
diff --git a/tests/fixtures/brain/fake_brain.py b/tests/fixtures/brain/fake_brain.py
index ee715b36d5..b1d893e802 100644
--- a/tests/fixtures/brain/fake_brain.py
+++ b/tests/fixtures/brain/fake_brain.py
@@ -19,10 +19,7 @@ class FakeBrain:
"""Fake brain provider for tests."""
name: str = "fake-brain"
- # A hosted-provider window. The manager sizes the tool surface to this
- # (BUG-187); a test that wants the small-local-model behaviour sets a
- # small window explicitly on its own fake.
- context_window: int = 200_000
+ context_window: int = 8192
supports_tools: bool = True
supports_vision: bool = False
diff --git a/tests/unit/agent_chat/test_agent_chat_core.py b/tests/unit/agent_chat/test_agent_chat_core.py
index 3a808caac7..134bd8edb4 100644
--- a/tests/unit/agent_chat/test_agent_chat_core.py
+++ b/tests/unit/agent_chat/test_agent_chat_core.py
@@ -477,93 +477,18 @@ def test_codex_reasoning_start_is_announced():
def test_resolve_runner_per_surface(monkeypatch):
- """The Jarvis surface is API endpoints only; the agent surface keeps its CLIs."""
+ """The Jarvis surface runs API-key and local rows on the brain; CLI seats stay CLIs."""
from jarvis.agent_chat import service as svc_mod
monkeypatch.setattr(svc_mod, "_claude_cli_installed", lambda: False)
assert svc_mod.resolve_runner("openai") == "api"
assert svc_mod.resolve_runner("openai", surface="jarvis") == "brain"
assert svc_mod.resolve_runner("ollama", surface="jarvis") == "brain"
+ assert svc_mod.resolve_runner("openai-codex", surface="jarvis") == "codex-cli"
+ assert svc_mod.resolve_runner("antigravity", surface="jarvis") == "agy-cli"
assert svc_mod.resolve_runner("claude-api") == "api"
assert svc_mod.resolve_runner("claude-api", surface="jarvis") == "brain"
- # A CLI-only row has no API path, so the surface that dropped its CLI
- # seats has no runner for it at all — and never offers it (see
- # test_the_jarvis_surface_offers_api_seats_only).
- assert svc_mod.resolve_runner("openai-codex", surface="jarvis") == "unknown"
- assert svc_mod.resolve_runner("antigravity", surface="jarvis") == "unknown"
- assert svc_mod.resolve_runner("openai-codex", surface="agent") == "codex-cli"
- assert svc_mod.resolve_runner("antigravity", surface="agent") == "agy-cli"
monkeypatch.setattr(svc_mod, "_claude_cli_installed", lambda: True)
assert svc_mod.resolve_runner("claude-api") == "claude-cli"
- # Even with Claude Code installed: the front page's chat runs the
- # Anthropic endpoint, not the subscription seat (maintainer 2026-08-26).
- assert svc_mod.resolve_runner("claude-api", surface="jarvis") == "brain"
+ assert svc_mod.resolve_runner("claude-api", surface="jarvis") == "claude-cli"
assert svc_mod.resolve_runner("no-such-provider", surface="jarvis") == "unknown"
-
-
-def test_the_jarvis_surface_offers_api_seats_only():
- """Every row the front page's chat lists has a brain plugin behind it."""
- from jarvis.agent_chat.catalog import PROVIDER_ROWS, offers, rows_for
- from jarvis.agent_chat.runner_api import supports_api_runner
-
- jarvis_ids = [row.id for row in rows_for("jarvis")]
- assert jarvis_ids and all(supports_api_runner(pid) for pid in jarvis_ids)
- # The CLI-only rows are gone from it and still there for the IDE's chat.
- for cli_row in ("openai-codex", "antigravity", "grok-build"):
- assert not offers("jarvis", cli_row)
- assert offers("agent", cli_row)
- assert [row.id for row in rows_for("agent")] == [row.id for row in PROVIDER_ROWS]
-
-
-def test_a_cli_seat_cannot_be_created_or_patched_onto_the_jarvis_chat(tmp_path):
- """The picker does not list them, and the routes refuse them either way."""
- import pytest
-
- from jarvis.agent_chat.service import AgentChatService
- from jarvis.agent_chat.store import AgentChatStore
-
- svc = AgentChatService(AgentChatStore(":memory:"), default_cwd=lambda: str(tmp_path))
- with pytest.raises(ValueError, match="not offered"):
- svc.create_session(provider="openai-codex", surface="jarvis")
- # The same row is fine on the surface that has CLI seats.
- assert svc.create_session(provider="openai-codex", surface="agent").provider == "openai-codex"
-
-
-def test_an_old_cli_seated_jarvis_chat_moves_to_its_api_twin(tmp_path):
- """A chat from before the change keeps its history and gains a working seat."""
- from jarvis.agent_chat.service import AgentChatService
- from jarvis.agent_chat.store import AgentChatStore
-
- store = AgentChatStore(":memory:")
- # ``gpt-5.2`` is in Codex's own catalog and not in OpenAI's, so it goes.
- codex = store.create_session(
- provider="openai-codex", model="gpt-5.2", effort="high", cwd=".", surface="jarvis"
- )
- # One the API does know rides along rather than resetting for nothing.
- shared = store.create_session(
- provider="openai-codex", model="gpt-5.5", effort="high", cwd=".", surface="jarvis"
- )
- claude = store.create_session(
- provider="claude-api", model="opusplan", effort="high", cwd=".", surface="jarvis"
- )
- kept = store.create_session(
- provider="claude-api", model="claude-opus-5", effort="high", cwd=".", surface="agent"
- )
- before = store.get_session(codex.session_id).updated_ms
-
- AgentChatService(store, default_cwd=lambda: str(tmp_path))
-
- moved = store.get_session(codex.session_id)
- assert (moved.provider, moved.model) == ("openai", "")
- assert (store.get_session(shared.session_id).provider, store.get_session(shared.session_id).model) == (
- "openai",
- "gpt-5.5",
- )
- # The list order is by updated_ms; a migration must not reshuffle it.
- assert moved.updated_ms == before
- # Claude keeps its row and loses only the model id the API cannot take.
- assert store.get_session(claude.session_id).provider == "claude-api"
- assert store.get_session(claude.session_id).model == ""
- # The IDE's chat is untouched.
- assert store.get_session(kept.session_id).provider == "claude-api"
- assert store.get_session(kept.session_id).model == "claude-opus-5"
diff --git a/tests/unit/agent_chat/test_agent_chat_surface_parity.py b/tests/unit/agent_chat/test_agent_chat_surface_parity.py
index f882c7360a..73b2fd9570 100644
--- a/tests/unit/agent_chat/test_agent_chat_surface_parity.py
+++ b/tests/unit/agent_chat/test_agent_chat_surface_parity.py
@@ -1,7 +1,8 @@
"""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). The value crosses
+plain coding-agent session (the Agentic IDE's chat mode), ``"local-models"``
+the Local models section's setup assistant. The value crosses
Python -> SQLite -> Pydantic -> TypeScript, so the four spellings are pinned
against each other here (AP-4) instead of trusted to stay in step by hand.
"""
@@ -38,6 +39,13 @@ 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_chat_attachments.py b/tests/unit/agent_chat/test_chat_attachments.py
deleted file mode 100644
index a910f5a59b..0000000000
--- a/tests/unit/agent_chat/test_chat_attachments.py
+++ /dev/null
@@ -1,257 +0,0 @@
-"""Files dropped, pasted or picked into a chat composer.
-
-Covers the whole path the composer uses: the attach route stores the bytes and
-returns what was read from them, and the message that follows carries those
-contents into the turn while the timeline still shows the person's own
-sentence.
-
-The vision layer is faked throughout. What is under test is the wiring — that a
-chat can take a file at all, which is what it could not do — not whether a
-model describes a picture well.
-"""
-
-from __future__ import annotations
-
-import asyncio
-from pathlib import Path
-
-import pytest
-from fastapi import FastAPI
-from fastapi.testclient import TestClient
-
-from jarvis.agent_chat import attachments as chat_attachments
-from jarvis.agent_chat.service import AgentChatService
-from jarvis.agent_chat.store import AgentChatStore
-from jarvis.agentic_ide import drop_analysis
-from jarvis.ui.web.agent_chat_routes import router
-
-# A one-pixel PNG — real bytes, so the store and the mime guess behave.
-PNG = bytes.fromhex(
- "89504e470d0a1a0a0000000d49484452000000010000000108060000001f15c4"
- "890000000a49444154789c6360000002000100" + "05fe02fe" + "0000000049454e44ae426082"
-)
-
-
-def _app(tmp_path: Path) -> FastAPI:
- app = FastAPI()
- app.include_router(router)
- app.state.agent_chat = None
- app.state.agent_chat_factory = lambda: AgentChatService(
- AgentChatStore(tmp_path / "db.sqlite"), default_cwd=lambda: str(tmp_path)
- )
- return app
-
-
-def described(monkeypatch: pytest.MonkeyPatch) -> None:
- """Every image comes back described, without a provider being involved."""
-
- async def fake_analyze(items, **_kwargs): # noqa: ANN001, ANN202
- return [
- drop_analysis.DropAnalysis(
- name=item.name,
- reference=reference,
- kind="image",
- detail="A screenshot of a chat composer with no attach button.",
- described_by=drop_analysis.BY_VISION,
- )
- for item, reference in items
- ]
-
- monkeypatch.setattr(drop_analysis, "analyze", fake_analyze)
-
-
-# ---------------------------------------------------------------- the route
-
-
-def test_attach_stores_the_bytes_and_returns_what_was_read(tmp_path: Path, described) -> None:
- with TestClient(_app(tmp_path)) as client:
- res = client.post(
- "/api/agent-chat/attachments",
- files=[("files", ("shot.png", PNG, "image/png"))],
- data={"cwd": str(tmp_path), "surface": "jarvis"},
- )
- assert res.status_code == 200, res.text
- body = res.json()
-
- (row,) = body["attachments"]
- assert row["name"].endswith(".png")
- assert row["described_by"] == "vision"
- assert "composer" in row["detail"]
- # The copy landed in the chat's own folder, where the agent can open it.
- copies = list((tmp_path / ".jarvis" / "drops").glob("*.png"))
- assert len(copies) == 1
- assert copies[0].read_bytes() == PNG
-
-
-def test_attach_falls_back_to_the_surface_folder_when_the_cwd_is_gone(
- tmp_path: Path, described
-) -> None:
- """A remembered folder that no longer exists must not refuse the file."""
- with TestClient(_app(tmp_path)) as client:
- res = client.post(
- "/api/agent-chat/attachments",
- files=[("files", ("shot.png", PNG, "image/png"))],
- data={"cwd": str(tmp_path / "moved-away"), "surface": "agent"},
- )
- assert res.status_code == 200, res.text
- assert res.json()["cwd"] == str(tmp_path)
-
-
-def test_attach_refuses_an_empty_drop(tmp_path: Path) -> None:
- with TestClient(_app(tmp_path)) as client:
- res = client.post(
- "/api/agent-chat/attachments",
- data={"cwd": str(tmp_path), "paths": " \n "},
- )
- assert res.status_code == 422
- assert "nothing" in res.json()["detail"].lower()
-
-
-def test_a_path_inside_the_folder_is_referenced_where_it_lies(
- tmp_path: Path, described
-) -> None:
- """Nothing is copied for a file the agent can already open."""
- existing = tmp_path / "notes.png"
- existing.write_bytes(PNG)
-
- with TestClient(_app(tmp_path)) as client:
- res = client.post(
- "/api/agent-chat/attachments",
- data={"cwd": str(tmp_path), "paths": str(existing)},
- )
- assert res.status_code == 200, res.text
- (row,) = res.json()["attachments"]
- assert "notes.png" in row["reference"]
- assert not (tmp_path / ".jarvis" / "drops").exists()
-
-
-# ------------------------------------------------------------- composition
-
-
-def test_compose_leaves_an_ordinary_message_alone() -> None:
- assert chat_attachments.compose("what is this", []) == "what is this"
- assert chat_attachments.compose(" spaced ", None) == "spaced"
-
-
-def test_compose_carries_the_contents_into_the_message() -> None:
- item = drop_analysis.DropAnalysis(
- name="shot.png",
- reference='"shot.png"',
- kind="image",
- detail="A red error banner over the login form.",
- described_by=drop_analysis.BY_VISION,
- )
- out = chat_attachments.compose("fix this", [item])
-
- assert out.startswith("fix this")
- # The description is what makes the drop useful to a model that cannot open
- # the file, so it must be IN the message, not merely referenced.
- assert "A red error banner over the login form." in out
- assert "shot.png" in out
-
-
-def test_to_analysis_survives_a_malformed_row() -> None:
- """The rows come back from a browser, so no shape may be assumed.
-
- A message somebody is waiting to send must not 500 over a stray field:
- anything that is not an object is dropped, and a row with a missing or
- mistyped field degrades to a named, empty-detail attachment.
- """
- rows = [
- {"name": "ok.png", "kind": "image", "detail": "d", "described_by": "vision"},
- {"kind": "image"}, # no name — kept under a placeholder, not dropped
- "not a dict", # not an object at all — dropped
- {"name": "odd.txt", "detail": 42}, # wrong type — degrades to empty
- ]
- out = chat_attachments.to_analysis(rows) # type: ignore[arg-type]
- assert [item.name for item in out] == ["ok.png", "file", "odd.txt"]
- assert out[2].detail == ""
-
-
-# ------------------------------------------------------ the message it rides
-
-
-def test_a_message_with_files_shows_the_sentence_and_sends_the_contents(
- tmp_path: Path,
-) -> None:
- """The event log holds both halves, and each is used for its own job."""
- svc = AgentChatService(
- AgentChatStore(tmp_path / "db.sqlite"), default_cwd=lambda: str(tmp_path)
- )
- session = svc.store.create_session(
- provider="fakeprov", model="", effort="", cwd=str(tmp_path)
- )
-
- async def run() -> None:
- # No runner is reachable for "fakeprov" here, so the turn fails after
- # the user message is persisted — which is the part under test.
- await svc.send(
- session.session_id,
- "what is wrong here",
- [
- {
- "name": "shot.png",
- "reference": '"shot.png"',
- "kind": "image",
- "detail": "A red error banner.",
- "described_by": "vision",
- "note": "",
- }
- ],
- )
- await svc.cancel(session.session_id)
-
- asyncio.run(run())
-
- events = svc.store.list_events(session.session_id)
- user = next(e for e in events if e["kind"] == "user_message")
- payload = user["payload"]
- # What the person typed — the timeline shows this.
- assert payload["typed"] == "what is wrong here"
- # What the turn received — history rebuilds from this.
- assert "A red error banner." in payload["text"]
- assert payload["text"].startswith("what is wrong here")
- # The receipt the timeline draws under the message.
- assert payload["attachments"] == [
- {"name": "shot.png", "kind": "image", "described_by": "vision", "note": ""}
- ]
-
-
-def test_files_alone_are_a_complete_message(tmp_path: Path) -> None:
- """Dropping a picture and pressing Enter says enough."""
- svc = AgentChatService(
- AgentChatStore(tmp_path / "db.sqlite"), default_cwd=lambda: str(tmp_path)
- )
- session = svc.store.create_session(
- provider="fakeprov", model="", effort="", cwd=str(tmp_path)
- )
-
- async def run() -> None:
- await svc.send(
- session.session_id,
- "",
- [{"name": "shot.png", "reference": "x", "kind": "image", "detail": "A chart."}],
- )
- await svc.cancel(session.session_id)
-
- asyncio.run(run())
- user = next(
- e for e in svc.store.list_events(session.session_id) if e["kind"] == "user_message"
- )
- assert "A chart." in user["payload"]["text"]
-
-
-def test_an_empty_message_with_nothing_attached_is_still_refused(tmp_path: Path) -> None:
- svc = AgentChatService(
- AgentChatStore(tmp_path / "db.sqlite"), default_cwd=lambda: str(tmp_path)
- )
- session = svc.store.create_session(
- provider="fakeprov", model="", effort="", cwd=str(tmp_path)
- )
-
- async def run() -> None:
- with pytest.raises(ValueError):
- await svc.send(session.session_id, " ", [])
-
- asyncio.run(run())
diff --git a/tests/unit/agent_chat/test_surface_kits.py b/tests/unit/agent_chat/test_surface_kits.py
index 8a2ae4b611..3a53ee22c8 100644
--- a/tests/unit/agent_chat/test_surface_kits.py
+++ b/tests/unit/agent_chat/test_surface_kits.py
@@ -1,19 +1,18 @@
-"""Surface kits: one lookup per call site, and what a kit hands a turn."""
+"""Surface kits: one lookup per call site, and the local-models surface's recipe."""
from __future__ import annotations
from pathlib import Path
from typing import Any
-import pytest
-
from jarvis.agent_chat import surface_kits
from jarvis.agent_chat.permissions import JARVIS_LADDER, ladder_key
from jarvis.agent_chat.runner_brain import build_override, kit_payload
from jarvis.agent_chat.service import resolve_runner
from jarvis.agent_chat.store import SURFACES, AgentChatSession
-from jarvis.agent_chat.surface_kits import SurfaceKit, kit_for
-from jarvis.core.protocols import Tool
+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
def _session(surface: str) -> AgentChatSession:
@@ -34,53 +33,49 @@ def _session(surface: str) -> AgentChatSession:
)
-class _Brain:
+class _SearchWeb:
+ name = "search_web"
+
def __init__(self) -> None:
- self._config = object()
+ self.queries: list[str] = []
+ 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."""
- def _tools(cfg: Any, brain: Any) -> dict[str, Tool]:
- return {"probe_read": object()} # type: ignore[dict-item]
+class _Brain:
+ def __init__(self, cfg: JarvisConfig, tools: dict[str, Any]) -> None:
+ self._config = cfg
+ self._tools = tools
- async def _extra(cfg: Any, brain: Any) -> str:
- return "BRIEFING"
- 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 kit
+def _cfg() -> JarvisConfig:
+ cfg = JarvisConfig()
+ cfg.brain.providers["ollama"] = BrainProviderConfig(model="qwen3.5:4b")
+ return cfg
def 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
+ assert kit_for("jarvis").brain_runner and kit_for(LOCAL_MODELS_SURFACE).brain_runner
assert not kit_for("agent").brain_runner
def test_the_four_call_sites_read_the_kit() -> None:
- assert resolve_runner("openai", surface="jarvis") == "brain"
+ assert resolve_runner("openai", surface=LOCAL_MODELS_SURFACE) == "brain"
assert resolve_runner("openai", surface="agent") == "api"
- assert ladder_key("jarvis", "brain") == JARVIS_LADDER
+ assert ladder_key(LOCAL_MODELS_SURFACE, "brain") == JARVIS_LADDER
assert ladder_key("agent", "api") == "api"
-def test_build_override_uses_the_kit_tools_and_briefing(monkeypatch: pytest.MonkeyPatch) -> None:
- _probe_kit(monkeypatch)
- session = _session("probe")
- tools = {"probe_read": object()}
+def test_build_override_uses_the_kit_tools_and_briefing() -> None:
+ session = _session(LOCAL_MODELS_SURFACE)
+ tools = {"lm_inventory": object()}
override = build_override(
session,
brain=None,
@@ -90,37 +85,61 @@ def test_build_override_uses_the_kit_tools_and_briefing(monkeypatch: pytest.Monk
kit_tools=tools, # type: ignore[arg-type]
system_extra="BRIEFING",
)
- assert set(override.tools_extra) == {"probe_read"}
+ assert set(override.tools_extra) == {"lm_inventory"}
assert override.system_extra == "BRIEFING"
- assert override.tool_context["tool_origin"] == "probe-origin"
+ assert override.tool_context["tool_origin"] == "local-models-assistant"
assert override.tool_context["approval_surface"] == "interactive"
- assert override.max_turns == 7
+ assert override.max_turns == 40
plain = 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_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"
+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
- 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 == ""
-def test_a_kit_filter_keeps_only_its_own_hands(monkeypatch: pytest.MonkeyPatch) -> None:
- kit = _probe_kit(monkeypatch)
+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
class _T:
def __init__(self, name: str) -> None:
self.name = name
- 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]
+ 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"]
assert kit_for("jarvis").tool_filter is None
diff --git a/tests/unit/agentic_ide/test_folders_create.py b/tests/unit/agentic_ide/test_folders_create.py
deleted file mode 100644
index 77663fa2cf..0000000000
--- a/tests/unit/agentic_ide/test_folders_create.py
+++ /dev/null
@@ -1,104 +0,0 @@
-"""Making a folder from the picker, and finding a hidden one by name.
-
-A new project has no folder to pick; a `.claude` folder is hidden from the
-search. Both left the wizard with "go make it in Explorer first", which is the
-detour the picker exists to remove.
-"""
-
-from __future__ import annotations
-
-from pathlib import Path
-
-import pytest
-
-from jarvis.agentic_ide.folders import create_folder, search_folders
-
-
-# ------------------------------------------------------------------- create
-def test_creates_one_folder_inside_an_existing_one(tmp_path: Path) -> None:
- entry, error = create_folder(tmp_path, "shop")
-
- assert error is None
- assert entry is not None
- assert entry.name == "shop"
- assert Path(entry.path) == tmp_path / "shop"
- assert (tmp_path / "shop").is_dir()
- assert entry.is_project is False
-
-
-def test_surrounding_whitespace_is_not_part_of_the_name(tmp_path: Path) -> None:
- entry, error = create_folder(tmp_path, " shop ")
-
- assert error is None
- assert entry is not None and entry.name == "shop"
-
-
-def test_a_folder_already_there_is_handed_back_not_refused(tmp_path: Path) -> None:
- (tmp_path / "shop").mkdir()
- (tmp_path / "shop" / ".git").mkdir()
-
- entry, error = create_folder(tmp_path, "shop")
-
- assert error is None
- assert entry is not None
- assert entry.is_repo is True
-
-
-def test_a_file_of_that_name_is_an_error(tmp_path: Path) -> None:
- (tmp_path / "shop").write_text("", encoding="utf-8")
-
- entry, error = create_folder(tmp_path, "shop")
-
- assert entry is None
- assert error is not None and "file" in error
-
-
[email protected]("name", ["", " ", ".", "..", "a/b", "a\\b"])
-def test_refuses_names_that_are_not_one_plain_segment(tmp_path: Path, name: str) -> None:
- entry, error = create_folder(tmp_path, name)
-
- assert entry is None
- assert error
- assert not any(p.is_dir() for p in tmp_path.iterdir())
-
-
-def test_a_missing_parent_is_reported_not_created(tmp_path: Path) -> None:
- entry, error = create_folder(tmp_path / "nowhere", "shop")
-
- assert entry is None
- assert error is not None and "nowhere" in error
- assert not (tmp_path / "nowhere").exists()
-
-
-def test_no_parent_means_home(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
- monkeypatch.setattr(Path, "home", classmethod(lambda cls: tmp_path))
-
- entry, error = create_folder(None, "shop")
-
- assert error is None
- assert entry is not None and Path(entry.path) == tmp_path / "shop"
-
-
-# ------------------------------------------------------------------- hidden
-def test_search_finds_a_hidden_folder_when_asked_for_by_its_dot_name(tmp_path: Path) -> None:
- (tmp_path / ".claude").mkdir()
- (tmp_path / "claude-notes").mkdir()
-
- names = [e.name for e in search_folders(".claude", roots=[tmp_path])]
-
- assert names == [".claude"]
-
-
-def test_search_still_hides_dot_folders_for_an_ordinary_query(tmp_path: Path) -> None:
- (tmp_path / ".claude").mkdir()
- (tmp_path / "claude-notes").mkdir()
-
- names = [e.name for e in search_folders("claude", roots=[tmp_path])]
-
- assert names == ["claude-notes"]
-
-
-def test_search_never_walks_into_a_hidden_folder(tmp_path: Path) -> None:
- (tmp_path / ".cache" / ".claude").mkdir(parents=True)
-
- assert search_folders(".claude", roots=[tmp_path]) == []
diff --git a/tests/unit/agentic_ide/test_pane_notifications.py b/tests/unit/agentic_ide/test_pane_notifications.py
index 7d111ebbff..5221275c08 100644
--- a/tests/unit/agentic_ide/test_pane_notifications.py
+++ b/tests/unit/agentic_ide/test_pane_notifications.py
@@ -18,13 +18,11 @@ and is unusable in a grid of twelve.
from __future__ import annotations
-import time
from pathlib import Path
from typing import Any
import pytest
-from jarvis.agentic_ide import activity as activity_mod
from jarvis.agentic_ide import notifications
from jarvis.agentic_ide import session as session_mod
from jarvis.agentic_ide.activity import STILL_S, read_activity
@@ -725,186 +723,19 @@ async def test_a_tool_step_gap_does_not_demand_reconfirmation(
watcher.poll(registry, now=at)
assert term.activity == "working", "sustained movement confirms"
- # A quiet tool step: the screen stands still past its freshness tail. The
- # RAW reading says waiting; the badge holds (see the next test).
+ # A quiet tool step: the screen stands still past its freshness tail.
watcher.poll(registry, now=1008.0 + STILL_S + 1)
- assert watcher._panes[(_session.id, term.key)].activity == "waiting" # noqa: SLF001
- assert term.activity == "working"
-
- # The pause outlasts the hold: now it is a stop, dated from the last paint.
- watcher.poll(registry, now=1008.0 + notifications.WORK_HOLD_S + 1)
assert term.activity == "waiting"
# Work resumes. The badge must follow on the SAME sweep, not five later.
term.transcript.clear()
_draw(term, "\r\n· working again after the tool call\r\n")
- term.last_output_at = 1020.0
- watcher.poll(registry, now=1020.0)
+ term.last_output_at = 1015.0
+ watcher.poll(registry, now=1015.0)
assert term.activity == "working", "a resuming job needs no re-confirmation"
-async def test_a_short_pause_is_not_published_as_done(registry: Registry, tmp_path: Path) -> None:
- """The dip itself. A working pane that stands still for a beat — a slow
- tool call, the redraw shadow of a resize — used to flip the badge to a
- finished dot for a sweep and restart its clock: a pane whose own spinner
- read "11m 00s" wore "Working for 7s" (maintainer, 2026-08-27). The badge
- now holds "working" for WORK_HOLD_S past the raw flip, and the episode's
- start survives the pause."""
- watcher = notifications.watcher()
- _session, term = await _pane(registry, tmp_path)
- term.last_submit_at = 500.0
- term.submit_generation = term.process_generation
- _quiet_since(term, 999.0)
- _draw(term, IDLE_SCREEN)
- watcher.poll(registry, now=996.0)
-
- for step, at in enumerate((1000.0, 1002.0, 1004.0, 1006.0, 1008.0)):
- term.transcript.clear()
- _draw(term, f"\r\n· working, frame {step}\r\n")
- term.last_output_at = at
- watcher.poll(registry, now=at)
- assert (term.activity, term.activity_since) == ("working", 1000.0)
-
- # Still past STILL_S — the raw reading has flipped — but inside the hold.
- for at in (1008.0 + STILL_S + 1, 1008.0 + notifications.WORK_HOLD_S):
- watcher.poll(registry, now=at)
- assert term.activity == "working", f"a pause of {at - 1008.0:.0f}s is not a stop"
- assert term.activity_since == 1000.0, "the clock counts the whole episode"
-
- # Work resumes: same episode, same clock.
- term.transcript.clear()
- _draw(term, "\r\n· working again\r\n")
- term.last_output_at = 1014.0
- watcher.poll(registry, now=1014.0)
- assert (term.activity, term.activity_since) == ("working", 1000.0)
-
-
-async def test_a_stop_is_dated_from_the_last_paint(registry: Registry, tmp_path: Path) -> None:
- """When the hold runs out the badge says "done" — and says since WHEN it
- has been done: the moment the screen last moved, not the sweep that
- finally admitted it. "Done for 0s" about a pane quiet for nine seconds is
- the clock lying the other way."""
- watcher = notifications.watcher()
- _session, term = await _pane(registry, tmp_path)
- term.last_submit_at = 500.0
- term.submit_generation = term.process_generation
- _quiet_since(term, 999.0)
- _draw(term, IDLE_SCREEN)
- watcher.poll(registry, now=996.0)
- for step, at in enumerate((1000.0, 1002.0, 1004.0, 1006.0, 1008.0)):
- term.transcript.clear()
- _draw(term, f"\r\n· working, frame {step}\r\n")
- term.last_output_at = at
- watcher.poll(registry, now=at)
-
- watcher.poll(registry, now=1008.0 + STILL_S + 1)
- watcher.poll(registry, now=1008.0 + notifications.WORK_HOLD_S + 1)
-
- assert term.activity == "waiting"
- assert term.activity_since == 1008.0, "quiet since the last paint, not since the sweep"
-
-
-async def test_a_question_is_not_held_back_by_the_hold(registry: Registry, tmp_path: Path) -> None:
- """A working pane that stops on a permission prompt has stopped FOR THE
- USER. The hold covers a plain pause only; a question on screen takes the
- badge over the moment the raw reading sees it."""
- watcher = notifications.watcher()
- _session, term = await _pane(registry, tmp_path)
- term.last_submit_at = 500.0
- term.submit_generation = term.process_generation
- _quiet_since(term, 999.0)
- _draw(term, IDLE_SCREEN)
- watcher.poll(registry, now=996.0)
- for step, at in enumerate((1000.0, 1002.0, 1004.0, 1006.0, 1008.0)):
- term.transcript.clear()
- _draw(term, f"\r\n· working, frame {step}\r\n")
- term.last_output_at = at
- watcher.poll(registry, now=at)
-
- term.transcript.clear()
- _draw(term, QUESTION_SCREEN)
- term.last_output_at = 1009.0
- watcher.poll(registry, now=1009.0)
- watcher.poll(registry, now=1009.0 + STILL_S + 1)
-
- assert term.activity == "asking"
-
-
-# ------------------------------------------------------------ the live feed
-#
-# The sweep is the one thing that knows the MOMENT a pane's word changes; the
-# feed turns that into one event per change for every client on the app
-# socket, so a finished session shows as finished without waiting for a poll.
-
-
-async def test_the_feed_reports_a_pane_once_per_change(registry: Registry, tmp_path: Path) -> None:
- feed = notifications.ActivityFeed()
- session, term = await _pane(registry, tmp_path)
-
- first = feed.changes(registry)
- assert [(row["session_id"], row["key"], row["name"]) for row in first] == [
- (session.id, term.key, "Alex")
- ]
- assert feed.changes(registry) == [], "nothing changed, nothing to say"
-
- # The sweep stamps a new word (on the wall clock: `reading()` trusts a
- # stamp only while it is fresh against the real time).
- now = time.time()
- activity_mod.stamp(term, "working", now=now)
- term.last_submit_at = now
- term.submit_generation = term.process_generation
- rows = feed.changes(registry)
- assert [(row["activity"], row["activity_since"], row["worked"]) for row in rows] == [
- ("working", now, True)
- ]
- assert feed.changes(registry) == []
-
- # A pane that is gone is forgotten, not carried as a ghost.
- await registry.close_terminal(term.name)
- assert feed.changes(registry) == []
- assert feed._last == {} # noqa: SLF001 - the leak this guards against is invisible otherwise
-
-
-async def test_changes_go_to_the_bus_as_pane_activity_events(
- registry: Registry, tmp_path: Path
-) -> None:
- """What a client receives: the activity half of a `/panes` row, verbatim,
- under the workspace id and the pane's stable key — enough to patch the
- row in place without a second request."""
- from jarvis.core.events import AgenticIdePaneActivity
-
- published: list[Any] = []
-
- async def publish(event: Any) -> None:
- published.append(event)
-
- notifications.set_publisher(publish)
- session, term = await _pane(registry, tmp_path)
-
- await notifications._publish_changes(registry) # noqa: SLF001 - the sweep's own step
- await notifications._publish_changes(registry) # noqa: SLF001
-
- assert len(published) == 1
- event = published[0]
- assert isinstance(event, AgenticIdePaneActivity)
- assert (event.session_id, event.key, event.name) == (session.id, term.key, "Alex")
- assert event.status == "live"
- assert event.activity == term.reading().activity
- assert event.worked is False
- assert event.source_layer == "agentic_ide.notifications"
-
-
-async def test_a_deaf_bus_does_not_end_the_sweep(registry: Registry, tmp_path: Path) -> None:
- async def publish(_event: Any) -> None:
- raise RuntimeError("bus closed")
-
- notifications.set_publisher(publish)
- await _pane(registry, tmp_path)
-
- await notifications._publish_changes(registry) # noqa: SLF001 - must not raise
-
-
async def test_a_question_is_reported_even_though_it_never_worked(
registry: Registry, tmp_path: Path
) -> None:
diff --git a/tests/unit/brain/test_context_window_fit.py b/tests/unit/brain/test_context_window_fit.py
deleted file mode 100644
index 21f56a9556..0000000000
--- a/tests/unit/brain/test_context_window_fit.py
+++ /dev/null
@@ -1,250 +0,0 @@
-"""The tool surface fits the answering brain's context window (BUG-187).
-
-Live 2026-08-27 10:11 (and 2026-08-26 20:32, 20:58): the front page's chat
-ran on a local 32k model, the registry held 221 tools (78 built-in, 131 from
-three connected MCP servers, 12 CLIs) and a plain "Hallo" went out as 67,852
-tokens. The server refused it with a 400 that named the cause, the
-one-provider chain was exhausted, and the user read "I can't reach my provider
-— check the network". Two defects, two guards:
-
-1. Nothing read ``Brain.context_window`` — ``_fit_tools_to_context_window``
- now sizes the surface: connected-server tools leave first, then the largest
- remaining ones, mandated tools never.
-2. The 400 was classified as a generic call failure —
- ``_classify_provider_error`` now returns ``context_overflow`` and the cause
- phrase / diagnostic name the size, not the network.
-"""
-from __future__ import annotations
-
-from dataclasses import dataclass, field
-from typing import Any
-
-import pytest
-
-from jarvis.brain.manager import (
- _DEAD_LIST_KINDS,
- _PROVIDER_DOWN_CAUSE_PHRASES,
- BrainManager,
- _classify_provider_error,
- _fit_tools_to_context_window,
- _format_provider_chain_error,
- _primary_provider_down_cause,
- _provider_down_phrase,
- _tool_surface_tokens,
-)
-
-# The exact server refusal from the live log (Ollama over the OpenAI route).
-_LIVE_OLLAMA_400 = (
- "Error code: 400 - {'error': {'message': '{\"error\":{\"code\":400,"
- "\"message\":\"request (67852 tokens) exceeds the available context size "
- "(32768 tokens), try increasing it\",\"type\":\"exceed_context_size_error\","
- "\"n_prompt_tokens\":67852,\"n_ctx\":32768}}', 'type': 'invalid_request_error'}}"
-)
-
-
-@dataclass
-class _FakeTool:
- name: str
- description: str = "does a thing"
- schema: dict[str, Any] = field(default_factory=lambda: {"type": "object", "properties": {}})
- is_mcp_tool: bool = False
-
-
-def _tool(name: str, *, size: int = 1, mcp: bool = False) -> _FakeTool:
- """A tool whose wire size scales with ``size`` (schema padding)."""
- props = {f"arg{i}": {"type": "string", "description": "x" * 40} for i in range(size)}
- return _FakeTool(
- name=name,
- schema={"type": "object", "properties": props},
- is_mcp_tool=mcp,
- )
-
-
-class _FakeBrain:
- name = "fake"
- context_window = 0
- supports_vision = False
-
- def __init__(self, window: int) -> None:
- self.context_window = window
-
-
-# --------------------------------------------------------------- the fit
-
-
-class TestFitToolsToContextWindow:
- def test_no_declared_window_leaves_the_surface_alone(self) -> None:
- tools = {"a": _tool("a", size=50), "b": _tool("b", size=50)}
- fitted, dropped = _fit_tools_to_context_window(
- tools, context_window=0, used_tokens=1_000_000
- )
- assert fitted is tools
- assert dropped == []
-
- def test_a_surface_that_fits_is_untouched(self) -> None:
- tools = {"a": _tool("a"), "b": _tool("b", mcp=True)}
- fitted, dropped = _fit_tools_to_context_window(
- tools, context_window=100_000, used_tokens=10_000
- )
- assert fitted is tools
- assert dropped == []
-
- def test_connected_server_tools_leave_before_built_in_ones(self) -> None:
- # Two small built-ins and two LARGE MCP tools; the budget holds only
- # the built-ins. Size alone would keep nothing built-in either way —
- # the group order is what protects Jarvis's own hands.
- tools = {
- "run_shell": _tool("run_shell", size=2),
- "search_web": _tool("search_web", size=2),
- "github/create_issue": _tool("github/create_issue", size=20, mcp=True),
- "linear/list_issues": _tool("linear/list_issues", size=20, mcp=True),
- }
- built_in_cost = sum(
- _tool_surface_tokens(n, t) for n, t in tools.items() if not t.is_mcp_tool
- )
- fitted, dropped = _fit_tools_to_context_window(
- tools, context_window=built_in_cost + 100, used_tokens=100
- )
- assert set(fitted) == {"run_shell", "search_web"}
- assert dropped == ["linear/list_issues", "github/create_issue"] or dropped == [
- "github/create_issue",
- "linear/list_issues",
- ]
-
- def test_then_the_largest_remaining_tools_go_first(self) -> None:
- tools = {
- "tiny": _tool("tiny", size=1),
- "huge": _tool("huge", size=40),
- "medium": _tool("medium", size=5),
- }
- budget = _tool_surface_tokens("tiny", tools["tiny"]) + _tool_surface_tokens(
- "medium", tools["medium"]
- )
- fitted, dropped = _fit_tools_to_context_window(
- tools, context_window=budget, used_tokens=0
- )
- assert dropped == ["huge"]
- assert list(fitted) == ["tiny", "medium"] # registry order preserved
-
- def test_kept_names_are_never_dropped(self) -> None:
- tools = {
- "mandated": _tool("mandated", size=40),
- "other": _tool("other", size=1),
- }
- fitted, dropped = _fit_tools_to_context_window(
- tools, context_window=10, used_tokens=0, keep={"mandated"}
- )
- assert "mandated" in fitted
- assert dropped == ["other"]
-
- def test_prompt_larger_than_window_drops_every_droppable_tool(self) -> None:
- tools = {"a": _tool("a"), "b": _tool("b", mcp=True)}
- fitted, dropped = _fit_tools_to_context_window(
- tools, context_window=1_000, used_tokens=5_000
- )
- assert fitted == {}
- assert set(dropped) == {"a", "b"}
-
-
-class TestFitOnTheManager:
- def _mgr(self) -> BrainManager:
- m = BrainManager.__new__(BrainManager) # bypass heavy __init__
- m._tools = {}
- m._evidence_required_tool = None
- m._skill_turn_match = None
- return m
-
- def test_cloud_sized_window_keeps_the_whole_surface(self) -> None:
- m = self._mgr()
- tools = {f"t{i}": _tool(f"t{i}", size=10, mcp=i % 2 == 0) for i in range(221)}
- fitted = m._fit_tools_to_brain(
- tools, _FakeBrain(1_048_576), system_prompt="x" * 40_000, history=None
- )
- assert fitted is tools
-
- def test_local_window_trims_the_live_shape(self) -> None:
- # 221 tools, a long system prompt, a 32k window: the surface shrinks
- # and the connected-server tools are the ones that went.
- m = self._mgr()
- tools = {f"t{i}": _tool(f"t{i}", size=10, mcp=i % 2 == 0) for i in range(221)}
- fitted = m._fit_tools_to_brain(
- tools, _FakeBrain(32_768), system_prompt="x" * 30_000, history=None
- )
- assert 0 < len(fitted) < 221
- assert not any(t.is_mcp_tool for t in fitted.values())
-
- def test_mandated_tool_survives_a_local_window(self) -> None:
- m = self._mgr()
- m._evidence_required_tool = "search_web"
- m._skill_turn_match = object()
- tools = {
- "search_web": _tool("search_web", size=60),
- "run-skill": _tool("run-skill", size=60),
- "github/x": _tool("github/x", size=60, mcp=True),
- }
- fitted = m._fit_tools_to_brain(
- tools, _FakeBrain(4_200), system_prompt="", history=None
- )
- assert {"search_web", "run-skill"} <= set(fitted)
- assert "github/x" not in fitted
-
- def test_undeclared_window_is_left_alone(self) -> None:
- m = self._mgr()
-
- class _Windowless:
- name = "w"
-
- tools = {"a": _tool("a", size=60)}
- assert m._fit_tools_to_brain(tools, _Windowless(), system_prompt="", history=None) is tools
-
-
-# ---------------------------------------------------------- the cause
-
-
-class TestContextOverflowCause:
- @pytest.mark.parametrize(
- "msg",
- [
- _LIVE_OLLAMA_400,
- "Error code: 400 - This model's maximum context length is 128000 tokens.",
- "Error code: 400 - context_length_exceeded",
- "prompt is too long: 213462 tokens > 200000 maximum",
- "400 INVALID_ARGUMENT. The input token count (2000000) exceeds the "
- "maximum number of tokens allowed (1048576).",
- ],
- )
- def test_size_refusals_classify_as_context_overflow(self, msg: str) -> None:
- assert _classify_provider_error(msg, default="call_fail") == "context_overflow"
-
- def test_overflow_never_dead_lists_the_provider(self) -> None:
- assert "context_overflow" not in _DEAD_LIST_KINDS
-
- def test_a_plain_400_still_falls_through(self) -> None:
- kind = _classify_provider_error("Error code: 400 - bad request", default="call_fail")
- assert kind == "call_fail"
-
- def test_spoken_cause_names_the_size_not_the_network(self) -> None:
- errors = [("ollama", "qwen3.8-16gb:latest", "context_overflow", _LIVE_OLLAMA_400)]
- cause = _primary_provider_down_cause(errors)
- assert cause == "context_overflow"
- for lang in ("de", "en", "es"):
- phrase = _provider_down_phrase(lang, 0, cause)
- assert phrase == _PROVIDER_DOWN_CAUSE_PHRASES["context_overflow"][lang]
- low = phrase.lower()
- assert "netzwerk" not in low and "network" not in low and "red" != low
- assert "ollama" not in low # voice-safe: no provider names
-
- def test_missing_key_still_outranks_an_overflow(self) -> None:
- errors = [
- ("ollama", "m", "context_overflow", "…"),
- ("gemini", "g", "missing_key", "…"),
- ]
- assert _primary_provider_down_cause(errors) == "missing_key"
-
- def test_developer_diagnostic_stops_blaming_the_network(self) -> None:
- text = _format_provider_chain_error(
- [("ollama", "qwen3.8-16gb:latest", "context_overflow", _LIVE_OLLAMA_400)]
- )
- assert "Kontextfenster" in text # i18n-allow: the diagnostic is German
- assert "ollama" in text
- assert "Netzwerk" not in text # i18n-allow
diff --git a/tests/unit/brain/test_gemini_schema_sanitize.py b/tests/unit/brain/test_gemini_schema_sanitize.py
index 9ed1d07064..f169d408f7 100644
--- a/tests/unit/brain/test_gemini_schema_sanitize.py
+++ b/tests/unit/brain/test_gemini_schema_sanitize.py
@@ -12,9 +12,7 @@ Drive question got no real answer for reasons unrelated to Drive.
import json
-import pytest
-
-from jarvis.plugins.brain.gemini import _gemini_schema_keys, _sanitize_for_gemini
+from jarvis.plugins.brain.gemini import _sanitize_for_gemini
def _flatten(schema: dict) -> str:
@@ -75,86 +73,3 @@ def test_sanitizer_recurses_into_nested_and_lists():
assert "propertyNames" not in _flatten(clean)
# Structure preserved.
assert clean["properties"]["outer"]["items"]["type"] == "object"
-
-
-def test_an_unknown_extension_key_is_dropped_whatever_it_is_called():
- """The 2026-08-26 outage: the GitHub MCP server tags parameters with
- ``x-mcp-header``. It was on no block-list, so 81 validation errors killed
- the whole request and the front page's chat answered "I can't reach my
- provider". An allow-list does not need to have heard of it."""
- bad = {
- "type": "object",
- "properties": {
- "owner": {"type": "string", "description": "Repo owner", "x-mcp-header": "owner"},
- "repo": {"type": "string", "x-mcp-header": "repo"},
- },
- "required": ["owner", "repo"],
- }
- clean = _sanitize_for_gemini(bad)
- assert "x-mcp-header" not in _flatten(clean)
- # A stripped tool is not a fix: the parameters and their prose survive.
- assert set(clean["properties"]) == {"owner", "repo"}
- assert clean["properties"]["owner"]["description"] == "Repo owner"
- assert clean["required"] == ["owner", "repo"]
- # And an invented key nobody has seen yet goes the same way.
- invented = _sanitize_for_gemini({"type": "string", "x-vendor-someday": {"a": 1}})
- assert invented == {"type": "string"}
-
-
-def test_a_property_named_like_a_schema_keyword_survives():
- """Under ``properties`` the keys are names a tool author chose. Judging
- those against the allow-list would delete the parameters themselves — the
- one way an allow-list can be worse than the block-list it replaces."""
- schema = {
- "type": "object",
- "properties": {
- "strict": {"type": "boolean"},
- "propertyNames": {"type": "string"},
- "x-mcp-header": {"type": "string"},
- },
- }
- clean = _sanitize_for_gemini(schema)
- assert set(clean["properties"]) == {"strict", "propertyNames", "x-mcp-header"}
- assert clean["properties"]["strict"]["type"] == "boolean"
-
-
-def test_a_data_value_is_not_walked_as_a_schema():
- """``example``/``default`` carry the tool author's DATA. A dict in there
- that happens to look like a schema must come back byte-identical."""
- schema = {
- "type": "object",
- "properties": {
- "cfg": {"type": "object", "default": {"strict": True, "propertyNames": "x"}},
- },
- }
- clean = _sanitize_for_gemini(schema)
- assert clean["properties"]["cfg"]["default"] == {"strict": True, "propertyNames": "x"}
-
-
-def test_the_allow_list_comes_from_the_installed_library():
- """The model that rejects the request is the only honest source for what
- it accepts — so the list is read off it, not spelled out beside it."""
- keys = _gemini_schema_keys()
- assert {"type", "properties", "items", "required", "description"} <= keys
- assert "x-mcp-header" not in keys and "strict" not in keys
-
-
-def test_the_sanitized_schema_passes_googles_own_validator():
- """The end-to-end claim: what we send validates where it is validated."""
- types = pytest.importorskip("google.genai.types")
- dirty = {
- "type": "object",
- "properties": {
- "owner": {"type": "string", "x-mcp-header": "owner"},
- "page": {"type": "integer", "exclusiveMinimum": 0},
- "anchor": {"type": "string", "propertyNames": {"type": "string"}},
- "opts": {"type": "object", "strict": True, "additionalProperties": False},
- },
- "required": ["owner"],
- }
- with pytest.raises(Exception):
- types.Schema.model_validate(dirty)
- clean = _sanitize_for_gemini(dirty)
- types.Schema.model_validate(clean) # must not raise
- # The exclusive bound was converted, not merely dropped.
- assert clean["properties"]["page"]["minimum"] == 0
diff --git a/tests/unit/cli_ctl/test_commands_local_models_assistant.py b/tests/unit/cli_ctl/test_commands_local_models_assistant.py
new file mode 100644
index 0000000000..379f4de0dd
--- /dev/null
+++ b/tests/unit/cli_ctl/test_commands_local_models_assistant.py
@@ -0,0 +1,58 @@
+"""`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/plugins/tool/test_youtube_music_rest.py b/tests/unit/plugins/tool/test_youtube_music_rest.py
index 55d8b697c8..951c9208b1 100644
--- a/tests/unit/plugins/tool/test_youtube_music_rest.py
+++ b/tests/unit/plugins/tool/test_youtube_music_rest.py
@@ -447,61 +447,6 @@ async def test_control_with_nothing_registered_is_an_error():
assert "Nothing is registered" in out["error"]
-# -- blind media keys (a machine that cannot read its media session) ---------
-#
-# Live 2026-08-26 19:50: "play some cool music" arrived as play without a
-# title, the machine had no winrt, the tool pressed the play/pause toggle
-# blindly and answered ``ok: true, resumed: true`` — the voice said "I've
-# just started some cool music on YouTube Music" over a silent machine.
-
-
-def _blind() -> FakeMedia:
- return FakeMedia(now=None, can_read=False, backend="media-keys", note="install X")
-
-
-async def test_blind_play_with_nothing_known_paused_presses_nothing_and_says_so():
- media = _blind()
- out = await _tool(_search_handler, media=media).play(query="")
- assert media.calls == []
- assert "say what to play" in out["error"]
-
-
-async def test_blind_pause_is_an_attempt_not_a_result():
- media = _blind()
- out = await _tool(_search_handler, media=media).pause()
- assert media.calls == ["pause"]
- assert out["ok"] is True and out["verified"] is False
- assert "cannot confirm" in out["note"] and "install X" in out["note"]
- assert "track" not in out
-
-
-async def test_blind_play_after_a_blind_pause_is_a_resume_attempt():
- media = _blind()
- tool = _tool(_search_handler, media=media)
- await tool.pause()
- out = await tool.play(query="")
- assert media.calls == ["pause", "play"]
- assert out["ok"] is True and out["resumed"] is True and out["verified"] is False
- # The resume spent the pause: a second bare play is a guess again.
- out = await tool.play(query="")
- assert media.calls == ["pause", "play"] and "say what to play" in out["error"]
-
-
-async def test_readable_session_control_is_verified():
- media = FakeMedia(now=_playing())
- out = await _tool(_search_handler, media=media).pause()
- assert out["ok"] is True and out["verified"] is True and out["track"] == "Karma Police"
-
-
-async def test_blind_play_of_a_song_opens_the_link_but_never_claims_playback():
- media = _blind()
- opener = Opener(media=media)
- out = await _tool(_search_handler, media=media, opener=opener).play(query="Karma Police")
- assert opener.urls == [song_url("vid123")]
- assert out["ok"] is True and out["playback_confirmed"] is False
- assert out["verified"] is False and "cannot confirm" in out["note"]
-
-
# -- library writes -----------------------------------------------------------
diff --git a/tests/unit/realtime/local_server/test_boot_progress.py b/tests/unit/realtime/local_server/test_boot_progress.py
index 15b9e2a10a..402d0f3408 100644
--- a/tests/unit/realtime/local_server/test_boot_progress.py
+++ b/tests/unit/realtime/local_server/test_boot_progress.py
@@ -126,6 +126,29 @@ class TestCrashTail:
"Windows fatal exception: access violation",
]
+ def test_an_older_generation_is_not_reported_as_this_crash(self) -> None:
+ """Live 2026-08-27: a child that exited saying nothing was reported
+ with a traceback from seven hours earlier, because the server log is
+ append-only across generations."""
+ lines = [
+ "2026-08-27 11:44:27,171 - openai._base_client - INFO - Retrying request",
+ "openai.APITimeoutError: Request timed out.",
+ "2026-08-27 18:11:30,000 - speech_to_speech.VAD.smart_turn - INFO - Loaded",
+ "Windows fatal exception: access violation",
+ ]
+ tail = boot_progress.crash_tail(lines, since=_epoch("2026-08-27 18:11:25"))
+ assert tail == [
+ "2026-08-27 18:11:30,000 - speech_to_speech.VAD.smart_turn - INFO - Loaded",
+ "Windows fatal exception: access violation",
+ ]
+
+ def test_a_generation_that_said_nothing_reports_nothing(self) -> None:
+ lines = [
+ "2026-08-27 11:44:27,171 - openai._base_client - INFO - Retrying request",
+ "openai.APITimeoutError: Request timed out.",
+ ]
+ assert boot_progress.crash_tail(lines, since=_epoch("2026-08-27 18:11:25")) == []
+
def test_output_is_bounded_in_lines_and_line_length(self) -> None:
lines = [f"line {index} " + "y" * 1000 for index in range(200)]
tail = boot_progress.crash_tail(lines)
diff --git a/tests/unit/realtime/local_server/test_supervisor.py b/tests/unit/realtime/local_server/test_supervisor.py
index 9f2b762b88..b59fb18fb9 100644
--- a/tests/unit/realtime/local_server/test_supervisor.py
+++ b/tests/unit/realtime/local_server/test_supervisor.py
@@ -1635,9 +1635,7 @@ def test_voice_brain_command_creates_a_bounded_ollama_profile(monkeypatch) -> No
# The size itself follows the machine (test_voice_brain_context.py); here
# the create round-trip is under test, so the choice is pinned.
- monkeypatch.setattr(
- supervisor, "voice_brain_context_tokens", lambda *a, **k: (8192, "pinned")
- )
+ monkeypatch.setattr(supervisor, "voice_brain_context_tokens", lambda *a, **k: (8192, "pinned"))
requests: list[tuple[str, dict[str, Any]]] = []
@@ -1673,9 +1671,7 @@ def test_voice_brain_command_creates_a_bounded_ollama_profile(monkeypatch) -> No
def test_voice_brain_profile_is_idempotent_across_restarts(monkeypatch) -> None:
import urllib.request
- monkeypatch.setattr(
- supervisor, "voice_brain_context_tokens", lambda *a, **k: (8192, "pinned")
- )
+ monkeypatch.setattr(supervisor, "voice_brain_context_tokens", lambda *a, **k: (8192, "pinned"))
payloads: list[dict[str, Any]] = []
@@ -1737,6 +1733,169 @@ def test_warm_brain_pings_ollama_with_keep_alive(monkeypatch) -> None:
assert payload["keep_alive"] == supervisor.BRAIN_KEEP_ALIVE
+def test_anchor_brain_load_outlives_the_caller(monkeypatch) -> None:
+ """Ollama drops a model load the moment its LAST client hangs up, so the
+ request that carries a cold load must not be one the spawn path waits on
+ (live 2026-08-27: the child's own 20 s warm-up aborted the load it needed,
+ six times, and died with APITimeoutError)."""
+ import urllib.request
+
+ supervisor._reset_for_tests()
+ monkeypatch.setattr(supervisor, "idle_release_s", lambda: 0.0)
+
+ entered = threading.Event()
+ release = threading.Event()
+ seen: list[tuple[str, dict[str, Any], float]] = []
+
+ class _Response:
+ def __enter__(self) -> _Response:
+ return self
+
+ def __exit__(self, *args: Any) -> None:
+ return None
+
+ def held_urlopen(request: Any, timeout: float = 0.0) -> _Response:
+ seen.append((request.full_url, json.loads(request.data.decode("utf-8")), timeout))
+ entered.set()
+ release.wait(5.0)
+ return _Response()
+
+ monkeypatch.setattr(urllib.request, "urlopen", held_urlopen)
+
+ assert supervisor.anchor_brain_load(launch_command=_COMMAND) is True
+ assert entered.wait(5.0), "the anchoring request never went out"
+ # The caller is back while the load is still in flight — and a second
+ # spawn attempt must not pile another request on the same weights.
+ assert supervisor.anchor_brain_load(launch_command=_COMMAND) is False
+ release.set()
+
+ url, payload, timeout = seen[0]
+ assert url == "http://127.0.0.1:11434/api/generate"
+ assert payload == {
+ "model": "qwen2.5:7b",
+ "prompt": "",
+ "keep_alive": supervisor.BRAIN_KEEP_ALIVE,
+ "stream": False,
+ }
+ assert timeout == supervisor.BRAIN_ANCHOR_TIMEOUT_S
+ assert len(seen) == 1
+
+
+def test_anchor_brain_load_without_a_brain_flag_is_a_noop() -> None:
+ supervisor._reset_for_tests()
+ assert supervisor.anchor_brain_load(launch_command="serve --mode realtime") is False
+
+
+def test_a_failed_anchor_frees_the_slot_for_the_next_spawn(monkeypatch) -> None:
+ """A refused endpoint must not leave the model permanently 'anchored'."""
+ import urllib.error
+ import urllib.request
+
+ supervisor._reset_for_tests()
+ attempts: list[str] = []
+
+ def dead(request: Any, timeout: float = 0.0) -> None:
+ attempts.append(request.full_url)
+ raise urllib.error.URLError("refused")
+
+ monkeypatch.setattr(urllib.request, "urlopen", dead)
+
+ assert supervisor.anchor_brain_load(launch_command=_COMMAND) is True
+ deadline = time.monotonic() + 5.0
+ while not attempts and time.monotonic() < deadline:
+ time.sleep(0.01)
+ while supervisor._BRAIN_ANCHORS and time.monotonic() < deadline:
+ time.sleep(0.01)
+ assert supervisor._BRAIN_ANCHORS == set()
+ assert supervisor.anchor_brain_load(launch_command=_COMMAND) is True
+
+
+def test_managed_spawn_anchors_the_brain_load_before_the_child_starts(
+ monkeypatch, tmp_path
+) -> None:
+ """Order is the whole point: the child begins cancelling the load 15 s
+ after it starts, so the anchor has to be in flight before Popen."""
+ from jarvis.realtime.local_server import install
+
+ supervisor._reset_for_tests()
+ monkeypatch.setenv("JARVIS_DATA_DIR", str(tmp_path))
+ entrypoint = install.install_root() / "venv" / "server.exe"
+ command = f'"{entrypoint}" --mode realtime --model_name qwen3.5:4b'
+ monkeypatch.setattr(supervisor, "probe_runtime", lambda *args, **kwargs: None)
+ monkeypatch.setattr(supervisor, "_port_open", lambda *args, **kwargs: False)
+ monkeypatch.setattr(supervisor, "_owned_process", lambda: (None, False))
+ monkeypatch.setattr(supervisor, "_kill_by_install_root", lambda root: (0, 0))
+ monkeypatch.setattr(supervisor, "prepare_voice_brain_command", lambda candidate: candidate)
+ monkeypatch.setattr(supervisor, "_write_pidfile", lambda *args: True)
+
+ order: list[str] = []
+ monkeypatch.setattr(
+ supervisor,
+ "anchor_brain_load",
+ lambda **kwargs: order.append("anchor") or True,
+ )
+ monkeypatch.setattr(
+ supervisor,
+ "_spawn",
+ lambda candidate, **kwargs: order.append("spawn") or 7331,
+ )
+
+ outcome = supervisor.ensure_running(
+ launch_command=command,
+ base_url="http://127.0.0.1:8765",
+ reason="test",
+ )
+
+ assert outcome == "spawned"
+ assert order == ["anchor", "spawn"]
+
+
+def test_a_model_switch_anchors_the_new_brain_load(monkeypatch, tmp_path) -> None:
+ """A switch is the one spawn whose brain is cold by definition."""
+ from jarvis.realtime.local_server import install
+
+ supervisor._reset_for_tests()
+ monkeypatch.setenv("JARVIS_DATA_DIR", str(tmp_path))
+ entrypoint = install.install_root() / "venv" / "server.exe"
+ current = f'"{entrypoint}" --mode realtime --model_name qwen3.5:4b'
+ wanted = f'"{entrypoint}" --mode realtime --model_name qwen2.5:7b'
+ monkeypatch.setattr(supervisor, "probe_runtime", lambda *a, **k: {"size": 1, "in_use": 0})
+ monkeypatch.setattr(supervisor, "_port_open", lambda *a, **k: False)
+ monkeypatch.setattr(supervisor, "_owned_process", lambda: (4242, True))
+ monkeypatch.setattr(supervisor, "_verified_owned_command", lambda: current)
+ monkeypatch.setattr(supervisor, "_stop_owned_unlocked", lambda **k: (True, "stopped"))
+ monkeypatch.setattr(supervisor, "prepare_voice_brain_command", lambda candidate: candidate)
+ monkeypatch.setattr(supervisor, "_write_pidfile", lambda *args: True)
+
+ order: list[str] = []
+ anchored: list[str] = []
+ monkeypatch.setattr(
+ supervisor,
+ "anchor_brain_load",
+ lambda **kwargs: (
+ order.append("anchor") or anchored.append(kwargs["launch_command"]) or True
+ ),
+ )
+ monkeypatch.setattr(
+ supervisor,
+ "_spawn",
+ lambda candidate, **kwargs: order.append("spawn") or 7331,
+ )
+
+ outcome = supervisor.replace_idle_managed_runtime(
+ current_command=current,
+ launch_command=wanted,
+ base_url="http://127.0.0.1:8765",
+ reason="model-switch",
+ )
+
+ assert outcome == "spawned"
+ assert order == ["anchor", "spawn"]
+ # The anchor loads the model the switch is switching TO, off the same
+ # normalized command the child is about to be started with.
+ assert "--model_name qwen2.5:7b" in anchored[0]
+
+
def test_warm_brain_without_a_brain_flag_is_a_noop() -> None:
assert supervisor.warm_brain(launch_command="serve --mode realtime") is False
diff --git a/tests/unit/realtime/test_tools.py b/tests/unit/realtime/test_tools.py
index 1c016e74ec..b1dd705747 100644
--- a/tests/unit/realtime/test_tools.py
+++ b/tests/unit/realtime/test_tools.py
@@ -28,9 +28,8 @@ class FakeTool:
class FakeExecutor:
- def __init__(self, *, confirmation_required: bool = False, output="opened") -> None:
+ def __init__(self, *, confirmation_required: bool = False) -> None:
self.confirmation_required = confirmation_required
- self.output = output
self.execute_calls = []
self.confirmed_calls = []
self.cancelled = []
@@ -44,7 +43,7 @@ class FakeExecutor:
output={"tool_name": tool.name},
error=VOICE_CONFIRM_SENTINEL,
)
- return SimpleNamespace(success=True, output=self.output, error=None)
+ return SimpleNamespace(success=True, output="opened", error=None)
async def execute_confirmed(self, trace_id, **kwargs):
self.confirmed_calls.append((trace_id, kwargs))
@@ -122,41 +121,6 @@ async def test_available_tool_runs_only_through_tool_executor():
assert executor.execute_calls[0][2]["config_snapshot"]["voice_confirm"] is True
-async def test_unverified_outcome_carries_the_attempt_not_outcome_instruction():
- """A tool that acted blind (``verified: false``) must reach the model as
- an attempt: live 2026-08-26 19:50 a media-key "play" came back ok and
- the voice announced music that never started."""
- tool = FakeTool("youtube_music")
- executor = FakeExecutor(output={"ok": True, "action": "play", "verified": False})
- bridge = RealtimeToolBridge(tools={"youtube_music": tool}, executor=executor, language="en")
-
- _name, result = await bridge.execute(
- wire_name="youtube_music", arguments={"app_name": "x"}
- )
-
- assert result["success"] is True and result["unverified"] is True
- assert "not a confirmed outcome" in result["instruction"]
- assert "never say it is done" in result["instruction"]
-
-
-async def test_verified_outcome_carries_no_instruction():
- tool = FakeTool("youtube_music")
- executor = FakeExecutor(output={"ok": True, "action": "play", "verified": True})
- bridge = RealtimeToolBridge(tools={"youtube_music": tool}, executor=executor, language="en")
-
- _name, result = await bridge.execute(
- wire_name="youtube_music", arguments={"app_name": "x"}
- )
-
- assert result == {
- "success": True,
- "output": {"ok": True, "action": "play", "verified": True},
- "error": None,
- }
-
-
@pytest.mark.asyncio
async def test_vertex_toolset_prefix_resolves_to_the_declared_tool():
"""Vertex Live prefixes user-declared functions with the tool-set name.
diff --git a/tests/unit/web/test_agentic_ide_create_folder.py b/tests/unit/web/test_agentic_ide_create_folder.py
deleted file mode 100644
index bb99752b93..0000000000
--- a/tests/unit/web/test_agentic_ide_create_folder.py
+++ /dev/null
@@ -1,34 +0,0 @@
-"""``POST /folders/create`` — a refusal is an answer, not a status code.
-
-The picker shows the reason next to the name field, the same way it shows a
-typed path that does not exist, so the route reports through ``error`` and
-never raises for an ordinary "no".
-"""
-
-from __future__ import annotations
-
-from pathlib import Path
-
-from jarvis.ui.web import agentic_ide_routes as routes
-
-
-async def test_makes_the_folder_and_describes_it(tmp_path: Path) -> None:
- res = await routes.create_new_folder(
- routes.CreateFolderRequest(parent=str(tmp_path), name="shop")
- )
-
- assert res.error is None
- assert res.folder is not None
- assert res.folder.name == "shop"
- assert Path(res.folder.path) == tmp_path / "shop"
- assert (tmp_path / "shop").is_dir()
-
-
-async def test_a_bad_name_comes_back_as_a_reason(tmp_path: Path) -> None:
- res = await routes.create_new_folder(
- routes.CreateFolderRequest(parent=str(tmp_path), name="a/b")
- )
-
- assert res.folder is None
- assert res.error is not None and "slashes" in res.error
- assert list(tmp_path.iterdir()) == [] # noqa: ASYNC240