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(voice): bound realtime session teardown so a bar-X hangup can't freeze the bar + deafen wake

Ruben Lütke800228345d93
diff --git a/jarvis/mcp/client.py b/jarvis/mcp/client.py
index e613df6981..2ccfebf974 100644
--- a/jarvis/mcp/client.py
+++ b/jarvis/mcp/client.py
@@ -88,6 +88,11 @@ def _read_call_timeout_s() -> float:
# Module-level so a test can monkeypatch it and call_tool re-reads it each call.
_CALL_TIMEOUT_S = _read_call_timeout_s()
+# Hard ceiling for stop(): the transport's anyio task group can stall for ~20 s
+# on a cross-task cancel-scope exit (see stop()). Module-level so a test can
+# monkeypatch it; stop() re-reads it each call.
+_STOP_TIMEOUT_S = 5.0
+
# Matches ``$NAME`` secret placeholders inside http header values, e.g.
# ``"Bearer $ZAPIER_TOKEN"`` → the ``ZAPIER_TOKEN`` group.
_SECRET_TOKEN_RE = re.compile(r"\$([A-Z_][A-Z0-9_]*)")
@@ -182,11 +187,31 @@ class MCPClient:
raise
async def stop(self) -> None:
- """Close the session and transport cleanly."""
+ """Close the session and transport cleanly.
+
+ Bounded by a hard timeout: the MCP SDK's ``streamablehttp_client`` wraps
+ its transport in an ``anyio`` task group whose cancel scope must be
+ entered and exited on the SAME task. When ``aclose()`` runs on a
+ different task than ``start()`` did, the exit both raises
+ ``RuntimeError: Attempted to exit cancel scope in a different task`` AND
+ can stall for ~20 s first while the underlying HTTP stream drains. If
+ that close is awaited unbounded on a load-bearing teardown path (a voice
+ session end, app shutdown), the whole teardown hangs — the live symptom
+ was a bar-X hangup of a realtime session freezing the JarvisBar on
+ "listening" and deafening wake for ~20 s (2026-07-23). Abandon the
+ transport on timeout so no caller can ever hang on it.
+ """
if self._exit_stack is None:
return
try:
- await self._exit_stack.aclose()
+ await asyncio.wait_for(self._exit_stack.aclose(), timeout=_STOP_TIMEOUT_S)
+ except TimeoutError:
+ log.warning(
+ "MCPClient[%s] stop timed out after %.1fs — abandoning the "
+ "transport so teardown/shutdown cannot hang",
+ self.spec.name,
+ _STOP_TIMEOUT_S,
+ )
except Exception as e: # noqa: BLE001
log.warning("MCPClient[%s] stop error: %s", self.spec.name, e)
finally:
diff --git a/jarvis/realtime/session.py b/jarvis/realtime/session.py
index 196c1e9080..2c48cd3ea3 100644
--- a/jarvis/realtime/session.py
+++ b/jarvis/realtime/session.py
@@ -5111,11 +5111,33 @@ class RealtimeVoiceSession:
# transcript text but before its turn_complete marker. Freeze the
# accumulated values into VoiceTurnCompleted before the logical session
# end lets SessionRecorder finalize the row.
- await self._publish_turn_completed()
+ try:
+ await asyncio.wait_for(self._publish_turn_completed(), timeout=3.0)
+ except TimeoutError:
+ log.warning(
+ "realtime[%s] publish_turn_completed timed out during end(); "
+ "continuing teardown",
+ self.session_id,
+ )
+ except Exception: # noqa: BLE001, S110 — best-effort teardown
+ pass
self._delegate_turns.clear()
if self._session is not None:
+ # The provider socket close (e.g. a gemini-live WebSocket) can stall
+ # when the session is torn down moments after it went ready — a bar-X
+ # hangup racing the just-completed handshake. Unbounded, that stall
+ # blocks the whole session end, so the supervisor never returns to
+ # IDLE, the JarvisBar freezes on its "listening" look and wake stays
+ # deaf until the socket eventually gives up (~20 s live 2026-07-23).
+ # Bound it: abandon the socket so the hangup always completes.
try:
- await self._session.close()
+ await asyncio.wait_for(self._session.close(), timeout=5.0)
+ except TimeoutError:
+ log.warning(
+ "realtime[%s] provider close timed out during end(); "
+ "abandoning the socket so hangup can complete",
+ self.session_id,
+ )
except Exception: # noqa: BLE001, S110 — best-effort teardown
pass
if self._tool_bridge is not None:
diff --git a/jarvis/speech/pipeline.py b/jarvis/speech/pipeline.py
index 5193fd1a4d..fc3746dff3 100644
--- a/jarvis/speech/pipeline.py
+++ b/jarvis/speech/pipeline.py
@@ -6853,7 +6853,24 @@ class SpeechPipeline:
except (asyncio.CancelledError, Exception): # noqa: S110 - teardown
pass
if session is not None:
- await session.end(reason=reason)
+ # Defense in depth around the two bounded closes inside end()
+ # (provider socket 5 s + turn-completed 3 s): should end() ever
+ # stall anywhere else, this outer bound still frees the realtime
+ # finally so the supervisor reaches its own IDLE teardown —
+ # returning _state to IDLE (wake re-arms) and publishing the
+ # SystemStateChanged(IDLE) that repaints the JarvisBar. Without
+ # it a single unbounded await here strands the session ACTIVE.
+ try:
+ await asyncio.wait_for(
+ session.end(reason=reason), timeout=8.0
+ )
+ except TimeoutError:
+ log.warning(
+ "Realtime session.end() timed out during teardown; "
+ "forcing the supervisor back to idle so wake re-arms."
+ )
+ except Exception as exc: # noqa: BLE001 — teardown best-effort
+ log.warning("Realtime session.end() failed: %s", exc)
# ``session.end`` quiesces the provider pump. Close once more to
# collect any callback that had already crossed the surface
# boundary when terminal teardown began. ``close`` is idempotent
diff --git a/tests/unit/mcp/test_mcp_client.py b/tests/unit/mcp/test_mcp_client.py
index 2095fbaffe..1bc8a832d5 100644
--- a/tests/unit/mcp/test_mcp_client.py
+++ b/tests/unit/mcp/test_mcp_client.py
@@ -7,6 +7,7 @@ reaching the plugin badge (caught generically at ``mcp/registry.py``).
"""
from __future__ import annotations
+import asyncio
import shutil
import pytest
@@ -108,3 +109,39 @@ async def test_start_does_not_which_check_when_launcher_present(monkeypatch) ->
client = MCPClient(_stdio_spec(command="npx", name="brave-search"))
with pytest.raises(RuntimeError, match="boom past the which"):
await client.start()
+
+
+# --- MCPClient.stop() — bounded so a wedged transport can't hang teardown ----
+
+
+async def test_stop_times_out_instead_of_hanging_on_a_stalled_transport(
+ monkeypatch,
+) -> None:
+ """A cross-task ``anyio`` cancel-scope exit can make
+ ``AsyncExitStack.aclose()`` stall for ~20 s before it even errors. ``stop()``
+ MUST bound that so a load-bearing teardown (a realtime voice-session end, app
+ shutdown) can never hang on it — the live 2026-07-23 bug where a bar-X hangup
+ of a realtime session froze the JarvisBar on "listening" and deafened wake
+ until the stalled close gave up.
+ """
+ import jarvis.mcp.client as client_mod
+
+ monkeypatch.setattr(client_mod, "_STOP_TIMEOUT_S", 0.05)
+
+ class _StalledExitStack:
+ async def aclose(self) -> None:
+ # Never completes — models the wedged transport close.
+ await asyncio.Event().wait()
+
+ client = MCPClient(_stdio_spec())
+ client._exit_stack = _StalledExitStack()
+ client._session = object()
+
+ # Bounded by the test itself, so a regression (unbounded stop) FAILS here
+ # instead of hanging the whole suite.
+ await asyncio.wait_for(client.stop(), timeout=2.0)
+
+ # The stall was abandoned and the client reset so a later start() is clean.
+ assert client._exit_stack is None
+ assert client._session is None
diff --git a/ui/orb/bus_bridge.py b/ui/orb/bus_bridge.py
index c06b09fd44..95485b4514 100644
--- a/ui/orb/bus_bridge.py
+++ b/ui/orb/bus_bridge.py
@@ -575,6 +575,22 @@ class OrbBusBridge:
event.hangup_reason,
)
self._suppress_show_until_session = True
+ # Defense in depth: a persistent (always-on) bar must drop to its idle
+ # look the instant a session ends, not only when the follow-up
+ # SystemStateChanged(IDLE) arrives. That state edge can be skipped or
+ # delayed — the supervisor's turn-state may never have been a real
+ # LISTENING→IDLE edge (so set_state("IDLE") is a no-op and nothing is
+ # published), or a stalling realtime teardown delays it — which froze
+ # the JarvisBar on its "listening" look after a bar-X hangup (live
+ # 2026-07-23). show(mode="idle") is idempotent and NOT gated by the
+ # suppression latch (that only blocks ACTIVE-state repaints), so the
+ # genuine IDLE transition, if it still arrives, is a harmless same-mode
+ # repaint. The idle-animation scheduler stays owned by that transition.
+ if not self._hide_on_idle:
+ try:
+ self._orb.show(mode="idle")
+ except Exception as exc: # noqa: BLE001
+ log.debug("session-ended idle repaint failed: %s", exc)
async def _on_voice_boot_status(self, event: VoiceBootStatus) -> None:
"""Release the Jarvis Bar only when voice is genuinely usable.