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.

refactor(providers): unify brain-switch validation behind apply_provider_switch

Ruben Lütkef47335f1fc8d
diff --git a/jarvis/brain/app_control.py b/jarvis/brain/app_control.py
index 55b4ddd922..50d0fc3d4f 100644
--- a/jarvis/brain/app_control.py
+++ b/jarvis/brain/app_control.py
@@ -64,6 +64,16 @@ def get_spec(provider_id: str) -> Any:
# restart to take effect.
SWITCHABLE_TIERS: frozenset[str] = frozenset({"brain", "tts", "stt", "subagent"})
+# Local providers allowed to stay active in the airgapped privacy profile.
+# Empty since v1.0.1: Ollama was removed 2026-04-21, and the local
+# "faster-whisper" STT dictation provider was removed from the user-selectable
+# catalog (see provider_spec.py). With no local provider left, the airgapped
+# profile admits no provider switch — an honest state, not a regression:
+# airgapped means "local only", and there is currently no local provider to
+# switch TO. (Wake still runs its own local Whisper off this list.) Lives HERE
+# (not in provider_routes) so every switch path shares the one lock.
+LOCAL_PROVIDERS: frozenset[str] = frozenset()
+
# Maps a provider id to the credential-manager *provider slot* used by
# ``cfg.get_provider_secret`` — needed where one key backs several provider ids
# (e.g. gemini + gemini-flash-tts share ``gemini_api_key``). Kept in sync with
@@ -363,6 +373,7 @@ async def apply_provider_switch(
*,
cfg: Any,
persist: bool = True,
+ manager: Any | None = None,
) -> dict[str, Any]:
"""Switch the active provider for ``tier`` to ``provider``.
@@ -372,6 +383,9 @@ async def apply_provider_switch(
Never sets a raw key — only flips which provider is active. The target
provider must already have a stored credential (checked up-front).
+
+ ``manager`` optionally pins the live BrainManager to switch (the REST
+ route passes its ``app.state.brain``); default is the runtime_refs lookup.
"""
tier = (tier or "").strip().lower()
provider = (provider or "").strip()
@@ -386,6 +400,21 @@ async def apply_provider_switch(
),
}
+ # Airgapped privacy profile admits only local providers. Enforced HERE so
+ # every switch path (voice gate, REST route, CLI, brain tool) hits the one
+ # lock — it used to live only in the REST route, so a voice-initiated
+ # switch could activate a cloud provider in privacy mode.
+ profile_name = getattr(getattr(cfg, "profile", None), "name", "default")
+ if profile_name == "airgapped" and provider not in LOCAL_PROVIDERS:
+ return {
+ "ok": False,
+ "error_kind": "airgapped_locked",
+ "error": (
+ "Privacy mode (airgapped profile) is active — only local "
+ "providers can be activated."
+ ),
+ }
+
old_provider = _current_provider(cfg, tier)
if tier == "subagent":
@@ -429,16 +458,20 @@ async def apply_provider_switch(
}
if tier == "brain":
- return await _switch_brain(provider, cfg=cfg, persist=persist, old=old_provider)
+ return await _switch_brain(
+ provider, cfg=cfg, persist=persist, old=old_provider, manager=manager
+ )
if tier == "tts":
return _switch_tts(provider, cfg=cfg, persist=persist, old=old_provider)
return _switch_stt(provider, cfg=cfg, persist=persist, old=old_provider)
async def _switch_brain(
- provider: str, *, cfg: Any, persist: bool, old: str | None
+ provider: str, *, cfg: Any, persist: bool, old: str | None,
+ manager: Any | None = None,
) -> dict[str, Any]:
- manager = runtime_refs.get_brain_manager()
+ if manager is None:
+ manager = runtime_refs.get_brain_manager()
persisted = False
applied_live = False
diff --git a/jarvis/ui/web/provider_routes.py b/jarvis/ui/web/provider_routes.py
index 02a118295f..ae2e7bde70 100644
--- a/jarvis/ui/web/provider_routes.py
+++ b/jarvis/ui/web/provider_routes.py
@@ -50,14 +50,9 @@ router = APIRouter(prefix="/api", tags=["providers"])
# Setup-Wizard deklarierten Slots.
ALLOWED_SECRET_KEYS: frozenset[str] = frozenset(s.key for s in WIZARD_SECRETS)
-# Local providers allowed to stay active in the airgapped privacy profile.
-# Empty since v1.0.1: Ollama was removed 2026-04-21, and the local
-# "faster-whisper" STT dictation provider was removed from the user-selectable
-# catalog (see provider_spec.py). With no local brain/STT provider left, the
-# airgapped profile admits no provider switch — an honest state, not a
-# regression: airgapped means "local only", and there is currently no local
-# provider to switch TO. (Wake still runs its own local Whisper off this list.)
-LOCAL_PROVIDERS: frozenset[str] = frozenset()
+# The airgapped local-provider allowlist (LOCAL_PROVIDERS) moved to
+# jarvis.brain.app_control: the lock is enforced inside apply_provider_switch
+# so voice, REST, CLI, and brain tools all share it.
# Codex subagent slugs (_CODEX_SUBAGENT_SLUGS / _CODEX_SUBAGENT_CANONICAL) are
# imported from jarvis.missions.worker_runtime.provider_map — the single source
@@ -237,24 +232,6 @@ class RealtimeOptionsSaveResponse(BaseModel):
# ----------------------------------------------------------------------
-def _persist_brain_primary_fallback(provider: str) -> bool:
- """Persist ``brain.primary`` directly when the manager's switch signature
- is too old to accept ``persist=`` (TypeError fallback path).
-
- Returns ``True`` iff the disk write succeeded. This exists so the legacy
- fallback never silently drops persistence: even when ``switch`` cannot
- persist, we still attempt the write here and report the honest outcome.
- """
- try:
- from jarvis.core import config_writer
-
- config_writer.set_brain_primary(provider)
- return True
- except Exception as exc: # noqa: BLE001
- log.error("Fallback persist of brain.primary=%r failed: %s", provider, exc)
- return False
-
-
def _is_credential_present(spec: ProviderSpec, binary_path: str | None = None) -> bool:
"""Heuristik je nach auth_mode.
@@ -1623,8 +1600,32 @@ async def delete_secret_value(key: str, request: Request) -> dict[str, Any]:
return {"ok": True, "key": key}
+# Maps apply_provider_switch error kinds to HTTP statuses. Route-level concern:
+# the shared switch logic in jarvis.brain.app_control stays transport-agnostic.
+_SWITCH_ERROR_STATUS: dict[str, int] = {
+ "unknown_tier": 400,
+ "unknown_provider": 404,
+ "wrong_tier": 400,
+ "subagent_only": 409,
+ "missing_credential": 409,
+ "airgapped_locked": 403,
+ "switch_failed": 500,
+ "switch_not_applied": 500,
+}
+
+
@router.post("/brain/switch")
async def brain_switch(body: SwitchBody, request: Request) -> dict[str, Any]:
+ """Switch the active main-brain provider.
+
+ Validation and the switch itself are delegated to the ONE shared
+ implementation (``app_control.apply_provider_switch``) that the voice
+ gate and the brain tools also use — the route only keeps checks that are
+ genuinely transport-specific (503 while the brain is still building, the
+ live plugin-registry 404, and the defensive Codex/Antigravity branches).
+ Previously the route carried its own parallel validation, which could
+ drift from the voice path's.
+ """
brain = getattr(request.app.state, "brain", None)
if brain is None or not hasattr(brain, "switch"):
# The brain is built on a background task after boot, so a very early
@@ -1641,27 +1642,8 @@ async def brain_switch(body: SwitchBody, request: Request) -> dict[str, Any]:
),
)
- spec = get_spec(body.provider)
- if spec is None:
- raise HTTPException(status_code=404, detail=f"Unbekannter Provider: {body.provider}")
- if spec.tier == "brain" and not spec.brain_switchable:
- raise HTTPException(
- status_code=409,
- detail=(
- f"{spec.label} is subagent-only in Jarvis. It cannot be used as "
- "the main Brain provider because it cannot see Computer-Use "
- "screenshots. Activate it in the Subagent section instead."
- ),
- )
-
- cfg = _resolve_cfg(request)
- profile_name = getattr(getattr(cfg, "profile", None), "name", "default")
- if profile_name == "airgapped" and body.provider not in LOCAL_PROVIDERS:
- raise HTTPException(
- status_code=403,
- detail="Privacy-Mode aktiv — nur lokale Provider erlaubt.",
- )
-
+ # Fast, specific 404 while the live registry is at hand — the shared logic
+ # would only surface an unloadable provider later as switch_not_applied.
available = []
if hasattr(brain, "available_providers"):
try:
@@ -1671,21 +1653,18 @@ async def brain_switch(body: SwitchBody, request: Request) -> dict[str, Any]:
if available and body.provider not in available:
raise HTTPException(
status_code=404,
- detail=f"Provider '{body.provider}' ist nicht im Plugin-Registry verfügbar",
+ detail=f"Provider '{body.provider}' is not available in the plugin registry",
)
- # Akzeptanzkriterium: Provider ohne gespeicherten Key duerfen nicht aktiviert
- # werden. Analog zu tts_switch/stt_switch — der Switch wuerde sonst
- # nominell gelingen, aber der erste Turn faellt mit "missing_key" und der
- # Provider landet in _dead_providers. Sauberer 409 statt stiller Fehler.
- # Reihenfolge: 404 (Provider unbekannt/nicht im Registry) kommt VOR
- # 409 (Provider bekannt, aber Credentials fehlen) — Identifiability vor
- # Konfiguration.
- #
- # Defensive legacy branch: Codex/Antigravity are rejected above as
- # ``brain_switchable=False``. If that guard is ever relaxed, keep credential
- # checks explicit instead of letting a switch succeed and fail on first turn.
- if spec.id == "codex":
+ # Defensive legacy branches: Codex/Antigravity are ``brain_switchable=False``
+ # and rejected by the shared validation below (as "subagent-only", which
+ # must stay the primary message). These credential checks are DORMANT until
+ # that guard is ever relaxed — then they keep a switch from succeeding
+ # nominally and failing on the first turn. Hence the brain_switchable gate.
+ spec = get_spec(body.provider)
+ if spec is not None and not getattr(spec, "brain_switchable", True):
+ pass # shared validation rejects with the canonical subagent-only 409
+ elif spec is not None and spec.id == "codex":
if not _codex_brain_usable():
raise HTTPException(
status_code=409,
@@ -1694,7 +1673,7 @@ async def brain_switch(body: SwitchBody, request: Request) -> dict[str, Any]:
"run 'codex login' (ChatGPT subscription, slower CLI path)."
),
)
- elif spec.id == "antigravity":
+ elif spec is not None and spec.id == "antigravity":
# OAuth-only: no API key. Gate on the Google CLI login being present,
# mirroring the codex branch (the CLI bills the Google subscription).
from jarvis.google_cli.auth_service import GoogleCliAuthService
@@ -1707,66 +1686,34 @@ async def brain_switch(body: SwitchBody, request: Request) -> dict[str, Any]:
"agy or the Gemini CLI and log in), then activate."
),
)
- elif not _is_credential_present(spec):
- raise HTTPException(
- status_code=409,
- detail=(
- f"{spec.label} hat keinen gespeicherten API-Key. "
- "Erst Key in der Karte speichern, dann aktivieren."
- ),
- )
- # ``persisted`` reflects the ACTUAL disk outcome, not the echoed request
- # flag — a failed write must surface as persisted=false so the UI knows the
- # choice will not survive a restart (anti-silent-drop, AD-OE6). We start
- # pessimistic and only flip to True when the manager confirms the write.
- persisted = False
- try:
- await brain.switch(body.provider, persist=body.persist)
- except TypeError:
- # Genuinely old switch signature without the persist kwarg. We must NOT
- # silently drop persistence: attempt the disk write directly here, and
- # if even that path is unavailable, report persisted=false so the UI is
- # honest about the outcome.
- await brain.switch(body.provider)
- if body.persist:
- persisted = _persist_brain_primary_fallback(body.provider)
- except Exception as exc: # noqa: BLE001
- log.exception("Brain-Switch zu '%s' fehlgeschlagen", body.provider)
- raise HTTPException(
- status_code=500,
- detail=f"Switch fehlgeschlagen: {type(exc).__name__}: {exc}",
- ) from exc
- else:
- # Normal path: read the real persist outcome the manager recorded.
- if body.persist:
- persisted = bool(getattr(brain, "last_persist_ok", False))
-
- # Switch-Validierung: BrainManager.switch() returnt silent bei einem
- # KeyError im Plugin-Registry. Wir lesen den Live-State zurueck und
- # propagieren einen Fehler, falls der Wechsel nicht angekommen ist —
- # sonst sieht das Frontend "200 OK" trotz No-Op und der User wundert
- # sich, warum die UI bei alt bleibt.
- actual = getattr(brain, "active_provider", None)
- if actual != body.provider:
- log.warning(
- "Brain-Switch silent failure: requested=%s, actual=%s",
- body.provider, actual,
- )
+ from jarvis.brain.app_control import apply_provider_switch
+
+ result = await apply_provider_switch(
+ "brain",
+ body.provider,
+ cfg=_resolve_cfg(request),
+ persist=body.persist,
+ manager=brain,
+ )
+ if not result.get("ok"):
raise HTTPException(
- status_code=500,
- detail=(
- f"Switch zu '{body.provider}' nicht angewendet "
- f"(aktuell: {actual!r}). Provider eventuell nicht ladbar."
- ),
+ status_code=_SWITCH_ERROR_STATUS.get(str(result.get("error_kind")), 500),
+ detail=result.get("error") or "Switch failed.",
)
- if body.persist and not persisted:
+ if body.persist and not result.get("persisted"):
log.warning(
- "Brain-Switch to '%s' applied live but persistence to disk FAILED — "
+ "Brain switch to '%s' applied live but persistence to disk FAILED — "
"the choice will not survive a restart.",
body.provider,
)
- return {"ok": True, "active": body.provider, "persisted": persisted}
+ return {
+ "ok": True,
+ "active": result.get("new_provider", body.provider),
+ "persisted": bool(result.get("persisted")),
+ "old_provider": result.get("old_provider"),
+ "requires_restart": bool(result.get("requires_restart")),
+ }
@router.post("/tts/switch")
diff --git a/tests/integration/test_provider_routes.py b/tests/integration/test_provider_routes.py
index 1be70c0067..8468fd673c 100644
--- a/tests/integration/test_provider_routes.py
+++ b/tests/integration/test_provider_routes.py
@@ -390,7 +390,8 @@ def test_brain_switch_rejects_provider_without_key(
with TestClient(server_with_brain.app) as client:
resp = client.post("/api/brain/switch", json={"provider": "openrouter"})
assert resp.status_code == 409
- assert "API-Key" in resp.json()["detail"]
+ # Shared app_control wording (one implementation for UI + voice + CLI).
+ assert "API key" in resp.json()["detail"]
# BrainManager.switch() must NOT have been called.
assert fake.calls == []
diff --git a/tests/unit/web/test_brain_switch_unified_validation.py b/tests/unit/web/test_brain_switch_unified_validation.py
new file mode 100644
index 0000000000..2cb4ebaf08
--- /dev/null
+++ b/tests/unit/web/test_brain_switch_unified_validation.py
@@ -0,0 +1,98 @@
+"""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).
+"""
+from __future__ import annotations
+
+from collections.abc import Iterator
+
+import pytest
+from fastapi.testclient import TestClient
+
+from jarvis.core.bus import EventBus
+from jarvis.core.config import JarvisConfig
+from jarvis.ui.web.server import WebServer
+
+
+class _FakeBrain:
+ def __init__(self, *, available: list[str], active: str = "openai") -> None:
+ self._available = available
+ self.active_provider = active
+ self.last_persist_ok = False
+ self.calls: list[tuple[str, bool]] = []
+
+ def available_providers(self) -> list[str]:
+ return list(self._available)
+
+ async def switch(self, provider: str, *, persist: bool = False) -> None:
+ self.calls.append((provider, persist))
+ self.active_provider = provider
+ self.last_persist_ok = False
+
+
+def server() -> Iterator[WebServer]:
+ cfg = JarvisConfig()
+ cfg.ui.dev_mode = True
+ srv = WebServer(cfg, bus=EventBus())
+ srv.app.state.brain = _FakeBrain(available=["openai", "claude-api", "openrouter"])
+ srv.app.state.cfg = cfg
+ srv.app.state.bus = srv.bus
+ yield srv
+
+
+def test_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, manager=manager)
+ return {
+ "ok": True, "tier": tier, "old_provider": "openai",
+ "new_provider": provider, "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:
+ resp = client.post(
+ "/api/brain/switch", json={"provider": "openrouter", "persist": True}
+ )
+ assert resp.status_code == 200
+ body = resp.json()
+ assert body["ok"] is True
+ assert body["active"] == "openrouter"
+ assert body["persisted"] is True
+ assert body["old_provider"] == "openai"
+ # The route handed its live manager to the shared implementation.
+ assert seen["tier"] == "brain"
+ assert seen["manager"] is server.app.state.brain
+
+
+def test_shared_error_kind_maps_to_http_status(server, monkeypatch) -> None:
+ async def fake_apply(tier, provider, *, cfg, persist=True, manager=None):
+ return {
+ "ok": False,
+ "error_kind": "missing_credential",
+ "error": "openrouter is not configured — its API key is missing.",
+ }
+
+ monkeypatch.setattr(
+ "jarvis.brain.app_control.apply_provider_switch", fake_apply
+ )
+ with TestClient(server.app) as client:
+ resp = client.post("/api/brain/switch", json={"provider": "openrouter"})
+ assert resp.status_code == 409
+ assert "not configured" in resp.json()["detail"]
+
+
+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."""
+ server.cfg.profile.name = "airgapped"
+ with TestClient(server.app) as client:
+ resp = client.post("/api/brain/switch", json={"provider": "openrouter"})
+ assert resp.status_code == 403
+ assert "privacy mode" in resp.json()["detail"].lower()