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): make the backstop boundary seamless, and sequence spliced responses

rubenluetke10-beepf90f42c7d79b
diff --git a/jarvis/audio/player.py b/jarvis/audio/player.py
index 6d81960099..9d8235a9b5 100644
--- a/jarvis/audio/player.py
+++ b/jarvis/audio/player.py
@@ -550,6 +550,12 @@ class AudioPlayer:
# makes the lookup miss for the new device and walk the cascade
# fresh.
self._device_rate_cache: dict[tuple[Any, int], int] = {}
+ # Negative sibling of the cache above: (device, rate) pairs PortAudio
+ # refused with -9997. Without it, every fresh walk retried the same
+ # refused rate first (live 2026-08-06: "@ 24000Hz failed" on every
+ # realtime turn, because the source rate leads the candidate order on
+ # purpose). Cleared together with the positive cache on device swap.
+ self._device_rate_failed: set[tuple[Any, int]] = set()
# Playback-progress telemetry for the pipeline stall watchdog (Wave-1
# latency fix). ``last_write_ns`` is bumped after every successful
# ``stream.write`` sub-block; the watchdog reads it to tell a healthy
@@ -684,6 +690,7 @@ class AudioPlayer:
if stream is not None:
self._close_output_stream(stream)
self._device_rate_cache.clear()
+ self._device_rate_failed.clear()
# A swapped device also invalidates the played-envelope record: echo
# correlation against a vanished device's output is meaningless.
echo_reference.reset()
@@ -926,6 +933,29 @@ class AudioPlayer:
candidates = [cached_rate]
else:
candidates = _candidate_output_rates(source_rate, dev_default)
+ # Skip rates this device already refused with -9997 — but never
+ # filter down to nothing: a device whose refusals covered every
+ # candidate still deserves the full walk (hot-swap edge).
+ known_bad = getattr(self, "_device_rate_failed", set())
+ filtered = [
+ rate
+ for rate in candidates
+ if (self._device, rate) not in known_bad
+ ]
+ if filtered:
+ if len(filtered) != len(candidates):
+ log.debug(
+ "output rate cascade skips %d rate(s) this device "
+ "already refused",
+ len(candidates) - len(filtered),
+ )
+ candidates = filtered
+ log.debug(
+ "output rate cache miss (device=%r, source=%d) - walking %s",
+ self._device,
+ source_rate,
+ candidates,
+ )
last_exc: BaseException | None = None
for target_rate in candidates:
@@ -968,8 +998,14 @@ class AudioPlayer:
last_exc = exc
if "-9997" not in str(exc) and "Invalid sample rate" not in str(exc):
raise
+ # Remember the refusal so no later walk in this player's life
+ # retries it (the per-turn "@ 24000Hz failed" log storm).
+ getattr(self, "_device_rate_failed", set()).add(
+ (self._device, target_rate)
+ )
log.warning(
- "OutputStream @ %dHz failed (%s) — trying next rate …",
+ "OutputStream @ %dHz failed (%s) — trying next rate "
+ "(this device+rate is now skipped for this session)",
target_rate, exc,
)
diff --git a/jarvis/plugins/realtime/codex_subscription.py b/jarvis/plugins/realtime/codex_subscription.py
index bb475c7e8e..da5c3ba69e 100644
--- a/jarvis/plugins/realtime/codex_subscription.py
+++ b/jarvis/plugins/realtime/codex_subscription.py
@@ -67,12 +67,17 @@ _TURN_INTERRUPT_TIMEOUT_S = 1.5
# that the quiescence backstop is not held open forever by a track that keeps
# sending silence between turns. Energy only, never transcript content (AP-27).
_OUTPUT_AUDIBLE_PEAK = 200
-# The v3 item vocabulary is OpenAI-Realtime family — the two items already
-# handled here (``input_audio_buffer.speech_started``, ``response.cancelled``)
-# are its members, and that family ends a response with ``response.done``; the
-# repo's own OpenAI adapter maps it exactly that way. The precise v3 spelling is
-# not yet confirmed live, so both plausible names are accepted AND the
-# quiescence backstop still terminates every turn if neither ever arrives.
+# CONFIRMED LIVE (notification-dump probe, 2026-08-06,
+# scripts/codex_live_probe.py --dump): ChatGPT-Live v3 announces NO items at
+# all — the complete notification vocabulary observed on a real answered call
+# was ``thread/realtime/{started,sdp,transcript/delta,transcript/done}``. No
+# ``response.*``, no ``input_audio_buffer.*``; responses exist only as audio
+# and transcripts. The quiescence backstop is therefore not a fallback but
+# THE turn boundary of this transport, and the playback path treats
+# backstop-derived boundaries as first-class (prebuffer-free resume,
+# sequenced back-to-back responses). This frozenset stays as dead-cheap
+# future-proofing: should the server ever start announcing a terminal item,
+# it is consumed correctly on arrival.
_TERMINAL_RESPONSE_ITEMS = frozenset({"response.done", "response.completed"})
_RESPONSE_OPENED_ITEMS = frozenset({"response.created", "response.in_progress"})
# Bound on the one-line-per-type unknown-item log, so a chatty protocol cannot
@@ -714,6 +719,15 @@ class _CodexSubscriptionRealtimeSession:
completion_task: asyncio.Task[None] | None = None
completion_generation = 0
completion_emitted = False
+ # Armed by ``_begin_response`` when a NEW response opens over a
+ # previous one whose audio played but never got a boundary (closed
+ # silently by an invented caption or a stale-refusal cleanup). Without
+ # this the two responses splice RAW into one playback stream - the
+ # 15/140 ms seams measured live 2026-08-06. The receive loop drains it
+ # into a local turn boundary BEFORE the new response's audio flows;
+ # the playback side then resumes prebuffer-free, so the sequenced
+ # boundary costs ~0 ms.
+ sequence_boundary_pending = False
stream_ended = False
local_transcript_failed = False
user_final_emitted = False
@@ -934,6 +948,7 @@ class _CodexSubscriptionRealtimeSession:
nonlocal entitled_generation, entitlement_spent
nonlocal interrupt_grace_until, refusal_run, refusal_run_started_at
nonlocal refusal_storm_noted, self_dialogue_detected
+ nonlocal sequence_boundary_pending
if response_open:
if response_allowed or not _rejected_response_is_stale():
return response_allowed
@@ -947,20 +962,29 @@ class _CodexSubscriptionRealtimeSession:
if last_output_activity > 0.0:
splice_gap_ms = (response_opened_at - last_output_activity) * 1000.0
if splice_gap_ms < 1_500.0:
- # Two responses splice into ONE playback stream here with
- # no marker the session could sequence on. A user-reported
- # ~2 s garble (2026-08-05 20:12) has exactly this shape as
- # its one plausible client-side mechanism; this line
- # timestamps the seam so the next incident is attributable
- # to the seam or to the server's own audio.
+ # Two responses would splice into ONE playback stream here
+ # with no marker between them. A user-reported ~2 s garble
+ # (2026-08-05 20:12) has exactly this shape; seams of 15
+ # and 140 ms were then measured live 2026-08-06. When the
+ # previous response's audio PLAYED and never got a
+ # boundary, arm the sequencing drain: the receive loop
+ # emits a local turn boundary before this response's audio
+ # flows, converting the raw splice into a clean seam the
+ # prebuffer-free playback resume makes inaudible.
self._diag["response_splices"] += 1
+ if not completion_emitted:
+ sequence_boundary_pending = True
log.info(
"Codex subscription realtime opened a new response "
"%d ms after the previous response's audio "
- "(source=%s) — back-to-back responses splice in one "
- "playback stream",
+ "(source=%s)%s",
int(splice_gap_ms),
source,
+ (
+ " — sequencing a local turn boundary between them"
+ if not completion_emitted
+ else " — previous response already closed cleanly"
+ ),
)
response_rejected_at = 0.0
active_response_generation = 0
@@ -1097,6 +1121,40 @@ class _CodexSubscriptionRealtimeSession:
"""Local turn boundary: closes the response, keeps the entitlement."""
_close_response(spent=False)
+ async def _drain_sequence_boundary() -> list[_ProviderEvent]:
+ """Events that close a spliced-over response behind a boundary.
+
+ Runs right after ``_begin_response`` armed the pending flag for a
+ back-to-back open: recovers whatever the OLD response left (its
+ missing input boundary, its transcript head) and closes it with a
+ ``turn_complete`` BEFORE the new response's audio flows. The
+ caller yields these in order; the capture reset makes the new
+ response start clean.
+ """
+ nonlocal sequence_boundary_pending, completion_emitted
+ if not sequence_boundary_pending:
+ return []
+ sequence_boundary_pending = False
+ events: list[_ProviderEvent] = []
+ missing_input = _missing_input_boundary()
+ if missing_input is not None:
+ events.append(missing_input)
+ recovered = await _recover_output_transcript()
+ if recovered is not None:
+ events.append(recovered)
+ self._diag["sequenced_boundaries"] += 1
+ log.info(
+ "Codex subscription realtime sequenced a back-to-back "
+ "response behind a local turn boundary"
+ )
+ events.append(_ProviderEvent(type="turn_complete"))
+ _reset_assistant_capture()
+ self._assistant_delta_text = ""
+ # The boundary belongs to the OLD response; the one just opened
+ # is live, so the completion flag stays clear for it.
+ completion_emitted = False
+ return events
+
def _note_output_activity() -> None:
nonlocal last_output_activity
last_output_activity = asyncio.get_running_loop().time()
@@ -1502,6 +1560,8 @@ class _CodexSubscriptionRealtimeSession:
if audible:
if not await _begin_response("media audio"):
continue
+ for boundary_event in await _drain_sequence_boundary():
+ yield boundary_event
# Energy only, never transcript content (AP-27): this
# stamp is what tells a pause inside one answer apart
# from a quiet stretch between responses.
@@ -1523,6 +1583,8 @@ class _CodexSubscriptionRealtimeSession:
continue
if not await _begin_response("media prelude"):
continue
+ for boundary_event in await _drain_sequence_boundary():
+ yield boundary_event
elif not response_allowed:
continue
if (
@@ -1737,6 +1799,8 @@ class _CodexSubscriptionRealtimeSession:
elif role == "assistant":
if not await _begin_response("assistant transcript"):
continue
+ for boundary_event in await _drain_sequence_boundary():
+ yield boundary_event
# Text arriving proves the same answer is still being
# produced, even while its audio pauses.
_note_output_activity()
@@ -1867,6 +1931,8 @@ class _CodexSubscriptionRealtimeSession:
elif role == "assistant":
if not await _begin_response("assistant transcript"):
continue
+ for boundary_event in await _drain_sequence_boundary():
+ yield boundary_event
_note_output_activity()
assistant_transcript_seen = True
assistant_audio.clear()
diff --git a/jarvis/realtime/desktop.py b/jarvis/realtime/desktop.py
index 1cc944ad40..d3580cf0c1 100644
--- a/jarvis/realtime/desktop.py
+++ b/jarvis/realtime/desktop.py
@@ -463,6 +463,16 @@ class DesktopRealtimePlayback:
``DEFAULT_PREBUFFER_MS``).
"""
+ #: Reopening within this window after a natural turn boundary skips the
+ #: jitter prebuffer. ChatGPT-Live announces no terminal response item
+ #: (probe-confirmed 2026-08-06: the notification vocabulary is
+ #: sdp/started/transcript only), so every generation pause longer than the
+ #: adapter's 1.2 s quiescence backstop ends the turn locally - and the
+ #: next delta used to reopen with a fresh 180 ms reserve, which made every
+ #: such pause an audible seam MID-REPLY. Matches the adapter's
+ #: continuation grace (same "still the same answer" semantic).
+ RESUME_WITHOUT_PREBUFFER_S = 4.0
+
def __init__(
self,
player: Any,
@@ -472,6 +482,7 @@ class DesktopRealtimePlayback:
finish_timeout_s: float = 120.0,
prebuffer_ms: int = DEFAULT_PREBUFFER_MS,
prebuffer_timeout_ms: int = DEFAULT_PREBUFFER_TIMEOUT_MS,
+ resume_without_prebuffer_s: float = RESUME_WITHOUT_PREBUFFER_S,
) -> None:
self._player = player
self._sample_rate = int(sample_rate)
@@ -479,17 +490,42 @@ class DesktopRealtimePlayback:
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._resume_without_prebuffer_s = max(
+ 0.0, float(resume_without_prebuffer_s)
+ )
self._queue: asyncio.Queue[AudioChunk | None] | None = None
self._task: asyncio.Task[None] | None = None
self._closed = False
+ self._last_finish_at = 0.0
async def send_binary(self, pcm: bytes) -> None:
if not pcm or self._closed:
return
if self._task is None or self._task.done():
+ prebuffer_s = self._prebuffer_s
+ since_finish = time.monotonic() - self._last_finish_at
+ # Strict comparison: a grace of 0.0 means "never" even on
+ # Windows' coarse monotonic clock, where since_finish can be
+ # exactly 0.0 right after the boundary.
+ if (
+ self._last_finish_at > 0.0
+ and since_finish < self._resume_without_prebuffer_s
+ ):
+ # Same-answer resume: the boundary we just crossed was the
+ # local silence backstop, not the provider ending its answer.
+ # Nothing is dropped or reordered - the reserve simply is not
+ # rebuilt, so the seam costs ~0 ms instead of 180 ms.
+ prebuffer_s = 0.0
+ log.debug(
+ "reopened realtime playback %d ms after the last boundary"
+ " - skipping the jitter prebuffer (same-answer resume)",
+ int(since_finish * 1000.0),
+ )
self._queue = asyncio.Queue(maxsize=self._max_queue_chunks)
self._task = asyncio.create_task(
- self._player.play_chunks(self._chunks(self._queue)),
+ self._player.play_chunks(
+ self._chunks(self._queue, prebuffer_s)
+ ),
name="realtime-desktop-playback",
)
# A terminal surface cancellation can race a provider callback
@@ -550,6 +586,10 @@ class DesktopRealtimePlayback:
if self._task is task:
self._queue = None
self._task = None
+ # Natural boundary only: a barge-in cancel() deliberately does
+ # NOT stamp this, so the next (genuinely new) reply rebuilds
+ # its jitter reserve.
+ self._last_finish_at = time.monotonic()
async def cancel(self) -> None:
queue, task = self._detach()
@@ -610,6 +650,7 @@ class DesktopRealtimePlayback:
async def _chunks(
self,
queue: asyncio.Queue[AudioChunk | None],
+ prebuffer_s: float | None = None,
) -> AsyncIterator[AudioChunk]:
"""Yield the turn's audio, opening with the jitter buffer.
@@ -617,11 +658,15 @@ class DesktopRealtimePlayback:
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.
+ shorter than the reserve still plays immediately. ``prebuffer_s``
+ overrides the configured reserve for THIS task (0.0 on a same-answer
+ resume).
"""
banked: list[AudioChunk] = []
ended = False
- target_bytes = int(self._sample_rate * 2 * self._prebuffer_s)
+ if prebuffer_s is None:
+ prebuffer_s = self._prebuffer_s
+ target_bytes = int(self._sample_rate * 2 * prebuffer_s)
if target_bytes > 0:
loop = asyncio.get_running_loop()
deadline = loop.time() + self._prebuffer_timeout_s
diff --git a/tests/unit/audio/test_player_device_swap.py b/tests/unit/audio/test_player_device_swap.py
index 81446d4c9b..dd5c4d5f7f 100644
--- a/tests/unit/audio/test_player_device_swap.py
+++ b/tests/unit/audio/test_player_device_swap.py
@@ -22,8 +22,6 @@ Fix:
"""
from __future__ import annotations
-import pytest
-
from jarvis.audio.player import AudioPlayer
@@ -40,6 +38,7 @@ def _make_player(device: int | str | None = None) -> AudioPlayer:
p._active_source_rate = None
p._active_device_rate = None
p._device_rate_cache = {}
+ p._device_rate_failed = set()
return p
@@ -97,11 +96,12 @@ def test_invalidate_device_cache_drops_active_stream_and_cache() -> None:
"""invalidate_device_cache() must:
- close the active stream (if any),
- reset _active_source_rate / _active_device_rate,
- - empty _device_rate_cache.
+ - empty _device_rate_cache (and its negative sibling).
"""
p = _make_player(device=3)
p._device_rate_cache[(3, 24000)] = 48000
p._device_rate_cache[(7, 22050)] = 44100
+ p._device_rate_failed.add((3, 22050))
close_calls: list = []
@@ -120,11 +120,95 @@ def test_invalidate_device_cache_drops_active_stream_and_cache() -> None:
assert p._active_source_rate is None
assert p._active_device_rate is None
assert p._device_rate_cache == {}
+ assert p._device_rate_failed == set(), (
+ "a swapped device invalidates remembered refusals too"
+ )
assert close_calls == ["stop", "close"], (
f"expected _close_output_stream to call stop+close; got {close_calls}"
)
+def test_a_remembered_refusal_is_skipped_on_the_next_walk(monkeypatch) -> None:
+ """Live 2026-08-06: realtime playback retried 24000 first on every fresh
+ cascade walk and PortAudio refused it with -9997 each time — one warning
+ per walk and the open-latency of a doomed attempt. A remembered refusal
+ is skipped outright."""
+ import jarvis.audio.player as player_mod
+
+ open_log: list[tuple] = []
+
+ class FakeStream:
+ latency = 0.2
+
+ def start(self):
+ pass
+
+ def fake_outputstream(*, samplerate, device, **kw):
+ open_log.append((device, samplerate))
+ if samplerate == 48000:
+ return FakeStream()
+ raise player_mod.sd.PortAudioError(
+ f"Error opening OutputStream: Invalid sample rate "
+ f"[PaErrorCode -9997] (device={device}, rate={samplerate})"
+ )
+
+ monkeypatch.setattr(player_mod.sd, "OutputStream", fake_outputstream)
+ monkeypatch.setattr(
+ player_mod.sd, "query_devices", lambda d: {"default_samplerate": 48000}
+ )
+
+ # First walk records the refusal (source-first order is deliberate).
+ p = _make_player(device=3)
+ _, rate = p._open_output_stream(24000)
+ assert rate == 48000
+ assert open_log[0] == (3, 24000)
+ assert (3, 24000) in p._device_rate_failed
+
+ # A later walk that misses the positive cache must skip the refused rate.
+ p._device_rate_cache.clear()
+ open_log.clear()
+ _, rate2 = p._open_output_stream(24000)
+ assert rate2 == 48000
+ assert open_log == [(3, 48000)], "the refused 24000 was never retried"
+
+
+def test_all_rates_refused_before_still_walks_everything(monkeypatch) -> None:
+ """The filter must never starve the cascade: a device whose remembered
+ refusals cover every candidate gets the full walk again (hot-swap edge —
+ the same index can come back as a different physical device)."""
+ import jarvis.audio.player as player_mod
+
+ open_log: list[tuple] = []
+
+ class FakeStream:
+ latency = 0.2
+
+ def start(self):
+ pass
+
+ def fake_outputstream(*, samplerate, device, **kw):
+ open_log.append((device, samplerate))
+ if samplerate == 48000:
+ return FakeStream()
+ raise player_mod.sd.PortAudioError(
+ f"[PaErrorCode -9997] (device={device}, rate={samplerate})"
+ )
+
+ monkeypatch.setattr(player_mod.sd, "OutputStream", fake_outputstream)
+ monkeypatch.setattr(
+ player_mod.sd, "query_devices", lambda d: {"default_samplerate": 44100}
+ )
+
+ p = _make_player(device=3)
+ p._device_rate_failed = {
+ (3, rate) for rate in (24000, 48000, 44100)
+ }
+
+ _, rate = p._open_output_stream(24000)
+ assert rate == 48000
+ assert open_log, "an all-refused device still deserves the full cascade"
+
+
def test_set_device_to_same_device_is_noop() -> None:
"""If the new device resolves to the same value, no cache flush,
no _device_logged reset.
diff --git a/tests/unit/realtime/test_codex_subscription.py b/tests/unit/realtime/test_codex_subscription.py
index 0c1d7931ec..0f03830329 100644
--- a/tests/unit/realtime/test_codex_subscription.py
+++ b/tests/unit/realtime/test_codex_subscription.py
@@ -2956,3 +2956,96 @@ async def test_the_language_pin_never_authorizes_a_response() -> None:
event.text for event in events if event.type == "output_transcript_delta"
] == []
await session.close()
+
+
+async def test_a_barge_splice_is_sequenced_behind_a_local_boundary() -> None:
+ """Live 2026-08-06 17:39/17:41: a cut answer's replacement opened 15-140 ms
+ after the previous response's audio and spliced RAW into the one playback
+ stream (no boundary between them - the barge closes silently). The
+ adapter now closes the spliced-over response with a local turn boundary
+ BEFORE the new response's text/audio flows, and counts the sequencing so
+ the postmortem can prove it happened.
+ """
+ transcriber = _ScheduledInputTranscriber(
+ [
+ (0.02, InputTranscriptEvent(kind="speech_started")),
+ (
+ 0.0,
+ InputTranscriptEvent(kind="transcript", text="Hello", is_final=True),
+ ),
+ # The interrupting user's own follow-up grounds response 2.
+ (0.25, InputTranscriptEvent(kind="speech_started")),
+ (
+ 0.0,
+ InputTranscriptEvent(
+ kind="transcript", text="And again", is_final=True
+ ),
+ ),
+ ]
+ )
+ client = _Client()
+ client.subscription = _ScheduledSubscription(
+ [
+ (
+ 0.1,
+ _Notification(
+ "thread/realtime/transcript/delta",
+ {
+ "threadId": "thread-1",
+ "role": "assistant",
+ "delta": "First answer",
+ },
+ ),
+ ),
+ (
+ 0.5,
+ _Notification(
+ "thread/realtime/transcript/delta",
+ {
+ "threadId": "thread-1",
+ "role": "assistant",
+ "delta": "Second answer",
+ },
+ ),
+ ),
+ ]
+ )
+ session = await _provider(
+ client, input_transcriber_factory=lambda: transcriber
+ ).open_session(RealtimeSessionConfig())
+
+ events = []
+ async with asyncio.timeout(5.0):
+ async for event in session.receive():
+ events.append(event)
+ text = event.text or ""
+ if event.type == "output_transcript_delta" and "First" in text:
+ # The user talks over the answer: the barge-in cuts response 1
+ # WITHOUT any boundary event of its own.
+ await session.interrupt()
+ if event.type == "output_transcript_delta" and "Second" in text:
+ break
+
+ deltas = [
+ i
+ for i, event in enumerate(events)
+ if event.type == "output_transcript_delta"
+ ]
+ first_idx = next(
+ i
+ for i, event in enumerate(events)
+ if event.type == "output_transcript_delta" and "First" in (event.text or "")
+ )
+ second_idx = next(
+ i
+ for i, event in enumerate(events)
+ if event.type == "output_transcript_delta" and "Second" in (event.text or "")
+ )
+ between = [event.type for event in events[first_idx:second_idx]]
+ assert "turn_complete" in between, (
+ "the spliced-over response must close behind a local boundary before "
+ f"the new one speaks; saw {between} (deltas at {deltas})"
+ )
+ assert session.diagnostics().get("sequenced_boundaries", 0) == 1
+ await session.close()
diff --git a/tests/unit/realtime/test_desktop.py b/tests/unit/realtime/test_desktop.py
index 4276c2a057..092e9a19ee 100644
--- a/tests/unit/realtime/test_desktop.py
+++ b/tests/unit/realtime/test_desktop.py
@@ -267,6 +267,78 @@ async def test_jitter_buffer_wait_is_bounded_by_its_timeout() -> None:
await playback.finish_turn()
+async def test_quick_resume_after_a_boundary_skips_the_jitter_buffer() -> None:
+ """ChatGPT-Live announces no terminal item (probe-confirmed 2026-08-06),
+ so any generation pause beyond the 1.2 s quiescence backstop closes the
+ stream MID-ANSWER. Reopening within the resume grace must not rebuild the
+ reserve — that rebuilt reserve WAS the audible seam."""
+ player = FakePlayer()
+ playback = DesktopRealtimePlayback(
+ player, prebuffer_ms=5_000, prebuffer_timeout_ms=10_000
+ )
+
+ await playback.send_binary(b"\x01\x00" * 8)
+ await playback.finish_turn() # a natural boundary stamps the resume clock
+
+ await playback.send_binary(b"\x02\x00" * 8) # far below the 5 s reserve
+ await asyncio.sleep(0)
+ await asyncio.sleep(0)
+ await asyncio.sleep(0)
+
+ assert [chunk.pcm for chunk in player.chunks] == [
+ b"\x01\x00" * 8,
+ b"\x02\x00" * 8,
+ ], "the same-answer resume must play immediately, reserve skipped"
+ await playback.finish_turn()
+
+
+async def test_resume_past_the_grace_rebuilds_the_reserve() -> None:
+ player = FakePlayer()
+ playback = DesktopRealtimePlayback(
+ player,
+ prebuffer_ms=5_000,
+ prebuffer_timeout_ms=10_000,
+ resume_without_prebuffer_s=0.0, # grace disabled = every turn banks
+ )
+
+ await playback.send_binary(b"\x01\x00" * 8)
+ await playback.finish_turn()
+
+ await playback.send_binary(b"\x02\x00" * 8)
+ await asyncio.sleep(0)
+ await asyncio.sleep(0)
+
+ assert all(chunk.pcm != b"\x02\x00" * 8 for chunk in player.chunks), (
+ "past the grace the reserve applies again"
+ )
+ await playback.finish_turn() # the sentinel releases the banked chunk
+ assert player.chunks[-1].pcm == b"\x02\x00" * 8
+
+
+async def test_barge_in_cancel_does_not_arm_the_resume_grace() -> None:
+ """After a barge-in the next reply is a genuinely NEW answer: it deserves
+ its jitter reserve, so cancel() must not stamp the resume clock."""
+ player = FakePlayer()
+ playback = DesktopRealtimePlayback(
+ player, prebuffer_ms=5_000, prebuffer_timeout_ms=10_000
+ )
+
+ await playback.send_binary(b"\x01\x00" * 8)
+ await playback.cancel()
+
+ await playback.send_binary(b"\x02\x00" * 8)
+ await asyncio.sleep(0)
+ await asyncio.sleep(0)
+
+ assert all(chunk.pcm != b"\x02\x00" * 8 for chunk in player.chunks), (
+ "a post-barge-in reply rebuilds its reserve"
+ )
+ 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