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): let a refused local voice call explain itself
rubenluetke10-beepfcfe931321f2
diff --git a/jarvis/plugins/realtime/openai_realtime.py b/jarvis/plugins/realtime/openai_realtime.pyindex fe97dc79e2..2a954527d2 100644--- a/jarvis/plugins/realtime/openai_realtime.py+++ b/jarvis/plugins/realtime/openai_realtime.py@@ -1396,6 +1396,34 @@ _LOCAL_CONNECT_RETRY_STEP_S = 2.0#: before the child even exists. Interactive readiness waits only this long;#: the same supervisor operation then continues on its worker thread._LOCAL_MANAGED_PREFLIGHT_WAIT_S = 0.75+#: The cheap proof that a RUNNING server can take this call. Deliberately its+#: own budget rather than the tail of the revive above: a healthy pool answers+#: in milliseconds, while a cold revive spends ~1 s preparing its bounded+#: Ollama model before it even spawns. Sharing one window made a running+#: server inherit the cold server's bill and lose the call to it.+_LOCAL_POOL_PROBE_TIMEOUT_S = 0.35+#: Why the managed server cannot take a call, in the words the USER needs.+#: This text reaches a toast (and the handshake summary) verbatim, so it names+#: the situation and the next step — the internal "duplex capability probe+#: reported unavailable" told nobody what to do (live 2026-08-09 11:50:47).+#: English on purpose: these are backend strings, and the spoken failure+#: sentence is localized separately by the session's language resolver.+_LOCAL_REASON_STARTING = (+ "The local voice server is not answering yet — it is starting in the "+ "background. Try the call again in about a minute."+)+_LOCAL_REASON_BUSY = (+ "The local voice server is still serving another call — its pipeline pool has no free slot."+)+_LOCAL_REASON_NO_CAPACITY = (+ "The local voice server has no usable pipeline — it is still loading "+ "its models, or the pool is wedged and needs a restart."+)+#: Phrased around the existing "needs a server url" marker so the shared+#: classifier lands on NOT_CONFIGURED (a setup gap) instead of a red error.+_LOCAL_REASON_NO_ADDRESS = (+ "The local realtime provider needs a server URL — enter the address on its provider card."+)#: A managed pool that just reported an idle slot should accept the first#: interactive handshake promptly. If that readiness becomes stale, bound the#: race here instead of falling back to the 120-second recovery window. Long@@ -1592,6 +1620,7 @@ class LocalRealtimeProvider:self._model = (model or "").strip()self._launch_command = (launch_command or "").strip()self._managed_interactive_preflight = False+ self._duplex_unavailable_reason = ""# -- factory wiring ----------------------------------------------------@@ -1632,8 +1661,19 @@ class LocalRealtimeProvider:# -- session -----------------------------------------------------------+ @property+ def duplex_unavailable_reason(self) -> str:+ """Why the last probe said no, in a sentence a user can act on.++ Optional capability, read defensively by the session (AP-21: never a+ provider-name check). Empty whenever the last probe said yes.+ """+ return self._duplex_unavailable_reason+async def can_open_duplex_session(self) -> bool:+ self._duplex_unavailable_reason = ""if not self._base_url:+ self._duplex_unavailable_reason = _LOCAL_REASON_NO_ADDRESSreturn Falseif not self._launch_command or not self._server_is_local_process():return True@@ -1655,6 +1695,32 @@ class LocalRealtimeProvider:self._managed_interactive_preflight = True+ def _pool_can_take_this_call() -> bool:+ """The running server's own verdict, asked directly.++ Separate from the revive below so a healthy pool never waits+ behind a spawn it does not need.+ """+ try:+ pool = supervisor.probe_runtime(self._base_url, timeout=_LOCAL_POOL_PROBE_TIMEOUT_S)+ except Exception: # noqa: BLE001 - a probe never breaks voice startup+ log.warning(+ "local-realtime: pool capacity probe failed",+ exc_info=True,+ )+ self._duplex_unavailable_reason = _LOCAL_REASON_STARTING+ return False+ if pool is None:+ self._duplex_unavailable_reason = _LOCAL_REASON_STARTING+ return False+ if int(pool.get("available", 0)) > 0:+ self._duplex_unavailable_reason = ""+ return True+ self._duplex_unavailable_reason = (+ _LOCAL_REASON_BUSY if int(pool.get("in_use", 0)) > 0 else _LOCAL_REASON_NO_CAPACITY+ )+ return False+def _ready_or_warming() -> bool:try:outcome = str(@@ -1700,19 +1766,29 @@ class LocalRealtimeProvider:)task.add_done_callback(_consume_background_start)++ # A server that is already serving answers for itself, in its own+ # budget. Before this the verdict came only from the tail of the+ # revive above, so a running-but-briefly-slow pool was judged by a+ # clock sized for a cold start and lost the call to it.+ if await asyncio.to_thread(_pool_can_take_this_call):+ return Truetry:- return bool(+ if bool(await asyncio.wait_for(asyncio.shield(task),timeout=_LOCAL_MANAGED_PREFLIGHT_WAIT_S,)- )+ ):+ self._duplex_unavailable_reason = ""+ return Trueexcept TimeoutError:log.info("local-realtime: managed server is still starting in the ""background; refusing to hold this call on Connecting")- return False+ self._duplex_unavailable_reason = _LOCAL_REASON_STARTING+ return Falseasync def _resolve_model(self) -> str:"""The configured model, else the first one the server serves.diff --git a/jarvis/realtime/protocol.py b/jarvis/realtime/protocol.pyindex 0df7bf2685..6d9bc914c5 100644--- a/jarvis/realtime/protocol.py+++ b/jarvis/realtime/protocol.py@@ -203,6 +203,18 @@ class RealtimeSession(Protocol):async def close(self) -> None: ...+class RealtimeUnavailableError(RuntimeError):+ """A provider declined the call and already said why, in plain words.++ Carries a sentence written for the USER, not a stack-trace fragment: the+ handshake summary reaches a toast verbatim, and the internal wording+ ("duplex capability probe reported unavailable") named the mechanism+ instead of the situation (live 2026-08-09). The session prints this+ message WITHOUT its exception class name — that is the whole point of+ the distinct type.+ """++@runtime_checkableclass RealtimeProvider(Protocol):"""The plugin entry-point class."""@@ -213,5 +225,11 @@ class RealtimeProvider(Protocol):output_sample_rate: intcredential_candidates: tuple[tuple[str, str | None], ...]+ #: OPTIONAL capability, deliberately NOT part of this Protocol's required+ #: surface (a data member would tighten every ``isinstance`` check and+ #: break third-party adapters): a provider MAY expose a+ #: ``duplex_unavailable_reason`` string explaining its last ``False``.+ #: The session reads it with ``getattr`` and falls back to a generic+ #: sentence — never a provider-name check (AP-21).async def can_open_duplex_session(self) -> bool: ...async def open_session(self, cfg: RealtimeSessionConfig) -> RealtimeSession: ...diff --git a/jarvis/realtime/session.py b/jarvis/realtime/session.pyindex da8e655b7b..5d3060f725 100644--- a/jarvis/realtime/session.py+++ b/jarvis/realtime/session.py@@ -58,7 +58,7 @@ from jarvis.core.turn_language import (validate_output_language,)from jarvis.realtime.audio import StreamingPcm16Resampler-from jarvis.realtime.protocol import RealtimeSessionConfig+from jarvis.realtime.protocol import RealtimeSessionConfig, RealtimeUnavailableErrorfrom jarvis.realtime.scrub_gate import ScrubHoldGatefrom jarvis.sessions.constants import (HANGUP_CLIENT_STOP,@@ -2441,8 +2441,14 @@ class RealtimeVoiceSession:) -> Any:probe = getattr(candidate, "can_open_duplex_session", None)if callable(probe) and not bool(await probe()):- raise RuntimeError(- "duplex capability probe reported unavailable"+ # A provider MAY explain its own refusal (capability,+ # never a provider-name check — AP-21). Whatever it+ # says lands in a user-facing toast verbatim, which is+ # why the generic fallback is a sentence too.+ declared = getattr(candidate, "duplex_unavailable_reason", "")+ raise RealtimeUnavailableError(+ str(declared or "").strip()+ or "The voice engine reported no free capacity right now.")return await candidate.open_session(candidate_config)@@ -2458,7 +2464,14 @@ class RealtimeVoiceSession:) from excexcept Exception as exc: # noqa: BLE001 — cross to the next familyprovider_id = str(getattr(provider, "name", "unknown") or "unknown")- detail = f"{type(exc).__name__}: {safe_preview(exc, max_chars=700)}"+ # A provider that already phrased its refusal for a human keeps+ # that phrasing whole: prefixing it with the exception class+ # turned an actionable sentence back into a stack trace.+ detail = (+ safe_preview(exc, max_chars=700)+ if isinstance(exc, RealtimeUnavailableError)+ else f"{type(exc).__name__}: {safe_preview(exc, max_chars=700)}"+ )last_failed_provider = provider_idself._provider_errors.append(f"{provider_id}: {detail}")status, _alternate_ready = self._prepare_cross_provider_fallback(diff --git a/tests/unit/realtime/test_local_realtime.py b/tests/unit/realtime/test_local_realtime.pyindex 707f79adc1..3817690b12 100644--- a/tests/unit/realtime/test_local_realtime.py+++ b/tests/unit/realtime/test_local_realtime.py@@ -232,6 +232,111 @@ async def test_ready_managed_pool_opens_only_with_idle_capacity(monkeypatch) ->assert await provider.can_open_duplex_session() is False+async def test_a_serving_pool_is_never_judged_by_the_cold_start_clock(+ monkeypatch,+) -> None:+ """A running server answers for itself, in its own budget.++ Live 2026-08-09 11:50:47: the verdict came only from the tail of the+ revive attempt, so a healthy pool waited behind a spawn that first spends+ ~1 s preparing its Ollama model — and lost the 0.75 s interactive window+ to work it did not need.+ """+ import asyncio+ import time++ from jarvis.plugins.realtime import openai_realtime as module+ from jarvis.realtime.local_server import supervisor++ monkeypatch.setattr(module, "_LOCAL_MANAGED_PREFLIGHT_WAIT_S", 0.05)+ monkeypatch.setattr(+ supervisor, "is_managed_launch_command", lambda command: True+ )++ def slow_revive(**kwargs: Any) -> str:+ time.sleep(0.5)+ return "already-running"++ monkeypatch.setattr(supervisor, "ensure_running", slow_revive)+ monkeypatch.setattr(supervisor, "start_runtime_monitor", lambda **kwargs: True)+ monkeypatch.setattr(+ supervisor,+ "probe_runtime",+ lambda *args, **kwargs: {+ "size": 1,+ "in_use": 0,+ "available": 1,+ "active": 0,+ },+ )+ provider = LocalRealtimeProvider(+ base_url="http://127.0.0.1:8765",+ launch_command="managed-server --mode realtime",+ )++ assert (+ await asyncio.wait_for(provider.can_open_duplex_session(), timeout=0.3)+ is True+ )+ assert provider.duplex_unavailable_reason == ""+ await asyncio.gather(*LocalRealtimeProvider._background_start_tasks)+++async def test_a_refusal_explains_itself_in_words_a_user_can_act_on(+ monkeypatch,+) -> None:+ """Each refusal names a DIFFERENT next step, so it may not be one text."""+ from jarvis.plugins.realtime import openai_realtime as module+ from jarvis.realtime.local_server import supervisor++ monkeypatch.setattr(+ supervisor, "is_managed_launch_command", lambda command: True+ )+ monkeypatch.setattr(+ supervisor, "ensure_running", lambda **kwargs: "already-running"+ )+ monkeypatch.setattr(supervisor, "start_runtime_monitor", lambda **kwargs: True)++ pool: dict[str, int] | None = None+ monkeypatch.setattr(supervisor, "probe_runtime", lambda *args, **kwargs: pool)+ provider = LocalRealtimeProvider(+ base_url="http://127.0.0.1:8765",+ launch_command="managed-server --mode realtime",+ )++ # No pool at all: the server is cold and somebody is starting it.+ assert await provider.can_open_duplex_session() is False+ assert provider.duplex_unavailable_reason == module._LOCAL_REASON_STARTING++ # Every slot in use: healthy, just occupied — a different situation.+ pool = {"size": 1, "in_use": 1, "available": 0, "active": 1}+ assert await provider.can_open_duplex_session() is False+ assert provider.duplex_unavailable_reason == module._LOCAL_REASON_BUSY++ # Slots exist, none usable, nobody served: loading or wedged.+ pool = {"size": 1, "in_use": 0, "available": 0, "active": 0}+ assert await provider.can_open_duplex_session() is False+ assert provider.duplex_unavailable_reason == module._LOCAL_REASON_NO_CAPACITY++ # Recovery clears the explanation instead of leaving a stale one behind.+ pool = {"size": 1, "in_use": 0, "available": 1, "active": 0}+ assert await provider.can_open_duplex_session() is True+ assert provider.duplex_unavailable_reason == ""+++async def test_a_missing_address_reads_as_a_setup_gap_not_an_outage() -> None:+ from jarvis.brain.provider_test import NOT_CONFIGURED, classify_provider_error++ provider = LocalRealtimeProvider()++ assert await provider.can_open_duplex_session() is False+ reason = provider.duplex_unavailable_reason+ assert "server URL" in reason+ # The shared classifier must read this as "finish the setup", which is+ # what routes it to the actionable amber instead of a red error.+ assert classify_provider_error(reason) == NOT_CONFIGURED++async def test_byo_server_never_requires_the_private_pool(monkeypatch) -> None:from jarvis.realtime.local_server import supervisordiff --git a/tests/unit/realtime/test_session.py b/tests/unit/realtime/test_session.pyindex 8ba57da3ce..94f417bb95 100644--- a/tests/unit/realtime/test_session.py+++ b/tests/unit/realtime/test_session.py@@ -493,6 +493,87 @@ async def test_total_handshake_failure_emits_audio_failed():assert failed["recoverable"] is True+class UnavailableWithReasonProvider(FakeProvider):+ """Declines and says why — the optional explanation capability."""++ name = "explaining-family"+ duplex_unavailable_reason = (+ "The local voice server is not answering yet — it is starting in the "+ "background. Try the call again in about a minute."+ )++ async def can_open_duplex_session(self):+ return False+++class MuteUnavailableProvider(FakeProvider):+ """Declines without explaining — the generic sentence must cover it."""++ name = "mute-family"++ async def can_open_duplex_session(self):+ return False+++async def test_declined_probe_surfaces_the_providers_own_sentence():+ """The handshake summary reaches a user-facing toast verbatim.++ Live 2026-08-09: a cold managed server ended the call with "RuntimeError:+ duplex capability probe reported unavailable" — the mechanism, not the+ situation, and no next step. A provider that phrases its own refusal keeps+ that phrasing whole, exception class name included nowhere.+ """+ messages = []+ sess = RealtimeVoiceSession(+ session_id="explained-decline",+ send_binary=lambda _data: asyncio.sleep(0),+ send_json=lambda message: messages.append(message) or asyncio.sleep(0),+ providers=[UnavailableWithReasonProvider([])],+ config=_cfg(),+ bus=None,+ )++ try:+ await sess.handle_control({"type": "audio_start", "sample_rate": 16_000})+ except RuntimeError:+ pass # the raise stays — only the wording is under test+ await sess.end(reason="test")++ failed = next(+ message for message in messages if message.get("type") == "audio_failed"+ )+ assert "starting in the background" in failed["error"]+ assert "Try the call again" in failed["error"]+ assert "RuntimeError" not in failed["error"]+ assert "duplex" not in failed["error"].lower()+++async def test_silent_decline_still_reads_as_a_sentence():+ messages = []+ sess = RealtimeVoiceSession(+ session_id="mute-decline",+ send_binary=lambda _data: asyncio.sleep(0),+ send_json=lambda message: messages.append(message) or asyncio.sleep(0),+ providers=[MuteUnavailableProvider([])],+ config=_cfg(),+ bus=None,+ )++ try:+ await sess.handle_control({"type": "audio_start", "sample_rate": 16_000})+ except RuntimeError:+ pass+ await sess.end(reason="test")++ failed = next(+ message for message in messages if message.get("type") == "audio_failed"+ )+ assert "no free capacity" in failed["error"]+ assert "RuntimeError" not in failed["error"]++@pytest.mark.asyncioasync def test_fallback_status_redacts_credentials_from_provider_errors():fallback = FakeProvider([])