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.

perf(realtime): remember the STUN media path across opens

rubenluetke10-beep8c3633deddcb
diff --git a/jarvis/plugins/realtime/codex_subscription.py b/jarvis/plugins/realtime/codex_subscription.py
index d23794527a..61b8d5cebf 100644
--- a/jarvis/plugins/realtime/codex_subscription.py
+++ b/jarvis/plugins/realtime/codex_subscription.py
@@ -85,6 +85,11 @@ _REJECTED_RESPONSE_MAX_S = 2.0
_NORMALIZATION_QUEUE_MAX = 128
_REMOTE_CLEANUP_TIMEOUT_S = 1.5
_TURN_INTERRUPT_TIMEOUT_S = 1.5
+# Key for the app-server's per-host STUN media-path memory. The WebRTC media
+# path runs from THIS machine to ChatGPT-Live, so whether STUN is needed is
+# decided by the local NAT, not by any configurable remote host — one
+# process-scoped key is the honest granularity.
+_MEDIA_PATH_MEMORY_KEY = "chatgpt-live"
# 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
@@ -3145,7 +3150,20 @@ class CodexSubscriptionRealtimeProvider:
genuinely needs a reflexive candidate gets one on the retry.
"""
transport_module = importlib.import_module("jarvis.realtime.webrtc_transport")
+ app_server_module = importlib.import_module("jarvis.codex_app_server")
+ # STUN need is a property of the LOCAL network path to ChatGPT-Live,
+ # not of a configurable remote host, so the process-scoped memory is
+ # keyed by a constant. When the last successful connect needed a
+ # reflexive candidate, start with STUN directly: on such a network the
+ # host-only attempt is doomed and costs a full second open (thread_start
+ # bundle included). The memory is an optimization, never a gate — an
+ # unknown or expired entry restores host-candidates-first.
attempts: tuple[Any, ...] = (None, transport_module.stun_ice_servers)
+ try:
+ if app_server_module.media_path_prefers_stun(_MEDIA_PATH_MEMORY_KEY):
+ attempts = (transport_module.stun_ice_servers, None)
+ except Exception: # noqa: BLE001 - the memory must never block an open
+ log.debug("STUN media-path memory probe failed", exc_info=True)
last_error: BaseException | None = None
# Built and primed ONCE for both attempts: the recognizer is pure
# local state, and rebuilding + re-warming it on the STUN retry paid
@@ -3172,9 +3190,20 @@ class CodexSubscriptionRealtimeProvider:
)
if index > 0:
# Postmortem marker: this call paid the full re-open (a
- # second thread_start bundle included) to reach STUN.
+ # second thread_start bundle included) to switch the
+ # media path (host-only -> STUN, or the reverse when
+ # the STUN memory reordered the attempts).
session._diag["stun_retries"] = index
log.info("RT-SPAWN stun_retry=%d", index)
+ try:
+ app_server_module.record_media_path_outcome(
+ _MEDIA_PATH_MEMORY_KEY,
+ needed_stun=ice_factory is not None,
+ )
+ except Exception: # noqa: BLE001 - memory is best-effort
+ log.debug(
+ "STUN media-path memory record failed", exc_info=True
+ )
return session
except transport_module.WebRtcMediaPathUnavailable as exc:
last_error = exc
diff --git a/tests/unit/realtime/test_codex_subscription.py b/tests/unit/realtime/test_codex_subscription.py
index 576ca76e1d..1aa780f1fe 100644
--- a/tests/unit/realtime/test_codex_subscription.py
+++ b/tests/unit/realtime/test_codex_subscription.py
@@ -1321,6 +1321,18 @@ async def test_broker_keeps_answered_lease_until_provider_release() -> None:
assert await broker.pending_count() == 0
[email protected](autouse=True)
+def _isolated_stun_media_path_memory():
+ """The STUN media-path memory is process-global; tests must not leak it."""
+ from jarvis import codex_app_server
+
+ with codex_app_server._stun_media_path_lock:
+ codex_app_server._stun_media_path_memory.clear()
+ yield
+ with codex_app_server._stun_media_path_lock:
+ codex_app_server._stun_media_path_memory.clear()
+
+
@pytest.mark.asyncio
async def test_unconnectable_host_path_retries_with_stun(
monkeypatch: pytest.MonkeyPatch,
@@ -1362,6 +1374,43 @@ async def test_unconnectable_host_path_retries_with_stun(
await session.close()
+async def test_stun_memory_starts_with_stun_and_host_success_clears_it(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """A network that needed STUN last time skips the doomed host-only attempt;
+ a later successful host-only connect forgets the preference again."""
+ from jarvis import codex_app_server
+ from jarvis.realtime import webrtc_transport
+
+ monkeypatch.setattr(webrtc_transport, "stun_ice_servers", lambda: ["stun"])
+
+ client = _Client()
+ ice_configs: list[object] = []
+
+ def factory(ice_servers=None) -> _FakeAudioEndpoint:
+ ice_configs.append(ice_servers)
+ return _FakeAudioEndpoint()
+
+ provider = CodexSubscriptionRealtimeProvider(client=client, audio_endpoint_factory=factory)
+
+ codex_app_server.record_media_path_outcome("chatgpt-live", needed_stun=True)
+ session = await provider.open_session(RealtimeSessionConfig())
+ await session.close()
+ # STUN went FIRST and succeeded in a single attempt.
+ assert ice_configs == [["stun"]]
+ # The successful STUN connect keeps the preference armed.
+ assert codex_app_server.media_path_prefers_stun("chatgpt-live")
+
+ codex_app_server.record_media_path_outcome("chatgpt-live", needed_stun=False)
+ ice_configs.clear()
+ session = await provider.open_session(RealtimeSessionConfig())
+ await session.close()
+ # Forgotten preference restores host-candidates-first.
+ assert ice_configs == [None]
+ assert not codex_app_server.media_path_prefers_stun("chatgpt-live")
+
+
@pytest.mark.asyncio
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