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): release grounded replies after barge-in

rubenluetke10-beep95b7f0781232
diff --git a/jarvis/plugins/realtime/codex_subscription.py b/jarvis/plugins/realtime/codex_subscription.py
index 5b3db25c2e..f49f1f0bbc 100644
--- a/jarvis/plugins/realtime/codex_subscription.py
+++ b/jarvis/plugins/realtime/codex_subscription.py
@@ -1056,6 +1056,12 @@ class _CodexSubscriptionRealtimeSession:
# during the legitimate response remain visible.
local_input_generation = 0
consumed_input_generation = 0
+ # The provider may deliver one delayed FINAL caption for the same
+ # microphone generation after the local recognizer already emitted its
+ # authoritative final. Retain that one as fallback metadata, but do
+ # not let every later invented caption borrow the still-unconsumed
+ # generation and masquerade as the user.
+ server_user_final_generation = 0
active_response_generation = 0
response_open = False
response_allowed = False
@@ -2455,15 +2461,27 @@ class _CodexSubscriptionRealtimeSession:
# it with its own latency — that caption is the
# documented fallback for this turn and is retained
# even though it arrived past the energy window.
- if fresh_input:
+ if (
+ fresh_input
+ and local_input_generation
+ > server_user_final_generation
+ ):
+ server_user_final_generation = local_input_generation
self._server_user_preview = text
ungrounded_final_captions = 0
log.info(
"A late server user transcript arrived past "
"the energy window; retained as the fallback "
- "for the utterance the endpointer confirmed"
+ "for the utterance the endpointer confirmed "
+ "without closing its active response"
)
- _close_response(spent=True)
+ # This caption describes the SAME microphone
+ # utterance the local final already grounded.
+ # ChatGPT-Live can deliver it while assistant
+ # PCM is streaming, so treating it as a new
+ # user-turn boundary splits one answer into
+ # fabricated response identities and refuses
+ # the remainder as ungrounded.
continue
# Neither energy nor a fresh utterance: this is the
# far end inventing a user turn. ONE is survivable
@@ -2538,6 +2556,10 @@ class _CodexSubscriptionRealtimeSession:
# recognizer reports it could not deliver.
local_owns_final = self._local_grounding_active()
if user_final_emitted:
+ server_user_final_generation = max(
+ server_user_final_generation,
+ local_input_generation,
+ )
continue
if local_owns_final and not local_transcript_failed:
self._server_user_preview = text
diff --git a/jarvis/realtime/session.py b/jarvis/realtime/session.py
index 5d3060f725..ccb983f648 100644
--- a/jarvis/realtime/session.py
+++ b/jarvis/realtime/session.py
@@ -3563,6 +3563,29 @@ class RealtimeVoiceSession:
and _is_presence_check(self._last_user_text)
):
await self._speak_pending_action_status()
+ if (
+ event.is_final
+ and input_observed
+ and not self._delegate_required_for_turn
+ and bool(
+ getattr(
+ self._session,
+ "isolates_response_generations",
+ False,
+ )
+ )
+ ):
+ # A locally grounded FINAL is the generation boundary
+ # the post-barge-in guard was waiting for. Automatic
+ # transports can already have marked a response as
+ # requested before this final arrives, so clearing only
+ # inside the request_response branch below left the
+ # guard latched forever (live 2026-08-10: 23.3 s to the
+ # first audible frame and three complete replies
+ # discarded). Generation isolation keeps late PCM from
+ # the interrupted response out; delegated turns retain
+ # their separate ownership guard.
+ self._drop_provider_output_until_new_response = False
if (
event.is_final
and input_observed
@@ -4789,6 +4812,8 @@ class RealtimeVoiceSession:
text: str,
*,
language: str | None = None,
+ spoken_kind: str = SPOKEN_KIND_REPLY,
+ detail: str | None = None,
) -> dict[str, Any]:
"""Build one ``error_spoken`` payload for the surface's classic TTS.
@@ -4813,6 +4838,11 @@ class RealtimeVoiceSession:
"type": "error_spoken",
"text": text,
"language": output_language,
+ # Queueing is not proof of playback. The desktop surface carries
+ # these fields onto SpeechSpoken only after AudioPlayer confirms
+ # that it accepted audible frames.
+ "spoken_kind": spoken_kind,
+ "detail": detail,
# Which realtime engine this line belongs to. The desktop surface
# resolves its realtime-scoped TTS from ambient state that is only
# set once a handshake SUCCEEDED, so a notice about a handshake
@@ -5101,27 +5131,23 @@ class RealtimeVoiceSession:
)
else:
await self._send_json(
- self._surface_speech_message(spoken_fallback)
+ self._surface_speech_message(
+ spoken_fallback,
+ spoken_kind=SPOKEN_KIND_WITHHELD,
+ detail=reason,
+ )
)
except Exception: # noqa: BLE001, S110 — surface may already be gone
pass
- # Keep the transcript honest (BUG-056): the 15:13 session recorded a
- # reply truncated to "Du hast zwei" with NO trace of why the audible
- # answer stopped. Persist the spoken fallback on the spoken track so
- # the exported transcript shows the abort and its detector names.
+ # Keep the diagnostic honest without claiming playback. The surface
+ # publishes SpeechSpoken only after its AudioPlayer confirms audible
+ # frames; a text-only fallback remains an ErrorOccurred record.
if self._bus is not None:
try:
- from jarvis.core.events import SpeechSpoken
-
- await self._bus.publish(
- SpeechSpoken(
- **self._event_trace_kwargs(),
- source_layer=f"realtime.{self.active_provider}",
- text=spoken_fallback,
- language=self._language,
- spoken_kind=SPOKEN_KIND_WITHHELD,
- detail=reason,
- )
+ await self._publish_error(
+ "RealtimeOutputWithheld",
+ reason,
+ recoverable=True,
)
except Exception: # noqa: BLE001, S110 — recording never breaks the turn
pass
@@ -5553,6 +5579,23 @@ class RealtimeVoiceSession:
# mismatched event, cancel the unsafe generation once, then allow
# subsequent events of the new identity to start cleanly.
self._response_identity_drops += 1
+ if not self._turn_id:
+ # A rollover after the local turn already closed has no user turn
+ # to apologize inside. Surfacing a fallback here both lies when no
+ # fallback TTS exists and leaks that text into the next real turn.
+ # Retire the stale binding and adopt the successor silently; its
+ # next event can still open a genuine turn if input races output.
+ log.warning(
+ "realtime[%s] dropped an unsequenced provider response "
+ "rollover after the local turn had already closed",
+ self.session_id,
+ )
+ if active_id not in self._completed_provider_response_ids:
+ self._completed_provider_response_ids.append(active_id)
+ self._gate.drain()
+ self._active_provider_response_id = response_id
+ self._gate.begin_response(response_id)
+ return False
drop_before_cancel = self._drop_provider_output_until_new_response
await self._cancel_unsafe_output(
reason=(
diff --git a/jarvis/speech/pipeline.py b/jarvis/speech/pipeline.py
index c5d26727f6..059380eef5 100644
--- a/jarvis/speech/pipeline.py
+++ b/jarvis/speech/pipeline.py
@@ -8368,7 +8368,14 @@ class SpeechPipeline:
self._emit_spoken(
cleaned,
language,
- SPOKEN_KIND_REPLY,
+ str(
+ message.get("spoken_kind", "")
+ or SPOKEN_KIND_REPLY
+ ),
+ detail=(
+ str(message.get("detail", "") or "")
+ or None
+ ),
tts=surface_tts,
)
except Exception as exc: # noqa: BLE001 -- final voice fallback
diff --git a/tests/unit/realtime/test_codex_subscription.py b/tests/unit/realtime/test_codex_subscription.py
index a73f1bffdc..c6f74ac66d 100644
--- a/tests/unit/realtime/test_codex_subscription.py
+++ b/tests/unit/realtime/test_codex_subscription.py
@@ -3264,6 +3264,89 @@ async def test_a_final_rejudges_the_open_refused_response_immediately() -> None:
await session.close()
+async def test_a_late_server_user_caption_does_not_split_the_active_answer() -> None:
+ """A second transcript source is not a second response boundary.
+
+ Live 2026-08-09 20:47: the locally grounded final opened the real answer,
+ then ChatGPT-Live's slower caption for the same microphone audio arrived
+ while that answer was streaming. Closing the response on that caption
+ fabricated a new response identity for the next PCM frame, refused the
+ rest as ungrounded, and left the user waiting 15 seconds for no audio.
+ """
+ loud = (1000).to_bytes(2, "little", signed=True) * 480
+ transcriber = _ScheduledInputTranscriber(
+ [
+ (0.01, InputTranscriptEvent(kind="speech_started")),
+ (
+ 0.02,
+ InputTranscriptEvent(
+ kind="transcript",
+ text="What is up?",
+ is_final=True,
+ ),
+ ),
+ ]
+ )
+ endpoint = _FakeAudioEndpoint(
+ output_schedule=[
+ (0.10, loud),
+ (0.30, loud),
+ (0.10, loud),
+ ]
+ )
+ client = _Client()
+ client.subscription = _ScheduledSubscription(
+ [
+ (
+ 0.15,
+ _Notification(
+ "thread/realtime/transcript/done",
+ {
+ "threadId": "thread-1",
+ "role": "user",
+ "text": "What is up?",
+ },
+ ),
+ ),
+ (
+ 0.40,
+ _Notification(
+ "thread/realtime/transcript/delta",
+ {
+ "threadId": "thread-1",
+ "role": "assistant",
+ "delta": "The complete answer.",
+ },
+ ),
+ ),
+ ]
+ )
+ session = await _provider(
+ client,
+ endpoint=endpoint,
+ input_transcriber_factory=lambda: transcriber,
+ ).open_session(RealtimeSessionConfig())
+
+ events = await _collect_until(
+ session,
+ stop_after=1,
+ kind="output_transcript_delta",
+ timeout_s=2.0,
+ )
+
+ audio = [event for event in events if event.type == "audio_delta"]
+ response_ids = {
+ event.provider_turn_id
+ for event in events
+ if event.type in {"audio_delta", "output_transcript_delta"}
+ }
+ assert len(audio) == 3, "the late duplicate caption must not cut the answer"
+ assert len(response_ids) == 1
+ assert session.diagnostics().get("response_splices", 0) == 0
+ await session.close()
+
+
@pytest.mark.asyncio
async def test_a_discarded_utterance_keeps_its_response_window(
monkeypatch,
diff --git a/tests/unit/realtime/test_session.py b/tests/unit/realtime/test_session.py
index 94f417bb95..22f8336d8d 100644
--- a/tests/unit/realtime/test_session.py
+++ b/tests/unit/realtime/test_session.py
@@ -5452,17 +5452,25 @@ async def test_delegate_does_not_retry_an_internal_type_error():
@pytest.mark.asyncio
-async def test_scrub_cancel_records_spoken_fallback_on_the_spoken_track():
- """BUG-056: the 15:13 session's transcript ended at a truncated reply with
- no trace of the safety abort. The scrub cancel must persist its spoken
- fallback as a SpeechSpoken(withheld) event carrying the detector names in
- ``detail``, so the exported transcript shows what happened and why."""
+async def test_scrub_cancel_waits_for_audible_receipt_before_claiming_speech():
+ """A queued fallback is not evidence that the user heard it.
+
+ Live 2026-08-09 20:47: the Codex subscription has no realtime-scoped
+ fallback TTS, yet the session published ``SpeechSpoken`` and the inspector
+ claimed "An error occurred" was spoken. The surface owns the playback
+ receipt, so the session may only send the request with its audit metadata.
+ """
provider = FakeProvider([])
bus = FakeBus()
+ sent: list[dict] = []
+
+ async def _capture_json(message):
+ sent.append(message)
+
sess = RealtimeVoiceSession(
session_id="scrub-cancel-record",
send_binary=lambda _data: asyncio.sleep(0),
- send_json=lambda _message: asyncio.sleep(0),
+ send_json=_capture_json,
provider=provider,
config=_cfg(),
bus=bus,
@@ -5475,10 +5483,11 @@ async def test_scrub_cancel_records_spoken_fallback_on_the_spoken_track():
await sess.end(reason="test")
spoken = [event for event in bus.events if isinstance(event, SpeechSpoken)]
- assert len(spoken) == 1
- assert spoken[0].spoken_kind == "withheld"
- assert spoken[0].detail == reason
- assert spoken[0].text == sess._gate.fallback_phrase()
+ assert spoken == []
+ fallbacks = [message for message in sent if message.get("type") == "error_spoken"]
+ assert fallbacks[-1]["spoken_kind"] == "withheld"
+ assert fallbacks[-1]["detail"] == reason
+ assert fallbacks[-1]["text"] == sess._gate.fallback_phrase()
@pytest.mark.asyncio
@@ -7319,6 +7328,57 @@ async def test_a_handoff_declined_through_provider_speech_closes_its_turn():
await sess.end(reason="test")
+async def test_grounded_final_releases_barge_in_withhold_for_automatic_transport():
+ """An automatic response may already exist when the local final arrives.
+
+ Live 2026-08-10: the Codex subscription opened its replacement response
+ before local transcription completed. ``_response_requested_for_turn``
+ therefore skipped the manual request branch that used to be the only place
+ clearing the barge-in guard; three complete replies were discarded and the
+ first audible frame arrived 23.3 seconds into the session.
+ """
+ provider = SubscriptionLikeProvider([])
+ binaries = []
+ sess = _half_duplex_session(provider, binaries=binaries)
+ await sess.handle_control({"type": "audio_start", "sample_rate": 16_000})
+ session = provider.session
+
+ sess._drop_provider_output_until_new_response = True # noqa: SLF001
+ sess._response_requested_for_turn = True # noqa: SLF001
+ await session.queue.put(
+ RealtimeEvent(
+ type="input_transcript",
+ text="Hello there.",
+ is_final=True,
+ )
+ )
+ await _wait_until(lambda: sess._last_user_text == "Hello there.") # noqa: SLF001
+ await _wait_until( # noqa: SLF001
+ lambda: sess._drop_provider_output_until_new_response is False
+ )
+ await session.queue.put(
+ RealtimeEvent(
+ type="output_transcript_delta",
+ text="This is the complete answer to your question.",
+ is_final=True,
+ provider_turn_id="replacement-response",
+ )
+ )
+ fresh_audio = _pcm_chunk()
+ await session.queue.put(
+ RealtimeEvent(
+ type="audio_delta",
+ audio=fresh_audio,
+ provider_turn_id="replacement-response",
+ )
+ )
+
+ await _wait_until(lambda: bool(binaries))
+ assert binaries == [fresh_audio.pcm]
+ await sess.end(reason="test")
+
+
@pytest.mark.asyncio
async def test_a_transport_rebuild_retires_the_answered_input_ids():
"""Input-item ids belong to the transport that issued them.
diff --git a/tests/unit/realtime/test_session_response_identity_recovery.py b/tests/unit/realtime/test_session_response_identity_recovery.py
index dc90e79d43..edd46da437 100644
--- a/tests/unit/realtime/test_session_response_identity_recovery.py
+++ b/tests/unit/realtime/test_session_response_identity_recovery.py
@@ -400,3 +400,30 @@ async def test_a_superseding_response_flows_after_the_stale_one_is_cancelled() -
assert len(cancels) == 1, (
"exactly one cancel: the stale identity, never the superseding one"
)
+
+
+async def test_an_idle_response_rollover_never_leaks_an_apology_into_the_next_turn() -> None:
+ """A late identity race after turn completion has no audible owner.
+
+ Live 2026-08-09 20:47: the old turn had already returned to listening when
+ a mismatched provider response arrived. The generic fallback was queued on
+ no turn, falsely recorded as spoken, then prepended to the next answer.
+ """
+ messages: list[dict[str, Any]] = []
+ session = _session(messages=messages)
+ session._active_provider_response_id = "resp-a"
+ session._gate.begin_response("resp-a")
+
+ accepted = await session._accept_provider_response_event(
+ RealtimeEvent(
+ type="output_transcript_delta",
+ text="stale successor",
+ provider_turn_id="resp-b",
+ )
+ )
+
+ assert accepted is False
+ assert "".join(session._output_transcript) == ""
+ assert not any(message.get("type") == "error_spoken" for message in messages)
+ assert session._scrub_cancelled_for_turn is False
+ assert session._active_provider_response_id == "resp-b"
diff --git a/tests/unit/speech/test_realtime_mode.py b/tests/unit/speech/test_realtime_mode.py
index eca035bc2c..c6cf0b9099 100644
--- a/tests/unit/speech/test_realtime_mode.py
+++ b/tests/unit/speech/test_realtime_mode.py
@@ -9,7 +9,7 @@ from types import SimpleNamespace
import pytest
import jarvis.speech.pipeline as pipeline_mod
-from jarvis.core.events import MessageSent
+from jarvis.core.events import MessageSent, SpeechSpoken
from jarvis.core.protocols import AudioChunk
from jarvis.sessions.constants import (
HANGUP_ERROR,
@@ -36,6 +36,14 @@ class _FakePlayer:
self.stopped += 1
+class _RecordingBus:
+ def __init__(self) -> None:
+ self.events: list[object] = []
+
+ async def publish(self, event: object) -> None:
+ self.events.append(event)
+
+
class _FakeTTS:
def __init__(self, pcm: bytes) -> None:
self.pcm = pcm
@@ -385,6 +393,7 @@ async def test_error_spoken_renders_through_realtime_scoped_surface_tts(
pipeline_tts = _FakeTTS(pipeline_pcm)
surface_tts = _FakeTTS(surface_pcm)
pipe._tts = pipeline_tts
+ pipe._bus = _RecordingBus()
resolved: dict[str, object] = {}
spoken_delivered = asyncio.Event()
@@ -405,6 +414,8 @@ async def test_error_spoken_renders_through_realtime_scoped_surface_tts(
"type": "error_spoken",
"text": "The grounded reply.",
"language": "en",
+ "spoken_kind": "withheld",
+ "detail": "response identity mismatch",
}
)
spoken_delivered.set()
@@ -425,6 +436,11 @@ async def test_error_spoken_renders_through_realtime_scoped_surface_tts(
assert [text for text, _lang in surface_tts.calls] == ["The grounded reply."]
assert pipeline_tts.calls == []
assert surface_pcm in pipe._player.pcm
+ await asyncio.sleep(0)
+ spoken = [event for event in pipe._bus.events if isinstance(event, SpeechSpoken)]
+ assert len(spoken) == 1
+ assert spoken[0].spoken_kind == "withheld"
+ assert spoken[0].detail == "response identity mismatch"
pipe._hangup_event.set()
assert await asyncio.wait_for(task, timeout=0.5) == HANGUP_HOTKEY