Skip to content

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.

fix(realtime): fail stale local-realtime installs fast and surface connect errors

rubenluetke10-beep984a6f27a4e6
diff --git a/jarvis/plugins/realtime/openai_realtime.py b/jarvis/plugins/realtime/openai_realtime.py
index 633ba6c7fa..d830e317dd 100644
--- a/jarvis/plugins/realtime/openai_realtime.py
+++ b/jarvis/plugins/realtime/openai_realtime.py
@@ -1261,6 +1261,58 @@ _LOCAL_CONNECT_RETRY_STEP_S = 2.0
_LOCAL_LAUNCH_MIN_INTERVAL_S = 60.0
+def _launch_command_target_state(command: str) -> str:
+ """Whether the program a launch command names still exists on this machine.
+
+ ``"missing"`` means the command's first token clearly names something that
+ is gone — a managed install whose tree was deleted while its command stayed
+ in jarvis.toml previously sat out the full patient reconnect window against
+ a spawn that could never succeed (live 2026-08-08: 120 s of "Connecting…"
+ ending in a silent idle). ``"present"`` means the target resolves today.
+ Everything ambiguous returns ``"unknown"`` and behaves exactly as before —
+ fail-open, so a bring-your-own command is never misjudged. Stdlib only.
+ """
+ text = (command or "").strip()
+ if not text:
+ return "unknown"
+ import shlex
+ import shutil
+ from pathlib import Path
+
+ head = ""
+ if text.startswith('"'):
+ # The managed installer always quotes its entry point; a quoted head
+ # is unambiguous on every platform.
+ end = text.find('"', 1)
+ if end > 1:
+ head = text[1:end]
+ elif os.name == "nt":
+ # Raw-string spawn: take the first whitespace token. An UNQUOTED path
+ # containing spaces is handled below (fail-open) because CreateProcess
+ # prefix probing makes it genuinely ambiguous.
+ head = text.split()[0]
+ else:
+ try:
+ head = (shlex.split(text) or [""])[0]
+ except ValueError:
+ return "unknown"
+ if not head:
+ return "unknown"
+ looks_pathlike = "/" in head or "\\" in head or (os.name == "nt" and ":" in head[:3])
+ if looks_pathlike:
+ if Path(head).exists():
+ return "present"
+ if os.name == "nt" and not text.startswith('"') and " " in text:
+ # Unquoted Windows command with spaces: the naive first token may
+ # have cut a spaced path short — cannot tell, so do not judge.
+ return "unknown"
+ return "missing"
+ # A bare program name resolves through PATH. Found → present; not found →
+ # still only "unknown": PATH resolution has too many shells and edge cases
+ # to declare a user-authored command dead on its account.
+ return "present" if shutil.which(head) else "unknown"
+
+
def _normalize_local_root(url: str) -> str:
"""Normalize a user-entered server address to an ``…/v1`` API root.
@@ -1434,10 +1486,15 @@ class LocalRealtimeProvider:
Patient only when patience can pay off: with a ``launch_command``
Jarvis revives a crashed server itself and the retries bridge its
- warm-up. Without one nothing will change on the other end, so a
- short window rides out a hiccup and then reports honestly.
+ warm-up. Without one — or with a command whose program provably no
+ longer exists (deleted managed install) — nothing will change on the
+ other end, so a short window rides out a hiccup and then reports
+ honestly.
"""
- if self._launch_command:
+ if (
+ self._launch_command
+ and _launch_command_target_state(self._launch_command) != "missing"
+ ):
return _LOCAL_CONNECT_PATIENT_WINDOW_S
return _LOCAL_CONNECT_SHORT_WINDOW_S
@@ -1589,6 +1646,25 @@ class LocalRealtimeProvider:
remaining = deadline - time.monotonic()
if remaining <= 0:
raise
+ # A connect failure with a launch command whose program no
+ # longer exists can never be retried into success: reviving
+ # would spawn a deleted entry point. Fail NOW with the fixing
+ # action instead of holding the call in "Connecting…" for the
+ # whole patient window (live 2026-08-08: the managed install
+ # tree was gone while jarvis.toml still pointed at it).
+ if (
+ self._launch_command
+ and self._server_is_local_process()
+ and _launch_command_target_state(self._launch_command)
+ == "missing"
+ ):
+ raise RuntimeError(
+ "The local realtime server is not installed anymore: "
+ "its configured launch command points at a program "
+ "that does not exist. Reinstall the managed server on "
+ "the local-realtime provider card, or clear its "
+ "launch command."
+ ) from exc
# First failure: the server may simply be gone — revive it if
# this install owns it, then keep knocking. A server that is
# merely warming up needs the same patience either way.
diff --git a/jarvis/realtime/local_server/install.py b/jarvis/realtime/local_server/install.py
index 8d5c394a4b..cad8cb509d 100644
--- a/jarvis/realtime/local_server/install.py
+++ b/jarvis/realtime/local_server/install.py
@@ -152,13 +152,43 @@ def snapshot() -> dict[str, object]:
}
+def _configured_launch_command() -> str:
+ """The persisted local-realtime launch command, read cheaply and safely.
+
+ A plain TOML read (no full config model) because this runs inside status
+ probes: the only question is whether jarvis.toml still points a launch
+ command at the managed tree. Any read problem answers "" — the status then
+ simply reports without the staleness refinement (fail-open).
+ """
+ try:
+ import tomllib
+
+ from jarvis.core.config import resolve_config_path
+
+ path = resolve_config_path()
+ if not path.exists():
+ return ""
+ with open(path, "rb") as fh:
+ data = tomllib.load(fh)
+ providers = (data.get("brain") or {}).get("providers") or {}
+ block = providers.get("local-realtime") or {}
+ return str(block.get("launch_command") or "").strip()
+ except Exception: # noqa: BLE001 — a status probe must never raise
+ log.debug("local-realtime: launch-command read failed", exc_info=True)
+ return ""
+
+
def server_status() -> dict[str, object]:
"""Fail-closed readiness of the managed install (read-only, no network).
Ready means ALL of: venv python present, server entry point present,
vendored patch applied, and a recorded successful smoke boot. Each
component is reported separately so the card can say exactly what is
- missing, in the server's words.
+ missing, in the server's words. ``stale`` flags the poisonous variant:
+ jarvis.toml still carries a launch command pointing into this tree while
+ the install files are gone (live 2026-08-08 — every call then chased a
+ deleted entry point), which deserves a repair sentence, not "not
+ installed".
"""
components = {
"venv": _venv_python().exists(),
@@ -167,17 +197,30 @@ def server_status() -> dict[str, object]:
"smoke_boot": _smoke_marker().exists(),
}
ready = all(components.values())
+ command = _configured_launch_command()
+ root_needle = str(install_root()).lower() if os.name == "nt" else str(install_root())
+ command_probe = command.lower() if os.name == "nt" else command
+ stale = (
+ not components["entrypoint"]
+ and bool(command)
+ and root_needle in command_probe.replace("/", os.sep)
+ )
if ready:
sentence = (
f"Managed server installed (speech-to-speech {PATCH_TARGET_VERSION}, "
"patched) and smoke-booted."
)
+ elif stale:
+ sentence = (
+ "Install files are missing but the launch command still points at "
+ "them — reinstall to repair, or remove the local server."
+ )
elif not components["venv"] and not components["entrypoint"]:
sentence = "Managed server not installed."
else:
missing = ", ".join(name for name, present in components.items() if not present)
sentence = f"Managed server incomplete: {missing} missing — reinstall to repair."
- return {"ready": ready, "components": components, "sentence": sentence}
+ return {"ready": ready, "stale": stale, "components": components, "sentence": sentence}
def derive_launch_command(brain: BrainResolution, *, memory_source: str) -> str:
diff --git a/jarvis/realtime/session.py b/jarvis/realtime/session.py
index d03a8099df..83a63a99f0 100644
--- a/jarvis/realtime/session.py
+++ b/jarvis/realtime/session.py
@@ -751,9 +751,9 @@ _DELEGATE_BRIDGE_TEXTS: dict[str, tuple[str, ...]] = {
#: call used to end after the full handshake budget with nothing said at all.
_HANDSHAKE_FAILURE_MESSAGES: dict[str, dict[str, str]] = {
"timeout": {
- "de": (
- "Die Sprachverbindung kam nicht rechtzeitig zustande, " # i18n-allow: localized runtime voice output
- "deshalb habe ich abgebrochen."
+ "de": ( # i18n-allow: localized runtime voice output
+ "Die Sprachverbindung kam nicht rechtzeitig zustande, " # i18n-allow
+ "deshalb habe ich abgebrochen." # i18n-allow
),
"en": (
"The voice connection did not come up in time, so I stopped."
@@ -763,8 +763,8 @@ _HANDSHAKE_FAILURE_MESSAGES: dict[str, dict[str, str]] = {
),
},
"unavailable": {
- "de": (
- "Ich konnte die Sprachverbindung gerade nicht aufbauen." # i18n-allow: localized runtime voice output
+ "de": ( # i18n-allow: localized runtime voice output
+ "Ich konnte die Sprachverbindung gerade nicht aufbauen." # i18n-allow
),
"en": "I couldn't establish the voice connection just now.",
"es": ( # i18n-allow: localized runtime voice output
@@ -2068,6 +2068,7 @@ class RealtimeVoiceSession:
deadline = loop.time() + max(
_PROVIDER_HANDSHAKE_TOTAL_TIMEOUT_S, declared_total
)
+ last_failed_provider = ""
for provider in self._providers:
if not self._provider_is_available(provider):
continue
@@ -2153,6 +2154,7 @@ class RealtimeVoiceSession:
except Exception as exc: # noqa: BLE001 — cross to the next family
provider_id = str(getattr(provider, "name", "unknown") or "unknown")
detail = f"{type(exc).__name__}: {safe_preview(exc, max_chars=700)}"
+ last_failed_provider = provider_id
self._provider_errors.append(f"{provider_id}: {detail}")
status, _alternate_ready = self._prepare_cross_provider_fallback(
provider,
@@ -2185,6 +2187,20 @@ class RealtimeVoiceSession:
return
summary = "; ".join(self._provider_errors) or "no provider could open a session"
+ # Terminal frame for the surfaces: without it the desktop status rows
+ # only ever saw audio_starting and then silence — the connecting look
+ # expired into idle with no reason shown (live 2026-08-08).
+ try:
+ await self._send_json(
+ {
+ "type": "audio_failed",
+ "provider": last_failed_provider,
+ "error": summary,
+ "recoverable": True,
+ }
+ )
+ except Exception: # noqa: BLE001, S110 — status is best-effort
+ pass
await self._publish_error("RealtimeHandshakeError", summary, recoverable=True)
await self._announce_handshake_failure(summary)
raise RuntimeError(f"No realtime provider could open a session: {summary}")
diff --git a/jarvis/speech/pipeline.py b/jarvis/speech/pipeline.py
index f6f7f0bdad..865ca64ae0 100644
--- a/jarvis/speech/pipeline.py
+++ b/jarvis/speech/pipeline.py
@@ -5960,6 +5960,11 @@ class SpeechPipeline:
getattr(self, "_voice_engine_transitioning", False)
or getattr(self, "_reopen_after_engine_change", False)
),
+ # Why the LAST realtime start attempt failed (None once a session
+ # is up): {provider, message, at}. The surfaces render it when a
+ # connecting window closes without a session instead of falling
+ # silently back to "idle".
+ "last_start_error": getattr(self, "_last_realtime_start_error", None),
}
def apply_voice_mode(self, mode: str) -> bool:
@@ -7977,6 +7982,8 @@ class SpeechPipeline:
)
self._active_realtime_model = str(message.get("model", "") or "")
self._voice_engine_transitioning = False
+ # A session is up — whatever failed on the way here is history.
+ self._last_realtime_start_error = None
log.info(
"Realtime desktop session ready: provider=%s model=%s input=%sHz output=%sHz",
message.get("provider", "unknown"),
@@ -8016,6 +8023,24 @@ class SpeechPipeline:
preserve_echo_tail=speaking,
)
await self._set_turn_state(TurnTakingState.PROCESSING)
+ elif kind == "provider_fallback":
+ # One provider's handshake failed; the session may still cross
+ # to the next family. Recorded so the status surfaces can name
+ # the reason if nothing comes up — audio_ready clears it.
+ self._last_realtime_start_error = {
+ "provider": str(message.get("provider", "") or ""),
+ "message": str(message.get("error", "") or ""),
+ "at": time.time(),
+ }
+ elif kind == "audio_failed":
+ # Terminal: no provider could open a session. Without this
+ # branch the desktop surfaces watched the connecting window
+ # expire into idle with no reason shown (live 2026-08-08).
+ self._last_realtime_start_error = {
+ "provider": str(message.get("provider", "") or ""),
+ "message": str(message.get("error", "") or ""),
+ "at": time.time(),
+ }
elif kind == "tts_cancel":
_close_output_segment(preserve_echo_tail=False)
await _cancel_output_playback()
diff --git a/jarvis/ui/web/frontend/src/hooks/useVoiceMode.ts b/jarvis/ui/web/frontend/src/hooks/useVoiceMode.ts
index a84eb27013..551470720a 100644
--- a/jarvis/ui/web/frontend/src/hooks/useVoiceMode.ts
+++ b/jarvis/ui/web/frontend/src/hooks/useVoiceMode.ts
@@ -39,6 +39,17 @@ type VoiceModeResp = {
active_session_model: string;
active_session_model_label?: string | null;
transitioning: boolean;
+ /**
+ * Why the LAST realtime start attempt failed ({provider, message, at} or
+ * null once a session is up). Rendered when the connecting window closes
+ * without a session — before this field those attempts fell back to the
+ * "no voice session is active" idle line with no reason shown.
+ */
+ last_start_error?: {
+ provider: string;
+ message: string;
+ at: number;
+ } | null;
};
const REALTIME_DISCOVERY_RETRY_WINDOW_MS = 5 * 60_000;
@@ -311,6 +322,11 @@ export function useVoiceMode() {
activeSessionModel:
q.data?.active_session_model_label ?? q.data?.active_session_model ?? "",
transitioning,
+ /** Failure detail of the last start attempt; null while connecting or live. */
+ lastStartError:
+ !sessionActive && !(transitioning || startPending)
+ ? q.data?.last_start_error ?? null
+ : null,
setMode: m.mutate,
isLoading: q.isLoading,
isSaving: m.isPending,
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/de.json b/jarvis/ui/web/frontend/src/i18n/locales/de.json
index 6c3d8128fa..72e65b6daa 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/de.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/de.json
@@ -399,6 +399,7 @@
"warming_hint": "Das Zuhören wird vorbereitet – einen Moment, gleich kannst du sprechen.",
"ready_title": "Bereit – du kannst jetzt sprechen",
"connecting": "Verbinde…",
+ "connect_failed": "Sprachverbindung fehlgeschlagen ({0}): {1}",
"paused": "Pausiert",
"indicator_label": "Sprachstatus"
},
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/en.json b/jarvis/ui/web/frontend/src/i18n/locales/en.json
index 652dfbefa3..6ecd11f200 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/en.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/en.json
@@ -399,6 +399,7 @@
"warming_hint": "Getting ready to listen – one moment, you'll be able to speak shortly.",
"ready_title": "Ready – you can speak now",
"connecting": "Connecting…",
+ "connect_failed": "Voice connect failed ({0}): {1}",
"paused": "Paused",
"indicator_label": "Voice state"
},
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/es.json b/jarvis/ui/web/frontend/src/i18n/locales/es.json
index f41a3d091e..2a10df6d2b 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/es.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/es.json
@@ -399,6 +399,7 @@
"warming_hint": "Preparando la escucha – un momento, podrás hablar en breve.",
"ready_title": "Listo – ya puedes hablar",
"connecting": "Conectando…",
+ "connect_failed": "La conexión de voz falló ({0}): {1}",
"paused": "En pausa",
"indicator_label": "Estado de voz"
},
diff --git a/jarvis/ui/web/frontend/src/views/ApiKeysView.tsx b/jarvis/ui/web/frontend/src/views/ApiKeysView.tsx
index dbf1e03af8..45aa1781b3 100644
--- a/jarvis/ui/web/frontend/src/views/ApiKeysView.tsx
+++ b/jarvis/ui/web/frontend/src/views/ApiKeysView.tsx
@@ -96,6 +96,7 @@ export function ApiKeysView() {
activeSessionProvider,
activeSessionModel,
transitioning,
+ lastStartError,
setMode: setVoiceMode,
isLoading: liveModeLoading,
} = useVoiceMode();
@@ -171,6 +172,7 @@ export function ApiKeysView() {
activeSessionProvider={activeSessionProvider}
activeSessionModel={activeSessionModel}
transitioning={transitioning}
+ lastStartError={lastStartError}
liveMode={liveMode}
onOpenRecommendedTab={openRecommendedTab}
/>
diff --git a/jarvis/ui/web/frontend/src/views/settings/RealtimeVoiceGroup.tsx b/jarvis/ui/web/frontend/src/views/settings/RealtimeVoiceGroup.tsx
index df10420669..aa3f6e3d8f 100644
--- a/jarvis/ui/web/frontend/src/views/settings/RealtimeVoiceGroup.tsx
+++ b/jarvis/ui/web/frontend/src/views/settings/RealtimeVoiceGroup.tsx
@@ -29,6 +29,7 @@ export function RealtimeVoiceGroup() {
activeSessionProvider,
activeSessionModel,
transitioning,
+ lastStartError,
setMode,
isLoading,
isSaving,
@@ -83,6 +84,17 @@ export function RealtimeVoiceGroup() {
<p className="mt-1.5 text-[11px] text-muted-foreground" aria-live="polite">
{runtimeText}
</p>
+ {on && lastStartError && (
+ <p
+ data-testid="realtime-last-start-error"
+ className="mt-1 text-[11px] leading-snug text-amber-600 dark:text-amber-400"
+ aria-live="polite"
+ >
+ {t("voice_state.connect_failed")
+ .replace("{0}", lastStartError.provider || "?")
+ .replace("{1}", lastStartError.message)}
+ </p>
+ )}
{offerDetail && (
<p
data-testid="realtime-transport-offer-detail"
diff --git a/jarvis/ui/web/settings_routes.py b/jarvis/ui/web/settings_routes.py
index d967d4772d..16015f3118 100644
--- a/jarvis/ui/web/settings_routes.py
+++ b/jarvis/ui/web/settings_routes.py
@@ -318,6 +318,10 @@ async def get_voice_mode(request: Request) -> dict[str, object]:
session_provider, session_model
),
"transitioning": bool(runtime.get("transitioning", False)),
+ # Why the last realtime start attempt failed ({provider, message, at}
+ # or null): rendered by the surfaces when a connecting window closes
+ # without a session instead of a silent fall-back to "idle".
+ "last_start_error": runtime.get("last_start_error"),
}
diff --git a/tests/unit/realtime/local_server/test_engine.py b/tests/unit/realtime/local_server/test_engine.py
index 4b14aace18..1622366a2d 100644
--- a/tests/unit/realtime/local_server/test_engine.py
+++ b/tests/unit/realtime/local_server/test_engine.py
@@ -169,6 +169,51 @@ class TestServerStatusFailClosed:
assert components["venv"] is True # type: ignore[index]
assert components["patch"] is False # type: ignore[index]
+ def test_stale_config_earns_the_repair_sentence(
+ self, monkeypatch, tmp_path: Path
+ ) -> None:
+ """Install files gone while jarvis.toml still points a launch command
+ at them (live 2026-08-08): the card must say "repair", not the
+ misleading "not installed"."""
+ import json
+
+ monkeypatch.setenv("JARVIS_DATA_DIR", str(tmp_path))
+ command = str(
+ install.install_root() / "venv" / "Scripts" / "speech-to-speech.exe"
+ )
+ quoted = f'"{command}" --mode realtime'
+ cfg = tmp_path / "jarvis.toml"
+ cfg.write_text(
+ "[brain.providers.local-realtime]\n"
+ f"launch_command = {json.dumps(quoted)}\n",
+ encoding="utf-8",
+ )
+ import jarvis.core.config as config_module
+
+ monkeypatch.setattr(config_module, "resolve_config_path", lambda: cfg)
+ status = install.server_status()
+ assert status["ready"] is False
+ assert status["stale"] is True
+ assert "reinstall to repair" in str(status["sentence"])
+
+ def test_a_foreign_launch_command_is_never_called_stale(
+ self, monkeypatch, tmp_path: Path
+ ) -> None:
+ """A bring-your-own command (docker, another tree) must keep the
+ plain "not installed" sentence — staleness is a MANAGED concept."""
+ monkeypatch.setenv("JARVIS_DATA_DIR", str(tmp_path))
+ cfg = tmp_path / "jarvis.toml"
+ cfg.write_text(
+ '[brain.providers.local-realtime]\nlaunch_command = "docker run my-server"\n',
+ encoding="utf-8",
+ )
+ import jarvis.core.config as config_module
+
+ monkeypatch.setattr(config_module, "resolve_config_path", lambda: cfg)
+ status = install.server_status()
+ assert status["stale"] is False
+ assert status["sentence"] == "Managed server not installed."
+
def test_uninstall_refuses_while_running(self, monkeypatch) -> None:
class _Alive:
@staticmethod
diff --git a/tests/unit/realtime/test_local_realtime.py b/tests/unit/realtime/test_local_realtime.py
index 2c1ce963f1..1e21d167c8 100644
--- a/tests/unit/realtime/test_local_realtime.py
+++ b/tests/unit/realtime/test_local_realtime.py
@@ -426,3 +426,88 @@ def test_declared_handshake_budget_covers_the_patient_window() -> None:
base_url="http://localhost:8765", launch_command="serve"
)
assert patient.handshake_budget_s > patient._connect_retry_window_s()
+
+
+# ── Stale launch commands (deleted managed install) ──────────────────────
+def test_launch_command_state_missing_for_a_deleted_path(tmp_path) -> None:
+ """A quoted path whose target is gone is exactly the deleted managed
+ install of 2026-08-08 — the one case that must be judged decisively."""
+ from jarvis.plugins.realtime import openai_realtime as module
+
+ gone = tmp_path / "venv" / "Scripts" / "speech-to-speech.exe"
+ assert (
+ module._launch_command_target_state(f'"{gone}" --mode realtime') == "missing"
+ )
+
+
+def test_launch_command_state_present_for_an_existing_path(tmp_path) -> None:
+ from jarvis.plugins.realtime import openai_realtime as module
+
+ exe = tmp_path / "server"
+ exe.write_bytes(b"")
+ assert module._launch_command_target_state(f'"{exe}" --flag') == "present"
+
+
+def test_launch_command_state_fails_open_on_ambiguity() -> None:
+ """Bare names and empty commands are never judged: a bring-your-own
+ command must keep exactly the pre-fix behavior."""
+ from jarvis.plugins.realtime import openai_realtime as module
+
+ assert module._launch_command_target_state("serve --flag") == "unknown"
+ assert module._launch_command_target_state("") == "unknown"
+ assert module._launch_command_target_state('"unclosed --flag') == "unknown"
+
+
+def test_a_stale_install_shrinks_the_retry_window(tmp_path) -> None:
+ """Patience only pays when the revive could ever succeed; a deleted
+ entry point earns the short window, not 120 s of knocking."""
+ from jarvis.plugins.realtime import openai_realtime as module
+
+ gone = tmp_path / "venv" / "Scripts" / "speech-to-speech.exe"
+ stale = LocalRealtimeProvider(
+ base_url="http://localhost:8765", launch_command=f'"{gone}" --mode realtime'
+ )
+ assert stale._connect_retry_window_s() == module._LOCAL_CONNECT_SHORT_WINDOW_S
+
+
+async def test_a_stale_install_fails_fast_with_the_fixing_action(
+ monkeypatch, tmp_path
+) -> None:
+ """The first refused connect against a deleted install must end the
+ attempt with the fixing action — not sit out any retry window (live
+ 2026-08-08: 120 s of "Connecting…" ending in a silent idle)."""
+ from jarvis.plugins.realtime import openai_realtime as module
+
+ monkeypatch.setattr(module, "_LOCAL_CONNECT_RETRY_STEP_S", 0.0)
+ gone = tmp_path / "venv" / "Scripts" / "speech-to-speech.exe"
+ provider = LocalRealtimeProvider(
+ base_url="http://localhost:8765", launch_command=f'"{gone}" --mode realtime'
+ )
+ attempts = 0
+
+ async def refused(cfg: Any) -> str:
+ nonlocal attempts
+ attempts += 1
+ raise ConnectionError("refused")
+
+ monkeypatch.setattr(provider, "_open_session_once", refused)
+ with pytest.raises(RuntimeError, match="not installed anymore"):
+ await provider.open_session(SimpleNamespace(model="m"))
+ assert attempts == 1
+
+
+async def test_a_running_orphan_still_connects_despite_a_stale_command(
+ monkeypatch, tmp_path
+) -> None:
+ """A server that outlived its deleted install keeps serving; the stale
+ check must only fire once a connect actually FAILED."""
+ gone = tmp_path / "venv" / "Scripts" / "speech-to-speech.exe"
+ provider = LocalRealtimeProvider(
+ base_url="http://localhost:8765", launch_command=f'"{gone}" --mode realtime'
+ )
+
+ async def healthy(cfg: Any) -> str:
+ return "session"
+
+ monkeypatch.setattr(provider, "_open_session_once", healthy)
+ assert await provider.open_session(SimpleNamespace(model="m")) == "session"
diff --git a/tests/unit/realtime/test_session.py b/tests/unit/realtime/test_session.py
index 4582b79920..fbc712ae51 100644
--- a/tests/unit/realtime/test_session.py
+++ b/tests/unit/realtime/test_session.py
@@ -462,6 +462,36 @@ async def test_handshake_timeout_preserves_budget_for_next_family(monkeypatch):
assert "handshake exceeded" in fallback_status["error"]
+async def test_total_handshake_failure_emits_audio_failed():
+ """When EVERY provider fails, the surfaces get a terminal frame naming
+ the last provider and the reason — before it, the desktop status rows
+ watched their connecting window expire into idle with nothing shown
+ (live 2026-08-08)."""
+ messages = []
+ sess = RealtimeVoiceSession(
+ session_id="all-fail",
+ send_binary=lambda _data: asyncio.sleep(0),
+ send_json=lambda message: messages.append(message) or asyncio.sleep(0),
+ providers=[FailingProvider([])],
+ config=_cfg(),
+ bus=None,
+ )
+
+ try:
+ await sess.handle_control({"type": "audio_start", "sample_rate": 16_000})
+ except RuntimeError:
+ pass # the raise stays — only the frame emission is under test
+ await sess.end(reason="test")
+
+ failed = next(
+ message for message in messages if message.get("type") == "audio_failed"
+ )
+ assert failed["provider"] == "failing-family"
+ assert "simulated depleted credits" in failed["error"]
+ assert failed["recoverable"] is True
+
+
@pytest.mark.asyncio
async def test_fallback_status_redacts_credentials_from_provider_errors():
fallback = FakeProvider([])