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.

fix(realtime): let the browser honor a provider's declared start budget

rubenluetke10-beep9d2bbe8a11f0
diff --git a/jarvis/realtime/factory.py b/jarvis/realtime/factory.py
index 3d55bff688..a4672f5fde 100644
--- a/jarvis/realtime/factory.py
+++ b/jarvis/realtime/factory.py
@@ -176,6 +176,36 @@ def realtime_requires_webrtc_offer(cfg: Any) -> bool:
return False
+def realtime_handshake_budget_s(cfg: Any) -> float:
+ """Longest handshake any eligible realtime provider declares it needs.
+
+ A capability read, never a provider-id check (AP-21). ``RealtimeVoiceSession``
+ stretches its own handshake deadline to the largest declared budget; a
+ SURFACE that gives up earlier throws that away, which is exactly what made
+ cold subscription calls unreachable from the browser: the transport is
+ allowed 45 s and documents 15-25 s cold starts, while the browser client
+ called the attempt dead after 20 s.
+
+ Returns the effective ceiling — never below the shared default — so a
+ caller can use the value directly as a timeout budget.
+ """
+ from jarvis.realtime.session import _PROVIDER_HANDSHAKE_TOTAL_TIMEOUT_S
+
+ declared = [float(_PROVIDER_HANDSHAKE_TOTAL_TIMEOUT_S)]
+ for provider_id in _configured_provider_ids(cfg):
+ try:
+ provider_cls = load(_GROUP, provider_id, protocol=RealtimeProvider)
+ except Exception as exc: # noqa: BLE001 - one broken plugin is skipped
+ log.warning(
+ "Realtime handshake-budget probe failed for %s: %s", provider_id, exc
+ )
+ continue
+ if not bool(getattr(provider_cls, "supports_realtime", False)):
+ continue
+ declared.append(float(getattr(provider_cls, "handshake_budget_s", 0.0) or 0.0))
+ return max(declared)
+
+
async def realtime_warm_selected_transports(cfg: Any) -> None:
"""Let every explicitly selected provider pre-open its transport.
@@ -201,6 +231,11 @@ async def realtime_warm_selected_transports(cfg: Any) -> None:
)
+#: The ChatGPT plan is its own quota pool, not metered platform usage. It is a
+#: DISTINCT family from ``openai``: a 429 on one says nothing about the other.
+_CHATGPT_SUBSCRIPTION_FAMILY = "openai-chatgpt-subscription"
+
+
def _provider_family(provider_id: str) -> str:
"""Credential/quota family of a provider id (AP-22 diagnostics only)."""
pid = (provider_id or "").strip().lower()
@@ -217,6 +252,28 @@ def _provider_family(provider_id: str) -> str:
return aliases.get(pid, pid.split("-")[0])
+def _brain_credential_family(provider_id: str) -> str:
+ """Family a configured BRAIN id will actually bill against.
+
+ ``codex`` is two products behind one id: with an OpenAI API key it is
+ metered platform usage (family ``openai``); WITHOUT one it runs on the
+ user's ChatGPT plan — the same account and the same quota the subscription
+ realtime voice uses. Reporting ``openai`` for both is why a Codex brain
+ sitting behind a Codex subscription voice never raised the AP-22 warning,
+ even though that is the single configuration where one 429 takes down the
+ voice and every action it delegates at the same moment.
+ """
+ family = _provider_family(provider_id)
+ if family != "openai" or (provider_id or "").strip().lower() != "codex":
+ return family
+ from jarvis.core.config import PROVIDER_SECRET_CANDIDATES # noqa: PLC0415
+
+ candidates = tuple(PROVIDER_SECRET_CANDIDATES.get("codex", ()) or ())
+ if candidates and get_secret_any(candidates):
+ return "openai"
+ return _CHATGPT_SUBSCRIPTION_FAMILY
+
+
def _warn_on_same_family_delegate_chain(
cfg: Any,
realtime_provider: str,
@@ -252,7 +309,7 @@ def _warn_on_same_family_delegate_chain(
]
if not realtime_family or not chain:
return
- if all(_provider_family(entry) == realtime_family for entry in chain):
+ if all(_brain_credential_family(entry) == realtime_family for entry in chain):
log.warning(
"AP-22: the realtime provider %r and EVERY configured brain "
"provider (%s) share the %r credential family — one quota or "
@@ -323,6 +380,7 @@ def build_realtime_session(
__all__ = [
"build_realtime_session",
"realtime_available_provider",
+ "realtime_handshake_budget_s",
"realtime_implicit_usage_fallback_allowed",
"realtime_requires_webrtc_offer",
]
diff --git a/jarvis/realtime/webrtc_transport.py b/jarvis/realtime/webrtc_transport.py
index b1fdd8c6c6..397bf974b1 100644
--- a/jarvis/realtime/webrtc_transport.py
+++ b/jarvis/realtime/webrtc_transport.py
@@ -218,6 +218,7 @@ class RealtimeWebRtcAudioEndpoint:
)
self._reader_task: asyncio.Task[None] | None = None
self._mic_resampler = _MicResampler()
+ self._outgoing_drops = 0
self._closed = False
@self._pc.on("track")
@@ -348,7 +349,21 @@ class RealtimeWebRtcAudioEndpoint:
self._sender.queue.put_nowait(payload)
except asyncio.QueueFull:
# Drop the oldest: stale microphone audio is worse than a gap.
+ # SAY so — this queue silently deleted user speech, which reads to
+ # the user as "it ignored me" and to a log reader as a healthy call.
+ # The receive side already reports its drops; this side did not.
with_suppress_get(self._sender.queue)
+ self._outgoing_drops += 1
+ if (
+ self._outgoing_drops == 1
+ or self._outgoing_drops % _DROP_LOG_EVERY == 0
+ ):
+ log.warning(
+ "Realtime WebRTC send queue is full — dropped %d outgoing "
+ "microphone frame(s); the far end is not draining audio at "
+ "wall clock",
+ self._outgoing_drops,
+ )
try:
self._sender.queue.put_nowait(payload)
except asyncio.QueueFull: # noqa: S110 - a full queue after a drop means the peer is gone
diff --git a/jarvis/ui/web/frontend/src/components/voice/BrowserRealtimeControl.tsx b/jarvis/ui/web/frontend/src/components/voice/BrowserRealtimeControl.tsx
index ac1e0f50aa..23242af7b0 100644
--- a/jarvis/ui/web/frontend/src/components/voice/BrowserRealtimeControl.tsx
+++ b/jarvis/ui/web/frontend/src/components/voice/BrowserRealtimeControl.tsx
@@ -75,7 +75,8 @@ export function waveformPhase(
export function BrowserRealtimeControl() {
const t = useT();
const capabilities = useCapabilities();
- const { mode, realtimeAvailable, requiresWebRtcOffer } = useVoiceMode();
+ const { mode, realtimeAvailable, requiresWebRtcOffer, startBudgetMs } =
+ useVoiceMode();
const setVoice = useEventStore((store) => store.setVoice);
const setTranscription = useEventStore((store) => store.setTranscription);
const voiceState = useEventStore((store) => store.voiceState);
@@ -195,7 +196,7 @@ export function BrowserRealtimeControl() {
}
},
},
- { requiresWebRtcOffer },
+ { requiresWebRtcOffer, startBudgetMs },
);
clientRef.current = client;
try {
@@ -222,6 +223,7 @@ export function BrowserRealtimeControl() {
requiresWebRtcOffer,
setTranscription,
setVoice,
+ startBudgetMs,
state,
stop,
supportMessage,
diff --git a/jarvis/ui/web/frontend/src/hooks/useVoiceMode.ts b/jarvis/ui/web/frontend/src/hooks/useVoiceMode.ts
index 563d35a03e..157370e089 100644
--- a/jarvis/ui/web/frontend/src/hooks/useVoiceMode.ts
+++ b/jarvis/ui/web/frontend/src/hooks/useVoiceMode.ts
@@ -7,6 +7,8 @@ type VoiceModeResp = {
mode: string;
realtime_available: boolean;
requires_webrtc_offer: boolean;
+ /** Longest handshake any eligible realtime provider declares it needs. */
+ handshake_budget_s?: number;
active_provider: string | null;
// Sidebar-footer display fields: pretty provider name + the model an idle
// realtime session would use (configured pin or catalog default).
@@ -23,6 +25,14 @@ type VoiceModeResp = {
const REALTIME_DISCOVERY_RETRY_WINDOW_MS = 5 * 60_000;
const REALTIME_DISCOVERY_RETRY_MAX_MS = 10_000;
+/** Historical surface budget for one realtime start attempt.
+ *
+ * Kept as the floor so an older backend (or a failed capability probe) behaves
+ * exactly as before. A provider that declares it needs LONGER raises it — the
+ * subscription transport declares 45 s and documents 15-25 s cold starts, and
+ * the fixed 20 s used to report those legitimate negotiations as timeouts.
+ */
+const REALTIME_START_BUDGET_FLOOR_MS = 20_000;
export function useVoiceMode() {
const qc = useQueryClient();
@@ -121,6 +131,10 @@ export function useVoiceMode() {
mode: q.data?.mode ?? "pipeline",
realtimeAvailable: q.data?.realtime_available ?? false,
requiresWebRtcOffer: q.data?.requires_webrtc_offer ?? false,
+ startBudgetMs: Math.max(
+ REALTIME_START_BUDGET_FLOOR_MS,
+ Math.round((q.data?.handshake_budget_s ?? 0) * 1000),
+ ),
// Distinguishes "the server SAID no realtime key" from "we never heard
// back" (timeout/loading). Without it a failed status fetch showed the
// false claim "Realtime needs provider setup" and looked like a locked
diff --git a/jarvis/ui/web/frontend/src/lib/realtimeAudio.test.ts b/jarvis/ui/web/frontend/src/lib/realtimeAudio.test.ts
index 3980d1f134..5a80fc55d9 100644
--- a/jarvis/ui/web/frontend/src/lib/realtimeAudio.test.ts
+++ b/jarvis/ui/web/frontend/src/lib/realtimeAudio.test.ts
@@ -16,9 +16,14 @@ class FakePort {
}
class FakeAudioNode {
+ static instances: FakeAudioNode[] = [];
port = new FakePort();
connect = vi.fn(() => this);
disconnect = vi.fn();
+
+ constructor() {
+ FakeAudioNode.instances.push(this);
+ }
}
class FakeAudioContext {
@@ -118,6 +123,7 @@ describe("realtime audio client", () => {
});
FakePeerConnection.instances = [];
FakeWebSocket.instances = [];
+ FakeAudioNode.instances = [];
wsFakes.mintWsTicket.mockClear();
});
@@ -223,6 +229,52 @@ describe("realtime audio client", () => {
expect(track.stop).toHaveBeenCalledOnce();
});
+ it("replays the opening spoken during a slow subscription start", async () => {
+ // A cold subscription transport spends 15-25 s coming up. Captured PCM was
+ // DISCARDED for that whole window, so the user's first sentence vanished —
+ // and because that transport drives its own turn detection, nothing ever
+ // asked for a repeat. The desktop already retains and replays the opening.
+ installVoiceBrowserFakes();
+ const client = new RealtimeAudioClient({}, { startBudgetMs: 45_000 });
+ const connecting = client.connect();
+
+ await vi.waitFor(() => expect(FakeWebSocket.instances).toHaveLength(1));
+ const socket = FakeWebSocket.instances[0];
+ socket.open();
+
+ const capture = FakeAudioNode.instances.find((node) => node.port.onmessage);
+ expect(capture).toBeDefined();
+ const opening = new Uint8Array([1, 2, 3, 4]).buffer;
+ capture!.port.onmessage!({ data: opening } as MessageEvent);
+
+ const binaries = () => socket.sent.filter((item) => item instanceof ArrayBuffer);
+ expect(binaries()).toHaveLength(0);
+
+ socket.receive({ type: "audio_ready", output_sample_rate: 24_000 });
+ await connecting;
+
+ expect(binaries()).toEqual([opening]);
+ await client.disconnect();
+ });
+
+ it("drops a retained opening that never reached a ready socket", async () => {
+ installVoiceBrowserFakes();
+ const client = new RealtimeAudioClient({}, {});
+ const connecting = client.connect();
+
+ await vi.waitFor(() => expect(FakeWebSocket.instances).toHaveLength(1));
+ const socket = FakeWebSocket.instances[0];
+ socket.open();
+ const capture = FakeAudioNode.instances.find((node) => node.port.onmessage);
+ capture!.port.onmessage!({ data: new Uint8Array([9]).buffer } as MessageEvent);
+
+ socket.close();
+ await expect(connecting).rejects.toBeInstanceOf(Error);
+ await client.disconnect();
+
+ expect(socket.sent.filter((item) => item instanceof ArrayBuffer)).toHaveLength(0);
+ });
+
it("keeps RTP detached and plays scrubbed subscription sideband PCM", async () => {
const createAudio = vi.fn();
vi.stubGlobal("Audio", createAudio);
diff --git a/jarvis/ui/web/frontend/src/lib/realtimeAudio.ts b/jarvis/ui/web/frontend/src/lib/realtimeAudio.ts
index f53d31b4b4..b590c89687 100644
--- a/jarvis/ui/web/frontend/src/lib/realtimeAudio.ts
+++ b/jarvis/ui/web/frontend/src/lib/realtimeAudio.ts
@@ -25,8 +25,32 @@ export type RealtimeCallbacks = {
export type RealtimeAudioOptions = {
/** The active provider needs a WebRTC offer to open its subscription transport. */
requiresWebRtcOffer?: boolean;
+ /**
+ * How long one start attempt may take before the surface calls it dead.
+ *
+ * Comes from the backend's declared provider capability, never from a
+ * provider name. Omitted (older backend, failed probe) keeps the historical
+ * fixed budget.
+ */
+ startBudgetMs?: number;
};
+/** Historical fixed budget for one realtime start attempt. */
+const DEFAULT_START_BUDGET_MS = 20_000;
+
+/** Bounded startup pre-roll, mirroring the desktop's 30 s replay window.
+ *
+ * Captured microphone PCM used to be DISCARDED until the backend answered
+ * `audio_ready`. On a cold subscription transport that window is 15-25 s, so
+ * whatever the user said first was simply gone — and because that transport
+ * generates its responses from its own turn detection, nothing ever asked for
+ * a repeat. Retaining the opening in order and replaying it once the socket
+ * accepts audio gives the browser the same contract the desktop already has.
+ * The cap is per-connection and drops the OLDEST frames, so a forgotten open
+ * tab cannot grow memory without bound.
+ */
+const MAX_STARTUP_PREROLL_BYTES = 48_000 * 2 * 30; // 30 s of mono PCM16 @48 kHz
+
export type BrowserSpeechOutcome = "ended" | "error" | "unavailable";
export type BrowserRealtimeSupportIssue =
@@ -276,6 +300,8 @@ export class RealtimeAudioClient {
private browserSpeech = new BrowserSpeechFallback();
private webRtcTransport: RealtimeWebRtcTransport;
private webRtcOfferSdp: string | null = null;
+ private startupPreroll: ArrayBuffer[] = [];
+ private startupPrerollBytes = 0;
constructor(
private cb: RealtimeCallbacks = {},
@@ -371,6 +397,8 @@ export class RealtimeAudioClient {
if (data instanceof ArrayBuffer) {
if (this.ready && this.ws?.readyState === WebSocket.OPEN) {
this.ws.send(data);
+ } else if (!this.ready) {
+ this.retainStartupFrame(data);
}
return;
}
@@ -387,13 +415,22 @@ export class RealtimeAudioClient {
}
private waitUntilReady(socket: WebSocket): Promise<void> {
+ // Never shorter than the historical budget, and long enough for whatever
+ // the active provider chain declared it needs. A cold subscription
+ // transport spends 15-25 s spawning its app-server, verifying the live
+ // account and negotiating WebRTC; giving up at a fixed 20 s reported that
+ // legitimate negotiation to the user as a failed connection.
+ const budgetMs = Math.max(
+ DEFAULT_START_BUDGET_MS,
+ Math.round(this.options.startBudgetMs ?? 0),
+ );
return new Promise((resolve, reject) => {
let settled = false;
const timeout = window.setTimeout(() => {
if (settled) return;
settled = true;
reject(new Error("Realtime voice connection timed out"));
- }, 20_000);
+ }, budgetMs);
const fail = (error: Error) => {
if (!settled) {
@@ -449,6 +486,7 @@ export class RealtimeAudioClient {
void this.finishAudioReady(message)
.then(() => {
this.ready = true;
+ this.flushStartupPreroll();
if (!settled) {
settled = true;
window.clearTimeout(timeout);
@@ -477,6 +515,30 @@ export class RealtimeAudioClient {
});
}
+ /** Retain one captured frame while the transport is still negotiating. */
+ private retainStartupFrame(frame: ArrayBuffer): void {
+ this.startupPreroll.push(frame);
+ this.startupPrerollBytes += frame.byteLength;
+ while (
+ this.startupPreroll.length > 1 &&
+ this.startupPrerollBytes > MAX_STARTUP_PREROLL_BYTES
+ ) {
+ const dropped = this.startupPreroll.shift();
+ this.startupPrerollBytes -= dropped?.byteLength ?? 0;
+ }
+ }
+
+ /** Replay the retained opening once the socket accepts audio. */
+ private flushStartupPreroll(): void {
+ const retained = this.startupPreroll;
+ this.startupPreroll = [];
+ this.startupPrerollBytes = 0;
+ if (this.ws?.readyState !== WebSocket.OPEN) return;
+ for (const frame of retained) {
+ this.ws.send(frame);
+ }
+ }
+
private async finishAudioReady(message: RealtimeStatusPayload): Promise<void> {
const answer = message.webrtc_answer_sdp;
const answerRequired =
@@ -557,6 +619,10 @@ export class RealtimeAudioClient {
const socket = this.ws;
this.ws = null;
this.ready = false;
+ // A start that never reached `audio_ready` must not carry its retained
+ // opening into the next connection attempt.
+ this.startupPreroll = [];
+ this.startupPrerollBytes = 0;
if (sendStop && socket?.readyState === WebSocket.OPEN) {
try {
socket.send(JSON.stringify({ type: "audio_stop" }));
diff --git a/jarvis/ui/web/settings_routes.py b/jarvis/ui/web/settings_routes.py
index 9dff38598b..530ceffe24 100644
--- a/jarvis/ui/web/settings_routes.py
+++ b/jarvis/ui/web/settings_routes.py
@@ -71,6 +71,32 @@ def _realtime_requires_webrtc_offer(cfg: object) -> bool:
return realtime_requires_webrtc_offer(cfg)
+#: Surface floor for the realtime start budget. Only ever RAISED by a
+#: provider's declared need — never lowered — so a browser that cannot reach
+#: the capability probe still behaves exactly as it always did.
+_REALTIME_SURFACE_HANDSHAKE_FLOOR_S = 20.0
+
+
+def _realtime_handshake_budget_s(cfg: object) -> float:
+ """Longest declared realtime handshake, or the historical surface floor.
+
+ The browser gave every start attempt a fixed 20 s. That is shorter than the
+ subscription transport's declared 45 s budget and its documented 15-25 s
+ cold start, so a cold subscription call could be reported as a timed-out
+ connection while the backend was still legitimately negotiating.
+ """
+ try:
+ from jarvis.realtime.factory import realtime_handshake_budget_s
+ except ImportError: # Optional realtime support keeps the historical floor.
+ return _REALTIME_SURFACE_HANDSHAKE_FLOOR_S
+ try:
+ declared = float(realtime_handshake_budget_s(cfg))
+ except Exception: # noqa: BLE001 — a probe failure must not break the screen
+ log.debug("Realtime handshake-budget probe failed", exc_info=True)
+ return _REALTIME_SURFACE_HANDSHAKE_FLOOR_S
+ return max(_REALTIME_SURFACE_HANDSHAKE_FLOOR_S, declared)
+
+
async def _realtime_transport_offer_ready(required: bool) -> bool | None:
"""Return desktop offer readiness, or ``None`` when no offer is required."""
if not required:
@@ -246,6 +272,9 @@ async def get_voice_mode(request: Request) -> dict[str, object]:
requires_webrtc_offer = await asyncio.to_thread(
_realtime_requires_webrtc_offer, cfg
)
+ # Capability, not a provider id (AP-21): the surface must not call a start
+ # attempt dead while the backend is still inside a budget it declared.
+ handshake_budget_s = await asyncio.to_thread(_realtime_handshake_budget_s, cfg)
transport_offer_ready = await _realtime_transport_offer_ready(
requires_webrtc_offer
)
@@ -269,6 +298,7 @@ async def get_voice_mode(request: Request) -> dict[str, object]:
"mode": mode,
"realtime_available": prov is not None,
"requires_webrtc_offer": requires_webrtc_offer,
+ "handshake_budget_s": handshake_budget_s,
"transport_offer_ready": transport_offer_ready,
"transport_offer_detail": transport_offer_detail,
"active_provider": prov,
diff --git a/tests/unit/realtime/test_factory.py b/tests/unit/realtime/test_factory.py
index 8260206078..c0aa41f859 100644
--- a/tests/unit/realtime/test_factory.py
+++ b/tests/unit/realtime/test_factory.py
@@ -378,3 +378,87 @@ async def test_warm_selected_transports_ignores_unselected_plugins(
await factory.realtime_warm_selected_transports(object())
assert warm.calls == 0
+
+
+def test_declared_handshake_budget_reaches_the_surface(monkeypatch) -> None:
+ """A surface must not call a start attempt dead inside a declared budget.
+
+ The browser gave every attempt a fixed 20 s while the subscription
+ transport declares 45 s and documents 15-25 s cold starts, so a cold
+ subscription call could be reported as a timed-out connection while the
+ backend was still legitimately negotiating.
+ """
+
+ class _SlowStart(_BaseProvider):
+ name = "codex-subscription-realtime"
+ credential_candidates = ()
+ handshake_budget_s = 45.0
+
+ @classmethod
+ def external_login_ready(cls):
+ return True
+
+ monkeypatch.setattr(factory, "list_plugins", lambda _group: ["codex-subscription-realtime"])
+ monkeypatch.setattr(factory, "load", lambda _group, _name, protocol=None: _SlowStart)
+
+ budget = factory.realtime_handshake_budget_s(
+ _cfg(provider="codex-subscription-realtime")
+ )
+
+ assert budget == 45.0
+
+
+def test_handshake_budget_never_drops_below_the_shared_default(monkeypatch) -> None:
+ """A provider that declares nothing keeps the historical ceiling."""
+ _fake_registry(monkeypatch, {"openai"})
+
+ from jarvis.realtime.session import _PROVIDER_HANDSHAKE_TOTAL_TIMEOUT_S
+
+ assert factory.realtime_handshake_budget_s(_cfg()) == pytest.approx(
+ _PROVIDER_HANDSHAKE_TOTAL_TIMEOUT_S
+ )
+
+
+def test_a_subscription_brain_behind_subscription_voice_warns(monkeypatch, caplog) -> None:
+ """AP-22: the one chain where a single 429 silences voice AND actions.
+
+ ``codex`` without an OpenAI key runs on the SAME ChatGPT plan as the
+ subscription voice. Resolving it to the generic ``openai`` family meant
+ this exact configuration never produced the warning it exists for.
+ """
+ monkeypatch.setattr(factory, "get_secret_any", lambda _candidates: None)
+ config = _cfg(provider="codex-subscription-realtime")
+ config.brain.primary = "codex"
+ config.brain.deep_brain = "codex"
+ config.brain.routing_provider = None
+ config.brain.local_fallback = None
+
+ with caplog.at_level("WARNING"):
+ factory._warn_on_same_family_delegate_chain(
+ config,
+ "codex-subscription-realtime",
+ credential_family="openai-chatgpt-subscription",
+ )
+
+ assert any("AP-22" in record.message for record in caplog.records)
+
+
+def test_a_metered_codex_brain_behind_subscription_voice_does_not_warn(
+ monkeypatch, caplog
+) -> None:
+ """With an OpenAI key the brain bills a DIFFERENT pool — no false alarm."""
+ monkeypatch.setattr(factory, "get_secret_any", lambda _candidates: "openai-key")
+ config = _cfg(provider="codex-subscription-realtime")
+ config.brain.primary = "codex"
+ config.brain.deep_brain = None
+ config.brain.routing_provider = None
+ config.brain.local_fallback = None
+
+ with caplog.at_level("WARNING"):
+ factory._warn_on_same_family_delegate_chain(
+ config,
+ "codex-subscription-realtime",
+ credential_family="openai-chatgpt-subscription",
+ )
+
+ assert not [record for record in caplog.records if "AP-22" in record.message]