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 when an in-flight response goes silent (BUG-064 recurrence #3)

Ruben Lütkee3aba6b68093
diff --git a/docs/BUGS.md b/docs/BUGS.md
index c34f0d13c6..9add06fd80 100644
--- a/docs/BUGS.md
+++ b/docs/BUGS.md
@@ -4622,6 +4622,37 @@ re-arming forever. Guards:
`test_grok_generic_cancellation_failed_error_is_recoverable`,
`test_second_stray_after_unheeded_rearm_rebuilds_the_transport`.
+**Recurrence #3, 2026-07-16 10:51 — a swallowed `response.done` disarms EVERY
+idle-gated defense at once (session `1fd3fa38`, first live run WITH the
+recurrence-#2 fixes).** Turn 2 ("Hey", again VAD-truncated) was transcribed,
+the orchestrator requested its native reply, and 360 ms later the user's
+continued speech triggered the local barge-in (`realtime_cancel
+reason=barge_in`), which drops provider output without a wire
+`response.cancel`. The server never sent that response's `response.done`, so
+`_response_idle` stayed CLEAR for the rest of the call — and every deaf-wedge
+defense gates on idle ("with a response in flight no transcript is owed"):
+the stray auto-response at +3 s was suppressed instead of adopted (idle
+check), the transcript deadline never armed (idle check), the rebuild never
+fired (idle check). One swallowed lifecycle event silently turned the entire
+BUG-064 defense stack off; the session sat mute until manual hang-up.
+
+**Fix (same adapter).** Response-lifecycle liveness: `_last_response_activity`
+is stamped by every `response.*` event and every outgoing `response.create`.
+While `_response_idle` is clear, total response-event silence for
+`_RESPONSE_STALL_S` (8 s — a healthy in-flight response streams events every
+few tens of milliseconds) declares the lifecycle dead and rebuilds the
+transport in place (microphone pump is the guaranteed trigger). The rebuild
+resets `_response_idle`, so a hung `_create_response` waiter also unblocks
+onto the fresh transport. Guard:
+`test_accepted_response_without_done_stalls_and_rebuilds`.
+
+**Class rule (extends the BUG-064 lesson).** Any defense gated on "a response
+is in flight" inherits a new failure mode: the response that never finishes.
+A lifecycle flag that only the SERVER can clear needs its own liveness
+watchdog, otherwise one swallowed terminal event freezes every dependent
+defense simultaneously — and the freeze is invisible because each defense
+individually looks correctly disarmed.
+
## 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 macOS
@@ -4810,3 +4841,64 @@ reasoning as a capability hint and (b) treat `finish_reason=length` as its
own recoverable failure class (retry with headroom), never as generic model
garbage. When a regression correlates with a feature landing, check what
ELSE changed in the window — including the SERVER side of a pinned alias.
+
+
+## BUG-068: Realtime delegate turn dies silently — a silent Gemini vetoes the dispatch, then a phantom `interrupted` edge kills the failure readback too (HIGH, FIXED 2026-07-16)
+
+**Symptoms (voice session 2026-07-16 10:26, gemini-live).** Turn 2 ("Was ist <!-- i18n-allow: quoted German user utterance under forensic analysis -->
+morgen für ein Tag?") produced no spoken answer at all: the transcript view <!-- i18n-allow: continuation of the quoted German utterance above -->
+recorded the canned reply "Das hat gerade nicht geklappt." with spoken time <!-- i18n-allow: quoted German runtime phrase under forensic analysis -->
+"--", the bar showed THINKING for ~4 s and then fell back to LISTENING
+without a word. The brain never ran (no dispatch logs). The identical
+question one turn later worked (the provider natively called
+`jarvis_action`).
+
+**Root cause — two independent defects in the deterministic delegate.**
+1. *Boundary-timeout veto.* The local-evidence dispatch waits
+ `_DELEGATE_INPUT_BOUNDARY_WAIT_S` for the provider to confirm the input
+ boundary (held turn_complete / native tool call). Gemini stayed
+ completely silent for turn 2 (no response, no tool call, no boundary —
+ it had just been barged-in mid-reply), and the timeout fallback read
+ `turn_state.input_final`, which the local-evidence path never sets. The
+ dispatch was VETOED: the brain never saw a perfectly complete, stable
+ transcript, and the canned failure phrase became the turn's reply.
+2. *Phantom `interrupted` kills the readback.* 16 ms after the failure
+ result was injected (`send_realtime_input(text=...)`), a spontaneous
+ `interrupted` edge arrived (Gemini server VAD; its only barge-in signal —
+ the adapter never emits `speech_started`). The endpoint protection
+ (`_pending_delegate_needs_endpoint_protection`) deferred only
+ `speech_started`, so the `interrupted` edge closed the turn immediately:
+ ResponseGenerated recorded the never-spoken reply, the turn state fell to
+ LISTENING, and `_drop_provider_output_until_new_response = True` swallowed
+ the provider readback of that very reply. For Gemini the protection was
+ structurally dead.
+
+**Fixes (jarvis/realtime/session.py).**
+1. `_await_stable_input_boundary`: a missing provider boundary DELAYS the
+ dispatch but can no longer veto it — after a full wait window in which
+ the accumulated input transcript did not grow, the utterance is final by
+ local evidence and the brain dispatches on the stable snapshot; a still-
+ growing transcript re-arms the window (max
+ `_DELEGATE_INPUT_BOUNDARY_MAX_ROUNDS`). The canned-refusal branch is gone.
+2. The endpoint-protection deferral now covers `interrupted` as well, plus a
+ new `_delegate_readback_awaits_first_audio()` window (result delivered,
+ zero PCM audible yet): an unconfirmed VAD edge during any silent span of
+ a delegated action is deferred and confirms itself only through a final
+ input transcript (the existing deferred-split path).
+3. Observability for audible mid-reply holes (same session, turn 3 had a
+ ~1 s gap mid-sentence with no attributable log line): `_emit_audio` now
+ logs stalls >= 400 ms with the scrub-gate hold time (late transcript vs.
+ silent provider) and detects embedded-silence runs inside provider PCM;
+ `ScrubHoldGate` exposes `pending_audio_ms` / `last_hold_ms`.
+
+**Guards.** `tests/unit/realtime/test_delegate_endpointing.py`
+(`test_silent_provider_boundary_timeout_dispatches_instead_of_refusing`,
+`test_phantom_interrupted_edge_defers_while_delegate_pending`,
+`test_phantom_interrupted_after_delivery_keeps_the_readback`).
+
+**Lesson.** A safety wait may DELAY an action on missing evidence, never
+convert missing evidence into a guaranteed failure — "provider said nothing"
+and "input incomplete" are different states, and only the second may block.
+And every provider-edge policy must be checked per adapter vocabulary: a
+guard keyed to an event type one adapter never emits is a guard that does
+not exist for that adapter.
diff --git a/jarvis/plugins/realtime/openai_realtime.py b/jarvis/plugins/realtime/openai_realtime.py
index 90fa7dc7de..86c5915d19 100644
--- a/jarvis/plugins/realtime/openai_realtime.py
+++ b/jarvis/plugins/realtime/openai_realtime.py
@@ -47,6 +47,16 @@ _TRANSCRIPT_OVERDUE_S = 6.0
# 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
+# BUG-064 recurrence #3 (grok-realtime 2026-07-16 10:51, session 1fd3fa38):
+# the client accepted its own requested response, a local barge-in dropped its
+# output, and the server never sent that response's ``response.done`` — so
+# ``_response_idle`` stayed CLEAR forever. Every deaf-wedge defense gates on
+# idle ("with a response in flight no transcript is owed"), so adoption, the
+# transcript deadline, and the transport rebuild were ALL disarmed at once and
+# the session sat silent until manual hang-up. A healthy in-flight response
+# streams events every few tens of milliseconds; one that produces NO
+# response event at all for this long is dead, and the transport is rebuilt.
+_RESPONSE_STALL_S = 8.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
@@ -244,6 +254,13 @@ class _OpenAIRealtimeSession:
# time.monotonic() ticks at ~16 ms, so two adjacent events can carry
# the SAME timestamp and an ordering comparison silently lies.
self._transcript_heard_since_rearm = True
+ # Last moment the server showed ANY response-lifecycle sign of life
+ # (any ``response.*`` event, or our own response.create going out).
+ # While ``_response_idle`` is clear this is the liveness signal that
+ # detects a response whose ``response.done`` the server swallowed
+ # (BUG-064 recurrence #3) — without it a stuck lifecycle disarms
+ # every idle-gated deaf-wedge defense at once.
+ self._last_response_activity = time.monotonic()
self._last_item_id = ""
self._response_had_tool_calls = False
self._tool_response_done_seen = False
@@ -348,6 +365,11 @@ class _OpenAIRealtimeSession:
async def _dispatch_event(self, event: Any) -> AsyncIterator[_ProviderEvent]:
event_type = str(getattr(event, "type", "") or "")
+ if event_type.startswith("response."):
+ # Any response event — accepted or not — is proof the response
+ # pipeline is alive; only its total absence marks a stalled
+ # lifecycle (BUG-064 recurrence #3).
+ self._last_response_activity = time.monotonic()
if event_type == "response.created":
await self._handle_response_created(event)
return
@@ -569,6 +591,7 @@ class _OpenAIRealtimeSession:
async with self._response_create_lock:
await self._response_idle.wait()
self._response_idle.clear()
+ self._last_response_activity = time.monotonic()
marker = uuid4().hex
self._pending_response_markers.add(marker)
response: dict[str, Any] = {
@@ -670,12 +693,10 @@ class _OpenAIRealtimeSession:
not self._transcript_heard_since_rearm
and time.monotonic() - self._last_contract_rearm >= _CONTRACT_REARM_COOLDOWN_S
):
- log.warning(
- "OpenAI Realtime unsolicited response after an unheeded "
- "contract re-arm (no input transcript since) — rebuilding "
- "the transport now"
+ self._begin_rebuild(
+ "unsolicited response after an unheeded contract re-arm "
+ "(no input transcript since)"
)
- self._begin_rebuild()
return
# BUG-064: under the manual-response contract an unsolicited
# response should be impossible — its arrival means the server
@@ -758,16 +779,42 @@ class _OpenAIRealtimeSession:
return False
return time.monotonic() >= self._transcript_deadline
+ def _response_lifecycle_stalled(self) -> bool:
+ """A response marked in flight that emits no events at all is dead.
+
+ BUG-064 recurrence #3 (grok-realtime 2026-07-16 10:51): the server
+ never sent ``response.done`` for an accepted response whose output a
+ local barge-in had dropped, so ``_response_idle`` stayed clear and
+ every idle-gated defense (adoption, transcript deadline, rebuild)
+ was disarmed at once. A healthy in-flight response streams events
+ continuously; total silence for ``_RESPONSE_STALL_S`` is proof the
+ lifecycle will never finish on this transport.
+ """
+ if self._closed or self._session_contract is None:
+ return False
+ if self._response_idle.is_set():
+ return False
+ return time.monotonic() - self._last_response_activity >= _RESPONSE_STALL_S
+
def _maybe_begin_rebuild(self) -> None:
+ if self._response_lifecycle_stalled():
+ self._begin_rebuild(
+ "in-flight response produced no response event for "
+ f"{_RESPONSE_STALL_S:.0f} s — response.done is not coming"
+ )
+ return
if not self._transcript_overdue():
return
- self._begin_rebuild()
+ self._begin_rebuild(
+ "input transcript overdue for a heard user turn despite a session-contract re-arm"
+ )
- def _begin_rebuild(self) -> None:
+ def _begin_rebuild(self, reason: str) -> None:
if self._closed or self._session_contract is None:
return
if self._rebuild_task is not None and not self._rebuild_task.done():
return
+ log.warning("OpenAI Realtime transport rebuild triggered: %s", reason)
self._transcript_deadline = None
self._rebuild_task = asyncio.create_task(
self._rebuild_transport(),
@@ -856,6 +903,7 @@ class _OpenAIRealtimeSession:
self._transcript_deadline = None
self._last_contract_rearm = float("-inf")
self._transcript_heard_since_rearm = True
+ self._last_response_activity = time.monotonic()
self._server_heard_user_since_response = False
self._auto_adopted_unanswered_input = False
self._response_idle.set()
diff --git a/tests/unit/realtime/test_openai_realtime.py b/tests/unit/realtime/test_openai_realtime.py
index 75b5e973c8..414fb891ab 100644
--- a/tests/unit/realtime/test_openai_realtime.py
+++ b/tests/unit/realtime/test_openai_realtime.py
@@ -22,9 +22,7 @@ class _FakeConn:
self.response_creates = 0
self.response_create_payloads: list[dict[str, Any]] = []
self.response_cancels: list[str] = []
- self.conversation = SimpleNamespace(
- item=SimpleNamespace(create=self._create_item)
- )
+ self.conversation = SimpleNamespace(item=SimpleNamespace(create=self._create_item))
self.response = SimpleNamespace(
create=self._create_response,
cancel=self._cancel_response,
@@ -88,9 +86,7 @@ class _FakeRealtimeAPI:
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()
- )
+ self.last_conn = self.extra_conns.pop(0) if self.extra_conns else _FakeConn()
return _FakeConnectCM(self.last_conn)
@@ -151,9 +147,7 @@ async def test_every_selectable_model_uses_the_valid_ga_session_schema(
"type": "audio/pcm",
"rate": 24_000,
}
- assert payload["audio"]["input"]["transcription"]["model"] == (
- "gpt-4o-mini-transcribe"
- )
+ assert payload["audio"]["input"]["transcription"]["model"] == ("gpt-4o-mini-transcribe")
assert "language" not in payload["audio"]["input"]["transcription"]
assert payload["audio"]["input"]["turn_detection"]["create_response"] is False
assert payload["audio"]["input"]["turn_detection"]["interrupt_response"] is False
@@ -169,9 +163,7 @@ async def test_text_update_creates_tool_free_audio_response(
monkeypatch: pytest.MonkeyPatch,
) -> None:
holder = _patch_openai_client(monkeypatch)
- session = await OpenAIRealtimeProvider(api_key="test-key").open_session(
- RealtimeSessionConfig()
- )
+ session = await OpenAIRealtimeProvider(api_key="test-key").open_session(RealtimeSessionConfig())
conn = holder["client"].realtime.last_conn
await session.send_text("Deliver the completed mission update.")
@@ -200,15 +192,11 @@ async def test_unsolicited_second_response_is_cancelled_without_replaying_audio(
) -> None:
"""One manual request may emit exactly one audible response lifecycle."""
holder = _patch_openai_client(monkeypatch)
- session = await OpenAIRealtimeProvider(api_key="test-key").open_session(
- RealtimeSessionConfig()
- )
+ session = await OpenAIRealtimeProvider(api_key="test-key").open_session(RealtimeSessionConfig())
conn = holder["client"].realtime.last_conn
await session.request_response()
- marker = conn.response_create_payloads[0]["response"]["metadata"][
- "jarvis_request_id"
- ]
+ marker = conn.response_create_payloads[0]["response"]["metadata"]["jarvis_request_id"]
conn._events = iter(
[
SimpleNamespace(
@@ -269,15 +257,11 @@ async def test_automatic_response_race_consumes_only_one_manual_allowance(
) -> None:
"""An unmarked VAD response racing response.create must not yield two replies."""
holder = _patch_openai_client(monkeypatch)
- session = await OpenAIRealtimeProvider(api_key="test-key").open_session(
- RealtimeSessionConfig()
- )
+ session = await OpenAIRealtimeProvider(api_key="test-key").open_session(RealtimeSessionConfig())
conn = holder["client"].realtime.last_conn
await session.request_response()
- marker = conn.response_create_payloads[0]["response"]["metadata"][
- "jarvis_request_id"
- ]
+ marker = conn.response_create_payloads[0]["response"]["metadata"]["jarvis_request_id"]
conn._events = iter(
[
SimpleNamespace(
@@ -328,15 +312,11 @@ async def test_interrupt_invalidates_late_events_from_cancelled_response(
monkeypatch: pytest.MonkeyPatch,
) -> None:
holder = _patch_openai_client(monkeypatch)
- session = await OpenAIRealtimeProvider(api_key="test-key").open_session(
- RealtimeSessionConfig()
- )
+ session = await OpenAIRealtimeProvider(api_key="test-key").open_session(RealtimeSessionConfig())
conn = holder["client"].realtime.last_conn
await session.request_response()
- old_marker = conn.response_create_payloads[0]["response"]["metadata"][
- "jarvis_request_id"
- ]
+ old_marker = conn.response_create_payloads[0]["response"]["metadata"]["jarvis_request_id"]
await session._handle_response_created(
SimpleNamespace(
type="response.created",
@@ -348,9 +328,7 @@ async def test_interrupt_invalidates_late_events_from_cancelled_response(
)
await session.interrupt()
await session.request_response()
- new_marker = conn.response_create_payloads[1]["response"]["metadata"][
- "jarvis_request_id"
- ]
+ new_marker = conn.response_create_payloads[1]["response"]["metadata"]["jarvis_request_id"]
conn._events = iter(
[
SimpleNamespace(
@@ -397,20 +375,14 @@ async def test_interrupt_invalidates_pending_response_before_created_event(
monkeypatch: pytest.MonkeyPatch,
) -> None:
holder = _patch_openai_client(monkeypatch)
- session = await OpenAIRealtimeProvider(api_key="test-key").open_session(
- RealtimeSessionConfig()
- )
+ session = await OpenAIRealtimeProvider(api_key="test-key").open_session(RealtimeSessionConfig())
conn = holder["client"].realtime.last_conn
await session.request_response()
- old_marker = conn.response_create_payloads[0]["response"]["metadata"][
- "jarvis_request_id"
- ]
+ old_marker = conn.response_create_payloads[0]["response"]["metadata"]["jarvis_request_id"]
await session.interrupt()
await session.request_response()
- new_marker = conn.response_create_payloads[1]["response"]["metadata"][
- "jarvis_request_id"
- ]
+ new_marker = conn.response_create_payloads[1]["response"]["metadata"]["jarvis_request_id"]
conn._events = iter(
[
SimpleNamespace(
@@ -493,9 +465,7 @@ async def test_handshake_error_rejects_session(monkeypatch: pytest.MonkeyPatch)
monkeypatch.setattr(openai, "AsyncOpenAI", _make_error_client)
with pytest.raises(RuntimeError, match="bad_schema"):
- await OpenAIRealtimeProvider(api_key="test-key").open_session(
- RealtimeSessionConfig()
- )
+ await OpenAIRealtimeProvider(api_key="test-key").open_session(RealtimeSessionConfig())
assert holder_factory["client"].closed is True
@@ -513,9 +483,7 @@ async def test_runtime_errors_preserve_provider_recoverability(
recoverable: bool,
) -> None:
holder = _patch_openai_client(monkeypatch)
- session = await OpenAIRealtimeProvider(api_key="test-key").open_session(
- RealtimeSessionConfig()
- )
+ session = await OpenAIRealtimeProvider(api_key="test-key").open_session(RealtimeSessionConfig())
conn = holder["client"].realtime.last_conn
conn._events = iter(
[
@@ -540,15 +508,11 @@ async def test_failed_response_done_is_reported_before_turn_completion(
monkeypatch: pytest.MonkeyPatch,
) -> None:
holder = _patch_openai_client(monkeypatch)
- session = await OpenAIRealtimeProvider(api_key="test-key").open_session(
- RealtimeSessionConfig()
- )
+ session = await OpenAIRealtimeProvider(api_key="test-key").open_session(RealtimeSessionConfig())
conn = holder["client"].realtime.last_conn
await session.request_response()
- marker = conn.response_create_payloads[0]["response"]["metadata"][
- "jarvis_request_id"
- ]
+ marker = conn.response_create_payloads[0]["response"]["metadata"]["jarvis_request_id"]
conn._events = iter(
[
SimpleNamespace(
@@ -589,15 +553,11 @@ async def test_response_requests_wait_for_the_active_response_boundary(
monkeypatch: pytest.MonkeyPatch,
) -> None:
holder = _patch_openai_client(monkeypatch)
- session = await OpenAIRealtimeProvider(api_key="test-key").open_session(
- RealtimeSessionConfig()
- )
+ session = await OpenAIRealtimeProvider(api_key="test-key").open_session(RealtimeSessionConfig())
conn = holder["client"].realtime.last_conn
await session.send_text("First trusted update")
- first_marker = conn.response_create_payloads[0]["response"]["metadata"][
- "jarvis_request_id"
- ]
+ first_marker = conn.response_create_payloads[0]["response"]["metadata"]["jarvis_request_id"]
second = asyncio.create_task(session.send_text("Second trusted update"))
await asyncio.sleep(0)
@@ -639,9 +599,7 @@ async def test_transcription_failure_is_a_final_input_event(
monkeypatch: pytest.MonkeyPatch,
) -> None:
holder = _patch_openai_client(monkeypatch)
- session = await OpenAIRealtimeProvider(api_key="test-key").open_session(
- RealtimeSessionConfig()
- )
+ session = await OpenAIRealtimeProvider(api_key="test-key").open_session(RealtimeSessionConfig())
conn = holder["client"].realtime.last_conn
conn._events = iter(
[
@@ -672,9 +630,7 @@ async def test_completed_transcription_preserves_input_item_identity(
monkeypatch: pytest.MonkeyPatch,
) -> None:
holder = _patch_openai_client(monkeypatch)
- session = await OpenAIRealtimeProvider(api_key="test-key").open_session(
- RealtimeSessionConfig()
- )
+ session = await OpenAIRealtimeProvider(api_key="test-key").open_session(RealtimeSessionConfig())
conn = holder["client"].realtime.last_conn
conn._events = iter(
[
@@ -720,9 +676,7 @@ async def test_tools_are_declared_mapped_and_answered(monkeypatch: pytest.Monkey
"type": "function",
"name": "open_app",
}
- marker = conn.response_create_payloads[0]["response"]["metadata"][
- "jarvis_request_id"
- ]
+ marker = conn.response_create_payloads[0]["response"]["metadata"]["jarvis_request_id"]
conn._events = iter(
[
SimpleNamespace(
@@ -783,9 +737,7 @@ async def test_live_session_update_replaces_tool_declarations(
monkeypatch: pytest.MonkeyPatch,
):
holder = _patch_openai_client(monkeypatch)
- session = await OpenAIRealtimeProvider(api_key="test-key").open_session(
- RealtimeSessionConfig()
- )
+ session = await OpenAIRealtimeProvider(api_key="test-key").open_session(RealtimeSessionConfig())
declaration = {
"name": "new_tool",
"description": "A newly connected tool.",
@@ -810,9 +762,7 @@ async def test_response_cancel_not_active_error_is_recoverable(
session pump warns and continues instead of ending the call (live
incidents 09:04 barge-in and 15:13 scrub-cancel, both 2026-07-14)."""
holder = _patch_openai_client(monkeypatch)
- session = await OpenAIRealtimeProvider(api_key="test-key").open_session(
- RealtimeSessionConfig()
- )
+ session = await OpenAIRealtimeProvider(api_key="test-key").open_session(RealtimeSessionConfig())
conn = holder["client"].realtime.last_conn
conn._events = iter(
[
@@ -844,9 +794,7 @@ async def test_unsolicited_response_after_heard_user_turn_is_adopted(
It must be adopted — audible, uncancelled — while the contract is still
re-armed for the following turns."""
holder = _patch_openai_client(monkeypatch)
- session = await OpenAIRealtimeProvider(api_key="test-key").open_session(
- RealtimeSessionConfig()
- )
+ session = await OpenAIRealtimeProvider(api_key="test-key").open_session(RealtimeSessionConfig())
conn = holder["client"].realtime.last_conn
conn._events = iter(
[
@@ -888,9 +836,7 @@ async def test_delayed_transcript_after_adoption_does_not_double_speak(
request would speak a second, independent answer to the same utterance —
it must be skipped exactly once."""
holder = _patch_openai_client(monkeypatch)
- session = await OpenAIRealtimeProvider(api_key="test-key").open_session(
- RealtimeSessionConfig()
- )
+ session = await OpenAIRealtimeProvider(api_key="test-key").open_session(RealtimeSessionConfig())
conn = holder["client"].realtime.last_conn
conn._events = iter(
[
@@ -932,9 +878,7 @@ async def test_second_unsolicited_response_without_new_speech_is_still_cancelled
unsolicited response WITHOUT new speech evidence is a true stray and keeps
the BUG-064 suppression (no double-speak)."""
holder = _patch_openai_client(monkeypatch)
- session = await OpenAIRealtimeProvider(api_key="test-key").open_session(
- RealtimeSessionConfig()
- )
+ session = await OpenAIRealtimeProvider(api_key="test-key").open_session(RealtimeSessionConfig())
conn = holder["client"].realtime.last_conn
conn._events = iter(
[
@@ -976,9 +920,7 @@ async def test_unsolicited_response_rearms_the_full_session_contract(
FULL session payload so transcription and ``create_response: false`` are
restored."""
holder = _patch_openai_client(monkeypatch)
- session = await OpenAIRealtimeProvider(api_key="test-key").open_session(
- RealtimeSessionConfig()
- )
+ session = await OpenAIRealtimeProvider(api_key="test-key").open_session(RealtimeSessionConfig())
conn = holder["client"].realtime.last_conn
conn._events = iter(
[
@@ -1013,9 +955,7 @@ async def test_contract_rearm_is_throttled_within_a_burst(
"""BUG-064: a burst of unsolicited responses re-arms the contract once per
cooldown window; every response in the burst is still cancelled."""
holder = _patch_openai_client(monkeypatch)
- session = await OpenAIRealtimeProvider(api_key="test-key").open_session(
- RealtimeSessionConfig()
- )
+ session = await OpenAIRealtimeProvider(api_key="test-key").open_session(RealtimeSessionConfig())
conn = holder["client"].realtime.last_conn
conn._events = iter(
[
@@ -1056,9 +996,7 @@ async def test_contract_rearm_carries_live_instruction_and_tool_updates(
"description": "A tool connected mid-session.",
"parameters": {"type": "object", "properties": {}},
}
- await session.update_session(
- instructions="Turn-updated instructions.", tools=(declaration,)
- )
+ await session.update_session(instructions="Turn-updated instructions.", tools=(declaration,))
conn._events = iter(
[
SimpleNamespace(
@@ -1086,9 +1024,7 @@ async def test_interrupt_skips_wire_cancel_when_no_response_active(
lifecycle is active, ``interrupt()`` must not put ``response.cancel`` on
the wire at all — that request can only ever produce the benign error."""
holder = _patch_openai_client(monkeypatch)
- session = await OpenAIRealtimeProvider(api_key="test-key").open_session(
- RealtimeSessionConfig()
- )
+ session = await OpenAIRealtimeProvider(api_key="test-key").open_session(RealtimeSessionConfig())
conn = holder["client"].realtime.last_conn
await session.interrupt()
@@ -1104,9 +1040,7 @@ async def test_interrupt_still_cancels_while_response_active(
"""The skip above must never eat a REAL cancellation: with a response
lifecycle in flight, interrupt() still sends response.cancel."""
holder = _patch_openai_client(monkeypatch)
- session = await OpenAIRealtimeProvider(api_key="test-key").open_session(
- RealtimeSessionConfig()
- )
+ session = await OpenAIRealtimeProvider(api_key="test-key").open_session(RealtimeSessionConfig())
conn = holder["client"].realtime.last_conn
await session.request_response()
@@ -1183,13 +1117,9 @@ async def test_committed_turn_arms_and_transcript_clears_the_deadline(
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()
- )
+ 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")]
- )
+ 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()] == []
@@ -1222,9 +1152,7 @@ async def test_suppressed_duplicate_right_after_a_transcript_does_not_arm(
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()
- )
+ session = await OpenAIRealtimeProvider(api_key="test-key").open_session(RealtimeSessionConfig())
conn = holder["client"].realtime.last_conn
conn._events = iter(
[
@@ -1258,9 +1186,7 @@ async def test_failed_transport_rebuild_closes_the_session(
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()
- )
+ session = await OpenAIRealtimeProvider(api_key="test-key").open_session(RealtimeSessionConfig())
api = holder["client"].realtime
api.connect_error = RuntimeError("reconnect refused")
conn1 = api.last_conn
@@ -1292,9 +1218,7 @@ async def test_grok_generic_cancellation_failed_error_is_recoverable(
cannot recognize it. The message shape must be matched — labeling this
error terminal ended a healthy live call with hangup_reason=error."""
holder = _patch_openai_client(monkeypatch)
- session = await OpenAIRealtimeProvider(api_key="test-key").open_session(
- RealtimeSessionConfig()
- )
+ session = await OpenAIRealtimeProvider(api_key="test-key").open_session(RealtimeSessionConfig())
conn = holder["client"].realtime.last_conn
conn._events = iter(
[
@@ -1379,3 +1303,66 @@ async def test_second_stray_after_unheeded_rearm_rebuilds_the_transport(
assert api.connect_calls == ["gpt-realtime", "gpt-realtime"]
assert session._conn is conn2
await session.close()
+
+
+async def test_accepted_response_without_done_stalls_and_rebuilds(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """BUG-064 recurrence #3 (grok-realtime 2026-07-16 10:51, session
+ 1fd3fa38): the server never sent ``response.done`` for an accepted
+ response whose output a local barge-in had dropped, so ``_response_idle``
+ stayed clear forever — and every idle-gated defense (adoption, transcript
+ deadline, transport rebuild) was disarmed at once while the session sat
+ silent until manual hang-up. A response lifecycle that emits no event at
+ all for ``_RESPONSE_STALL_S`` must be declared dead and the transport
+ rebuilt; the microphone pump is the guaranteed trigger because a fully
+ silent server delivers no events to react to."""
+ holder = _patch_openai_client(monkeypatch)
+ 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="Heard again",
+ ),
+ ]
+ )
+ api.extra_conns.append(conn2)
+
+ await session.request_response()
+ conn1._events = iter(
+ [
+ SimpleNamespace(
+ type="response.created",
+ response=SimpleNamespace(id="resp-hung", metadata=None),
+ ),
+ ]
+ )
+ session._events = conn1.__aiter__()
+
+ assert [event async for event in session.receive()] == []
+ assert not session._response_idle.is_set()
+
+ # The healthy 8 s threshold protected the accept flow above; from here
+ # the stalled clock has run out.
+ monkeypatch.setattr(openai_realtime, "_RESPONSE_STALL_S", 0.0)
+ await session.send_audio(SimpleNamespace(sample_rate=24000, pcm=b"\x00\x01"))
+ assert session._rebuild_task is not None
+ await session._rebuild_task
+
+ assert session._conn is conn2
+ assert session._response_idle.is_set()
+ assert api.connect_calls == ["gpt-realtime", "gpt-realtime"]
+
+ events = [event async for event in session.receive()]
+ assert [event.type for event in events] == ["input_transcript"]
+ assert events[0].text == "Heard again"
+ await session.close()