Skip to content

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

fix(agents): honor native Claude login on activation

Personal Jarvis Maintainerc50e8a900d4c
diff --git a/docs/commands-reference.md b/docs/commands-reference.md
index 8ace0efadf..2d58a12037 100644
--- a/docs/commands-reference.md
+++ b/docs/commands-reference.md
@@ -61,9 +61,9 @@ Switch the dedicated Computer-Use planner provider (screen control), decoupled f
- **Desktop UI section:** `apikeys`
- **Voice example (EN):** "switch the computer use provider to gemini"
-## `jarvis-agent-switch` — Switch Jarvis-Agent (worker) provider
+## `jarvis-agent-switch` — Switch mission-worker provider
-Switch the Jarvis-Agent / worker provider used for missions (e.g. codex to openai). Restart required.
+Switch the provider used for new missions (e.g. codex to openai). The next mission uses the new provider.
- **Endpoint:** `POST /api/jarvis-agent/switch`
- **Arguments:** `provider` (one of: antigravity, claude-api, codex, gemini, grok, nvidia, openai, openrouter; required); `persist` (boolean; optional)
diff --git a/docs/jarvis-cli-reference.md b/docs/jarvis-cli-reference.md
index 65548e1d51..eabb4e2e91 100644
--- a/docs/jarvis-cli-reference.md
+++ b/docs/jarvis-cli-reference.md
@@ -20,10 +20,10 @@ _Generated from the curated command tree by `scripts/ci/gen_cli_reference.py`
## brain
-- `jarvis brain deep-model <model> --persist --yes --dry-run` — Set the sub-agent deep model.
+- `jarvis brain deep-model <model> --persist --yes --dry-run` — Set the mission worker's deep model.
- `jarvis brain list` — List configured brain providers (alias of status).
- `jarvis brain status` — Show configured providers and which one is active.
-- `jarvis brain subagent-switch <provider> --persist --yes --dry-run` — Switch the sub-agent / worker provider (e.g. Codex -> OpenAI).
+- `jarvis brain subagent-switch <provider> --persist --yes --dry-run` — Switch the mission-worker provider (e.g. Codex -> OpenAI).
- `jarvis brain switch <provider> --persist --yes --dry-run` — Switch the ACTIVE main brain provider (e.g. `jarvis brain switch openai`).
- `jarvis brain test <provider> --dry-run` — Test connectivity + auth for a provider.
diff --git a/jarvis/brain/app_control.py b/jarvis/brain/app_control.py
index bdcc6f3573..e4cb9b0dc6 100644
--- a/jarvis/brain/app_control.py
+++ b/jarvis/brain/app_control.py
@@ -34,6 +34,7 @@ layer (``provider_routes``) imports *down* into this module — never the revers
"""
from __future__ import annotations
+import asyncio
import logging
from typing import TYPE_CHECKING, Any
@@ -59,9 +60,9 @@ def get_spec(provider_id: str) -> Any:
"""Provider spec by id, or ``None`` (thin wrapper over the lazy catalog)."""
return _catalog().get_spec(provider_id)
-# The tiers a provider switch can target. ``brain`` and ``tts`` apply live (no
-# restart); ``stt`` and ``subagent`` are wired once at bootstrap and need a
-# restart to take effect.
+# The tiers a provider switch can target. ``brain`` and ``tts`` apply live;
+# Jarvis-Agent workers re-resolve their provider before each mission. STT is
+# wired once at bootstrap and still needs a restart.
SWITCHABLE_TIERS: frozenset[str] = frozenset({"brain", "tts", "stt", "subagent"})
# Local providers allowed to stay active in the airgapped privacy profile.
@@ -603,7 +604,11 @@ async def _switch_subagent(
try:
from jarvis.codex_auth import CodexAuthService
- codex_status = CodexAuthService().status()
+ codex_cfg = getattr(cfg, "codex", None)
+ binary_path = getattr(codex_cfg, "binary_path", "") or None
+ codex_status = await asyncio.to_thread(
+ CodexAuthService(binary_path).status
+ )
codex_connected = codex_status.connected
except Exception: # noqa: BLE001 — codex CLI absent is just "not connected"
codex_status = None
@@ -628,26 +633,15 @@ async def _switch_subagent(
"error_kind": "missing_credential",
"error": (
"Codex is not connected — run 'codex login' or save an OpenAI "
- "API key first, then switch the subagent."
+ f"API key first, then switch the {brand}."
),
}
- persisted = (
- _persist(
- lambda: _import_writer().set_worker_provider(CODEX_SUBAGENT_CANONICAL)
- )
- if persist
- else False
+ return _complete_agent_switch(
+ CODEX_SUBAGENT_CANONICAL,
+ cfg=cfg,
+ persist=persist,
+ old=old,
)
- _set_in_memory(cfg, ["brain", "worker", "provider"], CODEX_SUBAGENT_CANONICAL)
- return {
- "ok": True,
- "tier": "subagent",
- "old_provider": old,
- "new_provider": CODEX_SUBAGENT_CANONICAL,
- "persisted": persisted,
- "applied_live": False,
- "requires_restart": True,
- }
if canon in ANTIGRAVITY_SUBAGENT_SLUGS:
antigravity_status = None
@@ -657,7 +651,9 @@ async def _switch_subagent(
antigravity_provider_ready,
)
- antigravity_status = GoogleCliAuthService().status()
+ antigravity_status = await asyncio.to_thread(
+ GoogleCliAuthService().status
+ )
except Exception as exc: # noqa: BLE001 — absent CLI is a normal capability miss
log.debug("Antigravity CLI readiness probe failed: %s", exc)
has_key = bool(cfg_mod.get_jarvis_agent_secret("gemini"))
@@ -681,30 +677,15 @@ async def _switch_subagent(
"error": (
"Antigravity is not connected — sign in with Google "
"(install agy or the Gemini CLI and log in) or save a "
- f"{brand} Gemini key, then switch the Agent."
+ f"{brand} Gemini key, then switch the {brand}."
),
}
- persisted = (
- _persist(
- lambda: _import_writer().set_worker_provider(
- ANTIGRAVITY_SUBAGENT_CANONICAL
- )
- )
- if persist
- else False
- )
- _set_in_memory(
- cfg, ["brain", "worker", "provider"], ANTIGRAVITY_SUBAGENT_CANONICAL
+ return _complete_agent_switch(
+ ANTIGRAVITY_SUBAGENT_CANONICAL,
+ cfg=cfg,
+ persist=persist,
+ old=old,
)
- return {
- "ok": True,
- "tier": "subagent",
- "old_provider": old,
- "new_provider": ANTIGRAVITY_SUBAGENT_CANONICAL,
- "persisted": persisted,
- "applied_live": False,
- "requires_restart": True,
- }
if canon not in JARVIS_TO_WORKER_SLUG:
# List EVERY worker-capable provider, not just the API/harness ones —
@@ -718,7 +699,10 @@ async def _switch_subagent(
return {
"ok": False,
"error_kind": "unknown_provider",
- "error": f"{provider!r} is not a subagent-capable provider. Available: {known}.",
+ "error": (
+ f"{provider!r} is not a {brand}-capable provider. "
+ f"Available: {known}."
+ ),
}
has_credential = bool(cfg_mod.get_jarvis_agent_secret(canon))
if canon == "claude-api" and not has_credential:
@@ -728,28 +712,63 @@ async def _switch_subagent(
has_credential = bool(read_live_claude_oauth_token())
except Exception: # noqa: BLE001
has_credential = False
+ if not has_credential:
+ try:
+ from jarvis.claude_auth import usable_native_claude_subscription
+
+ native_status = await asyncio.to_thread(
+ usable_native_claude_subscription
+ )
+ has_credential = native_status is not None
+ except Exception: # noqa: BLE001 — optional native CLI auth path
+ has_credential = False
if not has_credential:
return {
"ok": False,
"error_kind": "missing_credential",
"error": (
f"{canon} has no {brand} credential. Save a key on its "
- f"{brand} card first, then switch the Agent."
+ f"{brand} card first, then switch the {brand}."
),
}
+ return _complete_agent_switch(
+ canon,
+ cfg=cfg,
+ persist=persist,
+ old=old,
+ )
+
+
+def _complete_agent_switch(
+ provider: str, *, cfg: Any, persist: bool, old: str | None
+) -> dict[str, Any]:
+ """Persist and expose one validated Jarvis-Agent provider selection.
+
+ The mission factory re-reads the persisted provider before every new
+ mission, so a successful persisted switch is live without restarting the
+ app. An explicit non-persistent switch remains an in-memory preview only.
+ """
persisted = (
- _persist(lambda: _import_writer().set_worker_provider(canon)) if persist else False
+ _persist(lambda: _import_writer().set_worker_provider(provider))
+ if persist
+ else False
)
- _set_in_memory(cfg, ["brain", "worker", "provider"], canon)
+ if persist and not persisted:
+ return {
+ "ok": False,
+ "error_kind": "persist_failed",
+ "error": "The mission-worker provider could not be saved.",
+ }
+ _set_in_memory(cfg, ["brain", "worker", "provider"], provider)
return {
"ok": True,
"tier": "subagent",
"old_provider": old,
- "new_provider": canon,
+ "new_provider": provider,
"persisted": persisted,
- "applied_live": False,
- "requires_restart": True,
+ "applied_live": persisted,
+ "requires_restart": not persisted,
}
diff --git a/jarvis/cli_ctl/commands/brain.py b/jarvis/cli_ctl/commands/brain.py
index f8de334f4f..641f6dcabd 100644
--- a/jarvis/cli_ctl/commands/brain.py
+++ b/jarvis/cli_ctl/commands/brain.py
@@ -1,9 +1,9 @@
-"""brain: inspect and switch the active brain + sub-agent providers.
+"""brain: inspect and switch the active brain and mission-worker providers.
Flagship example: `jarvis brain switch openai` changes the active main brain
-provider; `jarvis brain subagent-switch openai` changes the worker/sub-agent
-provider (e.g. Codex -> OpenAI). Switches are reversible (config + live), so they
-proceed without --yes; pass --no-persist to apply live-only.
+provider; `jarvis brain subagent-switch openai` changes the mission-worker
+provider (for example, Codex to OpenAI). Switches are reversible, so they
+proceed without --yes; pass --no-persist to avoid writing the selection.
"""
from __future__ import annotations
@@ -13,7 +13,7 @@ from jarvis.cli_ctl import invoke, options
app = typer.Typer(
no_args_is_help=True,
- help="Brain providers: status, switch, sub-agent switch, models, test.",
+ help="Brain providers: status, switch, mission-worker switch, models, test.",
)
_PROVIDER_HELP = (
@@ -56,9 +56,9 @@ def subagent_switch(
yes: bool = options.yes_opt(),
dry_run: bool = options.dry_opt(),
) -> None:
- """Switch the sub-agent / worker provider (e.g. Codex -> OpenAI)."""
+ """Switch the mission-worker provider (e.g. Codex -> OpenAI)."""
invoke.run(
- "POST", "/api/subagent/switch",
+ "POST", "/api/jarvis-agent/switch",
body={"provider": provider, "persist": persist},
assume_yes=yes, dry_run=dry_run, dangerous=False,
)
@@ -80,9 +80,9 @@ def deep_model(
yes: bool = options.yes_opt(),
dry_run: bool = options.dry_opt(),
) -> None:
- """Set the sub-agent deep model."""
+ """Set the mission worker's deep model."""
invoke.run(
- "POST", "/api/subagent/model",
+ "POST", "/api/jarvis-agent/model",
body={"model": model, "persist": persist},
assume_yes=yes, dry_run=dry_run, dangerous=False,
)
diff --git a/jarvis/commands/registry.py b/jarvis/commands/registry.py
index 4e452923a4..a52cb5fc53 100644
--- a/jarvis/commands/registry.py
+++ b/jarvis/commands/registry.py
@@ -219,10 +219,10 @@ def _build_registry() -> tuple[AppCommand, ...]:
),
AppCommand(
id="jarvis-agent-switch",
- title="Switch Jarvis-Agent (worker) provider",
+ title="Switch mission-worker provider",
description=(
- "Switch the Jarvis-Agent / worker provider used for missions "
- "(e.g. codex to openai). Restart required."
+ "Switch the provider used for new missions (e.g. codex to "
+ "openai). The next mission uses the new provider."
),
method="POST",
path="/api/jarvis-agent/switch",
diff --git a/jarvis/ui/web/frontend/src/hooks/useProviders.ts b/jarvis/ui/web/frontend/src/hooks/useProviders.ts
index f46ea9ce85..435c7ef122 100644
--- a/jarvis/ui/web/frontend/src/hooks/useProviders.ts
+++ b/jarvis/ui/web/frontend/src/hooks/useProviders.ts
@@ -653,10 +653,10 @@ export async function switchComputerUseProvider(
/**
* Switches the active heavy-task WORKER provider
- * (`[brain.sub_jarvis].provider`). Persists across 3 layers
+ * (`[brain.worker].provider`; legacy config aliases remain readable). Persists across 3 layers
* (jarvis.toml + config-soll.json + ENV) so the drift guard doesn't roll (i18n-allow: "soll" is part of the config-soll.json filename)
- * back the switch. The worker reads the provider once at mission bootstrap,
- * so the backend sets `restart_required = true`.
+ * back the switch. The worker re-resolves the provider before every mission,
+ * so the next mission uses the selection without an app restart.
*/
export async function switchSubagentProvider(
providerId: string,
@@ -674,7 +674,7 @@ export async function switchSubagentProvider(
}
/**
- * Pins the dedicated subagent LLM model (`[brain.sub_jarvis].model`).
+ * Pins the dedicated mission-worker LLM model (`[brain.worker].model`).
* Empty string resets to the active subagent provider's deep model.
* 3-layer persisted server-side (drift-guard pinned key).
*/
@@ -1096,4 +1096,3 @@ export async function fetchRealtimeVoicePreview(opts: {
}
return await res.blob();
}
-
diff --git a/jarvis/ui/web/provider_routes.py b/jarvis/ui/web/provider_routes.py
index b991b792e9..2b3307d351 100644
--- a/jarvis/ui/web/provider_routes.py
+++ b/jarvis/ui/web/provider_routes.py
@@ -31,9 +31,6 @@ from jarvis.brain.model_catalog import ModelInfo, catalog_spec, classify_model
from jarvis.codex_auth import CodexAuthService
from jarvis.core import config as cfg_mod
from jarvis.core.events import SecretConfigured
-from jarvis.missions.worker_runtime.provider_map import (
- CODEX_SUBAGENT_CANONICAL as _CODEX_SUBAGENT_CANONICAL,
-)
from jarvis.missions.worker_runtime.provider_map import (
CODEX_SUBAGENT_SLUGS as _CODEX_SUBAGENT_SLUGS,
)
@@ -547,33 +544,11 @@ def _codex_binary_path(request: Request | None = None) -> str | None:
return getattr(getattr(cfg, "codex", None), "binary_path", "") or None
-def _apply_worker_in_memory(request: Request, provider: str) -> None:
- """Best-effort in-memory update of ``cfg.brain.worker.provider``.
-
- So the next ``/jarvis-agent/status`` reflects the choice immediately (the
- worker itself only re-reads at restart). Frozen / detached cfg is not an error.
- """
- cfg = _resolve_cfg(request)
- if cfg is None or getattr(cfg, "brain", None) is None:
- return
- sub = getattr(cfg.brain, "worker", None)
- try:
- if sub is None:
- from jarvis.core.config import BrainTierConfig
-
- cfg.brain.worker = BrainTierConfig(provider=provider)
- else:
- sub.provider = provider
- except Exception as exc: # noqa: BLE001 — frozen models / detached cfg are not errors
- log.debug("In-memory worker.provider update skipped: %s", exc)
-
-
def _apply_worker_model_in_memory(request: Request, model: str) -> None:
"""Best-effort in-memory update of ``cfg.brain.worker.model``.
- Mirrors :func:`_apply_worker_in_memory`; a missing ``worker``
- block is created with the router primary as provider so the override is
- never silently dropped.
+ A missing ``worker`` block is created with the router primary as provider,
+ so the override is never silently dropped.
"""
cfg = _resolve_cfg(request)
if cfg is None or getattr(cfg, "brain", None) is None:
@@ -2271,7 +2246,9 @@ _SWITCH_ERROR_STATUS: dict[str, int] = {
"wrong_tier": 400,
"subagent_only": 409,
"missing_credential": 409,
+ "subagent_unavailable": 409,
"airgapped_locked": 403,
+ "persist_failed": 500,
"switch_failed": 500,
"switch_not_applied": 500,
}
@@ -2984,196 +2961,41 @@ async def computer_use_switch(body: SwitchBody, request: Request) -> dict[str, A
async def jarvis_agent_switch(body: SwitchBody, request: Request) -> dict[str, Any]:
"""Switch the active Jarvis-Agent provider.
- Jarvis-Agents handle heavy tasks separately from the lightweight router
- brain. The route validates worker-capable providers, requires an API key or
- OAuth token, persists all drift-guard layers, and updates the live config
- for immediate UI feedback. Legacy ``sub_jarvis`` identifiers below remain
- read-time compatibility aliases. A running worker factory is wired once at
- mission bootstrap, so existing missions require a voice or app restart.
+ Validation is delegated to ``app_control.apply_provider_switch``, the same
+ source used by voice and connected tools. This prevents an auth capability
+ recognized by the worker (for example a platform-native Claude login) from
+ being rejected by a stale route-local credential check. The mission factory
+ re-resolves the persisted provider before every new mission, so a successful
+ switch needs no app restart.
"""
- from jarvis.missions.worker_runtime.provider_map import (
- JARVIS_TO_WORKER_SLUG,
- canonical_worker_provider,
- )
-
- # Normalize (lower/strip + ``openclaw-claude`` -> ``claude-api``) so the
- # accepted set matches what the UI cards display.
- provider = canonical_worker_provider(body.provider) or ""
-
- # Codex is a DIRECT worker (CodexDirectWorker) with no worker-harness slug —
- # it is not in JARVIS_TO_WORKER_SLUG. Handle it explicitly: it can be backed by
- # the ChatGPT subscription (OAuth, ``codex login``) OR an OpenAI API key.
- if provider in _CODEX_SUBAGENT_SLUGS:
- def _codex_status(): # noqa: ANN202
- return CodexAuthService(_codex_binary_path(request)).status()
-
- codex_status = await asyncio.to_thread(_codex_status)
- codex_connected = bool(codex_status.connected)
- has_key = bool(
- cfg_mod.get_secret(
- "codex_openai_api_key", env_fallback="CODEX_OPENAI_API_KEY"
- )
- )
- if not codex_status.installed:
- raise HTTPException(
- status_code=409,
- detail=(
- "Codex CLI is not installed. Install it or choose the OpenAI "
- "Jarvis-Agent card for key-only, in-process execution."
- ),
- )
- if not (codex_connected or has_key):
- raise HTTPException(
- status_code=409,
- detail=(
- "Codex is not connected — run 'codex login' (ChatGPT) or save "
- "an OpenAI API key first, then activate."
- ),
- )
- persisted = False
- if body.persist:
- try:
- from jarvis.core.config_writer import set_worker_provider
-
- set_worker_provider(_CODEX_SUBAGENT_CANONICAL)
- persisted = True
- except FileNotFoundError as exc:
- raise HTTPException(status_code=500, detail=str(exc)) from exc
- except Exception as exc: # noqa: BLE001
- raise HTTPException(
- status_code=500, detail=f"TOML write failed: {exc}"
- ) from exc
- _apply_worker_in_memory(request, _CODEX_SUBAGENT_CANONICAL)
- await _emit(request, SecretConfigured(key="brain.worker.provider", action="set"))
- _invalidate_section_health_state(request)
- return {
- "ok": True,
- "active": _CODEX_SUBAGENT_CANONICAL,
- "persisted": persisted,
- "restart_required": True,
- }
+ from jarvis.brain.app_control import apply_provider_switch
- # Antigravity is a DIRECT worker over the Google CLI, with subscription OAuth
- # or API-key billing only after that CLI capability exists. Key-only execution
- # belongs to the separate Google Gemini provider.
- from jarvis.missions.worker_runtime.provider_map import (
- ANTIGRAVITY_SUBAGENT_CANONICAL,
- ANTIGRAVITY_SUBAGENT_SLUGS,
+ cfg = _resolve_cfg(request)
+ if cfg is None:
+ raise HTTPException(status_code=503, detail="Configuration is not ready.")
+ result = await apply_provider_switch(
+ "subagent",
+ body.provider,
+ cfg=cfg,
+ persist=body.persist,
)
-
- if provider in ANTIGRAVITY_SUBAGENT_SLUGS:
- from jarvis.google_cli.auth_service import (
- GoogleCliAuthService,
- antigravity_provider_ready,
- )
-
- # Dual billing (mirror of Codex): subscription OAuth or a Gemini API key,
- # but both paths stay gated on the local CLI provider being installed.
- antigravity_status = await asyncio.to_thread(GoogleCliAuthService().status)
- antigravity_key = bool(cfg_mod.get_jarvis_agent_secret("gemini"))
- if not antigravity_status.installed:
- raise HTTPException(
- status_code=409,
- detail=(
- "Antigravity is not installed — install agy or the Gemini "
- "CLI, or select the separate Google Gemini provider for "
- "key-only execution."
- ),
- )
- if not antigravity_provider_ready(
- antigravity_status,
- api_key_present=antigravity_key,
- ):
- raise HTTPException(
- status_code=409,
- detail=(
- "Antigravity is not connected — sign in with Google "
- "(install agy or the Gemini CLI and log in) or set a Gemini "
- "API key, then activate."
- ),
- )
- persisted = False
- if body.persist:
- try:
- from jarvis.core.config_writer import set_worker_provider
-
- set_worker_provider(ANTIGRAVITY_SUBAGENT_CANONICAL)
- persisted = True
- except FileNotFoundError as exc:
- raise HTTPException(status_code=500, detail=str(exc)) from exc
- except Exception as exc: # noqa: BLE001
- raise HTTPException(
- status_code=500, detail=f"TOML write failed: {exc}"
- ) from exc
- _apply_worker_in_memory(request, ANTIGRAVITY_SUBAGENT_CANONICAL)
- await _emit(request, SecretConfigured(key="brain.worker.provider", action="set"))
- _invalidate_section_health_state(request)
- return {
- "ok": True,
- "active": ANTIGRAVITY_SUBAGENT_CANONICAL,
- "persisted": persisted,
- "restart_required": True,
- }
-
- if provider not in JARVIS_TO_WORKER_SLUG:
- known = ", ".join(sorted(JARVIS_TO_WORKER_SLUG))
- raise HTTPException(
- status_code=404,
- detail=(
- f"'{body.provider}' is not a Jarvis-Agent-capable provider. "
- f"Available: {known}."
- ),
- )
-
- # Key-Check — a provider without a stored credential cannot be activated.
- # ``claude-api`` counts the live Claude Max OAuth login (read by the
- # ClaudeDirectWorker from ~/.claude/.credentials.json) as a credential, so a
- # fresh Claude-Max user who only ran `claude login` (no stored API key) can
- # still select it — mirrors the codex/antigravity OAuth branches above.
- has_credential = bool(cfg_mod.get_jarvis_agent_secret(provider))
- if not has_credential and provider == "claude-api":
- try:
- from jarvis.missions.isolation.env import read_live_claude_oauth_token
-
- has_credential = bool(read_live_claude_oauth_token())
- except Exception: # noqa: BLE001
- has_credential = False
- if not has_credential:
+ if not result.get("ok"):
raise HTTPException(
- status_code=409,
- detail=(
- f"{provider} has no stored credential. "
- "Add a key on its Jarvis-Agent card before activating it."
+ status_code=_SWITCH_ERROR_STATUS.get(
+ str(result.get("error_kind")), 500
),
+ detail=result.get("error") or "Agent provider switch failed.",
)
- # 3-layer persist. ``persisted`` reflects the ACTUAL disk outcome (AD-OE6).
- persisted = False
- if body.persist:
- try:
- from jarvis.core.config_writer import set_worker_provider
-
- set_worker_provider(provider)
- persisted = True
- except FileNotFoundError as exc:
- raise HTTPException(status_code=500, detail=str(exc)) from exc
- except Exception as exc: # noqa: BLE001
- raise HTTPException(
- status_code=500, detail=f"TOML write failed: {exc}"
- ) from exc
-
- # Best-effort in-memory update so the next /jarvis-agent/status reflects the
- # choice immediately (the worker itself only re-reads on restart).
- _apply_worker_in_memory(request, provider)
-
await _emit(request, SecretConfigured(key="brain.worker.provider", action="set"))
_invalidate_section_health_state(request)
return {
"ok": True,
- "active": provider,
- "persisted": persisted,
- "restart_required": True,
+ "active": result.get("new_provider", body.provider),
+ "persisted": bool(result.get("persisted")),
+ "old_provider": result.get("old_provider"),
+ "restart_required": bool(result.get("requires_restart")),
}
diff --git a/tests/integration/test_jarvis_agent_active_brain.py b/tests/integration/test_jarvis_agent_active_brain.py
index a40e26c86c..1b633462ff 100644
--- a/tests/integration/test_jarvis_agent_active_brain.py
+++ b/tests/integration/test_jarvis_agent_active_brain.py
@@ -104,10 +104,10 @@ def _client(cfg) -> TestClient:
return TestClient(WebServer(bus=EventBus(), cfg=cfg).app)
-def test_subagent_switch_persists_and_restart_required(
+def test_subagent_switch_persists_and_applies_to_next_mission(
monkeypatch: pytest.MonkeyPatch,
) -> None:
- """Switch to a key-present provider: 200, persisted, restart_required."""
+ """A persisted switch is live for the next mission without an app restart."""
import jarvis.core.config as cfg_mod
import jarvis.core.config_writer as config_writer
@@ -121,12 +121,15 @@ def test_subagent_switch_persists_and_restart_required(
cfg.brain.primary = "gemini"
cfg.brain.worker = BrainTierConfig(provider="claude-api", model="")
- resp = _client(cfg).post("/api/jarvis-agent/switch", json={"provider": "gemini", "persist": True})
+ resp = _client(cfg).post(
+ "/api/jarvis-agent/switch",
+ json={"provider": "gemini", "persist": True},
+ )
assert resp.status_code == 200, resp.text
body = resp.json()
assert body["active"] == "gemini"
assert body["persisted"] is True
- assert body["restart_required"] is True
+ assert body["restart_required"] is False
assert calls == ["gemini"], "set_worker_provider must be called with the new provider"
@@ -154,10 +157,10 @@ def test_subagent_switch_409_when_no_key(monkeypatch: pytest.MonkeyPatch) -> Non
assert persisted == [], "must not persist a provider that has no key"
-def test_realtime_only_key_does_not_unlock_jarvis_agent(
+def test_realtime_only_key_unlocks_same_family_jarvis_agent(
monkeypatch: pytest.MonkeyPatch,
) -> None:
- """A key saved on Realtime must remain invisible to Jarvis-Agents."""
+ """A user's only OpenAI key must keep the same-family Agent usable."""
import jarvis.core.config as cfg_mod
import jarvis.core.config_writer as config_writer
@@ -177,15 +180,8 @@ def test_realtime_only_key_does_not_unlock_jarvis_agent(
json={"provider": "openai", "persist": True},
)
- assert response.status_code == 409
- row = next(
- item
- for item in client.get("/api/jarvis-agent/status").json()["mapping"]
- if item["jarvis"] == "openai"
- )
- assert row["key_set"] is False
- assert row["dedicated_key_set"] is False
- assert row["credential_source"] == "none"
+ assert response.status_code == 200, response.text
+ assert response.json()["active"] == "openai"
def test_dedicated_jarvis_agent_key_unlocks_provider_without_brain_key(
@@ -458,6 +454,48 @@ def test_subagent_switch_accepts_claude_max_oauth(monkeypatch: pytest.MonkeyPatc
assert calls == ["claude-api"]
+def test_subagent_switch_accepts_native_claude_subscription(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """A platform-native Claude login is usable even without an exportable token.
+
+ Current Claude Code stores the subscription in the macOS Keychain. The CLI
+ can use that account through its customization-free safe mode, while no
+ ``~/.claude/.credentials.json`` bearer exists for Jarvis to copy.
+ """
+ import jarvis.core.config as cfg_mod
+ import jarvis.core.config_writer as config_writer
+ from jarvis.claude_auth import ClaudeAuthStatus
+
+ monkeypatch.setattr(cfg_mod, "get_provider_secret", lambda _p: None)
+ monkeypatch.setattr(
+ "jarvis.missions.isolation.env.read_live_claude_oauth_token",
+ lambda: None,
+ )
+ monkeypatch.setattr(
+ "jarvis.claude_auth.usable_native_claude_subscription",
+ lambda: ClaudeAuthStatus(
+ installed=True,
+ connected=True,
+ mode="subscription",
+ binary_path="/opt/claude",
+ ),
+ )
+ calls: list[str] = []
+ monkeypatch.setattr(config_writer, "set_worker_provider", calls.append)
+
+ cfg = load_config()
+ response = _client(cfg).post(
+ "/api/jarvis-agent/switch",
+ json={"provider": "claude-api", "persist": True},
+ )
+
+ assert response.status_code == 200, response.text
+ assert response.json()["active"] == "claude-api"
+ assert response.json()["restart_required"] is False
+ assert calls == ["claude-api"]
+
+
def test_subagent_switch_409_claude_api_no_key_no_oauth(
monkeypatch: pytest.MonkeyPatch,
) -> None:
@@ -468,6 +506,10 @@ def test_subagent_switch_409_claude_api_no_key_no_oauth(
monkeypatch.setattr(
"jarvis.missions.isolation.env.read_live_claude_oauth_token", lambda: None
)
+ monkeypatch.setattr(
+ "jarvis.claude_auth.usable_native_claude_subscription",
+ lambda: None,
+ )
persisted: list[str] = []
monkeypatch.setattr(config_writer, "set_worker_provider", lambda n: persisted.append(n))
diff --git a/tests/unit/cli_ctl/test_commands_brain.py b/tests/unit/cli_ctl/test_commands_brain.py
index d08529a8ed..7f22c16fc8 100644
--- a/tests/unit/cli_ctl/test_commands_brain.py
+++ b/tests/unit/cli_ctl/test_commands_brain.py
@@ -45,7 +45,7 @@ def test_switch_dry_run_sends_nothing(capture_api):
def test_subagent_switch(capture_api):
runner.invoke(app, ["brain", "subagent-switch", "openai"])
call = capture_api["calls"][-1]
- assert call["path"] == "/api/subagent/switch"
+ assert call["path"] == "/api/jarvis-agent/switch"
assert call["body"]["provider"] == "openai"
@@ -58,5 +58,5 @@ def test_test_provider(capture_api):
def test_deep_model(capture_api):
runner.invoke(app, ["brain", "deep-model", "some-model", "--no-persist"])
call = capture_api["calls"][-1]
- assert call["path"] == "/api/subagent/model"
+ assert call["path"] == "/api/jarvis-agent/model"
assert call["body"] == {"model": "some-model", "persist": False}
diff --git a/tests/unit/plugins/tool/test_app_control_tools.py b/tests/unit/plugins/tool/test_app_control_tools.py
index e38bafc20d..cab537cb90 100644
--- a/tests/unit/plugins/tool/test_app_control_tools.py
+++ b/tests/unit/plugins/tool/test_app_control_tools.py
@@ -269,6 +269,9 @@ async def test_switch_codex_allowed_as_subagent(monkeypatch, no_keys):
installed = True
class _FakeCodexAuthService:
+ def __init__(self, _binary_path=None):
+ pass
+
def status(self):
return _Status()
@@ -285,6 +288,38 @@ async def test_switch_codex_allowed_as_subagent(monkeypatch, no_keys):
assert cfg.brain.worker.provider == "openai-codex"
+async def test_switch_native_claude_subscription_allowed_as_agent(
+ monkeypatch, no_keys
+):
+ """The shared switch accepts native CLI auth when no bearer file exists."""
+ from jarvis.brain.app_control import apply_provider_switch
+ from jarvis.claude_auth import ClaudeAuthStatus
+
+ monkeypatch.setattr(
+ "jarvis.missions.isolation.env.read_live_claude_oauth_token",
+ lambda: None,
+ )
+ monkeypatch.setattr(
+ "jarvis.claude_auth.usable_native_claude_subscription",
+ lambda: ClaudeAuthStatus(
+ installed=True,
+ connected=True,
+ mode="subscription",
+ binary_path="/opt/claude",
+ ),
+ )
+
+ cfg = make_cfg(sub="gemini")
+ result = await apply_provider_switch(
+ "subagent", "claude-api", cfg=cfg, persist=False
+ )
+
+ assert result["ok"] is True
+ assert result["new_provider"] == "claude-api"
+ assert result["requires_restart"] is True
+ assert cfg.brain.worker.provider == "claude-api"
+
+
async def test_switch_unknown_tier(configured_keys):
from jarvis.brain.app_control import apply_provider_switch
diff --git a/tests/unit/web/test_brain_switch_unified_validation.py b/tests/unit/web/test_brain_switch_unified_validation.py
index 2cb4ebaf08..7ae272653b 100644
--- a/tests/unit/web/test_brain_switch_unified_validation.py
+++ b/tests/unit/web/test_brain_switch_unified_validation.py
@@ -1,7 +1,8 @@
-"""Guard: the REST /api/brain/switch route delegates to the ONE shared switch
-implementation (app_control.apply_provider_switch) instead of carrying its own
-parallel validation — the voice gate, brain tools, CLI, and UI must never
-drift apart again (AP-4 class).
+"""Guard: provider-switch REST routes delegate to one shared implementation.
+
+``app_control.apply_provider_switch`` is the validation source for the voice
+gate, brain tools, CLI, and UI. A route-local credential check can otherwise
+drift from the worker's real auth capabilities (AP-4 class).
"""
from __future__ import annotations
@@ -88,6 +89,44 @@ def test_shared_error_kind_maps_to_http_status(server, monkeypatch) -> None:
assert "not configured" in resp.json()["detail"]
+def test_jarvis_agent_route_calls_shared_apply_provider_switch(
+ server, monkeypatch
+) -> None:
+ seen: dict[str, object] = {}
+
+ async def fake_apply(tier, provider, *, cfg, persist=True, manager=None):
+ seen.update(tier=tier, provider=provider, persist=persist, cfg=cfg)
+ return {
+ "ok": True,
+ "tier": tier,
+ "old_provider": "openai-codex",
+ "new_provider": "claude-api",
+ "persisted": True,
+ "applied_live": True,
+ "requires_restart": False,
+ }
+
+ monkeypatch.setattr(
+ "jarvis.brain.app_control.apply_provider_switch", fake_apply
+ )
+
+ with TestClient(server.app) as client:
+ response = client.post(
+ "/api/jarvis-agent/switch",
+ json={"provider": "claude-api", "persist": True},
+ )
+
+ assert response.status_code == 200, response.text
+ assert response.json()["active"] == "claude-api"
+ assert response.json()["restart_required"] is False
+ assert seen == {
+ "tier": "subagent",
+ "provider": "claude-api",
+ "persist": True,
+ "cfg": server.cfg,
+ }
+
+
def test_airgapped_lock_now_lives_in_shared_logic(server) -> None:
"""The airgapped check moved INTO apply_provider_switch; the route must
surface it as 403 without any route-local profile logic."""