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.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
fix(realtime): nothing unsolicited plays before the call's first user final
rubenluetke10-beep3d23af46e453
diff --git a/jarvis/plugins/realtime/codex_subscription.py b/jarvis/plugins/realtime/codex_subscription.pyindex 95e571a046..e0de9e7a76 100644--- a/jarvis/plugins/realtime/codex_subscription.py+++ b/jarvis/plugins/realtime/codex_subscription.py@@ -34,20 +34,14 @@ _BROKER_OFFER_WAIT_S = 3.0# in-reply pauses on ChatGPT-Live reach ~720 ms, so a shorter window would# split a single answer at every breath._OUTPUT_QUIESCENCE_S = 1.2-# Cap on the call's OPENING response while no user question exists yet.-# ChatGPT-Live opens a response the moment it hears a voice - before the-# user's first sentence is finished - and probe round 1 (2026-08-06) recorded-# a 16 s greeting monologue riding over the user's first question. A greeting-# that long is never a greeting. Bounded per frame (no timer task); a user-# final arriving mid-greeting ADOPTS the response instead (see the local-# input branch), so a genuinely fast answer is never cut.+# Cap on a recognizer-LESS host's first (failopen) response. On grounded+# hosts nothing unsolicited plays before the call's first user final at all+# (maintainer live test 2026-08-08 killed the bounded-greeting compromise:+# the opener's remainder re-earned grants and the first final adopted the+# model's own echo-monologue as "the answer"). A host without any local+# recognizer cannot ground anything, so its opening keeps only this coarse+# bound against the 13.9 s demo-monologue class (live 2026-08-06 17:03)._OPENING_RESPONSE_MAX_S = 6.0-# Much tighter cap while the user is MID-UTTERANCE: under half-duplex the-# greeting's own playback mutes the microphone, so every second of overlap-# eats a second of the user's first question (live probe 2026-08-06: only-# 2.4 s of the question survived and the server answered a fragment). The-# model may say "hey", not a paragraph, over a speaking user.-_OPENING_OVERLAP_MAX_S = 2.0# A locally DISCARDED utterance (under the endpointer's minimum voiced# length) keeps its response window this long. The far end heard the sound# regardless of the local verdict and often answers it; consuming the@@ -827,11 +821,6 @@ class _CodexSubscriptionRealtimeSession:# answer was then refused as ungrounded).first_user_final_seen = Falsecall_response_index = 0- # Once an opening response was cut at the cap, its streamed remainder- # must not earn a fresh greeting grant frame by frame - the utterance- # keeps its entitlement, but nothing speaks on it until a FINAL- # exists (or the user audibly starts over).- opening_bound_cut = False# A discarded utterance's still-open response window (see# _DISCARDED_UTTERANCE_GRACE_S): the generation it covers and when# the discard happened.@@ -1066,26 +1055,28 @@ class _CodexSubscriptionRealtimeSession:if not self._local_grounding_active():response_allowed = Trueresponse_grant = "failopen"- elif local_input_generation > consumed_input_generation and (- first_user_final_seen or not opening_bound_cut+ elif (+ local_input_generation > consumed_input_generation+ and first_user_final_seen):- # Same consumption machinery either way; the grant label is- # what changes the OPENING response's treatment. The server- # opens a response the moment it hears a VOICE - before the- # user's first sentence exists (probe round 1, 2026-08-06: a- # 16 s greeting monologue opened 2 s into the user's question- # and starved the real answer). A pre-first-final response is- # therefore a GREETING: bounded at the media handler, adopted- # as the answer if the final lands while it still speaks, and- # its bound-cut closes WITHOUT spending - the continuation- # window stays open for the answer the question still earns.+ # NOTHING unsolicited ever plays before the call's first user+ # FINAL. The bounded-greeting compromise this replaces lost+ # its live test (maintainer, 2026-08-08): the greeting's+ # remainder re-earned a grant the moment speech re-opened,+ # the first final then ADOPTED it as "the answer", and what+ # played was the model echoing the user's own words and+ # acknowledging itself ("geht ab? ... Okay."). The control+ # adapter (openai-realtime) never adopts unsolicited+ # responses and shows zero role-play - this is that policy.+ # The user's question keeps its entitlement while the opener+ # is refused (a refusal never consumes), and the first final+ # re-judges a refused-open response immediately (see the+ # local-input branch), so the real answer still flows.active_response_generation = local_input_generationentitled_generation = local_input_generationentitlement_spent = Falseresponse_allowed = True- response_grant = (- "fresh" if first_user_final_seen else "greeting"- )+ response_grant = "fresh"elif _trusted_permit_available():self._trusted_output_permits -= 1self._diag["trusted_permit_responses"] += 1@@ -1580,7 +1571,6 @@ class _CodexSubscriptionRealtimeSession:if payload.kind == _SPEECH_STARTED:local_input_generation += 1user_utterance_open = True- opening_bound_cut = Falselocal_transcript_failed = Falseuser_final_emitted = Falsemissing_boundary_emitted = False@@ -1636,6 +1626,19 @@ class _CodexSubscriptionRealtimeSession:# covers the same audio and the endpointer already# vouched for it. Silence here would strand the turn.user_utterance_open = False+ # The endpointer vouched for a COMPLETE real+ # utterance, so the call's opening phase ends here+ # even though no clean text exists - otherwise a+ # recognizer hiccup on turn 1 would keep refusing+ # every answer of the call.+ first_user_final_seen = True+ if response_open and not response_allowed:+ _close_response(spent=False)+ log.info(+ "Codex subscription re-judges the open "+ "refused response after a failed local "+ "transcript proved a real utterance"+ )preview = self._server_user_previewself._server_user_preview = ""local_transcript_failed = True@@ -1657,24 +1660,22 @@ class _CodexSubscriptionRealtimeSession:user_utterance_open = Falselocal_transcript_failed = Falseuser_final_emitted = True- if not first_user_final_seen:- first_user_final_seen = True- if (- response_open- and response_allowed- and response_grant == "greeting"- ):- # The question landed while the opening- # response still speaks: adopt it as the- # answer and lift the greeting bound- # (the entitlement machinery is already- # armed by the grant).- response_grant = "fresh"- log.info(- "Codex subscription adopted the "- "opening response as the answer to "- "the user's first utterance"- )+ first_user_final_seen = True+ if response_open and not response_allowed:+ # A REFUSED response is still open while the+ # user's final just landed - the far end may+ # already be answering the question it heard.+ # Close the refusal now (never consuming) so+ # the very next frame is re-judged against+ # the fresh entitlement, instead of the+ # answer waiting out the stale-refusal+ # window and losing its head.+ _close_response(spent=False)+ log.info(+ "Codex subscription re-judges the open "+ "refused response now that a user final "+ "landed"+ )yield _ProviderEvent(type="input_transcript",text=payload.text,@@ -1742,32 +1743,18 @@ class _CodexSubscriptionRealtimeSession:response_allowedand first_audible_atand not first_user_final_seen- and (- response_grant == "greeting"- or (- response_grant == "failopen"- and call_response_index == 1- )- )+ and response_grant == "failopen"+ and call_response_index == 1):+ # A recognizer-less host cannot refuse its opener (no+ # grounding exists), so its FIRST response keeps a+ # coarse cap against the demo-monologue class. On+ # grounded hosts the opener never plays at all.opening_age = (asyncio.get_running_loop().time() - first_audible_at)- opening_cap = (- _OPENING_OVERLAP_MAX_S- if user_utterance_open- else _OPENING_RESPONSE_MAX_S- )- if opening_age > opening_cap:- # No user question exists yet and the opener is- # still going: this is the 13.9 s / 16 s demo- # monologue class, cut at the cap. A greeting- # close keeps the user's entitlement (spent=False)- # so their in-flight question still earns its- # answer; a recognizer-less failopen host has no- # entitlement to keep.+ if opening_age > _OPENING_RESPONSE_MAX_S:self._diag["opening_responses_bounded"] += 1- opening_bound_cut = Truelog.warning("Codex subscription bounded an opening ""response at %.1fs - no user question exists "@@ -1776,15 +1763,6 @@ class _CodexSubscriptionRealtimeSession:response_grant,)await self._interrupt_active_codex_turn()- # The far end streams the remainder regardless.- # Deliberately NOT the output-drop barrier: its- # handler closes with spent=True, which would- # burn the continuation window the user's- # in-flight question needs for its real answer.- # The opening_bound_cut gate refuses the- # remainder frame by frame instead, and the- # grace keeps their echo captions out of the- # self-dialogue counters (the BUG-124 lesson).interrupt_grace_until = (asyncio.get_running_loop().time()+ _POST_INTERRUPT_GRACE_S@@ -1793,7 +1771,7 @@ class _CodexSubscriptionRealtimeSession:completion_emitted = Trueyield _ProviderEvent(type="turn_complete")_reset_assistant_capture()- _close_response(spent=response_grant != "greeting")+ _close_response(spent=True)response_grant = ""continueif (diff --git a/tests/unit/realtime/test_codex_subscription.py b/tests/unit/realtime/test_codex_subscription.pyindex b4ca14537e..8746dbcebc 100644--- a/tests/unit/realtime/test_codex_subscription.py+++ b/tests/unit/realtime/test_codex_subscription.py@@ -1405,12 +1405,20 @@ class _StubEndpointer:class _RecoveringEndpointer(_StubEndpointer):- def __init__(self, text: str) -> None:+ def __init__(self, text: str, *, ground_call: bool = True) -> None:super().__init__(speaking=True)self.text = textself.recovery_calls: list[tuple[bytes, int]] = []self._events = asyncio.Queue()self._events.put_nowait(InputTranscriptEvent(kind="speech_started"))+ if ground_call:+ # Under the no-unsolicited-opening policy an answer only plays+ # once a user final exists.+ self._events.put_nowait(+ InputTranscriptEvent(+ kind="transcript", text="Hi.", is_final=True+ )+ )async def next_event(self): # noqa: ANN202 - test protocolreturn await self._events.get()@@ -2231,7 +2239,16 @@ async def test_a_pause_inside_one_reply_does_not_cut_off_its_remainder(output_schedule=((0.02, speech), (0.30, speech)))transcriber = _ScheduledInputTranscriber(- [(0.0, InputTranscriptEvent(kind="speech_started"))]+ [+ (0.0, InputTranscriptEvent(kind="speech_started")),+ # Grounded call: the first answer needs a user final now.+ (+ 0.0,+ InputTranscriptEvent(+ kind="transcript", text="Hello there.", is_final=True+ ),+ ),+ ])client = _Client()client.subscription = _keeps_stream_open()@@ -2261,7 +2278,13 @@ async def test_a_completed_turn_still_refuses_the_next_ungrounded_response() ->even though the far end is still producing output milliseconds later."""transcriber = _ScriptedInputTranscriber(- [InputTranscriptEvent(kind="speech_started")]+ [+ InputTranscriptEvent(kind="speech_started"),+ # Grounded call: the first answer needs a user final now.+ InputTranscriptEvent(+ kind="transcript", text="Hello there.", is_final=True+ ),+ ])client = _Client([@@ -2306,7 +2329,13 @@ async def test_an_invented_user_caption_retires_the_entitlement() -> None:for its own invented turn is refused."""transcriber = _ScriptedInputTranscriber(- [InputTranscriptEvent(kind="speech_started")]+ [+ InputTranscriptEvent(kind="speech_started"),+ # Grounded call: the first answer needs a user final now.+ InputTranscriptEvent(+ kind="transcript", text="Hello there.", is_final=True+ ),+ ])transcriber._speaking = False # the microphone is quiet from here onclient = _Client(@@ -2358,7 +2387,16 @@ async def test_interrupt_drops_the_remainder_without_any_codex_turn_id(output_schedule=((0.02, speech), (0.15, speech), (0.05, speech)))transcriber = _ScheduledInputTranscriber(- [(0.0, InputTranscriptEvent(kind="speech_started"))]+ [+ (0.0, InputTranscriptEvent(kind="speech_started")),+ # Grounded call: the first answer needs a user final now.+ (+ 0.0,+ InputTranscriptEvent(+ kind="transcript", text="Hello there.", is_final=True+ ),+ ),+ ])client = _Client()client.subscription = _keeps_stream_open()@@ -2522,8 +2560,9 @@ async def test_shadow_recovery_yields_to_an_open_user_utterance(output_schedule=tuple((0.04, speech) for _ in range(8)))# speech_started with no final: the utterance stays open for the whole- # window, so no shadow attempt may run.- transcriber = _RecoveringEndpointer("Must never be used.")+ # window, so no shadow attempt may run (and under the+ # no-unsolicited-opening policy the response never plays either).+ transcriber = _RecoveringEndpointer("Must never be used.", ground_call=False)client = _Client()client.subscription = _keeps_stream_open()session = await _provider(@@ -3085,15 +3124,14 @@ async def test_the_standing_directive_is_reasserted_on_every_delivery() -> None:@pytest.mark.asyncio-async def test_a_rambling_opening_is_cut_and_the_real_answer_still_flows(- monkeypatch,-) -> None:- """Probe round 1: a 16 s greeting monologue rode over the user's first- question. The opening response is now cut at the cap, its remainder is- refused frame by frame, and the answer the question earns still flows- through the continuation window afterwards."""- monkeypatch.setattr(codex_subscription_mod, "_OPENING_RESPONSE_MAX_S", 0.2)- monkeypatch.setattr(codex_subscription_mod, "_OPENING_OVERLAP_MAX_S", 0.2)+async def test_an_unsolicited_opening_never_plays_on_a_grounded_host() -> None:+ """Maintainer live test 2026-08-08: the bounded-greeting compromise lost —+ what played was the model echoing the user's own words and acknowledging+ itself ("geht ab? ... Okay."). Policy now mirrors the zero-role-play+ control adapter: before the call's first user FINAL, nothing unsolicited+ plays at all; the answer the question earns flows right after the final+ (the refused-open response is re-judged immediately, never after the+ stale window)."""loud = (1000).to_bytes(2, "little", signed=True) * 480transcriber = _ScheduledInputTranscriber([@@ -3108,11 +3146,13 @@ async def test_a_rambling_opening_is_cut_and_the_real_answer_still_flows()endpoint = _FakeAudioEndpoint(output_schedule=[+ # The server's greeting monologue, streaming BEFORE any final.(0.05, loud),(0.10, loud),(0.10, loud),- (0.15, loud), # ~0.40 s in: past the 0.2 s cap -> cut here- (0.05, loud), # the remainder the far end streams anyway+ (0.15, loud),+ # ...and the frames it keeps sending after the final landed.+ (0.30, loud),(0.05, loud),])@@ -3139,43 +3179,49 @@ async def test_a_rambling_opening_is_cut_and_the_real_answer_still_flows().open_session(RealtimeSessionConfig())events = []+ final_seen = False+ audio_before_final = 0+ audio_after_final = 0async with asyncio.timeout(5.0):async for event in session.receive():events.append(event)+ if event.type == "input_transcript" and event.is_final:+ final_seen = True+ elif event.type == "audio_delta":+ if final_seen:+ audio_after_final += 1+ else:+ audio_before_final += 1if event.type == "output_transcript_delta" and "real answer" in (event.text or ""):break- assert session.diagnostics().get("opening_responses_bounded", 0) == 1- boundary_positions = [- i for i, e in enumerate(events) if e.type == "turn_complete"- ]- assert boundary_positions, "the cut must close the opening turn"- answer_position = next(- i- for i, e in enumerate(events)- if e.type == "output_transcript_delta"- and "real answer" in (e.text or "")+ assert audio_before_final == 0, (+ "an unsolicited opening reached the surface before the first final"+ )+ assert audio_after_final > 0, (+ "the re-judged response after the final must play"+ )+ assert session.diagnostics().get("opening_responses_bounded", 0) == 0, (+ "grounded hosts refuse the opener outright; the bound is the "+ "recognizer-less fallback only")- assert boundary_positions[0] < answer_positionawait session.close()@pytest.mark.asyncio-async def test_a_final_landing_mid_opening_adopts_the_response(- monkeypatch,-) -> None:- """A genuinely fast answer must never be cut: when the user's final lands- while the opening response still speaks, the response is ADOPTED as the- answer and the bound lifts."""- monkeypatch.setattr(codex_subscription_mod, "_OPENING_RESPONSE_MAX_S", 0.3)+async def test_a_final_rejudges_the_open_refused_response_immediately() -> None:+ """The far end often starts answering before the local final lands. That+ response is (correctly) refused while ungrounded - but once the final+ arrives, waiting out the stale-refusal window would eat the answer. The+ final closes the refusal on the spot, and the next frame is granted."""loud = (1000).to_bytes(2, "little", signed=True) * 480transcriber = _ScheduledInputTranscriber([(0.02, InputTranscriptEvent(kind="speech_started")),(- 0.10,+ 0.25,InputTranscriptEvent(kind="transcript", text="Quick one?", is_final=True),@@ -3184,10 +3230,9 @@ async def test_a_final_landing_mid_opening_adopts_the_response()endpoint = _FakeAudioEndpoint(output_schedule=[+ (0.05, loud), # pre-final: refused (opens the refused response)+ (0.35, loud), # post-final: must be re-judged and granted(0.05, loud),- (0.15, loud),- (0.20, loud), # ~0.40 s in: past the cap, but adopted by then- (0.10, loud),])client = _Client()@@ -3212,14 +3257,14 @@ async def test_a_final_landing_mid_opening_adopts_the_response().open_session(RealtimeSessionConfig())events = await _collect_until(- session, stop_after=1, kind="never", timeout_s=1.2+ session, stop_after=2, kind="audio_delta", timeout_s=2.0)- assert session.diagnostics().get("opening_responses_bounded", 0) == 0, (- "an adopted opening response is the answer and must not be cut"- )audio_events = [e for e in events if e.type == "audio_delta"]- assert len(audio_events) == 4, "all audio flowed, none was refused"+ assert len(audio_events) == 2, (+ "the post-final frames must flow without waiting out the "+ f"stale-refusal window; saw {len(audio_events)}"+ )await session.close()@@ -3233,9 +3278,19 @@ async def test_a_discarded_utterance_keeps_its_response_window(plays - and after the grace an unanswered window retires."""transcriber = _ScheduledInputTranscriber([- (0.02, InputTranscriptEvent(kind="speech_started")),+ # Priming exchange: the call opening answers no bare cough under+ # the no-unsolicited policy, so the discard under test is a+ # MID-CALL event like the live BUG-124 amplifier was.+ (0.01, InputTranscriptEvent(kind="speech_started")),(- 0.03,+ 0.0,+ InputTranscriptEvent(+ kind="transcript", text="Hello there.", is_final=True+ ),+ ),+ (0.05, InputTranscriptEvent(kind="speech_started")),+ (+ 0.01,InputTranscriptEvent(kind="speech_discarded", voiced_ms=200),),]@@ -3281,9 +3336,19 @@ async def test_an_unanswered_discard_window_expires(monkeypatch) -> None:)transcriber = _ScheduledInputTranscriber([- (0.02, InputTranscriptEvent(kind="speech_started")),+ # Priming exchange: the call opening answers no bare cough under+ # the no-unsolicited policy, so the discard under test is a+ # MID-CALL event like the live BUG-124 amplifier was.+ (0.01, InputTranscriptEvent(kind="speech_started")),(- 0.03,+ 0.0,+ InputTranscriptEvent(+ kind="transcript", text="Hello there.", is_final=True+ ),+ ),+ (0.05, InputTranscriptEvent(kind="speech_started")),+ (+ 0.01,InputTranscriptEvent(kind="speech_discarded", voiced_ms=200),),]