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): own the WebRTC media path so ChatGPT-Live audio actually flows
Ruben Lütkef15d5ea03fb9
diff --git a/jarvis/plugins/realtime/codex_subscription.py b/jarvis/plugins/realtime/codex_subscription.pyindex ccd06987f9..c8a1b0e1ee 100644--- a/jarvis/plugins/realtime/codex_subscription.py+++ b/jarvis/plugins/realtime/codex_subscription.py@@ -252,7 +252,7 @@ class _CodexSubscriptionRealtimeSession:subscription: Any,thread_id: str,answer_sdp: str,- offer_lease: Any = None,+ audio_endpoint: Any = None,language: str = "en",) -> None:self._client = client@@ -261,7 +261,8 @@ class _CodexSubscriptionRealtimeSession:self.session_id = thread_idself.answer_sdp = answer_sdpself.realtime_version = ""- self._offer_lease = offer_lease+ # Owns the media path: ChatGPT-Live carries audio ONLY over WebRTC.+ self._audio_endpoint = audio_endpointself._closed = Falseself._last_input_item_id = ""self._assistant_delta_text = ""@@ -302,13 +303,14 @@ class _CodexSubscriptionRealtimeSession:pcm = bytes(getattr(chunk, "pcm", b"") or b"")if not pcm:return- await self._client.realtime_append_audio(- self._thread_id,- data=base64.b64encode(pcm).decode("ascii"),- sample_rate=sample_rate,- num_channels=channels,- samples_per_channel=len(pcm) // 2,- )+ if self._audio_endpoint is None:+ raise RuntimeError(+ "Codex subscription realtime has no media path for microphone audio"+ )+ # ChatGPT-Live (v3) has NO audio client event: the sideband append that+ # the retired v1 protocol used is rejected outright ("Invalid value:+ # 'input_audio.append'"). Microphone audio rides the media track.+ self._audio_endpoint.send_pcm(pcm, sample_rate)async def receive(self) -> AsyncIterator[_ProviderEvent]:# Stay below app-server's bounded subscription queue so a stalled@@ -336,6 +338,27 @@ class _CodexSubscriptionRealtimeSession:else:await queue.put(("stream_end", None))+ async def _pump_media_audio() -> None:+ """Feed decoded RTP audio into the same normalized event stream.++ This is the ONLY audio source on ChatGPT-Live: the sideband+ ``outputAudio`` notification the retired v1 protocol used is never+ emitted (verified live — 956 RTP frames, zero sideband deltas).+ """+ endpoint = self._audio_endpoint+ if endpoint is None:+ return+ try:+ while True:+ pcm = await endpoint.next_output_pcm()+ if pcm is None:+ return+ await queue.put(("media_audio", pcm))+ except asyncio.CancelledError:+ raise+ except Exception as exc: # noqa: BLE001 - normalized by consumer+ await queue.put(("stream_error", exc))+async def _emit_after_idle(generation: int) -> None:await asyncio.sleep(_OUTPUT_QUIESCENCE_S)await queue.put(("completion", generation))@@ -362,9 +385,28 @@ class _CodexSubscriptionRealtimeSession:_pump_notifications(),name=f"codex-realtime-notifications-{self._thread_id}",)+ media_task = asyncio.create_task(+ _pump_media_audio(),+ name=f"codex-realtime-media-{self._thread_id}",+ )try:while True:queue_kind, payload = await queue.get()+ if 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:+ _arm_completion()+ yield _ProviderEvent(+ type="audio_delta",+ audio=_PcmChunk(+ pcm=payload,+ sample_rate=_OUTPUT_RATE,+ channels=1,+ ),+ )+ continueif queue_kind == "completion":if payload != completion_generation:continue@@ -508,10 +550,12 @@ class _CodexSubscriptionRealtimeSession:continueif method == "thread/realtime/outputAudio/delta":- # The sideband PCM is authoritative for Jarvis playback:- # it passes through the existing scrub, barge-in, and- # persistence gates. The browser peer intentionally does- # not play the duplicate RTP track.+ if self._audio_endpoint is not None:+ # ChatGPT-Live never emits this; if a future protocol+ # revision mirrors audio again, playing BOTH sources+ # would double every word. The media track wins.+ continue+ # Legacy sideband path (retired v1 protocol).audio = params.get("audio")if not isinstance(audio, dict):_cancel_completion()@@ -642,13 +686,15 @@ class _CodexSubscriptionRealtimeSession:)finally:_cancel_completion()- if not pump_task.done():- pump_task.cancel()+ for pump in (pump_task, media_task):+ if not pump.done():+ pump.cancel()for task in tuple(timer_tasks):if not task.done():task.cancel()await asyncio.gather(pump_task,+ media_task,*tuple(timer_tasks),return_exceptions=True,)@@ -710,8 +756,8 @@ class _CodexSubscriptionRealtimeSession:try:await _close_subscription(self._subscription)finally:- if self._offer_lease is not None:- await self._offer_lease.release()+ if self._audio_endpoint is not None:+ await self._audio_endpoint.close()class CodexSubscriptionRealtimeProvider:@@ -721,7 +767,9 @@ class CodexSubscriptionRealtimeProvider:credential_family = "openai-chatgpt-subscription"supports_realtime = Trueimplicit_usage_fallback_allowed = False- requires_webrtc_offer = True+ # Jarvis owns the WebRTC peer in-process now, so the UI no longer has to+ # broker a signalling offer (and a headless host needs no browser at all).+ requires_webrtc_offer = False# Declared handshake need (capability, AP-21): a COLD start spawns# app-server, verifies the live account, re-audits config, and negotiates# WebRTC — measured 15-25s on a mid-range desktop. The shared 12s ceiling@@ -760,11 +808,12 @@ class CodexSubscriptionRealtimeProvider:self,*,client: Any = None,- offer_broker: Any = None,+ audio_endpoint_factory: Any = None,binary_path: str | None = None,) -> None:self._client = client- self._offer_broker = offer_broker+ # Injected in tests; production builds the in-process WebRTC endpoint.+ self._audio_endpoint_factory = audio_endpoint_factoryself._binary_path = str(binary_path or "").strip() or None@classmethod@@ -815,25 +864,18 @@ class CodexSubscriptionRealtimeProvider:return Trueasync def open_session(self, cfg: Any) -> _CodexSubscriptionRealtimeSession:- offer_sdp = str(getattr(cfg, "transport_offer_sdp", "") or "").strip()- offer_lease: Any = None- if not offer_sdp:- broker = self._offer_broker- if broker is None:- broker_module = importlib.import_module(- "jarvis.realtime.offer_broker"- )- broker = broker_module.get_realtime_transport_offer_broker()- offer_lease = await broker.acquire(timeout_s=_BROKER_OFFER_WAIT_S)- if offer_lease is None:- raise RuntimeError(- "Codex subscription realtime needs a connected UI WebRTC "- "offer, so this session cannot start"- )- offer_sdp = offer_lease.offer_sdp-- broker_module = importlib.import_module("jarvis.realtime.offer_broker")- offer_sdp = broker_module.validate_webrtc_offer_sdp(offer_sdp)+ # Jarvis owns the media path in-process. The UI could only ever broker+ # a signalling-shaped offer (no microphone), which ChatGPT-Live cannot+ # use: on v3 the audio IS the WebRTC track.+ audio_endpoint: Any = None+ if self._audio_endpoint_factory is not None:+ audio_endpoint = self._audio_endpoint_factory()+ else:+ transport_module = importlib.import_module(+ "jarvis.realtime.webrtc_transport"+ )+ audio_endpoint = transport_module.RealtimeWebRtcAudioEndpoint()+ offer_sdp = await audio_endpoint.create_offer()client = self._clientif client is None:@@ -894,14 +936,16 @@ class CodexSubscriptionRealtimeProvider:answer_sdp = str(getattr(start, "answer_sdp", "") or "").strip()if not answer_sdp:raise RuntimeError("Codex app-server did not return a WebRTC answer SDP")- if offer_lease is not None and not await offer_lease.answer(answer_sdp):- raise RuntimeError("The UI WebRTC offer disconnected before Codex answered")+ await audio_endpoint.apply_answer(answer_sdp)+ # Fail here rather than mid-call: without a live media path the+ # session would look connected and stay mute in both directions.+ await audio_endpoint.wait_connected()return _CodexSubscriptionRealtimeSession(client=client,subscription=subscription,thread_id=thread_id,answer_sdp=answer_sdp,- offer_lease=offer_lease,+ audio_endpoint=audio_endpoint,language=str(getattr(cfg, "language", "en") or "en"),)except BaseException:@@ -912,8 +956,7 @@ class CodexSubscriptionRealtimeProvider:if subscription is not None:await _close_subscription(subscription)finally:- if offer_lease is not None:- await offer_lease.release()+ await audio_endpoint.close()raisediff --git a/jarvis/realtime/webrtc_transport.py b/jarvis/realtime/webrtc_transport.pynew file mode 100644index 0000000000..6a96a323c2--- /dev/null+++ b/jarvis/realtime/webrtc_transport.py@@ -0,0 +1,293 @@+"""In-process WebRTC audio endpoint for subscription realtime transports.++ChatGPT-Live (Codex app-server realtime ``v3``) carries audio ONLY on the+WebRTC media track: its client-event vocabulary has no audio append at all+(``session.update`` / ``session.context.append`` /+``delegation.context.append`` / ``delegation.function_call_output.create`` /+``session.close``), and the sideband ``thread/realtime/outputAudio/delta``+that the retired ``v1`` protocol used is never emitted. Verified live on+2026-08-01: a real peer received 956 RTP frames and zero sideband deltas.++Owning the peer HERE rather than in the UI keeps every audio-dependent+Jarvis feature intact — wake word, echo guard, barge-in, the Orb's speaking+state, transcript-gated playback — because PCM still flows through the same+pipeline. The UI only ever brokered a signalling-shaped offer, which cannot+carry a microphone.++The module imports ``aiortc`` lazily so plugin discovery and boot stay free+of it (AP-26), and degrades with an honest message when it is absent.+"""++from __future__ import annotations++import asyncio+import fractions+import logging+from typing import Any++log = logging.getLogger(__name__)++# Opus/WebRTC negotiate 48 kHz; Jarvis's realtime pipeline speaks 24 kHz mono.+_WIRE_RATE = 48_000+_WIRE_FRAME_SAMPLES = 960 # 20 ms+_JARVIS_RATE = 24_000+# Bounded so a stalled consumer propagates backpressure instead of buffering+# an unbounded amount of audio (~4 s at 20 ms frames).+_SEND_QUEUE_MAX = 200+_RECV_QUEUE_MAX = 200+_ICE_TIMEOUT_S = 15.0+++class WebRtcTransportUnavailable(RuntimeError):+ """The host cannot provide an in-process WebRTC audio endpoint."""+++def webrtc_available() -> bool:+ """Whether an in-process WebRTC audio endpoint can be built here."""+ try:+ import aiortc # noqa: F401, PLC0415 - capability probe only+ import av # noqa: F401, PLC0415+ except Exception: # noqa: BLE001 - a missing optional stack is a capability answer+ return False+ return True+++class _PcmSenderTrack:+ """Outgoing audio track fed by Jarvis PCM chunks.++ Real-time paced: the peer expects roughly wall-clock delivery, so a gap in+ the incoming PCM becomes silence rather than a burst that would desync the+ far end's voice-activity detection.+ """++ kind = "audio"++ def __init__(self) -> None:+ from aiortc.mediastreams import MediaStreamTrack # noqa: PLC0415++ # Composed rather than subclassed at import time so the aiortc import+ # stays inside the function that needs it.+ self._impl = _build_sender_track(MediaStreamTrack)+ self.queue: asyncio.Queue[bytes] = self._impl.queue++ @property+ def track(self) -> Any:+ return self._impl+++def _build_sender_track(base: Any) -> Any:+ """Return a live sender-track instance bound to ``aiortc``'s base class."""+ import numpy as np # noqa: PLC0415+ from av import AudioFrame # noqa: PLC0415++ class _SenderTrack(base): # type: ignore[misc, valid-type]+ kind = "audio"++ def __init__(self) -> None:+ super().__init__()+ self.queue: asyncio.Queue[bytes] = asyncio.Queue(+ maxsize=_SEND_QUEUE_MAX+ )+ self._timestamp = 0+ self._residue = b""++ async def recv(self) -> Any:+ # One 20 ms frame per tick, at wall clock.+ await asyncio.sleep(_WIRE_FRAME_SAMPLES / _WIRE_RATE)+ needed = _WIRE_FRAME_SAMPLES * 2 # int16 mono at the wire rate+ while len(self._residue) < needed:+ try:+ chunk = self.queue.get_nowait()+ except asyncio.QueueEmpty:+ break+ self._residue += chunk+ if len(self._residue) >= needed:+ payload = self._residue[:needed]+ self._residue = self._residue[needed:]+ else:+ # Underrun: send silence so the far end keeps a continuous+ # stream (its VAD reads gaps as end-of-speech).+ payload = self._residue + b"\x00" * (needed - len(self._residue))+ self._residue = b""+ samples = np.frombuffer(payload, dtype=np.int16).reshape(1, -1)+ frame = AudioFrame.from_ndarray(samples, format="s16", layout="mono")+ frame.sample_rate = _WIRE_RATE+ frame.pts = self._timestamp+ frame.time_base = fractions.Fraction(1, _WIRE_RATE)+ self._timestamp += _WIRE_FRAME_SAMPLES+ return frame++ return _SenderTrack()+++def _upsample_to_wire(pcm: bytes, source_rate: int) -> bytes:+ """Convert mono int16 PCM to the 48 kHz wire rate."""+ import numpy as np # noqa: PLC0415++ if source_rate == _WIRE_RATE or not pcm:+ return pcm+ samples = np.frombuffer(pcm, dtype=np.int16)+ if samples.size == 0:+ return b""+ ratio = _WIRE_RATE / float(source_rate)+ target_len = max(1, int(round(samples.size * ratio)))+ # Linear interpolation: cheap, artifact-free enough for speech, and it+ # keeps this hot path free of a heavy resampler dependency.+ positions = np.linspace(0, samples.size - 1, target_len)+ resampled = np.interp(positions, np.arange(samples.size), samples)+ return resampled.astype(np.int16).tobytes()+++class RealtimeWebRtcAudioEndpoint:+ """A Python-owned WebRTC peer that carries realtime audio both ways."""++ def __init__(self) -> None:+ if not webrtc_available():+ raise WebRtcTransportUnavailable(+ "In-process WebRTC audio needs the 'aiortc' package. Install "+ "Jarvis's requirements to use ChatGPT subscription voice."+ )+ from aiortc import RTCPeerConnection # noqa: PLC0415++ self._pc = RTCPeerConnection()+ self._sender = _PcmSenderTrack()+ self._pc.addTrack(self._sender.track)+ self._recv_queue: asyncio.Queue[bytes | None] = asyncio.Queue(+ maxsize=_RECV_QUEUE_MAX+ )+ self._reader_task: asyncio.Task[None] | None = None+ self._closed = False++ @self._pc.on("track")+ def _on_track(track: Any) -> None: # pragma: no cover - callback wiring+ if track.kind != "audio":+ return+ self._reader_task = asyncio.create_task(+ self._drain_remote(track), name="codex-realtime-rtp-reader"+ )++ @self._pc.on("connectionstatechange")+ async def _on_state() -> None: # pragma: no cover - callback wiring+ state = self._pc.connectionState+ if state in {"failed", "closed"}:+ log.warning("Realtime WebRTC peer entered state %s", state)+ await self._finish_stream()++ async def _drain_remote(self, track: Any) -> None:+ """Decode the remote track into 24 kHz mono PCM for the pipeline."""+ from av.audio.resampler import AudioResampler # noqa: PLC0415++ resampler = AudioResampler(+ format="s16", layout="mono", rate=_JARVIS_RATE+ )+ try:+ while True:+ frame = await track.recv()+ for resampled in resampler.resample(frame):+ pcm = bytes(resampled.planes[0])[: resampled.samples * 2]+ if not pcm:+ continue+ try:+ self._recv_queue.put_nowait(pcm)+ except asyncio.QueueFull:+ # Backpressure: drop the OLDEST frame so live speech+ # stays current instead of drifting further behind.+ with_suppress_get(self._recv_queue)+ self._recv_queue.put_nowait(pcm)+ except asyncio.CancelledError:+ raise+ except Exception as exc: # noqa: BLE001 - the track ends with the call+ log.debug("Realtime WebRTC remote track ended (%s)", type(exc).__name__)+ finally:+ await self._finish_stream()++ async def _finish_stream(self) -> None:+ if self._closed:+ return+ try:+ self._recv_queue.put_nowait(None)+ except asyncio.QueueFull: # noqa: S110 - the consumer already has a terminator queued+ pass++ async def create_offer(self) -> str:+ """Return a fully gathered offer SDP for the provider handshake."""+ offer = await self._pc.createOffer()+ await self._pc.setLocalDescription(offer)+ sdp = str(self._pc.localDescription.sdp or "")+ if not sdp.strip():+ raise WebRtcTransportUnavailable(+ "The local WebRTC endpoint produced no offer."+ )+ return sdp++ async def apply_answer(self, answer_sdp: str) -> None:+ from aiortc import RTCSessionDescription # noqa: PLC0415++ await self._pc.setRemoteDescription(+ RTCSessionDescription(sdp=answer_sdp, type="answer")+ )++ async def wait_connected(self, timeout_s: float = _ICE_TIMEOUT_S) -> None:+ """Block until the media path is usable, or fail honestly."""+ deadline = asyncio.get_running_loop().time() + timeout_s+ while True:+ state = self._pc.connectionState+ if state == "connected":+ return+ if state in {"failed", "closed"}:+ raise WebRtcTransportUnavailable(+ f"The realtime WebRTC media path {state}."+ )+ if asyncio.get_running_loop().time() >= deadline:+ raise WebRtcTransportUnavailable(+ "The realtime WebRTC media path did not connect in time."+ )+ await asyncio.sleep(0.05)++ def send_pcm(self, pcm: bytes, sample_rate: int) -> None:+ """Queue one mono int16 PCM chunk for the outgoing media track."""+ if self._closed or not pcm:+ return+ payload = _upsample_to_wire(pcm, int(sample_rate or _JARVIS_RATE))+ try:+ self._sender.queue.put_nowait(payload)+ except asyncio.QueueFull:+ # Drop the oldest: stale microphone audio is worse than a gap.+ with_suppress_get(self._sender.queue)+ try:+ self._sender.queue.put_nowait(payload)+ except asyncio.QueueFull: # noqa: S110 - a full queue after a drop means the peer is gone+ pass++ async def next_output_pcm(self) -> bytes | None:+ """Return the next decoded 24 kHz chunk, or ``None`` at end of stream."""+ return await self._recv_queue.get()++ async def close(self) -> None:+ if self._closed:+ return+ self._closed = True+ task = self._reader_task+ self._reader_task = None+ if task is not None and not task.done():+ task.cancel()+ await asyncio.gather(task, return_exceptions=True)+ try:+ await self._pc.close()+ except Exception: # noqa: BLE001 - teardown is best effort+ log.debug("Realtime WebRTC peer close failed", exc_info=True)+++def with_suppress_get(queue: asyncio.Queue[Any]) -> None:+ """Drop one queued item; used to make room under backpressure."""+ try:+ queue.get_nowait()+ except asyncio.QueueEmpty: # noqa: S110 - an empty queue already has room+ pass+++__all__ = [+ "RealtimeWebRtcAudioEndpoint",+ "WebRtcTransportUnavailable",+ "webrtc_available",+]diff --git a/pyproject.toml b/pyproject.tomlindex 3ea9cc5a5c..da17ddf924 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -72,6 +72,12 @@ dependencies = ["loguru>=0.7","keyring>=25.5","sounddevice>=0.5", # PortAudio binding; needs system libportaudio2 on Linux+ # ChatGPT-Live (Codex subscription voice) carries audio ONLY on a WebRTC+ # media track — its protocol has no audio event at all. Jarvis owns that+ # peer in-process so the existing pipeline (wake word, echo guard,+ # barge-in, Orb) keeps working; without aiortc that ONE provider degrades+ # with an honest message while every other voice path is unaffected.+ "aiortc>=1.13",# NumPy 2.1 is the conservative runtime branch everywhere it ships. Its# Windows ARM64 wheel gap is permanent, though, so that architecture uses# the first compatible branch with official CPython 3.11+ ARM64 wheels.diff --git a/tests/contract/test_realtime_provider_contract.py b/tests/contract/test_realtime_provider_contract.pyindex 91dfa1c799..b7fd567e9f 100644--- a/tests/contract/test_realtime_provider_contract.py+++ b/tests/contract/test_realtime_provider_contract.py@@ -39,7 +39,9 @@ def test_subscription_provider_is_structurally_conformant_without_api_key() -> Nassert provider.input_sample_rate == 24_000assert provider.output_sample_rate == 24_000assert provider.credential_candidates == ()- assert provider.requires_webrtc_offer is True+ # Jarvis owns the WebRTC peer in-process (ChatGPT-Live carries audio on+ # the media track), so no UI has to broker a signalling offer any more.+ assert provider.requires_webrtc_offer is False@pytest.mark.asynciodiff --git a/tests/unit/realtime/test_codex_subscription.py b/tests/unit/realtime/test_codex_subscription.pyindex 33df221885..21f7127a57 100644--- a/tests/unit/realtime/test_codex_subscription.py+++ b/tests/unit/realtime/test_codex_subscription.py@@ -3,7 +3,6 @@from __future__ import annotationsimport asyncio-import base64from types import SimpleNamespaceimport pytest@@ -75,6 +74,69 @@ class _CountingSubscription(_Subscription):)+class _FakeAudioEndpoint:+ """Stands in for the in-process WebRTC peer.++ ChatGPT-Live carries audio on the media track, so the adapter owns a real+ peer in production. Tests inject this to keep the suite off the network+ while still pinning that microphone PCM reaches the media path and that+ remote audio re-enters the normalized event stream.+ """++ def __init__(+ self,+ *,+ output_chunks: tuple[bytes, ...] = (),+ output_schedule: tuple[tuple[float, bytes], ...] = (),+ ) -> None:+ self.sent: list[tuple[bytes, int]] = []+ self.answers: list[str] = []+ self.closed = False+ self.connected = False+ # ``output_schedule`` paces chunks like real RTP arrival, which is what+ # the quiescence timer reacts to.+ self._schedule = list(output_schedule)+ self._outputs = asyncio.Queue()+ for chunk in output_chunks:+ self._outputs.put_nowait(chunk)+ if not output_schedule:+ self._outputs.put_nowait(None)++ async def create_offer(self) -> str:+ return "v=0\r\no=python-peer\r\n"++ async def apply_answer(self, answer_sdp: str) -> None:+ self.answers.append(answer_sdp)++ async def wait_connected(self, timeout_s: float = 15.0) -> None:+ del timeout_s+ self.connected = True++ def send_pcm(self, pcm: bytes, sample_rate: int) -> None:+ self.sent.append((pcm, sample_rate))++ async def next_output_pcm(self):+ if self._schedule:+ delay, chunk = self._schedule.pop(0)+ if delay:+ await asyncio.sleep(delay)+ return chunk+ return await self._outputs.get()++ async def close(self) -> None:+ self.closed = True+++def _provider(client, **kwargs):+ """Build the provider with an injected fake media endpoint."""+ endpoint = kwargs.pop("endpoint", None) or _FakeAudioEndpoint()+ provider = CodexSubscriptionRealtimeProvider(+ client=client, audio_endpoint_factory=lambda: endpoint, **kwargs+ )+ provider.test_endpoint = endpoint+ return provider++class _Client:def __init__(self,@@ -178,7 +240,7 @@ class _TimedOutCleanupClient(_Client):@pytest.mark.asyncioasync def test_direct_sdp_open_uses_safe_experimental_transport_contract() -> None:client = _Client()- provider = CodexSubscriptionRealtimeProvider(client=client)+ provider = _provider(client)session = await provider.open_session(RealtimeSessionConfig(@@ -198,7 +260,9 @@ async def test_direct_sdp_open_uses_safe_experimental_transport_contract() -> No_thread_id, start = client.realtime_starts[0]assert start == {"output_modality": "audio",- "offer_sdp": "v=0\r\no=browser-offer",+ # Jarvis's own peer produced this offer: ChatGPT-Live carries the+ # audio itself, which a signalling-only UI offer cannot do.+ "offer_sdp": "v=0\r\no=python-peer\r\n","prompt": "",# v3 (ChatGPT-Live): the server chooses the model — the client must# not send one (rejected with "Field `session.model` is not allowed",@@ -216,7 +280,7 @@ async def test_direct_sdp_open_uses_safe_experimental_transport_contract() -> No@pytest.mark.asyncioasync def test_failed_remote_cleanup_poisons_the_entire_app_server_client() -> None:client = _FailedCleanupClient()- session = await CodexSubscriptionRealtimeProvider(client=client).open_session(+ session = await _provider(client).open_session(RealtimeSessionConfig(transport_offer_sdp="v=0\r\no=offer"))@@ -233,7 +297,7 @@ async def test_timed_out_remote_cleanup_poisons_the_entire_client() -> None:monkeypatch.setattr(codex_subscription_mod, "_REMOTE_CLEANUP_TIMEOUT_S", 0.01)client = _TimedOutCleanupClient()- session = await CodexSubscriptionRealtimeProvider(client=client).open_session(+ session = await _provider(client).open_session(RealtimeSessionConfig(transport_offer_sdp="v=0\r\no=offer"))@@ -247,7 +311,7 @@ async def test_timed_out_remote_cleanup_poisons_the_entire_client(async def test_stale_api_voice_selection_fails_before_subscription_realtime_start() -> None:"""A voice outside the server-confirmed v3 roster fails before start."""client = _Client()- provider = CodexSubscriptionRealtimeProvider(client=client)+ provider = _provider(client)config = RealtimeSessionConfig(transport_offer_sdp="v=0\r\no=browser-offer",voice="marin",@@ -267,7 +331,7 @@ async def test_stale_model_pin_is_ignored_not_fatal() -> None:(or the dead v1 era) must not brick the call — it is dropped, and nomodel field reaches the server."""client = _Client()- provider = CodexSubscriptionRealtimeProvider(client=client)+ provider = _provider(client)config = RealtimeSessionConfig(transport_offer_sdp="v=0\r\no=browser-offer",model="gpt-4o-realtime-preview",@@ -285,7 +349,7 @@ async def test_stale_model_pin_is_ignored_not_fatal() -> None:@pytest.mark.asyncioasync def test_language_update_is_developer_context_and_speech_is_authoritative() -> None:client = _Client()- session = await CodexSubscriptionRealtimeProvider(client=client).open_session(+ session = await _provider(client).open_session(RealtimeSessionConfig(transport_offer_sdp="v=0\r\no=offer"))@@ -306,7 +370,7 @@ async def test_language_update_is_developer_context_and_speech_is_authoritative(@pytest.mark.asyncioasync def test_open_relies_on_authoritative_app_server_auth_without_pre_probe() -> None:client = _UnauthenticatedClient()- provider = CodexSubscriptionRealtimeProvider(client=client)+ provider = _provider(client)with pytest.raises(RuntimeError, match="unauthenticated account"):await provider.open_session(@@ -322,7 +386,7 @@ async def test_open_relies_on_authoritative_app_server_auth_without_pre_probe()async def test_orchestrator_capability_check_does_not_repeat_cli_auth_probe(monkeypatch,) -> None:- provider = CodexSubscriptionRealtimeProvider(client=_Client())+ provider = _provider(_Client())def _unexpected_probe(_cls):raise AssertionError("factory login probe must not repeat during handshake")@@ -451,33 +515,26 @@ def test_external_login_ready_fails_open_on_transient_busy(@pytest.mark.asyncio-async def test_send_audio_uses_sideband_pcm_without_api_usage_accounting() -> None:+async def test_send_audio_rides_the_media_track_not_a_sideband_append() -> None:+ """ChatGPT-Live has NO audio client event: the sideband append the retired+ v1 protocol used is rejected outright, so microphone PCM must reach the+ WebRTC media path instead."""client = _Client()- session = await CodexSubscriptionRealtimeProvider(client=client).open_session(- RealtimeSessionConfig(transport_offer_sdp="v=0\r\no=offer")- )+ provider = _provider(client)+ session = await provider.open_session(RealtimeSessionConfig())await session.send_audio(SimpleNamespace(pcm=b"\x01\x00\x02\x00", sample_rate=24_000, channels=1))- assert client.audio_appends == [- (- "thread-1",- {- "data": base64.b64encode(b"\x01\x00\x02\x00").decode("ascii"),- "sample_rate": 24_000,- "num_channels": 1,- "samples_per_channel": 2,- },- )- ]+ assert provider.test_endpoint.sent == [(b"\x01\x00\x02\x00", 24_000)]+ assert client.audio_appends == []await session.close()+ assert provider.test_endpoint.closed is True@pytest.mark.asyncioasync def test_notifications_normalize_audio_transcripts_and_boundaries() -> None:- encoded = base64.b64encode(b"\x01\x00\x02\x00").decode("ascii")client = _Client([_Notification(@@ -498,18 +555,6 @@ async def test_notifications_normalize_audio_transcripts_and_boundaries() -> Non"thread/realtime/transcript/done",{"threadId": "thread-1", "role": "user", "text": "hello"},),- _Notification(- "thread/realtime/outputAudio/delta",- {- "threadId": "thread-1",- "audio": {- "data": encoded,- "sampleRate": 24_000,- "numChannels": 1,- "samplesPerChannel": 2,- },- },- ),_Notification("thread/realtime/transcript/delta",{"threadId": "thread-1", "role": "assistant", "delta": "hi"},@@ -520,47 +565,70 @@ async def test_notifications_normalize_audio_transcripts_and_boundaries() -> Non),])- session = await CodexSubscriptionRealtimeProvider(client=client).open_session(+ session = await _provider(client).open_session(RealtimeSessionConfig(transport_offer_sdp="v=0\r\no=offer"))events = [event async for event in session.receive()]+ # No audio_delta here on purpose: ChatGPT-Live carries assistant audio on+ # the WebRTC media track, never as a sideband notification.assert [event.type for event in events] == ["speech_started","input_transcript","input_transcript",- "audio_delta","output_transcript_delta","turn_complete","error",]assert events[2].is_final is Trueassert events[2].item_id == "input-1"- assert events[3].audio is not None- assert events[3].audio.pcm == b"\x01\x00\x02\x00"+ assert events[3].text == "hi"# A cleanly exhausted fake stream is still an unexpected transport death.assert "ended unexpectedly" in str(events[-1].error)await session.close()+async def test_media_track_audio_becomes_normalized_audio_deltas() -> None:+ """Assistant audio arrives as RTP on ChatGPT-Live; it must reach the+ pipeline as ordinary audio_delta events so playback, the Orb, and the+ transcript-gated release keep working exactly as before."""+ client = _Client()+ # The notification stream stays open past the audio, exactly as it does+ # during a live call — otherwise the fake transport death would race the+ # media pump.+ client.subscription = _ScheduledSubscription(+ [+ (+ 0.05,+ _Notification(+ "thread/realtime/transcript/done",+ {"threadId": "thread-1", "role": "assistant", "text": "hi"},+ ),+ )+ ]+ )+ endpoint = _FakeAudioEndpoint(output_chunks=(b"\x01\x00\x02\x00", b"\x03\x00"))+ session = await _provider(client, endpoint=endpoint).open_session(+ RealtimeSessionConfig()+ )++ audio = [+ event async for event in session.receive() if event.type == "audio_delta"+ ]++ assert [event.audio.pcm for event in audio] == [b"\x01\x00\x02\x00", b"\x03\x00"]+ assert {event.audio.sample_rate for event in audio} == {24_000}+ assert {event.audio.channels for event in audio} == {1}+ await session.close()++@pytest.mark.asyncioasync def test_default_done_waits_for_all_late_audio_before_one_completion(monkeypatch,) -> None:monkeypatch.setattr(codex_subscription_mod, "_OUTPUT_QUIESCENCE_S", 0.03)- encoded = base64.b64encode(b"\x01\x00").decode("ascii")- audio = _Notification(- "thread/realtime/outputAudio/delta",- {- "threadId": "thread-1",- "audio": {- "data": encoded,- "sampleRate": 24_000,- "numChannels": 1,- },- },- )client = _Client()client.subscription = _ScheduledSubscription([@@ -571,12 +639,18 @@ async def test_default_done_waits_for_all_late_audio_before_one_completion({"threadId": "thread-1", "role": "assistant", "text": "hi"},),),- (0.015, audio),- (0.015, audio),+ # Keeps the notification stream open while the late media audio+ # arrives, as a live transport does.+ (0.2, _Notification("thread/realtime/keepalive", {"threadId": "thread-1"})),])- session = await CodexSubscriptionRealtimeProvider(client=client).open_session(- RealtimeSessionConfig(transport_offer_sdp="v=0\r\no=offer")+ # Late RTP audio must keep re-arming the quiescence timer so one turn ends+ # exactly once, after the last audible chunk.+ endpoint = _FakeAudioEndpoint(+ output_schedule=((0.015, b"\x01\x00"), (0.015, b"\x01\x00"), (0.0, None))+ )+ session = await _provider(client, endpoint=endpoint).open_session(+ RealtimeSessionConfig())events = [event async for event in session.receive()]@@ -614,7 +688,7 @@ async def test_later_assistant_delta_cancels_pending_completion_until_next_done(),])- session = await CodexSubscriptionRealtimeProvider(client=client).open_session(+ session = await _provider(client).open_session(RealtimeSessionConfig(transport_offer_sdp="v=0\r\no=offer"))@@ -652,7 +726,7 @@ async def test_terminal_or_interruption_event_cancels_pending_completion()cancelling = _Notification(method, {"threadId": "thread-1", **params})client = _Client([done, cancelling])- session = await CodexSubscriptionRealtimeProvider(client=client).open_session(+ session = await _provider(client).open_session(RealtimeSessionConfig(transport_offer_sdp="v=0\r\no=offer"))@@ -670,7 +744,7 @@ async def test_duplicate_transcript_done_emits_one_completion(monkeypatch) -> No{"threadId": "thread-1", "role": "assistant", "text": "done"},)client = _Client([done, done])- session = await CodexSubscriptionRealtimeProvider(client=client).open_session(+ session = await _provider(client).open_session(RealtimeSessionConfig(transport_offer_sdp="v=0\r\no=offer"))@@ -693,7 +767,7 @@ async def test_handoff_without_transcript_preserves_neutral_boundary() -> None:)])- session = await CodexSubscriptionRealtimeProvider(client=client).open_session(+ session = await _provider(client).open_session(RealtimeSessionConfig(transport_offer_sdp="v=0\r\no=offer"))@@ -733,7 +807,7 @@ async def test_handoff_preserves_item_transcript_and_interrupts_late_codex_turn(),])- session = await CodexSubscriptionRealtimeProvider(client=client).open_session(+ session = await _provider(client).open_session(RealtimeSessionConfig(transport_offer_sdp="v=0\r\no=offer"))@@ -764,7 +838,7 @@ async def test_done_then_handoff_cancels_synthetic_completion(monkeypatch) -> No),])- session = await CodexSubscriptionRealtimeProvider(client=client).open_session(+ session = await _provider(client).open_session(RealtimeSessionConfig(transport_offer_sdp="v=0\r\no=offer"))@@ -790,7 +864,7 @@ async def test_v3_authoritative_done_completes_without_idle_debounce(monkeypatch)])- session = await CodexSubscriptionRealtimeProvider(client=client).open_session(+ session = await _provider(client).open_session(RealtimeSessionConfig(transport_offer_sdp="v=0\r\no=offer"))@@ -807,7 +881,7 @@ async def test_normalization_queue_backpressures_and_pump_cleans_up() -> None:client = _Client()subscription = _CountingSubscription()client.subscription = subscription- session = await CodexSubscriptionRealtimeProvider(client=client).open_session(+ session = await _provider(client).open_session(RealtimeSessionConfig(transport_offer_sdp="v=0\r\no=offer"))stream = session.receive()@@ -844,7 +918,7 @@ async def test_handoff_request_never_becomes_a_direct_tool_call() -> None:),])- session = await CodexSubscriptionRealtimeProvider(client=client).open_session(+ session = await _provider(client).open_session(RealtimeSessionConfig(transport_offer_sdp="v=0\r\no=offer"))@@ -864,16 +938,16 @@ async def test_provider_error_and_app_server_death_are_normalized() -> None:)])- provider_session = await CodexSubscriptionRealtimeProvider(- client=provider_error_client- ).open_session(RealtimeSessionConfig(transport_offer_sdp="v=0\r\no=offer"))+ provider_session = await _provider(provider_error_client).open_session(+ RealtimeSessionConfig()+ )provider_events = [event async for event in provider_session.receive()]assert provider_events[0].type == "error"assert provider_events[0].recoverable is Falsedead_client = _Client(failure=RuntimeError("process exited"))- dead_session = await CodexSubscriptionRealtimeProvider(client=dead_client).open_session(- RealtimeSessionConfig(transport_offer_sdp="v=0\r\no=offer")+ dead_session = await _provider(dead_client).open_session(+ RealtimeSessionConfig())dead_events = [event async for event in dead_session.receive()]assert dead_events[0].type == "error"@@ -883,14 +957,22 @@ async def test_provider_error_and_app_server_death_are_normalized() -> None:@pytest.mark.asyncio-async def test_missing_browser_offer_fails_before_app_server_launch() -> None:+async def test_media_endpoint_failure_fails_before_app_server_launch() -> None:+ """No media path means no call: ChatGPT-Live audio IS the WebRTC track, so+ failing early beats a session that looks connected and stays mute."""client = _Client()- provider = CodexSubscriptionRealtimeProvider(client=client, offer_broker=_NoOfferBroker())- with pytest.raises(RuntimeError, match="connected UI WebRTC offer"):+ class _BrokenEndpoint(_FakeAudioEndpoint):+ async def create_offer(self) -> str:+ raise RuntimeError("no local WebRTC endpoint")++ provider = _provider(client, endpoint=_BrokenEndpoint())++ with pytest.raises(RuntimeError, match="no local WebRTC endpoint"):await provider.open_session(RealtimeSessionConfig())assert client.capability_calls == 0+ assert client.thread_starts == []@pytest.mark.asyncio@@ -912,24 +994,33 @@ async def test_broker_keeps_answered_lease_until_provider_release() -> None:@pytest.mark.asyncio-async def test_two_consecutive_native_sessions_each_consume_a_fresh_offer() -> None:- broker = RealtimeTransportOfferBroker()+async def test_each_session_negotiates_its_own_media_endpoint() -> None:+ """Every call owns a fresh peer: the answer is applied to it and the media+ path is proven live before the session is handed to the pipeline."""client = _Client()- provider = CodexSubscriptionRealtimeProvider(client=client, offer_broker=broker)+ endpoints: list[_FakeAudioEndpoint] = []++ def factory() -> _FakeAudioEndpoint:+ endpoint = _FakeAudioEndpoint()+ endpoints.append(endpoint)+ return endpoint++ provider = CodexSubscriptionRealtimeProvider(+ client=client, audio_endpoint_factory=factory+ )- for number in (1, 2):- offer_id = f"offer-{number}"- registration = await broker.register(offer_id, f"v=0\r\no=native-{number}")+ for _ in (1, 2):session = await provider.open_session(RealtimeSessionConfig())- answer = await registration.wait()- assert answer.type == "answer"await session.close()- released = await registration.wait()- assert released.type == "release"+ assert len(endpoints) == 2+ assert all(endpoint.answers == ["v=0\r\nanswer"] for endpoint in endpoints)+ assert all(endpoint.connected for endpoint in endpoints)+ assert all(endpoint.closed for endpoint in endpoints)+ # The offer the provider sent is the one its OWN peer produced.assert [kwargs["offer_sdp"] for _thread, kwargs in client.realtime_starts] == [- "v=0\r\no=native-1",- "v=0\r\no=native-2",+ "v=0\r\no=python-peer\r\n",+ "v=0\r\no=python-peer\r\n",]