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): rebuild the transport when a deaf session outlives the contract re-arm (BUG-064 escalation)
Ruben Lütke67d8d0a30b66
diff --git a/docs/BUGS.md b/docs/BUGS.mdindex 7c7b9bc9f8..c4376f5eba 100644--- a/docs/BUGS.md+++ b/docs/BUGS.md@@ -4561,6 +4561,40 @@ contract instead of only suppressing the symptom. Suppression withoutrestoration turns one server-side hiccup into an unbounded silent outage thatthe user experiences as "it hears me (indicators fire) but nothing happens."+**Recurrence 2026-07-16 09:23 — the re-arm alone does NOT heal Grok; transport+rebuild escalation added.** Session `30c532cb`, first live run WITH the re-arm+fix (committed 08:34): turn 0 committed ("Constable?", an English mishearing+of the German sentence opener), the user kept talking, the barge-in cancel+fired (`realtime_cancel reason=barge_in`), and the known wedge followed — one+suppressed unsolicited response at 09:23:45, the re-arm log line proves the+recovery ran, and **still no input transcription event ever arrived again**.+The session sat in LISTENING for 19 more seconds until manual hang-up+(`turn_count=0`). Conclusion: on a wedged Grok server, re-sending the session+contract restores at most the manual-response half; the transcription half+stays dead server-side.++**Escalation fix (same adapter).** The session now tracks a *transcript+deadline*: whenever the server has provably heard a user turn — an+`input_audio_buffer.committed` event, or an auto-created response it is+forbidden to create — an input transcript (completed or failed) is owed under+the contract. If none arrives within `_TRANSCRIPT_OVERDUE_S` (6 s) while no+response lifecycle is active, the adapter **rebuilds the transport in place**:+a fresh WebSocket connection carrying the CURRENT session contract, state+reset, and the receive pump hops onto the new iterator (the orchestrator sees+one recoverable `RealtimeProviderError` warning, not a session end). In-call+conversation history is lost — strictly better than a call that can no longer+hear. A suppressed duplicate arriving <2 s after a transcript (the benign+openai-realtime race, 2026-07-15) never arms the deadline; a failed rebuild+closes the session so the orchestrator reports an honest provider error. The+deaf-wedge watchdog also runs from `send_audio`, because a fully deaf server+emits no events at all — the microphone pump is the only guaranteed heartbeat.++Additional guards: `test_deaf_session_rebuilds_the_transport_and_receive_hops_onto_it`,+`test_committed_turn_arms_and_transcript_clears_the_deadline`,+`test_suppressed_duplicate_right_after_a_transcript_does_not_arm`,+`test_failed_transport_rebuild_closes_the_session` (openai) and+`test_deaf_grok_session_rebuild_carries_the_grok_contract` (grok).+## BUG-065: macOS/Linux desktop shows a permanent OFFLINE — WebKit drops the HttpOnly session cookie from WebSocket handshakes (HIGH, FIXED 2026-07-16)**Symptom (real Mac hardware, 2026-07-15).** During and after boot the macOSdiff --git a/jarvis/plugins/realtime/grok_realtime.py b/jarvis/plugins/realtime/grok_realtime.pyindex 3aef8bc500..0cad698f2d 100644--- a/jarvis/plugins/realtime/grok_realtime.py+++ b/jarvis/plugins/realtime/grok_realtime.py@@ -56,9 +56,8 @@ class GrokRealtimeProvider:from openai import AsyncOpenAI # lazy (AP-26)client = AsyncOpenAI(api_key=self._api_key, base_url=_BASE_URL)- connection_cm = client.realtime.connect(- model=str(getattr(cfg, "model", "") or _MODEL)- )+ connect_model = str(getattr(cfg, "model", "") or _MODEL)+ connection_cm = client.realtime.connect(model=connect_model)try:connection = await connection_cm.__aenter__()except BaseException as exc:@@ -89,6 +88,7 @@ class GrokRealtimeProvider:client=client,session_id=str(uuid4()),session_payload=payload,+ connect_model=connect_model,)try:await connection.session.update(session=payload)diff --git a/jarvis/plugins/realtime/openai_realtime.py b/jarvis/plugins/realtime/openai_realtime.pyindex f70053cff0..2f754412c5 100644--- a/jarvis/plugins/realtime/openai_realtime.py+++ b/jarvis/plugins/realtime/openai_realtime.py@@ -33,6 +33,20 @@ _RESPONSE_REQUEST_METADATA_KEY = "jarvis_request_id"# halves of the contract; the cooldown keeps a burst of unsolicited responses# from turning into a session.update storm._CONTRACT_REARM_COOLDOWN_S = 5.0+# BUG-064 escalation (grok-realtime 2026-07-16 09:23): the re-arm demonstrably+# ran and the server STILL never delivered another input transcript — the call+# sat in LISTENING until manual hang-up. Once the server has provably heard a+# user turn (an input_audio_buffer commit, or an auto-created response it is+# forbidden to create), an input transcript is owed under the session+# contract. If none arrives within this window while no response lifecycle is+# active, the transcription side of the session is dead beyond what a+# session.update can repair, and the transport itself is rebuilt in place.+_TRANSCRIPT_OVERDUE_S = 6.0+# A suppressed auto-response that follows a transcript almost immediately is+# the benign duplicate race seen on openai-realtime 2026-07-15 (our+# response.create crossing the server's), not deafness — only arm the+# transcript deadline when the last transcript is comfortably in the past.+_SUPPRESS_ARM_MIN_QUIET_S = 2.0# Benign response-lifecycle races (BUG-053/BUG-056): both sides of the same# boundary. ``conversation_already_has_active_response`` = our response.create# arrived while one was still running; ``response_cancel_not_active`` = our@@ -187,12 +201,19 @@ class _OpenAIRealtimeSession:client: Any,session_id: str,session_payload: dict[str, Any] | None = None,+ connect_model: str = "",) -> None:self._conn = connectionself._connection_cm = connection_cmself._client = clientself._events = connection.__aiter__()self.session_id = session_id+ # Model the transport was opened with — required to rebuild the+ # connection in place when the server goes deaf (BUG-064 escalation).+ self._connect_model = str(connect_model or "")+ self._last_transcript_at = float("-inf")+ self._transcript_deadline: float | None = None+ self._rebuild_task: asyncio.Task[None] | None = None# The full session contract as sent at open. Kept current by# update_session() so a BUG-064 re-arm never reverts live# instructions or tool declarations to their session-start values.@@ -241,101 +262,145 @@ class _OpenAIRealtimeSession:pcm = bytes(getattr(chunk, "pcm", b"") or b"")if not pcm:return- await self._conn.input_audio_buffer.append(- audio=base64.b64encode(pcm).decode("ascii")- )+ # The microphone pump runs even when a deaf server emits no events at+ # all, so it is the one place guaranteed to notice an overdue+ # transcript and start the transport rebuild (BUG-064 escalation).+ self._maybe_begin_rebuild()+ try:+ await self._conn.input_audio_buffer.append(audio=base64.b64encode(pcm).decode("ascii"))+ except Exception:+ if self._rebuild_task is not None and not self._rebuild_task.done():+ # The dying transport is being replaced; this frame is lost+ # either way and must not end the whole voice session.+ return+ raiseasync def receive(self) -> AsyncIterator[_ProviderEvent]:- async for event in self._events:- event_type = str(getattr(event, "type", "") or "")- if event_type == "response.created":- await self._handle_response_created(event)- continue- if event_type.startswith("response.") and not self._response_is_accepted(- event- ):- continue- if event_type == "response.output_audio.delta":- self._last_item_id = str(getattr(event, "item_id", "") or "")- yield _ProviderEvent(- type="audio_delta",- audio=_PcmChunk(- pcm=base64.b64decode(getattr(event, "delta", "")),- sample_rate=_OUTPUT_RATE,- ),- )- elif event_type == "response.output_audio_transcript.delta":- yield _ProviderEvent(- type="output_transcript_delta",- text=str(getattr(event, "delta", "") or ""),- )- elif event_type == "conversation.item.input_audio_transcription.completed":- yield _ProviderEvent(- type="input_transcript",- text=str(getattr(event, "transcript", "") or ""),- is_final=True,- item_id=str(getattr(event, "item_id", "") or "") or None,- )- elif event_type == "conversation.item.input_audio_transcription.failed":- # The model still has the committed audio in conversation- # context. Let the orchestrator fail open to a spoken response,- # while withholding tools because no auditable text exists.- yield _ProviderEvent(- type="input_transcript",- text="",- is_final=True,- error=_error_message(event),- item_id=str(getattr(event, "item_id", "") or "") or None,- )- elif event_type == "input_audio_buffer.speech_started":- yield _ProviderEvent(type="speech_started")- elif event_type == "response.function_call_arguments.done":- call_id = str(getattr(event, "call_id", "") or "")- self._response_had_tool_calls = True- if call_id:- self._pending_tool_call_ids.add(call_id)- raw_arguments = str(getattr(event, "arguments", "") or "{}")- try:- arguments = json.loads(raw_arguments)- except (TypeError, ValueError):- arguments = {}- if not isinstance(arguments, dict):- arguments = {}- yield _ProviderEvent(- type="tool_call",- call_id=call_id,- tool_name=str(getattr(event, "name", "") or ""),- tool_args=arguments,- )- elif event_type == "response.done":- response_id = self._event_response_id(event)- if response_id:- self._accepted_response_ids.discard(response_id)- elif len(self._accepted_response_ids) == 1:- self._accepted_response_ids.pop()- self._response_idle.set()- status_error = _response_status_error(event)- if status_error:- # response.done is emitted for completed, failed, and- # incomplete generations. Preserve the lifecycle boundary,- # but do not mislabel a provider failure as clean success.- yield _ProviderEvent(- type="error",- error=status_error,- recoverable=True,- )- if self._response_had_tool_calls:- self._tool_response_done_seen = True- await self._continue_after_tools_if_ready()- else:- yield _ProviderEvent(type="turn_complete")- elif event_type == "error":- error_code = _error_code(event)+ # One while-iteration per transport: a BUG-064 rebuild replaces+ # ``self._events`` mid-call, and the pump must hop onto the fresh+ # iterator instead of treating the old transport's end as the end of+ # the whole voice session.+ while True:+ events = self._events+ try:+ async for event in events:+ # Runs before dispatch so it also fires on the event after+ # a ``continue`` branch; the send_audio pump covers the+ # no-events-at-all case.+ self._maybe_begin_rebuild()+ async for out in self._dispatch_event(event):+ yield out+ except Exception:+ if not await self._transport_was_rebuilt(events):+ raise+ else:+ if not await self._transport_was_rebuilt(events):+ return+ yield _ProviderEvent(+ type="error",+ error=(+ "Realtime transport rebuilt after the provider went deaf "+ "(no input transcript for a heard user turn); the last "+ "utterance was lost"+ ),+ recoverable=True,+ )++ async def _dispatch_event(self, event: Any) -> AsyncIterator[_ProviderEvent]:+ event_type = str(getattr(event, "type", "") or "")+ if event_type == "response.created":+ await self._handle_response_created(event)+ return+ if event_type.startswith("response.") and not self._response_is_accepted(event):+ return+ if event_type == "response.output_audio.delta":+ self._last_item_id = str(getattr(event, "item_id", "") or "")+ yield _ProviderEvent(+ type="audio_delta",+ audio=_PcmChunk(+ pcm=base64.b64decode(getattr(event, "delta", "")),+ sample_rate=_OUTPUT_RATE,+ ),+ )+ elif event_type == "response.output_audio_transcript.delta":+ yield _ProviderEvent(+ type="output_transcript_delta",+ text=str(getattr(event, "delta", "") or ""),+ )+ elif event_type == "conversation.item.input_audio_transcription.completed":+ self._note_input_transcript()+ yield _ProviderEvent(+ type="input_transcript",+ text=str(getattr(event, "transcript", "") or ""),+ is_final=True,+ item_id=str(getattr(event, "item_id", "") or "") or None,+ )+ elif event_type == "conversation.item.input_audio_transcription.failed":+ # The model still has the committed audio in conversation+ # context. Let the orchestrator fail open to a spoken response,+ # while withholding tools because no auditable text exists.+ self._note_input_transcript()+ yield _ProviderEvent(+ type="input_transcript",+ text="",+ is_final=True,+ error=_error_message(event),+ item_id=str(getattr(event, "item_id", "") or "") or None,+ )+ elif event_type == "input_audio_buffer.committed":+ # The server sealed a user turn; the session contract now owes an+ # input transcript (completed or failed). If none arrives, the+ # transcription half of the contract is dead (BUG-064).+ self._arm_transcript_deadline(require_recent_quiet=False)+ elif event_type == "input_audio_buffer.speech_started":+ yield _ProviderEvent(type="speech_started")+ elif event_type == "response.function_call_arguments.done":+ call_id = str(getattr(event, "call_id", "") or "")+ self._response_had_tool_calls = True+ if call_id:+ self._pending_tool_call_ids.add(call_id)+ raw_arguments = str(getattr(event, "arguments", "") or "{}")+ try:+ arguments = json.loads(raw_arguments)+ except (TypeError, ValueError):+ arguments = {}+ if not isinstance(arguments, dict):+ arguments = {}+ yield _ProviderEvent(+ type="tool_call",+ call_id=call_id,+ tool_name=str(getattr(event, "name", "") or ""),+ tool_args=arguments,+ )+ elif event_type == "response.done":+ response_id = self._event_response_id(event)+ if response_id:+ self._accepted_response_ids.discard(response_id)+ elif len(self._accepted_response_ids) == 1:+ self._accepted_response_ids.pop()+ self._response_idle.set()+ status_error = _response_status_error(event)+ if status_error:+ # response.done is emitted for completed, failed, and+ # incomplete generations. Preserve the lifecycle boundary,+ # but do not mislabel a provider failure as clean success.yield _ProviderEvent(type="error",- error=_error_message(event),- recoverable=error_code in _RECOVERABLE_ERROR_CODES,+ error=status_error,+ recoverable=True,)+ if self._response_had_tool_calls:+ self._tool_response_done_seen = True+ await self._continue_after_tools_if_ready()+ else:+ yield _ProviderEvent(type="turn_complete")+ elif event_type == "error":+ error_code = _error_code(event)+ yield _ProviderEvent(+ type="error",+ error=_error_message(event),+ recoverable=error_code in _RECOVERABLE_ERROR_CODES,+ )async def update_session(self,@@ -415,9 +480,7 @@ class _OpenAIRealtimeSession:finally:self._response_idle.set()- async def send_tool_result(- self, call_id: str, name: str, result: dict[str, Any]- ) -> None:+ async def send_tool_result(self, call_id: str, name: str, result: dict[str, Any]) -> None:del nameawait self._conn.conversation.item.create(item={@@ -514,6 +577,11 @@ class _OpenAIRealtimeSession:# session hears again; on a healthy server this is an idempotent# no-op.await self._rearm_session_contract()+ # The auto-response proves the server heard a user turn, yet no+ # transcript preceded it. If none follows either, the re-arm did+ # not restore hearing and the transport must be rebuilt (the+ # 2026-07-16 09:23 recurrence, where exactly that happened).+ self._arm_transcript_deadline(require_recent_quiet=True)returnif not response_id:@@ -551,6 +619,129 @@ class _OpenAIRealtimeSession:exc_info=True,)+ def _note_input_transcript(self) -> None:+ """Any input transcript proves the server can still hear."""+ self._last_transcript_at = time.monotonic()+ self._transcript_deadline = None++ def _arm_transcript_deadline(self, *, require_recent_quiet: bool) -> None:+ # Only arm while the session is at rest: with a response lifecycle in+ # flight the assistant is speaking and no transcript is owed yet.+ if self._transcript_deadline is not None or not self._response_idle.is_set():+ return+ now = time.monotonic()+ if require_recent_quiet and now - self._last_transcript_at < _SUPPRESS_ARM_MIN_QUIET_S:+ return+ self._transcript_deadline = now + _TRANSCRIPT_OVERDUE_S++ def _transcript_overdue(self) -> bool:+ if self._closed or self._session_contract is None:+ return False+ if self._transcript_deadline is None or not self._response_idle.is_set():+ return False+ return time.monotonic() >= self._transcript_deadline++ def _maybe_begin_rebuild(self) -> None:+ if not self._transcript_overdue():+ return+ if self._rebuild_task is not None and not self._rebuild_task.done():+ return+ self._transcript_deadline = None+ self._rebuild_task = asyncio.create_task(+ self._rebuild_transport(),+ name="openai-realtime-transport-rebuild",+ )++ async def _transport_was_rebuilt(self, old_events: Any) -> bool:+ """True when the receive pump should hop onto a fresh transport."""+ task = self._rebuild_task+ if task is not None and not task.done():+ try:+ await task+ except Exception: # noqa: BLE001 — a failed rebuild closes the session+ log.debug(+ "OpenAI Realtime transport rebuild await failed",+ exc_info=True,+ )+ return not self._closed and self._events is not old_events++ async def _rebuild_transport(self) -> None:+ """Replace the connection when a deaf session cannot be re-armed.++ BUG-064 escalation (grok-realtime 2026-07-16 09:23): the contract+ re-arm demonstrably ran and the server still never delivered another+ input transcript — the call sat in LISTENING until manual hang-up.+ A fresh transport carrying the same session contract is the only+ remaining repair. In-call conversation history is lost, which is+ strictly better than a session that can no longer hear at all. A+ failed rebuild closes the session so the orchestrator reports an+ honest provider error instead of keeping a silently deaf call open.+ """+ log.warning(+ "OpenAI Realtime rebuilding the transport: the server kept the "+ "session deaf (heard user turn, no input transcript within "+ "%.0f s) despite a session-contract re-arm",+ _TRANSCRIPT_OVERDUE_S,+ )+ old_cm = self._connection_cm+ try:+ connection_cm = self._client.realtime.connect(model=self._connect_model or _MODEL)+ connection = await connection_cm.__aenter__()+ try:+ await connection.session.update(session=self._session_contract)+ events = connection.__aiter__()++ async def _wait_ready() -> None:+ while True:+ event = await anext(events)+ event_type = str(getattr(event, "type", "") or "")+ if event_type == "session.updated":+ return+ if event_type == "error":+ raise RuntimeError(_error_message(event))++ await asyncio.wait_for(_wait_ready(), timeout=_HANDSHAKE_TIMEOUT_S)+ except BaseException as exc:+ try:+ await connection_cm.__aexit__(type(exc), exc, exc.__traceback__)+ except BaseException: # noqa: BLE001 — preserve the root cause+ log.debug(+ "OpenAI Realtime rebuild cleanup after failed handshake failed",+ exc_info=True,+ )+ raise+ except asyncio.CancelledError:+ raise+ except Exception: # noqa: BLE001 — degrade honestly instead of hanging deaf+ log.warning(+ "OpenAI Realtime transport rebuild failed; closing the dead session",+ exc_info=True,+ )+ await self.close()+ return+ # Swap fully initialized state first; only then retire the old+ # transport so send_audio and the receive() hop never observe a+ # half-built connection.+ self._conn = connection+ self._connection_cm = connection_cm+ self._events = events+ self._pending_response_markers.clear()+ self._accepted_response_ids.clear()+ self._response_had_tool_calls = False+ self._tool_response_done_seen = False+ self._pending_tool_call_ids.clear()+ self._last_item_id = ""+ self._transcript_deadline = None+ self._last_contract_rearm = float("-inf")+ self._response_idle.set()+ try:+ await old_cm.__aexit__(None, None, None)+ except Exception: # noqa: BLE001 — the dead transport may already be gone+ log.debug(+ "OpenAI Realtime old transport close failed after rebuild",+ exc_info=True,+ )+def _response_is_accepted(self, event: Any) -> bool:response_id = self._event_response_id(event)if response_id:@@ -564,6 +755,9 @@ class _OpenAIRealtimeSession:if self._closed:returnself._closed = True+ rebuild = self._rebuild_task+ if rebuild is not None and not rebuild.done() and rebuild is not asyncio.current_task():+ rebuild.cancel()self._pending_response_markers.clear()self._accepted_response_ids.clear()self._response_idle.set()@@ -602,9 +796,8 @@ class OpenAIRealtimeProvider:from openai import AsyncOpenAI # lazy (AP-26)client = AsyncOpenAI(api_key=self._api_key)- connection_cm = client.realtime.connect(- model=str(getattr(cfg, "model", "") or _MODEL)- )+ connect_model = str(getattr(cfg, "model", "") or _MODEL)+ connection_cm = client.realtime.connect(model=connect_model)try:connection = await connection_cm.__aenter__()except BaseException as exc:@@ -637,6 +830,7 @@ class OpenAIRealtimeProvider:client=client,session_id=str(uuid4()),session_payload=payload,+ connect_model=connect_model,)try:await connection.session.update(session=payload)diff --git a/tests/unit/realtime/test_grok_realtime.py b/tests/unit/realtime/test_grok_realtime.pyindex 196252e5e3..566a4d5dd7 100644--- a/tests/unit/realtime/test_grok_realtime.py+++ b/tests/unit/realtime/test_grok_realtime.py@@ -82,9 +82,13 @@ class _FakeRealtimeAPI:def __init__(self) -> None:self.models: list[str] = []self.conn = _FakeConn()+ # Transports handed out to reconnects (BUG-064 rebuild tests).+ self.extra_conns: list[_FakeConn] = []def connect(self, *, model: str) -> _FakeConnectCM:self.models.append(model)+ if len(self.models) > 1 and self.extra_conns:+ self.conn = self.extra_conns.pop(0)return _FakeConnectCM(self.conn)@@ -249,6 +253,56 @@ async def test_unsolicited_response_rearms_grok_transcription_contract(await session.close()+async def test_deaf_grok_session_rebuild_carries_the_grok_contract(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """BUG-064 escalation (live 2026-07-16 09:23): the re-arm ran and the Grok+ server still delivered no further input transcript. The transport rebuild+ must reconnect with the Grok model and re-send the full Grok session+ payload — including grok-transcribe input transcription — on the fresh+ connection."""+ _patch_client(monkeypatch)+ from jarvis.plugins.realtime import openai_realtime as shared_adapter++ monkeypatch.setattr(shared_adapter, "_TRANSCRIPT_OVERDUE_S", 0.0)+ session = await GrokRealtimeProvider(api_key="xai-test").open_session(+ RealtimeSessionConfig()+ )+ client = _FakeAsyncOpenAI.last+ assert client is not None+ api = client.realtime+ conn1 = api.conn+ conn2 = _FakeConn()+ conn2._events = iter([SimpleNamespace(type="session.updated")])+ api.extra_conns.append(conn2)+ conn1._events = iter(+ [+ SimpleNamespace(+ type="response.created",+ response=SimpleNamespace(id="resp-auto", metadata=None),+ ),+ SimpleNamespace(type="input_audio_buffer.speech_started"),+ ]+ )+ session._events = conn1.__aiter__()++ events = [event async for event in session.receive()]++ assert [event.type for event in events] == ["speech_started", "error"]+ assert events[1].recoverable is True+ assert api.models == ["grok-voice-latest", "grok-voice-latest"]+ rebuilt_contract = conn2.session_updates[0]+ assert rebuilt_contract["audio"]["input"]["transcription"] == {+ "model": "grok-transcribe"+ }+ assert (+ rebuilt_contract["audio"]["input"]["turn_detection"]["create_response"]+ is False+ )+ await session.close()++@pytest.mark.asyncioasync def test_keyless_provider_is_unavailable() -> None:assert await GrokRealtimeProvider().can_open_duplex_session() is Falsediff --git a/tests/unit/realtime/test_openai_realtime.py b/tests/unit/realtime/test_openai_realtime.pyindex 107a52c396..c57a5e8324 100644--- a/tests/unit/realtime/test_openai_realtime.py+++ b/tests/unit/realtime/test_openai_realtime.py@@ -10,6 +10,7 @@ from typing import Anyimport pytestfrom jarvis.brain.model_catalog import REALTIME_MODELS+from jarvis.plugins.realtime import openai_realtimefrom jarvis.plugins.realtime.openai_realtime import OpenAIRealtimeProviderfrom jarvis.realtime.protocol import RealtimeSessionConfig@@ -78,9 +79,18 @@ class _FakeRealtimeAPI:def __init__(self) -> None:self.connect_calls: list[str] = []self.last_conn = _FakeConn()+ # Transports handed out to reconnects (BUG-064 rebuild tests).+ self.extra_conns: list[_FakeConn] = []+ self.connect_error: Exception | None = Nonedef connect(self, *, model: str) -> _FakeConnectCM:self.connect_calls.append(model)+ if len(self.connect_calls) > 1:+ if self.connect_error is not None:+ raise self.connect_error+ self.last_conn = (+ self.extra_conns.pop(0) if self.extra_conns else _FakeConn()+ )return _FakeConnectCM(self.last_conn)@@ -972,3 +982,169 @@ async def test_interrupt_still_cancels_while_response_active(assert conn.response_cancels == ["<active>"]await session.close()+++async def test_deaf_session_rebuilds_the_transport_and_receive_hops_onto_it(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """BUG-064 escalation (grok-realtime 2026-07-16 09:23): the contract+ re-arm demonstrably ran and the server STILL never delivered another+ input transcript — the call sat in LISTENING until manual hang-up. Once+ the transcript deadline for a heard-but-untranscribed user turn expires,+ the adapter must open a fresh transport carrying the same session+ contract, and the receive pump must hop onto it instead of treating the+ old transport's end as the end of the voice session."""+ holder = _patch_openai_client(monkeypatch)+ monkeypatch.setattr(openai_realtime, "_TRANSCRIPT_OVERDUE_S", 0.0)+ session = await OpenAIRealtimeProvider(api_key="test-key").open_session(+ RealtimeSessionConfig(model="gpt-realtime")+ )+ api = holder["client"].realtime+ conn1 = api.last_conn+ conn2 = _FakeConn()+ conn2._events = iter(+ [+ SimpleNamespace(type="session.updated"),+ SimpleNamespace(+ type="conversation.item.input_audio_transcription.completed",+ item_id="post-rebuild-1",+ transcript="Repeated question",+ ),+ ]+ )+ api.extra_conns.append(conn2)+ conn1._events = iter(+ [+ SimpleNamespace(+ type="response.created",+ response=SimpleNamespace(id="resp-auto", metadata=None),+ ),+ SimpleNamespace(type="input_audio_buffer.speech_started"),+ ]+ )+ session._events = conn1.__aiter__()++ events = [event async for event in session.receive()]++ assert [event.type for event in events] == [+ "speech_started",+ "error",+ "input_transcript",+ ]+ assert events[1].recoverable is True+ assert "rebuilt" in str(events[1].error)+ assert events[2].text == "Repeated question"+ assert api.connect_calls == ["gpt-realtime", "gpt-realtime"]+ contract = conn2.session_updates[0]+ assert contract["audio"]["input"]["turn_detection"]["create_response"] is False+ assert contract["audio"]["input"]["transcription"]["model"]+ assert session._conn is conn2+ await session.close()+++async def test_committed_turn_arms_and_transcript_clears_the_deadline(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """An input_audio_buffer commit means the contract owes a transcript; the+ arriving transcript proves the server hears and must disarm the rebuild+ deadline so healthy sessions never reconnect."""+ holder = _patch_openai_client(monkeypatch)+ session = await OpenAIRealtimeProvider(api_key="test-key").open_session(+ RealtimeSessionConfig()+ )+ conn = holder["client"].realtime.last_conn+ conn._events = iter(+ [SimpleNamespace(type="input_audio_buffer.committed", item_id="item-1")]+ )+ session._events = conn.__aiter__()++ assert [event async for event in session.receive()] == []+ assert session._transcript_deadline is not None++ conn._events = iter(+ [+ SimpleNamespace(+ type="conversation.item.input_audio_transcription.completed",+ item_id="item-1",+ transcript="One request",+ )+ ]+ )+ session._events = conn.__aiter__()+ events = [event async for event in session.receive()]++ assert [event.type for event in events] == ["input_transcript"]+ assert session._transcript_deadline is None+ assert holder["client"].realtime.connect_calls == ["gpt-realtime"]+ await session.close()+++async def test_suppressed_duplicate_right_after_a_transcript_does_not_arm(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """The benign duplicate race (openai-realtime 2026-07-15): our+ response.create crossed the server's auto response moments after the+ input transcript arrived. That suppression must NOT arm the transcript+ deadline — the session demonstrably hears."""+ holder = _patch_openai_client(monkeypatch)+ session = await OpenAIRealtimeProvider(api_key="test-key").open_session(+ RealtimeSessionConfig()+ )+ conn = holder["client"].realtime.last_conn+ conn._events = iter(+ [+ SimpleNamespace(+ type="conversation.item.input_audio_transcription.completed",+ item_id="item-1",+ transcript="Heard fine",+ ),+ SimpleNamespace(+ type="response.created",+ response=SimpleNamespace(id="resp-duplicate", metadata=None),+ ),+ ]+ )+ session._events = conn.__aiter__()++ events = [event async for event in session.receive()]++ assert [event.type for event in events] == ["input_transcript"]+ assert conn.response_cancels == ["resp-duplicate"]+ assert session._transcript_deadline is None+ await session.close()+++async def test_failed_transport_rebuild_closes_the_session(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """A rebuild that cannot reconnect must close the session so the+ orchestrator reports an honest provider error — never keep a silently+ deaf call open."""+ holder = _patch_openai_client(monkeypatch)+ monkeypatch.setattr(openai_realtime, "_TRANSCRIPT_OVERDUE_S", 0.0)+ session = await OpenAIRealtimeProvider(api_key="test-key").open_session(+ RealtimeSessionConfig()+ )+ api = holder["client"].realtime+ api.connect_error = RuntimeError("reconnect refused")+ conn1 = api.last_conn+ conn1._events = iter(+ [+ SimpleNamespace(+ type="response.created",+ response=SimpleNamespace(id="resp-auto", metadata=None),+ ),+ SimpleNamespace(type="input_audio_buffer.speech_started"),+ ]+ )+ session._events = conn1.__aiter__()++ events = [event async for event in session.receive()]++ assert [event.type for event in events] == ["speech_started"]+ assert session._closed is True+ assert holder["client"].closed is True