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(live): cut GPT-Live wake-to-ready latency and stop dropping hidden-tab wakes

rubenluetke10-beep5526a8de16aa
diff --git a/jarvis/live/session.py b/jarvis/live/session.py
index c0828fb0ec..74c855f9a2 100644
--- a/jarvis/live/session.py
+++ b/jarvis/live/session.py
@@ -7,6 +7,7 @@ import base64
import json
import logging
import random
+import time
from typing import Any, Literal
from uuid import uuid4
@@ -135,7 +136,7 @@ class LiveVoiceSession:
return
try:
await self._send_json(message)
- except Exception: # noqa: BLE001 — indicators must not kill voice
+ except Exception: # noqa: BLE001 — indicators must not kill voice
log.debug("Live indicator frame could not be sent", exc_info=True)
async def _note_thinking(self) -> None:
@@ -189,7 +190,7 @@ class LiveVoiceSession:
elif kind == "audio_stop":
await self.end(reason="client_stop")
elif kind == "cancel_work" and self._tools is not None:
- self._tools.cancel_token.cancel("user_cancelled")
+ await self._tools.cancel_work()
elif kind == "text_input" and self._connection is not None:
text = str(message.get("text", ""))[:32000]
if self._tools is not None:
@@ -197,7 +198,8 @@ class LiveVoiceSession:
self._tools.revision += 1
if not self._recovering:
self._resume_needs_input = False
- self._tools.accepting = True
+ self._tools.accept_new_input()
+ self._reconnect_attempts = 0
preview = text.encode("utf-8")[:192].decode("utf-8", errors="ignore")
await self._connection.send(
{
@@ -229,6 +231,7 @@ class LiveVoiceSession:
async def _start(self, message: dict) -> None:
self._adopt_desktop_session()
+ started_at = time.monotonic()
profile = getattr(self._config, "live", LiveConfig())
self._active_model = profile.model
# Validate before acquiring devices, a durable store or a billed connection.
@@ -237,8 +240,21 @@ class LiveVoiceSession:
if gateway is None:
raise RuntimeError("Jarvis tools are still starting. Try voice again shortly.")
root = user_data_dir()
- await asyncio.to_thread(root.mkdir, parents=True, exist_ok=True)
- self._ledger = await asyncio.to_thread(LiveLedger, root / "live.sqlite3")
+
+ async def _open_ledger() -> LiveLedger:
+ await asyncio.to_thread(root.mkdir, parents=True, exist_ok=True)
+ return await asyncio.to_thread(LiveLedger, root / "live.sqlite3")
+
+ async def _take_permit() -> None:
+ from jarvis.live.recovery import connection_permit
+
+ await connection_permit()
+
+ # The durable store and the shared connection budget are independent:
+ # opening them concurrently keeps the permit's quarter-second budget
+ # off the wake path instead of stacked after a cold-disk sqlite open.
+ self._ledger, _ = await asyncio.gather(_open_ledger(), _take_permit())
+ setup_ms = (time.monotonic() - started_at) * 1000.0
self._tools = LiveTools(
gateway,
self._ledger,
@@ -257,16 +273,22 @@ class LiveVoiceSession:
from jarvis.live.runtime import claim
claim(self.session_id)
- from jarvis.live.recovery import connection_permit, seed_messages
+ from jarvis.live.recovery import seed_messages
self._initial_seed = self._take_initial_context()
if self._initial_seed:
config["input"] = seed_messages(self._initial_seed, [])
- await connection_permit()
+ open_started_at = time.monotonic()
self._connection = await self._provider.open_session(
ContinuousVoiceStart(session=config, offer_sdp=offer)
)
+ open_ms = (time.monotonic() - open_started_at) * 1000.0
+ log.info(
+ "Live session opening: setup %.0f ms, provider open %.0f ms.",
+ setup_ms,
+ open_ms,
+ )
if not offer:
async with asyncio.timeout(25):
while True:
@@ -427,7 +449,7 @@ class LiveVoiceSession:
self._tools.revision += 1
if not self._closing and not self._recovering:
self._resume_needs_input = False
- self._tools.accepting = True
+ self._tools.accept_new_input()
self._reconnect_attempts = 0
await self._send_json(
{
@@ -447,7 +469,7 @@ class LiveVoiceSession:
# The sideband carries this event on every transport, including
# WebRTC where the media itself travels over RTP. The binary
# forwarding below stays PCM-only, but the speaking signal must
- # reach the surfaces on both paths — otherwise the Jarvis bar
+ # reach the surfaces on both paths — otherwise the Jarvis bar
# never leaves listening while GPT-Live talks.
await self._note_speaking()
if not self._connection.answer_sdp:
@@ -531,9 +553,9 @@ class LiveVoiceSession:
self._completed.add(rid)
await self._note_turn_end()
usage = response.get("usage") or {}
- profile = getattr(self._config, "live", LiveConfig())
+ backend_model = self._tools.backend_model
await asyncio.to_thread(
- self._ledger.backend_usage, self.session_id, rid, profile.backend_model, usage
+ self._ledger.backend_usage, self.session_id, rid, backend_model, usage
)
if self._bus is not None:
from jarvis.brain.cost import calculate_cost_usd
@@ -545,13 +567,11 @@ class LiveVoiceSession:
await self._bus.publish(
BrainTurnCompleted(
provider="openai",
- model=profile.backend_model,
+ model=backend_model,
tokens_in=tokens_in,
tokens_out=tokens_out,
tokens_cached=cached,
- cost_usd=calculate_cost_usd(
- profile.backend_model, tokens_in, tokens_out, cached
- ),
+ cost_usd=calculate_cost_usd(backend_model, tokens_in, tokens_out, cached),
finish_reason="live_delegation",
)
)
diff --git a/jarvis/plugins/realtime/openai_live.py b/jarvis/plugins/realtime/openai_live.py
index f9c4eae842..a845d35360 100644
--- a/jarvis/plugins/realtime/openai_live.py
+++ b/jarvis/plugins/realtime/openai_live.py
@@ -3,9 +3,12 @@
from __future__ import annotations
import json
+import logging
from typing import Any
from urllib.parse import quote
+log = logging.getLogger(__name__)
+
class OpenAILiveConnection:
"""One primary socket or WebRTC sideband; the application owns tool execution."""
@@ -52,8 +55,41 @@ class OpenAILiveProvider:
async def can_open_duplex_session(self) -> bool:
return bool(self._api_key)
+ @staticmethod
+ async def warm_transport(cfg: Any = None) -> None:
+ """Pre-import the handshake stack and resolve the Live endpoint.
+
+ The first wake of the day paid for all of this inside the call:
+ importing httpx + websockets from a cold disk, and the DNS lookup
+ for api.openai.com on the handshake's critical path. Warming moves
+ it to the boot worker (after the voice gate, re-armed after every
+ call), so a wake word pays only the session creation itself.
+ Best-effort by contract: no socket is held, no billed call is made,
+ and any failure here only costs the latency it was meant to save.
+ """
+ del cfg # nothing session-specific about imports and DNS
+ import asyncio
+ import importlib
+
+ def _warm() -> None:
+ importlib.import_module("httpx")
+ importlib.import_module("websockets.asyncio.client")
+ try:
+ import socket
+
+ socket.getaddrinfo("api.openai.com", 443)
+ except OSError:
+ # Offline or DNS-blocked: the handshake reports it honestly.
+ pass
+
+ await asyncio.to_thread(_warm)
+
async def open_session(self, cfg: Any) -> OpenAILiveConnection:
# Imported only on an explicit call, never during boot or registration.
+ # (warm_transport pre-imports these; the import here stays as the
+ # fallback for a call that was never warmed.)
+ import time
+
import httpx
from websockets.asyncio.client import connect
@@ -67,6 +103,7 @@ class OpenAILiveProvider:
url = "wss://api.openai.com/v1/live/sessions"
if offer:
# No automatic retries: session creation is a billed mutation.
+ started_at = time.monotonic()
async with httpx.AsyncClient(timeout=25) as client:
response = await client.post(
"https://api.openai.com/v1/live/sessions",
@@ -80,6 +117,10 @@ class OpenAILiveProvider:
payload = response.json()
session_id = payload["session"]["id"]
answer = payload["transport"]["sdp"]
+ log.info(
+ "OpenAI Live session created in %.0f ms.",
+ (time.monotonic() - started_at) * 1000.0,
+ )
url += f"/{quote(session_id, safe='')}/attach"
else:
session["audio"] = {
@@ -87,9 +128,14 @@ class OpenAILiveProvider:
"format": {"type": "audio/pcm", "rate": 24000},
}
try:
+ attach_started_at = time.monotonic()
socket = await connect(
url, additional_headers=headers, open_timeout=25, max_size=8_000_000
)
+ log.info(
+ "OpenAI Live transport attached in %.0f ms.",
+ (time.monotonic() - attach_started_at) * 1000.0,
+ )
except Exception:
if session_id:
# A failed attachment must not leave the billed primary session open.
@@ -102,5 +148,10 @@ class OpenAILiveProvider:
raise
connection = OpenAILiveConnection(socket, session_id=session_id, answer_sdp=answer)
if not offer:
- await connection.send({"type": "session.start", "session": session})
+ try:
+ await connection.send({"type": "session.start", "session": session})
+ except BaseException:
+ # A failed or cancelled start still owns the newly opened socket.
+ await connection.close()
+ raise
return connection
diff --git a/jarvis/ui/web/frontend/src/components/voice/BrowserRealtimeControl.test.tsx b/jarvis/ui/web/frontend/src/components/voice/BrowserRealtimeControl.test.tsx
index 00797784b9..d462609e9a 100644
--- a/jarvis/ui/web/frontend/src/components/voice/BrowserRealtimeControl.test.tsx
+++ b/jarvis/ui/web/frontend/src/components/voice/BrowserRealtimeControl.test.tsx
@@ -98,6 +98,32 @@ describe("BrowserRealtimeControl", () => {
expect(await screen.findByRole("link", { name: "live.open_browser" })).toBeTruthy();
});
+ it("parks a wake start while hidden and fires it when the tab returns", async () => {
+ fakes.browserAudio = true;
+ const visibility = vi.spyOn(document, "visibilityState", "get").mockReturnValue("hidden");
+ try {
+ const { unmount } = render(<BrowserRealtimeControl />);
+ act(() => {
+ useEventStore.setState({ events: [{
+ id: "wake-hidden", name: "BrowserVoiceRequested", ts: Date.now(),
+ payload: { action: "start" },
+ }] });
+ });
+ await act(async () => {
+ await new Promise((resolve) => setTimeout(resolve, 20));
+ });
+ expect(fakes.connect).not.toHaveBeenCalled();
+ visibility.mockReturnValue("visible");
+ act(() => {
+ document.dispatchEvent(new Event("visibilitychange"));
+ });
+ await waitFor(() => expect(fakes.connect).toHaveBeenCalledTimes(1));
+ unmount();
+ } finally {
+ visibility.mockRestore();
+ }
+ });
+
it("is hidden in the desktop shell to prevent a second microphone", () => {
fakes.native = true;
(window as unknown as { pywebview?: unknown }).pywebview = { api: {} };
@@ -153,7 +179,7 @@ describe("BrowserRealtimeControl", () => {
});
it("shows speaking on the live tts_start frame without binary audio", async () => {
- // GPT-Live talks over WebRTC: no PCM sideband, no onAudio — the
+ // GPT-Live talks over WebRTC: no PCM sideband, no onAudio — the
// backend's explicit frame is the only speaking signal the bar gets.
render(<BrowserRealtimeControl />);
fireEvent.click(screen.getByRole("button", { name: "sidebar.realtime_start" }));
diff --git a/jarvis/ui/web/frontend/src/components/voice/BrowserRealtimeControl.tsx b/jarvis/ui/web/frontend/src/components/voice/BrowserRealtimeControl.tsx
index 1bc1306826..9fb78e72e3 100644
--- a/jarvis/ui/web/frontend/src/components/voice/BrowserRealtimeControl.tsx
+++ b/jarvis/ui/web/frontend/src/components/voice/BrowserRealtimeControl.tsx
@@ -107,6 +107,10 @@ export function BrowserRealtimeControl({ controlOnly = false }: { controlOnly?:
const clientRef = useRef<RealtimeAudioClient | null>(null);
const events = useEventStore((store) => store.events);
const handledRequest = useRef<string | null>(null);
+ // A wake that lands while the tab is hidden must not be consumed: the
+ // desktop is already waiting for this call, and dropping the request
+ // leaves it waiting out the full handshake budget for nothing.
+ const pendingStart = useRef<{ id: string; ts: number } | null>(null);
const connectionGenerationRef = useRef(0);
// A progress/preamble surface line is not the end of the turn. After the
// browser finishes speaking it, tts_end must restore thinking — not
@@ -329,14 +333,45 @@ export function BrowserRealtimeControl({ controlOnly = false }: { controlOnly?:
t,
]);
+ useEffect(() => {
+ if (!browserAudio) return;
+ const onVisible = () => {
+ const pending = pendingStart.current;
+ if (document.visibilityState !== "visible" || !pending) return;
+ if (Date.now() - pending.ts > 45_000) {
+ pendingStart.current = null;
+ return;
+ }
+ pendingStart.current = null;
+ handledRequest.current = pending.id;
+ void start();
+ };
+ document.addEventListener("visibilitychange", onVisible);
+ return () => document.removeEventListener("visibilitychange", onVisible);
+ }, [browserAudio, start]);
+
useEffect(() => {
if (!browserAudio) return;
const event = [...events].reverse().find(e => e.name === "BrowserVoiceRequested");
if (!event || event.id === handledRequest.current || Date.now() - event.ts > 45_000) return;
- handledRequest.current = event.id;
const action = (event.payload as { action?: string })?.action;
- if (action === "start" && document.visibilityState === "visible") void start();
- if (action === "stop") void stop();
+ if (action === "start") {
+ if (document.visibilityState === "visible") {
+ handledRequest.current = event.id;
+ pendingStart.current = null;
+ void start();
+ } else {
+ // Parked, not handled: firing when the tab returns keeps a
+ // background wake from dying silently on the desktop side.
+ pendingStart.current = { id: event.id, ts: event.ts };
+ }
+ return;
+ }
+ if (action === "stop") {
+ handledRequest.current = event.id;
+ pendingStart.current = null;
+ void stop();
+ }
}, [events, browserAudio, start, stop]);
useEffect(() => {
diff --git a/jarvis/ui/web/frontend/src/lib/realtimeAudio.ts b/jarvis/ui/web/frontend/src/lib/realtimeAudio.ts
index e59b99ce6b..4a768a0f37 100644
--- a/jarvis/ui/web/frontend/src/lib/realtimeAudio.ts
+++ b/jarvis/ui/web/frontend/src/lib/realtimeAudio.ts
@@ -142,7 +142,8 @@ export class RealtimeWebRtcTransport {
await waitForIceGathering(peer);
if (this.peer !== peer) return null;
const sdp = peer.localDescription?.sdp ?? offer.sdp ?? "";
- return sdp.trim() || null;
+ // SDP is a wire format: the terminal CRLF is required by Live's parser.
+ return sdp.trim() ? sdp : null;
}
async applyAnswer(sdp: string): Promise<void> {
@@ -482,10 +483,16 @@ export class RealtimeAudioClient {
if (!this.ctx.audioWorklet) {
throw new RealtimeAudioSupportError("audio_worklet_unavailable");
}
- await this.ctx.audioWorklet.addModule(pcmWorkletUrl);
- await this.ctx.resume();
-
- this.stream = await navigator.mediaDevices.getUserMedia({
+ // The worklet load, the microphone open, the one-time WS ticket and
+ // the shared connect-budget turn are independent: acquiring them
+ // concurrently keeps three disk/network waits off the wake path
+ // instead of stacked end to end. The WebRTC offer still needs the
+ // microphone stream, so it is built once the mic resolves below.
+ const setupStartedAt = performance.now();
+ const workletReady = this.ctx.audioWorklet
+ .addModule(pcmWorkletUrl)
+ .then(() => this.ctx?.resume());
+ const micReady = navigator.mediaDevices.getUserMedia({
audio: {
channelCount: { ideal: 1 },
echoCancellation: true,
@@ -493,6 +500,13 @@ export class RealtimeAudioClient {
autoGainControl: true,
},
});
+ const ticketReady = mintWsTicket();
+ const turnReady = new Promise<void>((resolve) => requestConnect(resolve));
+ this.stream = await micReady;
+ if (this.intentionalClose) throw new Error("Voice start cancelled");
+ await workletReady;
+ if (this.intentionalClose) throw new Error("Voice start cancelled");
+ const setupMs = Math.round(performance.now() - setupStartedAt);
const source = this.ctx.createMediaStreamSource(this.stream);
this.captureNode = new AudioWorkletNode(this.ctx, "pcm-capture");
this.playbackNode = new AudioWorkletNode(this.ctx, "pcm-playback");
@@ -539,8 +553,12 @@ export class RealtimeAudioClient {
// session cookie to a WS handshake (BUG-065). Minting over plain HTTP
// first works on every engine; on a mint failure (e.g. older backend)
// fall back to the cookie-only handshake, which Chromium still accepts.
- const ticket = await mintWsTicket();
- await new Promise<void>((resolve) => requestConnect(resolve));
+ // The ticket was minted concurrently with the microphone setup above,
+ // and the budget turn was queued there too, so both are (nearly) free
+ // by now instead of two more serial waits on the wake path.
+ const ticket = await ticketReady;
+ await turnReady;
+ console.info(`Voice start setup took ${setupMs} ms (mic/worklet/ticket).`);
if (this.intentionalClose) throw new Error("Voice start cancelled");
this.ws = new WebSocket(buildAudioSocketUrl(ticket));
this.ws.binaryType = "arraybuffer";
diff --git a/tests/unit/realtime/test_openai_live_warm.py b/tests/unit/realtime/test_openai_live_warm.py
new file mode 100644
index 0000000000..8aaaa33072
--- /dev/null
+++ b/tests/unit/realtime/test_openai_live_warm.py
@@ -0,0 +1,155 @@
+"""OpenAI Live wake-path latency: warmable setup must not bill a call."""
+
+from __future__ import annotations
+
+import asyncio
+import socket
+import sys
+import time
+from types import SimpleNamespace
+
+import pytest
+
+from jarvis.live.config import LiveConfig
+
+
+async def test_warm_transport_preimports_without_network(monkeypatch) -> None:
+ """First wake must not pay cold imports or DNS on the handshake path."""
+ from jarvis.plugins.realtime.openai_live import OpenAILiveProvider
+
+ for module in ("httpx", "websockets.asyncio.client"):
+ sys.modules.pop(module, None)
+ monkeypatch.setattr(
+ socket, "getaddrinfo", lambda *args, **kwargs: [("warm",)]
+ )
+ await OpenAILiveProvider.warm_transport(None)
+ assert "httpx" in sys.modules
+ assert "websockets.asyncio.client" in sys.modules
+
+
+async def test_warm_transport_survives_offline_dns(monkeypatch) -> None:
+ """Offline DNS must degrade to an unwarned call, never a failed warm."""
+ from jarvis.plugins.realtime.openai_live import OpenAILiveProvider
+
+ def _offline(*args, **kwargs):
+ raise OSError("no network")
+
+ monkeypatch.setattr(socket, "getaddrinfo", _offline)
+ await OpenAILiveProvider.warm_transport(None)
+
+
+async def test_factory_warm_reaches_openai_live(monkeypatch) -> None:
+ """The boot worker must pick up the new capability for an explicit primary."""
+ from jarvis.plugins.realtime.openai_live import OpenAILiveProvider
+ from jarvis.realtime import factory
+
+ seen: list[object] = []
+ real_warm = OpenAILiveProvider.warm_transport
+
+ async def _spy(cfg: object = None) -> None:
+ seen.append(cfg)
+ await real_warm(cfg)
+
+ monkeypatch.setattr(OpenAILiveProvider, "warm_transport", _spy)
+ monkeypatch.setattr(
+ factory, "_explicit_provider_ids", lambda _cfg: ["openai-live"]
+ )
+ monkeypatch.setattr(
+ factory, "load", lambda _group, pid, protocol=None: OpenAILiveProvider
+ )
+ cfg = SimpleNamespace(
+ voice=SimpleNamespace(mode="realtime", profile=""),
+ brain=SimpleNamespace(realtime=SimpleNamespace(provider="openai-live")),
+ )
+ monkeypatch.setattr(
+ factory, "_realtime_is_the_configured_voice_mode", lambda _cfg: True
+ )
+ await factory.realtime_warm_selected_transports(cfg)
+ assert len(seen) == 1
+
+
+async def test_start_opens_store_and_permit_concurrently(monkeypatch, tmp_path) -> None:
+ """Ledger open and the connection budget must overlap, not stack."""
+ import jarvis.live.session as module
+ from jarvis.live.recovery import connection_permit as real_permit
+ from jarvis.live.session import LiveVoiceSession
+ from jarvis.live.state import LiveLedger
+
+ events: list[tuple[str, float]] = []
+
+ async def _slow_permit() -> None:
+ events.append(("permit_start", time.monotonic()))
+ await asyncio.sleep(0.3)
+ events.append(("permit_end", time.monotonic()))
+ await real_permit()
+
+ def _slow_ledger(path):
+ events.append(("ledger_start", time.monotonic()))
+ time.sleep(0.3)
+ ledger = LiveLedger(path)
+ events.append(("ledger_end", time.monotonic()))
+ return ledger
+
+ monkeypatch.setattr(
+ module, "get_supervisor_tool_gateway", lambda: SimpleNamespace()
+ )
+ monkeypatch.setattr(module, "user_data_dir", lambda: tmp_path)
+ monkeypatch.setattr(module.LiveTools, "declarations", lambda self: [])
+ monkeypatch.setattr("jarvis.live.recovery.connection_permit", _slow_permit)
+ monkeypatch.setattr(module, "LiveLedger", _slow_ledger)
+
+ sent: list[dict] = []
+
+ async def _send_json(message: dict) -> None:
+ sent.append(message)
+
+ async def _send_binary(_data: bytes) -> None:
+ return None
+
+ class Connection:
+ answer_sdp = "answer"
+ session_id = "wire"
+
+ async def send(self, _event: dict) -> None:
+ return None
+
+ async def receive(self) -> dict:
+ await asyncio.sleep(3600)
+ return {"type": "noop"}
+
+ async def close(self) -> None:
+ return None
+
+ class Provider:
+ name = "openai-live"
+
+ async def open_session(self, _cfg):
+ return Connection()
+
+ cfg = SimpleNamespace(
+ brain=SimpleNamespace(reply_language="en"),
+ live=LiveConfig(
+ configured=True, backend_model="chosen-model", model="gpt-live-1"
+ ),
+ )
+ session = LiveVoiceSession(
+ session_id="warm-wake",
+ send_json=_send_json,
+ send_binary=_send_binary,
+ providers=[Provider()],
+ config=cfg,
+ )
+ try:
+ await session.handle_control(
+ {"type": "audio_start", "sample_rate": 48000, "webrtc_offer_sdp": "v=0"}
+ )
+ finally:
+ await session.end(reason="client_stop")
+ assert any(message.get("type") == "audio_ready" for message in sent)
+ stamp = dict(events)
+ assert stamp["permit_start"] < stamp["ledger_end"]
+ assert stamp["ledger_start"] < stamp["permit_end"]