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): stop counting the echo of our own cut as a self-dialogue

rubenluetke10-beepbe5cc60e8757
diff --git a/jarvis/plugins/realtime/codex_subscription.py b/jarvis/plugins/realtime/codex_subscription.py
index 72c32b9225..fb027e93af 100644
--- a/jarvis/plugins/realtime/codex_subscription.py
+++ b/jarvis/plugins/realtime/codex_subscription.py
@@ -93,13 +93,30 @@ _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
+# After a LOCAL interrupt, 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).
+#
+# There are THREE local interrupt sources, and the window must cover all of
+# them: a barge-in, a delegation retiring the competing native answer, and the
+# grounding gate REFUSING an automatic response. The refusal was missing, and
+# it is the one that fires in a storm: each refusal cut a turn, the far end
+# captioned its own truncated words back as a user turn, and two of those
+# tore the transport down — the rebuild storm of 2026-08-06 17:41, where the
+# invented "user" line was literally the first words of the answer we had just
+# cut ("Hi! Schön"). # i18n-allow: quoted German live caption, the evidence
+# See BUG-124.
_POST_INTERRUPT_GRACE_S = 3.0
+# A refusal storm is the honest self-dialogue signal: captions are polluted by
+# the far end's reaction to our own cuts, refusals are not. This many refused
+# responses with no grounded utterance in between, inside the window below,
+# means the far end is talking to itself and the transport needs replacing.
+# The window makes it a RATE: a long call may legitimately refuse the odd
+# stray response without ever being in a loop.
+_REFUSALS_BEFORE_REBUILD = 5
+_REFUSAL_STORM_WINDOW_S = 10.0
# When a response's audible audio flows while the far end's own transcript is
# still absent, the session's scrub gate holds ALL of it fail-closed — and
# ChatGPT-Live's transcripts lag their audio by SECONDS (measured live
@@ -685,6 +702,18 @@ class _CodexSubscriptionRealtimeSession:
# nor a fresh local utterance behind them. One is normal on a laggy
# link; a run of them is the self-dialogue loop.
ungrounded_final_captions = 0
+ # Consecutive REFUSED responses and when that run started. Unlike the
+ # caption counter above this signal is not polluted by the far end's
+ # reaction to our own cuts, so it — not the captions — is what decides
+ # a self-dialogue loop (BUG-124).
+ refusal_run = 0
+ refusal_run_started_at = 0.0
+ # Whether this run already logged that it stopped interrupting.
+ refusal_storm_noted = False
+ # Set by the refusal path once the run proves a loop; the receive loop
+ # turns it into the user-facing reconnect advice on its next pass
+ # (``_begin_response`` is not a generator and cannot yield).
+ self_dialogue_detected = False
grounding_loss_reported = False
assistant_audio = bytearray()
assistant_audio_active = False
@@ -878,6 +907,8 @@ class _CodexSubscriptionRealtimeSession:
nonlocal active_response_generation, response_allowed, response_open
nonlocal response_opened_at, response_rejected_at
nonlocal entitled_generation, entitlement_spent
+ nonlocal interrupt_grace_until, refusal_run, refusal_run_started_at
+ nonlocal refusal_storm_noted, self_dialogue_detected
if response_open:
if response_allowed or not _rejected_response_is_stale():
return response_allowed
@@ -929,7 +960,16 @@ class _CodexSubscriptionRealtimeSession:
else:
response_allowed = False
response_rejected_at = response_opened_at
- if _within_interrupt_grace():
+ # Evaluate the window BEFORE this refusal arms its own, or the
+ # log would call every refusal a post-interrupt continuation.
+ post_interrupt = _within_interrupt_grace()
+ now = response_opened_at
+ if now - refusal_run_started_at > _REFUSAL_STORM_WINDOW_S:
+ refusal_run = 0
+ refusal_run_started_at = now
+ refusal_storm_noted = False
+ refusal_run += 1
+ if post_interrupt:
# 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.
@@ -941,11 +981,58 @@ class _CodexSubscriptionRealtimeSession:
else:
log.warning(
"Codex subscription realtime rejected an automatic response "
- "without a fresh local user utterance (%s); interrupting a "
- "probable self-echo turn",
+ "without a fresh local user utterance (%s); refusal %d of "
+ "the current run",
source,
+ refusal_run,
+ )
+ # A refusal IS a local interrupt, and the far end answers one
+ # with echo captions of its own truncated speech. Without this
+ # window those captions counted as invented user turns and two
+ # of them tore the transport down (BUG-124).
+ interrupt_grace_until = now + _POST_INTERRUPT_GRACE_S
+ if refusal_run <= 1:
+ await self._interrupt_active_codex_turn()
+ elif not refusal_storm_noted:
+ # Cutting a turn makes ChatGPT-Live start a new one, which
+ # is refused, which is cut: the interrupt is what keeps the
+ # cycle spinning. The refused audio is dropped before it can
+ # ever reach the user either way, so past the first refusal
+ # the far end is simply left to run out.
+ refusal_storm_noted = True
+ log.info(
+ "Codex subscription realtime is in a refusal run — "
+ "dropping the far end's automatic responses without "
+ "interrupting, so a cut cannot provoke the next one"
+ )
+ if (
+ refusal_run >= _REFUSALS_BEFORE_REBUILD
+ and not self_dialogue_detected
+ ):
+ self_dialogue_detected = True
+ log.warning(
+ "Codex subscription refused %d automatic responses "
+ "within %.0f s with no locally grounded speech in "
+ "between; the far end is talking to itself and the "
+ "realtime transport needs replacing",
+ refusal_run,
+ _REFUSAL_STORM_WINDOW_S,
)
- await self._interrupt_active_codex_turn()
+ try:
+ # Wake the receive loop NOW: it owns the yield, and a
+ # loop that has gone quiet would otherwise leave the
+ # verdict unreported until the far end happens to send
+ # again — the silent-mute failure this detector exists
+ # to end. A full queue already guarantees that wake-up,
+ # so dropping the nudge there changes nothing.
+ queue.put_nowait(("self_dialogue", None))
+ except asyncio.QueueFull:
+ pass
+ if response_allowed:
+ # An authorized response proves there is no loop: whatever the
+ # run was counting ended here.
+ refusal_run = 0
+ refusal_storm_noted = False
return response_allowed
def _close_response(*, spent: bool) -> None:
@@ -1141,6 +1228,20 @@ class _CodexSubscriptionRealtimeSession:
timer_tasks.add(completion_task)
completion_task.add_done_callback(timer_tasks.discard)
+ async def _retire_self_dialogue_turn() -> None:
+ """Silence the looping far end before the transport is replaced.
+
+ Shared by both detectors — the refusal run and the caption run —
+ so a rebuild always leaves the same state behind whichever proved
+ the loop.
+ """
+ nonlocal completion_emitted
+ _cancel_completion()
+ completion_emitted = True
+ _reset_assistant_capture()
+ await self._interrupt_active_codex_turn()
+ _close_response(spent=True)
+
# Start local input first. A user may finish speaking while the
# handshake is still draining already-buffered server notifications;
# scheduling the network pump first could otherwise reject the valid
@@ -1160,6 +1261,20 @@ class _CodexSubscriptionRealtimeSession:
try:
while True:
queue_kind, payload = await queue.get()
+ if self_dialogue_detected:
+ # Raised by ``_begin_response``, which cannot yield. The
+ # far end is answering itself; a clean transport is the
+ # only recovery, and saying so is what keeps a mute call
+ # from looking healthy (AP-30).
+ await _retire_self_dialogue_turn()
+ yield _ProviderEvent(
+ type="error",
+ error=_ungrounded_turn_message(self._language),
+ recoverable=True,
+ reconnect_advised=True,
+ )
+ yield _ProviderEvent(type="turn_complete")
+ return
if _interrupt_barrier_moved():
# Barge-in. ChatGPT-Live keeps streaming the rest of the
# answer the user talked over, so retire the cut response
@@ -1267,6 +1382,11 @@ class _CodexSubscriptionRealtimeSession:
user_final_emitted = False
missing_boundary_emitted = False
ungrounded_final_captions = 0
+ # Somebody really spoke into this host's microphone —
+ # the one signal the far end cannot fake. Whatever the
+ # refusal run was counting, it was not a loop.
+ refusal_run = 0
+ refusal_storm_noted = False
_cancel_completion()
completion_emitted = False
self._assistant_delta_text = ""
@@ -1671,11 +1791,7 @@ class _CodexSubscriptionRealtimeSession:
ungrounded_final_captions,
text[:80],
)
- _cancel_completion()
- completion_emitted = True
- _reset_assistant_capture()
- await self._interrupt_active_codex_turn()
- _close_response(spent=True)
+ await _retire_self_dialogue_turn()
yield _ProviderEvent(
type="error",
error=_ungrounded_turn_message(self._language),
diff --git a/jarvis/realtime/session.py b/jarvis/realtime/session.py
index 2bbf61ff32..94206c37ac 100644
--- a/jarvis/realtime/session.py
+++ b/jarvis/realtime/session.py
@@ -168,6 +168,11 @@ _EMBEDDED_SILENCE_PEAK = 200
# of reconnect-storming.
_TRANSPORT_REBUILD_WINDOW_S = 120.0
_TRANSPORT_REBUILD_MAX_PER_WINDOW = 3
+# How soon a repeat of the SAME advised-reconnect cause proves the rebuild it
+# followed did not fix anything. Longer than a rebuild's own handshake (a few
+# seconds) so the fresh transport gets a fair chance to work, short enough that
+# a genuinely healed call never trips it (BUG-124).
+_ADVISED_REBUILD_RELAPSE_S = 15.0
_CREDENTIAL_TERMINAL_STATUSES = frozenset(
{BAD_KEY, NO_CREDITS, NOT_CONFIGURED}
)
@@ -319,7 +324,9 @@ _DELEGATE_DECLARATION: dict[str, Any] = {
"(click, type, and navigate inside any application window until the "
"task is finished), manage files, start a background research or "
"coding mission the user explicitly asked to run, read or write the "
- "user's private Wiki memory, and inspect the current MCP, CLI, tool, "
+ "user's private Wiki memory — including recalling anything from the "
+ "user's own past (what they did, said, visited, planned, or once "
+ "told Jarvis) — and inspect the current MCP, CLI, tool, "
"integration, configuration, or system state. Also call this to "
"relay the user's answer to a pending confirmation question. Never "
"call it just to look up general world knowledge, public facts or "
@@ -349,7 +356,12 @@ _DELEGATE_ROLE_DIRECTIVE = (
"Wiki or personal memory, their people, their projects, their files, their "
"apps, their settings, their system state, or any action on their computer "
"— including a vague, elliptical, or garbled follow-up that refers back to "
- "such a turn ('and what else is in there?', 'what does it say?'). You "
+ "such a turn ('and what else is in there?', 'what does it say?'). The "
+ "user's own PAST is part of that world: any 'do you remember', 'what was "
+ "that again', 'when did I / were we', 'how was X called' question about "
+ "something they did, said, visited, planned, or once told you MUST be "
+ "delegated — the answer lives in the Wiki memory, and answering it from "
+ "conversation guesswork invents the user's own life. You "
"cannot see any of it yourself, so guessing is always wrong. "
"General world knowledge is YOURS: public facts and figures, well-known "
"people and companies, definitions, explanations, recommendations, "
@@ -406,7 +418,8 @@ _DELEGATE_DISCOURAGED_DIRECTIVE = (
"conversation. Answer it directly from your own knowledge now, without "
"calling any function. Call jarvis_action on this turn ONLY if the "
"request actually needs the user's own world (their Wiki or personal "
- "memory, their files, apps, settings, or system state), performs a "
+ "memory, their own past — 'do you remember', 'when did I' — their "
+ "files, apps, settings, or system state), performs a "
"real action on their computer, or explicitly asks you to look up, "
"check, or verify current information you may only know in an "
"outdated state."
@@ -1408,6 +1421,10 @@ class RealtimeVoiceSession:
# the pump rebuilds proactively instead of waiting for the forced
# close (which can race the recovery chain and end the call).
self._advised_reconnect_detail: str | None = None
+ # The cause of the most recently REQUESTED advised rebuild, kept so
+ # the same cause coming back moments later can be recognized as a
+ # rebuild that did not help (BUG-124).
+ self._last_advised_reconnect_detail: str | None = None
# Monotonic timestamps of in-place transport rebuilds (BUG-071),
# pruned to the rolling _TRANSPORT_REBUILD_WINDOW_S budget window.
self._transport_rebuild_times: list[float] = []
@@ -3480,7 +3497,7 @@ class RealtimeVoiceSession:
{"type": "provider_warning", "error": message}
)
if getattr(event, "reconnect_advised", False):
- self._schedule_advised_reconnect(message)
+ await self._schedule_advised_reconnect(message)
continue
# A terminal provider failure can strike while the tail of
# the current reply is still held by the scrub gate.
@@ -3665,7 +3682,7 @@ class RealtimeVoiceSession:
pass
return None
- def _schedule_advised_reconnect(self, detail: str) -> None:
+ async def _schedule_advised_reconnect(self, detail: str) -> None:
"""React to a provider's pre-disconnect notice (GoAway).
The transport still works, but the server will force-close it when
@@ -3681,6 +3698,21 @@ class RealtimeVoiceSession:
return
if self._session is self._transport_rebuild_pending:
return # a rebuild is already queued or running
+ if self._advised_rebuild_relapsed(detail):
+ # A rebuild that has to be repeated for the SAME cause seconds
+ # after the last one is not a recovery — it is a loop the fresh
+ # transport walks straight back into (live 2026-08-06 17:41:
+ # rebuild 1/3 at :53, the identical advice back at :56, rebuild
+ # 2/3 at :59). Burning the remaining budget only delays the same
+ # ending by a worse route, so stop here and say why. Deliberately
+ # NOT a cross-provider failover: a subscription-backed provider
+ # forbids falling through to metered voice, and the ChatGPT card
+ # promises the call stops instead.
+ await self._fail_terminally(
+ "the realtime provider keeps producing the same fault "
+ f"immediately after a transport rebuild; ending the call: {detail}"
+ )
+ return
self._advised_reconnect_detail = detail
if (
self._output_active
@@ -3696,12 +3728,30 @@ class RealtimeVoiceSession:
return
self._request_advised_rebuild()
+ def _advised_rebuild_relapsed(self, detail: str) -> bool:
+ """Did the LAST rebuild already fail to fix this exact fault?
+
+ Rebuild timestamps alone cannot answer this: a long call may
+ legitimately rebuild for unrelated reasons. The cause has to match
+ too, and it has to come back fast — a fault that stays away for
+ longer than the window was genuinely cleared by the rebuild.
+ """
+ if not self._transport_rebuild_times:
+ return False
+ if detail != self._last_advised_reconnect_detail:
+ return False
+ elapsed = time.monotonic() - self._transport_rebuild_times[-1]
+ return elapsed < _ADVISED_REBUILD_RELAPSE_S
+
def _request_advised_rebuild(self) -> None:
"""Queue the advised in-place rebuild through the pump arbitration."""
detail = self._advised_reconnect_detail
self._advised_reconnect_detail = None
if detail is None or not self._transport_death_is_rebuildable():
return
+ # Remembered for the relapse check above: the next advice carrying
+ # this same cause within the window proves the rebuild did not help.
+ self._last_advised_reconnect_detail = detail
target_session = self._session
if target_session is None or (
target_session is self._transport_rebuild_pending
diff --git a/tests/unit/realtime/test_codex_subscription.py b/tests/unit/realtime/test_codex_subscription.py
index 7613d85f0b..0c1d7931ec 100644
--- a/tests/unit/realtime/test_codex_subscription.py
+++ b/tests/unit/realtime/test_codex_subscription.py
@@ -2729,6 +2729,115 @@ async def test_post_interrupt_captions_do_not_feed_the_rebuild_counter(
await session.close()
+def _self_echo_client(rounds: int) -> _Client:
+ """A far end answering itself: each refused turn captions its own words.
+
+ One ungrounded user caption closes the open response, the assistant text
+ that follows opens a new one with nothing local behind it — a refusal —
+ and the caption after that is the far end transcribing the very words we
+ just cut. That is the shape of the live 17:41 loop.
+ """
+ events = [
+ _Notification(
+ "thread/realtime/transcript/delta",
+ {"threadId": "thread-1", "role": "assistant", "delta": "Hi."},
+ )
+ ]
+ for index in range(rounds):
+ events.append(
+ _Notification(
+ "thread/realtime/transcript/done",
+ {"threadId": "thread-1", "role": "user", "text": f"echo {index}"},
+ )
+ )
+ events.append(
+ _Notification(
+ "thread/realtime/transcript/delta",
+ {
+ "threadId": "thread-1",
+ "role": "assistant",
+ "delta": f"invented turn {index}",
+ },
+ )
+ )
+ return _Client(events)
+
+
+async def _drain(session) -> list:
+ events = []
+ with contextlib.suppress(TimeoutError):
+ async with asyncio.timeout(2.0):
+ async for event in session.receive():
+ events.append(event)
+ return events
+
+
+async def test_a_refusals_own_echo_captions_never_tear_the_transport_down(
+ monkeypatch,
+) -> None:
+ """BUG-124: refusing a turn is a LOCAL interrupt and must arm the grace.
+
+ Live 2026-08-06 17:41: every refusal cut the far end, the far end
+ captioned its own truncated words back as a user turn — the caption was
+ the first words of the answer just cut — and two of those captions
+ rebuilt the transport. Twice in six seconds, with the loop back each time.
+ """
+ monkeypatch.setattr(codex_subscription_mod, "_UNGROUNDED_RESPONSE_GRACE_S", 0.0)
+ # High enough that only the caption counter could fire here: three rounds
+ # deliver three ungrounded final captions against a threshold of two, so
+ # this test fails outright unless the refusals arm the grace window.
+ monkeypatch.setattr(codex_subscription_mod, "_REFUSALS_BEFORE_REBUILD", 99)
+ session = await _provider(
+ _self_echo_client(rounds=3),
+ input_transcriber_factory=_GroundedThenQuietTranscriber,
+ ).open_session(RealtimeSessionConfig())
+
+ events = await _drain(session)
+
+ assert [
+ event
+ for event in events
+ if event.type == "error" and getattr(event, "reconnect_advised", False)
+ ] == []
+ await session.close()
+
+
+async def test_a_run_of_refusals_is_what_proves_the_self_dialogue_loop(
+ monkeypatch,
+) -> None:
+ """The honest signal: refusals, which our own reaction cannot manufacture.
+
+ With the post-interrupt grace now covering refusals, the caption counter
+ can no longer see a storm at all — so the storm needs its own detector, or
+ a call would refuse every answer forever in silence (the 17:39 call died
+ exactly that way, and only an app restart recovered it).
+ """
+ monkeypatch.setattr(codex_subscription_mod, "_UNGROUNDED_RESPONSE_GRACE_S", 0.0)
+ monkeypatch.setattr(codex_subscription_mod, "_REFUSALS_BEFORE_REBUILD", 3)
+ client = _self_echo_client(rounds=6)
+ session = await _provider(
+ client,
+ input_transcriber_factory=_GroundedThenQuietTranscriber,
+ ).open_session(RealtimeSessionConfig())
+
+ events = await _drain(session)
+
+ rebuild_errors = [
+ event
+ for event in events
+ if event.type == "error" and getattr(event, "reconnect_advised", False)
+ ]
+ assert len(rebuild_errors) == 1
+ assert rebuild_errors[0].recoverable is True
+ assert events[-1].type == "turn_complete"
+ # Only the FIRST refusal of the run interrupts: cutting a turn is what
+ # makes ChatGPT-Live start the next one, so a storm is left to run out.
+ assert len(client.interrupts) <= 1
+ 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.
diff --git a/tests/unit/realtime/test_session.py b/tests/unit/realtime/test_session.py
index 9d747ed9c4..97a85d7b88 100644
--- a/tests/unit/realtime/test_session.py
+++ b/tests/unit/realtime/test_session.py
@@ -6160,6 +6160,52 @@ async def test_advised_reconnect_defers_to_the_turn_boundary_mid_turn():
await sess.end(reason="test")
+async def test_the_same_advice_right_after_a_rebuild_ends_the_call_honestly():
+ """BUG-124: a rebuild that has to be repeated for the same cause failed.
+
+ Live 2026-08-06 17:41: the self-dialogue advice rebuilt the transport at
+ :53, came straight back at :56, rebuilt again at :59. A third would have
+ exhausted the budget and ended the call as reason=error anyway — by a
+ worse route, after two pointless handshakes. Stop at the relapse and say
+ why. Deliberately no cross-provider failover: a subscription-backed
+ provider must never fall through to metered voice.
+ """
+ advice = RealtimeEvent(
+ type="error",
+ error="the far end is answering itself",
+ recoverable=True,
+ reconnect_advised=True,
+ )
+ provider = RebuildingProvider(
+ [
+ lambda: StayOpenSession([advice]),
+ # The fresh transport walks straight back into the same fault.
+ lambda: StayOpenSession([advice]),
+ lambda: StayOpenSession([]),
+ ]
+ )
+ jsons = []
+ sess = RealtimeVoiceSession(
+ session_id="relapsed-rebuild",
+ send_binary=lambda _data: asyncio.sleep(0),
+ send_json=lambda m: jsons.append(m) or asyncio.sleep(0),
+ provider=provider,
+ config=_cfg(),
+ bus=None,
+ )
+ await sess.handle_control({"type": "audio_start", "sample_rate": 16_000})
+ await _wait_until(lambda: sess.failed)
+
+ # Exactly one rebuild was attempted; the relapse ended the call instead of
+ # spending the rest of the budget on transports that cannot help.
+ assert provider.open_calls == 2
+ errors = [m for m in jsons if m.get("type") == "provider_error"]
+ assert errors, "a call that stops must say so"
+ assert "after a transport rebuild" in str(errors[-1].get("error"))
+ await sess.end(reason="test")
+
+
@pytest.mark.asyncio
async def test_provider_cannot_re_run_the_order_already_being_executed():
"""One spoken order must reach the world exactly once.