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): let a delegated turn actually own its answer

rubenluetke10-beep6a833480a625
diff --git a/jarvis/plugins/realtime/codex_subscription.py b/jarvis/plugins/realtime/codex_subscription.py
index 07ae10b81a..03321a67dd 100644
--- a/jarvis/plugins/realtime/codex_subscription.py
+++ b/jarvis/plugins/realtime/codex_subscription.py
@@ -93,6 +93,13 @@ _UNGROUNDED_RESPONSE_GRACE_S = 3.0
# it for other providers — so rebuilding on the first one ended a healthy call
# every time the far end transcribed slowly. A run of them is the loop.
_UNGROUNDED_CAPTIONS_BEFORE_REBUILD = 2
+# After a LOCAL interrupt (barge-in or a delegation retiring the competing
+# native answer), the far end predictably reacts with echo captions of its own
+# truncated speech and continuation fragments. Inside this window those are
+# consequences of OUR cut, not evidence of a self-dialogue loop — counting
+# them toward the rebuild threshold turned every delegation into a transport
+# rebuild storm (live 2026-08-04: 11 rejections, 3 rebuilds in 43 s).
+_POST_INTERRUPT_GRACE_S = 3.0
# How long a trusted injection's permit may wait for the response it provokes.
# Generous relative to the far end's latency, and bounded so an injection that
# was never answered cannot authorize an unrelated response later in the call.
@@ -663,6 +670,9 @@ class _CodexSubscriptionRealtimeSession:
# Local copy of the interrupt barrier; a mismatch means ``interrupt``
# ran and everything still queued for the cut response is stale.
output_barrier = self._output_drop_barrier
+ # Monotonic deadline of the post-interrupt grace window (see
+ # ``_POST_INTERRUPT_GRACE_S``); 0.0 while no interrupt is recent.
+ interrupt_grace_until = 0.0
# Item types this session has already reported as unhandled. The v3 item
# vocabulary is only partly known, and silently swallowing the rest is
# why neither the real terminal-response item nor the never-observed
@@ -830,12 +840,22 @@ class _CodexSubscriptionRealtimeSession:
else:
response_allowed = False
response_rejected_at = response_opened_at
- log.warning(
- "Codex subscription realtime rejected an automatic response "
- "without a fresh local user utterance (%s); interrupting a "
- "probable self-echo turn",
- source,
- )
+ if _within_interrupt_grace():
+ # Expected fallout of OUR own cut: the far end streams the
+ # remainder of the retired answer for a while. Dropping it
+ # is routine, not an anomaly.
+ log.info(
+ "Codex subscription realtime dropped the far end's "
+ "post-interrupt continuation (%s)",
+ source,
+ )
+ else:
+ log.warning(
+ "Codex subscription realtime rejected an automatic response "
+ "without a fresh local user utterance (%s); interrupting a "
+ "probable self-echo turn",
+ source,
+ )
await self._interrupt_active_codex_turn()
return response_allowed
@@ -884,6 +904,13 @@ class _CodexSubscriptionRealtimeSession:
output_barrier = self._output_drop_barrier
return True
+ def _within_interrupt_grace() -> bool:
+ """Whether a local interrupt is recent enough to explain fallout."""
+ return (
+ interrupt_grace_until > 0.0
+ and asyncio.get_running_loop().time() < interrupt_grace_until
+ )
+
def _caption_is_too_early_to_judge() -> bool:
"""Whether an ungrounded caption landed too soon to count as evidence.
@@ -1020,6 +1047,19 @@ class _CodexSubscriptionRealtimeSession:
_cancel_completion()
_reset_assistant_capture()
_close_response(spent=True)
+ # Jarvis owns everything spoken up to this cut (barge-in or
+ # a delegation taking the turn): an utterance that already
+ # happened must not re-authorize the far end's answer AFTER
+ # the interrupt. Closing the open response alone left that
+ # entitlement standing whenever the interrupt beat the
+ # response's first frame, and the "retired" answer simply
+ # started afterwards.
+ consumed_input_generation = max(
+ consumed_input_generation, local_input_generation
+ )
+ interrupt_grace_until = (
+ asyncio.get_running_loop().time() + _POST_INTERRUPT_GRACE_S
+ )
self._assistant_delta_text = ""
completion_emitted = True
if queue_kind == "local_input_failed":
@@ -1369,6 +1409,18 @@ class _CodexSubscriptionRealtimeSession:
)
_close_response(spent=True)
continue
+ if _within_interrupt_grace():
+ # A cut response's echo of its own truncated
+ # speech, not the far end inventing a turn:
+ # never let OUR interrupt feed the rebuild
+ # counter.
+ log.info(
+ "Ignoring an ungrounded server user caption "
+ "inside the post-interrupt window: %r",
+ text[:80],
+ )
+ _close_response(spent=True)
+ continue
ungrounded_final_captions += 1
if (
ungrounded_final_captions
diff --git a/jarvis/realtime/session.py b/jarvis/realtime/session.py
index cb0df3b5ca..b2c02641f0 100644
--- a/jarvis/realtime/session.py
+++ b/jarvis/realtime/session.py
@@ -5678,6 +5678,17 @@ class RealtimeVoiceSession:
and not turn_state.pending_tool_calls
and not turn_state.provider_boundary_seen
):
+ if self._drop_provider_output_until_new_response:
+ # The competing native response was already retired when the
+ # delegate took the turn; a full boundary wait here would only
+ # add dead air before the trusted reply. Re-assert the
+ # interrupt (idempotent) so the far end is cut no matter which
+ # path armed the withhold, and inject immediately.
+ try:
+ await self._session.interrupt()
+ except Exception: # noqa: BLE001, S110 — best-effort boundary
+ pass
+ return
try:
await asyncio.wait_for(
turn_state.provider_ready.wait(),
@@ -5901,6 +5912,21 @@ class RealtimeVoiceSession:
turn_state: _DelegateTurnState,
) -> None:
try:
+ if bool(
+ getattr(self._session, "creates_responses_automatically", False)
+ ):
+ # This transport is already answering the SAME utterance on its
+ # own VAD, and it has no server-side response cancel. Retire
+ # that competing native answer now — the adapter drops its
+ # remaining frames — because merely withholding it lets it
+ # resume MID-SENTENCE the moment the trusted delivery clears
+ # the withhold (live 2026-08-04: ". It's concrete, not
+ # fluffy…" played instead of the computed weather answer).
+ self._drop_provider_output_until_new_response = True
+ try:
+ await self._session.interrupt()
+ except Exception: # noqa: BLE001, S110 — best-effort retire
+ pass
if turn_state.wait_for_provider_boundary or bool(
getattr(
self._session,
diff --git a/tests/unit/realtime/test_codex_subscription.py b/tests/unit/realtime/test_codex_subscription.py
index f19e0525d8..998af0ddec 100644
--- a/tests/unit/realtime/test_codex_subscription.py
+++ b/tests/unit/realtime/test_codex_subscription.py
@@ -2284,6 +2284,134 @@ async def test_interrupt_drops_the_remainder_without_any_codex_turn_id(
await session.close()
+async def test_interrupt_retires_an_entitlement_the_response_never_used(
+ monkeypatch,
+) -> None:
+ """A delegation interrupt must beat the response's FIRST frame too.
+
+ When Jarvis takes a turn deterministically it interrupts before the far
+ end has begun streaming. Closing only the OPEN response left the spoken
+ utterance's entitlement standing, so the "retired" native answer simply
+ started a moment later and played over the trusted delegate reply (live
+ 2026-08-04: an unrelated English fragment replaced the computed weather
+ answer).
+ """
+ speech = (1000).to_bytes(2, "little", signed=True) * 480
+ endpoint = _FakeAudioEndpoint(
+ output_schedule=((0.35, speech), (0.02, speech))
+ )
+ transcriber = _ScheduledInputTranscriber(
+ [
+ (0.0, InputTranscriptEvent(kind="speech_started")),
+ (
+ 0.02,
+ InputTranscriptEvent(
+ kind="transcript", text="Wetter morgen?", is_final=True
+ ),
+ ),
+ ]
+ )
+ client = _Client()
+ client.subscription = _keeps_stream_open()
+ session = await _provider(
+ client,
+ endpoint=endpoint,
+ input_transcriber_factory=lambda: transcriber,
+ ).open_session(RealtimeSessionConfig())
+
+ stream = session.receive()
+ async with asyncio.timeout(1.5):
+ async for event in stream:
+ if event.type == "input_transcript" and event.is_final:
+ break
+
+ await session.interrupt()
+
+ audio_after = []
+ with contextlib.suppress(TimeoutError):
+ async with asyncio.timeout(0.8):
+ async for event in stream:
+ if event.type == "audio_delta":
+ audio_after.append(event)
+
+ assert audio_after == []
+ await session.close()
+
+
+async def test_post_interrupt_captions_do_not_feed_the_rebuild_counter(
+ monkeypatch,
+) -> None:
+ """Echo captions caused by OUR OWN cut must not tear the transport down.
+
+ The far end predictably reacts to a local interrupt with captions of its
+ own truncated speech. Counting those toward the self-dialogue rebuild
+ threshold turned every delegation into a rebuild storm (live 2026-08-04:
+ three transport rebuilds inside one 43 s call).
+ """
+ monkeypatch.setattr(codex_subscription_mod, "_UNGROUNDED_RESPONSE_GRACE_S", 0.0)
+ client = _Client()
+ client.subscription = _ScheduledSubscription(
+ [
+ (
+ 0.01,
+ _Notification(
+ "thread/realtime/transcript/done",
+ {"threadId": "thread-1", "role": "assistant", "text": "Hi."},
+ ),
+ ),
+ (
+ 0.02,
+ _Notification(
+ "thread/realtime/transcript/done",
+ {"threadId": "thread-1", "role": "user", "text": "Thanks."},
+ ),
+ ),
+ (
+ 0.0,
+ _Notification(
+ "thread/realtime/transcript/done",
+ {"threadId": "thread-1", "role": "user", "text": "Sure thing."},
+ ),
+ ),
+ (
+ 0.0,
+ _Notification(
+ "thread/realtime/transcript/done",
+ {"threadId": "thread-1", "role": "user", "text": "Anything else?"},
+ ),
+ ),
+ ]
+ )
+ session = await _provider(
+ client,
+ input_transcriber_factory=_GroundedThenQuietTranscriber,
+ ).open_session(RealtimeSessionConfig())
+
+ stream = session.receive()
+ async with asyncio.timeout(1.5):
+ async for event in stream:
+ if event.type == "output_transcript_delta":
+ break
+
+ await session.interrupt()
+
+ events = []
+ with contextlib.suppress(TimeoutError):
+ async with asyncio.timeout(0.8):
+ async for event in stream:
+ events.append(event)
+
+ rebuild_errors = [
+ event
+ for event in events
+ if event.type == "error" and getattr(event, "reconnect_advised", False)
+ ]
+ assert rebuild_errors == []
+ await session.close()
+
+
@pytest.mark.asyncio
async def test_truncate_reports_the_played_position_to_the_model() -> None:
"""AD-3: the model must learn how much of its answer was actually heard.