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): deliver ChatGPT-Live replies whole instead of in fragments
Ruben Lütkeac930581086b
diff --git a/jarvis/plugins/realtime/codex_subscription.py b/jarvis/plugins/realtime/codex_subscription.pyindex b94fc87fda..7b67b7bf65 100644--- a/jarvis/plugins/realtime/codex_subscription.py+++ b/jarvis/plugins/realtime/codex_subscription.py@@ -10,6 +10,7 @@ closes honestly instead of silently entering usage-billed API voice.from __future__ import annotations+import arrayimport asyncioimport base64import importlib@@ -25,10 +26,36 @@ log = logging.getLogger(__name__)_INPUT_RATE = 24_000_OUTPUT_RATE = 24_000_BROKER_OFFER_WAIT_S = 3.0-_OUTPUT_QUIESCENCE_S = 0.5+# No audible frame for this long ends the turn. It is a BACKSTOP, not the+# boundary: the terminal response item ends a turn immediately. Measured+# 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_NORMALIZATION_QUEUE_MAX = 128_REMOTE_CLEANUP_TIMEOUT_S = 1.5_TURN_INTERRUPT_TIMEOUT_S = 1.5+# ChatGPT-Live renders a generation pause as silent PCM. This USED to be+# compressed away — correct for the retired v1 protocol, where audio arrived as+# sideband deltas FASTER than realtime, so dropping silence genuinely shortened+# the wait. On v3 the audio is a live WebRTC media track: 20 ms frames arrive at+# wall clock, and a dropped frame cannot fast-forward anything — it only starves+# the permanently open output stream, which is exactly the chopped voice users+# reported (measured 2026-08-02: six cuts inside one reply). Every chunk is+# forwarded verbatim now; the peak below only classifies a chunk as AUDIBLE, so+# that the quiescence backstop is not held open forever by a track that keeps+# sending silence between turns. Energy only, never transcript content (AP-27).+_OUTPUT_AUDIBLE_PEAK = 200+# The v3 item vocabulary is OpenAI-Realtime family — the two items already+# handled here (``input_audio_buffer.speech_started``, ``response.cancelled``)+# are its members, and that family ends a response with ``response.done``; the+# repo's own OpenAI adapter maps it exactly that way. The precise v3 spelling is+# not yet confirmed live, so both plausible names are accepted AND the+# quiescence backstop still terminates every turn if neither ever arrives.+_TERMINAL_RESPONSE_ITEMS = frozenset({"response.done", "response.completed"})+_RESPONSE_OPENED_ITEMS = frozenset({"response.created", "response.in_progress"})+# Bound on the one-line-per-type unknown-item log, so a chatty protocol cannot+# turn observability into log spam.+_UNKNOWN_ITEM_LOG_MAX = 32# The experimental v1 protocol was shut off server-side with the ChatGPT-Live# launch (every v1 start now answers "403 Voice session access denied",# verified live 2026-08-01). v3 is the ChatGPT-Live protocol: the SERVER@@ -134,6 +161,21 @@ def _notification_parts(notification: Any) -> tuple[str, dict[str, Any]]:return method, params if isinstance(params, dict) else {}+def _pcm16_peak(pcm: bytes) -> int:+ """Loudest sample in a PCM16 chunk, at C speed.++ Mirrors ``jarvis.realtime.session._pcm16_peak``; copied rather than imported+ because this plugin module must stay free of ``jarvis.*`` imports so plugin+ discovery never drags the app onto the startup path.+ """+ usable = len(pcm) - (len(pcm) % 2)+ if usable < 2:+ return 0+ samples = array.array("h")+ samples.frombytes(pcm[:usable])+ return max(max(samples), -min(samples))++def _thread_id_from_result(result: Any) -> str:if not isinstance(result, dict):return ""@@ -269,7 +311,9 @@ class _CodexSubscriptionRealtimeSession:audio_endpoint: Any = None,input_transcriber: Any = None,language: str = "en",+ voice: str = "",) -> None:+ self._voice = str(voice or "").strip()self._client = clientself._subscription = subscriptionself._thread_id = thread_id@@ -278,9 +322,9 @@ class _CodexSubscriptionRealtimeSession:self.realtime_version = ""# Owns the media path: ChatGPT-Live carries audio ONLY over WebRTC.self._audio_endpoint = audio_endpoint- # ChatGPT-Live never transcribes the USER, so Jarvis does it locally.- # Without this the bar stays blank and every transcript-driven- # integration (delegate, wiki, project files, hang-up phrase) is deaf.+ # ChatGPT-Live emits a user transcript, but it can hallucinate captions+ # from silence or speaker echo. Local energy-gated STT is authoritative+ # for the bar and every transcript-driven Jarvis integration.self._input_transcriber = input_transcriberself._closed = Falseself._last_input_item_id = ""@@ -372,8 +416,11 @@ class _CodexSubscriptionRealtimeSession:completion_generation = 0completion_emitted = Falsestream_ended = False- version = self.realtime_version.lower().removeprefix("v")- authoritative_done = version == "3"+ # Item types this session has already reported as unhandled. The v3 item+ # vocabulary is only partly known, and silently swallowing the rest is+ # why neither the real terminal-response item nor the never-observed+ # handoff item could be identified from a whole call's log (AP-30).+ seen_unknown_items: set[str] = set()async def _pump_notifications() -> None:try:@@ -389,9 +436,9 @@ class _CodexSubscriptionRealtimeSession:async def _pump_local_input() -> None:"""Feed locally recognized USER speech into the same event stream.- Other providers deliver these; ChatGPT-Live does not. Emitting- them here is what makes the bar show live text, the indicators- move, and every transcript-driven Jarvis integration work.+ The server transcript remains only a live preview/failure fallback.+ Emitting locally grounded events here makes the bar, indicators,+ and every transcript-driven Jarvis integration trustworthy."""transcriber = self._input_transcriberif transcriber is None:@@ -502,15 +549,22 @@ class _CodexSubscriptionRealtimeSession:)continueif queue_kind == "media_audio":- # Real provider audio keeps the turn alive exactly like the- # old sideband deltas did (quiescence timer, Orb state,- # transcript-gated playback).- if completion_task is not None:+ pcm = bytes(payload or b"")+ if not pcm:+ continue+ # Only AUDIBLE audio keeps the turn open. The media track+ # also carries silence between turns, so re-arming on every+ # chunk would mean the backstop could never fire and a turn+ # whose terminal item never arrives would hang forever.+ if (+ completion_task is not None+ and _pcm16_peak(pcm) >= _OUTPUT_AUDIBLE_PEAK+ ):_arm_completion()yield _ProviderEvent(type="audio_delta",audio=_PcmChunk(- pcm=payload,+ pcm=pcm,sample_rate=_OUTPUT_RATE,channels=1,),@@ -592,8 +646,11 @@ class _CodexSubscriptionRealtimeSession:# The start RPC result is empty in exact-0.146; the live# protocol version exists only on this notification.self.realtime_version = str(params.get("version", "") or "").strip()- authoritative_done = (- self.realtime_version.lower().removeprefix("v") == "3"+ log.info(+ "Codex subscription realtime negotiated protocol %s "+ "(voice=%s; ChatGPT-Live picks the model server-side)",+ self.realtime_version or "unknown",+ self._voice or _DEFAULT_VOICE,)continue@@ -670,12 +727,15 @@ class _CodexSubscriptionRealtimeSession:is_final=True,)self._assistant_delta_text = ""- if authoritative_done:- _cancel_completion()- if not completion_emitted:- completion_emitted = True- yield _ProviderEvent(type="turn_complete")- elif not completion_emitted:+ # ChatGPT-Live emits this per transcript PART, not per+ # response. Treating it as a turn boundary drained+ # playback, armed a ~0.9 s echo window and re-armed the+ # scrub gate three times inside ONE answer (measured+ # 2026-08-02 08:21:58 / 08:22:00 / 08:22:05) — the+ # chopped voice, and a microphone deaf between the+ # pieces. The turn ends on the terminal response item,+ # or on the quiescence backstop.+ if not completion_emitted:_arm_completion()continue@@ -780,6 +840,30 @@ class _CodexSubscriptionRealtimeSession:or None,provider_turn_id=(direct_turn_id or None),)+ elif item_type in _TERMINAL_RESPONSE_ITEMS:+ _cancel_completion()+ if not completion_emitted:+ completion_emitted = True+ log.info(+ "Codex subscription realtime turn ended on "+ "item %r (protocol %s)",+ item_type,+ self.realtime_version or "unknown",+ )+ yield _ProviderEvent(type="turn_complete")+ elif item_type in _RESPONSE_OPENED_ITEMS:+ _cancel_completion()+ completion_emitted = False+ elif item_type and item_type not in seen_unknown_items:+ # Type NAME only, once per type, bounded — never the+ # payload, which can carry transcript text.+ if len(seen_unknown_items) < _UNKNOWN_ITEM_LOG_MAX:+ seen_unknown_items.add(item_type)+ log.info(+ "Codex subscription realtime saw an unhandled "+ "realtime item type %r",+ item_type,+ )continueif method == "thread/realtime/error":@@ -837,13 +921,23 @@ class _CodexSubscriptionRealtimeSession:language: str | None = None,tools: tuple[dict[str, Any], ...] | None = None,) -> None:- # Tools stay unsupported by design: the Jarvis supervisor remains the- # only action boundary. INSTRUCTIONS, however, are the assistant's- # identity and project knowledge — dropping them was why the voice- # knew nothing about its own project. ChatGPT-Live accepts developer- # context (session.context.append), so a changed persona is delivered- # mid-call instead of being discarded.+ # Tools cannot be declared here, and that is a transport fact rather+ # than a policy choice: the app-server realtime RPC surface is only+ # start / appendAudio / appendText / appendSpeech / stop, with custom+ # fields refused outright, so there is no way to deliver a v3+ # session.update. The handoff item stays the one model-initiated action+ # channel. Say so once instead of discarding wordlessly (AP-30).+ if tools:+ log.debug(+ "Codex subscription realtime cannot declare %d tool(s): the "+ "app-server realtime RPC surface has no session.update",+ len(tools),+ )del tools+ # INSTRUCTIONS, however, are the assistant's identity and project+ # knowledge — dropping them was why the voice knew nothing about its own+ # project. ChatGPT-Live accepts developer context, so a changed persona+ # is delivered mid-call instead of being discarded.await self._deliver_context(instructions)normalized = str(language or "").strip().lower()if normalized not in _LANGUAGE_UPDATE_TEXT or normalized == self._language:@@ -945,12 +1039,11 @@ class CodexSubscriptionRealtimeProvider:async def verify_activation(cls, cfg: Any) -> None:"""Run the provider's authoritative account/config activation gate.- When the gate itself started app-server just to judge the account, it- also cleans up: leaving the transport reservation and an idle Codex- child running would make the card's reconnect button answer- "disconnect active subscription voice" after every activation. A- client that was ALREADY ready is carrying a live call — verifying is- harmless, closing it would cut the call mid-sentence.+ A successful cold verification deliberately keeps the shared+ app-server warm. Closing it here made provider selection pay one cold+ start and the first call immediately pay another. A failed probe still+ cleans up the child it started; an already-ready client may be serving+ another Codex feature and is never closed here."""app_server_module = importlib.import_module("jarvis.codex_app_server")codex_cfg = getattr(cfg, "codex", None)@@ -959,12 +1052,13 @@ class CodexSubscriptionRealtimeProvider:was_ready = bool(getattr(client, "ready", False))try:await client.require_chatgpt_login()- finally:+ except Exception:# A cold call may have raced this gate onto the same client while# we awaited: active thread subscriptions mean someone else is# using it now — closing would cut their session mid-setup.if not was_ready and not getattr(client, "_subscriptions", None):await client.close()+ raisedef __init__(self,@@ -1062,9 +1156,9 @@ class CodexSubscriptionRealtimeProvider:def _build_input_transcriber(self) -> Any:"""Local user-speech recognition, or ``None`` when unavailable.- ChatGPT-Live sends assistant transcripts only, so without this the- provider is deaf to Jarvis: the model talks, but the bar, the- indicators and every transcript-driven integration stay idle.+ ChatGPT-Live also guesses at user speech, but local energy-gated STT is+ authoritative. Without it silence/echo captions could become commands,+ while transcript-driven Jarvis integrations would have no grounded text."""if self._input_transcriber_factory is not None:return self._input_transcriber_factory()@@ -1168,6 +1262,7 @@ class CodexSubscriptionRealtimeProvider:audio_endpoint=audio_endpoint,input_transcriber=self._build_input_transcriber(),language=str(getattr(cfg, "language", "en") or "en"),+ voice=voice,)# Identity FIRST: the model must know who it is and what this# project is before the user's first word arrives.diff --git a/tests/unit/realtime/test_codex_subscription.py b/tests/unit/realtime/test_codex_subscription.pyindex f4a6515ec7..661fa1935d 100644--- a/tests/unit/realtime/test_codex_subscription.py+++ b/tests/unit/realtime/test_codex_subscription.py@@ -3,6 +3,8 @@from __future__ import annotationsimport asyncio+import contextlib+import loggingfrom types import SimpleNamespaceimport pytest@@ -439,12 +441,10 @@ def test_external_login_ready_respects_the_activation_block(@pytest.mark.asyncio-async def test_verify_activation_cleans_up_its_own_transport(+async def test_verify_activation_keeps_successful_cold_transport_warm(monkeypatch: pytest.MonkeyPatch,) -> None:- """The gate starts app-server only to judge the account; leaving the- reservation and an idle child running would 409 the card's reconnect- button after every activation."""+ """Provider selection warms the transport the first call will reuse."""from jarvis import codex_app_serverevents: list[str] = []@@ -464,7 +464,35 @@ async def test_verify_activation_cleans_up_its_own_transport(await CodexSubscriptionRealtimeProvider.verify_activation(SimpleNamespace())- assert events == ["verified", "closed"]+ assert events == ["verified"]+++async def test_verify_activation_cleans_up_a_failed_cold_transport(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ from jarvis import codex_app_server++ events: list[str] = []++ class _Client:+ async def require_chatgpt_login(self) -> None:+ events.append("failed")+ raise RuntimeError("login failed")++ async def close(self) -> None:+ events.append("closed")++ monkeypatch.setattr(+ codex_app_server,+ "get_shared_codex_app_server",+ lambda _binary: _Client(),+ )++ with pytest.raises(RuntimeError, match="login failed"):+ await CodexSubscriptionRealtimeProvider.verify_activation(SimpleNamespace())++ assert events == ["failed", "closed"]@pytest.mark.asyncio@@ -646,6 +674,45 @@ async def test_media_track_audio_becomes_normalized_audio_deltas() -> None:await session.close()+async def test_media_track_forwards_provider_silence_verbatim() -> None:+ """The reply's own pauses must survive the trip to the speaker.++ They used to be compressed away, which was right for the retired sideband+ protocol (audio arrived faster than realtime, so dropping silence really+ did shorten the wait). On a live WebRTC track it removes audio the player+ needed in order to keep playing: the output stream starves and the voice+ chops. Measured on 2026-08-02: six cuts inside a single answer.+ """+ client = _Client()+ client.subscription = _ScheduledSubscription(+ [+ (+ 0.05,+ _Notification(+ "thread/realtime/transcript/done",+ {"threadId": "thread-1", "role": "assistant", "text": "hi"},+ ),+ )+ ]+ )+ speech = (1000).to_bytes(2, "little", signed=True) * 480+ long_silence = b"\x00\x00" * (24_000 * 2)+ endpoint = _FakeAudioEndpoint(output_chunks=(speech, long_silence, speech))+ session = await _provider(client, endpoint=endpoint).open_session(+ RealtimeSessionConfig()+ )++ audio = [+ event.audio.pcm+ async for event in session.receive()+ if event.type == "audio_delta"+ ]++ assert b"".join(audio) == speech + long_silence + speech+ await session.close()++@pytest.mark.asyncioasync def test_default_done_waits_for_all_late_audio_before_one_completion(monkeypatch,@@ -872,7 +939,12 @@ async def test_done_then_handoff_cancels_synthetic_completion(monkeypatch) -> No@pytest.mark.asyncio-async def test_v3_authoritative_done_completes_without_idle_debounce(monkeypatch) -> None:+async def test_a_terminal_response_item_ends_the_turn_at_once(monkeypatch) -> None:+ """The server says when a response is over; Jarvis must not guess.++ The quiescence backstop is pushed out of reach here, so a completion can+ only come from the terminal item itself.+ """monkeypatch.setattr(codex_subscription_mod, "_OUTPUT_QUIESCENCE_S", 10.0)client = _Client([@@ -883,7 +955,11 @@ async def test_v3_authoritative_done_completes_without_idle_debounce(monkeypatch_Notification("thread/realtime/transcript/done",{"threadId": "thread-1", "role": "assistant", "text": "done"},- )+ ),+ _Notification(+ "thread/realtime/itemAdded",+ {"threadId": "thread-1", "item": {"type": "response.done"}},+ ),])session = await _provider(client).open_session(@@ -898,6 +974,53 @@ async def test_v3_authoritative_done_completes_without_idle_debounce(monkeypatchawait session.close()+async def test_transcript_done_is_a_part_boundary_not_a_turn(monkeypatch) -> None:+ """One answer, one ending.++ ChatGPT-Live streams a reply as several transcript parts. Treating each+ part's ``done`` as the end of the turn drained playback, armed a ~0.9 s+ echo window and re-armed the scrub gate three times inside ONE answer+ (measured live 2026-08-02) — the chopped voice, plus a microphone that went+ deaf between the pieces.+ """+ monkeypatch.setattr(codex_subscription_mod, "_OUTPUT_QUIESCENCE_S", 10.0)+ parts = [+ _Notification(+ "thread/realtime/started",+ {"threadId": "thread-1", "version": 3},+ )+ ]+ for text in ("first. ", "second. ", "third."):+ parts.append(+ _Notification(+ "thread/realtime/transcript/done",+ {"threadId": "thread-1", "role": "assistant", "text": text},+ )+ )+ parts.append(+ _Notification(+ "thread/realtime/itemAdded",+ {"threadId": "thread-1", "item": {"type": "response.done"}},+ )+ )+ session = await _provider(_Client(parts)).open_session(+ RealtimeSessionConfig(transport_offer_sdp="v=0\r\no=offer")+ )++ async with asyncio.timeout(0.2):+ events = [event async for event in session.receive()]++ assert len([event for event in events if event.type == "turn_complete"]) == 1+ # Every part still reaches the transcript consumers.+ assert [+ event.text+ for event in events+ if event.type == "output_transcript_delta"+ ] == ["first. ", "second. ", "third."]+ await session.close()++@pytest.mark.asyncioasync def test_normalization_queue_backpressures_and_pump_cleans_up() -> None:client = _Client()@@ -1122,7 +1245,7 @@ class _StubEndpointer:return None-def _hallucination_client() -> "_Client":+def _hallucination_client() -> _Client:return _Client([_Notification(@@ -1184,3 +1307,152 @@ async def test_without_a_local_recognizer_the_server_transcript_is_final():finals = [event for event in await _user_transcripts(speaking=None) if event.is_final]assert [event.text for event in finals] == ["a_lee pixelated image"]+++def _keeps_stream_open(*extra):+ """Notifications plus a late one, so the stream outlives the assertions."""+ return _ScheduledSubscription(+ [+ (+ 0.0,+ _Notification(+ "thread/realtime/started",+ {"threadId": "thread-1", "version": 3},+ ),+ ),+ *extra,+ (+ 2.0,+ _Notification(+ "thread/realtime/started",+ {"threadId": "thread-1", "version": 3},+ ),+ ),+ ]+ )+++_ARMS_THE_BACKSTOP = (+ 0.0,+ _Notification(+ "thread/realtime/transcript/done",+ {"threadId": "thread-1", "role": "assistant", "text": "hi"},+ ),+)+++async def test_silent_frames_never_hold_a_turn_open(monkeypatch) -> None:+ """The trap that makes the backstop the ONLY safe boundary.++ The media track keeps sending silence between turns. If silence re-armed+ the quiescence timer, that timer could never fire — and since the terminal+ response item's v3 spelling is not yet confirmed live, a turn would hang+ forever on any protocol that omits it.+ """+ monkeypatch.setattr(codex_subscription_mod, "_OUTPUT_QUIESCENCE_S", 0.1)+ client = _Client()+ client.subscription = _keeps_stream_open(_ARMS_THE_BACKSTOP)+ silence = b"\x00\x00" * 480+ endpoint = _FakeAudioEndpoint(+ output_schedule=tuple((0.02, silence) for _ in range(25))+ )+ session = await _provider(client, endpoint=endpoint).open_session(+ RealtimeSessionConfig()+ )++ completions = 0+ async with asyncio.timeout(1.0):+ async for event in session.receive():+ if event.type == "turn_complete":+ completions += 1+ break++ assert completions == 1+ await session.close()+++async def test_audible_frames_keep_a_turn_open(monkeypatch) -> None:+ """The other half: real speech must not be cut off by the backstop.++ Paired with the test above on purpose — together they rule out an+ implementation that satisfies one by ignoring audio altogether.+ """+ monkeypatch.setattr(codex_subscription_mod, "_OUTPUT_QUIESCENCE_S", 0.1)+ client = _Client()+ client.subscription = _keeps_stream_open(_ARMS_THE_BACKSTOP)+ speech = (1000).to_bytes(2, "little", signed=True) * 480+ endpoint = _FakeAudioEndpoint(+ output_schedule=tuple((0.02, speech) for _ in range(25))+ )+ session = await _provider(client, endpoint=endpoint).open_session(+ RealtimeSessionConfig()+ )++ events = []+ with contextlib.suppress(TimeoutError):+ async with asyncio.timeout(0.3):+ async for event in session.receive():+ events.append(event)++ assert [event for event in events if event.type == "audio_delta"]+ assert not [event for event in events if event.type == "turn_complete"]+ await session.close()+++async def test_an_unknown_realtime_item_type_is_named_once(caplog) -> None:+ """Silently swallowing unknown items is why neither the real terminal+ response item nor the never-observed handoff item could be identified from+ a whole call's log (AP-30). The name is logged; the payload never is."""+ caplog.set_level(logging.INFO)+ unknown = _Notification(+ "thread/realtime/itemAdded",+ {+ "threadId": "thread-1",+ "item": {"type": "response.output_audio.done", "secret": "transcript"},+ },+ )+ session = await _provider(_Client([unknown, unknown])).open_session(+ RealtimeSessionConfig(transport_offer_sdp="v=0\r\no=offer")+ )++ events = [event async for event in session.receive()]++ assert not [event for event in events if event.type == "turn_complete"]+ named = [+ record.getMessage()+ for record in caplog.records+ if "unhandled realtime item type" in record.getMessage()+ ]+ assert len(named) == 1+ assert "response.output_audio.done" in named[0]+ assert "transcript" not in named[0]+ await session.close()+++async def test_the_negotiated_protocol_and_voice_are_logged(caplog) -> None:+ """"Is this really what Codex uses?" has to be answerable from evidence."""+ caplog.set_level(logging.INFO)+ client = _Client(+ [+ _Notification(+ "thread/realtime/started",+ {"threadId": "thread-1", "version": 3},+ )+ ]+ )+ session = await _provider(client).open_session(+ RealtimeSessionConfig(voice="cove")+ )++ [event async for event in session.receive()]++ assert any(+ "negotiated protocol 3" in record.getMessage()+ and "cove" in record.getMessage()+ for record in caplog.records+ )+ await session.close()