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): rebuild the transport proactively inside Gemini's GoAway window

Personal Jarvis Maintainercd333abe9da0
diff --git a/jarvis/plugins/realtime/gemini_live.py b/jarvis/plugins/realtime/gemini_live.py
index 8e224030fe..c0b7877d7d 100644
--- a/jarvis/plugins/realtime/gemini_live.py
+++ b/jarvis/plugins/realtime/gemini_live.py
@@ -37,6 +37,7 @@ class _ProviderEvent:
ms_played: int | None = None
error: str | None = None
recoverable: bool = False
+ reconnect_advised: bool = False
item_id: str | None = None
call_id: str | None = None
tool_name: str | None = None
@@ -205,13 +206,16 @@ class _GeminiLiveSession:
# to Live-API session limits, not a wire failure. Treating
# it as terminal used to end the session with reason=error
# while the current reply was still being spoken, dropping
- # the buffered tail. Surface it as recoverable; if the
- # transport really closes, the pump observes that end
- # separately.
+ # the buffered tail. Surface it as recoverable AND advise
+ # a proactive rebuild: a client that merely keeps using
+ # the socket is hard-killed with 1008 when the window
+ # expires (live 2026-07-21 11:14 — the forced close raced
+ # the recovery chain and the call ended reason=error).
yield _ProviderEvent(
type="error",
error=f"Gemini Live requested reconnect{suffix}",
recoverable=True,
+ reconnect_advised=True,
)
# An iterator that vanishes without a model-turn boundary signals a
diff --git a/jarvis/realtime/protocol.py b/jarvis/realtime/protocol.py
index 740c718b2e..9e412c2458 100644
--- a/jarvis/realtime/protocol.py
+++ b/jarvis/realtime/protocol.py
@@ -40,6 +40,11 @@ class RealtimeEvent:
# duplex transport remains usable. It must not end voice ownership or
# trigger the classic pipeline.
recoverable: bool = False
+ # The provider announced it will close this transport soon (e.g. a
+ # session-duration GoAway) while the socket still works. The
+ # orchestrator should rebuild the transport in place at the next safe
+ # boundary instead of waiting for the server-forced close.
+ reconnect_advised: bool = False
item_id: str | None = None
call_id: str | None = None
tool_name: str | None = None
diff --git a/jarvis/realtime/session.py b/jarvis/realtime/session.py
index 5d3bfd07b8..e24bfe19ed 100644
--- a/jarvis/realtime/session.py
+++ b/jarvis/realtime/session.py
@@ -966,6 +966,11 @@ class RealtimeVoiceSession:
asyncio.Queue()
)
self._transport_rebuild_pending: Any | None = None
+ # A provider announced it will close the transport soon (GoAway).
+ # Holds the announcement detail until the next safe boundary, where
+ # the pump rebuilds proactively instead of waiting for the forced
+ # close (which can race the recovery chain and end the call).
+ self._advised_reconnect_detail: str | None = None
# Monotonic timestamps of in-place transport rebuilds (BUG-071),
# pruned to the rolling _TRANSPORT_REBUILD_WINDOW_S budget window.
self._transport_rebuild_times: list[float] = []
@@ -2303,6 +2308,10 @@ class RealtimeVoiceSession:
# its goodbye to the end — hang up.
await self._finish_with_hangup()
break
+ if self._advised_reconnect_detail is not None:
+ # The provider's pre-disconnect window is ticking;
+ # this turn boundary is the safe moment to rebuild.
+ self._request_advised_rebuild()
elif event.type == "error":
message = safe_preview(
event.error or "provider error", max_chars=800
@@ -2347,6 +2356,8 @@ class RealtimeVoiceSession:
await self._send_json(
{"type": "provider_warning", "error": message}
)
+ if getattr(event, "reconnect_advised", False):
+ self._schedule_advised_reconnect(message)
continue
# A terminal provider failure can strike while the tail of
# the current reply is still held by the scrub gate.
@@ -2481,6 +2492,59 @@ class RealtimeVoiceSession:
pass
return None
+ def _schedule_advised_reconnect(self, detail: str) -> None:
+ """React to a provider's pre-disconnect notice (GoAway).
+
+ The transport still works, but the server will force-close it when
+ the announced window expires — and that forced close can race the
+ recovery chain into a dead call (live 2026-07-21 11:14: the 1008
+ close escalated to a cross-provider fallback whose only alternative
+ was quota-dead, reason=error after 17 turns). Rebuild proactively:
+ immediately when the call is idle, otherwise at the next turn
+ boundary. If no boundary arrives inside the window, the forced
+ close still lands on the existing reactive rebuild path.
+ """
+ if not self._transport_death_is_rebuildable():
+ return
+ if self._session is self._transport_rebuild_pending:
+ return # a rebuild is already queued or running
+ self._advised_reconnect_detail = detail
+ if (
+ self._output_active
+ or self._response_requested_for_turn
+ or self._user_speech_active
+ ):
+ log.info(
+ "realtime[%s] provider advised a reconnect — deferring the "
+ "transport rebuild to the next turn boundary (%s)",
+ self.session_id,
+ detail,
+ )
+ return
+ self._request_advised_rebuild()
+
+ def _request_advised_rebuild(self) -> None:
+ """Queue the advised in-place rebuild through the pump arbitration."""
+ detail = self._advised_reconnect_detail
+ self._advised_reconnect_detail = None
+ if detail is None or not self._transport_death_is_rebuildable():
+ return
+ target_session = self._session
+ if target_session is None or (
+ target_session is self._transport_rebuild_pending
+ ):
+ return
+ self._transport_rebuild_pending = target_session
+ self._transport_rebuild_requests.put_nowait(
+ (target_session, f"provider requested reconnect ({detail})")
+ )
+ log.info(
+ "realtime[%s] rebuilding the transport proactively inside the "
+ "provider's reconnect window (%s)",
+ self.session_id,
+ detail,
+ )
+
def _transport_death_is_rebuildable(self, *, session: Any | None = None) -> bool:
"""Whether the just-died transport may be rebuilt in place (BUG-071).
@@ -2580,6 +2644,10 @@ class RealtimeVoiceSession:
except Exception: # noqa: BLE001, S110 — surface mirror is best-effort
pass
await self._publish_turn_completed()
+ # The dying transport's pre-disconnect notice must not carry over:
+ # the fresh session would otherwise be rebuilt again at its first
+ # turn boundary for no reason.
+ self._advised_reconnect_detail = None
self._gate = ScrubHoldGate(self._language)
self._output_active = False
self._output_samples_sent = 0
diff --git a/tests/unit/realtime/test_gemini_live.py b/tests/unit/realtime/test_gemini_live.py
index b60268fb01..67e4dc56da 100644
--- a/tests/unit/realtime/test_gemini_live.py
+++ b/tests/unit/realtime/test_gemini_live.py
@@ -113,6 +113,10 @@ async def test_go_away_is_recoverable_and_keeps_the_stream_flowing() -> None:
errors = [event for event in events if event.type == "error"]
assert len(errors) == 1
assert errors[0].recoverable is True
+ # The notice also advises a proactive rebuild: a client that merely
+ # keeps using the socket is hard-killed with 1008 when the announced
+ # window expires (live 2026-07-21 11:14).
+ assert errors[0].reconnect_advised is True
assert "reconnect" in (errors[0].error or "")
# The notice must not terminate the stream: the reply that follows it is
# still delivered.
diff --git a/tests/unit/realtime/test_session.py b/tests/unit/realtime/test_session.py
index 0348b26c01..b04e47adf1 100644
--- a/tests/unit/realtime/test_session.py
+++ b/tests/unit/realtime/test_session.py
@@ -5708,3 +5708,95 @@ async def test_transport_death_after_end_call_converts_to_hangup():
assert provider.open_calls == 1
assert any(m.get("type") == "hangup" for m in jsons)
await sess.end(reason="test")
+
+
+# ---------------------------------------------------------------------------
+# Proactive GoAway reconnect: a provider's pre-disconnect notice rebuilds the
+# transport inside the announced window instead of waiting for the forced
+# close (live 2026-07-21 11:14: the 1008 close raced the recovery chain into
+# a cross-provider fallback whose only alternative was quota-dead, and the
+# call ended reason=error after 17 turns).
+# ---------------------------------------------------------------------------
+
+
+async def test_advised_reconnect_rebuilds_immediately_when_idle():
+ provider = RebuildingProvider(
+ [
+ lambda: StayOpenSession(
+ [
+ RealtimeEvent(
+ type="error",
+ error="Gemini Live requested reconnect (time_left=50s)",
+ recoverable=True,
+ reconnect_advised=True,
+ ),
+ ]
+ ),
+ lambda: StayOpenSession([]),
+ ]
+ )
+ jsons = []
+ sess = RealtimeVoiceSession(
+ session_id="goaway-idle-rebuild",
+ send_binary=lambda _data: asyncio.sleep(0),
+ send_json=lambda m: jsons.append(m) or asyncio.sleep(0),
+ provider=provider,
+ config=_cfg(),
+ bus=None,
+ )
+ await sess.handle_control({"type": "audio_start", "sample_rate": 16_000})
+ # No turn boundary is ever yielded: the idle call must rebuild at once.
+ await _wait_until(lambda: provider.open_calls == 2)
+
+ assert not sess.failed
+ assert [m for m in jsons if m.get("type") == "provider_error"] == []
+ assert len([m for m in jsons if m.get("type") == "audio_ready"]) == 2
+ await sess.end(reason="test")
+
+
+async def test_advised_reconnect_defers_to_the_turn_boundary_mid_turn():
+ provider = RebuildingProvider(
+ [
+ lambda: StayOpenSession(
+ [
+ RealtimeEvent(
+ type="input_transcript", text="hello", is_final=True
+ ),
+ # The response for this turn is now pending — the advised
+ # rebuild must NOT tear the transport down mid-turn.
+ RealtimeEvent(
+ type="error",
+ error="Gemini Live requested reconnect (time_left=50s)",
+ recoverable=True,
+ reconnect_advised=True,
+ ),
+ RealtimeEvent(type="turn_complete"),
+ ]
+ ),
+ lambda: StayOpenSession([]),
+ ]
+ )
+ jsons = []
+ sess = RealtimeVoiceSession(
+ session_id="goaway-boundary-rebuild",
+ send_binary=lambda _data: asyncio.sleep(0),
+ send_json=lambda m: jsons.append(m) or asyncio.sleep(0),
+ provider=provider,
+ config=_cfg(),
+ bus=None,
+ )
+ await sess.handle_control({"type": "audio_start", "sample_rate": 16_000})
+ await _wait_until(lambda: provider.open_calls == 2)
+
+ assert not sess.failed
+ assert [m for m in jsons if m.get("type") == "provider_error"] == []
+ # The first turn's boundary reached the surface before the rebuild's
+ # audio_ready: the reply was never cut mid-turn.
+ types = [m.get("type") for m in jsons]
+ assert types.index("turn_complete") < len(types) - 1 - types[::-1].index(
+ "audio_ready"
+ )
+ assert len([m for m in jsons if m.get("type") == "audio_ready"]) == 2
+ await sess.end(reason="test")