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): keep subscription turns audible

rubenluetke10-beep0a9bee4efebc
diff --git a/jarvis/plugins/realtime/codex_subscription.py b/jarvis/plugins/realtime/codex_subscription.py
index f49f1f0bbc..2fde989017 100644
--- a/jarvis/plugins/realtime/codex_subscription.py
+++ b/jarvis/plugins/realtime/codex_subscription.py
@@ -753,6 +753,10 @@ class _CodexSubscriptionRealtimeSession:
supports_tool_updates = False
supports_direct_tools = False
creates_responses_automatically = True
+ # Server VAD creates the first answer, but request_response() cannot create
+ # a replacement after Jarvis blocks it. A trusted text append is the
+ # transport's explicit retry mechanism.
+ supports_prompted_response_retry = True
isolates_response_generations = True
rebuild_on_transport_death = True
direct_speech_is_authoritative = True
@@ -987,6 +991,10 @@ class _CodexSubscriptionRealtimeSession:
sequence_boundary_pending = False
stream_ended = False
local_transcript_failed = False
+ # Silence/too-short is not a recognizer outage. It may still fall back
+ # to a provider caption for the same audio, but must not manufacture a
+ # user-visible transcription error when no caption arrives.
+ local_transcript_discarded = False
user_final_emitted = False
# The "we could not transcribe this turn" notice is emitted once per
# turn, but it must NOT latch ``user_final_emitted``: a genuine
@@ -1724,7 +1732,11 @@ class _CodexSubscriptionRealtimeSession:
was permanently recorded as empty.
"""
nonlocal missing_boundary_emitted
- if not local_transcript_failed or user_final_emitted:
+ if (
+ not local_transcript_failed
+ or local_transcript_discarded
+ or user_final_emitted
+ ):
return None
if missing_boundary_emitted:
return None
@@ -2006,6 +2018,7 @@ class _CodexSubscriptionRealtimeSession:
local_input_generation += 1
user_utterance_open = True
local_transcript_failed = False
+ local_transcript_discarded = False
user_final_emitted = False
missing_boundary_emitted = False
ungrounded_final_captions = 0
@@ -2042,6 +2055,8 @@ class _CodexSubscriptionRealtimeSession:
# instead of being refused on the spot (the BUG-124
# amplifier: a 200 ms "hm?" got its real answer cut).
user_utterance_open = False
+ local_transcript_failed = True
+ local_transcript_discarded = True
discarded_generation = local_input_generation
discarded_at = asyncio.get_running_loop().time()
log.debug(
@@ -2079,6 +2094,7 @@ class _CodexSubscriptionRealtimeSession:
preview = self._server_user_preview
self._server_user_preview = ""
local_transcript_failed = True
+ local_transcript_discarded = False
if preview and not user_final_emitted:
user_final_emitted = True
log.info(
@@ -2096,6 +2112,7 @@ class _CodexSubscriptionRealtimeSession:
if payload.is_final:
user_utterance_open = False
local_transcript_failed = False
+ local_transcript_discarded = False
user_final_emitted = True
first_user_final_seen = True
if response_open and not response_allowed:
@@ -2566,6 +2583,7 @@ class _CodexSubscriptionRealtimeSession:
else:
user_final_emitted = True
local_transcript_failed = False
+ local_transcript_discarded = False
yield _ProviderEvent(
type="input_transcript",
text=text,
@@ -2663,14 +2681,28 @@ class _CodexSubscriptionRealtimeSession:
continue
item_type = str(item.get("type", "") or "")
if item_type == "input_audio_buffer.speech_started":
+ item_id = str(item.get("item_id", "") or "")
+ if self._local_grounding_active():
+ # The local endpointer already emitted the one
+ # authoritative boundary for this microphone audio.
+ # ChatGPT-Live's duplicate commonly arrives after
+ # the assistant response has opened; forwarding it
+ # as another barge-in cancels that valid response
+ # and leaves later generations behind the interrupt
+ # barrier. Retain only the id needed by its caption.
+ self._last_input_item_id = item_id
+ self._diag[
+ "duplicate_provider_speech_starts_suppressed"
+ ] += 1
+ continue
_cancel_completion()
completion_emitted = False
self._assistant_delta_text = ""
- self._last_input_item_id = str(item.get("item_id", "") or "")
- if not self._local_grounding_active():
- local_transcript_failed = False
- user_final_emitted = False
- missing_boundary_emitted = False
+ self._last_input_item_id = item_id
+ local_transcript_failed = False
+ local_transcript_discarded = False
+ user_final_emitted = False
+ missing_boundary_emitted = False
_reset_assistant_capture()
yield _ProviderEvent(
type="speech_started",
diff --git a/jarvis/realtime/input_transcription.py b/jarvis/realtime/input_transcription.py
index 53e46c493b..b82ad63f29 100644
--- a/jarvis/realtime/input_transcription.py
+++ b/jarvis/realtime/input_transcription.py
@@ -164,15 +164,12 @@ _EVENT_QUEUE_MAX = 256
SPEECH_STARTED = "speech_started"
TRANSCRIPT = "transcript"
TRANSCRIPT_FAILED = "transcript_failed"
+SPEECH_DISCARDED = "speech_discarded"
-# A discarded (too short) utterance is reported through the LOG, deliberately
-# not as a new event kind. This stream has exactly one reader, and it branches
-# on the two kinds above and routes everything else through a fallback that
-# wipes the provider's own user-transcript preview — so a new kind would make
-# every cough destroy the very fallback the failure path exists to promote.
-# Nothing waits on a close for a discarded utterance either (the transport ends
-# its turns on its own boundaries, not on this stream), so the honest fix is
-# observability, not a wire change.
+# A discarded (too short or confidently boilerplate) utterance must close the
+# ``speech_started`` edge it already emitted. The subscription adapter handles
+# this kind explicitly: it preserves any provider-side caption as a fallback,
+# but does not surface a transcription error when the audio was not a real turn.
_DISCARD_STREAK_WARN = 5
@@ -595,6 +592,9 @@ class LocalInputTranscriber:
self._speech_ms = 0
if voiced_ms < _MIN_VOICED_MS or not pcm:
self._note_discarded(voiced_ms)
+ self._emit(
+ InputTranscriptEvent(kind=SPEECH_DISCARDED, voiced_ms=voiced_ms)
+ )
return
# Only a qualifying utterance vouches for a server-side transcript; a
# cough must not open the door that the energy gate just closed.
@@ -912,10 +912,10 @@ class LocalInputTranscriber:
# keyword ban on real speech). Live 2026-08-06 17:39:57 the
# recognizer delivered a subtitle outro as a genuine turn: it
# grounded a response the user never asked for AND flipped the
- # call's output language on its way through. Treated as a failed
- # transcript, so the far end's own caption for the same audio can
- # still stand in — the endpointer only vouched for ENERGY, and
- # energy is what a speaker leak has too.
+ # call's output language on its way through. This closes as a
+ # discard rather than a recognizer failure: the far end's caption
+ # can still stand in, but a speaker leak must not raise a visible
+ # "transcription unavailable" error when none arrives.
log.info(
"Discarding a %d ms local input transcript as silence "
"boilerplate: %r",
@@ -923,7 +923,7 @@ class LocalInputTranscriber:
text[:80],
)
self._emit(
- InputTranscriptEvent(kind=TRANSCRIPT_FAILED, voiced_ms=voiced_ms)
+ InputTranscriptEvent(kind=SPEECH_DISCARDED, voiced_ms=voiced_ms)
)
return
log.info(
@@ -1054,10 +1054,15 @@ class LocalInputTranscriber:
A dropped ``speech_started`` does not merely lose a bar update: the
adapter counts it as the proof that a human spoke, so losing one makes
the next genuine answer look like a self-echo and get interrupted.
- Transcript events are the droppable ones.
+ The matching ``speech_discarded`` edge is equally load-bearing: losing
+ it leaves the adapter believing that utterance is still open. Ordinary
+ transcript events are the droppable ones.
"""
for index, queued in enumerate(self._events):
- if queued is not None and queued.kind != SPEECH_STARTED:
+ if queued is not None and queued.kind not in {
+ SPEECH_STARTED,
+ SPEECH_DISCARDED,
+ }:
del self._events[index]
log.warning(
"Local input transcript queue is full; dropped one %s "
@@ -1096,6 +1101,7 @@ class LocalInputTranscriber:
__all__ = [
+ "SPEECH_DISCARDED",
"SPEECH_STARTED",
"TRANSCRIPT",
"TRANSCRIPT_FAILED",
diff --git a/jarvis/realtime/session.py b/jarvis/realtime/session.py
index ccb983f648..263534a39d 100644
--- a/jarvis/realtime/session.py
+++ b/jarvis/realtime/session.py
@@ -858,6 +858,18 @@ def _direct_tool_result_retry_prompt(*, language: str) -> str:
)
+def _output_language_retry_prompt(*, language: str) -> str:
+ """Request one replacement for an answer blocked at the speech boundary."""
+ language_name = _LANGUAGE_NAMES.get(language, "the conversation language")
+ return (
+ f"{SPEAK_REQUEST_OPENER} "
+ "Your immediately preceding answer was not delivered because it used "
+ "the wrong output language. Repeat the same answer now in "
+ f"{language_name}. Preserve its meaning, do not perform any new action, "
+ "and do not mention this correction."
+ )
+
+
# Several equivalent progress lines per language: one fixed sentence on every
# slow turn reads robotic (live feedback 2026-07-17 08:47, three "Ich bin noch
# dran." in one session). Each entry must stay short, promise nothing about
@@ -4977,6 +4989,25 @@ class RealtimeVoiceSession:
await send_text(
_direct_tool_result_retry_prompt(language=self._language)
)
+ elif bool(
+ getattr(
+ self._session,
+ "supports_prompted_response_retry",
+ False,
+ )
+ ):
+ # Some server-VAD transports create only the original response
+ # automatically; their ordinary request_response() is a no-op.
+ # A trusted developer append is the capability they expose for
+ # an explicit replacement after the original was blocked.
+ send_text = getattr(self._session, "send_text", None)
+ if not callable(send_text):
+ raise RuntimeError(
+ "provider advertises prompted retries without send_text"
+ )
+ await send_text(
+ _output_language_retry_prompt(language=self._language)
+ )
else:
try:
await self._session.request_response(required_tool=None)
diff --git a/tests/integration/realtime/test_codex_multi_turn.py b/tests/integration/realtime/test_codex_multi_turn.py
index cd827db1fa..dfcbd0e900 100644
--- a/tests/integration/realtime/test_codex_multi_turn.py
+++ b/tests/integration/realtime/test_codex_multi_turn.py
@@ -46,6 +46,7 @@ OUTPUT_RATE = 24_000
#: cannot quietly drift into testing a provider that does not exist.
CODEX_CAPABILITIES: dict[str, bool] = {
"creates_responses_automatically": True,
+ "supports_prompted_response_retry": True,
"isolates_response_generations": True,
"supports_direct_tools": False,
"supports_tool_updates": False,
@@ -79,6 +80,9 @@ class _CodexShapedWire:
creates_responses_automatically = CODEX_CAPABILITIES[
"creates_responses_automatically"
]
+ supports_prompted_response_retry = CODEX_CAPABILITIES[
+ "supports_prompted_response_retry"
+ ]
isolates_response_generations = CODEX_CAPABILITIES[
"isolates_response_generations"
]
@@ -94,6 +98,7 @@ class _CodexShapedWire:
self.sent_audio: list[AudioChunk] = []
self.spoken: list[str] = []
self.texts: list[str] = []
+ self.text_appended = asyncio.Event()
self.session_updates: list[dict[str, Any]] = []
self.response_requests = 0
self.interrupts = 0
@@ -134,6 +139,7 @@ class _CodexShapedWire:
async def send_text(self, text: str) -> None:
self.texts.append(text)
+ self.text_appended.set()
async def send_speech(self, text: str) -> None:
self.spoken.append(text)
@@ -372,6 +378,80 @@ def test_the_fake_mirrors_the_real_codex_capability_tuple() -> None:
assert callable(getattr(_CodexShapedWire, "send_speech", None))
+async def test_wrong_language_uses_prompted_subscription_retry() -> None:
+ """The subscription's ordinary response request is intentionally a no-op.
+
+ Once the scrub gate blocks a wrong-language answer, the replacement must
+ therefore travel through the adapter's trusted prompt capability; otherwise
+ the turn waits forever and the next utterance inherits the interrupt state.
+ """
+ session, _provider, wire, surface = await _open_call()
+ wrong_pcm = _pcm(value=700)
+ correct_pcm = _pcm(value=1300)
+ try:
+ since = surface.mark()
+ wire.push(
+ RealtimeEvent(type="speech_started"),
+ RealtimeEvent(
+ type="input_transcript",
+ text="What is kindness?",
+ is_final=True,
+ ),
+ RealtimeEvent(
+ type="audio_delta",
+ audio=AudioChunk(
+ pcm=wrong_pcm,
+ sample_rate=OUTPUT_RATE,
+ timestamp_ns=0,
+ ),
+ ),
+ RealtimeEvent(
+ type="output_transcript_delta",
+ text=(
+ "Esta es una respuesta completa en español con suficientes "
+ "palabras para identificar claramente el idioma."
+ ),
+ ),
+ RealtimeEvent(type="turn_complete"),
+ )
+
+ await asyncio.wait_for(wire.text_appended.wait(), TIMEOUT_S)
+ assert "English" in wire.texts[-1]
+ assert wire.response_requests == 1, (
+ "the dead automatic-response request was used for the retry"
+ )
+ assert surface.binary == [], "blocked wrong-language PCM reached playback"
+
+ wire.push(
+ RealtimeEvent(
+ type="output_transcript_delta",
+ text=(
+ "Kindness means treating other people with consistent care "
+ "and respect."
+ ),
+ ),
+ RealtimeEvent(
+ type="audio_delta",
+ audio=AudioChunk(
+ pcm=correct_pcm,
+ sample_rate=OUTPUT_RATE,
+ timestamp_ns=0,
+ ),
+ ),
+ RealtimeEvent(type="turn_complete"),
+ )
+ await surface.wait_json(
+ lambda message: message.get("type") == "turn_complete",
+ since=since,
+ )
+
+ assert surface.binary == [correct_pcm]
+ await _assert_at_rest(session, wire, note="after a prompted language retry")
+ finally:
+ await _end(session)
+
+
# -- the headline case ------------------------------------------------------
diff --git a/tests/unit/realtime/test_codex_subscription.py b/tests/unit/realtime/test_codex_subscription.py
index c6f74ac66d..00e665d3a2 100644
--- a/tests/unit/realtime/test_codex_subscription.py
+++ b/tests/unit/realtime/test_codex_subscription.py
@@ -2205,6 +2205,72 @@ async def _collect_until(session, *, stop_after: int, kind: str, timeout_s: floa
return events
+async def test_provider_speech_start_does_not_duplicate_local_boundary() -> None:
+ """A late server VAD edge is the same utterance, not a new barge-in.
+
+ ChatGPT-Live commonly sends it after the locally grounded final, while the
+ answer is already opening. Forwarding both boundaries cancels that answer
+ and strands the following response generation behind the interrupt barrier.
+ """
+ transcriber = _ScheduledInputTranscriber(
+ [
+ (0.01, InputTranscriptEvent(kind="speech_started")),
+ (
+ 0.0,
+ InputTranscriptEvent(kind="transcript", text="Hello", is_final=True),
+ ),
+ ]
+ )
+ client = _Client()
+ client.subscription = _ScheduledSubscription(
+ [
+ (
+ 0.04,
+ _Notification(
+ "thread/realtime/itemAdded",
+ {
+ "threadId": "thread-1",
+ "item": {
+ "type": "input_audio_buffer.speech_started",
+ "item_id": "input-1",
+ },
+ },
+ ),
+ ),
+ (
+ 0.02,
+ _Notification(
+ "thread/realtime/transcript/delta",
+ {
+ "threadId": "thread-1",
+ "role": "assistant",
+ "delta": "Hi there.",
+ },
+ ),
+ ),
+ ]
+ )
+ session = await _provider(
+ client,
+ input_transcriber_factory=lambda: transcriber,
+ ).open_session(RealtimeSessionConfig())
+
+ events = await _collect_until(
+ session,
+ stop_after=1,
+ kind="output_transcript_delta",
+ timeout_s=1.0,
+ )
+
+ assert [event.type for event in events].count("speech_started") == 1
+ assert [event.text for event in events if event.type == "output_transcript_delta"] == [
+ "Hi there."
+ ]
+ assert session.diagnostics().get("duplicate_provider_speech_starts_suppressed", 0) == 1
+ await session.close()
+
+
@pytest.mark.asyncio
async def test_a_refused_response_does_not_deafen_the_next_real_turn() -> None:
"""AD-1: one refusal must not decide the rest of the call.
diff --git a/tests/unit/realtime/test_input_transcription.py b/tests/unit/realtime/test_input_transcription.py
index d76d70fac6..93085fccb4 100644
--- a/tests/unit/realtime/test_input_transcription.py
+++ b/tests/unit/realtime/test_input_transcription.py
@@ -175,17 +175,12 @@ async def test_a_blip_of_noise_never_becomes_a_transcript() -> None:
transcriber = LocalInputTranscriber(sample_rate=RATE, stt_factory=lambda: stt)
_speak(transcriber, speech_chunks=8) # 160 ms - too short to be speech
- events = await _drain(transcriber, 1)
+ events = await _drain(transcriber, 2)
assert events[0].kind == module.SPEECH_STARTED
+ assert events[1].kind == module.SPEECH_DISCARDED
+ assert events[1].voiced_ms == 160
assert stt.calls == 0
- # Nothing follows it on the wire. The discard is reported through the log,
- # NOT as a new event kind: this stream's one reader routes any unknown kind
- # through a fallback that wipes the provider's own user-transcript preview,
- # so a per-cough event would destroy the very fallback that the failure path
- # exists to promote.
- with pytest.raises(asyncio.TimeoutError):
- await asyncio.wait_for(transcriber.next_event(), timeout=0.05)
await transcriber.close()
@@ -335,9 +330,9 @@ async def test_silence_boilerplate_never_becomes_a_grounded_turn() -> None:
The endpointer only ever vouches for ENERGY, and a speaker leak has energy
too — so a Whisper-family model produced its end-card boilerplate over
that leak, the far end answered a question nobody asked, and the call's
- output language flipped to English on the way through. It must land as a
- FAILED transcript, so the far end's own caption for the same audio can
- still stand in for the turn.
+ output language flipped to English on the way through. It must close as a
+ discarded utterance, so a provider caption can still stand in without a
+ false transcription failure when none arrives.
"""
stt = _FakeSTT("Thank you for watching!")
transcriber = LocalInputTranscriber(sample_rate=RATE, stt_factory=lambda: stt)
@@ -345,7 +340,7 @@ async def test_silence_boilerplate_never_becomes_a_grounded_turn() -> None:
events = await _drain(transcriber, 2)
assert events[0].kind == module.SPEECH_STARTED
- assert events[1].kind == module.TRANSCRIPT_FAILED
+ assert events[1].kind == module.SPEECH_DISCARDED
await transcriber.close()