Skip to content

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

feat(chat): the chat surface keeps its face and gets Jarvis behind it

rubenluetke10-beep7e3c3baece51
diff --git a/jarvis/agent_chat/catalog.py b/jarvis/agent_chat/catalog.py
index 924d69d864..f37a065a21 100644
--- a/jarvis/agent_chat/catalog.py
+++ b/jarvis/agent_chat/catalog.py
@@ -1,32 +1,24 @@
-"""The provider rows the agent-chat composer can pick from.
-
-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 runner sit behind the rows:
-
-``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 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.
+"""The provider rows the 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.
+
+A subscription coding CLI (Codex, Antigravity, Grok Build) is deliberately
+NOT here. Those are agent loops with their own tools and no chat API; the
+brain cannot be switched to them at all (``SUBAGENT_ONLY_BRAIN_PROVIDERS``),
+and a coding session belongs in the Agentic IDE. ``claude-api`` stays because
+an Anthropic key IS a brain — the row is the API, not Claude Code.
+
+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".
Presentation data only — nothing here decides behaviour (AP-21); the rows
exist so the picker can show a provider before a key is typed.
@@ -40,7 +32,9 @@ from typing import Any, Final, Literal
from jarvis.agent_chat.effort import default_effort, effort_levels
from jarvis.brain.model_catalog import CURATED_MODELS
-Runner = Literal["api", "claude-cli", "codex-cli", "agy-cli", "grok-cli"]
+#: One runner answers on this surface: Jarvis' brain. The string is what
+#: ``turn_started`` reports and what the permission/effort ladders key on.
+Runner = Literal["brain"]
@dataclass(frozen=True, slots=True)
@@ -154,67 +148,32 @@ PROVIDER_ROWS: Final[tuple[ProviderRow, ...]] = (
id="claude-api",
label="Anthropic Claude",
family="claude",
- runner="claude-cli",
+ runner="brain",
models_source="curated",
curated_models=_curated("claude-api"),
default_model="",
native_resume=True,
),
+ ProviderRow(id="openai", label="OpenAI", family="openai", runner="brain", models_source="live"),
ProviderRow(
- id="openai-codex",
- label="OpenAI Codex",
- family="openai",
- runner="codex-cli",
- models_source="curated",
- # Codex's OWN catalog, not the OpenAI API's: the route replaces this
- # with the account's live list from ``models_cache.json``.
- curated_models=CODEX_FALLBACK_MODELS,
- default_model="",
- native_resume=True,
- ),
- ProviderRow(
- id="antigravity",
- label="Antigravity",
- family="antigravity",
- runner="agy-cli",
- models_source="curated",
- # agy's OWN ids (not the Gemini API's): the route replaces this with
- # the live ``agy models`` list when the binary answers.
- curated_models=tuple(
- CuratedModel(mid, label, efforts) for mid, label, efforts in _agy_fallback_models()
- ),
- default_model="",
- native_resume=True,
- ),
- ProviderRow(
- id="grok-build",
- label="Grok Build",
- family="xai",
- runner="grok-cli",
- models_source="curated",
- curated_models=_curated("grok"),
- default_model="",
- ),
- ProviderRow(id="openai", label="OpenAI", family="openai", runner="api", models_source="live"),
- ProviderRow(
- id="gemini", label="Google Gemini", family="gemini", runner="api", models_source="live"
+ id="gemini", label="Google Gemini", family="gemini", runner="brain", models_source="live"
),
- ProviderRow(id="grok", label="xAI Grok", family="xai", runner="api", models_source="live"),
+ ProviderRow(id="grok", label="xAI Grok", family="xai", runner="brain", models_source="live"),
ProviderRow(
id="openrouter",
label="OpenRouter",
family="openrouter",
- runner="api",
+ runner="brain",
models_source="live",
),
ProviderRow(
- id="nvidia", label="NVIDIA NIM", family="nvidia", runner="api", models_source="live"
+ id="nvidia", label="NVIDIA NIM", family="nvidia", runner="brain", models_source="live"
),
ProviderRow(
id="vertex",
label="Google Vertex AI",
family="google-cloud",
- runner="api",
+ runner="brain",
models_source="curated",
curated_models=_curated("gemini"),
),
@@ -222,7 +181,7 @@ PROVIDER_ROWS: Final[tuple[ProviderRow, ...]] = (
id="ollama",
label="Ollama",
family="ollama",
- runner="api",
+ runner="brain",
models_source="live",
keyless=True,
),
@@ -230,7 +189,7 @@ PROVIDER_ROWS: Final[tuple[ProviderRow, ...]] = (
id="local-openai",
label="Local OpenAI-compatible",
family="local",
- runner="api",
+ runner="brain",
models_source="live",
keyless=True,
),
diff --git a/jarvis/agent_chat/permissions.py b/jarvis/agent_chat/permissions.py
index 586874eeaf..37a411a848 100644
--- a/jarvis/agent_chat/permissions.py
+++ b/jarvis/agent_chat/permissions.py
@@ -179,7 +179,15 @@ _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_brain.py b/jarvis/agent_chat/runner_brain.py
new file mode 100644
index 0000000000..fb5f1e5024
--- /dev/null
+++ b/jarvis/agent_chat/runner_brain.py
@@ -0,0 +1,190 @@
+"""The chat surface's runner: Jarvis' own brain, driven by text.
+
+This is what the front page's chat runs on. A typed turn is the same turn a
+spoken one is — ``BrainManager.generate`` with its router, its tools, its
+memory, its wiki and its two-turn confirmation for a consequential action —
+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-24).
+
+What the picker changes is which MODEL Jarvis thinks with. Picking a provider
+switches the live brain (``BrainManager.switch``, not persisted, so a restart
+returns to the configured one), and picking a model writes that provider's
+model the same way the API-Keys page does. Both are the app's ONE brain
+setting: what you pick here is what answers by voice as well, which is the
+honest behaviour — there is no second, hidden Jarvis.
+
+A coding CLI (Claude Code, Codex, Antigravity, Grok Build) cannot be a brain:
+it is an agent loop with its own tools, reachable only as a sub-agent
+(``SUBAGENT_ONLY_BRAIN_PROVIDERS``). Those rows are therefore not in this
+picker — the Agentic IDE is where a coding session belongs.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import logging
+import time
+import uuid
+from typing import TYPE_CHECKING, Any
+
+from jarvis.agent_chat.events import make_event
+
+if TYPE_CHECKING:
+ from jarvis.agent_chat.runner_api import TurnHandle
+
+log = logging.getLogger(__name__)
+
+#: The runner id this module answers to, in the catalog and in ``turn_started``.
+RUNNER: str = "brain"
+
+#: ``MessageSent.source_layer`` for a turn typed into the chat surface. The
+#: brain's router reads it, and the desktop bridge uses it to know this turn
+#: already has an owner — see ``_on_user_message``'s "chat" guard.
+SOURCE_LAYER: str = "ui.chat.typed"
+
+
+def brain_manager() -> Any | None:
+ """The live BrainManager, or ``None`` before the brain finished building."""
+ from jarvis.core import runtime_refs
+
+ return runtime_refs.get_brain_manager()
+
+
+async def apply_pick(brain: Any, provider: str, model: str) -> str:
+ """Make the session's pick the live brain. Returns a human error, or "".
+
+ Best-effort by design: a pick that cannot be applied must not lose the
+ person's message. The turn then runs on whatever brain IS active, and the
+ reason is reported as the turn's error line rather than swallowed.
+ """
+ provider = (provider or "").strip()
+ if not provider:
+ return ""
+ try:
+ from jarvis.brain.manager import SUBAGENT_ONLY_BRAIN_PROVIDERS
+
+ if provider in SUBAGENT_ONLY_BRAIN_PROVIDERS:
+ return (
+ f"{provider} is a coding sub-agent, not a brain — it cannot answer "
+ "in this chat. Pick a provider with an API key."
+ )
+ except Exception: # noqa: BLE001 — an import failure must not block the turn
+ log.debug("brain runner: could not read the subagent-only set", exc_info=True)
+
+ if (model or "").strip():
+ # The same live-apply the API-Keys page calls (PUT /providers/{id}/model
+ # with persist=false): this turn's model, not a config write. A restart
+ # returns to the configured one, which is what a per-chat pick should do.
+ apply_model = getattr(brain, "apply_provider_model", None)
+ if callable(apply_model):
+ try:
+ apply_model(provider, model)
+ except Exception as exc: # noqa: BLE001
+ log.debug("brain runner: model %r not applied: %s", model, exc)
+
+ try:
+ active = getattr(brain, "active_provider_name", None)
+ current = active() if callable(active) else getattr(brain, "_active_name", "")
+ if current != provider:
+ await brain.switch(provider, persist=False)
+ except Exception as exc: # noqa: BLE001
+ return f"Could not switch to {provider}: {type(exc).__name__}: {exc}"
+ return ""
+
+
+async def run_brain_turn(handle: TurnHandle, text: str) -> None:
+ """Run one typed turn on Jarvis' brain, streaming it into the timeline."""
+ started = time.monotonic()
+ turn_id = handle.turn_id
+ message_id = uuid.uuid4().hex
+
+ async def emit(kind: str, payload: dict[str, Any]) -> None:
+ await handle.emit(make_event(kind, payload))
+
+ async def finish(status: str, error: str | None = None) -> None:
+ await emit(
+ "turn_finished",
+ {
+ "turn_id": turn_id,
+ "status": status,
+ "duration_ms": int((time.monotonic() - started) * 1000),
+ "usage": {},
+ "error": error,
+ },
+ )
+
+ brain = brain_manager()
+ if brain is None or not hasattr(brain, "generate"):
+ await finish(
+ "error",
+ "Jarvis' brain is still starting up. Give it a moment and send again.",
+ )
+ return
+
+ pick_error = await apply_pick(brain, handle.session.provider, handle.session.model)
+
+ # The "thinking" line the timeline shows until the first words arrive. The
+ # brain streams its answer but not its reasoning, so the time IS the fact —
+ # the same shape a vendor that redacts its thinking gets.
+ await emit("reasoning_started", {"turn_id": turn_id, "message_id": message_id})
+
+ loop = asyncio.get_running_loop()
+ seen = ""
+
+ def feed(chunk: str) -> None:
+ """Called from the brain's own thread/task as the answer is produced."""
+ nonlocal seen
+ if not chunk:
+ return
+ seen += chunk
+ # The consumer is synchronous (the brain's contract), so hand the emit
+ # back to this loop rather than blocking the producer.
+ asyncio.run_coroutine_threadsafe(
+ emit("text_delta", {"turn_id": turn_id, "message_id": message_id, "text": seen}),
+ loop,
+ )
+
+ try:
+ reply = await _generate(brain, text, handle, feed)
+ except asyncio.CancelledError:
+ raise
+ except Exception as exc: # noqa: BLE001 — the timeline must never spin forever
+ log.exception("brain chat turn %s failed", turn_id)
+ await finish("error", f"{type(exc).__name__}: {exc}")
+ return
+
+ if handle.cancel.is_set():
+ await finish("cancelled")
+ return
+
+ answer = (reply or "").strip() or seen.strip()
+ if answer:
+ await emit(
+ "assistant_text",
+ {"turn_id": turn_id, "message_id": message_id, "text": answer},
+ )
+ await finish("done", pick_error or None)
+
+
+async def _generate(brain: Any, text: str, handle: TurnHandle, feed: Any) -> str:
+ """Call the brain, degrading through the argument shapes older brains take.
+
+ ``allow_voice_confirm=True`` is load-bearing (audit GT-12): a person typing
+ IS present, so a consequential ask-tier tool asks back in the reply and the
+ next message answers it — the same two-turn flow voice has. Without it the
+ executor sees no channel to ask on and refuses outright.
+ """
+ kwargs: dict[str, Any] = {
+ "conversation_id": handle.session.session_id,
+ "source_layer": SOURCE_LAYER,
+ "allow_voice_confirm": True,
+ "text_consumer": feed,
+ }
+ try:
+ return await brain.generate(text, **kwargs)
+ except TypeError:
+ # An older brain shape without the streaming hook or the confirm flag.
+ kwargs.pop("text_consumer", None)
+ kwargs.pop("allow_voice_confirm", None)
+ return await brain.generate(text, **kwargs)
diff --git a/jarvis/agent_chat/service.py b/jarvis/agent_chat/service.py
index fdbce29041..85e7b82b2b 100644
--- a/jarvis/agent_chat/service.py
+++ b/jarvis/agent_chat/service.py
@@ -8,18 +8,18 @@ approval card. Cancel sets the turn's event and awaits the task; a runner
that is mid-tool or mid-stream ends at the next boundary (the API loop
between deltas, the CLI by killing the child).
-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.
+Every turn runs on :mod:`runner_brain` — Jarvis' own brain, with the picked
+provider and model applied to it. That is what this surface IS: the assistant,
+typed at instead of spoken to. The CLI and API runners stay in the package for
+the sub-agent paths that drive a vendor CLI; nothing on the chat surface
+reaches them any more (maintainer, 2026-08-24). The runner is recorded in
+``turn_started`` so the timeline can say what answered.
"""
from __future__ import annotations
import asyncio
import logging
-import shutil
import uuid
from collections.abc import Callable
from pathlib import Path
@@ -29,8 +29,9 @@ 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 normalize_permission
-from jarvis.agent_chat.runner_api import TurnHandle, run_api_turn, supports_api_runner
-from jarvis.agent_chat.runner_cli import run_cli_turn, supports_cli_runner
+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.store import AgentChatSession, AgentChatStore
log = logging.getLogger(__name__)
@@ -48,21 +49,14 @@ class NoSuchSession(KeyError):
def resolve_runner(provider: str) -> str:
- """Which runner answers for ``provider`` on this machine, right now.
+ """Which runner answers for ``provider`` — on this surface, always the brain.
- ``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.
+ The pick names the MODEL Jarvis thinks with, not a different assistant, so
+ there is one runner: :mod:`runner_brain`. A provider that cannot be a brain
+ (a subscription coding CLI) is not offered by the catalog at all, and the
+ runner reports it as the turn's error if one ever arrives.
"""
- row = provider_row(provider)
- if row is None:
- 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 "api"
- return row.runner
+ return BRAIN_RUNNER
class _Running:
@@ -106,8 +100,8 @@ class AgentChatService:
title: str = "",
) -> AgentChatSession:
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 None:
+ raise ValueError(f"Unknown 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:
@@ -205,29 +199,7 @@ class AgentChatService:
async def _body() -> None:
try:
- if supports_cli_runner(runner):
- 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 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."
- ),
- },
- ),
- )
+ await run_brain_turn(handle, text)
except asyncio.CancelledError:
await self._emit(
session_id,
diff --git a/jarvis/ui/web/frontend/src/components/home/AllChatsDialog.tsx b/jarvis/ui/web/frontend/src/components/home/AllChatsDialog.tsx
index 04bb3c539d..37d00a24c7 100644
--- a/jarvis/ui/web/frontend/src/components/home/AllChatsDialog.tsx
+++ b/jarvis/ui/web/frontend/src/components/home/AllChatsDialog.tsx
@@ -16,15 +16,14 @@ import {
* "All chats" — the whole history, not the handful the sidebar has room for.
*
* The sidebar block is a shortcut to what you touched last; this is the
- * archive: every conversation with Jarvis, typed or spoken, searchable,
- * grouped by day like a mail client, opening on the same click path as the
- * sidebar
+ * archive: every voice session and every agent chat, searchable, grouped by
+ * day like a mail client, opening on the same click path as the sidebar
* (components/home/chatRows). Modelled on the recents dialog desktop chat
* apps use — one field, one list, Escape closes — because a second full
* SECTION for the same data would be one more place to keep in sync.
*
- * The list is whatever the sidebar's poller already holds, so opening the
- * dialog costs no request.
+ * The list is whatever the two pollers already hold, so opening the dialog
+ * costs no request; the sidebar refreshes both lists every few seconds.
*/
export function AllChatsDialog({
open,
@@ -36,7 +35,7 @@ export function AllChatsDialog({
const t = useT();
const { rows, isActive, open: openRow, remove } = useChatRows();
const [query, setQuery] = useState("");
- const [kind, setKind] = useState<"all" | "text" | "voice">("all");
+ const [kind, setKind] = useState<"all" | "agent" | "voice">("all");
const searchRef = useRef<HTMLInputElement | null>(null);
// A reopened dialog starts clean — a stale filter hiding the chat someone
@@ -57,7 +56,7 @@ export function AllChatsDialog({
const counts = useMemo(
() => ({
all: rows.length,
- text: rows.filter((r) => r.kind === "text").length,
+ agent: rows.filter((r) => r.kind === "agent").length,
voice: rows.filter((r) => r.kind === "voice").length,
}),
[rows],
@@ -129,9 +128,9 @@ export function AllChatsDialog({
/>
<FilterChip
label={t("all_chats.filter_chats")}
- count={counts.text}
- selected={kind === "text"}
- onClick={() => setKind("text")}
+ count={counts.agent}
+ selected={kind === "agent"}
+ onClick={() => setKind("agent")}
/>
<FilterChip
label={t("all_chats.filter_voice")}
@@ -163,7 +162,7 @@ export function AllChatsDialog({
openRow(row);
onOpenChange(false);
}}
- onDelete={row.kind === "text" ? () => remove(row) : undefined}
+ onDelete={row.kind === "agent" ? () => remove(row) : undefined}
/>
))}
</ul>
diff --git a/jarvis/ui/web/frontend/src/components/home/ChatStage.test.tsx b/jarvis/ui/web/frontend/src/components/home/ChatStage.test.tsx
index c6e3b0c046..241381c524 100644
--- a/jarvis/ui/web/frontend/src/components/home/ChatStage.test.tsx
+++ b/jarvis/ui/web/frontend/src/components/home/ChatStage.test.tsx
@@ -1,22 +1,63 @@
-import { cleanup, render as rtlRender, screen, within } from "@testing-library/react";
+import { act, cleanup, fireEvent, render as rtlRender, screen, within } from "@testing-library/react";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { ChatStage } from "@/components/home/ChatStage";
+import { EMPTY_TIMELINE, reduceEvents } from "@/components/agentchat/reduce";
+import type { AgentChatCatalog, AgentChatEvent } from "@/lib/agentChatApi";
+import { useAgentChatStore } from "@/store/agentChat";
import { useEventStore } from "@/store/events";
-/**
- * The front page's chat is JARVIS with a keyboard — the same assistant the
- * microphone talks to, reading the same store the voice path fills. These
- * tests pin exactly that: the composer that sends on the app socket, the
- * brain's own reasoning steps, its answer streaming in, and a spoken session
- * read in the same column.
- *
- * What must NOT be here is a provider / model / effort / permission picker:
- * those belong to a coding-agent session, which is a different surface
- * (components/agentchat/AgentChatStage). A picker appearing on this stage is
- * the exact regression this file exists to catch.
- */
+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" },
+ { id: "claude-sonnet-5", label: "Claude Sonnet 5" },
+ ],
+ default_model: "",
+ keyless: false,
+ native_resume: true,
+ effort_levels: ["low", "medium", "high", "xhigh", "max"],
+ default_effort: "high",
+ permission_modes: [
+ { id: "default", label: "Ask before acting", description: "" },
+ { id: "acceptEdits", label: "Auto-accept edits", description: "" },
+ { id: "plan", label: "Plan", description: "" },
+ { id: "bypassPermissions", label: "Bypass permissions", description: "" },
+ ],
+ default_permission_mode: "acceptEdits",
+ cli_installed: true,
+ },
+ {
+ id: "openai-codex",
+ label: "OpenAI Codex",
+ family: "openai",
+ runner: "codex-cli",
+ models_source: "curated",
+ curated_models: [{ id: "gpt-5.4", label: "GPT-5.4" }],
+ default_model: "",
+ keyless: false,
+ native_resume: true,
+ effort_levels: ["minimal", "low", "medium", "high", "xhigh"],
+ default_effort: "medium",
+ permission_modes: [
+ { id: "read-only", label: "Read only", description: "" },
+ { id: "auto", label: "Auto", description: "" },
+ { id: "full-access", label: "Full access", description: "" },
+ ],
+ default_permission_mode: "auto",
+ cli_installed: false,
+ },
+ ],
+};
// The greeting reads the profile name (a query), so the stage mounts under a
// query client like the app.
@@ -27,166 +68,329 @@ function render(ui: React.ReactElement) {
return rtlRender(<QueryClientProvider client={client}>{ui}</QueryClientProvider>);
}
-const IDLE = {
- connected: true,
- brainProvider: "grok",
- brainModel: "grok-4.3",
- wsWarming: false,
- assistantName: "Jarvis",
- activeKind: "text" as const,
- activeThreadId: null,
- messages: [],
- chatThinking: false,
- thinkingSteps: [],
- thinkingStartedTs: null,
- thinkingTraces: {},
- liveReply: null,
- conversations: [],
-};
+let seq = 0;
+function ev(kind: string, payload: Record<string, unknown>): AgentChatEvent {
+ seq += 1;
+ return { seq, ts_ms: 1_000 + seq, kind, payload };
+}
+
+describe("ChatStage (agent chat)", () => {
+ let scrollTo: ReturnType<typeof vi.fn>;
-describe("ChatStage (Jarvis, typed)", () => {
beforeEach(() => {
+ scrollTo = vi.fn();
Object.defineProperty(HTMLElement.prototype, "scrollTo", {
configurable: true,
writable: true,
- value: vi.fn(),
+ value: scrollTo,
});
+ // jsdom implements neither; the column scrolls with one or the other.
Object.defineProperty(HTMLElement.prototype, "scrollIntoView", {
configurable: true,
writable: true,
value: vi.fn(),
});
window.localStorage.clear();
- useEventStore.setState(IDLE);
+ useEventStore.setState({ connected: true, wsWarming: false, assistantName: "Jarvis" });
+ useAgentChatStore.setState({
+ catalog: CATALOG,
+ connections: [
+ { jarvis: "claude-api", key_set: true, is_active_brain: true },
+ { jarvis: "openai-codex", key_set: true, is_active_brain: false },
+ ],
+ catalogError: null,
+ backendOutdated: false,
+ liveModels: {},
+ sessions: [],
+ activeSessionId: null,
+ activeSession: null,
+ timeline: EMPTY_TIMELINE,
+ draft: {
+ provider: "claude-api",
+ model: "",
+ effort: "high",
+ permissionMode: "acceptEdits",
+ buildMode: "acceptEdits",
+ cwd: "C:\\work",
+ },
+ busy: false,
+ lastError: null,
+ // The stage's mount effects fetch; keep them inert here.
+ loadCatalog: async () => {},
+ loadSessions: async () => {},
+ loadModels: async () => {},
+ });
});
afterEach(() => {
cleanup();
});
- it("opens on the greeting and Jarvis' own composer — no agent picks", () => {
+ it("shows the greeting and the composer with the four picks when there is nothing yet", () => {
render(<ChatStage />);
-
expect(screen.getByTestId("chat-stage").getAttribute("data-empty")).toBe("true");
- expect(screen.getByTestId("home-greeting")).toBeTruthy();
- expect(screen.getByTestId("chat-composer")).toBeTruthy();
- // The four coding-session picks have no business on this surface.
- expect(screen.queryByTestId("agent-composer")).toBeNull();
- expect(screen.queryByTestId("composer-provider")).toBeNull();
- expect(screen.queryByTestId("composer-effort")).toBeNull();
- expect(screen.queryByTestId("composer-permission")).toBeNull();
+ const composer = screen.getByTestId("agent-composer");
+ expect(within(composer).getByTestId("composer-provider").getAttribute("data-value")).toBe("claude-api");
+ expect(within(composer).getByTestId("composer-model")).toBeTruthy();
+ expect(within(composer).getByTestId("composer-effort").getAttribute("data-value")).toBe("high");
+ expect(within(composer).getByTestId("composer-permission").getAttribute("data-value")).toBe("acceptEdits");
+ // Claude Code has a plan entry, so the Build | Plan switch is drawn.
+ expect(within(composer).getByTestId("composer-plan").getAttribute("aria-checked")).toBe("false");
+ });
+
+ it("hides the Build | Plan switch for a provider whose ladder has no plan entry", () => {
+ useAgentChatStore.setState((s) => ({ draft: { ...s.draft, provider: "openai-codex", permissionMode: "auto" } }));
+ render(<ChatStage />);
expect(screen.queryByTestId("composer-plan")).toBeNull();
});
- it("names the brain that answers, never the realtime voice engine", () => {
- useEventStore.setState({
- activeThreadId: "t1",
- messages: [
- { id: "m1", role: "user", content: "hi", ts: 1 },
- { id: "m2", role: "assistant", content: "Hello.", ts: 2 },
+ it("groups the provider list by what stands behind a row: coding CLIs, API keys, local servers", async () => {
+ const apiRow = {
+ ...CATALOG.providers[0],
+ id: "openai",
+ label: "OpenAI",
+ family: "openai",
+ runner: "api",
+ models_source: "live" as const,
+ curated_models: [],
+ cli_installed: null,
+ };
+ const localRow = { ...apiRow, id: "ollama", label: "Ollama", family: "ollama", keyless: true };
+ useAgentChatStore.setState({
+ catalog: { ...CATALOG, providers: [...CATALOG.providers, apiRow, localRow] },
+ connections: [
+ { jarvis: "claude-api", key_set: true, is_active_brain: false },
+ { jarvis: "openai-codex", key_set: false, is_active_brain: false },
+ { jarvis: "openai", key_set: true, is_active_brain: true },
],
});
render(<ChatStage />);
-
- // A typed turn runs the classic brain; the realtime engine only answers
- // speech, so its name must not appear on this surface.
- const composer = screen.getByTestId("chat-composer");
- expect(within(composer).getByTestId("composer-model").textContent).toContain("grok-4.3");
- expect(screen.getByTestId("chat-message-assistant").textContent).toContain("grok-4.3");
- expect(document.body.textContent).not.toContain("Live");
+ fireEvent.click(screen.getByTestId("composer-provider"));
+ const panel = await screen.findByTestId("composer-provider-panel");
+ // The headings, in catalog order — never "connected / not connected".
+ const headings = Array.from(panel.querySelectorAll("div.uppercase")).map((el) => el.textContent);
+ expect(headings).toEqual(["Coding CLIs", "API keys", "On your own hardware"]);
+ expect(within(panel).queryByText("Connected")).toBeNull();
+ // Only what the Agents tab has set up is listed: Codex (no login) is not
+ // there at all, and the voice sub-agent's "active" word is not shown.
+ const options = within(panel).getAllByRole("option").map((el) => el.textContent ?? "");
+ expect(options.map((o) => o.replace(/\s+/g, " ").trim())).toEqual(["Anthropic Claude", "OpenAI", "Ollama"]);
+ expect(within(panel).queryByText("active")).toBeNull();
});
- it("hangs the turn off a rail, the way the timeline always did", () => {
- useEventStore.setState({
- activeThreadId: "t1",
- messages: [{ id: "m2", role: "assistant", content: "Done.", ts: 2 }],
+ it("with nothing connected yet, lists every provider greyed with its connect hint", async () => {
+ useAgentChatStore.setState({
+ connections: [
+ { jarvis: "claude-api", key_set: false, is_active_brain: false },
+ { jarvis: "openai-codex", key_set: false, is_active_brain: false },
+ ],
});
render(<ChatStage />);
- expect(screen.getByTestId("chat-turn-rail")).toBeTruthy();
+ fireEvent.click(screen.getByTestId("composer-provider"));
+ const panel = await screen.findByTestId("composer-provider-panel");
+ const options = within(panel).getAllByRole("option");
+ expect(options).toHaveLength(2);
+ expect(options[0].textContent).toContain("connect");
+ // Codex is not installed on this box: the hint says so instead of "connect".
+ expect(options[1].textContent).toContain("not installed");
});
- it("renders a turn: the person's bubble, then Jarvis' answer as prose", () => {
- useEventStore.setState({
- activeThreadId: "t1",
- messages: [
- { id: "m1", role: "user", content: "What is on today?", ts: 1 },
- {
- id: "m2",
- role: "assistant",
- content: "Two meetings:\n\n- **10:00** standup\n- 14:00 review",
- ts: 2,
- },
- ],
- });
+ it("says when the backend is older than this window and offers the restart", async () => {
+ const fetchMock = vi.fn(async () => new Response(null, { status: 200 }));
+ vi.stubGlobal("fetch", fetchMock);
+ try {
+ useAgentChatStore.setState({ backendOutdated: true });
+ render(<ChatStage />);
+ const notice = screen.getByTestId("composer-backend-outdated");
+ expect(notice.textContent).toContain("older version");
+ fireEvent.click(within(notice).getByRole("button"));
+ await act(async () => {});
+ expect(fetchMock).toHaveBeenCalledWith("/api/settings/restart-app", { method: "POST" });
+ } finally {
+ vi.unstubAllGlobals();
+ }
+ });
+
+ it("draws a different glyph per permission mode in the pill and the list", async () => {
render(<ChatStage />);
+ const pill = screen.getByTestId("composer-permission");
+ // acceptEdits wears the pen, not the column's shield.
+ expect(pill.querySelector("svg.lucide-file-pen")).not.toBeNull();
+ expect(pill.querySelector("svg.lucide-shield-check")).toBeNull();
+ fireEvent.click(pill);
+ const panel = await screen.findByTestId("composer-permission-panel");
+ const glyphs = within(panel)
+ .getAllByRole("option")
+ .map((el) => el.querySelector("svg")?.getAttribute("class") ?? "");
+ // default → question shield, acceptEdits → pen, bypass → shield off; plan lives on the switch.
+ expect(glyphs.some((c) => c.includes("lucide-shield-question"))).toBe(true);
+ expect(glyphs.some((c) => c.includes("lucide-file-pen"))).toBe(true);
+ expect(glyphs.some((c) => c.includes("lucide-shield-off"))).toBe(true);
+ expect(new Set(glyphs).size).toBe(glyphs.length);
+ });
- expect(screen.getByTestId("chat-stage").getAttribute("data-empty")).toBe("false");
- expect(screen.getByTestId("chat-message-user").textContent).toContain("What is on today?");
- const answer = screen.getByTestId("chat-message-assistant");
- expect(answer.textContent).toContain("Jarvis");
- // Markdown is rendered, not printed: the list is a list and the bold is bold.
- expect(within(answer).getAllByRole("listitem")).toHaveLength(2);
- expect(within(answer).getByText("10:00").tagName).toBe("STRONG");
- // The composer stays with the conversation.
- expect(screen.getByTestId("chat-composer")).toBeTruthy();
+ it("grows the text box with the typed text and caps it at its max height", () => {
+ render(<ChatStage />);
+ const box = screen.getByPlaceholderText("Ask anything…") as HTMLTextAreaElement;
+ // jsdom has no layout: stand in for scrollHeight and the max-height rule.
+ let scrollHeight = 48;
+ Object.defineProperty(box, "scrollHeight", { configurable: true, get: () => scrollHeight });
+ const computed = vi.spyOn(window, "getComputedStyle").mockImplementation(
+ () => ({ maxHeight: "192px" }) as CSSStyleDeclaration,
+ );
+ try {
+ scrollHeight = 120;
+ fireEvent.change(box, { target: { value: "one two three four five" } });
+ expect(box.style.height).toBe("120px");
+ expect(box.style.overflowY).toBe("hidden");
+ scrollHeight = 400;
+ fireEvent.change(box, { target: { value: "a much longer prompt".repeat(40) } });
+ expect(box.style.height).toBe("192px");
+ expect(box.style.overflowY).toBe("auto");
+ } finally {
+ computed.mockRestore();
+ }
});
- it("shows the turn while it runs: the brain's steps and the answer as it is written", () => {
- useEventStore.setState({
- activeThreadId: "t1",
- messages: [{ id: "m1", role: "user", content: "Turn on the lights", ts: 1 }],
- chatThinking: true,
- thinkingStartedTs: Date.now() - 4_000,
- thinkingSteps: [
- {
- id: "s1",
- kind: "tool",
- labelKey: "thinking.step_tool",
- detail: "living room",
- status: "active",
- startedTs: Date.now() - 3_000,
- },
- ],
- liveReply: { text: "On, in the living room", threadId: "t1", done: false, ts: 2 },
+ it("shows no restart notice when the catalog carries the permission ladders", () => {
+ render(<ChatStage />);
+ expect(screen.queryByTestId("composer-backend-outdated")).toBeNull();
+ });
+
+ it("greys out a provider that is not connected and says how to fix it", () => {
+ useAgentChatStore.setState({
+ connections: [{ jarvis: "claude-api", key_set: false, is_active_brain: true }],
});
render(<ChatStage />);
+ const hint = screen.getByTestId("composer-connect-hint");
+ expect(hint.textContent).toContain("Anthropic Claude");
+ // Send stays off until the provider is usable.
+ expect((screen.getByTestId("composer-send") as HTMLButtonElement).disabled).toBe(true);
+ });
- const live = screen.getByTestId("chat-turn-live");
- expect(live.textContent).toContain("living room");
- expect(screen.getByTestId("chat-live-text").textContent).toContain("On, in the living room");
+ it("renders the folded timeline: user bubble, byline with provider + model, tool row, answer", () => {
+ const timeline = reduceEvents(EMPTY_TIMELINE, [
+ ev("user_message", { text: "list the files" }),
+ ev("turn_started", { turn_id: "t1", provider: "claude-api", model: "claude-opus-5", effort: "high", runner: "claude-cli" }),
+ ev("tool_call", { turn_id: "t1", call_id: "c1", name: "Bash", input: { command: "ls" } }),
+ ev("tool_result", { turn_id: "t1", call_id: "c1", output: "a.py\nb.py", is_error: false, duration_ms: 40 }),
+ ev("assistant_text", { turn_id: "t1", message_id: "m1", text: "Two files: **a.py** and b.py." }),
+ ev("turn_finished", { turn_id: "t1", status: "done", duration_ms: 1200, usage: {} }),
+ ]);
+ useAgentChatStore.setState({ activeSessionId: "s1", timeline });
+ render(<ChatStage />);
+ expect(screen.getByTestId("chat-stage").getAttribute("data-empty")).toBe("false");
+ expect(screen.getByTestId("agent-message-user").textContent).toContain("list the files");
+ const turn = screen.getByTestId("agent-turn");
+ expect(turn.textContent).toContain("Anthropic Claude");
+ expect(turn.textContent).toContain("claude-opus-5");
+ const tool = within(turn).getByTestId("agent-tool");
+ expect(tool.getAttribute("data-tool")).toBe("Bash");
+ expect(tool.getAttribute("data-state")).toBe("done");
+ // The row opens to show input and output.
+ fireEvent.click(within(tool).getByRole("button"));
+ expect(tool.textContent).toContain("a.py");
+ expect(within(turn).getByTestId("agent-text").querySelector("strong")?.textContent).toBe("a.py");
+ // The person's message was pinned to the top of the scroll area.
+ expect(scrollTo).toHaveBeenCalled();
});
- it("keeps the steps a finished reply came with when it is replayed from the history", () => {
- useEventStore.setState({
- activeThreadId: "t1",
- messages: [
- {
- id: "m2",
- role: "assistant",
- content: "Sent.",
- ts: 2,
- trace: {
- durationMs: 3_200,
- steps: [
- {
- id: "s1",
- kind: "tool",
- labelKey: "thinking.step_tool",
- detail: "mailbox",
- status: "done",
- startedTs: 1,
- durationMs: 900,
- },
- ],
- },
- },
- ],
+ it("shows the approval card while the runner waits and routes the click to the store", () => {
+ const decide = vi.fn(async () => {});
+ const timeline = reduceEvents(EMPTY_TIMELINE, [
+ ev("user_message", { text: "delete it" }),
+ ev("turn_started", { turn_id: "t2", provider: "openai", model: "", effort: "", runner: "api" }),
+ ev("approval_required", { turn_id: "t2", approval_id: "a1", call_id: "c2", name: "RunCommand", input: { command: "rm x" }, summary: "rm x" }),
+ ]);
+ useAgentChatStore.setState({ activeSessionId: "s2", timeline, decide });
+ render(<ChatStage />);
+ const card = screen.getByTestId("agent-approval");
+ expect(card.textContent).toContain("rm x");
+ act(() => {
+ fireEvent.click(within(card).getByTestId("approval-allow"));
});
+ expect(decide).toHaveBeenCalledWith("a1", "allow");
+ // The composer offers Stop while the turn runs.
+ expect(screen.getByTestId("composer-stop")).toBeTruthy();
+ });
+
+ it("always shows that the turn is alive: glyph, a word, the clock and the tokens", () => {
+ vi.useFakeTimers();
+ try {
+ const started = Date.now();
+ const timeline = reduceEvents(EMPTY_TIMELINE, [
+ ev("user_message", { text: "dig into it" }),
+ { seq: 2, ts_ms: started, kind: "turn_started", payload: { turn_id: "t1", provider: "claude-api", model: "claude-opus-5", effort: "high", runner: "claude-cli" } },
+ { seq: 0, ts_ms: started, kind: "reasoning_started", payload: { turn_id: "t1", message_id: "m1" } },
+ { seq: 0, ts_ms: started, kind: "usage_delta", payload: { turn_id: "t1", usage: { input_tokens: 12, output_tokens: 4800 } } },
+ ]);
+ useAgentChatStore.setState({ activeSessionId: "s1", timeline });
+ render(<ChatStage />);
+
+ // The redacted thought is a row of its own — thinking you cannot read
+ // is still thinking you can see.
+ const reasoning = screen.getByTestId("agent-reasoning");
+ expect(reasoning.getAttribute("data-live")).toBe("true");
+
+ const live = screen.getByTestId("agent-turn-live");
+ expect(within(live).getByTestId("agent-glyph")).toBeTruthy();
+ expect(live.textContent).toMatch(/4\.8k/);
+ // The clock moves on its own.
+ act(() => {
+ vi.advanceTimersByTime(12_000);
+ });
+ expect(live.textContent).toMatch(/1[0-9]s|12s/);
+ // The rail marks the whole block as running.
+ expect(screen.getByTestId("agent-turn-rail").className).toContain("agent-rail-live");
+ // A running turn shows no receipt yet.
+ expect(screen.queryByTestId("agent-turn-footer")).toBeNull();
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it("names tools the way the agent's log does and closes with time and tokens", () => {
+ const timeline = reduceEvents(EMPTY_TIMELINE, [
+ ev("user_message", { text: "check the repo" }),
+ ev("turn_started", { turn_id: "t9", provider: "claude-api", model: "claude-opus-5", effort: "high", runner: "claude-cli" }),
+ ev("tool_call", { turn_id: "t9", call_id: "c1", name: "PowerShell", input: { command: "Get-ChildItem -Path 'C:\\Users'" } }),
+ ev("tool_result", { turn_id: "t9", call_id: "c1", output: "ok", is_error: false }),
+ ev("tool_call", { turn_id: "t9", call_id: "c2", name: "mcp__github__create_issue", input: { title: "Bug" } }),
+ ev("tool_result", { turn_id: "t9", call_id: "c2", output: "#12", is_error: false }),
+ ev("reasoning", { turn_id: "t9", text: "", duration_ms: 8585 }),
+ ev("assistant_text", { turn_id: "t9", message_id: "m1", text: "Done." }),
+ ev("turn_finished", { turn_id: "t9", status: "done", duration_ms: 12_000, usage: { input_tokens: 2, output_tokens: 219 }, cost_usd: 0.8483 }),
+ ]);
+ useAgentChatStore.setState({ activeSessionId: "s9", timeline });
render(<ChatStage />);
- expect(screen.getByTestId("chat-message-assistant").textContent).toContain("mailbox");
+ const tools = screen.getAllByTestId("agent-tool");
+ expect(tools[0].getAttribute("data-tool")).toBe("PowerShell");
+ expect(tools[0].textContent).toContain("PowerShell");
+ expect(tools[0].textContent).toContain("Get-ChildItem");
+ // An MCP call is named after its server, and wears its mark.
+ expect(tools[1].getAttribute("data-family")).toBe("mcp");
+ expect(tools[1].textContent).toContain("GitHub");
+
+ // Thinking with no readable text still shows its time and does not open.
+ const reasoning = screen.getByTestId("agent-reasoning");
+ expect(reasoning.textContent).toMatch(/9s|8\.6s|8s/);
+ expect(within(reasoning).getByRole("button").hasAttribute("disabled")).toBe(true);
+
+ const footer = screen.getByTestId("agent-turn-footer");
+ expect(footer.textContent).toContain("12s");
+ expect(footer.textContent).toContain("219");
+ expect(footer.textContent).toContain("$0.8483");
});
- it("reads a spoken session in the same column, without a composer", () => {
+ it("reads an opened voice session in the chat column instead of the previous chat", () => {
+ // The regression this guards: the sidebar's history lists voice sessions
+ // next to agent chats, and clicking one used to load its words into the
+ // event store while the stage kept rendering the agent timeline — the
+ // screen did not change at all.
+ const timeline = reduceEvents(EMPTY_TIMELINE, [
+ ev("user_message", { turn_id: "t1", text: "Earlier agent chat" }),
+ ]);
+ useAgentChatStore.setState({ activeSessionId: null, timeline });
useEventStore.setState({
activeKind: "voice",
activeThreadId: "v1",
@@ -205,14 +409,24 @@ describe("ChatStage (Jarvis, typed)", () => {
{ id: "m1", role: "user", content: "set a timer", ts: 1 },
{ id: "m2", role: "assistant", content: "Ten minutes, running.", ts: 2 },
],
+ thinkingTraces: {},
});
render(<ChatStage />);
const stage = screen.getByTestId("voice-thread-stage");
expect(stage.getAttribute("data-thread")).toBe("v1");
+ expect(stage.textContent).toContain("Kitchen timer");
expect(stage.textContent).toContain("Ten minutes, running.");
- // A spoken thread is continued by talking.
- expect(screen.queryByTestId("chat-composer")).toBeNull();
+ // A spoken thread has no composer: it is continued by talking.
+ expect(screen.queryByTestId("agent-composer")).toBeNull();
expect(screen.getByTestId("continue-by-voice")).toBeTruthy();
});
+
+ it("gives the stage back to the agent chat once a session is open", () => {
+ useEventStore.setState({ activeKind: "voice", activeThreadId: "v1", messages: [] });
+ useAgentChatStore.setState({ activeSessionId: "s1", timeline: EMPTY_TIMELINE });
+ render(<ChatStage />);
+ expect(screen.queryByTestId("voice-thread-stage")).toBeNull();
+ expect(screen.getByTestId("chat-stage")).toBeTruthy();
+ });
});
diff --git a/jarvis/ui/web/frontend/src/components/home/ChatStage.tsx b/jarvis/ui/web/frontend/src/components/home/ChatStage.tsx
index beb2df1f2b..13de25e3f7 100644
--- a/jarvis/ui/web/frontend/src/components/home/ChatStage.tsx
+++ b/jarvis/ui/web/frontend/src/components/home/ChatStage.tsx
@@ -1,62 +1,69 @@
-import { useEffect, useLayoutEffect, useRef, useState } from "react";
-import ReactMarkdown from "react-markdown";
-import remarkGfm from "remark-gfm";
+import { useCallback, useEffect, useLayoutEffect, useMemo, useRef } from "react";
-import { useEventStore, type ChatMessage } from "@/store/events";
+import { useEventStore } from "@/store/events";
+import { useAgentChatStore } from "@/store/agentChat";
import { ScrollArea } from "@/components/ui/scroll-area";
-import { ChatInput } from "@/components/ChatInput";
-import { TurnSteps } from "@/components/home/TurnSteps";
+import { AgentComposer } from "@/components/agentchat/AgentComposer";
+import { AgentTimeline } from "@/components/agentchat/AgentTimeline";
import { Greeting } from "@/components/home/Greeting";
-import { ProviderLogo } from "@/components/providers/ProviderLogo";
-import { prettyProviderName } from "@/lib/prettyProviderName";
import { VoiceThreadStage } from "@/components/home/VoiceThreadStage";
+import type { ApprovalDecision } from "@/lib/agentChatApi";
import { useT } from "@/i18n";
-import { cn } from "@/lib/utils";
/**
- * The chat stage — Jarvis with a keyboard.
+ * The chat stage — the typed half of the front page.
*
- * This is the SAME assistant the microphone talks to, on the same brain, with
- * the same tools, the same memory and the same conversation history. The only
- * difference from the voice stage next door is the input: here the person
- * types and reads instead of speaking and listening. Everything a spoken turn
- * can do — open an app, read the calendar, run a skill, ask back before a
- * consequential action — a typed turn does too, because it is literally the
- * same turn (jarvis/ui/desktop_app.py::_on_user_message → BrainManager).
+ * Since 2026-08-23 this is the AGENT chat (jarvis/agent_chat): a coding-agent
+ * session on whichever sub-agent — Claude Code, Codex, Antigravity, Grok
+ * Build, or an API-key provider — the composer picks, with the model, the
+ * reasoning effort and the permission mode dialled in the composer itself.
+ * The voice stage next door still talks to the voice brain; this stage does
+ * not (AP-9: nothing here touches the voice path).
*
- * What it is NOT, and was between 2026-08-23 and 2026-08-24: a coding-agent
- * session that happened to run in the Jarvis folder, picked by provider,
- * model, reasoning effort and permission mode. Coding agents are a real thing
- * this app has — they are the Agentic IDE's sessions, where a workspace
- * folder is the whole point. On the front page that was the wrong assistant
- * wearing the right name (maintainer, 2026-08-24).
+ * One centred column, like a document: the greeting and the composer sit
+ * in the middle of an empty page; once there are messages the column
+ * scrolls and the composer docks to the bottom. The history is the
+ * sidebar's (components/home/RecentChats), visible from every section.
*
- * The wiring, end to end:
- * composer (components/ChatInput) sends a `message` frame on the app socket
- * → MessageSent on the event bus
- * → the brain answers, streaming its text as AssistantTextDelta("chat")
- * and its progress as the reasoning steps this column shows live
- * → the finished reply arrives as the assistant message and is stored in
- * the thread, so the sidebar's history holds it like any other.
+ * One conversation is on stage at a time. The sidebar's history mixes agent
+ * chats with VOICE sessions, and a voice session opened from here is read in
+ * components/home/VoiceThreadStage — the same column, no composer. Which of
+ * the two shows is decided by the event store's active thread: opening either
+ * kind clears the other (components/home/chatRows), so the two can never both
+ * claim the stage and leave a click looking like it did nothing.
*
- * A spoken session opened from that history is READ here, in
- * components/home/VoiceThreadStage: the same column, no composer, because a
- * spoken thread is continued by speaking.
- *
- * Scrolling follows the Claude app: when the person sends, their message is
- * brought to the TOP of the scroll area and the answer grows below it — the
- * eye stays where the new turn begins instead of chasing the bottom. A spacer
- * under the last turn makes that possible even when the turn is short; it
- * shrinks as the answer fills the viewport, so a finished answer never trails
- * a screen of blank paper. Nothing jumps on assistant output.
+ * Scrolling follows the Claude app: when the person sends, their message
+ * is brought to the TOP of the scroll area and the answer grows below it —
+ * the eye stays where the new turn begins instead of chasing the bottom.
+ * A spacer under the last turn makes that possible even when the turn is
+ * short; it shrinks as the answer fills the viewport. Nothing jumps on
+ * assistant output.
*/
export function ChatStage() {
const t = useT();
- const messages = useEventStore((s) => s.messages);
- const chatThinking = useEventStore((s) => s.chatThinking);
- const activeThreadId = useEventStore((s) => s.activeThreadId);
- const isVoiceThread = useEventStore((s) => s.activeKind === "voice" && s.activeThreadId !== null);
- const hasContent = messages.length > 0 || chatThinking;
+ const assistantName = useEventStore((s) => s.assistantName);
+ const items = useAgentChatStore((s) => s.timeline.items);
+ const activeSessionId = useAgentChatStore((s) => s.activeSessionId);
+ const catalog = useAgentChatStore((s) => s.catalog);
+ const decide = useAgentChatStore((s) => s.decide);
+ const loadCatalog = useAgentChatStore((s) => s.loadCatalog);
+ const loadSessions = useAgentChatStore((s) => s.loadSessions);
+ const voiceThreadId = useEventStore((s) => (s.activeKind === "voice" ? s.activeThreadId : null));
+ const hasContent = items.length > 0;
+
+ useEffect(() => {
+ if (!catalog) void loadCatalog();
+ void loadSessions();
+ }, [catalog, loadCatalog, loadSessions]);
+
+ const providerLabel = useCallback(
+ (id: string) => catalog?.providers.find((p) => p.id === id)?.label ?? id,
+ [catalog],
+ );
+ const onDecide = useCallback(
+ (approvalId: string, decision: ApprovalDecision) => void decide(approvalId, decision),
+ [decide],
+ );
const rootRef = useRef<HTMLDivElement | null>(null);
const columnRef = useRef<HTMLDivElement | null>(null);
@@ -65,8 +72,8 @@ export function ChatStage() {
// turn. Null until the person sends in this mounted column — opening an
// old conversation lands at its end like before, with no spacer.
const anchorIdRef = useRef<string | null>(null);
- const lastMessageIdRef = useRef<string | null>(null);
- const threadRef = useRef<string | null>(activeThreadId);
+ const lastItemIdRef = useRef<string | null>(null);
+ const sessionRef = useRef<string | null>(activeSessionId);
// Refs, not state, on purpose: the spacer must be sized BEFORE the scroll
// that relies on it, in the same layout pass — a state round-trip would
@@ -80,44 +87,39 @@ export function ChatStage() {
spacer.style.minHeight = "0px";
return;
}
- // Everything from the anchored message down to the spacer is the turn.
const turnHeight = spacer.getBoundingClientRect().top - anchor.getBoundingClientRect().top;
const room = viewport.clientHeight - turnHeight - TURN_BOTTOM_PAD_PX;
spacer.style.minHeight = `${Math.max(0, Math.round(room))}px`;
};
- // React to the newest message: a user line is the start of a turn and gets
- // pinned to the top; anything else, with no turn in flight, keeps the old
- // "follow the end" behaviour (first render of a conversation). Switching
- // conversations resets the anchor: the new thread is read from its end, not
- // from wherever the previous turn left the scroll position.
+ const lastItem = items[items.length - 1];
+ const lastItemId = lastItem?.id ?? null;
+ const lastItemIsUser = lastItem?.type === "user";
+
useLayoutEffect(() => {
- if (threadRef.current !== activeThreadId) {
- threadRef.current = activeThreadId;
+ if (sessionRef.current !== activeSessionId) {
+ sessionRef.current = activeSessionId;
anchorIdRef.current = null;
- lastMessageIdRef.current = null;
+ lastItemIdRef.current = null;
}
const viewport = viewportOf(rootRef.current);
- const last = messages[messages.length - 1];
- const lastId = last?.id ?? null;
- const isNew = lastId !== lastMessageIdRef.current;
- lastMessageIdRef.current = lastId;
- if (!viewport || !last) return;
- if (isNew && last.role === "user") {
- anchorIdRef.current = last.id;
+ const isNew = lastItemId !== lastItemIdRef.current;
+ lastItemIdRef.current = lastItemId;
+ if (!viewport || !lastItemId) return;
+ if (isNew && lastItemIsUser) {
+ anchorIdRef.current = lastItemId;
applySpacer();
- scrollMessageToTop(viewport, last.id);
+ scrollMessageToTop(viewport, lastItemId);
return;
}
applySpacer();
if (isNew && anchorIdRef.current === null) scrollToEnd(viewport);
// `applySpacer` reads refs only and is recreated per render by design.
// eslint-disable-next-line react-hooks/exhaustive-deps
- }, [messages, activeThreadId, chatThinking]);
+ }, [lastItemId, lastItemIsUser, activeSessionId, items.length]);
- // The live turn grows without a new message (steps arrive, the answer
- // streams in), so the spacer also follows the column's own size where the
- // platform has ResizeObserver.
+ // The live blocks grow without a new item; the spacer follows the
+ // column's size where the platform has ResizeObserver.
useEffect(() => {
const column = columnRef.current;
const viewport = viewportOf(rootRef.current);
@@ -129,45 +131,41 @@ export function ChatStage() {
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [hasContent]);
+ const subtitle = useMemo(() => t("agent_chat.empty_subtitle"), [t]);
+
// A spoken thread was opened from the history: read it here, in the column
- // the composer would otherwise own.
- if (isVoiceThread) return <VoiceThreadStage />;
+ // the composer would otherwise own. An agent chat opening clears this.
+ if (voiceThreadId && !activeSessionId) return <VoiceThreadStage />;
if (!hasContent) {
return (
- <div
- className="flex min-h-0 flex-1 flex-col items-center"
- data-testid="chat-stage"
- data-empty="true"
- >
+ <div className="flex min-h-0 flex-1 flex-col items-center" data-testid="chat-stage" data-empty="true">
<div className="flex w-full max-w-[760px] flex-1 flex-col justify-center gap-8 px-6 pb-20">
- <Greeting subtitle={t("home.chat_empty_title")} />
- <ChatInput />
+ <Greeting subtitle={subtitle} />
+ <AgentComposer autoFocus />
</div>
</div>
);
}
return (
- <div
- className="flex min-h-0 flex-1 flex-col items-center"
- data-testid="chat-stage"
- data-empty="false"
- >
+ <div className="flex min-h-0 flex-1 flex-col items-center" data-testid="chat-stage" data-empty="false">
<ScrollArea ref={rootRef} className="min-h-0 w-full flex-1">
<div
ref={columnRef}
className="relative mx-auto flex w-full max-w-[760px] flex-col gap-5 px-6 pb-6 pt-8"
>
- {messages.map((m) => (
- <MessageRow key={m.id} message={m} />
- ))}
- {chatThinking && <LiveTurn />}
+ <AgentTimeline
+ items={items}
+ assistantName={assistantName}
+ providerLabel={providerLabel}
+ onDecide={onDecide}
+ />
<div ref={spacerRef} aria-hidden data-testid="chat-bottom-spacer" className="shrink-0" />
</div>
</ScrollArea>
<div className="w-full max-w-[760px] px-6 pb-5 pt-2">
- <ChatInput />
+ <AgentComposer />
</div>
</div>
);
@@ -183,8 +181,8 @@ function viewportOf(root: HTMLElement | null): HTMLElement | null {
}
function messageElement(viewport: HTMLElement, id: string): HTMLElement | null {
- // Attribute compare instead of a selector: message ids carry characters
- // (":" , ".") a CSS selector would need escaping for.
+ // Attribute compare instead of a selector: ids carry characters a CSS
+ // selector would need escaping for.
for (const el of Array.from(viewport.querySelectorAll<HTMLElement>("[data-message-id]"))) {
if (el.dataset.messageId === id) return el;
}
@@ -215,183 +213,3 @@ function scrollMessageToTop(viewport: HTMLElement, id: string) {
function scrollToEnd(viewport: HTMLElement) {
scrollViewport(viewport, viewport.scrollHeight);
}
-
-/** Elapsed wall-clock since `startedTs`, ticking once a second while set. */
-function useElapsedMs(startedTs: number | null): number {
- const [now, setNow] = useState(() => Date.now());
- useEffect(() => {
- if (startedTs === null) return;
- setNow(Date.now());
- const id = window.setInterval(() => setNow(Date.now()), 1000);
- return () => window.clearInterval(id);
- }, [startedTs]);
- return startedTs === null ? 0 : Math.max(0, now - startedTs);
-}
-
-/**
- * The assistant turn still in progress: byline, the live steps, and the
- * answer as it is being written.
- *
- * The streaming text is the half that was missing while this column showed
- * only the steps: the brain publishes the answer as cumulative
- * AssistantTextDelta snapshots on the "chat" channel several times a second
- * (jarvis/core/text_stream.py), so a long reply reads as it arrives instead
- * of appearing at once when the turn ends. The store clears it the moment the
- * finished message lands, so the two never show the same words twice.
- *
- * Reads the store itself so the column does not re-render on every delta —
- * only this block does.
- */
-function LiveTurn() {
- const steps = useEventStore((s) => s.thinkingSteps);
- const startedTs = useEventStore((s) => s.thinkingStartedTs);
- const liveText = useEventStore((s) => s.liveReply?.text ?? "");
- const elapsed = useElapsedMs(startedTs);
- return (
- <Turn live testId="chat-turn-live">
- <TurnSteps steps={steps} live durationMs={elapsed} />
- {liveText.trim() !== "" && <Prose text={liveText} testId="chat-live-text" />}
- </Turn>
- );
-}
-
-/**
- * One assistant turn: the byline that says who answered, and a hairline rail
- * everything the turn produced hangs off — the steps it took, then the answer.
- * The rail glows while the turn runs, so the block reads as one live unit
- * rather than a list of disconnected rows.
- *
- * The byline names the BRAIN, with its vendor's own mark: the provider and
- * model configured under Agents / API keys, which is what a typed turn runs
- * on. It is deliberately not the voice engine — that one only answers speech.
- */
-function Turn({
- children,
- live = false,
- testId,
- messageId,
-}: {
- children: React.ReactNode;
- live?: boolean;
- testId?: string;
- messageId?: string;
-}) {
- const assistantName = useEventStore((s) => s.assistantName);
- const provider = useEventStore((s) => s.brainProvider);
- const model = useEventStore((s) => s.brainModel);
- const label = provider ? prettyProviderName(provider) : "";
- return (
- <div className="flex flex-col gap-1.5" data-testid={testId} data-message-id={messageId}>
- <div className="flex flex-wrap items-center gap-x-2 gap-y-1 px-1 font-mono text-[10px] uppercase tracking-[0.14em] text-primary">
- <span
- className={cn("h-1 w-1 rounded-full bg-primary", live && "motion-safe:animate-pulse")}
- aria-hidden
- />
- <span>{assistantName}</span>
- {provider && (
- <span className="inline-flex items-center gap-1.5 normal-case tracking-normal text-muted-foreground">
- <ProviderLogo providerId={provider} label={label} size="sm" />
- <span>{label}</span>
- {model && <span className="text-muted-foreground/70">· {model}</span>}
- </span>
- )}
- </div>
- <div className="relative flex flex-col gap-1.5 pl-4">
- <span
- aria-hidden
- data-testid="chat-turn-rail"
- className={cn(
- "absolute bottom-1 left-[3px] top-1 w-px rounded-full",
- live ? "agent-rail-live" : "bg-border",
- )}
- />
- {children}
- </div>
- </div>
- );
-}
-
-/**
- * An assistant answer, rendered as Markdown.
- *
- * Jarvis writes lists, short headings and the odd bit of code, and typed
- * answers are read rather than heard — so an answer is rendered, not printed
- * as source. Colours come from theme tokens (`prose-neutral` +
- * `dark:prose-invert`), so it reads correctly in light and dark. The person's
- * own lines stay plain text: they typed characters, not markup.
- */
-function Prose({ text, testId }: { text: string; testId?: string }) {
- return (
- <div
- data-testid={testId}
- className={cn(
- "prose prose-neutral max-w-none text-[15px] leading-relaxed dark:prose-invert [overflow-wrap:anywhere]",
- "prose-p:my-2 prose-headings:font-display prose-headings:tracking-tight prose-h1:text-xl prose-h2:text-lg prose-h3:text-base",
- "prose-a:text-primary prose-a:no-underline hover:prose-a:underline",
- "prose-code:rounded prose-code:bg-muted/60 prose-code:px-1 prose-code:py-0.5 prose-code:font-mono prose-code:text-[0.85em] prose-code:font-normal prose-code:before:hidden prose-code:after:hidden",
- "prose-pre:my-2 prose-pre:border prose-pre:border-border prose-pre:bg-card/80 prose-pre:text-[13px]",
- "prose-li:my-0.5 prose-ul:my-2 prose-ol:my-2",
- )}
- >
- <ReactMarkdown remarkPlugins={[remarkGfm]}>{text}</ReactMarkdown>
- </div>
- );
-}
-
-/**
- * One message in the column. The person's lines sit right in a quiet bubble;
- * the assistant's run flush-left with a byline and, when there is one, the
- * turn's steps ("Thought for Ns" + tool calls) above the answer — prose on
- * the page, not a bubble.
- */
-function MessageRow({ message }: { message: ChatMessage }) {
- const assistantName = useEventStore((s) => s.assistantName);
- const liveTrace = useEventStore((s) => s.thinkingTraces[message.id]);
- // A replayed conversation carries its steps on the message itself; a reply
- // that happened in this session has them in the store's live map.
- const trace = liveTrace ?? message.trace;
- const isUser = message.role === "user";
-
- if (message.role === "system") {
- return (
- <div
- data-message-id={message.id}
- data-testid="chat-message-system"
- className="mx-auto max-w-[85%] rounded-lg border border-border bg-secondary/50 px-3 py-2 text-center text-xs italic text-muted-foreground"
- >
- {message.content}
- </div>
- );
- }
-
- if (message.role === "preamble") {
- return (
- <div
- data-message-id={message.id}
- className="flex flex-col gap-1 text-xs italic leading-relaxed text-muted-foreground"
- >
- <span className="font-mono text-[10px] not-italic uppercase tracking-[0.14em] text-muted-foreground">
- {assistantName} · pre-ack
- </span>
- <div className="whitespace-pre-wrap">{message.content}</div>
- </div>
- );
- }
-
- if (isUser) {
- return (
- <div className="flex justify-end" data-testid="chat-message-user" data-message-id={message.id}>
- <div className="max-w-[78%] rounded-2xl rounded-br-md border border-border bg-secondary px-4 py-2.5 text-[15px] leading-relaxed text-foreground">
- <div className="whitespace-pre-wrap">{message.content}</div>
- </div>
- </div>
- );
- }
-
- return (
- <Turn testId="chat-message-assistant" messageId={message.id}>
- {trace && <TurnSteps steps={trace.steps} durationMs={trace.durationMs} className="mb-1" />}
- <Prose text={message.content} />
- </Turn>
- );
-}
diff --git a/jarvis/ui/web/frontend/src/components/home/RecentChats.test.tsx b/jarvis/ui/web/frontend/src/components/home/RecentChats.test.tsx
index b0eb9826df..e8f69ae5ad 100644
--- a/jarvis/ui/web/frontend/src/components/home/RecentChats.test.tsx
+++ b/jarvis/ui/web/frontend/src/components/home/RecentChats.test.tsx
@@ -2,23 +2,17 @@ import { act, cleanup, fireEvent, render, screen } from "@testing-library/react"
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { RecentChats } from "@/components/home/RecentChats";
+import { useAgentChatStore } from "@/store/agentChat";
import { useEventStore, type ConversationSummary } from "@/store/events";
import { useHomeStore } from "@/store/home";
-/**
- * The sidebar history lists Jarvis' own conversations — the ones you spoke and
- * the ones you typed — because both are the same assistant. The Agentic IDE's
- * agent chats are listed in the IDE, next to the folder they belong to; a row
- * for one here would open a surface the front page does not have.
- */
-
function row(kind: ConversationSummary["kind"], id: string, title: string): ConversationSummary {
return { kind, id, title, preview: title, created_ms: 500, updated_ms: 1_000, message_count: 2 };
}
const CONVERSATIONS = [row("voice", "v1", "Spoken thread"), row("text", "t1", "Typed thread")];
-const VOICE_DETAIL = {
+const DETAIL = {
kind: "voice",
id: "v1",
title: "Voice session",
@@ -29,17 +23,6 @@ const VOICE_DETAIL = {
seeded_turns: 2,
};
-const TEXT_DETAIL = {
- kind: "text",
- id: "t1",
- title: "Typed thread",
- messages: [
- { role: "user", text: "was steht an", ts_ms: 1_000 },
- { role: "assistant", text: "Zwei Termine.", ts_ms: 2_000 },
- ],
- seeded_turns: 2,
-};
-
async function flush() {
await act(async () => {
await Promise.resolve();
@@ -51,25 +34,43 @@ describe("RecentChats", () => {
beforeEach(() => {
vi.stubGlobal(
"fetch",
- vi.fn(async (url: string) => {
- const href = String(url);
- if (href.endsWith("/resume")) {
- const detail = href.includes("/t1/") ? TEXT_DETAIL : VOICE_DETAIL;
- return new Response(JSON.stringify(detail), { status: 200 });
- }
- // The block polls GET /api/chats on mount; answering with the same
- // rows keeps the refresh from wiping what the test just seeded.
- return new Response(JSON.stringify(CONVERSATIONS), { status: 200 });
- }),
+ vi.fn(async (url: string) =>
+ String(url).endsWith("/resume")
+ ? new Response(JSON.stringify(DETAIL), { status: 200 })
+ : // The block polls GET /api/chats on mount; answering with the same
+ // rows keeps the refresh from wiping what the test just seeded.
+ new Response(JSON.stringify(CONVERSATIONS), { status: 200 }),
+ ),
);
useEventStore.setState({
conversations: CONVERSATIONS,
activeThreadId: null,
- activeKind: "text",
messages: [],
activeSection: "board",
});
useHomeStore.setState({ surface: "voice", transcript: [] });
+ useAgentChatStore.setState({
+ sessions: [
+ {
+ session_id: "s1",
+ title: "Agent chat",
+ provider: "claude-api",
+ model: "",
+ effort: "high",
+ cwd: "C:\work",
+ permission_mode: "acceptEdits",
+ vendor_session: null,
+ created_ms: 500,
+ updated_ms: 900,
+ message_count: 2,
+ preview: "Agent chat",
+ },
+ ],
+ activeSessionId: null,
+ loadSessions: async () => {},
+ newChat: vi.fn(),
+ openSession: vi.fn((id: string) => useAgentChatStore.setState({ activeSessionId: id })),
+ });
});
afterEach(() => {
cleanup();
@@ -89,22 +90,30 @@ describe("RecentChats", () => {
]);
});
- it("opens a typed thread on the chat surface, even from the voice stage", async () => {
+ it("opens an agent chat on the chat surface even from the voice stage", async () => {
render(<RecentChats />);
- fireEvent.click(screen.getByTitle("Typed thread"));
+ // The classic brain's text threads are no longer listed — the chat
+ // surface is the agent chat now (components/home/ChatStage).
+ expect(screen.queryByTitle("Typed thread")).toBeNull();
+ fireEvent.click(screen.getByTitle("Agent chat"));
await flush();
expect(useHomeStore.getState().surface).toBe("chat");
expect(useEventStore.getState().activeSection).toBe("chats");
- expect(useEventStore.getState().activeThreadId).toBe("t1");
- expect(useEventStore.getState().activeKind).toBe("text");
- expect(useEventStore.getState().messages.map((m) => m.content)).toEqual([
- "was steht an",
- "Zwei Termine.",
- ]);
- // A typed thread is read on the chat stage, not spoken back into the lane.
+ expect(useAgentChatStore.getState().openSession).toHaveBeenCalledWith("s1");
expect(useHomeStore.getState().transcript).toEqual([]);
});
+ it("clears the voice thread when an agent chat takes the stage", async () => {
+ useEventStore.setState({ activeKind: "voice", activeThreadId: "v1" });
+ render(<RecentChats />);
+ fireEvent.click(screen.getByTitle("Agent chat"));
+ await flush();
+ // Both conversations claiming the stage is what made a click look like it
+ // did nothing: the chat stage kept showing the previous one.
+ expect(useEventStore.getState().activeThreadId).toBeNull();
+ expect(useEventStore.getState().messages).toEqual([]);
+ });
+
it("loads a voice session onto the chat surface when that is where you are", async () => {
useHomeStore.setState({ surface: "chat" });
render(<RecentChats />);
@@ -112,9 +121,11 @@ describe("RecentChats", () => {
await flush();
expect(useHomeStore.getState().surface).toBe("chat");
// Read on the chat stage (components/home/VoiceThreadStage), not seeded
- // into the voice lane.
+ // into the voice lane — and the agent session is ended so it cannot keep
+ // the stage.
expect(useEventStore.getState().activeThreadId).toBe("v1");
expect(useEventStore.getState().messages.map((m) => m.content)).toEqual(["hello", "Hi there."]);
+ expect(useAgentChatStore.getState().newChat).toHaveBeenCalled();
expect(useHomeStore.getState().transcript).toEqual([]);
});
@@ -125,7 +136,7 @@ describe("RecentChats", () => {
expect(screen.getByTestId("all-chats-dialog")).toBeTruthy();
// Both kinds are listed there, whatever the sidebar had room for.
const rows = screen.getAllByTestId("all-chats-row");
- expect(rows.map((r) => r.getAttribute("data-kind")).sort()).toEqual(["text", "voice"]);
+ expect(rows.map((r) => r.getAttribute("data-kind")).sort()).toEqual(["agent", "voice"]);
});
it("filters the archive by what you type", async () => {
diff --git a/jarvis/ui/web/frontend/src/components/home/RecentChats.tsx b/jarvis/ui/web/frontend/src/components/home/RecentChats.tsx
index 9edd311ab7..a917973744 100644
--- a/jarvis/ui/web/frontend/src/components/home/RecentChats.tsx
+++ b/jarvis/ui/web/frontend/src/components/home/RecentChats.tsx
@@ -1,19 +1,22 @@
-import { useState } from "react";
+import { useEffect, useState } from "react";
import { Archive, MessageSquare, Mic, Trash2 } from "lucide-react";
+import { useAgentChatStore } from "@/store/agentChat";
import { useT } from "@/i18n";
import { cn } from "@/lib/utils";
import { SidebarGroup } from "@/components/home/SidebarGroup";
import { AllChatsDialog } from "@/components/home/AllChatsDialog";
import { formatChatWhen, useChatRows, type ChatRow } from "@/components/home/chatRows";
+import { CONVERSATIONS_REFRESH_MS } from "@/hooks/useConversations";
export const RECENT_CHATS_FOLDED = 3;
export const RECENT_CHATS_UNFOLDED = 15;
/**
- * The last conversations — the ones you typed and the ones you spoke, in one
- * list — from the sidebar. This block is the app's one long-lived poller of
- * that history (`useChatRows({ poll: true })`).
+ * The last conversations — agent chats and voice sessions in one list —
+ * from the sidebar. This block is the one long-lived poller of both
+ * histories (`useConversations({ poll: true })` for the voice sessions,
+ * the agent-chat store's session list for the typed ones).
*
* It is a shortcut, not the archive: it shows the handful you touched last
* and hands everything else to "All chats" (components/home/AllChatsDialog),
@@ -24,18 +27,26 @@ export const RECENT_CHATS_UNFOLDED = 15;
* 2026-08-23): a VOICE session opened while the voice stage is up stays
* there, its words loaded into the transcript lane, so you just keep
* talking. Opened from the chat surface it is read there as an archive.
- * A typed thread goes to the chat surface and is continued by typing.
+ * An agent chat goes to the chat surface, where the session is read and
+ * continued by typing — on the provider and model it was using.
*
- * Both are Jarvis, which is why they share one list. The Agentic IDE's agent
- * chats are not here — they belong to a workspace folder and are listed where
- * that folder is (components/agentic/WorkspaceChats).
+ * The classic brain's text threads are no longer listed: since the chat
+ * surface became the agent chat there is nowhere to open them; the data
+ * stays on disk.
*/
export function RecentChats() {
const t = useT();
const { rows, isActive, open: openRow, remove } = useChatRows({ poll: true });
+ const loadSessions = useAgentChatStore((s) => s.loadSessions);
const [open, setOpen] = useState(false);
const [archiveOpen, setArchiveOpen] = useState(false);
+ useEffect(() => {
+ void loadSessions();
+ const id = window.setInterval(() => void loadSessions(), CONVERSATIONS_REFRESH_MS);
+ return () => window.clearInterval(id);
+ }, [loadSessions]);
+
const shown = rows.slice(0, open ? RECENT_CHATS_UNFOLDED : RECENT_CHATS_FOLDED);
const canExpand = rows.length > RECENT_CHATS_FOLDED;
// The archive earns its place only once the sidebar cannot show everything.
@@ -66,7 +77,7 @@ export function RecentChats() {
row={row}
active={isActive(row)}
onOpen={() => openRow(row)}
- onDelete={row.kind === "text" ? () => remove(row) : undefined}
+ onDelete={row.kind === "agent" ? () => remove(row) : undefined}
/>
))}
</ul>
diff --git a/jarvis/ui/web/frontend/src/components/home/chatRows.ts b/jarvis/ui/web/frontend/src/components/home/chatRows.ts
index 197c27f640..538e0cc63c 100644
--- a/jarvis/ui/web/frontend/src/components/home/chatRows.ts
+++ b/jarvis/ui/web/frontend/src/components/home/chatRows.ts
@@ -2,42 +2,38 @@ import { useCallback, useMemo } from "react";
import { useConversations } from "@/hooks/useConversations";
import { useEventStore, type ConversationSummary } from "@/store/events";
+import { useAgentChatStore } from "@/store/agentChat";
import { useHomeStore } from "@/store/home";
import { transcriptFromMessages } from "@/lib/homeTranscript";
/**
- * The one chat history the front page has, and the one way to open a row.
+ * The one chat history the app has, and the one way to open a row of it.
*
- * Both kinds in it are the SAME assistant: the voice sessions you spoke and
- * the chats you typed, from `/api/chats`, merged into one list sorted by when
- * each was last touched. That is the point of the front page — one Jarvis,
- * two ways to reach it — and it is why a typed thread can pick up where a
- * spoken one stopped. The sidebar block and the "All chats" dialog both read
- * THIS, so the two can never disagree about what exists or about what a click
- * does.
+ * Two backends feed it — the voice sessions (`/api/chats`) and the agent
+ * chats (`/api/agent-chat/sessions`) — merged into one list sorted by when
+ * each was last touched. The sidebar block and the "All chats" dialog both
+ * read THIS, so the two can never disagree about what exists or about what
+ * a click does.
*
- * The Agentic IDE's agent chats are deliberately NOT here (maintainer,
- * 2026-08-24). They belong to a workspace folder and are opened where that
- * folder is — components/agentic/WorkspaceChats. Listing them next to Jarvis'
- * own conversations was the visible half of the mix-up this file's history
- * records: for a day, opening the front page's chat opened a coding agent.
- *
- * The rule a click follows: the front page shows exactly ONE conversation, so
- * opening a row replaces whatever was on stage. A spoken session opened while
- * the voice stage is up stays there with its words in the lane; opened from
- * the chat surface it is read there as an archive
- * (components/home/VoiceThreadStage).
+ * The rule a click follows (the bug this file was extracted to fix): the
+ * front page shows exactly ONE conversation, so opening a row must also
+ * close the other kind. Opening an agent chat drops the voice thread from
+ * the stage; opening a voice session ends the agent session's socket. Before
+ * that, clicking a voice row while the chat surface was up loaded its words
+ * into a store the chat stage does not read — the screen simply kept showing
+ * the previous conversation.
*/
export interface ChatRow {
- /** "voice" was spoken, "text" was typed — both are Jarvis. */
- kind: "voice" | "text";
+ kind: "voice" | "agent";
id: string;
title: string;
preview: string;
updatedMs: number;
messageCount: number;
- raw: ConversationSummary;
+ /** The sub-agent an agent chat runs on; empty for a voice session. */
+ provider: string;
+ raw: ConversationSummary | null;
}
export interface ChatRowsApi {
@@ -45,45 +41,59 @@ export interface ChatRowsApi {
/** True for the row currently on the front page's stage. */
isActive: (row: ChatRow) => boolean;
open: (row: ChatRow) => void;
- /** A typed thread can be deleted; a voice session is a recording, not a draft. */
+ /** Agent chats can be deleted; a voice session is a recording, not a draft. */
remove: (row: ChatRow) => void;
}
export function useChatRows({ poll = false }: { poll?: boolean } = {}): ChatRowsApi {
- const { conversations, openConversation, removeConversation } = useConversations({ poll });
- const activeThreadId = useEventStore((s) => s.activeThreadId);
- const activeKind = useEventStore((s) => s.activeKind);
+ const { conversations, openConversation } = useConversations({ poll });
+ const sessions = useAgentChatStore((s) => s.sessions);
+ const activeSessionId = useAgentChatStore((s) => s.activeSessionId);
+ const activeVoiceId = useEventStore((s) => (s.activeKind === "voice" ? s.activeThreadId : null));
const setActiveSection = useEventStore((s) => s.setActiveSection);
+ const setActiveConversation = useEventStore((s) => s.setActiveConversation);
+ const setMessages = useEventStore((s) => s.setMessages);
const seedTranscript = useHomeStore((s) => s.seedTranscript);
const setSurface = useHomeStore((s) => s.setSurface);
- const rows = useMemo<ChatRow[]>(
- () =>
- conversations
- .map((c) => ({
- kind: c.kind === "voice" ? ("voice" as const) : ("text" as const),
- id: c.id,
- title: c.title || c.preview,
- preview: c.preview,
- updatedMs: c.updated_ms,
- messageCount: c.message_count,
- raw: c,
- }))
- .sort((a, b) => b.updatedMs - a.updatedMs),
- [conversations],
- );
+ const rows = useMemo<ChatRow[]>(() => {
+ const voice: ChatRow[] = conversations
+ .filter((c) => c.kind === "voice")
+ .map((c) => ({
+ kind: "voice",
+ id: c.id,
+ title: c.title || c.preview,
+ preview: c.preview,
+ updatedMs: c.updated_ms,
+ messageCount: c.message_count,
+ provider: "",
+ raw: c,
+ }));
+ const agent: ChatRow[] = sessions.map((s) => ({
+ kind: "agent",
+ id: s.session_id,
+ title: s.title || s.preview,
+ preview: s.preview,
+ updatedMs: s.updated_ms,
+ messageCount: s.message_count,
+ provider: s.provider,
+ raw: null,
+ }));
+ return [...voice, ...agent].sort((a, b) => b.updatedMs - a.updatedMs);
+ }, [conversations, sessions]);
const isActive = useCallback(
- (row: ChatRow) => row.id === activeThreadId && row.kind === activeKind,
- [activeKind, activeThreadId],
+ (row: ChatRow) => (row.kind === "agent" ? row.id === activeSessionId : row.id === activeVoiceId),
+ [activeSessionId, activeVoiceId],
);
const open = useCallback(
(row: ChatRow) => {
if (row.kind === "voice") {
- // Standing on the voice stage, a spoken session is resumed there with
- // its words in the lane — you just keep talking. From the chat
- // surface it is read as an archive instead.
+ // End the agent session on stage first: the chat stage renders the
+ // voice archive only while no agent chat is open, and its socket has
+ // no business staying connected to a conversation nobody is looking at.
+ useAgentChatStore.getState().newChat();
const stayOnVoice = useHomeStore.getState().surface === "voice";
const opened = openConversation("voice", row.id);
if (stayOnVoice) {
@@ -93,21 +103,22 @@ export function useChatRows({ poll = false }: { poll?: boolean } = {}): ChatRows
setSurface("chat");
}
} else {
- void openConversation("text", row.id);
+ // Drop the voice thread so the stage shows the agent timeline, not a
+ // stale archive underneath it.
+ setActiveConversation("text", null);
+ setMessages([]);
+ useAgentChatStore.getState().openSession(row.id);
setSurface("chat");
}
setActiveSection("chats");
},
- [openConversation, seedTranscript, setActiveSection, setSurface],
+ [openConversation, seedTranscript, setActiveConversation, setActiveSection, setMessages, setSurface],
);
- const remove = useCallback(
- (row: ChatRow) => {
- if (row.kind !== "text") return;
- void removeConversation(row.id);
- },
- [removeConversation],
- );
+ const remove = useCallback((row: ChatRow) => {
+ if (row.kind !== "agent") return;
+ void useAgentChatStore.getState().removeSession(row.id);
+ }, []);
return { rows, isActive, open, remove };
}
diff --git a/jarvis/ui/web/frontend/src/components/layout/Sidebar.tsx b/jarvis/ui/web/frontend/src/components/layout/Sidebar.tsx
index bc1b801bc1..7c53026d29 100644
--- a/jarvis/ui/web/frontend/src/components/layout/Sidebar.tsx
+++ b/jarvis/ui/web/frontend/src/components/layout/Sidebar.tsx
@@ -18,6 +18,7 @@ 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";
@@ -131,9 +132,9 @@ export function Sidebar({
// "+ 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. The Agentic
- // IDE's chats have their own button in their own column (WorkspaceChats).
+ // button used to do, and it read as the button being broken.
const { newChat, newVoiceRun } = useConversations();
+ const newChatSession = 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`.
@@ -167,11 +168,12 @@ export function Sidebar({
void newVoiceRun();
setActive("chats");
};
- // On the chat surface: an empty page for a new chat with Jarvis. `newChat`
- // drops the open thread whichever kind it was, so a reopened voice session
- // does not linger behind the fresh page either.
+ // 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.
const startNewChat = () => {
newChat();
+ newChatSession();
setSurface("chat");
setActive("chats");
};
diff --git a/tests/unit/agent_chat/test_agent_chat_core.py b/tests/unit/agent_chat/test_agent_chat_core.py
index a7989df363..91e1cb1e8a 100644
--- a/tests/unit/agent_chat/test_agent_chat_core.py
+++ b/tests/unit/agent_chat/test_agent_chat_core.py
@@ -55,15 +55,38 @@ def test_normalize_effort_folds_onto_the_nearest_offered_level(provider, picked,
assert effort.normalize_effort(provider, picked) == expected
-def test_catalog_rows_carry_ladders_and_curated_models_for_cli_runners():
+def test_every_row_is_a_brain_jarvis_can_actually_think_with():
+ """The picker names the MODEL behind the assistant, so every row must be one.
+
+ A subscription coding CLI cannot be a brain (it is an agent loop with no
+ chat API, and ``BrainManager.switch`` refuses it), so offering one here
+ would be a pick that silently does nothing — the class of bug this whole
+ surface was rebuilt to end.
+ """
+ from jarvis.brain.manager import SUBAGENT_ONLY_BRAIN_PROVIDERS
+
+ ids = [row.id for row in PROVIDER_ROWS]
+ assert ids, "the picker needs rows"
+ offered = sorted(set(ids) & SUBAGENT_ONLY_BRAIN_PROVIDERS)
+ assert not offered, f"a subagent-only provider is offered as a brain: {offered}"
+ assert all(row.runner == "brain" for row in PROVIDER_ROWS)
+
claude = provider_row("claude-api")
- assert claude is not None and claude.runner == "claude-cli"
+ assert claude is not None, "an Anthropic key is a brain and stays offered"
d = claude.to_dict()
assert d["effort_levels"] == ["low", "medium", "high", "xhigh", "max"]
- assert d["curated_models"], "CLI-backed rows need a curated list"
+ assert d["curated_models"], "a curated row needs its 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") == ""
+
+
# ----------------------------------------------------------------- store
diff --git a/tests/unit/agent_chat/test_agent_chat_ladders.py b/tests/unit/agent_chat/test_agent_chat_ladders.py
index 95074ac0a7..a70dd703a1 100644
--- a/tests/unit/agent_chat/test_agent_chat_ladders.py
+++ b/tests/unit/agent_chat/test_agent_chat_ladders.py
@@ -9,6 +9,7 @@ import pytest
from jarvis.agent_chat import permissions, runner_cli
from jarvis.agent_chat.catalog import CODEX_FALLBACK_MODELS, provider_row
+from jarvis.agent_chat.effort import effort_levels
from jarvis.agent_chat.runner_cli import (
_AgyState,
agy_model_args,
@@ -392,19 +393,17 @@ 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_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"
+def test_the_coding_clis_are_not_offered_as_brains():
+ """Codex / Antigravity / Grok Build left the picker with the runner swap.
+
+ They are sub-agents: an agent loop on a subscription seat, with no chat API
+ to think with. Their per-model effort ladders still live in effort.py for
+ the sub-agent paths that DO drive them.
+ """
+ for cli in ("antigravity", "openai-codex", "grok-build"):
+ assert provider_row(cli) is None, f"{cli} is offered as a brain"
+ # The ladders themselves are untouched — the IDE and the missions read them.
+ assert "low" in effort_levels("antigravity")
# ------------------------------------------------------------ Anthropic API effort
diff --git a/tests/unit/agent_chat/test_agent_chat_service.py b/tests/unit/agent_chat/test_agent_chat_service.py
index 613cb24951..1d597d5541 100644
--- a/tests/unit/agent_chat/test_agent_chat_service.py
+++ b/tests/unit/agent_chat/test_agent_chat_service.py
@@ -1,9 +1,16 @@
-"""Agent chat — a whole turn through the service and the routes with a fake brain."""
+"""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.
+"""
from __future__ import annotations
import asyncio
-from collections.abc import AsyncIterator
from pathlib import Path
from typing import Any
@@ -11,180 +18,159 @@ import pytest
from fastapi import FastAPI
from fastapi.testclient import TestClient
-from jarvis.agent_chat import runner_api
from jarvis.agent_chat.service import AgentChatService, SessionBusy
from jarvis.agent_chat.store import AgentChatStore
-from jarvis.core.protocols import BrainDelta, BrainRequest
+from jarvis.core import runtime_refs
from jarvis.ui.web.agent_chat_routes import router
-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] = []
+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
@pytest.fixture
-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
+def brain(monkeypatch: pytest.MonkeyPatch) -> FakeBrain:
+ fake = FakeBrain()
+ monkeypatch.setattr(runtime_refs, "get_brain_manager", lambda: fake)
+ return fake
-async def _drain(q: asyncio.Queue, until_kind: str, timeout: float = 5.0) -> list[dict[str, Any]]:
+async def _drain(
+ q: asyncio.Queue, until_kind: str, budget_s: float = 5.0
+) -> list[dict[str, Any]]:
out: list[dict[str, Any]] = []
loop = asyncio.get_running_loop()
- deadline = loop.time() + timeout
+ deadline = loop.time() + budget_s
while True:
remaining = deadline - loop.time()
if remaining <= 0:
- raise AssertionError(f"timed out waiting for {until_kind}; got {[e['kind'] for e in out]}")
+ seen = [e['kind'] for e in out]
+ raise AssertionError(f"timed out waiting for {until_kind}; got {seen}")
ev = await asyncio.wait_for(q.get(), timeout=remaining)
out.append(ev)
if ev["kind"] == until_kind:
return out
-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")],
- ]
-
+def test_a_typed_turn_runs_on_the_brain_with_the_picked_model(tmp_path: Path, brain: FakeBrain):
async def scenario() -> None:
store = AgentChatStore(":memory:")
svc = AgentChatService(store, assistant_name=lambda: "Testo")
- session = svc.create_session(provider="fakeprov", model="m", effort="high", cwd=str(tmp_path))
+ session = svc.create_session(provider="grok", model="grok-4.3", cwd=str(tmp_path))
q = svc.subscribe(session.session_id)
- turn_id = await svc.send(session.session_id, "please write hello.txt")
+ turn_id = await svc.send(session.session_id, "was steht heute an")
with pytest.raises(SessionBusy):
await svc.send(session.session_id, "again")
- events = await _drain(q, "approval_required")
+ events = await _drain(q, "turn_finished")
kinds = [e["kind"] for e in events]
assert kinds[:2] == ["user_message", "turn_started"]
- 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 "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 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 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.system
+ 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 not svc.is_running(session.session_id)
asyncio.run(scenario())
-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")],
- ]
+def test_a_coding_subagent_cannot_answer_here_and_says_so(tmp_path: Path, brain: FakeBrain):
+ """A sub-agent pick is refused with a sentence, not a silent wrong answer."""
async def scenario() -> None:
svc = AgentChatService(AgentChatStore(":memory:"))
- session = svc.create_session(provider="fakeprov", cwd=str(tmp_path))
+ # The catalog no longer offers one, so build the session past it: what
+ # is pinned here is the runner's own guard, the last line of defence.
+ session = svc.create_session(provider="grok", cwd=str(tmp_path))
+ svc.store.update_session(session.session_id, provider="antigravity")
q = svc.subscribe(session.session_id)
- 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")
+ await svc.send(session.session_id, "hi")
events = await _drain(q, "turn_finished")
- 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]
+ finished = events[-1]["payload"]
+ assert finished["status"] == "done"
+ assert "coding sub-agent" in (finished["error"] or "")
+ assert brain.switched == [], "a sub-agent must never become the brain"
asyncio.run(scenario())
-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"}})],
- ]
+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)
async def scenario() -> None:
svc = AgentChatService(AgentChatStore(":memory:"))
- session = svc.create_session(provider="fakeprov", cwd=str(tmp_path))
+ session = svc.create_session(provider="openai", cwd=str(tmp_path))
q = svc.subscribe(session.session_id)
- await svc.send(session.session_id, "go")
- await _drain(q, "approval_required")
- assert await svc.cancel(session.session_id)
+ await svc.send(session.session_id, "hi")
events = await _drain(q, "turn_finished")
- assert events[-1]["payload"]["status"] == "cancelled"
- assert not (tmp_path / "a").exists()
+ assert events[-1]["payload"]["status"] == "error"
+ assert "starting up" in events[-1]["payload"]["error"]
asyncio.run(scenario())
-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)
+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)
async def scenario() -> None:
svc = AgentChatService(AgentChatStore(":memory:"))
- session = svc.create_session(provider="boomprov", cwd=str(tmp_path))
+ session = svc.create_session(provider="openai", cwd=str(tmp_path))
q = svc.subscribe(session.session_id)
await svc.send(session.session_id, "hi")
events = await _drain(q, "turn_finished")
@@ -194,6 +180,26 @@ def test_provider_error_is_reported_not_raised(tmp_path: Path, monkeypatch: pyte
asyncio.run(scenario())
+def test_cancel_ends_the_turn(tmp_path: Path, monkeypatch: pytest.MonkeyPatch):
+ fake = FakeBrain()
+
+ 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))
+ 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)
+ events = await _drain(q, "turn_finished")
+ assert events[-1]["payload"]["status"] in {"cancelled", "done"}
+
+ asyncio.run(scenario())
+
+
# ------------------------------------------------------------------ routes
@@ -207,8 +213,7 @@ def _app(tmp_path: Path) -> FastAPI:
return app
-def test_routes_catalog_sessions_and_websocket_snapshot(tmp_path: Path, scripted):
- ScriptedBrain.script = [[BrainDelta(content="hello from fake")]]
+def test_routes_catalog_sessions_and_websocket_snapshot(tmp_path: Path, brain: FakeBrain):
# 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.
@@ -217,26 +222,31 @@ def test_routes_catalog_sessions_and_websocket_snapshot(tmp_path: Path, scripted
def _exercise_routes(client: TestClient, tmp_path: Path) -> None:
-
cat = client.get("/api/agent-chat/catalog").json()
ids = [p["id"] for p in cat["providers"]]
- assert "claude-api" in ids and "openai" in ids and "openai-codex" in ids
+ assert "claude-api" in ids and "openai" in ids
+ # The subscription coding CLIs are not brains and are not offered.
+ assert "openai-codex" not in ids and "antigravity" not in ids
claude = 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": "fakeprov", "model": "m", "effort": "xhigh"},
+ json={"provider": "openai", "model": "gpt-5.5", "effort": "xhigh"},
)
assert created.status_code == 201, created.text
sid = created.json()["session_id"]
assert created.json()["cwd"] == str(tmp_path)
- bad = client.post("/api/agent-chat/sessions", json={"provider": "fakeprov", "cwd": "/no/such/dir"})
+ bad = client.post(
+ "/api/agent-chat/sessions", json={"provider": "openai", "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: