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 a dead provider transport in place instead of hanging up (BUG-071)

Ruben Lütkef66e063f5e26
diff --git a/docs/BUGS.md b/docs/BUGS.md
index 8fafcd740b..434c30a10d 100644
--- a/docs/BUGS.md
+++ b/docs/BUGS.md
@@ -5120,3 +5120,77 @@ turn category whose only correct answer is known in advance belongs to
the orchestrator, not the model. And: any path that discards work the
user asked for — even legitimately, on hangup — must say so in the log,
or the next forensic starts from nothing.
+
+## BUG-071: Random auto-hangup mid-call — the provider drops the Live WebSocket and the whole session ends with "error" (HIGH, FIXED 2026-07-17)
+
+**Symptom (maintainer report + live session 2026-07-17 10:42,
+gemini-live).** The call hangs up by itself. The user said no hang-up word,
+did not close the app, and touched nothing — the session just ends. The
+exported transcript shows `Beendet durch: Fehler` <!-- i18n-allow: quoted German session-export field under test -->
+with a completely normal conversation above it. Intermittent: most runs are
+fine, some die.
+
+**Evidence (data/jarvis_desktop.log, session 5e553e27, 10:42-10:44).**
+Turn 2's reply tripped the scrub-gate abort (`output transcript exceeded
+safe audio buffer`, 10:43:15) and the trusted answer was correctly re-spoken
+through the realtime-scoped surface TTS for ~69 s. During that playback the
+half-duplex echo guard uploads no microphone audio and the interrupted
+provider streams nothing, so the Live WebSocket sat fully idle both ways —
+and Google closed it: `pump ended` + `provider_error: 1006 None. abnormal
+closure [internal]` at 10:44:24, the exact second playback finished. The
+desktop pipeline then refused the classic-replay fallback (a committed turn
+makes replaying the capture buffer unsafe — that guard is correct) and ended
+the call with `reason=error`.
+
+**Root cause (jarvis/realtime/session.py).** The receive pump treated EVERY
+transport end as terminal: one `async for` pass over `session.receive()`;
+an exception or a silent iterator end set `_failed` and finished the pump,
+and the desktop surface translates a finished pump after a committed turn
+into a hang-up. A provider-side WebSocket drop — which Gemini does on its
+own schedule (session limits/GoAway, abrupt 1006 closes, idle timeouts) —
+therefore ended the whole call, even though the session object could simply
+have opened a new transport. The BUG-064 transport-rebuild lesson existed
+only INSIDE the openai adapter; gemini-live (SDK-managed socket, no
+in-protocol resume) had no equivalent, and the orchestrator had none either.
+
+**Fix (capability-gated in-place transport rebuild, orchestrator level).**
+`RealtimeVoiceSession._pump` is now a reconnect loop over
+`_pump_transport_once()`. When a transport dies — receive raising, or the
+iterator ending without a boundary, mid-turn or idle — and the dead session
+declares `rebuild_on_transport_death = True` (a capability attribute, never
+a provider name — AP-21; `_GeminiLiveSession` sets it), the orchestrator
+closes the dead session, freezes the open turn into the persisted record,
+resets per-turn output state, re-runs `_open()` (the key-aware provider
+chain — a dead family crosses to the next, AP-22 for free), and re-announces
+`audio_ready` so playback and surface labels follow the possibly-new
+provider/rates. Mid-turn deaths still release the transcript-cleared audio
+tail first. In-provider conversation history is lost — strictly better than
+a dead call; the orchestrator-side delegate history survives. Deliberate
+ends never rebuild: session end, voice hangup, and an acknowledged
+`end_call` (a death there converts to the requested hangup, not an error).
+The budget is rate-based (3 rebuilds per rolling 120 s), so a long call
+outliving several provider session limits keeps healing while a flapping
+transport fails honestly with one terminal `provider_error`. Sessions
+without the capability (openai_realtime self-heals internally and declares
+terminal deliberately; test doubles) keep the old terminal semantics
+exactly. `handle_audio_frame` additionally drops a microphone frame whose
+send hits the just-died socket instead of raising — a raise there killed
+the desktop mic pump, which is its own path into `reason=error`.
+
+**Guards.** `tests/unit/realtime/test_session.py`
+(`test_transport_death_rebuilds_the_session_in_place`,
+`test_transport_death_without_capability_keeps_terminal_semantics`,
+`test_transport_rebuild_storm_fails_honestly`,
+`test_idle_stream_end_with_capability_rebuilds_instead_of_ending`,
+`test_mid_turn_stream_end_with_capability_salvages_then_rebuilds`,
+`test_transport_death_after_end_call_converts_to_hangup`).
+
+**Lesson (BUG-064 class rule, final form).** A duplex provider's transport
+WILL die mid-call for reasons no client controls; the session and the
+transport are different lifetimes, and only the adapter knows whether a
+fresh transport can continue the session. Ending the call because a socket
+closed is answering the wrong question. And the trigger chain matters: a
+long LOCAL fallback playback starves the provider socket of traffic in both
+directions — every recovery path that takes the voice surface away from the
+provider for tens of seconds must assume the provider connection may not
+survive the silence.
diff --git a/jarvis/plugins/realtime/gemini_live.py b/jarvis/plugins/realtime/gemini_live.py
index 95ac70e375..9bbe4d562a 100644
--- a/jarvis/plugins/realtime/gemini_live.py
+++ b/jarvis/plugins/realtime/gemini_live.py
@@ -50,6 +50,13 @@ class _GeminiLiveSession:
# next input transcript. Output observed after that boundary belongs to
# the new automatic response generation.
isolates_response_generations = True
+ # Gemini's server drops the Live WebSocket on its own schedule: session
+ # limits (GoAway), and abrupt ``1006 abnormal closure`` closes — observed
+ # live 2026-07-17 10:44 right after a long surface-TTS fallback during
+ # which no traffic flowed, which used to end the whole call with
+ # reason=error (BUG-071). This adapter has no in-protocol resume, so the
+ # orchestrator may reopen a fresh session in place and continue the call.
+ rebuild_on_transport_death = True
def __init__(
self,
diff --git a/jarvis/realtime/session.py b/jarvis/realtime/session.py
index c3d4af6af3..c72988d5d3 100644
--- a/jarvis/realtime/session.py
+++ b/jarvis/realtime/session.py
@@ -106,6 +106,19 @@ _EMBEDDED_SILENCE_LOG_MS = 400.0
# full scale — comfortably above the AP-27 silence-ghost RMS empirics, far
# below any audible speech).
_EMBEDDED_SILENCE_PEAK = 200
+# In-place transport rebuild (BUG-071). A provider server may drop the duplex
+# WebSocket at any time mid-call (live incident 2026-07-17 10:44: Gemini Live
+# closed with ``1006 abnormal closure`` right as a 69 s surface-TTS fallback
+# finished, and the whole call hung up with reason=error although the user
+# never asked to end it). When the dead provider session declares
+# ``rebuild_on_transport_death = True``, the pump reopens the provider chain
+# in place instead of failing the session — the BUG-064 class rule applied
+# transport-neutrally. The budget is rate-based, not a per-session cap: a
+# healthy long call may legitimately outlive several provider-side session
+# limits, while a flapping transport dies fast and must fail honestly instead
+# of reconnect-storming.
+_TRANSPORT_REBUILD_WINDOW_S = 120.0
+_TRANSPORT_REBUILD_MAX_PER_WINDOW = 3
def _pcm16_peak(pcm: bytes) -> int:
@@ -768,6 +781,9 @@ class RealtimeVoiceSession:
self._last_audio_emit_monotonic = 0.0
self._last_audio_emit_turn = ""
self._embedded_silence_ms = 0.0
+ # 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] = []
def _resolve_lang(self, *, text: str) -> str:
brain = getattr(self._config, "brain", None)
@@ -1017,6 +1033,18 @@ class RealtimeVoiceSession:
recoverable=True,
)
raise RuntimeError(message) from exc
+ except Exception: # noqa: BLE001 — a dead transport drops the frame
+ # A send onto a just-died socket must not kill the caller: the
+ # desktop microphone pump turns a raise here straight into a
+ # session end with reason=error, while the receive pump is about
+ # to observe the same death and — for rebuild-capable providers —
+ # reopen the transport in place (BUG-071). The frame is lost
+ # either way; the transport is already gone.
+ log.debug(
+ "realtime[%s] dropped a microphone frame on a dead transport",
+ self.session_id,
+ exc_info=True,
+ )
@property
def is_active(self) -> bool:
@@ -1146,6 +1174,35 @@ class RealtimeVoiceSession:
return True
async def _pump(self) -> None:
+ """Consume provider events; rebuild a dead transport in place.
+
+ One inner pass runs one provider transport to its end. A deliberate
+ end (voice hangup, terminal provider error event) finishes the pump.
+ A transport DEATH — the receive iterator raising, or ending without a
+ boundary — is recoverable when the dead session opted in via
+ ``rebuild_on_transport_death`` (BUG-071): the provider chain is
+ reopened in place and the call continues, instead of the surface
+ ending the whole session with reason=error.
+ """
+ while True:
+ rebuild_detail = await self._pump_transport_once()
+ if rebuild_detail is None or self._ended or self._hangup_reason:
+ return
+ if self._end_after_turn:
+ # The user already asked to end the call (end_call was
+ # acknowledged); a dead transport cannot speak the goodbye.
+ # End as the requested hangup, not as an error.
+ await self._finish_with_hangup()
+ return
+ if not await self._rebuild_transport(detail=rebuild_detail):
+ return
+
+ async def _pump_transport_once(self) -> str | None:
+ """Run one provider transport to its end.
+
+ Returns ``None`` for a deliberate or terminal end, or a short detail
+ string when the transport died and an in-place rebuild may proceed.
+ """
try:
async for event in self._session.receive():
if event.type == "input_transcript":
@@ -1818,33 +1875,167 @@ class RealtimeVoiceSession:
await self._emit_audio(chunk)
self._gate.drain()
message = "provider stream ended mid-turn without a boundary"
- self._failure_detail = message
- self._failed.set()
log.warning("realtime[%s] %s", self.session_id, message)
await self._publish_error(
"RealtimeProviderStreamEnd", message, recoverable=True
)
+ if self._transport_death_is_rebuildable():
+ return message
+ self._failure_detail = message
+ self._failed.set()
await self._send_json(
{"type": "provider_error", "error": message}
)
+ elif self._transport_death_is_rebuildable():
+ # A benign idle-boundary end still ends the CALL on the
+ # desktop surface (a committed turn forbids the classic
+ # replay fallback, so the pipeline hangs up with
+ # reason=error). A rebuild-capable provider — e.g. Gemini
+ # closing at its Live-API session limit — is reopened
+ # instead (BUG-071).
+ return "provider stream ended at an idle turn boundary"
except asyncio.CancelledError:
raise
- except Exception as exc: # noqa: BLE001 — AP-20: pump error is terminal
+ except Exception as exc: # noqa: BLE001 — AP-20: never re-read a dead transport
message = safe_preview(exc, max_chars=800) or "Realtime receive loop ended"
- self._failure_detail = message
- self._failed.set()
log.warning("realtime[%s] pump ended", self.session_id, exc_info=True)
await self._publish_error(
type(exc).__name__,
message,
recoverable=True,
)
+ if self._transport_death_is_rebuildable():
+ return message
+ self._failure_detail = message
+ self._failed.set()
try:
await self._send_json(
{"type": "provider_error", "error": message}
)
except Exception: # noqa: BLE001, S110
pass
+ return None
+
+ def _transport_death_is_rebuildable(self) -> bool:
+ """Whether the just-died transport may be rebuilt in place (BUG-071).
+
+ Opt-in per provider session — a capability attribute, never a
+ provider name (AP-21): adapters that self-heal internally (the
+ openai_realtime BUG-064 stack declares terminal deliberately) keep
+ today's terminal semantics. A deliberate end (session ended, voice
+ hangup) or an already-failed session (e.g. the microphone send
+ timeout marked it dead) is never rebuilt; the acknowledged-end_call
+ case is converted to a hangup by the pump loop.
+ """
+ return (
+ bool(getattr(self._session, "rebuild_on_transport_death", False))
+ and not self._ended
+ and not self._hangup_reason
+ and not self._failed.is_set()
+ )
+
+ async def _rebuild_transport(self, *, detail: str) -> bool:
+ """Reopen the duplex transport in place after it died mid-call.
+
+ A provider's server can drop the WebSocket at any moment (live
+ incident 2026-07-17 10:44: Gemini closed with ``1006 abnormal
+ closure`` right as a 69 s surface-TTS fallback finished, and the call
+ ended with reason=error although the user never hung up). The BUG-064
+ class rule applies transport-neutrally: rebuild the transport in
+ place; the surfaces see one fresh ``audio_ready`` instead of a
+ session end. In-provider conversation history is lost — strictly
+ better than a dead call; the orchestrator-side delegate history
+ survives and keeps follow-up questions grounded.
+ """
+ now = time.monotonic()
+ self._transport_rebuild_times = [
+ stamp
+ for stamp in self._transport_rebuild_times
+ if now - stamp < _TRANSPORT_REBUILD_WINDOW_S
+ ]
+ if len(self._transport_rebuild_times) >= _TRANSPORT_REBUILD_MAX_PER_WINDOW:
+ await self._fail_terminally(
+ "realtime transport keeps dying "
+ f"({_TRANSPORT_REBUILD_MAX_PER_WINDOW} rebuilds in "
+ f"{_TRANSPORT_REBUILD_WINDOW_S:.0f} s); giving up: {detail}"
+ )
+ return False
+ self._transport_rebuild_times.append(now)
+ old_session, self._session = self._session, None
+ if old_session is not None:
+ try:
+ await old_session.close()
+ except Exception: # noqa: BLE001, S110 — the transport is already dead
+ pass
+ # Freeze whatever the dead transport left of the open turn into the
+ # persisted record, then reset per-turn output state. Microphone
+ # frames arriving during the fresh handshake are dropped by
+ # handle_audio_frame's session-None guard, so nothing races it.
+ self._cancel_tool_transcript_wait()
+ if self._pending_tool_events:
+ log.warning(
+ "realtime[%s] dropped %d pending tool call(s) whose transport "
+ "died before their input transcripts arrived",
+ self.session_id,
+ len(self._pending_tool_events),
+ )
+ self._pending_tool_events = []
+ await self._publish_turn_completed()
+ self._gate = ScrubHoldGate(self._language)
+ self._output_active = False
+ self._output_samples_sent = 0
+ self._response_requested_for_turn = False
+ self._user_speech_active = False
+ self._drop_provider_output_until_new_response = False
+ self._drop_provider_output_until_user_turn = False
+ log.warning(
+ "realtime[%s] transport died mid-call (%s) — rebuilding the "
+ "provider session in place (%d/%d in the current %.0f s window)",
+ self.session_id,
+ detail,
+ len(self._transport_rebuild_times),
+ _TRANSPORT_REBUILD_MAX_PER_WINDOW,
+ _TRANSPORT_REBUILD_WINDOW_S,
+ )
+ try:
+ await self._open()
+ except Exception as exc: # noqa: BLE001 — no provider family reachable
+ await self._fail_terminally(
+ "realtime transport rebuild failed: "
+ f"{type(exc).__name__}: {safe_preview(exc, max_chars=400)}"
+ )
+ return False
+ # The fresh transport may resolve to a different provider, model, or
+ # sample rates — re-announce so playback and surface labels follow.
+ try:
+ await self._send_json(
+ {
+ "type": "audio_ready",
+ "provider": self.active_provider,
+ "model": self._active_model,
+ "input_sample_rate": self._input_sample_rate,
+ "output_sample_rate": int(
+ getattr(self._provider, "output_sample_rate", 24_000)
+ or 24_000
+ ),
+ }
+ )
+ except Exception: # noqa: BLE001, S110 — surface refresh is best-effort
+ pass
+ return True
+
+ async def _fail_terminally(self, message: str) -> None:
+ """Mark the duplex stream dead and tell every surface honestly."""
+ self._failure_detail = message
+ self._failed.set()
+ log.warning("realtime[%s] %s", self.session_id, message)
+ await self._publish_error(
+ "RealtimeTransportDead", message, recoverable=False
+ )
+ try:
+ await self._send_json({"type": "provider_error", "error": message})
+ except Exception: # noqa: BLE001, S110 — surface may already be gone
+ pass
def _scrubbed_trusted_reply(self, delegate_state: Any) -> str:
"""Scrub-clean the delegate's trusted reply for direct surface speech.
diff --git a/tests/unit/realtime/test_session.py b/tests/unit/realtime/test_session.py
index e781953e40..44f3240806 100644
--- a/tests/unit/realtime/test_session.py
+++ b/tests/unit/realtime/test_session.py
@@ -4546,3 +4546,299 @@ async def test_session_end_names_the_delegated_request_it_cancels(caplog):
]
assert len(lost) == 1
assert "travel plan" in lost[0].getMessage()
+
+
+# ---------------------------------------------------------------------------
+# BUG-071: in-place transport rebuild after a mid-call provider death
+# ---------------------------------------------------------------------------
+
+
+class DyingSession(FakeSession):
+ """Yield the scripted events, then die like a dropped WebSocket."""
+
+ rebuild_on_transport_death = True
+
+ def __init__(self, events, error="1006 None. abnormal closure [internal]"):
+ super().__init__(events)
+ self._error = error
+
+ async def receive(self):
+ for ev in self._events:
+ yield ev
+ await asyncio.sleep(0)
+ raise RuntimeError(self._error)
+
+
+class EndingSession(FakeSession):
+ """Yield the scripted events, then end the iterator cleanly (a graceful
+ server close, e.g. Gemini's Live-API session limit)."""
+
+ rebuild_on_transport_death = True
+
+
+class StayOpenSession(FakeSession):
+ """Yield the scripted events, then stay open like a healthy live call."""
+
+ rebuild_on_transport_death = True
+
+ def __init__(self, events):
+ super().__init__(events)
+ self._released = asyncio.Event()
+
+ async def receive(self):
+ for ev in self._events:
+ yield ev
+ await asyncio.sleep(0)
+ await self._released.wait()
+
+ async def close(self):
+ await super().close()
+ self._released.set()
+
+
+class RebuildingProvider(FakeProvider):
+ """Serve a scripted sequence of session objects, one per open_session."""
+
+ def __init__(self, session_factories):
+ super().__init__([])
+ self._session_factories = list(session_factories)
+ self.open_calls = 0
+ self.sessions = []
+
+ async def open_session(self, cfg):
+ self.opened_with = cfg
+ self.open_calls += 1
+ factory = self._session_factories[
+ min(self.open_calls - 1, len(self._session_factories) - 1)
+ ]
+ self.session = factory()
+ self.sessions.append(self.session)
+ return self.session
+
+
+async def _wait_until(predicate):
+ async with asyncio.timeout(2):
+ while not predicate():
+ await asyncio.sleep(0.01)
+
+
+async def test_transport_death_rebuilds_the_session_in_place():
+ """BUG-071: Gemini dropped the Live WebSocket (1006 abnormal closure)
+ mid-call and the whole call ended with reason=error although the user
+ never hung up. A provider session that declares
+ rebuild_on_transport_death gets a fresh transport in place; the surfaces
+ see one new audio_ready, never a session end."""
+ provider = RebuildingProvider(
+ [
+ lambda: DyingSession(
+ [
+ RealtimeEvent(
+ type="input_transcript", text="hello", is_final=True
+ ),
+ RealtimeEvent(type="turn_complete"),
+ ]
+ ),
+ lambda: StayOpenSession(
+ [
+ RealtimeEvent(
+ type="input_transcript",
+ text="still there?",
+ is_final=True,
+ ),
+ RealtimeEvent(type="turn_complete"),
+ ]
+ ),
+ ]
+ )
+ jsons = []
+ sess = RealtimeVoiceSession(
+ session_id="rebuild-inplace",
+ 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})
+ # The rebuilt transport must serve real turns, not merely exist.
+ await _wait_until(
+ lambda: len(provider.sessions) == 2
+ and provider.sessions[1].response_requests >= 1
+ )
+
+ assert 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_transport_death_without_capability_keeps_terminal_semantics():
+ """Adapters that self-heal internally (openai_realtime's BUG-064 stack)
+ or declare nothing keep today's contract: a dead receive loop fails the
+ session honestly instead of being rebuilt behind their back."""
+
+ class TerminalDyingSession(FakeSession):
+ async def receive(self):
+ for ev in self._events:
+ yield ev
+ await asyncio.sleep(0)
+ raise RuntimeError("socket vanished")
+
+ class TerminalProvider(FakeProvider):
+ async def open_session(self, cfg):
+ self.opened_with = cfg
+ self.session = TerminalDyingSession(self._events)
+ return self.session
+
+ jsons = []
+ sess = RealtimeVoiceSession(
+ session_id="terminal-death",
+ send_binary=lambda _data: asyncio.sleep(0),
+ send_json=lambda m: jsons.append(m) or asyncio.sleep(0),
+ provider=TerminalProvider([]),
+ config=_cfg(),
+ bus=None,
+ )
+ await sess.handle_control({"type": "audio_start", "sample_rate": 16_000})
+ await asyncio.wait_for(sess.wait_finished(), timeout=5)
+
+ assert sess.failed
+ assert any(m.get("type") == "provider_error" for m in jsons)
+ await sess.end(reason="test")
+
+
+async def test_transport_rebuild_storm_fails_honestly():
+ """A flapping transport must not reconnect-storm: after the rolling
+ budget is spent, the session fails terminally with one honest error."""
+ from jarvis.realtime import session as session_mod
+
+ provider = RebuildingProvider([lambda: DyingSession([])])
+ jsons = []
+ sess = RealtimeVoiceSession(
+ session_id="rebuild-storm",
+ 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 asyncio.wait_for(sess.wait_finished(), timeout=5)
+
+ assert sess.failed
+ assert "keeps dying" in sess.failure_detail
+ assert provider.open_calls == 1 + session_mod._TRANSPORT_REBUILD_MAX_PER_WINDOW
+ errors = [m for m in jsons if m.get("type") == "provider_error"]
+ assert len(errors) == 1
+ await sess.end(reason="test")
+
+
+async def test_idle_stream_end_with_capability_rebuilds_instead_of_ending():
+ """A graceful provider close at an idle boundary (Live-API session limit)
+ still ends the whole CALL on the desktop surface, so a rebuild-capable
+ provider is reopened instead of hanging up with reason=error."""
+ provider = RebuildingProvider(
+ [
+ lambda: EndingSession(
+ [
+ RealtimeEvent(
+ type="input_transcript", text="hi", is_final=True
+ ),
+ RealtimeEvent(type="turn_complete"),
+ ]
+ ),
+ lambda: StayOpenSession([]),
+ ]
+ )
+ jsons = []
+ sess = RealtimeVoiceSession(
+ session_id="rebuild-idle-end",
+ 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"] == []
+ await sess.end(reason="test")
+
+
+async def test_mid_turn_stream_end_with_capability_salvages_then_rebuilds():
+ """A transport dying mid-reply still releases the transcript-cleared
+ audio tail before the rebuild — the fix must not chop the answer harder
+ than the transport failure requires."""
+ provider = RebuildingProvider(
+ [
+ lambda: EndingSession(
+ [
+ RealtimeEvent(
+ type="input_transcript", text="hi", is_final=True
+ ),
+ RealtimeEvent(
+ type="output_transcript_delta", text="Hi there."
+ ),
+ RealtimeEvent(
+ type="audio_delta",
+ audio=AudioChunk(
+ pcm=b"\x01\x02" * 8,
+ sample_rate=24000,
+ timestamp_ns=0,
+ ),
+ ),
+ ]
+ ),
+ lambda: StayOpenSession([]),
+ ]
+ )
+ binaries, jsons = [], []
+ sess = RealtimeVoiceSession(
+ session_id="rebuild-mid-turn",
+ send_binary=lambda b: binaries.append(b) or 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 binaries # the cleared audio tail was salvaged, not dropped
+ assert [m for m in jsons if m.get("type") == "provider_error"] == []
+ await sess.end(reason="test")
+
+
+async def test_transport_death_after_end_call_converts_to_hangup():
+ """The user already asked to end the call (end_call acknowledged); a
+ dead transport cannot speak the goodbye. The session must end as the
+ requested hangup — never as an error, never through a rebuild."""
+ provider = RebuildingProvider([lambda: DyingSession([])])
+ jsons = []
+ sess = RealtimeVoiceSession(
+ session_id="rebuild-end-after-turn",
+ send_binary=lambda _data: asyncio.sleep(0),
+ send_json=lambda m: jsons.append(m) or asyncio.sleep(0),
+ provider=provider,
+ config=_cfg(),
+ bus=None,
+ )
+ sess._end_after_turn = True
+ await sess.handle_control({"type": "audio_start", "sample_rate": 16_000})
+ await asyncio.wait_for(sess.wait_finished(), timeout=5)
+
+ assert sess.hangup_reason == "voice_pattern"
+ assert not sess.failed
+ assert provider.open_calls == 1
+ assert any(m.get("type") == "hangup" for m in jsons)
+ await sess.end(reason="test")