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(agent-chat): sessions carry a surface, and the Jarvis surface has one permission ladder

rubenluetke10-beep482120ee9a98
diff --git a/jarvis/agent_chat/catalog.py b/jarvis/agent_chat/catalog.py
index 924d69d864..cbd6bc3ffd 100644
--- a/jarvis/agent_chat/catalog.py
+++ b/jarvis/agent_chat/catalog.py
@@ -22,11 +22,18 @@ Two kinds of runner sit behind the rows:
Codex's ``models_cache.json``), else the curated fallback here — and
``""`` means "the CLI's default".
+``brain``
+ Jarvis' own harness — ``BrainManager.generate`` with a per-turn pick of
+ provider, model and effort (:mod:`jarvis.agent_chat.runner_brain`). Never
+ a row's static runner: the service chooses it for every ``api`` row on
+ the Jarvis surface (the front page's chat), where the typed turn is
+ Jarvis rather than a coding agent.
+
``claude-api`` is the one dual row: 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.
+does (the brain runner on the Jarvis surface). The route decides per request
+by probing; this module only carries the static shape.
Presentation data only — nothing here decides behaviour (AP-21); the rows
exist so the picker can show a provider before a key is typed.
@@ -40,7 +47,7 @@ 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"]
+Runner = Literal["api", "brain", "claude-cli", "codex-cli", "agy-cli", "grok-cli"]
@dataclass(frozen=True, slots=True)
diff --git a/jarvis/agent_chat/permissions.py b/jarvis/agent_chat/permissions.py
index 586874eeaf..248e386523 100644
--- a/jarvis/agent_chat/permissions.py
+++ b/jarvis/agent_chat/permissions.py
@@ -18,6 +18,16 @@ change nothing" (Claude Code's plan mode; a read-only sandbox on Codex; the
read-only tool set on the API runner). The composer draws it as the
Build | Plan switch next to the permission pill.
+The **Jarvis surface** (the front page's chat — Jarvis with a keyboard, see
+``jarvis.agent_chat.store.SURFACES``) shows ONE ladder whatever answers:
+``ask`` / ``accept-edits`` / ``bypass`` plus ``plan``, the three stances
+Claude Code's own modes express, in Claude Code's words (maintainer,
+2026-08-25). A CLI seat folds them onto its vendor spelling through
+:func:`normalize_permission`; the brain runner reads them as stances (see
+``jarvis.agent_chat.approval_bridge``). ``bypass`` never overrides the
+blacklist — ``RiskTierEvaluator.evaluate`` raises for a blacklisted call
+before any approval logic runs, in every stance.
+
Single source of truth: the frontend receives the ladders through
``GET /api/agent-chat/catalog`` and never mirrors them (AP-4).
"""
@@ -178,13 +188,43 @@ _API: Final[tuple[PermissionMode, ...]] = (
),
)
-# runner -> (ladder, default)
+_JARVIS: Final[tuple[PermissionMode, ...]] = (
+ PermissionMode(
+ "ask",
+ "Ask before acting",
+ "Reads run freely; edits, shell commands and Jarvis' consequential actions "
+ "show an approval card here in the chat before they run.",
+ ),
+ PermissionMode(
+ "accept-edits",
+ "Auto-accept edits",
+ "File writes and edits in the working folder run without asking; shell "
+ "commands and consequential actions still ask.",
+ ),
+ PermissionMode(
+ "plan",
+ "Plan",
+ "Read and plan only — nothing is changed.",
+ ),
+ PermissionMode(
+ "bypass",
+ "Bypass permissions",
+ "Nothing asks. Blacklisted actions stay blocked.",
+ ),
+)
+
+#: The ladder key of the Jarvis surface — not a runner, but the one word the
+#: front page's composer shows whichever runner answers.
+JARVIS_LADDER: Final[str] = "jarvis"
+
+# runner (or JARVIS_LADDER) -> (ladder, default)
_LADDERS: Final[dict[str, tuple[tuple[PermissionMode, ...], str]]] = {
"claude-cli": (_CLAUDE, "acceptEdits"),
"codex-cli": (_CODEX, "auto"),
"agy-cli": (_AGY, "accept-edits"),
"grok-cli": (_GROK, "acceptEdits"),
"api": (_API, "ask"),
+ JARVIS_LADDER: (_JARVIS, "ask"),
}
# The universal stance ordering: every ladder is a sub-sequence of this once
@@ -205,6 +245,7 @@ _STANCE: Final[dict[str, int]] = {
"full-access": 3,
"bypassPermissions": 3,
"skip-permissions": 3,
+ "bypass": 3,
}
@@ -218,8 +259,20 @@ def _stance(runner: str, mode: str) -> int:
return _STANCE.get(mode, 1)
+def ladder_key(surface: str, runner: str) -> str:
+ """Which ladder a session shows: the runner's own on the agent surface,
+ the one Jarvis ladder on the front page's chat."""
+ return JARVIS_LADDER if surface == "jarvis" else runner
+
+
+def stance_of(mode: str) -> int:
+ """The runner-independent stance of a mode: 0 reads only, 1 ask first,
+ 2 edits yes / commands ask, 3 everything. Unknown words count as "ask"."""
+ return _STANCE.get((mode or "").strip(), 1)
+
+
def permission_modes(runner: str) -> tuple[PermissionMode, ...]:
- """The ladder the composer offers for ``runner``."""
+ """The ladder the composer offers for ``runner`` (or the Jarvis ladder)."""
return _LADDERS.get(runner, _LADDERS["api"])[0]
@@ -267,10 +320,13 @@ def normalize_permission(runner: str, mode: str | None) -> str:
__all__ = [
+ "JARVIS_LADDER",
"PermissionMode",
"default_permission",
"is_permission_mode",
+ "ladder_key",
"normalize_permission",
"permission_ids",
"permission_modes",
+ "stance_of",
]
diff --git a/jarvis/agent_chat/service.py b/jarvis/agent_chat/service.py
index fdbce29041..7883c18f97 100644
--- a/jarvis/agent_chat/service.py
+++ b/jarvis/agent_chat/service.py
@@ -8,11 +8,13 @@ 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.
+The runner is picked per turn from the provider row AND the session's
+surface. On the agent surface a CLI-backed provider uses :mod:`runner_cli`,
+``claude-api`` uses the CLI when the ``claude`` binary is on PATH and the API
+otherwise, and everything else uses :mod:`runner_api`. On the Jarvis surface
+(the front page's chat) every API-key or local row runs on Jarvis' own brain
+instead (``brain``), and a CLI seat runs as Jarvis. The choice is recorded in
+``turn_started`` so the timeline can say what answered.
"""
from __future__ import annotations
@@ -28,10 +30,10 @@ from typing import Any
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.permissions import ladder_key, normalize_permission
from jarvis.agent_chat.runner_api import TurnHandle, run_api_turn, supports_api_runner
from jarvis.agent_chat.runner_cli import run_cli_turn, supports_cli_runner
-from jarvis.agent_chat.store import AgentChatSession, AgentChatStore
+from jarvis.agent_chat.store import DEFAULT_SURFACE, AgentChatSession, AgentChatStore
log = logging.getLogger(__name__)
@@ -47,21 +49,31 @@ class NoSuchSession(KeyError):
pass
-def resolve_runner(provider: str) -> str:
+def _claude_cli_installed() -> bool:
+ return bool(shutil.which("claude") or shutil.which("claude.cmd") or shutil.which("claude.exe"))
+
+
+def resolve_runner(provider: str, *, surface: str = "agent") -> str:
"""Which runner answers for ``provider`` on this machine, right now.
``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.
+ Anthropic API. Every other provider row names its runner outright.
+
+ On the Jarvis surface the API path is Jarvis' own brain (``brain``): the
+ same set of providers, driven by ``BrainManager.generate`` instead of the
+ coding agent's tool loop. The CLI seats keep their CLI runner there — a
+ subscription only pays for the vendor's own loop — and run as Jarvis
+ (see :mod:`jarvis.agent_chat.jarvis_harness`).
"""
+ api_runner = "brain" if surface == "jarvis" else "api"
row = provider_row(provider)
if row is None:
- return "api" if supports_api_runner(provider) else "unknown"
+ return api_runner 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 "claude-cli" if _claude_cli_installed() else api_runner
+ if row.runner == "api":
+ return api_runner
return row.runner
@@ -89,6 +101,12 @@ class AgentChatService:
self._subscribers: dict[str, set[Subscriber]] = {}
self._approvals: dict[str, asyncio.Future[str]] = {}
self._approval_session: dict[str, str] = {}
+ # "Always allow" on the Jarvis surface: the tools a person waved through
+ # for the rest of the session, per session. Claude Code's "don't ask
+ # again for this tool" rather than a mode flip — the unified ladder has
+ # no word for "auto" and flipping to bypass would silence every later
+ # card, a mail send included.
+ self._always_allowed: dict[str, set[str]] = {}
# ------------------------------------------------------------ sessions
@@ -104,11 +122,13 @@ class AgentChatService:
cwd: str | None = None,
permission_mode: str = "",
title: str = "",
+ surface: str = DEFAULT_SURFACE,
) -> AgentChatSession:
row = provider_row(provider)
if row is None and not supports_api_runner(provider):
raise ValueError(f"Unknown agent-chat provider: {provider!r}")
- permission_mode = normalize_permission(resolve_runner(provider), permission_mode)
+ ladder = ladder_key(surface, resolve_runner(provider, surface=surface))
+ permission_mode = normalize_permission(ladder, permission_mode)
eff = normalize_effort(provider, effort) if effort is not None else ""
if effort is None:
from jarvis.agent_chat.effort import default_effort
@@ -121,6 +141,7 @@ class AgentChatService:
cwd=cwd or self.default_cwd(),
permission_mode=permission_mode,
title=title,
+ surface=surface,
)
def is_running(self, session_id: str) -> bool:
@@ -176,7 +197,7 @@ class AgentChatService:
history = self.store.list_events(session_id)
await self._emit(session_id, make_event("user_message", {"text": text}))
- runner = resolve_runner(session.provider)
+ runner = resolve_runner(session.provider, surface=session.surface)
await self._emit(
session_id,
make_event(
@@ -187,6 +208,7 @@ class AgentChatService:
"model": session.model,
"effort": normalize_effort(session.provider, session.effort),
"runner": runner,
+ "surface": session.surface,
},
),
)
@@ -333,10 +355,20 @@ class AgentChatService:
),
)
if decision == "allow_always":
- self.store.update_session(session_id, permission_mode="auto")
- await self._emit(session_id, make_event("session_updated", {"permission_mode": "auto"}))
+ session = self.store.get_session(session_id)
+ if session is not None and session.surface == "jarvis":
+ self._always_allowed.setdefault(session_id, set()).add(name)
+ else:
+ self.store.update_session(session_id, permission_mode="auto")
+ await self._emit(
+ session_id, make_event("session_updated", {"permission_mode": "auto"})
+ )
return decision
+ def always_allowed(self, session_id: str) -> set[str]:
+ """The tools waved through with "always allow" in this session (Jarvis surface)."""
+ return self._always_allowed.setdefault(session_id, set())
+
def resolve_approval(self, session_id: str, approval_id: str, decision: str) -> bool:
if decision not in DECISIONS:
raise ValueError(f"decision must be one of {DECISIONS}")
diff --git a/jarvis/agent_chat/store.py b/jarvis/agent_chat/store.py
index 44b6ca3d5f..df7f73d373 100644
--- a/jarvis/agent_chat/store.py
+++ b/jarvis/agent_chat/store.py
@@ -6,8 +6,9 @@ asyncio loop; the lock keeps a future worker-thread caller safe). Two tables:
``agent_chat_sessions``
One row per session — title, the provider / model / effort the composer
- last used in it, the working directory, the permission mode and, for the
- CLI runners, the vendor's own session id so a later turn can resume it.
+ last used in it, the working directory, the permission mode, the SURFACE
+ it belongs to (see :data:`SURFACES`) and, for the CLI runners, the
+ vendor's own session id so a later turn can resume it.
``agent_chat_events``
The append-only event log (see :mod:`jarvis.agent_chat.events`), ordered
@@ -25,7 +26,7 @@ import threading
import uuid
from dataclasses import asdict, dataclass
from pathlib import Path
-from typing import Any
+from typing import Any, Final
from jarvis.agent_chat.events import is_transient, now_ms
@@ -42,7 +43,8 @@ CREATE TABLE IF NOT EXISTS agent_chat_sessions (
created_ms INTEGER NOT NULL,
updated_ms INTEGER NOT NULL,
message_count INTEGER NOT NULL DEFAULT 0,
- preview TEXT NOT NULL DEFAULT ''
+ preview TEXT NOT NULL DEFAULT '',
+ surface TEXT NOT NULL DEFAULT 'agent'
);
CREATE TABLE IF NOT EXISTS agent_chat_events (
session_id TEXT NOT NULL,
@@ -61,6 +63,19 @@ _PREVIEW_MAX_CHARS = 120
# The permission ladders live in jarvis/agent_chat/permissions.py (per
# runner); the store keeps whatever id the route validated.
+#: Which chat a session belongs to. ``"jarvis"`` is the front page's chat —
+#: Jarvis with a keyboard: the same assistant the microphone talks to, on the
+#: model the composer picked for this chat. ``"agent"`` is a plain coding-agent
+#: session (a vendor CLI or the API tool loop in a folder), which is what the
+#: Agentic IDE's chat mode runs. Rows written before the column existed were
+#: coding sessions, so the column's default is ``"agent"``. The TypeScript twin
+#: is ``AgentChatSurface`` in ``src/lib/agentChatApi.ts`` and the Pydantic one
+#: ``CreateSessionBody.surface`` in ``jarvis/ui/web/agent_chat_routes.py`` —
+#: ``tests/unit/agent_chat/test_agent_chat_surface_parity.py`` keeps the three
+#: in step (AP-4).
+SURFACES: Final[tuple[str, ...]] = ("jarvis", "agent")
+DEFAULT_SURFACE: Final[str] = "agent"
+
@dataclass(slots=True)
class AgentChatSession:
@@ -76,6 +91,7 @@ class AgentChatSession:
updated_ms: int
message_count: int
preview: str
+ surface: str = DEFAULT_SURFACE
def to_dict(self) -> dict[str, Any]:
return asdict(self)
@@ -102,8 +118,26 @@ class AgentChatStore:
if self._path != ":memory:":
self._conn.execute("PRAGMA journal_mode=WAL")
self._conn.executescript(_SCHEMA)
+ self._migrate()
self._conn.commit()
+ def _migrate(self) -> None:
+ """Add columns a database from an older build lacks (same idiom as
+ ``jarvis/state/chat_store.py``). ``CREATE TABLE IF NOT EXISTS`` never
+ touches an existing table, so a column added to ``_SCHEMA`` reaches an
+ old file only through here."""
+ have = {
+ row["name"]
+ for row in self._conn.execute("PRAGMA table_info(agent_chat_sessions)").fetchall()
+ }
+ if "surface" not in have:
+ # Every row from before the column is a coding session: the chat
+ # surface was the agent chat back then (see SURFACES).
+ self._conn.execute(
+ "ALTER TABLE agent_chat_sessions ADD COLUMN surface TEXT NOT NULL "
+ f"DEFAULT '{DEFAULT_SURFACE}'"
+ )
+
def close(self) -> None:
with self._lock:
self._conn.close()
@@ -120,7 +154,10 @@ class AgentChatStore:
permission_mode: str = "",
title: str = "",
session_id: str | None = None,
+ surface: str = DEFAULT_SURFACE,
) -> AgentChatSession:
+ if surface not in SURFACES:
+ raise ValueError(f"surface must be one of {SURFACES}, not {surface!r}")
sid = session_id or uuid.uuid4().hex
now = now_ms()
# The route validated the mode against the runner's ladder; the store
@@ -130,8 +167,8 @@ class AgentChatStore:
self._conn.execute(
"INSERT INTO agent_chat_sessions (session_id, title, provider, model, effort, "
"cwd, permission_mode, vendor_session, created_ms, updated_ms, message_count, "
- "preview) VALUES (?, ?, ?, ?, ?, ?, ?, NULL, ?, ?, 0, '')",
- (sid, title, provider, model, effort, cwd, mode, now, now),
+ "preview, surface) VALUES (?, ?, ?, ?, ?, ?, ?, NULL, ?, ?, 0, '', ?)",
+ (sid, title, provider, model, effort, cwd, mode, now, now, surface),
)
self._conn.commit()
session = self.get_session(sid)
@@ -145,18 +182,29 @@ class AgentChatStore:
).fetchone()
return self._row_to_session(row) if row else None
- def list_sessions(self, limit: int = 200) -> list[AgentChatSession]:
+ def list_sessions(
+ self, limit: int = 200, *, surface: str | None = None
+ ) -> list[AgentChatSession]:
+ """Newest first; ``surface`` narrows the list to one chat's sessions."""
with self._lock:
- rows = self._conn.execute(
- "SELECT * FROM agent_chat_sessions ORDER BY updated_ms DESC LIMIT ?",
- (int(limit),),
- ).fetchall()
+ if surface is None:
+ rows = self._conn.execute(
+ "SELECT * FROM agent_chat_sessions ORDER BY updated_ms DESC LIMIT ?",
+ (int(limit),),
+ ).fetchall()
+ else:
+ rows = self._conn.execute(
+ "SELECT * FROM agent_chat_sessions WHERE surface = ? "
+ "ORDER BY updated_ms DESC LIMIT ?",
+ (surface, int(limit)),
+ ).fetchall()
return [self._row_to_session(r) for r in rows]
def update_session(self, session_id: str, **fields: Any) -> AgentChatSession | None:
"""Set any of title / provider / model / effort / cwd / permission_mode /
vendor_session. Unknown keys are ignored so a route can pass its body
- through after validation."""
+ through after validation. ``surface`` is deliberately NOT settable: a
+ session is born on one chat and stays there."""
allowed = {
"title",
"provider",
@@ -282,4 +330,5 @@ class AgentChatStore:
updated_ms=int(row["updated_ms"]),
message_count=int(row["message_count"]),
preview=row["preview"],
+ surface=str(row["surface"] or DEFAULT_SURFACE),
)
diff --git a/jarvis/ui/web/agent_chat_routes.py b/jarvis/ui/web/agent_chat_routes.py
index 867dace75b..0df75902a2 100644
--- a/jarvis/ui/web/agent_chat_routes.py
+++ b/jarvis/ui/web/agent_chat_routes.py
@@ -2,9 +2,10 @@
Prefix ``/api/agent-chat``:
- GET /catalog provider rows + effort + permission ladders
- GET /sessions newest first
- POST /sessions create (provider, model, effort, cwd, permission_mode)
+ GET /catalog?surface= provider rows + effort + permission ladders
+ GET /sessions?surface= newest first; ``surface`` narrows to one chat
+ POST /sessions create (provider, model, effort, cwd,
+ permission_mode, surface)
GET /sessions/{id} session + its persisted events
PATCH /sessions/{id} title/provider/model/effort/cwd/permission_mode
DELETE /sessions/{id}
@@ -26,7 +27,7 @@ import asyncio
import logging
import os
from pathlib import Path
-from typing import Any
+from typing import Any, Literal
from fastapi import APIRouter, HTTPException, Query, Request, WebSocket, WebSocketDisconnect
from pydantic import BaseModel, Field
@@ -37,6 +38,7 @@ from jarvis.agent_chat.events import make_event
from jarvis.agent_chat.permissions import (
default_permission,
is_permission_mode,
+ ladder_key,
normalize_permission,
permission_modes,
)
@@ -51,6 +53,10 @@ from jarvis.agent_chat.tools import shell_label
log = logging.getLogger(__name__)
+#: The Pydantic twin of ``jarvis.agent_chat.store.SURFACES`` (AP-4; the parity
+#: test in tests/unit/agent_chat/test_agent_chat_surface_parity.py pins it).
+SurfaceName = Literal["jarvis", "agent"]
+
router = APIRouter(prefix="/api/agent-chat", tags=["agent-chat"])
_WS_PING_S = 20.0
@@ -67,6 +73,9 @@ class CreateSessionBody(BaseModel):
#: "" = the runner's default mode (jarvis/agent_chat/permissions.py).
permission_mode: str = ""
title: str = ""
+ #: Which chat the session belongs to — the front page ("jarvis") or the
+ #: Agentic IDE's chat mode ("agent"). Fixed for the session's life.
+ surface: SurfaceName = "agent"
class PatchSessionBody(BaseModel):
@@ -176,23 +185,24 @@ def _validate_cwd(raw: str | None) -> str | None:
@router.get("/catalog")
-async def get_catalog(request: Request) -> dict[str, Any]:
+async def get_catalog(request: Request, surface: SurfaceName = "agent") -> dict[str, Any]:
"""Provider rows for the composer's picker.
Static shape from ``jarvis.agent_chat.catalog`` plus two live facts per
- row: which runner answers on this machine and whether that runner's
- binary is installed. Credential state is NOT repeated here — the
- picker reads it from ``/api/jarvis-agent/status`` like the Agents tab,
- so the two never disagree.
+ row: which runner answers on this machine (for ``surface``) and whether
+ that runner's binary is installed. Credential state is NOT repeated here
+ — the picker reads it from ``/api/jarvis-agent/status`` like the Agents
+ tab, so the two never disagree. On the Jarvis surface every row shows the
+ one Jarvis ladder (``permissions.JARVIS_LADDER``).
"""
svc = _service(request)
rows: list[dict[str, Any]] = []
live_models = await _live_cli_models()
for row in PROVIDER_ROWS:
d = row.to_dict()
- runner = resolve_runner(row.id)
+ runner = resolve_runner(row.id, surface=surface)
d["runner"] = runner
- d["cli_installed"] = _cli_installed(runner) if runner != "api" else None
+ d["cli_installed"] = _cli_installed(runner) if runner not in ("api", "brain") else None
# A CLI that publishes its own model list (agy, Codex) overrides the
# curated fallback with what THIS account can actually pick.
if d["cli_installed"] and runner in live_models and live_models[runner]:
@@ -207,9 +217,11 @@ async def get_catalog(request: Request) -> dict[str, Any]:
d["models_source"] = "live"
# The permission ladder is the RUNNER's (Claude Code's modes when the
# CLI answers, the API runner's when only a key is there), so the
- # composer shows the words the thing that runs actually understands.
- d["permission_modes"] = [m.to_dict() for m in permission_modes(runner)]
- d["default_permission_mode"] = default_permission(runner)
+ # composer shows the words the thing that runs actually understands —
+ # except on the Jarvis surface, where one ladder serves every seat.
+ ladder = ladder_key(surface, runner)
+ d["permission_modes"] = [m.to_dict() for m in permission_modes(ladder)]
+ d["default_permission_mode"] = default_permission(ladder)
rows.append(d)
return {
"providers": rows,
@@ -222,10 +234,14 @@ async def get_catalog(request: Request) -> dict[str, Any]:
@router.get("/sessions")
-async def list_sessions(request: Request, limit: int = Query(200, ge=1, le=1000)) -> dict[str, Any]:
+async def list_sessions(
+ request: Request,
+ limit: int = Query(200, ge=1, le=1000),
+ surface: SurfaceName | None = None,
+) -> dict[str, Any]:
svc = _service(request)
out = []
- for s in svc.store.list_sessions(limit=limit):
+ for s in svc.store.list_sessions(limit=limit, surface=surface):
d = s.to_dict()
d["running"] = svc.is_running(s.session_id)
out.append(d)
@@ -235,13 +251,13 @@ async def list_sessions(request: Request, limit: int = Query(200, ge=1, le=1000)
@router.post("/sessions", status_code=201)
async def create_session(body: CreateSessionBody, request: Request) -> dict[str, Any]:
svc = _service(request)
- runner = resolve_runner(body.provider)
- if body.permission_mode and not is_permission_mode(runner, body.permission_mode):
+ ladder = ladder_key(body.surface, resolve_runner(body.provider, surface=body.surface))
+ if body.permission_mode and not is_permission_mode(ladder, body.permission_mode):
raise HTTPException(
status_code=400,
detail=(
"permission_mode must be one of "
- + ", ".join(m.id for m in permission_modes(runner))
+ + ", ".join(m.id for m in permission_modes(ladder))
),
)
cwd = _validate_cwd(body.cwd)
@@ -251,8 +267,9 @@ async def create_session(body: CreateSessionBody, request: Request) -> dict[str,
model=body.model,
effort=body.effort,
cwd=cwd,
- permission_mode=normalize_permission(runner, body.permission_mode),
+ permission_mode=normalize_permission(ladder, body.permission_mode),
title=body.title,
+ surface=body.surface,
)
except ValueError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
@@ -296,20 +313,22 @@ async def patch_session(
fields["cwd"] = _validate_cwd(body.cwd) or svc.default_cwd()
current = svc.store.get_session(session_id)
assert current is not None
- runner = resolve_runner(fields.get("provider") or current.provider)
+ runner = resolve_runner(fields.get("provider") or current.provider, surface=current.surface)
+ ladder = ladder_key(current.surface, runner)
if body.permission_mode is not None:
- if not is_permission_mode(runner, body.permission_mode):
+ if not is_permission_mode(ladder, body.permission_mode):
raise HTTPException(
status_code=400,
detail=(
"permission_mode must be one of "
- + ", ".join(m.id for m in permission_modes(runner))
+ + ", ".join(m.id for m in permission_modes(ladder))
),
)
fields["permission_mode"] = body.permission_mode
elif "provider" in fields:
- # A provider change folds the old mode onto the new runner's ladder.
- fields["permission_mode"] = normalize_permission(runner, current.permission_mode)
+ # A provider change folds the old mode onto the new runner's ladder
+ # (a no-op on the Jarvis surface, whose ladder is the same for all).
+ fields["permission_mode"] = normalize_permission(ladder, current.permission_mode)
session = svc.store.update_session(session_id, **fields)
assert session is not None
changed = {k: v for k, v in fields.items() if k != "vendor_session"}
diff --git a/tests/unit/agent_chat/test_agent_chat_core.py b/tests/unit/agent_chat/test_agent_chat_core.py
index a7989df363..ff5aca12b5 100644
--- a/tests/unit/agent_chat/test_agent_chat_core.py
+++ b/tests/unit/agent_chat/test_agent_chat_core.py
@@ -444,3 +444,24 @@ def test_codex_reasoning_start_is_announced():
]
kinds = [ev["kind"] for obj in lines for ev in translate_codex_line(obj, st)]
assert kinds == ["reasoning_started", "reasoning"]
+
+
+# ---------------------------------------------------------------- runners
+
+
+def test_resolve_runner_per_surface(monkeypatch):
+ """The Jarvis surface runs API-key and local rows on the brain; CLI seats stay CLIs."""
+ from jarvis.agent_chat import service as svc_mod
+
+ monkeypatch.setattr(svc_mod, "_claude_cli_installed", lambda: False)
+ assert svc_mod.resolve_runner("openai") == "api"
+ assert svc_mod.resolve_runner("openai", surface="jarvis") == "brain"
+ assert svc_mod.resolve_runner("ollama", surface="jarvis") == "brain"
+ assert svc_mod.resolve_runner("openai-codex", surface="jarvis") == "codex-cli"
+ assert svc_mod.resolve_runner("antigravity", surface="jarvis") == "agy-cli"
+ assert svc_mod.resolve_runner("claude-api") == "api"
+ assert svc_mod.resolve_runner("claude-api", surface="jarvis") == "brain"
+ monkeypatch.setattr(svc_mod, "_claude_cli_installed", lambda: True)
+ assert svc_mod.resolve_runner("claude-api") == "claude-cli"
+ assert svc_mod.resolve_runner("claude-api", surface="jarvis") == "claude-cli"
+ assert svc_mod.resolve_runner("no-such-provider", surface="jarvis") == "unknown"
diff --git a/tests/unit/agent_chat/test_agent_chat_ladders.py b/tests/unit/agent_chat/test_agent_chat_ladders.py
index 95074ac0a7..48680db448 100644
--- a/tests/unit/agent_chat/test_agent_chat_ladders.py
+++ b/tests/unit/agent_chat/test_agent_chat_ladders.py
@@ -24,7 +24,7 @@ from jarvis.plugins.brain._anthropic_base import _is_reasoning_model, reasoning_
def test_every_runner_has_a_ladder_with_its_default_on_it():
- for runner in ("claude-cli", "codex-cli", "agy-cli", "grok-cli", "api"):
+ for runner in ("claude-cli", "codex-cli", "agy-cli", "grok-cli", "api", "jarvis"):
ids = permissions.permission_ids(runner)
assert ids, runner
assert permissions.default_permission(runner) in ids, runner
@@ -47,12 +47,37 @@ def test_every_runner_has_a_ladder_with_its_default_on_it():
("api", "acceptEdits", "accept-edits"),
("api", "", "ask"),
("api", "read-only", "plan"),
+ # The Jarvis ladder's words, folded onto every seat's own spelling.
+ ("claude-cli", "bypass", "bypassPermissions"),
+ ("claude-cli", "accept-edits", "acceptEdits"),
+ ("claude-cli", "ask", "default"),
+ ("codex-cli", "ask", "approve-for-me"),
+ ("codex-cli", "accept-edits", "auto"),
+ ("codex-cli", "bypass", "full-access"),
+ ("agy-cli", "bypass", "skip-permissions"),
+ ("agy-cli", "ask", "accept-edits"),
+ ("grok-cli", "accept-edits", "acceptEdits"),
+ ("grok-cli", "bypass", "bypassPermissions"),
+ ("jarvis", "", "ask"),
+ ("jarvis", "acceptEdits", "accept-edits"),
+ ("jarvis", "bypassPermissions", "bypass"),
+ ("jarvis", "plan", "plan"),
],
)
def test_normalize_permission_folds_across_runners(runner, picked, expected):
assert permissions.normalize_permission(runner, picked) == expected
+def test_the_jarvis_ladder_is_the_three_stances_and_plan():
+ assert permissions.permission_ids("jarvis") == ("ask", "accept-edits", "plan", "bypass")
+ assert permissions.ladder_key("jarvis", "claude-cli") == "jarvis"
+ assert permissions.ladder_key("jarvis", "brain") == "jarvis"
+ assert permissions.ladder_key("agent", "claude-cli") == "claude-cli"
+ stances = [permissions.stance_of(m) for m in ("plan", "ask", "accept-edits", "bypass")]
+ assert stances == [0, 1, 2, 3]
+ assert permissions.stance_of("nonsense") == 1
+
+
# ------------------------------------------------------------ planners
diff --git a/tests/unit/agent_chat/test_agent_chat_surface_parity.py b/tests/unit/agent_chat/test_agent_chat_surface_parity.py
new file mode 100644
index 0000000000..cc827c7519
--- /dev/null
+++ b/tests/unit/agent_chat/test_agent_chat_surface_parity.py
@@ -0,0 +1,95 @@
+"""The session's ``surface`` — one enum in three languages, and the migration.
+
+``"jarvis"`` is the front page's chat (Jarvis with a keyboard), ``"agent"`` a
+plain coding-agent session (the Agentic IDE's chat mode). The value crosses
+Python -> SQLite -> Pydantic -> TypeScript, so the four spellings are pinned
+against each other here (AP-4) instead of trusted to stay in step by hand.
+"""
+
+from __future__ import annotations
+
+import re
+import sqlite3
+from pathlib import Path
+from typing import get_args
+
+from jarvis.agent_chat import store as store_mod
+from jarvis.agent_chat.store import DEFAULT_SURFACE, SURFACES, AgentChatStore
+from jarvis.ui.web import agent_chat_routes
+
+_ROOT = Path(__file__).resolve().parents[3]
+_TS_API = _ROOT / "jarvis" / "ui" / "web" / "frontend" / "src" / "lib" / "agentChatApi.ts"
+
+
+def test_python_and_pydantic_spell_the_surface_the_same():
+ assert set(get_args(agent_chat_routes.SurfaceName)) == set(SURFACES)
+ body_field = agent_chat_routes.CreateSessionBody.model_fields["surface"]
+ assert set(get_args(body_field.annotation)) == set(SURFACES)
+ assert body_field.default == DEFAULT_SURFACE
+
+
+def test_typescript_spells_the_surface_the_same():
+ """The TS union is read off the file text: no build step, no node."""
+ if not _TS_API.is_file():
+ import pytest
+
+ pytest.skip("frontend sources not present")
+ text = _TS_API.read_text(encoding="utf-8")
+ match = re.search(r"export type AgentChatSurface\s*=\s*([^;]+);", text)
+ assert match, "agentChatApi.ts must export `AgentChatSurface`"
+ members = set(re.findall(r'"([a-z]+)"', match.group(1)))
+ assert members == set(SURFACES)
+
+
+def test_old_rows_read_as_agent_sessions(tmp_path: Path):
+ """A database from before the column: every row was a coding session."""
+ db = tmp_path / "agent_chat.db"
+ column = ",\n surface TEXT NOT NULL DEFAULT 'agent'"
+ old_schema = store_mod._SCHEMA.replace(column, "")
+ assert "surface" not in old_schema, "the old schema must not know the column"
+ conn = sqlite3.connect(db)
+ conn.executescript(old_schema)
+ conn.execute(
+ "INSERT INTO agent_chat_sessions (session_id, provider, created_ms, updated_ms) "
+ "VALUES ('old1', 'openai', 1, 1)"
+ )
+ conn.commit()
+ conn.close()
+
+ store = AgentChatStore(db)
+ old = store.get_session("old1")
+ assert old is not None and old.surface == "agent"
+ # And the migration is idempotent: reopening does not add the column twice.
+ store.close()
+ again = AgentChatStore(db)
+ assert again.get_session("old1") is not None
+ again.close()
+
+
+def test_the_store_lists_one_surface_at_a_time():
+ store = AgentChatStore(":memory:")
+ jarvis = store.create_session(
+ provider="openai", model="m", effort="", cwd=".", surface="jarvis"
+ )
+ agent = store.create_session(provider="openai", model="m", effort="", cwd=".")
+ assert agent.surface == "agent"
+ assert [s.session_id for s in store.list_sessions(surface="jarvis")] == [jarvis.session_id]
+ assert [s.session_id for s in store.list_sessions(surface="agent")] == [agent.session_id]
+ assert {s.session_id for s in store.list_sessions()} == {jarvis.session_id, agent.session_id}
+ assert jarvis.to_dict()["surface"] == "jarvis"
+
+
+def test_a_session_never_changes_its_surface():
+ store = AgentChatStore(":memory:")
+ s = store.create_session(provider="openai", model="m", effort="", cwd=".", surface="jarvis")
+ store.update_session(s.session_id, surface="agent", title="renamed")
+ after = store.get_session(s.session_id)
+ assert after is not None and after.surface == "jarvis" and after.title == "renamed"
+
+
+def test_an_unknown_surface_is_refused():
+ import pytest
+
+ store = AgentChatStore(":memory:")
+ with pytest.raises(ValueError):
+ store.create_session(provider="openai", model="m", effort="", cwd=".", surface="voice")