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): guard the no-metered-fallback promise and tell the truth about what a subscription call costs
rubenluetke10-beepfd4cafb04302
diff --git a/jarvis/brain/provider_test.py b/jarvis/brain/provider_test.pyindex 1e06b6042e..6207e3b8d7 100644--- a/jarvis/brain/provider_test.py+++ b/jarvis/brain/provider_test.py@@ -93,6 +93,26 @@ BILLING_LIMIT_MARKERS = ("depleted","plan and billing","plans & billing",+ # Machine-readable TOKEN twins of the prose forms above. A transport that+ # redacts a provider body (the Codex app-server keeps only method + code)+ # can still forward a bounded `error.type`, and that token is then the ONLY+ # evidence of the account state — spelled with underscores, so the+ # space-separated entries above never match it. Both are terminal shapes+ # ("reached"/"exceeded" against a quota), never a transient throttle, so+ # they satisfy the hard invariant and are safe for the dead-list path in+ # manager.py::_is_account_blocked_exc, which shares this list.+ "usage_limit_reached",+ "quota_exceeded",+)++# Transient throttling as a machine TOKEN, for the same redacted-transport+# reason — but kept OUT of the billing list on purpose: a rate limit clears by+# itself and must never dead-list a funded account. Checked after the billing+# markers so a message carrying both still reads as the terminal state.+_RATE_LIMIT_TOKEN_MARKERS = (+ "rate_limit_exceeded",+ "rate limit exceeded",+ "too many requests",)# Back-compat alias (anything importing the old private name keeps working).@@ -182,6 +202,11 @@ def classify_provider_error(message: str | None) -> str:return UNREACHABLEif _has_billing(msg):return NO_CREDITS+ if any(m in msg for m in _RATE_LIMIT_TOKEN_MARKERS):+ # A throttle whose transport dropped the HTTP status. Without this the+ # only honest read left is "possible integration bug", which sends the+ # user hunting a defect instead of waiting or topping up.+ return RATE_LIMITEDreturn ERRORdiff --git a/jarvis/browser_voice/route.py b/jarvis/browser_voice/route.pyindex ba9392b941..9c5829f609 100644--- a/jarvis/browser_voice/route.py+++ b/jarvis/browser_voice/route.py@@ -137,6 +137,13 @@ def _automatic_usage_fallback_allowed(cfg: Any) -> bool:return realtime_implicit_usage_fallback_allowed(cfg)except Exception: # noqa: BLE001 - configured realtime fails closed on ambiguity+ # Fail closed, but never silently (AP-30): refusing the metered+ # fallback ENDS calls, so the reason has to be findable in the log.+ log.warning(+ "Realtime billing-fallback capability could not be read; refusing "+ "automatic usage-billed fallback for this session",+ exc_info=True,+ )return Falsediff --git a/jarvis/realtime/factory.py b/jarvis/realtime/factory.pyindex a4672f5fde..ed364ec695 100644--- a/jarvis/realtime/factory.py+++ b/jarvis/realtime/factory.py@@ -206,6 +206,17 @@ def realtime_handshake_budget_s(cfg: Any) -> float:return max(declared)+def _realtime_is_the_configured_voice_mode(cfg: Any) -> bool:+ """Whether realtime voice is the mode this install actually runs.++ The same switch ``build_realtime_session`` reads, so warming can never+ prepare a transport the session builder would refuse. Deliberately about+ CONFIGURATION, not about a live call: a warm transport is worth having+ BEFORE the first wake word, which is the entire point of warming.+ """+ return getattr(getattr(cfg, "voice", None), "mode", "pipeline") == "realtime"++async def realtime_warm_selected_transports(cfg: Any) -> None:"""Let every explicitly selected provider pre-open its transport.@@ -218,7 +229,19 @@ async def realtime_warm_selected_transports(cfg: Any) -> None:app-server and verifies the account INSIDE the first call's handshake(~1.5 s of 3.0 s, measured 2026-08-02). One broken plugin never stops theothers, and no failure here reaches the caller.++ Skipped entirely when realtime is not the configured voice mode. Warming a+ transport the session builder would refuse anyway is pure cost, and for a+ subscription transport that cost is a spawned process, a live account+ check, and a HELD profile lock at every boot — which is what makes the+ user's own login/logout report "busy" for a feature they switched off."""+ if not _realtime_is_the_configured_voice_mode(cfg):+ log.debug(+ "Realtime transport warm skipped: realtime is not the configured "+ "voice mode."+ )+ returnfor provider_id in _explicit_provider_ids(cfg):try:provider_cls = load(_GROUP, provider_id, protocol=RealtimeProvider)@@ -341,8 +364,7 @@ def build_realtime_session(pipeline. Actual socket handshakes happen lazily on ``audio_start`` and thewrapper tries every candidate in order before failing."""- mode = getattr(getattr(cfg, "voice", None), "mode", "pipeline")- if mode != "realtime":+ if not _realtime_is_the_configured_voice_mode(cfg):return Nonetry:providers = _provider_candidates(cfg, defer_external_login_probe=True)diff --git a/jarvis/ui/web/provider_spec.py b/jarvis/ui/web/provider_spec.pyindex 11de51b037..976fc9b445 100644--- a/jarvis/ui/web/provider_spec.py+++ b/jarvis/ui/web/provider_spec.py@@ -755,11 +755,15 @@ PROVIDERS: tuple[ProviderSpec, ...] = (install_hint="npm i -g @openai/[email protected]",signup_url="https://chatgpt.com",credential_help=(- "Uses the ChatGPT plan signed in through Codex. This experimental "- "realtime path does not need an API key. The app never switches it "- "silently to metered API voice. If it cannot start, the call stops; "- "select an API Realtime provider if you want usage billing. Brain "- "and tool providers keep their separately configured billing."+ "Uses the ChatGPT plan signed in through Codex. The voice itself "+ "needs no API key, and the app never switches it silently to "+ "metered API voice: if it cannot start, the call stops. Select an "+ "API Realtime provider if you want usage billing. One caveat — "+ "Jarvis transcribes your side of the call with the provider chosen "+ "in Speech-to-Text, so a CLOUD recognizer is still billed per turn "+ "to that key; choose an on-device one to keep the whole call off "+ "metered billing. Brain and tool providers keep their separately "+ "configured billing."),experimental=True,),diff --git a/tests/unit/brain/test_redacted_provider_error_tokens.py b/tests/unit/brain/test_redacted_provider_error_tokens.pynew file mode 100644index 0000000000..11b01b48d2--- /dev/null+++ b/tests/unit/brain/test_redacted_provider_error_tokens.py@@ -0,0 +1,80 @@+"""Refusals that survived a redacting transport must still be actionable.++Some transports never hand us a provider's prose body. The Codex app-server is+the extreme case: it keeps a JSON-RPC method name and a numeric code and drops+the message entirely, so a ChatGPT plan that ran out of voice quota used to+reach the user as ``rejected thread/realtime/start (code -32603)`` and classify+as ``error`` — "probably an integration bug", which sends someone hunting a+defect instead of waiting out a throttle or checking their plan.++The one detail such a transport can safely forward is a bounded machine token+(``rate_limit_exceeded``, ``usage_limit_reached``) — no account, prompt, or+identity data. These tests pin that those tokens land on the right status, and+that adding them did not blur the line the whole dead-list path depends on:+a transient throttle must never be mistaken for an exhausted account.+"""++from __future__ import annotations++import pytest++from jarvis.brain.provider_test import (+ _RATE_LIMIT_TOKEN_MARKERS,+ BILLING_LIMIT_MARKERS,+ classify_provider_error,+)+++ "message",+ [+ "Codex app-server rejected thread/realtime/start: rate_limit_exceeded",+ "{'error': {'type': 'rate_limit_exceeded'}}",+ "Too many requests",+ ],+)+def test_throttle_token_without_an_http_status_is_rate_limited(message: str) -> None:+ assert classify_provider_error(message) == "rate_limited"+++ "message",+ [+ "Codex app-server rejected thread/realtime/start: usage_limit_reached",+ "{'error': {'type': 'quota_exceeded'}}",+ ],+)+def test_exhausted_account_token_is_no_credits(message: str) -> None:+ assert classify_provider_error(message) == "no_credits"+++def test_underscore_token_is_needed_because_the_prose_form_misses_it() -> None:+ """The reason these entries exist at all, pinned so nobody 'tidies' them.++ The space-separated prose markers cannot match a token spelling, so without+ the twins below an exhausted plan reads as an integration bug.+ """+ assert "usage limit" in BILLING_LIMIT_MARKERS+ assert "usage limit" not in "usage_limit_reached"+ assert classify_provider_error("usage_limit_reached") == "no_credits"+++def test_no_throttle_token_can_dead_list_a_funded_account() -> None:+ """The hard invariant the billing list documents, now across both lists.++ A rate limit clears by itself; if any billing marker were a substring of a+ throttle message, one burst would permanently retire a working provider.+ """+ for token in _RATE_LIMIT_TOKEN_MARKERS:+ assert not any(marker in token for marker in BILLING_LIMIT_MARKERS), token+ assert classify_provider_error(token) == "rate_limited"+++def test_an_unrecognised_redacted_refusal_stays_an_honest_error() -> None:+ """No token, no guess: the classifier must not invent an account state."""+ assert (+ classify_provider_error(+ "Codex app-server rejected thread/realtime/start (code -32603)."+ )+ == "error"+ )diff --git a/tests/unit/realtime/test_factory.py b/tests/unit/realtime/test_factory.pyindex c0aa41f859..9087859e68 100644--- a/tests/unit/realtime/test_factory.py+++ b/tests/unit/realtime/test_factory.py@@ -335,7 +335,7 @@ async def test_warm_selected_transports_skips_providers_without_the_capability(factory, "load", lambda _group, pid, protocol=None: loaded[pid])- await factory.realtime_warm_selected_transports(object())+ await factory.realtime_warm_selected_transports(_cfg())assert warm.calls == 1@@ -358,7 +358,7 @@ async def test_warm_selected_transports_survives_one_broken_provider()monkeypatch.setattr(factory, "load", _load)- await factory.realtime_warm_selected_transports(object())+ await factory.realtime_warm_selected_transports(_cfg())assert warm.calls == 1@@ -375,11 +375,59 @@ async def test_warm_selected_transports_ignores_unselected_plugins(factory, "load", lambda _group, _pid, protocol=None: warm)- await factory.realtime_warm_selected_transports(object())+ await factory.realtime_warm_selected_transports(_cfg())assert warm.calls == 0+async def test_warm_selected_transports_skips_a_pipeline_mode_install(+ monkeypatch,+) -> None:+ """A stale realtime pin must not spawn a transport for a disabled feature.++ Warming a subscription transport means spawning a process, running a live+ account check, and HOLDING the profile lock — which is what made the user's+ own Codex login report "busy" on an install whose voice runs the classic+ pipeline. Gate on the same switch ``build_realtime_session`` reads.+ """+ warm = _WarmProbe()+ monkeypatch.setattr(+ factory, "_explicit_provider_ids", lambda _cfg: ["warm-me"]+ )+ monkeypatch.setattr(+ factory, "load", lambda _group, _pid, protocol=None: warm+ )++ await factory.realtime_warm_selected_transports(_cfg(mode="pipeline"))++ assert warm.calls == 0+++async def test_warm_selected_transports_still_warms_the_realtime_install(+ monkeypatch,+) -> None:+ """The mirror: the case warming EXISTS for keeps working.++ Warming is about the cold start before the first wake word, so it must+ depend on the configured mode alone — never on a call being in flight.+ """+ warm = _WarmProbe()+ monkeypatch.setattr(+ factory, "_explicit_provider_ids", lambda _cfg: ["warm-me"]+ )+ monkeypatch.setattr(+ factory, "load", lambda _group, _pid, protocol=None: warm+ )++ await factory.realtime_warm_selected_transports(+ _cfg(mode="realtime", provider="codex-subscription-realtime")+ )++ assert warm.calls == 1++def test_declared_handshake_budget_reaches_the_surface(monkeypatch) -> None:"""A surface must not call a start attempt dead inside a declared budget.diff --git a/tests/unit/realtime/test_usage_billed_fallback_guard.py b/tests/unit/realtime/test_usage_billed_fallback_guard.pynew file mode 100644index 0000000000..70be669303--- /dev/null+++ b/tests/unit/realtime/test_usage_billed_fallback_guard.py@@ -0,0 +1,224 @@+"""The one guarantee that costs real money when it breaks.++A provider that declares ``implicit_usage_fallback_allowed = False`` (today: the+ChatGPT-subscription transport) promises the user that a failed call STOPS+instead of quietly continuing on metered API credentials. The factory turns that+capability into ``allow_classic_fallback`` and both voice surfaces are supposed+to honour it — but until this module the whole promise was one ``if`` on each+surface with nothing asserting it, so a refactor could delete it and leave every+failed subscription call silently billed to the user's own API keys.++Each case is asserted in BOTH directions: the guard must stop the metered path+when it is off AND still allow it when it is on, so a test that passes by+accident (or a guard hardwired to one answer) fails here.++The harnesses are imported from the two suites that own those surfaces rather+than copied — a private copy of ``_pipe`` would drift out of sync with the real+``SpeechPipeline`` attributes and start passing for the wrong reason.+"""++from __future__ import annotations++import asyncio+from types import SimpleNamespace++import pytest++import jarvis.browser_voice.route as route_mod+import jarvis.speech.pipeline as pipeline_mod+from jarvis.browser_voice.route import (+ _USAGE_FALLBACK_DISABLED_DETAIL,+ browser_voice_ws,+)+from jarvis.sessions.constants import HANGUP_ERROR+from jarvis.ui.web.missions_auth import register_token, revoke_token+from tests.unit.browser_voice.test_route import (+ _VALID_TOKEN,+ _FakeWS,+ _RecSession,+ _state,+)+from tests.unit.speech.test_realtime_mode import _pipe, _SilentMic++[email protected](autouse=True)+def _registered_browser_token():+ """The browser socket authenticates even on loopback."""+ register_token(_VALID_TOKEN)+ try:+ yield+ finally:+ revoke_token(_VALID_TOKEN)+++class _FailingDesktopSession:+ """A realtime session that dies in its handshake, like a refused plan."""++ def __init__(self, *, allow_classic_fallback: bool) -> None:+ self.allow_classic_fallback = allow_classic_fallback+ self.hangup_reason = ""+ self.end_reason = ""++ async def handle_control(self, _message) -> None:+ raise RuntimeError("simulated subscription transport failure")++ async def handle_audio_frame(self, _pcm: bytes) -> None:+ return None++ async def wait_finished(self) -> None:+ return None++ async def end(self, *, reason: str = "") -> None:+ self.end_reason = reason+++# ── Desktop surface ──────────────────────────────────────────────────────────+++ ("fallback_allowed", "expected"),+ [(False, HANGUP_ERROR), (True, None)],+)+async def test_desktop_unbuildable_realtime_stops_instead_of_billing_api(+ monkeypatch: pytest.MonkeyPatch,+ fallback_allowed: bool,+ expected: str | None,+) -> None:+ """No credential-ready provider: end the call, never run metered classic.++ ``None`` is the pipeline's request to replay this call through the classic+ STT/TTS/brain stack — every one of which spends an API key.+ """+ pipe = _pipe()+ monkeypatch.setattr(+ "jarvis.realtime.factory.realtime_implicit_usage_fallback_allowed",+ lambda _cfg: fallback_allowed,+ )+ monkeypatch.setattr(+ "jarvis.realtime.factory.build_realtime_session",+ lambda **_kwargs: None,+ )+ monkeypatch.setattr(+ pipeline_mod, "MicrophoneCapture", lambda **_kwargs: _SilentMic()+ )++ reason = await asyncio.wait_for(pipe._active_realtime_session(), timeout=2.0)++ assert reason == expected+++ ("fallback_allowed", "expected"),+ [(False, HANGUP_ERROR), (True, None)],+)+async def test_desktop_failed_handshake_stops_instead_of_billing_api(+ monkeypatch: pytest.MonkeyPatch,+ fallback_allowed: bool,+ expected: str | None,+) -> None:+ """The session exists but its handshake dies — the live plan-limit shape.++ The surface must read the capability off the SESSION here (the factory+ already resolved it), not re-derive it from anything else.+ """+ pipe = _pipe()+ built: dict[str, _FailingDesktopSession] = {}++ def _build(**_kwargs):+ session = _FailingDesktopSession(allow_classic_fallback=fallback_allowed)+ built["session"] = session+ return session++ # Deliberately the OPPOSITE of the session's own answer: whichever value the+ # surface honours, it must be the one the built session carries.+ monkeypatch.setattr(+ "jarvis.realtime.factory.realtime_implicit_usage_fallback_allowed",+ lambda _cfg: not fallback_allowed,+ )+ monkeypatch.setattr("jarvis.realtime.factory.build_realtime_session", _build)+ monkeypatch.setattr(+ pipeline_mod, "MicrophoneCapture", lambda **_kwargs: _SilentMic()+ )++ reason = await asyncio.wait_for(pipe._active_realtime_session(), timeout=2.0)++ assert reason == expected+ assert built["session"].allow_classic_fallback is fallback_allowed+++# ── Browser surface ──────────────────────────────────────────────────────────+++def _browser_socket(state) -> _FakeWS:+ return _FakeWS(+ [+ {+ "type": "websocket.receive",+ "text": '{"type":"audio_start","sample_rate":48000}',+ }+ ],+ state=state,+ )+++async def test_browser_failed_realtime_closes_instead_of_billing_api(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ classic = _RecSession()++ class _SubscriptionOnlyRealtime(_RecSession):+ is_realtime = True+ allow_classic_fallback = False++ async def handle_control(self, _msg: dict) -> None:+ raise RuntimeError("simulated subscription transport failure")++ failed = _SubscriptionOnlyRealtime()+ state = _state(classic)+ state.config.voice = SimpleNamespace(mode="realtime")+ monkeypatch.setattr(route_mod, "_build_browser_session", lambda **_kwargs: failed)+ ws = _browser_socket(state)++ await browser_voice_ws(ws)++ assert failed.ended is True+ # The metered stack was never handed the turn.+ assert classic.controls == []+ assert classic.audio == []+ assert {"type": "mode_fallback", "mode": "pipeline"} not in ws.sent_json+ assert any(+ message.get("type") == "provider_error"+ and message.get("error") == _USAGE_FALLBACK_DISABLED_DETAIL+ for message in ws.sent_json+ )+ assert ws.closed == (1011, "automatic API fallback disabled")+++async def test_browser_failed_realtime_still_crosses_when_fallback_is_allowed(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """The mirror: an API-billed primary keeps its classic safety net."""+ classic = _RecSession()++ class _MeteredRealtime(_RecSession):+ is_realtime = True+ allow_classic_fallback = True++ async def handle_control(self, _msg: dict) -> None:+ raise RuntimeError("simulated metered transport failure")++ failed = _MeteredRealtime()+ state = _state(classic)+ state.config.voice = SimpleNamespace(mode="realtime")+ monkeypatch.setattr(route_mod, "_build_browser_session", lambda **_kwargs: failed)+ ws = _browser_socket(state)++ await browser_voice_ws(ws)++ assert failed.ended is True+ assert classic.controls == [{"type": "audio_start", "sample_rate": 48_000}]+ assert {"type": "mode_fallback", "mode": "pipeline"} in ws.sent_json