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(voice): stop the fraction-of-a-second holes in the middle of a spoken answer

Ruben Lütke5242cf5c3a6e
diff --git a/docs/BUGS.md b/docs/BUGS.md
index 1094b3f6a7..e47db4b4b9 100644
--- a/docs/BUGS.md
+++ b/docs/BUGS.md
@@ -7979,3 +7979,78 @@ everything that lives there, not the one thing you were thinking about. Before
redirecting one, enumerate what else resolves from that directory — and when the
answer is "the user's whole setup", carry it across explicitly instead of
discovering the loss one setting at a time.
+
+## BUG-115: Jarvis pauses for a fraction of a second mid-sentence, then speaks on (MEDIUM, FIXED 2026-07-27)
+
+**Symptom (desktop field report).** "When you talk to Jarvis there are
+sometimes pauses of 0.2 or 0.5 seconds in the middle of a sentence, then he
+carries on." Intermittent, never reproducible on demand, no error anywhere.
+
+**Root cause — one buffer, three different producers of a gap.** The realtime
+voice path fed a device stream opened with a 200 ms PortAudio buffer, and that
+buffer was the ONLY thing between a hiccup and silence. The app already
+attributed its own holes: `RealtimeSession._note_audio_flow` logs every
+mid-reply gap with a cause, and the 2026-07-26/27 logs name all three —
+
+- **this process stalled its own event loop** (5 events, 311-375 ms): "the
+ audio likely sat unread in the socket, not missing from the provider". A PTY
+ spawn storm from the Agentic IDE, synchronous CLI auth probes behind the
+ provider panels, embedding work. While the loop is stalled NOTHING can move
+ audio, so only what is already inside PortAudio keeps playing — 200 ms of it;
+- **the provider delivered no audio** (3 events, 405-686 ms): gemini-live
+ bursts and then goes quiet while it generates the next span. Nothing was
+ banked to bridge it, because the writer is throttled to one buffer ahead;
+- **the provider rendered its own pause as silent PCM** (many, 400-800 ms) —
+ a genuine generation pause inside the audio, not a hole in delivery, and the
+ one of the three that is the model speaking rather than Jarvis failing.
+
+Every one of the first two exceeded 200 ms, so every one of them was audible.
+The earlier de-click (2026-07-21) had smoothed the EDGES of these gaps without
+touching what produced them.
+
+**Fix — give the gap something to eat, at both levels.**
+
+- `jarvis/audio/player.py` — `DEFAULT_OUTPUT_BUFFER_S = 0.4`: the reserved
+ device buffer now outlasts the worst measured event-loop stall. This is the
+ only layer that helps there, because audio banked in an asyncio queue still
+ needs the stalled loop to reach the device. It costs nothing elsewhere:
+ barge-in's `Pa_AbortStream` discards the buffer, so a deeper one never speaks
+ past an interruption; the realtime echo guard already reads the stream's
+ REPORTED latency instead of assuming a value; and a deeper buffer bounds only
+ how far AHEAD the writer may run — it does not pre-fill, so the first word
+ still starts on the first write.
+- The feed-dry de-click window is derived from that buffer instead of being
+ fixed at 80 ms. Ramping the waveform down while the device still holds 400 ms
+ would carve a dip out of speech that was never going to break — with a deep
+ buffer, ordinary network jitter is exactly that case.
+- `jarvis/realtime/desktop.py` — a jitter buffer (`DEFAULT_PREBUFFER_MS = 180`)
+ banks the opening of each turn before playback starts, so a provider that
+ goes quiet mid-reply eats a reserve rather than the speaker. Bounded twice
+ over — by `prebuffer_timeout_ms` and by the end-of-turn sentinel — so a short
+ reply is never held back and the first word is delayed by at most the
+ timeout.
+- `jarvis/ui/web/{provider_routes,antigravity_routes,server}.py` — the Codex
+ and Google CLI auth probes now run in a worker thread. Each one SPAWNS the
+ CLI binary; on the event loop, one poll from an open provider panel was a
+ few hundred milliseconds of frozen process. `list_providers` and the Claude
+ probe had already been moved off the loop for the same reason; these were
+ the ones left behind.
+
+**Regression guard.** `tests/unit/audio/test_player_output_buffer.py` — the
+reserved buffer outlasts the measured stall, a requested depth is clamped to an
+audible range, the stall window scales with the buffer, a gap the buffer
+absorbs reaches the device byte-identical, and a gap past the window is still
+de-clicked. `tests/unit/realtime/test_desktop.py` — playback waits for the
+reserve, order and content survive it, a short reply is released by the
+sentinel, and the wait is bounded by its timeout.
+`tests/unit/web/test_cli_auth_probes_off_the_event_loop.py` — a structural walk
+of the route modules that fails on any `async def` reaching a blocking CLI probe
+inline, which is what regresses the next time a provider CLI is added.
+
+**Class rule.** While audio is streaming, the event loop is a real-time
+deadline: anything blocking on it is heard. A buffer sized for a device's own
+jitter is not sized for the process that feeds it — pick the depth from the
+worst stall the process actually produces, and measure that instead of assuming
+the remote end is at fault. What the third cause shows is the other half of the
+rule: log an attributable cause at the boundary, or an intermittent gap stays
+unfalsifiable forever.
diff --git a/jarvis/audio/player.py b/jarvis/audio/player.py
index 3af0039293..74d5031199 100644
--- a/jarvis/audio/player.py
+++ b/jarvis/audio/player.py
@@ -45,21 +45,69 @@ _PortAudioError: type[BaseException] = sd.PortAudioError if sd is not None else
TTS_SAMPLE_RATE = 24_000 # Gemini 3.1 Flash TTS output rate
TTS_WRITE_BUFFER_MS = 120
_MAX_REPORTED_OUTPUT_LATENCY_S = 5.0
+
+# How much audio the OUTPUT DEVICE is asked to hold (PortAudio's ``latency``).
+#
+# This buffer is the only thing that keeps speech continuous while NOTHING in
+# this process is able to move audio: during an event-loop stall the playback
+# task cannot run, so whatever already sits inside PortAudio is all that will
+# be heard. Audio banked in an asyncio queue does not help there — moving it
+# needs the very loop that is stalled.
+#
+# Live forensic 2026-07-27 (realtime voice, gemini-live): mid-reply holes of
+# 400-800 ms, attributed by ``RealtimeSession._note_audio_flow``. Half of them
+# read "this process's event loop stalled 311-375 ms in the same window" — a
+# PTY spawn storm from the Agentic IDE, synchronous CLI auth probes, embedding
+# work. Against the previous 200 ms buffer every one of those stalls became an
+# audible pause mid-sentence.
+#
+# 400 ms covers the measured stalls with margin and costs nothing elsewhere:
+# barge-in calls ``stop()``, whose ``Pa_AbortStream`` DISCARDS the buffer (so a
+# deeper buffer never speaks past an interruption); the realtime echo guard
+# reads the stream's REPORTED latency instead of assuming a value; and a
+# deeper buffer only bounds how far AHEAD the writer may run — it does not
+# pre-fill, so the first word still starts on the first write.
+DEFAULT_OUTPUT_BUFFER_S = 0.4
+# Below ~100 ms USB headsets underrun (Wave-2 diagnosis 2026-05-16); above 2 s
+# the UI's speaking animation would visibly lead the voice, because the level
+# tap is fed at write time rather than at playout time.
+_MIN_OUTPUT_BUFFER_S = 0.1
+_MAX_OUTPUT_BUFFER_S = 2.0
# Feed-dry stall de-click (live forensic 2026-07-21 08:40: the realtime
# provider paused audio delivery 1850 ms mid-sentence; the device buffer
# drained and PortAudio cut the waveform at speech amplitude — audible as a
# choppy mid-sentence pause with a click/crackle at both edges). The missing
# audio cannot be conjured locally, but the gap's EDGES can be smoothed:
-# when the chunk feed stays dry longer than FEED_STALL_FADE_S, append a
+# when the chunk feed stays dry longer than the stall window, append a
# short ramp from the last written sample down to zero, and ramp the first
-# resumed block back in. The timeout must undercut the device-buffer drain
-# (a completed 120 ms write leaves at least ~that much buffered), so the
-# ramp reaches PortAudio before the buffer runs empty; a healthy burst-fed
+# resumed block back in. The window must undercut the device-buffer drain so
+# the ramp reaches PortAudio before the buffer runs empty; a healthy burst-fed
# stream never waits this long between chunks.
+#
+# It is derived from the ACTIVE device buffer (``_feed_stall_window_s``), not
+# fixed: ramping while the device still holds hundreds of milliseconds would
+# insert an audible dip into speech that was never going to break. This floor
+# applies to a shallow buffer; a deeper one waits proportionally longer.
FEED_STALL_FADE_S = 0.08
+# Headroom left between the stall window and the device-buffer drain: one
+# ``TTS_WRITE_BUFFER_MS`` batch, which is what a flush has to push through.
+_STALL_FADE_HEADROOM_S = TTS_WRITE_BUFFER_MS / 1000.0
STALL_EDGE_FADE_MS = 12.0
+def _clamp_output_buffer_s(value: float | None) -> float:
+ """Bound a requested output-buffer depth to a safe, audible range."""
+ if value is None:
+ return DEFAULT_OUTPUT_BUFFER_S
+ try:
+ seconds = float(value)
+ except (TypeError, ValueError):
+ return DEFAULT_OUTPUT_BUFFER_S
+ if not math.isfinite(seconds):
+ return DEFAULT_OUTPUT_BUFFER_S
+ return min(_MAX_OUTPUT_BUFFER_S, max(_MIN_OUTPUT_BUFFER_S, seconds))
+
+
class _PlaybackSuperseded(RuntimeError):
"""A stopped playback attempted to acquire a new output stream."""
@@ -414,6 +462,7 @@ class AudioPlayer:
bus: Any = None,
volume: float = 1.0,
device_priority: Sequence[str] | None = None,
+ buffer_s: float | None = None,
) -> None:
# User-configured device-name priority ([audio].output_device_priority).
# Consulted BEFORE the generic _HEADSET_PRIORITY default when resolving
@@ -431,6 +480,10 @@ class AudioPlayer:
# boost + soft limiter so 100% is a real loudness lift, not just unity.
# Clamped so a stray config/runtime value can never invert or over-range.
self._volume = clamp_volume(volume)
+ # How deep the device buffer is opened. See DEFAULT_OUTPUT_BUFFER_S:
+ # it is the process's only defense against an event-loop stall eating
+ # a hole out of the middle of a spoken answer.
+ self._output_buffer_s = _clamp_output_buffer_s(buffer_s)
self._device_logged = False # logged once on the first play call
# Optional bus reference. When set, play_chunks() publishes
# AudioOutFirst on the first audible sample so UI subscribers
@@ -520,6 +573,29 @@ class AudioPlayer:
self._stream_state_lock = lock
return lock
+ def _output_buffer_seconds(self) -> float:
+ """Device-buffer depth this player opens streams with.
+
+ ``getattr`` default: ``__new__``-built instances (test fixtures,
+ hot-reload) skip ``__init__`` and must still open a stream.
+ """
+ return _clamp_output_buffer_s(
+ getattr(self, "_output_buffer_s", DEFAULT_OUTPUT_BUFFER_S)
+ )
+
+ def _feed_stall_window_s(self) -> float:
+ """How long a dry chunk feed may last before the gap is de-clicked.
+
+ Scales with the device buffer: ramping the waveform down while the
+ device still holds hundreds of milliseconds would carve an audible dip
+ out of speech that was never going to break. One write batch of
+ headroom is kept so the ramp still reaches PortAudio in time.
+ """
+ return max(
+ FEED_STALL_FADE_S,
+ self._output_buffer_seconds() - _STALL_FADE_HEADROOM_S,
+ )
+
@property
def output_latency_s(self) -> float:
"""Return the active device's bounded PortAudio output latency.
@@ -718,14 +794,15 @@ class AudioPlayer:
last_exc: BaseException | None = None
for target_rate in candidates:
try:
- # latency=0.2 reserves a real 200 ms PortAudio buffer.
- # The string keyword "high" is a DEVICE HINT — on USB
+ # An explicit float reserves a REAL buffer of that many
+ # seconds. The string keyword "high" is a DEVICE HINT — on USB
# headsets like the AB13X it resolves to ~10 ms, far too
# small to absorb inter-sentence pipeline gaps. The Wave 2
# diagnosis on 2026-05-16 attributed audible "crackling +
- # slowdown" to this 10 ms drain. 0.2 s matches the buffer
- # depth used by LiveKit-Agents / Pipecat / RealtimeTTS for
- # TTS-streaming on WASAPI shared mode.
+ # slowdown" to this 10 ms drain. The depth itself is
+ # DEFAULT_OUTPUT_BUFFER_S — see the constant for why it has to
+ # cover this process's worst event-loop stall, not just the
+ # device's own jitter.
# Guarded against the hot-swap watcher's PortAudio re-init
# window (BUG-102): a stream born between _terminate and
# _initialize is a native fault.
@@ -736,7 +813,7 @@ class AudioPlayer:
channels=stream_channels,
dtype="float32",
blocksize=0,
- latency=0.2,
+ latency=self._output_buffer_seconds(),
)
stream.start()
self._stream_channels = stream_channels
@@ -1131,6 +1208,7 @@ class AudioPlayer:
feed = _from_first().__aiter__()
next_pull: asyncio.Task[AudioChunk] | None = None
resume_fade_in = False
+ stall_window_s = self._feed_stall_window_s()
try:
while True:
if next_pull is None:
@@ -1140,7 +1218,7 @@ class AudioPlayer:
timeout=(
None
if resume_fade_in or pending_rate is None
- else FEED_STALL_FADE_S
+ else stall_window_s
),
)
if not done:
diff --git a/jarvis/realtime/desktop.py b/jarvis/realtime/desktop.py
index 0a5d629c96..1cc944ad40 100644
--- a/jarvis/realtime/desktop.py
+++ b/jarvis/realtime/desktop.py
@@ -20,6 +20,27 @@ log = logging.getLogger("jarvis.realtime.desktop")
# Silero frames are fixed 512 samples at the 16 kHz capture rate.
_VAD_FRAME_S = VAD_FRAME_SAMPLES / 16_000.0
+# Jitter buffer: how much provider audio is banked before a turn starts playing.
+#
+# A realtime provider does not deliver its audio at a steady rate — it bursts,
+# then goes quiet while it generates the next span. ``_note_audio_flow`` logged
+# those quiet spans on 2026-07-27 as "the provider sent no audio for this span"
+# at 405-686 ms, which the device buffer alone could not cover, so the speaker
+# ran dry mid-sentence. Holding the first chunks back builds a reserve that the
+# player eats through during such a pause instead of falling silent; the reserve
+# refills on the provider's next burst.
+#
+# This is the mirror image of DEFAULT_OUTPUT_BUFFER_S in jarvis.audio.player,
+# and the two cover different failures: audio banked HERE needs the event loop
+# to reach the device, so it helps against a slow PROVIDER; audio already inside
+# PortAudio plays without this process, so that is what covers an event-loop
+# stall. Both are needed.
+DEFAULT_PREBUFFER_MS = 180
+# Ceiling on how long the reserve may be waited for, so this can only ever
+# delay the first word by this much — a provider that trickles its audio out
+# in real time starts speaking on time with whatever it has delivered.
+DEFAULT_PREBUFFER_TIMEOUT_MS = 240
+
class DesktopRealtimeBargeInDetector:
"""Detect deliberate desktop barge-in on the existing microphone stream.
@@ -436,6 +457,10 @@ class DesktopRealtimePlayback:
The bounded queue applies backpressure when an output device is slower than
the provider. A turn-complete marker drains naturally; barge-in or teardown
stops the device immediately and discards queued audio.
+
+ Each turn opens with a jitter buffer (``prebuffer_ms``) so a provider that
+ pauses mid-reply eats a reserve instead of the speaker (see
+ ``DEFAULT_PREBUFFER_MS``).
"""
def __init__(
@@ -445,11 +470,15 @@ class DesktopRealtimePlayback:
sample_rate: int = 24_000,
max_queue_chunks: int = 200,
finish_timeout_s: float = 120.0,
+ prebuffer_ms: int = DEFAULT_PREBUFFER_MS,
+ prebuffer_timeout_ms: int = DEFAULT_PREBUFFER_TIMEOUT_MS,
) -> None:
self._player = player
self._sample_rate = int(sample_rate)
self._max_queue_chunks = max(1, int(max_queue_chunks))
self._finish_timeout_s = max(1.0, float(finish_timeout_s))
+ self._prebuffer_s = max(0.0, float(prebuffer_ms) / 1000.0)
+ self._prebuffer_timeout_s = max(0.0, float(prebuffer_timeout_ms) / 1000.0)
self._queue: asyncio.Queue[AudioChunk | None] | None = None
self._task: asyncio.Task[None] | None = None
self._closed = False
@@ -578,10 +607,42 @@ class DesktopRealtimePlayback:
self._task = None
return queue, task
- @staticmethod
async def _chunks(
+ self,
queue: asyncio.Queue[AudioChunk | None],
) -> AsyncIterator[AudioChunk]:
+ """Yield the turn's audio, opening with the jitter buffer.
+
+ Nothing is dropped or reordered: the banked chunks are handed on in
+ arrival order, the reserve simply starts playback that much later so a
+ provider pause has something to eat. The wait is bounded twice over —
+ by ``prebuffer_timeout_ms`` and by the end-of-turn sentinel — so a reply
+ shorter than the reserve still plays immediately.
+ """
+ banked: list[AudioChunk] = []
+ ended = False
+ target_bytes = int(self._sample_rate * 2 * self._prebuffer_s)
+ if target_bytes > 0:
+ loop = asyncio.get_running_loop()
+ deadline = loop.time() + self._prebuffer_timeout_s
+ banked_bytes = 0
+ while banked_bytes < target_bytes:
+ remaining = deadline - loop.time()
+ if remaining <= 0:
+ break
+ try:
+ chunk = await asyncio.wait_for(queue.get(), remaining)
+ except TimeoutError:
+ break
+ if chunk is None:
+ ended = True
+ break
+ banked.append(chunk)
+ banked_bytes += len(chunk.pcm)
+ for chunk in banked:
+ yield chunk
+ if ended:
+ return
while True:
chunk = await queue.get()
if chunk is None:
diff --git a/jarvis/ui/web/antigravity_routes.py b/jarvis/ui/web/antigravity_routes.py
index b711543443..755b4dc788 100644
--- a/jarvis/ui/web/antigravity_routes.py
+++ b/jarvis/ui/web/antigravity_routes.py
@@ -45,8 +45,16 @@ def _install_hint() -> str:
@router.get("/antigravity/status")
async def antigravity_status() -> dict[str, Any]:
- """Honest snapshot of the Google CLI login (installed / connected / account)."""
- return GoogleCliAuthService().status().to_dict()
+ """Honest snapshot of the Google CLI login (installed / connected / account).
+
+ Off the event loop: the probe SPAWNS the CLI binary, which costs a few
+ hundred milliseconds. On the loop that pause froze everything else running
+ in this process — including the realtime voice socket, where it surfaced as
+ an audible hole mid-sentence (forensic 2026-07-27, see
+ ``jarvis.audio.player.DEFAULT_OUTPUT_BUFFER_S``).
+ """
+ status = await asyncio.to_thread(GoogleCliAuthService().status)
+ return status.to_dict()
@router.post("/antigravity/test")
@@ -93,10 +101,10 @@ async def antigravity_login() -> dict[str, Any]:
async def antigravity_logout() -> dict[str, Any]:
"""Disconnect the Google login (removes the on-disk creds / agy logout)."""
service = GoogleCliAuthService()
- status = service.status()
+ status = await asyncio.to_thread(service.status)
if not status.installed:
raise HTTPException(status_code=409, detail="No Google CLI found")
- ok, error = service.logout_blocking()
+ ok, error = await asyncio.to_thread(service.logout_blocking)
if not ok:
raise HTTPException(status_code=500, detail=error or "Google logout failed")
return {"ok": True, "message": "Antigravity (Google) was disconnected"}
diff --git a/jarvis/ui/web/provider_routes.py b/jarvis/ui/web/provider_routes.py
index 249bab145b..84ac71c954 100644
--- a/jarvis/ui/web/provider_routes.py
+++ b/jarvis/ui/web/provider_routes.py
@@ -2199,7 +2199,17 @@ async def realtime_voice_preview(
@router.get("/codex/status")
async def codex_status(request: Request) -> dict[str, Any]:
- return CodexAuthService(_codex_binary_path(request)).status().to_dict()
+ """Honest snapshot of the Codex CLI login.
+
+ Off the event loop: the probe SPAWNS the CLI binary, which costs a few
+ hundred milliseconds. On the loop that pause froze everything else running
+ in this process — including the realtime voice socket, where it surfaced as
+ an audible hole mid-sentence (forensic 2026-07-27, see
+ ``jarvis.audio.player.DEFAULT_OUTPUT_BUFFER_S``).
+ """
+ service = CodexAuthService(_codex_binary_path(request))
+ status = await asyncio.to_thread(service.status)
+ return status.to_dict()
@router.post("/codex/test")
@@ -2241,7 +2251,7 @@ async def codex_set_binary_path(body: CodexBinaryPathBody, request: Request) ->
@router.post("/codex/login")
async def codex_login(request: Request) -> dict[str, Any]:
service = CodexAuthService(_codex_binary_path(request))
- status = service.status()
+ status = await asyncio.to_thread(service.status)
if not status.installed:
raise HTTPException(
status_code=409,
@@ -2265,10 +2275,10 @@ async def codex_login(request: Request) -> dict[str, Any]:
@router.post("/codex/logout")
async def codex_logout(request: Request) -> dict[str, Any]:
service = CodexAuthService(_codex_binary_path(request))
- status = service.status()
+ status = await asyncio.to_thread(service.status)
if not status.installed:
raise HTTPException(status_code=409, detail="Codex CLI is not installed")
- ok, error = service.logout_blocking()
+ ok, error = await asyncio.to_thread(service.logout_blocking)
if not ok:
raise HTTPException(status_code=500, detail=error or "Codex logout failed")
return {"ok": True, "message": "Codex was disconnected"}
diff --git a/jarvis/ui/web/server.py b/jarvis/ui/web/server.py
index e6d7ebaa9e..c591c2a5a3 100644
--- a/jarvis/ui/web/server.py
+++ b/jarvis/ui/web/server.py
@@ -1113,7 +1113,13 @@ class WebServer:
codex_bin = (
getattr(getattr(cfg, "codex", None), "binary_path", "") or None
)
- codex_status = CodexAuthService(codex_bin).status()
+ # Off the event loop like the Claude probe above: it spawns the
+ # CLI binary, and on the loop that few-hundred-millisecond pause
+ # froze the realtime voice socket into an audible mid-sentence
+ # hole (forensic 2026-07-27).
+ codex_status = await asyncio.to_thread(
+ CodexAuthService(codex_bin).status
+ )
codex_connected = codex_status.connected
codex_installed = codex_status.installed
except Exception: # noqa: BLE001
@@ -1170,7 +1176,10 @@ class WebServer:
antigravity_provider_ready,
)
- antigravity_status = GoogleCliAuthService().status()
+ # Off the event loop for the same reason as the Codex probe.
+ antigravity_status = await asyncio.to_thread(
+ GoogleCliAuthService().status
+ )
antigravity_connected = (
antigravity_status.connected
and antigravity_status.mode == "oauth-personal"
diff --git a/tests/unit/audio/test_player_output_buffer.py b/tests/unit/audio/test_player_output_buffer.py
new file mode 100644
index 0000000000..3ff2f54b5c
--- /dev/null
+++ b/tests/unit/audio/test_player_output_buffer.py
@@ -0,0 +1,179 @@
+"""Device-buffer depth: the only shock absorber for an event-loop stall.
+
+Live forensic 2026-07-27 (realtime voice, gemini-live): replies came out with
+400-800 ms holes mid-sentence. ``RealtimeSession._note_audio_flow`` attributed
+half of them to "this process's event loop stalled 311-375 ms in the same
+window" — while the loop is stalled nothing can move audio, so whatever sits
+inside PortAudio is all that plays. Against the previous 200 ms buffer every
+one of those stalls became silence.
+
+These tests pin the two properties that follow from that: the reserved buffer
+must outlast a measured stall, and the feed-dry de-click must not fire while
+the device still holds plenty of audio.
+"""
+from __future__ import annotations
+
+import asyncio
+from collections.abc import AsyncIterator
+
+import numpy as np
+import pytest
+
+import jarvis.audio.player as player_module
+from jarvis.audio.player import DEFAULT_OUTPUT_BUFFER_S, AudioPlayer
+from jarvis.core.protocols import AudioChunk
+
+#: Worst event-loop stall observed in the 2026-07-27 logs. The reserved buffer
+#: has to outlast it, or the speaker runs dry before the loop comes back.
+MEASURED_WORST_LOOP_STALL_S = 0.375
+
+
+def _chunk(samples: np.ndarray, sample_rate: int = 24_000) -> AudioChunk:
+ return AudioChunk(
+ pcm=samples.astype(np.int16).tobytes(),
+ sample_rate=sample_rate,
+ timestamp_ns=0,
+ channels=1,
+ )
+
+
+def _bare_player() -> AudioPlayer:
+ """Player without ``__init__`` — mirrors the other player unit tests."""
+ player = AudioPlayer.__new__(AudioPlayer)
+ player._device = None
+ player._sample_rate = 24_000
+ player._channels = 1
+ player._device_logged = True
+ player._bus = None
+ player._play_lock = None
+ player._active_stream = None
+ player._active_source_rate = None
+ player._active_device_rate = None
+ player._device_rate_cache = {}
+ return player
+
+
+def _writing_player(monkeypatch, buffer_s: float) -> tuple[AudioPlayer, list]:
+ player = _bare_player()
+ player._output_buffer_s = buffer_s
+ written: list[np.ndarray] = []
+
+ monkeypatch.setattr(
+ player, "_open_output_stream", lambda rate: (object(), rate)
+ )
+ monkeypatch.setattr(player, "_close_output_stream", lambda stream: None)
+ monkeypatch.setattr(
+ player,
+ "_write_samples",
+ lambda stream, arr, src, dev, **_kw: written.append(
+ np.array(arr, dtype=np.int16)
+ ),
+ )
+ return player, written
+
+
+def test_reserved_buffer_outlasts_the_measured_event_loop_stall() -> None:
+ """The default buffer must survive the worst stall this process produced."""
+ assert DEFAULT_OUTPUT_BUFFER_S > MEASURED_WORST_LOOP_STALL_S, (
+ "an event-loop stall drains the device buffer with nothing able to "
+ "refill it, so a buffer shallower than the measured stall is an "
+ "audible hole in the middle of a spoken answer"
+ )
+
+
+def test_open_output_stream_reserves_the_configured_buffer(monkeypatch) -> None:
+ player = _bare_player()
+ player._output_buffer_s = 0.4
+ captured: dict = {}
+
+ class FakeStream:
+ latency = 0.4
+
+ def start(self) -> None:
+ pass
+
+ def fake_outputstream(**kw):
+ captured.update(kw)
+ return FakeStream()
+
+ monkeypatch.setattr(
+ player_module.sd, "query_devices", lambda d: {"default_samplerate": 48_000}
+ )
+ monkeypatch.setattr(player_module.sd, "OutputStream", fake_outputstream)
+
+ player._open_output_stream(24_000)
+
+ assert captured["latency"] == pytest.approx(0.4)
+
+
+ ("requested", "expected"),
+ [
+ (None, DEFAULT_OUTPUT_BUFFER_S),
+ (0.6, 0.6),
+ (0.001, 0.1), # clamped up: a USB headset underruns below ~100 ms
+ (30.0, 2.0), # clamped down: the UI animation would lead the voice
+ ("nonsense", DEFAULT_OUTPUT_BUFFER_S),
+ (float("nan"), DEFAULT_OUTPUT_BUFFER_S),
+ ],
+)
+def test_requested_buffer_is_clamped_to_an_audible_range(requested, expected) -> None:
+ assert player_module._clamp_output_buffer_s(requested) == pytest.approx(expected)
+
+
+def test_stall_window_scales_with_the_device_buffer() -> None:
+ """A deeper buffer waits proportionally longer before de-clicking."""
+ shallow = _bare_player()
+ shallow._output_buffer_s = 0.2
+ deep = _bare_player()
+ deep._output_buffer_s = 0.4
+
+ assert shallow._feed_stall_window_s() == pytest.approx(
+ player_module.FEED_STALL_FADE_S
+ )
+ assert deep._feed_stall_window_s() > shallow._feed_stall_window_s()
+ assert deep._feed_stall_window_s() < 0.4, (
+ "the ramp must still reach PortAudio before the buffer runs empty"
+ )
+
+
+async def test_short_feed_gap_inside_the_buffer_injects_nothing(monkeypatch) -> None:
+ """A provider hiccup the device buffer covers must stay inaudible.
+
+ Ramping down here would carve a dip out of speech that was never going to
+ break — with a deep buffer, ordinary network jitter is exactly this case.
+ """
+ player, written = _writing_player(monkeypatch, buffer_s=0.4)
+ tone = np.full(4_000, 6_000, dtype=np.int16)
+
+ async def briefly_stalling_feed() -> AsyncIterator[AudioChunk]:
+ yield _chunk(tone)
+ await asyncio.sleep(0.1) # well inside the 0.4 s device buffer
+ yield _chunk(tone)
+
+ await player.play_chunks(briefly_stalling_feed())
+
+ joined = np.concatenate(written)
+ assert joined.tobytes() == np.tile(tone, 2).tobytes(), (
+ "a gap the device buffer absorbs must reach the speaker byte-identical"
+ )
+
+
+async def test_gap_past_the_window_still_gets_de_clicked(monkeypatch) -> None:
+ """Once the buffer really is about to run dry, the edge is still ramped."""
+ player, written = _writing_player(monkeypatch, buffer_s=0.4)
+ tone = np.full(4_000, 6_000, dtype=np.int16)
+
+ async def long_stalling_feed() -> AsyncIterator[AudioChunk]:
+ yield _chunk(tone)
+ await asyncio.sleep(player._feed_stall_window_s() + 0.1)
+ yield _chunk(tone)
+
+ await player.play_chunks(long_stalling_feed())
+
+ assert len(written) == 3, (
+ f"expected [audio, fade-out ramp, resumed audio], got {len(written)}"
+ )
+ assert written[1][-1] == 0, "the fade-out must end at silence"
diff --git a/tests/unit/audio/test_player_stall_declick.py b/tests/unit/audio/test_player_stall_declick.py
index 7bea21b865..fa460a609d 100644
--- a/tests/unit/audio/test_player_stall_declick.py
+++ b/tests/unit/audio/test_player_stall_declick.py
@@ -60,6 +60,9 @@ def _make_player(monkeypatch) -> tuple[AudioPlayer, list[np.ndarray]]:
monkeypatch.setattr(player, "_close_output_stream", lambda stream: None)
monkeypatch.setattr(player, "_write_samples", fake_write)
# Fast stall detection so the test does not sleep for real buffer spans.
+ # The effective window is derived from the device buffer, so the shallow
+ # buffer here is what lets the patched floor win.
+ player._output_buffer_s = 0.1
monkeypatch.setattr(player_module, "FEED_STALL_FADE_S", 0.02)
return player, written
diff --git a/tests/unit/realtime/test_desktop.py b/tests/unit/realtime/test_desktop.py
index fa4182cc50..4276c2a057 100644
--- a/tests/unit/realtime/test_desktop.py
+++ b/tests/unit/realtime/test_desktop.py
@@ -209,6 +209,64 @@ async def test_handshake_sample_rate_is_used_for_the_next_turn():
assert [chunk.sample_rate for chunk in player.chunks] == [16_000]
+async def test_playback_waits_for_the_jitter_buffer_before_the_first_word() -> None:
+ """A turn banks a reserve first, so a provider pause has something to eat.
+
+ Live forensic 2026-07-27: gemini-live went quiet for 405-686 ms mid-reply
+ ("the provider sent no audio for this span") and the speaker ran dry.
+ """
+ player = FakePlayer()
+ # 24 kHz mono int16 = 48 bytes per millisecond; 100 ms of reserve = 4800 B.
+ playback = DesktopRealtimePlayback(
+ player, prebuffer_ms=100, prebuffer_timeout_ms=10_000
+ )
+
+ await playback.send_binary(b"\x01\x00" * 24) # ~1 ms — nowhere near full
+ await asyncio.sleep(0)
+ await asyncio.sleep(0)
+ assert player.chunks == [], "playback must not start on a bare first chunk"
+
+ await playback.send_binary(b"\x02\x00" * 2_400) # tips it over 100 ms
+ await asyncio.sleep(0)
+ await asyncio.sleep(0)
+
+ await playback.finish_turn()
+ assert [chunk.pcm for chunk in player.chunks] == [
+ b"\x01\x00" * 24,
+ b"\x02\x00" * 2_400,
+ ], "the reserve delays playback; it never drops or reorders audio"
+
+
+async def test_short_reply_is_not_held_back_by_the_jitter_buffer() -> None:
+ """A reply shorter than the reserve still plays — the sentinel releases it."""
+ player = FakePlayer()
+ playback = DesktopRealtimePlayback(
+ player, prebuffer_ms=5_000, prebuffer_timeout_ms=10_000
+ )
+
+ await playback.send_binary(b"\x07\x00" * 8)
+ await playback.finish_turn()
+
+ assert [chunk.pcm for chunk in player.chunks] == [b"\x07\x00" * 8]
+
+
+async def test_jitter_buffer_wait_is_bounded_by_its_timeout() -> None:
+ """A provider that trickles audio out still starts speaking on time."""
+ player = FakePlayer()
+ playback = DesktopRealtimePlayback(
+ player, prebuffer_ms=5_000, prebuffer_timeout_ms=30
+ )
+
+ await playback.send_binary(b"\x05\x00" * 8)
+ await asyncio.sleep(0.15) # past the timeout, turn still open
+
+ assert [chunk.pcm for chunk in player.chunks] == [b"\x05\x00" * 8]
+ await playback.finish_turn()
+
+
def test_energy_pre_gate_skips_onnx_for_quiet_frames() -> None:
# BUG-062: quiet frames (silence / hiss / moderate speaker echo) must
# never reach the Silero model — that is both the loop-load fix (stutter
diff --git a/tests/unit/web/test_cli_auth_probes_off_the_event_loop.py b/tests/unit/web/test_cli_auth_probes_off_the_event_loop.py
new file mode 100644
index 0000000000..91db0ecd9f
--- /dev/null
+++ b/tests/unit/web/test_cli_auth_probes_off_the_event_loop.py
@@ -0,0 +1,75 @@
+"""CLI auth probes must never run on the event loop.
+
+``ClaudeAuthService.status`` / ``CodexAuthService.status`` /
+``GoogleCliAuthService.status`` and the matching ``logout_blocking`` SPAWN the
+real CLI binary. That costs a few hundred milliseconds, and on the event loop
+it freezes everything else this process is doing.
+
+Live forensic 2026-07-27 (realtime voice, gemini-live): the UI's provider
+panels poll these endpoints while a reply is being spoken. Each inline probe
+stalled the loop 311-375 ms, the realtime audio socket went unread, the device
+buffer drained, and the maintainer heard a hole in the middle of a sentence —
+logged by ``RealtimeSession._note_audio_flow`` as "this process's event loop
+stalled ... the audio likely sat unread in the socket".
+
+This is a structural guard, not a behavioural one: it walks the route modules
+and fails on any ``async def`` that reaches a blocking probe without handing it
+to a worker thread. Adding a new provider CLI is exactly when this regresses.
+"""
+from __future__ import annotations
+
+import ast
+from pathlib import Path
+
+import pytest
+
+#: Auth services whose probes spawn a subprocess.
+BLOCKING_SERVICES = (
+ "ClaudeAuthService",
+ "CodexAuthService",
+ "GoogleCliAuthService",
+)
+
+#: Route modules that expose those services to the UI.
+ROUTE_MODULES = (
+ "jarvis/ui/web/provider_routes.py",
+ "jarvis/ui/web/antigravity_routes.py",
+ "jarvis/ui/web/claude_routes.py",
+ "jarvis/ui/web/server.py",
+)
+
+_REPO_ROOT = Path(__file__).resolve().parents[3]
+
+
+def _async_defs_touching_a_blocking_service(path: Path):
+ """Yield (function name, source) for async defs naming a blocking service."""
+ # utf-8-sig: several route modules are BOM-prefixed (the config writer's
+ # BOM-safe contract, AP-7), which plain utf-8 parsing rejects.
+ source = path.read_text(encoding="utf-8-sig")
+ lines = source.splitlines()
+ for node in ast.walk(ast.parse(source)):
+ if not isinstance(node, ast.AsyncFunctionDef):
+ continue
+ body = "\n".join(lines[node.lineno - 1 : node.end_lineno or node.lineno])
+ if any(service in body for service in BLOCKING_SERVICES):
+ yield node.name, body
+
+
[email protected]("module", ROUTE_MODULES)
+def test_route_handlers_offload_cli_auth_probes(module: str) -> None:
+ path = _REPO_ROOT / module
+ if not path.exists(): # pragma: no cover - module renamed
+ pytest.skip(f"{module} is gone")
+
+ offenders = [
+ name
+ for name, body in _async_defs_touching_a_blocking_service(path)
+ if "to_thread" not in body and "run_in_executor" not in body
+ ]
+
+ assert not offenders, (
+ f"{module}: {offenders} call a CLI auth probe inline. The probe spawns "
+ "a binary and blocks the event loop for hundreds of milliseconds, "
+ "which is heard as a hole in the middle of a spoken answer. Wrap it: "
+ "`await asyncio.to_thread(service.status)`."
+ )