Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
test(computer-use): add dispatch-hoist and switch-route tests for the dedicated CU provider
Ruben Lütke440aa40ee5ae
diff --git a/tests/unit/cu/test_brain_call_cu_provider.py b/tests/unit/cu/test_brain_call_cu_provider.pynew file mode 100644index 0000000000..bd20e5bfda--- /dev/null+++ b/tests/unit/cu/test_brain_call_cu_provider.py@@ -0,0 +1,162 @@+"""Dedicated Computer-Use provider dispatch (jarvis/cu/brain_call.py).++Covers the CU-own-provider hoist: ``manager._cu_provider()``, when it returns+a configured provider id, must be hoisted to the HEAD of the+``_build_fallback_chain("fast")`` candidate list before anything else in+``call_vision_brain`` applies (the cu_model pin loop, the speed tune, and —+critically — the vision/health gate in ``ComputerUsePlannerSelector``, so a+blind/dead CU pick degrades through the rest of the chain instead of+bricking Computer-Use, AP-21/22). When ``_cu_provider()`` returns ``""``+(unset) or is absent altogether, dispatch must be BYTE-FOR-BYTE unchanged —+CU keeps leading with whatever ``_build_fallback_chain`` already produces+(``brain.primary`` first), the default-preserving contract from the plan.++Fakes only (no real network, no real BrainManager) — mirrors the+``_FallbackChainManager``/``_StreamingBrain`` shape used in+``tests/unit/harness/test_cu_loop_robustness.py``.+"""+from __future__ import annotations++from typing import Any++from jarvis.core.protocols import BrainDelta, ImageBlock+from jarvis.cu.brain_call import call_vision_brain+++class _FakeBrain:+ """Minimal provider-shaped brain: records dispatch, yields scripted text."""++ supports_tools = False++ def __init__(self, *, text: str = '{"action": "done"}', supports_vision: bool = True) -> None:+ self.text = text+ self.supports_vision = supports_vision+ self.calls = 0++ async def complete(self, req: Any): # type: ignore[no-untyped-def]+ self.calls += 1+ if self.text:+ yield BrainDelta(content=self.text)+ yield BrainDelta(finish_reason="stop")++ def estimate_cost(self, req: Any) -> float:+ return 0.0+++class _FakeManager:+ """BrainManager-shaped fake exposing only the CU dispatch surface.++ Deliberately has NO ``complete_text`` attribute — ``call_vision_brain``+ checks ``getattr(manager, "complete_text", None)`` first and, if present,+ takes the FakeBrain test-shim early-return path, which would bypass the+ fallback-chain / hoist logic entirely and defeat these tests.+ """++ active_provider = "brain-primary"++ def __init__(self, *, cu_provider: str = "") -> None:+ self._cu_provider_value = cu_provider+ self.brains: dict[str, _FakeBrain] = {+ "brain-primary": _FakeBrain(),+ "brain-fallback": _FakeBrain(),+ "claude-api": _FakeBrain(),+ }+ self.requested: list[tuple[str, str | None]] = []++ def _build_fallback_chain(self, level: str) -> list[tuple[str, str | None]]:+ assert level == "fast"+ return [("brain-primary", None), ("brain-fallback", None)]++ def _get_brain(self, name: str, model: str | None = None) -> _FakeBrain:+ self.requested.append((name, model))+ return self.brains[name]++ def _cu_model(self, name: str) -> str | None:+ return None++ def _cu_provider(self) -> str:+ return self._cu_provider_value+++class _FakeManagerNoResolver(_FakeManager):+ """Same as ``_FakeManager`` but without ``_cu_provider`` at all — the+ shape of an older/pre-feature manager. Must dispatch exactly as before,+ never raise ``AttributeError``."""++ _cu_provider = None # type: ignore[assignment] # not callable -> not used++ def __init__(self) -> None:+ super().__init__(cu_provider="")+++def _build_prompt(provider: str, brain: Any) -> tuple[str, str]:+ return "system", "user"+++async def test_cu_provider_hoists_configured_provider_to_chain_head() -> None:+ """A dedicated CU provider takes priority over brain.primary / the normal+ fallback chain — the chain is REORDERED (hoisted), not replaced, so the+ downstream vision/health gate still runs over it."""+ manager = _FakeManager(cu_provider="claude-api")++ reply = await call_vision_brain(manager, build_prompt=_build_prompt, images=[])++ assert reply.provider == "claude-api"+ assert manager.requested[0] == ("claude-api", None)+ assert manager.brains["claude-api"].calls == 1+ assert manager.brains["brain-primary"].calls == 0+++async def test_no_cu_provider_leaves_chain_unchanged() -> None:+ """An unset CU provider ('') must not touch dispatch — CU still leads+ with brain.primary / the existing fallback-chain head (default-preserving,+ current behavior)."""+ manager = _FakeManager(cu_provider="")++ reply = await call_vision_brain(manager, build_prompt=_build_prompt, images=[])++ assert reply.provider == "brain-primary"+ assert manager.requested[0] == ("brain-primary", None)+++async def test_cu_provider_already_in_chain_is_deduplicated() -> None:+ """When the configured CU provider is already present in the fallback+ chain, it is hoisted, never duplicated (no repeated dispatch attempt)."""+ manager = _FakeManager(cu_provider="brain-fallback")++ reply = await call_vision_brain(manager, build_prompt=_build_prompt, images=[])++ assert reply.provider == "brain-fallback"+ assert manager.requested == [("brain-fallback", None)]+++async def test_cu_provider_resolver_missing_is_safe() -> None:+ """A manager without a callable ``_cu_provider`` (older manager shape)+ must dispatch exactly as before the feature — no AttributeError, no+ change in behavior."""+ manager = _FakeManagerNoResolver()++ reply = await call_vision_brain(manager, build_prompt=_build_prompt, images=[])++ assert reply.provider == "brain-primary"+ assert manager.requested[0] == ("brain-primary", None)+++async def test_blind_cu_provider_falls_back_through_vision_gate() -> None:+ """A configured CU provider that cannot see the screen must never brick+ Computer-Use: the vision/health gate downstream (ComputerUsePlannerSelector)+ skips it and falls through to the next vision-capable candidate in the+ (hoisted) chain — never a hard failure just because the CU pick is blind+ (AP-21/22)."""+ manager = _FakeManager(cu_provider="claude-api")+ manager.brains["claude-api"] = _FakeBrain(+ text='{"action": "click"}', supports_vision=False,+ )+ img = ImageBlock(mime="image/jpeg", data_b64="QQ==", source_hash="x")++ reply = await call_vision_brain(+ manager, build_prompt=_build_prompt, images=[img],+ )++ assert reply.provider == "brain-primary"+ assert manager.brains["claude-api"].calls == 0diff --git a/tests/unit/web/test_computer_use_provider_category.py b/tests/unit/web/test_computer_use_provider_category.pynew file mode 100644index 0000000000..c52b6e6573--- /dev/null+++ b/tests/unit/web/test_computer_use_provider_category.py@@ -0,0 +1,230 @@+"""Dedicated Computer-Use provider tier — backend for the API-Keys "Computer-Use" tab.++Overlay over the brain-tier provider cards (Claude/OpenAI/OpenRouter/Gemini),+not a new provider tier — a GLOBAL "which brain provider plans Computer-Use"+selection, decoupled from ``[brain] primary``. Covers the ``computer_use_active``+resolution in ``list_providers`` and the ``POST /computer-use/switch`` route.++Style follows ``tests/unit/web/test_realtime_provider_category.py``: a+lightweight FastAPI app with just the router mounted, monkeypatched secrets —+never the live ``jarvis.toml``. Every test that calls the switch route with+``persist=True`` monkeypatches ``config_writer.set_computer_use_provider`` so+it NEVER writes the real config file (isolation — see the earlier real-write+defect this repeats the fix for).+"""+from __future__ import annotations++from fastapi import FastAPI+from fastapi.testclient import TestClient++from jarvis.core import config as cfg_mod+from jarvis.core import config_writer+from jarvis.core.config import JarvisConfig+from jarvis.ui.web.provider_routes import router+from jarvis.ui.web.provider_spec import get_spec+++def _only_claude_key(key: str, *_a, **_kw) -> str | None:+ """Fake ``cfg_mod.get_secret``: only ``anthropic_api_key`` looks configured."""+ return "sk-test" if key == "anthropic_api_key" else None+++def _app() -> FastAPI:+ app = FastAPI()+ app.include_router(router)+ app.state.config = JarvisConfig()+ return app+++# ---------------------------------------------------------------------------+# GET /api/providers — computer_use_active+# ---------------------------------------------------------------------------+++def test_list_providers_defaults_computer_use_active_to_brain_primary(monkeypatch):+ """With no [brain.computer_use].provider configured, CU runs on the main+ Brain — brain.primary's card must show computer_use_active True (default-+ preserving contract from the plan)."""+ monkeypatch.setattr(cfg_mod, "get_secret", lambda *a, **kw: "sk-test")+ app = _app()+ assert app.state.config.brain.primary == "claude-api"+ client = TestClient(app)++ resp = client.get("/api/providers")++ assert resp.status_code == 200+ by_id = {p["id"]: p for p in resp.json()["providers"]}+ assert by_id["claude-api"]["computer_use_active"] is True+ assert by_id["openai"]["computer_use_active"] is False+++def test_list_providers_marks_configured_cu_provider_active(monkeypatch):+ """Once [brain.computer_use].provider is set, ITS card gets+ computer_use_active True — independent of brain.primary / the Brain+ tab's "active" field."""+ monkeypatch.setattr(cfg_mod, "get_secret", lambda *a, **kw: "sk-test")+ app = _app()+ from types import SimpleNamespace++ from jarvis.core.config import BrainTierConfig++ app.state.config.brain.computer_use = BrainTierConfig(provider="openai")+ # The Brain tab's "active" field reads app.state.brain (the live+ # BrainManager), independent of cfg.brain.computer_use.+ app.state.brain = SimpleNamespace(active_provider="claude-api")+ client = TestClient(app)++ resp = client.get("/api/providers")++ by_id = {p["id"]: p for p in resp.json()["providers"]}+ assert by_id["openai"]["computer_use_active"] is True+ # Brain primary stays claude-api's "active" — the two selections are+ # independent, never coupled.+ assert by_id["claude-api"]["active"] is True+ assert by_id["claude-api"]["computer_use_active"] is False+ assert by_id["openai"]["active"] is False+++# ---------------------------------------------------------------------------+# POST /api/computer-use/switch+# ---------------------------------------------------------------------------+++def test_computer_use_switch_persists_with_key(monkeypatch):+ monkeypatch.setattr(cfg_mod, "get_secret", _only_claude_key)+ writes: list[str] = []+ monkeypatch.setattr(+ config_writer, "set_computer_use_provider",+ lambda name, **kw: writes.append(name),+ )++ app = _app()+ client = TestClient(app)+ resp = client.post(+ "/api/computer-use/switch", json={"provider": "claude-api", "persist": True},+ )++ assert resp.status_code == 200+ body = resp.json()+ assert body["ok"] is True+ assert body["active"] == "claude-api"+ assert body["persisted"] is True+ # Unlike worker/realtime, CU takes effect immediately — no restart.+ assert body["restart_required"] is False+ assert writes == ["claude-api"]+ assert app.state.config.brain.computer_use is not None+ assert app.state.config.brain.computer_use.provider == "claude-api"+++def test_computer_use_switch_updates_existing_tier_in_memory(monkeypatch):+ """A second switch must UPDATE the existing [brain.computer_use] block,+ not silently no-op or create a duplicate."""+ monkeypatch.setattr(cfg_mod, "get_secret", lambda *a, **kw: "sk-test")+ monkeypatch.setattr(config_writer, "set_computer_use_provider", lambda name, **kw: None)++ app = _app()+ from jarvis.core.config import BrainTierConfig++ app.state.config.brain.computer_use = BrainTierConfig(provider="claude-api")+ client = TestClient(app)++ resp = client.post(+ "/api/computer-use/switch", json={"provider": "gemini", "persist": True},+ )++ assert resp.status_code == 200+ assert app.state.config.brain.computer_use.provider == "gemini"+++def test_computer_use_switch_without_key_is_409(monkeypatch):+ monkeypatch.setattr(cfg_mod, "get_secret", lambda *a, **kw: None)+ client = TestClient(_app())++ resp = client.post(+ "/api/computer-use/switch", json={"provider": "claude-api", "persist": True},+ )++ assert resp.status_code == 409+++def test_computer_use_switch_rejects_non_brain_switchable_provider(monkeypatch):+ """Codex/Antigravity are brain_switchable=False (can't receive+ screenshots) — the CU planner must reject them like /api/brain/switch does."""+ monkeypatch.setattr(cfg_mod, "get_secret", lambda *a, **kw: "sk-test")+ spec = get_spec("codex")+ assert spec is not None and spec.brain_switchable is False+ client = TestClient(_app())++ resp = client.post(+ "/api/computer-use/switch", json={"provider": "codex", "persist": True},+ )++ assert resp.status_code == 400+++def test_computer_use_switch_rejects_non_brain_tier_provider(monkeypatch):+ """A TTS/STT-tier id is not a valid CU planner candidate either."""+ monkeypatch.setattr(cfg_mod, "get_secret", lambda *a, **kw: "sk-test")+ client = TestClient(_app())++ resp = client.post(+ "/api/computer-use/switch",+ json={"provider": "elevenlabs", "persist": True},+ )++ assert resp.status_code == 400+++def test_computer_use_switch_unknown_provider_is_404(monkeypatch):+ monkeypatch.setattr(cfg_mod, "get_secret", lambda *a, **kw: None)+ client = TestClient(_app())++ resp = client.post(+ "/api/computer-use/switch",+ json={"provider": "does-not-exist", "persist": True},+ )++ assert resp.status_code == 404+++def test_computer_use_switch_does_not_touch_brain_primary(monkeypatch):+ """Activating a Computer-Use provider must NEVER move brain.primary or+ the Brain tab's active provider (Constraint: don't break Pipeline)."""+ monkeypatch.setattr(cfg_mod, "get_secret", lambda *a, **kw: "sk-test")+ monkeypatch.setattr(config_writer, "set_computer_use_provider", lambda name, **kw: None)++ app = _app()+ assert app.state.config.brain.primary == "claude-api"+ client = TestClient(app)++ resp = client.post(+ "/api/computer-use/switch", json={"provider": "gemini", "persist": True},+ )++ assert resp.status_code == 200+ assert app.state.config.brain.primary == "claude-api"+++def test_computer_use_switch_emits_secret_configured_event(monkeypatch):+ monkeypatch.setattr(cfg_mod, "get_secret", lambda *a, **kw: "sk-test")+ monkeypatch.setattr(config_writer, "set_computer_use_provider", lambda name, **kw: None)+ from jarvis.core.bus import EventBus++ bus = EventBus()+ events: list[object] = []++ async def _record(ev: object) -> None:+ events.append(ev)++ bus.subscribe_all(_record)++ app = _app()+ app.state.bus = bus+ client = TestClient(app)+ resp = client.post(+ "/api/computer-use/switch", json={"provider": "claude-api", "persist": True},+ )++ assert resp.status_code == 200+ keys = [getattr(e, "key", None) for e in events]+ assert "brain.computer_use.provider" in keys