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
fix(realtime): validate exact duplex provider health
Ruben Lütke6137a4c9483f
diff --git a/jarvis/brain/provider_test.py b/jarvis/brain/provider_test.pyindex 0476e91cbf..da2f38ed4f 100644--- a/jarvis/brain/provider_test.py+++ b/jarvis/brain/provider_test.py@@ -202,26 +202,51 @@ def _resolve_brain_model(cfg: Any, provider: str) -> str:return ""-def _same_family_brain_id(spec: Any) -> str | None:- """The brain-tier provider sharing ``spec``'s credential slots, if any.+def _resolve_provider_option(cfg: Any, provider: str, field: str) -> str:+ """Read a per-provider model or voice override without assuming its family."""+ try:+ providers = getattr(getattr(cfg, "brain", None), "providers", None)+ provider_config = providers.get(provider) if isinstance(providers, dict) else None+ return str(getattr(provider_config, field, "") or "")+ except Exception: # noqa: BLE001+ return ""- Resolved via the SHARED SECRET SLOTS (e.g. OpenAI Realtime reuses- ``openai_api_key``), never a provider-name mapping (AP-21) — a new realtime- provider that declares its key slot gets a working test with no code change.- """- keys = set(getattr(spec, "secret_keys", ()) or ())- if not keys:- return None- # Lazy import — same pattern as app_control._provider_spec(): the catalog- # lives in the UI layer, importing it at call time avoids an import cycle.- from jarvis.ui.web.provider_spec import PROVIDERS- for cand in PROVIDERS:- if getattr(cand, "tier", None) != "brain":- continue- if keys & set(getattr(cand, "secret_keys", ()) or ()):- return cand.id- return None+async def _default_realtime_probe(spec: Any, cfg: Any, *, timeout_s: float) -> float:+ """Open and close the exact selected realtime provider.++ A sibling text-model call cannot validate the duplex endpoint, model id,+ session schema, audio formats, or SDK event contract. The provider adapter's+ ``open_session`` returns only after its handshake is accepted, so this is a+ small but authoritative connectivity check with no audio sent.+ """+ from jarvis.core.config import get_secret_any+ from jarvis.core.registry import load+ from jarvis.realtime.protocol import RealtimeProvider, RealtimeSessionConfig++ provider_cls = load("jarvis.realtime", spec.id, protocol=RealtimeProvider)+ credentials = tuple(getattr(provider_cls, "credential_candidates", ()) or ())+ api_key = get_secret_any(credentials)+ if not api_key:+ raise RuntimeError("No API key configured for the realtime provider")+ provider = provider_cls(api_key=api_key)+ session_config = RealtimeSessionConfig(+ instructions="Connection validation only. Do not respond until audio arrives.",+ language="en",+ model=_resolve_provider_option(cfg, spec.id, "model"),+ voice=_resolve_provider_option(cfg, spec.id, "voice"),+ input_sample_rate=int(getattr(provider, "input_sample_rate", 16_000)),+ output_sample_rate=int(getattr(provider, "output_sample_rate", 24_000)),+ modalities=("audio",),+ )+ started = perf_counter()+ session = await asyncio.wait_for(+ provider.open_session(session_config), timeout=timeout_s+ )+ try:+ return (perf_counter() - started) * 1000.0+ finally:+ await session.close()def _default_make_tts(cfg: Any, provider: str) -> Any:@@ -275,6 +300,7 @@ async def run_provider_test(brain_probe: Callable[[str, str], Awaitable[Any]] | None = None,make_tts: Callable[[Any, str], Any] | None = None,make_stt: Callable[[Any, str], Any] | None = None,+ realtime_probe: Callable[[Any, Any], Awaitable[float]] | None = None,codex_status: Callable[[], Any] | None = None,antigravity_status: Callable[[], Any] | None = None,timeout_s: float = 60.0,@@ -338,36 +364,46 @@ async def run_provider_test(checker = BrainHealthChecker(BrainProviderRegistry())return await checker.probe(p, m, timeout_s=timeout_s)- if spec.tier == "brain":- model = _resolve_brain_model(cfg, provider)- hr = await brain_probe(provider, model)- if getattr(hr, "ok", False):- return ProviderTestResult(provider, OK, "", getattr(hr, "duration_ms", 0.0))- err = getattr(hr, "error", None)- return ProviderTestResult(- provider, classify_provider_error(err), err or "", getattr(hr, "duration_ms", 0.0),- )-if spec.tier == "realtime":- # A realtime tier used to fall through to the STT branch below — the test- # button on a realtime card built an unrelated STT provider and hung or- # lied. Opening a REAL duplex session here would be heavy and billed; the- # honest minimal call is a 1-token probe through the text brain of the- # SAME credential family (resolved by shared secret slots, AP-21), which- # verifies key + reachability end-to-end.- sibling = _same_family_brain_id(spec)- if sibling is None:+ started = perf_counter()+ try:+ if realtime_probe is None:+ latency_ms = await _default_realtime_probe(+ spec, cfg, timeout_s=min(timeout_s, 20.0)+ )+ else:+ latency_ms = await asyncio.wait_for(+ realtime_probe(spec, cfg), timeout=min(timeout_s, 20.0)+ )return ProviderTestResult(- provider, OK, "Credential stored; no live probe for this provider."+ provider,+ OK,+ "Realtime session handshake accepted.",+ latency_ms,)- hr = await brain_probe(sibling, _resolve_brain_model(cfg, sibling))- if getattr(hr, "ok", False):+ except TimeoutError:+ latency_ms = (perf_counter() - started) * 1000.0return ProviderTestResult(provider,- OK,- f"Key verified via {sibling}.",- getattr(hr, "duration_ms", 0.0),+ UNREACHABLE,+ "Realtime session handshake timed out.",+ latency_ms,)+ except Exception as exc: # noqa: BLE001+ latency_ms = (perf_counter() - started) * 1000.0+ detail = f"{type(exc).__name__}: {exc}"+ return ProviderTestResult(+ provider,+ classify_provider_error(detail),+ detail,+ latency_ms,+ )++ if spec.tier == "brain":+ model = _resolve_brain_model(cfg, provider)+ hr = await brain_probe(provider, model)+ if getattr(hr, "ok", False):+ return ProviderTestResult(provider, OK, "", getattr(hr, "duration_ms", 0.0))err = getattr(hr, "error", None)return ProviderTestResult(provider, classify_provider_error(err), err or "", getattr(hr, "duration_ms", 0.0),diff --git a/jarvis/ui/web/provider_routes.py b/jarvis/ui/web/provider_routes.pyindex 5a420f5171..45e28c99e2 100644--- a/jarvis/ui/web/provider_routes.py+++ b/jarvis/ui/web/provider_routes.py@@ -879,32 +879,15 @@ def _jarvis_agent_section_health(cfg: Any) -> SectionHealth:)-def _realtime_section_health(request: Request) -> SectionHealth:- """Realtime tab: credential-presence ONLY — there is no realtime- provider-test yet (the client is not wired in, Phase 2), so this never- calls ``run_provider_test``. Mirrors the shape of ``_tier_section_health``- without the live connectivity probe.+async def _realtime_section_health(request: Request) -> SectionHealth:+ """Test the active provider's actual duplex handshake.++ Credential presence alone previously painted a depleted or schema-broken+ provider green. Reuse the standard tier health mapping so the Realtime tab+ reports the same honest account/integration states as every other tier."""- spec = get_spec(_active_realtime(request) or "")- if spec is None:- return SectionHealth(- status=_section_health.NEEDS_SETUP,- reason="no_active",- detail="No active provider selected",- )- try:- configured = _is_credential_present(spec)- except Exception: # noqa: BLE001 — a probe failure is "not set up", not a crash- configured = False- if configured:- return SectionHealth(- status=_section_health.OK, reason="ok", detail=f"{spec.label}: ready"- )- return SectionHealth(- status=_section_health.NEEDS_SETUP,- reason="not_configured",- detail=f"{spec.label}: no key set",- )+ cfg = _resolve_cfg(request)+ return await _tier_section_health(cfg, get_spec(_active_realtime(request) or ""))def _advanced_section_health(request: Request) -> SectionHealth:@@ -996,11 +979,10 @@ async def _compute_section_health(request: Request, now: float) -> SectionHealth_tier_section_health(cfg, tts_spec),_tier_section_health(cfg, stt_spec),)- # These three helpers are synchronous (keyring reads, CLI status- # subprocesses) — run them in a worker thread so the sweep never blocks- # the event loop for every other request in flight.+ # Realtime performs an async duplex handshake. The remaining helpers are+ # synchronous (keyring reads, CLI status subprocesses) and stay off-loop.try:- sections["realtime"] = await asyncio.to_thread(_realtime_section_health, request)+ sections["realtime"] = await _realtime_section_health(request)except Exception as exc: # noqa: BLE001log.warning("section-health realtime check failed: %s", exc)sections["realtime"] = SectionHealth()@@ -2588,4 +2570,3 @@ async def jarvis_agent_model(body: SubagentModelBody, request: Request) -> dict["persisted": persisted,"restart_required": True,}-diff --git a/tests/unit/brain/test_provider_test_service.py b/tests/unit/brain/test_provider_test_service.pyindex 8c626feeb9..a2fc4795f4 100644--- a/tests/unit/brain/test_provider_test_service.py+++ b/tests/unit/brain/test_provider_test_service.py@@ -172,41 +172,52 @@ def test_tts_synthesis_bytes_is_ok() -> None:assert res.status == "ok"-def test_realtime_probes_same_family_brain_not_stt() -> None:- """A realtime card's test probes the text brain sharing its key slot.+def test_realtime_test_opens_the_exact_duplex_provider() -> None:+ probed: list[str] = []- The realtime tier used to fall through to the STT branch, building an- unrelated STT provider — the "Testing…" spinner then hung or lied. The fix- routes it to a 1-token probe of the same-credential-family brain (resolved- by shared secret slots, never a provider-name pin).- """- probed: list[tuple[str, str]] = []-- async def probe(p, m):- probed.append((p, m))- return HealthResult(provider=p, model=m, ok=True, duration_ms=42.0)+ async def probe(spec, _cfg):+ probed.append(spec.id)+ return 42.0res = _run(run_provider_test(- get_spec("openai-realtime"), _cfg(), present=True, brain_probe=probe,+ get_spec("openai-realtime"),+ _cfg(),+ present=True,+ realtime_probe=probe,))assert res.status == "ok"- # openai-realtime shares openai_api_key with the "openai" brain provider.- assert probed and probed[0][0] == "openai"- assert "openai" in res.detail+ assert probed == ["openai-realtime"]+ assert res.latency_ms == pytest.approx(42.0)+ assert "handshake accepted" in res.detail.lower()-def test_realtime_bad_key_classified_from_family_probe() -> None:- async def probe(_p, _m):- return HealthResult(- provider="gemini", model="m", ok=False,- error="ClientError: Error code: 401 - API key not valid",- )+def test_realtime_bad_key_is_classified_from_duplex_handshake() -> None:+ async def probe(_spec, _cfg):+ raise RuntimeError("ClientError: Error code: 401 - API key not valid")res = _run(run_provider_test(- get_spec("gemini-live"), _cfg(), present=True, brain_probe=probe,+ get_spec("gemini-live"),+ _cfg(),+ present=True,+ realtime_probe=probe,))assert res.status == "bad_key"+++def test_realtime_depleted_credits_are_an_account_error() -> None:+ async def probe(_spec, _cfg):+ raise RuntimeError("Your prepayment credits are depleted")++ res = _run(+ run_provider_test(+ get_spec("gemini-live"),+ _cfg(),+ present=True,+ realtime_probe=probe,+ )+ )+ assert res.status == "no_credits"