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 a raced late-result readback from doubling the answer in a second voice

Ruben Lütkea8af6d00c6e5
diff --git a/docs/BUGS.md b/docs/BUGS.md
index b364a55876..4ad1c37999 100644
--- a/docs/BUGS.md
+++ b/docs/BUGS.md
@@ -7051,3 +7051,60 @@ shuffles invisible, unplug + default move visible), one refresh per settled
change, probe outage fails open, refresh order (quiesce → re-init →
invalidate → re-resolve), watchdog heartbeat backdating. Physical
plug/unplug validation on macOS/Windows/Linux remains pending.
+
+---
+
+## BUG-103: late action-result readback races the user's next utterance — the same answer is spoken twice in two different voices and doubles in the transcript (HIGH, FIXED 2026-07-20)
+
+**Symptom.** Realtime voice session `31dd0f25-8102-4159-83ca-466d6c1bb450`
+(2026-07-20 17:49, Gemini Live, delegate tool mode): one answer was rendered
+by the surface TTS fallback voice (`gemini-flash-tts`, ~30 s) while the rest
+of the session used the live provider voice, and the transcript view showed
+the identical reply text twice in a row. The recorded `voice_turns` row for
+that turn was completely empty (no user text, no reply).
+
+**Reconstruction (event-log forensic).**
+
+1. A barged delegate turn's Brain result outlived its provider turn and was
+ correctly queued as a late follow-up
+ (`_queue_late_delegate_result`).
+2. The flush found the session "at rest" ~1 s after the turn closed and
+ injected the readback (`_speak_late_delegate_result`: sets
+ `_external_update(spoken_kind="action_result")`, opens a SILENT turn) —
+ exactly as the user drew breath to continue talking.
+3. The user's next utterance landed INSIDE that readback turn. The provider
+ interrupted the still-silent readback, the deterministic delegate answered
+ the user, the provider then failed to render that grounded result, and the
+ surface TTS fallback spoke it (the first, different voice).
+4. At turn completion the STALE `_external_update` still owned the turn:
+ `_publish_turn_completed` took the external-readback branch, re-published
+ the fallback answer as a second `SpeechSpoken(action_result)` (the
+ duplicate transcript line), published NO `ResponseGenerated`, and skipped
+ `VoiceTurnCompleted` entirely (the empty recorder row).
+
+**Fix (`jarvis/realtime/session.py`).**
+
+1. **User speech reclaims a silent readback turn.** When a real input
+ transcript arrives while `_external_update` is set and no readback audio
+ has played (`_output_samples_sent == 0`), the readback is dropped (its
+ action already ran; only the spoken confirmation is lost, logged), the
+ deferred `VoiceTurnStarted` is published, the turn's response request is
+ reset, and — only on adapters that isolate response generations — the
+ provider's now-stale readback rendering is withheld until a response for
+ the user's turn exists.
+2. **Belt-and-braces at completion.** `_publish_turn_completed` treats a turn
+ that carries BOTH an external update and a delegate turn state as a user
+ turn: the superseded readback track is discarded so the answer is
+ published exactly once (`ResponseGenerated` + `VoiceTurnCompleted`),
+ never re-surfaced under the readback kind.
+
+**Class rule.** An out-of-band injection into a live duplex session can
+always race the user's next utterance — "at rest" is a snapshot, not a
+reservation. Any state that lets a non-user prompt own a turn must be
+surrendered the moment genuine user input arrives in that turn, and turn
+completion must never let a stale out-of-band marker swallow a real user
+turn's record.
+
+**Guards.** `tests/unit/realtime/test_session.py::
+test_user_speech_during_silent_external_update_reclaims_the_turn` and
+`::test_hijacked_external_update_turn_completes_on_the_user_track`.
diff --git a/jarvis/realtime/session.py b/jarvis/realtime/session.py
index c9ff9b0f80..50b7abc9f1 100644
--- a/jarvis/realtime/session.py
+++ b/jarvis/realtime/session.py
@@ -1556,6 +1556,50 @@ class RealtimeVoiceSession:
# The user audibly opened this turn — a fallback-era
# suppression of stale provider output ends here.
self._drop_provider_output_until_user_turn = False
+ if (
+ self._external_update is not None
+ and self._output_samples_sent == 0
+ ):
+ # Real user input landed while a trusted out-of-band
+ # readback (late action result / announcement) was
+ # still silent: the injection raced the user's next
+ # utterance, so the turn belongs to the user now
+ # (BUG-103: keeping the readback state made the turn
+ # complete on the readback track — the user's answer
+ # was re-published as a second spoken event and the
+ # turn's VoiceTurnCompleted record was skipped). The
+ # readback's action already ran; only its spoken
+ # confirmation is lost, and the provider's now-stale
+ # rendering stays inaudible until a response for
+ # THIS turn exists.
+ log.info(
+ "realtime[%s] user speech pre-empted a silent "
+ "out-of-band readback (%s) — the turn belongs "
+ "to the user",
+ self.session_id,
+ self._external_update.spoken_kind,
+ )
+ self._external_update = None
+ self._response_requested_for_turn = False
+ if bool(
+ getattr(
+ self._session,
+ "isolates_response_generations",
+ False,
+ )
+ ):
+ # Only an adapter that can tell the stale
+ # readback generation from the next response
+ # gets the suppression; on any other adapter
+ # the flag would never clear and deafen the
+ # user's own answer.
+ self._drop_provider_output_until_new_response = (
+ True
+ )
+ if self._turn_id:
+ # The turn opened silently for the readback;
+ # announce it now that it is a real user turn.
+ await self._publish_turn_started()
await self._ensure_turn_started()
new_language = self._language
if transcript:
@@ -3107,6 +3151,18 @@ class RealtimeVoiceSession:
answer = "".join(self._output_transcript).strip()
delegate_state = self._delegate_turns.pop(self._turn_id, None)
external_update = self._external_update
+ if external_update is not None and delegate_state is not None:
+ # A real user turn (delegate dispatch) ran inside what began as an
+ # out-of-band readback turn — the readback was superseded (BUG-103).
+ # Completing on the readback track here would publish the answer
+ # the surface already spoke a second time and skip the turn's
+ # ResponseGenerated/VoiceTurnCompleted record entirely.
+ log.info(
+ "realtime[%s] out-of-band readback superseded by a user turn "
+ "— completing on the user track",
+ self.session_id,
+ )
+ external_update = None
response_text = answer or (
delegate_state.last_reply if delegate_state is not None else ""
)
diff --git a/tests/unit/realtime/test_session.py b/tests/unit/realtime/test_session.py
index 6de898fafc..fb95f7539d 100644
--- a/tests/unit/realtime/test_session.py
+++ b/tests/unit/realtime/test_session.py
@@ -1292,6 +1292,135 @@ async def test_idle_session_renders_external_update_as_realtime_spoken_track():
assert "artifact: report.md" in history
+async def test_user_speech_during_silent_external_update_reclaims_the_turn():
+ """BUG-103: real user input during a still-silent readback owns the turn.
+
+ Live forensic 2026-07-20 17:50: a late action-result injection raced the
+ user's next utterance. The turn kept its readback state, so it completed
+ on the external-update track — the user's answer (already spoken by the
+ surface TTS fallback) was re-published as a second spoken event and the
+ turn produced no ResponseGenerated/VoiceTurnCompleted record at all,
+ which the transcript view rendered as the same reply twice.
+ """
+ provider = TextResultGatedProvider(
+ [
+ RealtimeEvent(
+ type="input_transcript",
+ text="What can I do?",
+ is_final=True,
+ ),
+ RealtimeEvent(
+ type="output_transcript_delta",
+ text="Here is what you can do.",
+ ),
+ RealtimeEvent(type="turn_complete"),
+ ]
+ )
+ bus = FakeBus()
+ sess = RealtimeVoiceSession(
+ session_id="reclaimed-update",
+ send_binary=lambda _data: asyncio.sleep(0),
+ send_json=lambda _message: asyncio.sleep(0),
+ provider=provider,
+ config=_cfg(),
+ bus=bus,
+ surface="desktop",
+ )
+
+ await sess.handle_control({"type": "audio_start", "sample_rate": 16_000})
+ accepted = await sess.deliver_announcement(
+ text="Research completed successfully.",
+ language="en",
+ spoken_kind="subagent",
+ )
+ await sess.wait_finished()
+ await sess.end(reason="test")
+
+ assert accepted is True
+ # The unrendered readback was dropped; nothing may claim it was spoken,
+ # and the user's answer must not surface twice under the readback kind.
+ assert not any(
+ isinstance(event, SpeechSpoken) and event.spoken_kind == "subagent"
+ for event in bus.events
+ )
+ # The turn belongs to the user: full user-turn record chain.
+ assert any(isinstance(event, VoiceTurnStarted) for event in bus.events)
+ responses = [
+ event for event in bus.events if isinstance(event, ResponseGenerated)
+ ]
+ assert [event.text for event in responses] == ["Here is what you can do."]
+ completed = [
+ event for event in bus.events if isinstance(event, VoiceTurnCompleted)
+ ]
+ assert len(completed) == 1
+ assert completed[0].user_text == "What can I do?"
+ assert completed[0].jarvis_text == "Here is what you can do."
+
+
+async def test_hijacked_external_update_turn_completes_on_the_user_track():
+ """BUG-103 belt-and-braces: a delegate turn inside a readback turn wins.
+
+ Even when the abort-on-user-speech path is bypassed (e.g. the readback had
+ already started rendering when the user barged in and a delegate answered
+ the new utterance), turn completion must publish the user track exactly
+ once instead of re-publishing the answer under the readback kind.
+ """
+ from jarvis.realtime.session import (
+ _DelegateTurnState,
+ _ExternalUpdateState,
+ )
+
+ bus = FakeBus()
+ sess = RealtimeVoiceSession(
+ session_id="hijacked-update",
+ send_binary=lambda _data: asyncio.sleep(0),
+ send_json=lambda _message: asyncio.sleep(0),
+ provider=FakeProvider([]),
+ config=_cfg(),
+ bus=bus,
+ surface="desktop",
+ )
+ await sess.handle_control({"type": "audio_start", "sample_rate": 16_000})
+ sess._turn_id = "hijacked-turn"
+ sess._last_user_text = "What can I do?"
+ sess._output_transcript = ["Here is what you can do."]
+ sess._output_samples_sent = 0
+ sess._delegate_turns["hijacked-turn"] = _DelegateTurnState(
+ deterministic=True,
+ result_complete=True,
+ result_success=True,
+ delivery_started=True,
+ last_reply="Here is what you can do.",
+ user_text="What can I do?",
+ )
+ sess._external_update = _ExternalUpdateState(
+ source_text="Old late action result.",
+ language="en",
+ spoken_kind="action_result",
+ )
+
+ await sess._publish_turn_completed()
+ await sess.end(reason="test")
+
+ assert not any(
+ isinstance(event, SpeechSpoken)
+ and event.spoken_kind == "action_result"
+ for event in bus.events
+ )
+ responses = [
+ event for event in bus.events if isinstance(event, ResponseGenerated)
+ ]
+ assert [event.text for event in responses] == ["Here is what you can do."]
+ completed = [
+ event for event in bus.events if isinstance(event, VoiceTurnCompleted)
+ ]
+ assert len(completed) == 1
+ assert completed[0].user_text == "What can I do?"
+ assert sess._external_update is None
+
+
@pytest.mark.asyncio
async def test_busy_realtime_session_refuses_external_update_for_classic_fallback():
provider = FakeProvider([])