Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
revert(chat): undo this session's chat rework entirely
rubenluetke10-beepb380358f3772
diff --git a/jarvis/agent_chat/__init__.py b/jarvis/agent_chat/__init__.pyindex 637fe8b720..51a899a93a 100644--- a/jarvis/agent_chat/__init__.py+++ b/jarvis/agent_chat/__init__.py@@ -1,47 +1,26 @@-"""The chat surface — Jarvis with a keyboard.--**This is not the Agentic IDE's chat.** The two look alike on purpose and mean-different things; keeping them apart is the whole point of this package's-existence, and mixing them up has cost two rebuilds already:--* **The chat section** (this package, ``components/home/ChatStage``) is JARVIS.- You type instead of speaking, and the same assistant answers — the same- brain, tools, memory, wiki and confirmations the microphone reaches. It has- no working directory, writes no code on its own, and its history is your- conversations with Jarvis.-* **The Agentic IDE's chat** (``jarvis/agentic_ide``,- ``components/agentic/IdeChatSurface``) is a CODING AGENT. It reads and drives- the terminal sessions running in the workspace folder you opened — one pane,- its conversation rendered as an exchange. Its subject is code and files.--Same shape, different job: one is who you talk to, the other is what you have-working for you.--What runs a turn here, and who pays for it:--* :mod:`.runner_brain` — an API-key row. Jarvis' own brain thinks with that- provider's model (``BrainManager.generate``), billed per token. The turn's- steps are mirrored into the timeline from the app's event bus, so you see- the tools it reached for and the sentence it wrote next to each one.-* :mod:`.runner_cli` — a subscription row (Claude Max, ChatGPT, Antigravity,- Grok). The vendor CLI runs the loop — that is what the seat pays for — but- inside the Jarvis harness (:mod:`.jarvis_harness`): Jarvis' own tools over- MCP and a preamble telling it whose hands those are, so it acts as Jarvis- rather than as a coding assistant that happens to sit in this folder.--The rest of the package:--* :mod:`.catalog` — the provider rows the picker shows, and which runner each- one uses;-* :mod:`.effort` — the reasoning-effort ladders, per provider and per model;-* :mod:`.permissions` — the vendor permission ladders (CLI rows only: the- brain has none, Jarvis' own risk tiers gate its tools);-* :mod:`.events` — the one event vocabulary the store and the live stream- both speak;+"""Agent chat — the typed front-page chat as an agent session.++The chat surface of the front page used to be a second mouth for the voice+brain: typed text went down the same ``MessageSent`` path the microphone+uses and the router brain answered. Since 2026-08-23 it is its own thing —+a coding-agent session in the Claude Code shape, run on whichever+*agent-tier* provider and model the person picks in the composer, with the+reasoning effort dialled by hand:++* :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);+* :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+ stream speak;* :mod:`.store` — SQLite persistence for sessions and their event log;-* :mod:`.tools` — the in-process file/shell tools of the API runner;+* :mod:`.runner_api` / :mod:`.runner_cli` — the two ways a turn runs: the+ provider's own chat API in a tool loop, or a vendor CLI (``claude``,+ ``codex``, ``agy``, ``grok``) driven non-interactively;* :mod:`.service` — sessions in flight, subscribers, cancel and approvals.-The voice path is untouched: nothing here sits on it, and the step mirror is a-read-only bus subscriber that never reaches the publisher (AP-9, AP-18).+The voice path is untouched: nothing here subscribes to the event bus, and+nothing on the voice critical path imports this package (AP-9)."""diff --git a/jarvis/agent_chat/catalog.py b/jarvis/agent_chat/catalog.pyindex 985723292c..924d69d864 100644--- a/jarvis/agent_chat/catalog.py+++ b/jarvis/agent_chat/catalog.py@@ -1,34 +1,32 @@-"""The provider rows the chat composer can pick from.+"""The provider rows the agent-chat composer can pick from.-The picker lists the providers Jarvis can THINK with — the brain-tier keys-from the API-Keys page. Picking one makes it the live brain for the turn-(:mod:`jarvis.agent_chat.runner_brain`), so what the row names is the model-behind the assistant, not a different assistant.+The picker lists every provider of the AGENT tier — the same families the+API-Keys "Agents" section shows (``MAPPINGS`` in+``jarvis.missions.worker_runtime.provider_map`` plus the three direct CLI+workers) — whether or not a credential is saved: a provider without one is+shown disabled with a "connect" hint that leads to the API-Keys page, so the+person sees what they *could* use (maintainer, 2026-08-23: all agents, not+only the active one).-Two kinds of row, and the difference is who pays and who runs the loop:+Two kinds of runner sit behind the rows:-``brain``- An API key. Jarvis thinks with that provider's model — the router, the- tools, the memory, all of it (:mod:`runner_brain`). Billed per token.+``api``+ The provider's own chat API, driven in-process in a tool loop+ (:mod:`jarvis.agent_chat.runner_api`). Model lists come live from the+ provider catalog (``GET /api/providers/{id}/models``).``claude-cli`` / ``codex-cli`` / ``agy-cli`` / ``grok-cli``- A SUBSCRIPTION seat (Claude Max, ChatGPT, Antigravity, Grok). The vendor- CLI runs the loop — that is what a subscription pays for — but inside the- Jarvis harness (:mod:`jarvis_harness`): it gets Jarvis' own tools over MCP- and a preamble telling it whose hands those are, so it acts as Jarvis and- not as a coding assistant that happens to sit in this folder.--Both are offered because both are worth having: the subscription costs-nothing per turn, the API keys reach models no CLI exposes.--Rows are shown whether or not a credential is saved: one without a key is-disabled with a "connect" hint that leads to the API-Keys page, so the person-sees what they *could* use (maintainer, 2026-08-23: all agents, not only the-active one).--Model lists come live from the provider catalog-(``GET /api/providers/{id}/models``) where the provider publishes one, else-from the curated list below; ``""`` means "the provider's default".+ A vendor CLI driven non-interactively (:mod:`jarvis.agent_chat.runner_cli`).+ The CLI brings its own tools and permissions; the model list is the+ CLI's own — read live where the CLI publishes one (``agy models``,+ Codex's ``models_cache.json``), else the curated fallback here — and+ ``""`` means "the CLI's default".++``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 route decides per request by probing; this module only carries the+static shape.Presentation data only — nothing here decides behaviour (AP-21); the rowsexist so the picker can show a provider before a key is typed.@@ -42,11 +40,7 @@ from typing import Any, Final, Literalfrom jarvis.agent_chat.effort import default_effort, effort_levelsfrom jarvis.brain.model_catalog import CURATED_MODELS-#: ``brain`` = Jarvis thinks with this provider's model (runner_brain).-#: The ``*-cli`` runners are the subscription seats: a vendor CLI driven-#: non-interactively INSIDE the Jarvis harness (runner_cli + jarvis_harness),-#: so the model works with Jarvis' own tools and answers as Jarvis.-Runner = Literal["brain", "claude-cli", "codex-cli", "agy-cli", "grok-cli"]+Runner = Literal["api", "claude-cli", "codex-cli", "agy-cli", "grok-cli"]@dataclass(frozen=True, slots=True)@@ -201,26 +195,26 @@ PROVIDER_ROWS: Final[tuple[ProviderRow, ...]] = (curated_models=_curated("grok"),default_model="",),- ProviderRow(id="openai", label="OpenAI", family="openai", runner="brain", models_source="live"),+ ProviderRow(id="openai", label="OpenAI", family="openai", runner="api", models_source="live"),ProviderRow(- id="gemini", label="Google Gemini", family="gemini", runner="brain", models_source="live"+ id="gemini", label="Google Gemini", family="gemini", runner="api", models_source="live"),- ProviderRow(id="grok", label="xAI Grok", family="xai", runner="brain", models_source="live"),+ ProviderRow(id="grok", label="xAI Grok", family="xai", runner="api", models_source="live"),ProviderRow(id="openrouter",label="OpenRouter",family="openrouter",- runner="brain",+ runner="api",models_source="live",),ProviderRow(- id="nvidia", label="NVIDIA NIM", family="nvidia", runner="brain", models_source="live"+ id="nvidia", label="NVIDIA NIM", family="nvidia", runner="api", models_source="live"),ProviderRow(id="vertex",label="Google Vertex AI",family="google-cloud",- runner="brain",+ runner="api",models_source="curated",curated_models=_curated("gemini"),),@@ -228,7 +222,7 @@ PROVIDER_ROWS: Final[tuple[ProviderRow, ...]] = (id="ollama",label="Ollama",family="ollama",- runner="brain",+ runner="api",models_source="live",keyless=True,),@@ -236,7 +230,7 @@ PROVIDER_ROWS: Final[tuple[ProviderRow, ...]] = (id="local-openai",label="Local OpenAI-compatible",family="local",- runner="brain",+ runner="api",models_source="live",keyless=True,),diff --git a/jarvis/agent_chat/permissions.py b/jarvis/agent_chat/permissions.pyindex 37a411a848..586874eeaf 100644--- a/jarvis/agent_chat/permissions.py+++ b/jarvis/agent_chat/permissions.py@@ -179,15 +179,7 @@ _API: Final[tuple[PermissionMode, ...]] = ()# runner -> (ladder, default)-#-# ``brain`` has NO ladder, and that is the honest answer rather than a missing-# one: Jarvis' own risk tiers decide what a tool may do (safe / monitor / ask /-# block, ``ToolExecutor``), a consequential action asks back inside the answer,-# and none of that is a per-chat dial. A picker offering vendor permission-# modes there would be a control wired to nothing (AP-31). The composer hides-# the pick — and the Build | Plan switch with it — when the ladder is empty._LADDERS: Final[dict[str, tuple[tuple[PermissionMode, ...], str]]] = {- "brain": ((), ""),"claude-cli": (_CLAUDE, "acceptEdits"),"codex-cli": (_CODEX, "auto"),"agy-cli": (_AGY, "accept-edits"),diff --git a/jarvis/agent_chat/runner_api.py b/jarvis/agent_chat/runner_api.pyindex 33e347cd5f..e7eec55328 100644--- a/jarvis/agent_chat/runner_api.py+++ b/jarvis/agent_chat/runner_api.py@@ -139,11 +139,6 @@ class TurnHandle:cancel: asyncio.Eventhistory: list[dict[str, Any]] = field(default_factory=list)assistant_name: str = "Jarvis"- #: The app's event bus, when there is one. The brain runner watches it for- #: the turn's own steps — the tools Jarvis reached for and why — so the- #: timeline shows the work instead of a spinner. ``None`` in tests and in- #: any build without a bus; the turn then simply has no step rows.- bus: Any | None = None# ------------------------------------------------------------ historydiff --git a/jarvis/agent_chat/service.py b/jarvis/agent_chat/service.pyindex abb8141f5d..fdbce29041 100644--- a/jarvis/agent_chat/service.py+++ b/jarvis/agent_chat/service.py@@ -8,18 +8,11 @@ approval card. Cancel sets the turn's event and awaits the task; a runnerthat is mid-tool or mid-stream ends at the next boundary (the API loopbetween deltas, the CLI by killing the child).-The runner is picked per turn from the provider row, and either way the-answer is JARVIS — the difference is only who runs the loop and who pays:--* an API-key row runs :mod:`runner_brain`: Jarvis' own brain thinks with that- provider's model, billed per token;-* a subscription row runs :mod:`runner_cli`: the vendor CLI drives the loop- (that is what a Claude Max / ChatGPT / Antigravity seat pays for) inside the- Jarvis harness, so it works with Jarvis' tools and answers as Jarvis.--``claude-api`` is the dual row: Claude Code when the binary is on PATH, the-brain on the Anthropic key otherwise. The choice is recorded in-``turn_started`` so the timeline can say what answered.+The runner is picked per turn from the provider row: a CLI-backed provider+uses :mod:`runner_cli`; ``claude-api`` uses the CLI when the ``claude``+binary is on PATH and the API otherwise; everything else uses+:mod:`runner_api`. The choice is recorded in ``turn_started`` so the+timeline can say what answered."""from __future__ import annotations@@ -36,9 +29,7 @@ from jarvis.agent_chat.catalog import provider_rowfrom jarvis.agent_chat.effort import normalize_effortfrom jarvis.agent_chat.events import make_eventfrom jarvis.agent_chat.permissions import normalize_permission-from jarvis.agent_chat.runner_api import TurnHandle-from jarvis.agent_chat.runner_brain import RUNNER as BRAIN_RUNNER-from jarvis.agent_chat.runner_brain import run_brain_turn+from jarvis.agent_chat.runner_api import TurnHandle, run_api_turn, supports_api_runnerfrom jarvis.agent_chat.runner_cli import run_cli_turn, supports_cli_runnerfrom jarvis.agent_chat.store import AgentChatSession, AgentChatStore@@ -59,18 +50,18 @@ class NoSuchSession(KeyError):def resolve_runner(provider: str) -> str:"""Which runner answers for ``provider`` on this machine, right now.- ``claude-api`` is dual: Claude Code (the CLI) when it is installed — the- subscription path, no per-token cost — else Jarvis' brain on the Anthropic- key. Every other row names its runner outright, and an unknown provider- falls back to the brain, which reports honestly if it cannot answer.+ ``claude-api`` is dual: Claude Code (the CLI) when it is installed — that+ is the subscription path and the one with the CLI's own tools — else the+ Anthropic API in the in-process loop. Every other provider row names its+ runner outright."""row = provider_row(provider)if row is None:- return BRAIN_RUNNER+ return "api" if supports_api_runner(provider) else "unknown"if row.id == "claude-api":if shutil.which("claude") or shutil.which("claude.cmd") or shutil.which("claude.exe"):return "claude-cli"- return BRAIN_RUNNER+ return "api"return row.runner@@ -90,10 +81,8 @@ class AgentChatService:*,assistant_name: Callable[[], str] | None = None,default_cwd: Callable[[], str] | None = None,- bus: Any | None = None,) -> None:self.store = store- self._bus = busself._assistant_name = assistant_name or (lambda: "Jarvis")self._default_cwd = default_cwd or (lambda: str(Path.home()))self._running: dict[str, _Running] = {}@@ -117,8 +106,8 @@ class AgentChatService:title: str = "",) -> AgentChatSession:row = provider_row(provider)- if row is None:- raise ValueError(f"Unknown chat provider: {provider!r}")+ if row is None and not supports_api_runner(provider):+ raise ValueError(f"Unknown agent-chat provider: {provider!r}")permission_mode = normalize_permission(resolve_runner(provider), permission_mode)eff = normalize_effort(provider, effort) if effort is not None else ""if effort is None:@@ -212,7 +201,6 @@ class AgentChatService:cancel=cancel,history=history,assistant_name=self._assistant_name(),- bus=self._bus,)async def _body() -> None:@@ -221,8 +209,25 @@ class AgentChatService:vendor = await run_cli_turn(handle, text, runner)if vendor and vendor != session.vendor_session:self.store.update_session(session_id, vendor_session=vendor)+ elif runner == "api" and supports_api_runner(session.provider):+ await run_api_turn(handle, text)else:- await run_brain_turn(handle, text)+ await self._emit(+ session_id,+ make_event(+ "turn_finished",+ {+ "turn_id": turn_id,+ "status": "error",+ "duration_ms": 0,+ "usage": {},+ "error": (+ f"No runner for provider {session.provider!r} on this "+ "machine. Connect it under API Keys → Agents."+ ),+ },+ ),+ )except asyncio.CancelledError:await self._emit(session_id,diff --git a/jarvis/ui/web/agent_chat_routes.py b/jarvis/ui/web/agent_chat_routes.pyindex 0768b0e1cc..867dace75b 100644--- a/jarvis/ui/web/agent_chat_routes.py+++ b/jarvis/ui/web/agent_chat_routes.py@@ -192,10 +192,7 @@ async def get_catalog(request: Request) -> dict[str, Any]:d = row.to_dict()runner = resolve_runner(row.id)d["runner"] = runner- # ``None`` = "not a CLI question": an API-key row is connected by its- # key, and reporting False there greyed every brain out as "not- # installed" (live 2026-08-24).- d["cli_installed"] = _cli_installed(runner) if runner.endswith("-cli") else None+ d["cli_installed"] = _cli_installed(runner) if runner != "api" else None# A CLI that publishes its own model list (agy, Codex) overrides the# curated fallback with what THIS account can actually pick.if d["cli_installed"] and runner in live_models and live_models[runner]:diff --git a/jarvis/ui/web/frontend/src/components/ChatInput.tsx b/jarvis/ui/web/frontend/src/components/ChatInput.tsxindex e7edb53613..3e348af607 100644--- a/jarvis/ui/web/frontend/src/components/ChatInput.tsx+++ b/jarvis/ui/web/frontend/src/components/ChatInput.tsx@@ -1,18 +1,15 @@import { useEffect, useRef, useState, type KeyboardEvent } from "react";import { ArrowUp, Mic, Square } from "lucide-react";import { getWSClient } from "@/hooks/useWebSocket";-import { ProviderLogo } from "@/components/providers/ProviderLogo";-import { prettyProviderName } from "@/lib/prettyProviderName";+import { useVoiceEngineDisplay } from "@/hooks/useVoiceEngineDisplay";import { useEventStore } from "@/store/events";import { cn } from "@/lib/utils";import { useT } from "@/i18n";-// Safety net: a backend hang must not leave the UI waiting forever. This is a-// SILENCE window, not a turn budget — every sign of life (a reasoning step, a-// streamed piece of the answer) re-arms it. A turn that reads the calendar,-// runs a skill and then writes three paragraphs takes well over a minute and-// is perfectly healthy; only a turn that goes quiet is one nobody is having.-const THINKING_SILENCE_MS = 60_000;+// Safety net: if the brain doesn't respond within 60s (no reply, no error event),+// we revert the indicator. A backend hang must not leave the UI stuck in the+// wait state permanently.+const THINKING_TIMEOUT_MS = 60_000;/*** The composer — a card with the text box and, on its bottom row, dictation,@@ -27,23 +24,14 @@ export function ChatInput() {const [value, setValue] = useState("");const connected = useEventStore((s) => s.connected);const setActiveSection = useEventStore((s) => s.setActiveSection);- // What will answer HERE. A typed turn always runs the classic brain- // (desktop_app._on_user_message -> BrainManager) — the realtime engine is- // the voice stage's, it never sees a typed prompt. Naming it here said the- // chat ran on "Gemini Live" while the answer actually came from the- // configured brain provider, which is the pick people make under Agents /- // API keys (maintainer, 2026-08-24).- const brainProvider = useEventStore((s) => s.brainProvider);- const brainModel = useEventStore((s) => s.brainModel);- const brainLabel = brainProvider ? prettyProviderName(brainProvider) : "";+ // What will answer: the classic brain, or the realtime engine when voice+ // mode is realtime — the same resolver the header and the sidebar use.+ const engine = useVoiceEngineDisplay();const wsWarming = useEventStore((s) => s.wsWarming);// The turn's progress is no longer mirrored in the composer — the chat// column renders the live steps (components/home/TurnSteps) as the// in-progress assistant turn. The composer only arms the wait state.const setChatThinking = useEventStore((s) => s.setChatThinking);- const chatThinking = useEventStore((s) => s.chatThinking);- const stepCount = useEventStore((s) => s.thinkingSteps.length);- const liveLength = useEventStore((s) => s.liveReply?.text.length ?? 0);// Mic-dictation: live transcript streams into the box as the user speaks.const dictating = useEventStore((s) => s.dictating);const dictationText = useEventStore((s) => s.dictationText);@@ -62,24 +50,11 @@ export function ChatInput() {const mirroringRef = useRef(false);const lastCommitSeqRef = useRef(dictationCommitSeq);- // Arm the silence window while a turn is in flight, and re-arm it whenever- // the turn shows a sign of life. `stepCount`/`liveLength` are the two live- // signals the brain produces; either one moving means the turn is alive.useEffect(() => {- if (timeoutRef.current) clearTimeout(timeoutRef.current);- if (!chatThinking) {- timeoutRef.current = null;- return;- }- timeoutRef.current = setTimeout(() => {- setChatThinking(false);- timeoutRef.current = null;- }, THINKING_SILENCE_MS);return () => {if (timeoutRef.current) clearTimeout(timeoutRef.current);- timeoutRef.current = null;};- }, [chatThinking, stepCount, liveLength, setChatThinking]);+ }, []);// While dictating, mirror the live interim tail into the textarea in real time.useEffect(() => {@@ -143,6 +118,11 @@ export function ChatInput() {payload: { content },});setChatThinking(true);+ if (timeoutRef.current) clearTimeout(timeoutRef.current);+ timeoutRef.current = setTimeout(() => {+ setChatThinking(false);+ timeoutRef.current = null;+ }, THINKING_TIMEOUT_MS);setValue("");}@@ -247,12 +227,9 @@ export function ChatInput() {data-testid="composer-model"className="inline-flex h-8 max-w-[280px] items-center gap-1.5 rounded-lg px-2 text-xs text-muted-foreground transition-colors hover:bg-secondary hover:text-foreground">- {brainProvider && (- <ProviderLogo providerId={brainProvider} label={brainLabel} size="sm" />- )}- <span className="truncate font-medium text-foreground">{brainLabel || "—"}</span>- {brainModel && (- <span className="truncate font-mono text-[10px] text-muted-foreground">{brainModel}</span>+ <span className="truncate font-medium text-foreground">{engine.providerLabel}</span>+ {engine.model && (+ <span className="truncate font-mono text-[10px] text-muted-foreground">{engine.model}</span>)}</button><buttondiff --git a/jarvis/ui/web/frontend/src/components/agentchat/AgentComposer.tsx b/jarvis/ui/web/frontend/src/components/agentchat/AgentComposer.tsxindex 333a6b83c9..1b4da9fe68 100644--- a/jarvis/ui/web/frontend/src/components/agentchat/AgentComposer.tsx+++ b/jarvis/ui/web/frontend/src/components/agentchat/AgentComposer.tsx@@ -61,7 +61,6 @@ export function AgentComposer({ autoFocus = false }: { autoFocus?: boolean }) {const connected = useEventStore((s) => s.connected);const wsWarming = useEventStore((s) => s.wsWarming);const setActiveSection = useEventStore((s) => s.setActiveSection);- const setApiKeysTab = useEventStore((s) => s.setApiKeysTab);const pushToast = useEventStore((s) => s.pushToast);const [restarting, setRestarting] = useState(false);@@ -144,14 +143,6 @@ export function AgentComposer({ autoFocus = false }: { autoFocus?: boolean }) {}}- // A subscription row is connected by LOGGING IN under Sub-agents; an- // API-key row by pasting a key under Brain. Sending everyone to the same- // page and letting them hunt is what made this link feel broken.- function openConnectPage(p: ProviderOption) {- setApiKeysTab(providerKind(p) === "cli" ? "subagents" : "brain");- setActiveSection("apikeys");- }-// ---- option lists -------------------------------------------------// Only what the Agents tab has set up is offered (maintainer, 2026-08-23:@@ -465,7 +456,7 @@ export function AgentComposer({ autoFocus = false }: { autoFocus?: boolean }) {</span><buttontype="button"- onClick={() => openConnectPage(provider)}+ onClick={() => setActiveSection("apikeys")}className="font-medium text-primary hover:underline">{t("agent_chat.open_api_keys")}@@ -493,11 +484,7 @@ export type ProviderKind = "cli" | "api" | "local";export const PROVIDER_KINDS: readonly ProviderKind[] = ["cli", "api", "local"];export function providerKind(p: { runner: string; keyless: boolean }): ProviderKind {if (p.keyless) return "local";- // "brain" = Jarvis thinks with this provider's model on an API key; anything- // else is a vendor CLI on a subscription seat. The runner used to be called- // "api" for the first kind, and grouping on that name put every brain under- // "Coding CLIs" the day it was renamed (live 2026-08-24).- return p.runner === "brain" ? "api" : "cli";+ return p.runner === "api" ? "api" : "cli";}/** One compact pick on the composer's bottom row — a pill-sized Combobox. */diff --git a/jarvis/ui/web/frontend/src/components/home/ChatStage.test.tsx b/jarvis/ui/web/frontend/src/components/home/ChatStage.test.tsxindex 03a236bda5..241381c524 100644--- a/jarvis/ui/web/frontend/src/components/home/ChatStage.test.tsx+++ b/jarvis/ui/web/frontend/src/components/home/ChatStage.test.tsx@@ -149,7 +149,7 @@ describe("ChatStage (agent chat)", () => {id: "openai",label: "OpenAI",family: "openai",- runner: "brain",+ runner: "api",models_source: "live" as const,curated_models: [],cli_installed: null,diff --git a/jarvis/ui/web/frontend/src/components/layout/Sidebar.test.tsx b/jarvis/ui/web/frontend/src/components/layout/Sidebar.test.tsxindex a7e169da10..f21ec118e1 100644--- a/jarvis/ui/web/frontend/src/components/layout/Sidebar.test.tsx+++ b/jarvis/ui/web/frontend/src/components/layout/Sidebar.test.tsx@@ -325,9 +325,6 @@ describe("Sidebar brain footer", () => {describe("Sidebar footer in realtime voice mode", () => {beforeEach(() => {- // The card follows the surface, so every case here states its own — the- // store keeps whatever the previous test left behind.- useHomeStore.setState({ surface: "voice" });useEventStore.setState({voiceState: "idle",transcription: "",@@ -390,26 +387,6 @@ describe("Sidebar footer in realtime voice mode", () => {expect(screen.getByTestId("sidebar-brain-model").textContent).toBe("gpt-realtime-2.1");});- test("the chat surface names the brain even when realtime is configured", () => {- // The mirror of the case above: standing in a typed chat, the realtime- // engine is the dormant one — a typed turn always runs the classic brain.- // Naming "Gemini Live" there read as if the chat ran on the realtime model.- useHomeStore.setState({ surface: "chat" });- voiceModeMock.value = {- ...voiceModeMock.value,- mode: "realtime",- activeProvider: "gemini-live",- activeProviderLabel: "Gemini Live",- activeModel: "gemini-3.1-flash-live-preview",- };-- renderSidebar();-- expect(screen.getByTestId("sidebar-footer-tier").textContent).toBe("Brain");- expect(screen.queryByText("Gemini Live")).toBeNull();- expect(screen.getByText("OpenRouter")).toBeTruthy();- });-test("pipeline mode keeps the classic brain footer", () => {// Guard the split itself: mode "pipeline" must still show the brain card// even when a realtime provider is fully configured.diff --git a/jarvis/ui/web/frontend/src/components/layout/Sidebar.tsx b/jarvis/ui/web/frontend/src/components/layout/Sidebar.tsxindex 7c53026d29..d1ff505b69 100644--- a/jarvis/ui/web/frontend/src/components/layout/Sidebar.tsx+++ b/jarvis/ui/web/frontend/src/components/layout/Sidebar.tsx@@ -18,8 +18,6 @@ import { useVoiceMode } from "@/hooks/useVoiceMode";import { useSectionHealth } from "@/hooks/useProviders";import { usePluginAttention } from "@/hooks/usePluginAttention";import { useVoiceEngineDisplay } from "@/hooks/useVoiceEngineDisplay";-import { useAgentChatStore } from "@/store/agentChat";-import { prettyProviderName } from "@/lib/prettyProviderName";import { cn } from "@/lib/utils";import { useMemo, useState } from "react";import { useT } from "@/i18n";@@ -28,6 +26,7 @@ import { SurfaceSwitch } from "@/components/home/SurfaceSwitch";import { RecentChats } from "@/components/home/RecentChats";import { useConversations } from "@/hooks/useConversations";import { useHomeStore } from "@/store/home";+import { useAgentChatStore } from "@/store/agentChat";import { useIdeChatStore } from "@/store/ideChat";import { WorkspaceChats } from "@/components/agentic/WorkspaceChats";import { PRODUCT_NAME } from "@/lib/branding";@@ -130,11 +129,11 @@ export function Sidebar({const appInstance = useAppInstance();const devTag = appInstance?.isDev ? appInstance.name.toUpperCase() : null;// "+ New" starts a new conversation of the KIND you are looking at: on the- // chat surface an empty chat with Jarvis, on the voice stage a fresh voice- // run. Sending someone standing in Voice to the chat page is what the one- // button used to do, and it read as the button being broken.+ // chat surface an empty agent chat, on the voice stage a fresh voice run.+ // Sending someone standing in Voice to the chat page is what the one button+ // used to do, and it read as the button being broken.const { newChat, newVoiceRun } = useConversations();- const newChatSession = useAgentChatStore((s) => s.newChat);+ const newAgentChat = useAgentChatStore((s) => s.newChat);const setSurface = useHomeStore((s) => s.setSurface);// The front page's nav row names the face the switch picked (Voice / Chat),// see `presentNavItem`.@@ -168,12 +167,11 @@ export function Sidebar({void newVoiceRun();setActive("chats");};- // On the chat surface: an empty page for a new chat with Jarvis. Both stores- // are cleared — the chat session that owns the stage, and the voice thread —- // so a reopened conversation does not linger behind the fresh page.+ // On the chat surface: an empty agent chat. The voice thread is cleared as+ // well so a reopened voice session does not linger behind the fresh page.const startNewChat = () => {newChat();- newChatSession();+ newAgentChat();setSurface("chat");setActive("chats");};@@ -215,8 +213,6 @@ export function Sidebar({// pick so a mid-call cross-family fallback is visible (AP-22).const voiceMode = useVoiceMode();const engine = useVoiceEngineDisplay();- const brainProvider = useEventStore((s) => s.brainProvider);- const brainModel = useEventStore((s) => s.brainModel);// The window connects in ~1s but the voice feature warms up ~20s in the// background. During that gap show a "Voice starting…" spinner instead of the@@ -241,22 +237,15 @@ export function Sidebar({? t("voice_state.connecting"): t(`voice_state.${voiceState}`);- // ...but only on the VOICE surface. On the chat surface the realtime engine- // is the dormant one — a typed turn always runs the classic brain — so- // naming "Gemini Live" under a chat you are typing into is the same mislead- // in the other direction, and it read as if the chat ran on the realtime- // model (maintainer, 2026-08-24). The card follows the surface.- const realtimeFooter = engine.tier === "realtime" && onVoiceSurface;+ const realtimeFooter = engine.tier === "realtime";const footerLabel = realtimeFooter? t("sidebar.realtime_label"): t("sidebar.brain_label");const footerTooltip = realtimeFooter? t("sidebar.realtime_tooltip"): t("sidebar.brain_tooltip");- const footerProvider = realtimeFooter- ? engine.providerLabel- : prettyProviderName(brainProvider) || engine.providerLabel;- const footerModel = realtimeFooter ? engine.model : brainModel || engine.model;+ const footerProvider = engine.providerLabel;+ const footerModel = engine.model;const [logoRetry, setLogoRetry] = useState(0);diff --git a/jarvis/ui/web/frontend/src/store/events.ts b/jarvis/ui/web/frontend/src/store/events.tsindex 4497ba5ade..ccd47fe2a0 100644--- a/jarvis/ui/web/frontend/src/store/events.ts+++ b/jarvis/ui/web/frontend/src/store/events.ts@@ -502,15 +502,6 @@ interface EventStore {setWarming: (warming: boolean) => void;clearEvents: () => void;setActiveSection: (s: SectionId) => void;- /**- * Which tab the API-Keys view should open on, set by whoever sends someone- * there. Null once that view has consumed it, so a later visit opens- * normally. Without this, "connect this provider" landed on whichever tab- * the view defaults to — Realtime, when the voice engine is realtime — and- * the key the person came to set was nowhere on screen (live 2026-08-24).- */- apiKeysTab: string | null;- setApiKeysTab: (tab: string | null) => void;setDetachedViews: (views: SectionId[]) => void;/*** Route a visual into the Visualization section and go there.@@ -594,7 +585,6 @@ export const useEventStore = create<EventStore>((set, get) => ({voiceReady: false,connected: false,wsWarming: true,- apiKeysTab: null,activeSection: initialSectionFromSearch(typeof window === "undefined" ? "" : window.location.search,),@@ -642,7 +632,6 @@ export const useEventStore = create<EventStore>((set, get) => ({setWarming: (warming) => set({ wsWarming: warming }),clearEvents: () => set({ events: [] }),setActiveSection: (s) => set({ activeSection: s }),- setApiKeysTab: (tab) => set({ apiKeysTab: tab }),setDetachedViews: (views) => set({ detachedViews: views }),requestVisual: (target = "latest") =>diff --git a/jarvis/ui/web/frontend/src/views/ApiKeysView.tsx b/jarvis/ui/web/frontend/src/views/ApiKeysView.tsxindex aeccda59ab..bddd75b8a1 100644--- a/jarvis/ui/web/frontend/src/views/ApiKeysView.tsx+++ b/jarvis/ui/web/frontend/src/views/ApiKeysView.tsx@@ -1,7 +1,6 @@import { useEffect, useRef, useState } from "react";import { Bot, Brain, KeyRound, Mic, Phone, Radio, SlidersHorizontal, Terminal, Volume2, Wand2 } from "lucide-react";import { ViewHeader } from "@/views/ChatsView";-import { useEventStore } from "@/store/events";import { JarvisAgentSection } from "@/components/JarvisAgentSection";import { TelephonyPanel } from "@/views/TelephonyView";import { WikiProviderCard } from "@/views/settings/WikiProviderCard";@@ -63,14 +62,8 @@ const PIPELINE_TABS: CategoryKey[] = ["jarvis-key","advanced",];-// "brain" is in BOTH sets on purpose. Realtime replaces the brain for the-// SPOKEN turn only — the typed chat always runs the classic brain-// (agent_chat/runner_brain.py), and so do tools and missions. Hiding the brain-// key in realtime mode meant "connect this provider" from the chat composer-// landed on a page where that key was not on screen at all (live 2026-08-24).const REALTIME_TABS: CategoryKey[] = ["realtime",- "brain","computer-use","subagents","jarvis-key",@@ -115,21 +108,7 @@ export function ApiKeysView() {// Reset the selected tab to the mode's first tab whenever the mode changes,// so switching Pipeline→Realtime never leaves `active` pointing at a tab// that no longer exists in the new mode (e.g. "tts").- // Somebody sent us here for a specific tab ("connect this provider"). That- // pick outranks both defaults below, and is consumed so a later visit opens- // normally. Declared FIRST so it wins the mount race with them.- const pendingTab = useEventStore((s) => s.apiKeysTab);- const setApiKeysTab = useEventStore((s) => s.setApiKeysTab);- const deepLinked = useRef(false);- useEffect(() => {- if (!pendingTab) return;- deepLinked.current = true;- setActive(pendingTab as CategoryKey);- setApiKeysTab(null);- }, [pendingTab, setApiKeysTab]);-useEffect(() => {- if (deepLinked.current) return;setActive(engineMode === "realtime" ? "realtime" : "brain");}, [engineMode]);@@ -143,12 +122,6 @@ export function ApiKeysView() {setEngineMode(liveMode === "realtime" ? "realtime" : "pipeline");}, [liveMode, liveModeLoading]);- // A tab the person clicks themselves takes the wheel back from the link.- function pickTab(tab: CategoryKey) {- deepLinked.current = false;- setActive(tab);- }-const modeTabs = engineMode === "realtime" ? REALTIME_TABS : PIPELINE_TABS;// A recommendation row navigates to the tab it talks about. This is VIEW@@ -179,7 +152,7 @@ export function ApiKeysView() {}/>- <CategoryTabs active={active} onSelect={pickTab} health={health} tabs={modeTabs} />+ <CategoryTabs active={active} onSelect={setActive} health={health} tabs={modeTabs} /><divdata-testid="api-keys-provider-scroll"diff --git a/jarvis/ui/web/server.py b/jarvis/ui/web/server.pyindex 4e4ac2be34..cee6920295 100644--- a/jarvis/ui/web/server.py+++ b/jarvis/ui/web/server.py@@ -3491,10 +3491,7 @@ class WebServer:except Exception: # noqa: BLE001 — the name is cosmeticreturn "Jarvis"- # The bus lets the brain runner mirror the turn's own steps into the- # timeline — the tools Jarvis reached for and the sentence it wrote- # next to each one — instead of a bare spinner.- return AgentChatService(store, assistant_name=_name, bus=self.bus)+ return AgentChatService(store, assistant_name=_name)async def stop(self) -> None:self._mic_level_sessions.clear()diff --git a/tests/unit/agent_chat/test_agent_chat_core.py b/tests/unit/agent_chat/test_agent_chat_core.pyindex 66295bcd07..a7989df363 100644--- a/tests/unit/agent_chat/test_agent_chat_core.py+++ b/tests/unit/agent_chat/test_agent_chat_core.py@@ -55,44 +55,15 @@ def test_normalize_effort_folds_onto_the_nearest_offered_level(provider, picked,assert effort.normalize_effort(provider, picked) == expected-def test_every_row_names_a_runner_that_can_actually_answer():- """Two kinds of row, and neither may promise something it cannot do.-- An API-key row runs Jarvis' brain with that provider's model. A- subscription row runs the vendor CLI inside the Jarvis harness. What must- never happen is a row that would try to make a coding CLI the BRAIN —- ``BrainManager.switch`` refuses those, so the pick could only ever fail.- """- from jarvis.brain.manager import SUBAGENT_ONLY_BRAIN_PROVIDERS-- assert PROVIDER_ROWS, "the picker needs rows"- for row in PROVIDER_ROWS:- assert row.runner in {"brain", "claude-cli", "codex-cli", "agy-cli", "grok-cli"}- if row.id in SUBAGENT_ONLY_BRAIN_PROVIDERS:- assert row.runner != "brain", f"{row.id} cannot be a brain"-- # The subscription seats are offered — they cost nothing per turn.- ids = {row.id for row in PROVIDER_ROWS}- assert {"openai-codex", "antigravity", "grok-build"} <= ids- # …and so are the API keys, which reach models no CLI exposes.- assert {"openai", "gemini", "grok", "openrouter"} <= ids-+def test_catalog_rows_carry_ladders_and_curated_models_for_cli_runners():claude = provider_row("claude-api")- assert claude is not None+ assert claude is not None and claude.runner == "claude-cli"d = claude.to_dict()assert d["effort_levels"] == ["low", "medium", "high", "xhigh", "max"]- assert d["curated_models"], "a curated row needs its list"+ assert d["curated_models"], "CLI-backed rows need a curated list"assert provider_row("openai").models_source == "live" # type: ignore[union-attr]-def test_the_brain_offers_no_vendor_permission_ladder():- """Jarvis' own risk tiers gate its tools; a vendor ladder here is dead UI."""- from jarvis.agent_chat.permissions import normalize_permission, permission_modes-- assert permission_modes("brain") == ()- assert normalize_permission("brain", "acceptEdits") == ""--# ----------------------------------------------------------------- storediff --git a/tests/unit/agent_chat/test_agent_chat_ladders.py b/tests/unit/agent_chat/test_agent_chat_ladders.pyindex ed15f16804..95074ac0a7 100644--- a/tests/unit/agent_chat/test_agent_chat_ladders.py+++ b/tests/unit/agent_chat/test_agent_chat_ladders.py@@ -9,7 +9,6 @@ import pytestfrom jarvis.agent_chat import permissions, runner_clifrom jarvis.agent_chat.catalog import CODEX_FALLBACK_MODELS, provider_row-from jarvis.agent_chat.effort import effort_levelsfrom jarvis.agent_chat.runner_cli import (_AgyState,agy_model_args,@@ -393,17 +392,19 @@ def test_read_codex_models_reads_the_account_cache(monkeypatch, tmp_path: Path):assert CODEX_FALLBACK_MODELS[0].id == "gpt-5.6-sol"-def test_the_coding_clis_keep_their_own_runner_and_ladders():- """A subscription row runs its CLI — never the brain — with its own dials."""- for cli, runner in (- ("antigravity", "agy-cli"),- ("openai-codex", "codex-cli"),- ("grok-build", "grok-cli"),- ):- row = provider_row(cli)- assert row is not None, f"{cli} is missing from the picker"- assert row.runner == runner- assert "low" in effort_levels("antigravity")+def test_catalog_rows_carry_per_model_efforts_for_cli_runners():+ agy = provider_row("antigravity")+ assert agy is not None+ models = agy.to_dict()["curated_models"]+ assert models[0]["id"] == "gemini-3.7-flash" and models[0]["efforts"] == [+ "low",+ "medium",+ "high",+ ]+ assert any(m["id"] == "claude-sonnet-4-6" and m["efforts"] == [] for m in models)+ codex = provider_row("openai-codex")+ assert codex is not None+ assert codex.to_dict()["curated_models"][0]["efforts"][-1] == "ultra"# ------------------------------------------------------------ Anthropic API effortdiff --git a/tests/unit/agent_chat/test_agent_chat_service.py b/tests/unit/agent_chat/test_agent_chat_service.pyindex 6b6451a398..613cb24951 100644--- a/tests/unit/agent_chat/test_agent_chat_service.py+++ b/tests/unit/agent_chat/test_agent_chat_service.py@@ -1,16 +1,9 @@-"""The chat surface end to end: a typed turn, run on Jarvis' brain.--The surface used to run a coding agent — a vendor CLI or an in-process tool-loop, with approval cards of its own. Since 2026-08-24 it runs the assistant:-``BrainManager.generate``, with the picked provider and model applied to the-live brain. So these tests fake the BRAIN, not a provider adapter, and there-are no approval cards here — a consequential action is confirmed inside the-answer (``allow_voice_confirm``), the same two-turn flow voice has.-"""+"""Agent chat — a whole turn through the service and the routes with a fake brain."""from __future__ import annotationsimport asyncio+from collections.abc import AsyncIteratorfrom pathlib import Pathfrom typing import Any@@ -18,182 +11,185 @@ import pytestfrom fastapi import FastAPIfrom fastapi.testclient import TestClient+from jarvis.agent_chat import runner_apifrom jarvis.agent_chat.service import AgentChatService, SessionBusyfrom jarvis.agent_chat.store import AgentChatStore-from jarvis.core import runtime_refs+from jarvis.core.protocols import BrainDelta, BrainRequestfrom jarvis.ui.web.agent_chat_routes import router-class FakeBrain:- """A BrainManager stand-in: streams a scripted answer, records the pick."""-- def __init__(self, answer: str = "Two meetings today.", *, fail: str = "") -> None:- self.answer = answer- self.fail = fail- self.calls: list[tuple[str, dict[str, Any]]] = []- self.switched: list[str] = []- self.models: list[tuple[str, str]] = []- self.started = asyncio.Event()- self.release: asyncio.Event | None = None-- # -- the pick ---------------------------------------------------------- async def switch(self, provider: str, *, persist: bool = False) -> None:- self.switched.append(provider)-- def apply_provider_model(self, provider: str, model: str) -> bool:- self.models.append((provider, model))- return True-- # -- the turn ---------------------------------------------------------- async def generate(self, text: str, **kwargs: Any) -> str:- self.calls.append((text, kwargs))- self.started.set()- if self.release is not None:- await self.release.wait()- if self.fail:- raise RuntimeError(self.fail)- consumer = kwargs.get("text_consumer")- if callable(consumer):- for piece in self.answer.split(" "):- consumer(piece + " ")- await asyncio.sleep(0)- return self.answer+class ScriptedBrain:+ """A brain that answers from a script: each entry is a list of deltas."""++ def __init__(self, model: str | None = None) -> None:+ self.model = model+ self.requests: list[BrainRequest] = []++ script: list[list[BrainDelta]] = []++ async def complete(self, req: BrainRequest) -> AsyncIterator[BrainDelta]:+ self.requests.append(req)+ ScriptedBrain.seen.append(req)+ step = ScriptedBrain.script.pop(0) if ScriptedBrain.script else [BrainDelta(content="(done)")]+ for d in step:+ await asyncio.sleep(0)+ yield d++ seen: list[BrainRequest] = []@pytest.fixture-def brain(monkeypatch: pytest.MonkeyPatch) -> FakeBrain:- fake = FakeBrain()- monkeypatch.setattr(runtime_refs, "get_brain_manager", lambda: fake)- return fake+def scripted(monkeypatch: pytest.MonkeyPatch):+ ScriptedBrain.script = []+ ScriptedBrain.seen = []+ monkeypatch.setitem(runner_api.BRAIN_BY_PROVIDER, "fakeprov", ("tests.unit.agent_chat.test_agent_chat_service", "ScriptedBrain"))+ # Catalog has no row for fakeprov; supports_api_runner() still says yes.+ return ScriptedBrain-async def _drain(- q: asyncio.Queue, until_kind: str, budget_s: float = 5.0-) -> list[dict[str, Any]]:+async def _drain(q: asyncio.Queue, until_kind: str, timeout: float = 5.0) -> list[dict[str, Any]]:out: list[dict[str, Any]] = []loop = asyncio.get_running_loop()- deadline = loop.time() + budget_s+ deadline = loop.time() + timeoutwhile True:remaining = deadline - loop.time()if remaining <= 0:- seen = [e['kind'] for e in out]- raise AssertionError(f"timed out waiting for {until_kind}; got {seen}")+ raise AssertionError(f"timed out waiting for {until_kind}; got {[e['kind'] for e in out]}")ev = await asyncio.wait_for(q.get(), timeout=remaining)out.append(ev)if ev["kind"] == until_kind:return out-def test_a_typed_turn_runs_on_the_brain_with_the_picked_model(tmp_path: Path, brain: FakeBrain):+def test_turn_streams_text_runs_a_tool_and_asks_for_approval(tmp_path: Path, scripted):+ ScriptedBrain.script = [+ [+ BrainDelta(content="Let me "),+ BrainDelta(content="write it."),+ BrainDelta(+ tool_call={+ "id": "c1",+ "name": "Write",+ "input": {"file_path": "hello.txt", "content": "hi"},+ }+ ),+ BrainDelta(finish_reason="tool_use", usage={"input_tokens": 3, "output_tokens": 4}),+ ],+ [BrainDelta(content="Written."), BrainDelta(finish_reason="stop")],+ ]+async def scenario() -> None:store = AgentChatStore(":memory:")svc = AgentChatService(store, assistant_name=lambda: "Testo")- session = svc.create_session(provider="grok", model="grok-4.3", cwd=str(tmp_path))+ session = svc.create_session(provider="fakeprov", model="m", effort="high", cwd=str(tmp_path))q = svc.subscribe(session.session_id)- turn_id = await svc.send(session.session_id, "was steht heute an")+ turn_id = await svc.send(session.session_id, "please write hello.txt")with pytest.raises(SessionBusy):await svc.send(session.session_id, "again")- events = await _drain(q, "turn_finished")+ events = await _drain(q, "approval_required")kinds = [e["kind"] for e in events]assert kinds[:2] == ["user_message", "turn_started"]- assert "text_delta" in kinds, "the answer must stream as it is written"- assert "assistant_text" in kinds-- started = events[1]["payload"]- assert started["runner"] == "brain", "the assistant answers, not a coding CLI"- assert started["provider"] == "grok" and started["model"] == "grok-4.3"+ assert "text_delta" in kinds and "tool_call" in kinds+ approval = events[-1]["payload"]+ assert approval["name"] == "Write" and approval["summary"] == "hello.txt"+ assert svc.pending_approvals(session.session_id) == [approval["approval_id"]]+ assert svc.resolve_approval(session.session_id, approval["approval_id"], "allow")+ events += await _drain(q, "turn_finished")+ kinds = [e["kind"] for e in events]+ assert "approval_resolved" in kinds and "tool_result" in kinds+ assert (tmp_path / "hello.txt").read_text(encoding="utf-8") == "hi"finished = events[-1]["payload"]- assert finished["turn_id"] == turn_id- assert finished["status"] == "done" and finished["error"] is None-- # The pick reached the live brain, both halves of it.- assert brain.switched == ["grok"]- assert brain.models == [("grok", "grok-4.3")]-- # It really is the brain's own turn: present-user confirmation on, and- # the conversation keyed to this session so follow-ups keep context.- _, kwargs = brain.calls[0]- assert kwargs["allow_voice_confirm"] is True- assert kwargs["conversation_id"] == session.session_id- assert callable(kwargs["text_consumer"])-- # The persisted log keeps the answer, never the token dust.- stored = [e["kind"] for e in store.list_events(session.session_id)]- assert "text_delta" not in stored and "assistant_text" in stored+ assert finished["turn_id"] == turn_id and finished["status"] == "done"+ assert finished["usage"] == {"input_tokens": 3, "output_tokens": 4}++ # The persisted log has no transient deltas and the final texts.+ stored = store.list_events(session.session_id)+ stored_kinds = [e["kind"] for e in stored]+ assert "text_delta" not in stored_kinds+ texts = [e["payload"]["text"] for e in stored if e["kind"] == "assistant_text"]+ assert texts == ["Let me write it.", "Written."]+ # The second request carried the tool round back to the brain.+ second = ScriptedBrain.seen[1]+ assert second.reasoning_effort == "high"+ assert second.messages[-1].role == "tool"+ assert second.system and "Testo" in second.systemassert not svc.is_running(session.session_id)asyncio.run(scenario())-def test_the_brain_runner_refuses_a_coding_subagent_in_words(brain: FakeBrain):- """The last line of defence, if a sub-agent ever reaches the brain runner.-- Those rows run their own CLI, so they never get here in practice — but a- stale session or a hand-made request must be told, not answered as- somebody else.- """-- async def scenario() -> None:- from jarvis.agent_chat.runner_brain import apply_pick-- why = await apply_pick(brain, "antigravity", "")- assert "coding sub-agent" in why- assert brain.switched == [], "a sub-agent must never become the brain"-- asyncio.run(scenario())---def test_a_brain_that_is_not_up_yet_is_reported_instead_of_spinning(- tmp_path: Path, monkeypatch: pytest.MonkeyPatch-):- monkeypatch.setattr(runtime_refs, "get_brain_manager", lambda: None)+def test_deny_feeds_a_denied_result_and_allow_always_flips_the_mode(tmp_path: Path, scripted):+ ScriptedBrain.script = [+ [BrainDelta(tool_call={"id": "c1", "name": "RunCommand", "input": {"command": "echo x"}})],+ [BrainDelta(tool_call={"id": "c2", "name": "RunCommand", "input": {"command": "echo y"}})],+ [BrainDelta(tool_call={"id": "c3", "name": "RunCommand", "input": {"command": "echo z"}})],+ [BrainDelta(content="ok")],+ ]async def scenario() -> None:svc = AgentChatService(AgentChatStore(":memory:"))- session = svc.create_session(provider="openai", cwd=str(tmp_path))+ session = svc.create_session(provider="fakeprov", cwd=str(tmp_path))q = svc.subscribe(session.session_id)- await svc.send(session.session_id, "hi")+ await svc.send(session.session_id, "run things")+ ev = (await _drain(q, "approval_required"))[-1]["payload"]+ svc.resolve_approval(session.session_id, ev["approval_id"], "deny")+ events = await _drain(q, "tool_result")+ assert events[-1]["payload"]["is_error"] and "Denied" in events[-1]["payload"]["output"]+ ev = (await _drain(q, "approval_required"))[-1]["payload"]+ svc.resolve_approval(session.session_id, ev["approval_id"], "allow_always")events = await _drain(q, "turn_finished")- assert events[-1]["payload"]["status"] == "error"- assert "starting up" in events[-1]["payload"]["error"]+ kinds = [e["kind"] for e in events]+ # c2 ran after allow_always, c3 ran with no approval card at all.+ assert kinds.count("approval_required") == 0+ assert kinds.count("tool_result") == 2+ assert svc.store.get_session(session.session_id).permission_mode == "auto" # type: ignore[union-attr]asyncio.run(scenario())-def test_a_failing_turn_is_reported_not_raised(tmp_path: Path, monkeypatch: pytest.MonkeyPatch):- fake = FakeBrain(fail="401 invalid api key")- monkeypatch.setattr(runtime_refs, "get_brain_manager", lambda: fake)+def test_cancel_ends_the_turn(tmp_path: Path, scripted):+ ScriptedBrain.script = [+ [BrainDelta(tool_call={"id": "c1", "name": "Write", "input": {"file_path": "a", "content": "b"}})],+ ]async def scenario() -> None:svc = AgentChatService(AgentChatStore(":memory:"))- session = svc.create_session(provider="openai", cwd=str(tmp_path))+ session = svc.create_session(provider="fakeprov", cwd=str(tmp_path))q = svc.subscribe(session.session_id)- await svc.send(session.session_id, "hi")+ await svc.send(session.session_id, "go")+ await _drain(q, "approval_required")+ assert await svc.cancel(session.session_id)events = await _drain(q, "turn_finished")- assert events[-1]["payload"]["status"] == "error"- assert "invalid api key" in events[-1]["payload"]["error"]+ assert events[-1]["payload"]["status"] == "cancelled"+ assert not (tmp_path / "a").exists()asyncio.run(scenario())-def test_cancel_ends_the_turn(tmp_path: Path, monkeypatch: pytest.MonkeyPatch):- fake = FakeBrain()+def test_provider_error_is_reported_not_raised(tmp_path: Path, monkeypatch: pytest.MonkeyPatch):+ class Boom:+ def __init__(self, model=None):+ pass++ async def complete(self, req):+ raise RuntimeError("401 invalid api key")+ yield # pragma: no cover++ monkeypatch.setitem(runner_api.BRAIN_BY_PROVIDER, "boomprov", (__name__, "Boom"))+ import sys++ setattr(sys.modules[__name__], "Boom", Boom)async def scenario() -> None:- fake.release = asyncio.Event()- monkeypatch.setattr(runtime_refs, "get_brain_manager", lambda: fake)svc = AgentChatService(AgentChatStore(":memory:"))- session = svc.create_session(provider="openai", cwd=str(tmp_path))+ session = svc.create_session(provider="boomprov", cwd=str(tmp_path))q = svc.subscribe(session.session_id)- await svc.send(session.session_id, "go")- await asyncio.wait_for(fake.started.wait(), timeout=5)- cancelled = asyncio.create_task(svc.cancel(session.session_id))- fake.release.set()- assert await asyncio.wait_for(cancelled, timeout=5)+ await svc.send(session.session_id, "hi")events = await _drain(q, "turn_finished")- assert events[-1]["payload"]["status"] in {"cancelled", "done"}+ assert events[-1]["payload"]["status"] == "error"+ assert "invalid api key" in events[-1]["payload"]["error"]asyncio.run(scenario())@@ -211,7 +207,8 @@ def _app(tmp_path: Path) -> FastAPI:return app-def test_routes_catalog_sessions_and_websocket_snapshot(tmp_path: Path, brain: FakeBrain):+def test_routes_catalog_sessions_and_websocket_snapshot(tmp_path: Path, scripted):+ ScriptedBrain.script = [[BrainDelta(content="hello from fake")]]# One portal for the whole test: a bare TestClient opens a fresh event# loop per request, and the turn task spawned by POST /messages would be# cancelled the moment that request returns.@@ -220,37 +217,26 @@ def test_routes_catalog_sessions_and_websocket_snapshot(tmp_path: Path, brain: Fdef _exercise_routes(client: TestClient, tmp_path: Path) -> None:+cat = client.get("/api/agent-chat/catalog").json()ids = [p["id"] for p in cat["providers"]]- # Both kinds are offered: the API keys and the subscription seats.- assert {"claude-api", "openai", "openai-codex", "antigravity"} <= set(ids)- codex = next(p for p in cat["providers"] if p["id"] == "openai-codex")- assert codex["runner"] == "codex-cli"- openai = next(p for p in cat["providers"] if p["id"] == "openai")- assert openai["runner"] == "brain"- # An API-key row is not a CLI question — reporting False there greyed every- # brain out as "not installed" (live 2026-08-24).- assert openai["cli_installed"] is None+ assert "claude-api" in ids and "openai" in ids and "openai-codex" in idsclaude = next(p for p in cat["providers"] if p["id"] == "claude-api")assert claude["effort_levels"][-1] == "max"assert cat["default_cwd"] == str(tmp_path)created = client.post("/api/agent-chat/sessions",- json={"provider": "openai", "model": "gpt-5.5", "effort": "xhigh"},+ json={"provider": "fakeprov", "model": "m", "effort": "xhigh"},)assert created.status_code == 201, created.textsid = created.json()["session_id"]assert created.json()["cwd"] == str(tmp_path)- bad = client.post(- "/api/agent-chat/sessions", json={"provider": "openai", "cwd": "/no/such/dir"}- )+ bad = client.post("/api/agent-chat/sessions", json={"provider": "fakeprov", "cwd": "/no/such/dir"})assert bad.status_code == 400- patched = client.patch(- f"/api/agent-chat/sessions/{sid}", json={"title": "My chat", "effort": "low"}- )+ patched = client.patch(f"/api/agent-chat/sessions/{sid}", json={"title": "My chat", "effort": "low"})assert patched.json()["title"] == "My chat" and patched.json()["effort"] == "low"with client.websocket_connect(f"/api/agent-chat/sessions/{sid}/ws") as ws: