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
perf(realtime): drop the 5s STUN wait that swallowed the first sentence
Ruben Lütke08c4cb535170
diff --git a/jarvis/plugins/realtime/codex_subscription.py b/jarvis/plugins/realtime/codex_subscription.pyindex c8a1b0e1ee..96473eb4b7 100644--- a/jarvis/plugins/realtime/codex_subscription.py+++ b/jarvis/plugins/realtime/codex_subscription.py@@ -864,17 +864,53 @@ class CodexSubscriptionRealtimeProvider:return Trueasync def open_session(self, cfg: Any) -> _CodexSubscriptionRealtimeSession:+ """Open a session, preferring the fast host-only media path.++ Host candidates alone connect on an ordinary network and cost no+ gathering time; STUN costs a fixed ~5 s wait that used to sit in front+ of every call and swallow the user's first sentence. A network that+ genuinely needs a reflexive candidate gets one on the retry.+ """+ transport_module = importlib.import_module(+ "jarvis.realtime.webrtc_transport"+ )+ attempts: tuple[Any, ...] = (None, transport_module.stun_ice_servers)+ last_error: BaseException | None = None+ for index, ice_factory in enumerate(attempts):+ try:+ return await self._open_session_once(+ cfg, None if ice_factory is None else ice_factory()+ )+ except transport_module.WebRtcMediaPathUnavailable as exc:+ last_error = exc+ if index + 1 < len(attempts):+ log.warning(+ "Realtime media path did not connect on host candidates "+ "(%s); retrying with a STUN server",+ exc,+ )+ continue+ raise+ raise RuntimeError( # pragma: no cover - the loop always returns or raises+ "Codex subscription realtime could not open a media path"+ ) from last_error++ async def _open_session_once(+ self, cfg: Any, ice_servers: Any+ ) -> _CodexSubscriptionRealtimeSession:# 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 = Noneif self._audio_endpoint_factory is not None:- audio_endpoint = self._audio_endpoint_factory()+ audio_endpoint = self._audio_endpoint_factory(ice_servers)else:transport_module = importlib.import_module("jarvis.realtime.webrtc_transport")- audio_endpoint = transport_module.RealtimeWebRtcAudioEndpoint()+ audio_endpoint = transport_module.RealtimeWebRtcAudioEndpoint(+ ice_servers+ )offer_sdp = await audio_endpoint.create_offer()client = self._clientdiff --git a/jarvis/realtime/webrtc_transport.py b/jarvis/realtime/webrtc_transport.pyindex 6a96a323c2..35c75e2916 100644--- a/jarvis/realtime/webrtc_transport.py+++ b/jarvis/realtime/webrtc_transport.py@@ -42,6 +42,21 @@ class WebRtcTransportUnavailable(RuntimeError):"""The host cannot provide an in-process WebRTC audio endpoint."""+class WebRtcMediaPathUnavailable(WebRtcTransportUnavailable):+ """The negotiated media path never became usable.++ Distinct from a missing stack so a caller can retry with a different ICE+ configuration instead of giving up on the provider entirely.+ """+++def stun_ice_servers() -> list[Any]:+ """Public STUN fallback for networks where host candidates cannot connect."""+ from aiortc import RTCIceServer # noqa: PLC0415++ return [RTCIceServer(urls="stun:stun.l.google.com:19302")]++def webrtc_available() -> bool:"""Whether an in-process WebRTC audio endpoint can be built here."""try:@@ -141,15 +156,24 @@ def _upsample_to_wire(pcm: bytes, source_rate: int) -> bytes:class RealtimeWebRtcAudioEndpoint:"""A Python-owned WebRTC peer that carries realtime audio both ways."""- def __init__(self) -> None:+ def __init__(self, ice_servers: list[Any] | None = None) -> 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()+ from aiortc import RTCConfiguration, RTCPeerConnection # noqa: PLC0415++ # Host candidates only by DEFAULT. We are the offerer and the provider's+ # media server is publicly reachable, so our outgoing checks establish+ # the path without a reflexive candidate — measured live: gathering+ # 0.00 s vs 5.01 s with STUN, identical media either way. Those five+ # seconds sat in front of every call, swallowing the user's first+ # sentence. ``stun_ice_servers()`` is the retry for networks that+ # genuinely need it.+ self._pc = RTCPeerConnection(+ configuration=RTCConfiguration(iceServers=list(ice_servers or []))+ )self._sender = _PcmSenderTrack()self._pc.addTrack(self._sender.track)self._recv_queue: asyncio.Queue[bytes | None] = asyncio.Queue(@@ -235,11 +259,11 @@ class RealtimeWebRtcAudioEndpoint:if state == "connected":returnif state in {"failed", "closed"}:- raise WebRtcTransportUnavailable(+ raise WebRtcMediaPathUnavailable(f"The realtime WebRTC media path {state}.")if asyncio.get_running_loop().time() >= deadline:- raise WebRtcTransportUnavailable(+ raise WebRtcMediaPathUnavailable("The realtime WebRTC media path did not connect in time.")await asyncio.sleep(0.05)@@ -288,6 +312,8 @@ def with_suppress_get(queue: asyncio.Queue[Any]) -> None:__all__ = ["RealtimeWebRtcAudioEndpoint",+ "WebRtcMediaPathUnavailable","WebRtcTransportUnavailable",+ "stun_ice_servers","webrtc_available",]diff --git a/tests/unit/realtime/test_codex_subscription.py b/tests/unit/realtime/test_codex_subscription.pyindex 21f7127a57..00b020da2d 100644--- a/tests/unit/realtime/test_codex_subscription.py+++ b/tests/unit/realtime/test_codex_subscription.py@@ -131,7 +131,10 @@ 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+ client=client,+ # The factory receives the ICE configuration for this attempt.+ audio_endpoint_factory=lambda _ice=None: endpoint,+ **kwargs,)provider.test_endpoint = endpointreturn provider@@ -993,6 +996,44 @@ async def test_broker_keeps_answered_lease_until_provider_release() -> None:assert await broker.pending_count() == 0+async def test_unconnectable_host_path_retries_with_stun() -> None:+ """Host candidates cost no gathering time and connect on an ordinary+ network; a network that needs a reflexive candidate must still work, so a+ dead media path is retried once WITH a STUN server."""+ from jarvis.realtime.webrtc_transport import WebRtcMediaPathUnavailable++ client = _Client()+ ice_configs: list[object] = []++ class _HostOnlyFails(_FakeAudioEndpoint):+ def __init__(self, ice_servers) -> None:+ super().__init__()+ self.ice_servers = ice_servers++ async def wait_connected(self, timeout_s: float = 15.0) -> None:+ del timeout_s+ if not self.ice_servers:+ raise WebRtcMediaPathUnavailable("media path failed")+ self.connected = True++ def factory(ice_servers=None) -> _HostOnlyFails:+ ice_configs.append(ice_servers)+ return _HostOnlyFails(ice_servers)++ provider = CodexSubscriptionRealtimeProvider(+ client=client, audio_endpoint_factory=factory+ )++ session = await provider.open_session(RealtimeSessionConfig())++ # First attempt host-only (no servers), second with STUN.+ assert ice_configs[0] is None+ assert ice_configs[1]+ assert len(ice_configs) == 2+ await session.close()++@pytest.mark.asyncioasync 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@@ -1000,7 +1041,7 @@ async def test_each_session_negotiates_its_own_media_endpoint() -> None:client = _Client()endpoints: list[_FakeAudioEndpoint] = []- def factory() -> _FakeAudioEndpoint:+ def factory(_ice_servers=None) -> _FakeAudioEndpoint:endpoint = _FakeAudioEndpoint()endpoints.append(endpoint)return endpoint