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(providers): bounded, honest provider tests end-to-end
Ruben Lütke229de78b59e5
diff --git a/jarvis/brain/provider_test.py b/jarvis/brain/provider_test.pyindex 2353e39897..0476e91cbf 100644--- a/jarvis/brain/provider_test.py+++ b/jarvis/brain/provider_test.py@@ -202,6 +202,28 @@ 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.++ 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++def _default_make_tts(cfg: Any, provider: str) -> Any:from jarvis.plugins.tts import _build_provider@@ -307,15 +329,16 @@ async def run_provider_test(if not is_present:return ProviderTestResult(provider, NOT_CONFIGURED, "No credential stored.")- if spec.tier == "brain":- if brain_probe is None:- async def brain_probe(p: str, m: str) -> Any: # type: ignore[misc]- from jarvis.brain.healthcheck import BrainHealthChecker- from jarvis.brain.provider_registry import BrainProviderRegistry+ # Default 1-token probe, shared by the brain tier AND the realtime tier below.+ if brain_probe is None:+ async def brain_probe(p: str, m: str) -> Any: # type: ignore[misc]+ from jarvis.brain.healthcheck import BrainHealthChecker+ from jarvis.brain.provider_registry import BrainProviderRegistry- checker = BrainHealthChecker(BrainProviderRegistry())- return await checker.probe(p, m, timeout_s=timeout_s)+ 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):@@ -325,6 +348,31 @@ async def run_provider_test(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:+ return ProviderTestResult(+ provider, OK, "Credential stored; no live probe for this provider."+ )+ hr = await brain_probe(sibling, _resolve_brain_model(cfg, sibling))+ if getattr(hr, "ok", False):+ return ProviderTestResult(+ provider,+ OK,+ f"Key verified via {sibling}.",+ 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 == "tts":builder = make_tts or _default_make_ttstry:@@ -332,17 +380,28 @@ async def run_provider_test(except Exception as exc: # noqa: BLE001detail = f"{type(exc).__name__}: {exc}"return ProviderTestResult(provider, classify_provider_error(detail), str(exc))- start = perf_counter()- try:++ async def _first_audio_bytes() -> int:total = 0async for chunk in inst.synthesize("Test."):total += len(getattr(chunk, "pcm", b"") or b"")if total > 0:break+ return total++ start = perf_counter()+ try:+ # Bounded like the STT branch below: an unresponsive TTS stream must+ # surface as an honest "unreachable" instead of hanging the request+ # (and the UI's "Testing…" spinner) forever.+ total = await asyncio.wait_for(_first_audio_bytes(), timeout=timeout_s)dur = (perf_counter() - start) * 1000.0if total > 0:return ProviderTestResult(provider, OK, f"{total} audio bytes", dur)return ProviderTestResult(provider, ERROR, "synthesized 0 bytes", dur)+ except TimeoutError:+ dur = (perf_counter() - start) * 1000.0+ return ProviderTestResult(provider, UNREACHABLE, f"timeout after {timeout_s:.0f}s", dur)except Exception as exc: # noqa: BLE001dur = (perf_counter() - start) * 1000.0detail = f"{type(exc).__name__}: {exc}"@@ -351,7 +410,10 @@ async def run_provider_test(# sttbuilder = make_stt or _default_make_stttry:- inst = builder(cfg, provider)+ # Built off the event loop: the local faster-whisper build LOADS the model+ # synchronously (seconds), which would otherwise freeze every other request+ # (and the whole API-Keys screen) while a test/section-health check runs.+ inst = await asyncio.to_thread(builder, cfg, provider)except (ImportError, ModuleNotFoundError):# M5: the local faster-whisper STT needs the [desktop] extra. On a headless# base install the import raises — that is "not installed", an actionablediff --git a/jarvis/ui/web/frontend/src/hooks/useProviders.ts b/jarvis/ui/web/frontend/src/hooks/useProviders.tsindex b2ece09fc5..34112d59a5 100644--- a/jarvis/ui/web/frontend/src/hooks/useProviders.ts+++ b/jarvis/ui/web/frontend/src/hooks/useProviders.ts@@ -256,7 +256,14 @@ export function useSectionHealth() {useEffect(() => {void reload(false);- const onChange = () => void reload(true);+ // Debounced: one action can fire several of these events back-to-back+ // (switch + refetch + test). Each refresh runs REAL connectivity tests+ // server-side, so bursts are collapsed into a single trailing reload.+ let timer: number | undefined;+ const onChange = () => {+ window.clearTimeout(timer);+ timer = window.setTimeout(() => void reload(true), 400);+ };const events = ["jarvis:secret-configured","jarvis:brain-switched",@@ -268,7 +275,10 @@ export function useSectionHealth() {"jarvis:provider-tested",];events.forEach((e) => window.addEventListener(e, onChange));- return () => events.forEach((e) => window.removeEventListener(e, onChange));+ return () => {+ window.clearTimeout(timer);+ events.forEach((e) => window.removeEventListener(e, onChange));+ };}, [reload]);return { health, reload };@@ -565,20 +575,47 @@ export interface ProviderTestResult {integration_ok: boolean;}+// The backend caps a test at 75 s (route-level wait_for); this client-side+// ceiling sits above it so a wedged backend can never leave the "Testing…"+// spinner running forever — the ONE state a test control must never reach.+const PROVIDER_TEST_CLIENT_TIMEOUT_MS = 80_000;+/*** Runs a REAL minimal call against the provider (1-token brain completion, a* tiny TTS synthesis, an STT transcription, or the Codex OAuth status) and* reports the honest outcome — not just whether a key string is stored.+ *+ * Never hangs: aborts client-side after `PROVIDER_TEST_CLIENT_TIMEOUT_MS` and+ * resolves to an honest "unreachable" result instead of rejecting, so the UI+ * always gets a renderable outcome.*/export async function testProvider(providerId: string): Promise<ProviderTestResult> {- const res = await fetch(`/api/providers/${encodeURIComponent(providerId)}/test`, {- method: "POST",- });- const body = await res.json().catch(() => ({}));- if (!res.ok) {- throw new Error(body.detail ?? `HTTP ${res.status}`);+ const controller = new AbortController();+ const timer = window.setTimeout(() => controller.abort(), PROVIDER_TEST_CLIENT_TIMEOUT_MS);+ try {+ const res = await fetch(`/api/providers/${encodeURIComponent(providerId)}/test`, {+ method: "POST",+ signal: controller.signal,+ });+ const body = await res.json().catch(() => ({}));+ if (!res.ok) {+ throw new Error(body.detail ?? `HTTP ${res.status}`);+ }+ return body as ProviderTestResult;+ } catch (e) {+ if ((e as Error).name === "AbortError") {+ return {+ provider: providerId,+ status: "unreachable",+ detail: "No answer from the app after 80s — the backend may be busy or stuck.",+ latency_ms: PROVIDER_TEST_CLIENT_TIMEOUT_MS,+ integration_ok: false,+ };+ }+ throw e;+ } finally {+ window.clearTimeout(timer);}- return body as ProviderTestResult;}// ── Per-provider model picker ───────────────────────────────────────────────diff --git a/jarvis/ui/web/provider_routes.py b/jarvis/ui/web/provider_routes.pyindex ed2f489891..5d877217a4 100644--- a/jarvis/ui/web/provider_routes.py+++ b/jarvis/ui/web/provider_routes.py@@ -593,6 +593,12 @@ async def list_providers(request: Request) -> dict[str, Any]:return {"providers": providers}+# Belt-and-suspenders ceiling for the whole /test call. run_provider_test's own+# timeout_s (60 s, generous for NVIDIA NIM's 13-30 s cold-start TTFB) bounds the+# individual probe; this outer bound guarantees the HTTP response itself.+_PROVIDER_TEST_HARD_TIMEOUT_S = 75.0++@router.post("/providers/{provider_id}/test")async def test_provider_connection(provider_id: str, request: Request@@ -616,7 +622,25 @@ async def test_provider_connection(status_code=503, detail="Konfiguration nicht verfügbar (Headless-Mode?)")- result = await _provider_test.run_provider_test(spec, cfg)+ # Hard ceiling ABOVE run_provider_test's own per-call timeout (60 s): the+ # route must always answer, else the UI's "Testing…" spinner never resolves.+ # Any async path that slips past the inner bounds is cut here and reported+ # as an honest "unreachable" instead of a hung HTTP request.+ try:+ result = await asyncio.wait_for(+ _provider_test.run_provider_test(spec, cfg),+ timeout=_PROVIDER_TEST_HARD_TIMEOUT_S,+ )+ except TimeoutError:+ result = _provider_test.ProviderTestResult(+ provider=spec.id,+ status=_provider_test.UNREACHABLE,+ detail=(+ f"Test timed out after {_PROVIDER_TEST_HARD_TIMEOUT_S:.0f}s — "+ "the provider did not answer."+ ),+ latency_ms=_PROVIDER_TEST_HARD_TIMEOUT_S * 1000.0,+ )return ProviderTestResponse(provider=result.provider,status=result.status,@@ -767,6 +791,26 @@ def _worker_flagged_dead(provider: str) -> bool:return False+def _claude_worker_display_label(*, default: str) -> str:+ """Honest display name for the Claude worker slot in health messages.++ The ``claude-api`` spec label says "(API-Key)", but the SAME slot runs on+ the Claude subscription OAuth login whenever one exists — a degraded+ banner blaming the "API-Key" then reads as nonsense to a subscription+ user (2026-07-10 report: "I selected the subscription, the key is+ irrelevant"). Presence of ANY OAuth bearer, live or expired-in-place,+ means the user is on the subscription path. Offline + cheap; any probe+ failure keeps the spec label rather than breaking the health check.+ """+ try:+ from jarvis.claude_credentials import freshest_claude_oauth++ oauth_status = freshest_claude_oauth().status+ except Exception: # noqa: BLE001+ oauth_status = "absent"+ return "Claude (subscription)" if oauth_status != "absent" else default++def _jarvis_agent_section_health(cfg: Any) -> SectionHealth:"""Subagents tab: reflects whether the SELECTED heavy-task worker is usable.@@ -794,6 +838,8 @@ def _jarvis_agent_section_health(cfg: Any) -> SectionHealth:)spec = get_spec(provider)label = spec.label if spec is not None else provider+ if (provider or "").lower() in {"claude-api", "claude"}:+ label = _claude_worker_display_label(default=label)if _worker_usable(provider) and not _worker_flagged_dead(provider):return SectionHealth(status=_section_health.OK, reason="ok", detail=f"Subagent worker: {label}"@@ -896,6 +942,34 @@ async def section_health(request: Request, refresh: bool = False) -> SectionHealsections=cache["payload"], checked_at=cache["checked_at"], cached=True)+ # Coalesce concurrent (re)checks: a provider switch fires several UI events in+ # a burst, each of which used to launch its OWN full sweep of REAL provider+ # tests — a multi-second storm that made the whole screen feel broken. Requests+ # arriving while one sweep runs wait for it and reuse its result — a waiting+ # ?refresh=true only reuses a sweep that FINISHED while it waited (so an+ # explicit refresh still always reflects a check started after the request,+ # the contract the UI relies on after a key save / provider switch).+ entered = time.time()+ lock = getattr(request.app.state, "_section_health_refresh_lock", None)+ if lock is None:+ lock = asyncio.Lock()+ request.app.state._section_health_refresh_lock = lock+ async with lock:+ cache = getattr(request.app.state, "_section_health_cache", None)+ checked_at = cache.get("checked_at", 0.0) if isinstance(cache, dict) else 0.0+ now = time.time()+ fresh_enough = (+ checked_at >= entered if refresh else now - checked_at < _SECTION_HEALTH_TTL_S+ )+ if isinstance(cache, dict) and fresh_enough:+ return SectionHealthResponse(+ sections=cache["payload"], checked_at=checked_at, cached=True+ )+ return await _compute_section_health(request, now)+++async def _compute_section_health(request: Request, now: float) -> SectionHealthResponse:+ """One full sweep of the per-tab health checks (called under the refresh lock)."""cfg = _resolve_cfg(request)sections: dict[str, SectionHealth] = {}diff --git a/tests/unit/brain/test_provider_test_service.py b/tests/unit/brain/test_provider_test_service.pyindex c807e61a5e..8c626feeb9 100644--- a/tests/unit/brain/test_provider_test_service.py+++ b/tests/unit/brain/test_provider_test_service.py@@ -170,3 +170,43 @@ 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.++ 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)++ res = _run(+ run_provider_test(+ get_spec("openai-realtime"), _cfg(), present=True, brain_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+++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",+ )++ res = _run(+ run_provider_test(+ get_spec("gemini-live"), _cfg(), present=True, brain_probe=probe,+ )+ )+ assert res.status == "bad_key"