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): cancel realtime surface playback atomically

Ruben Lütke1ee961419655
diff --git a/docs/BUGS.md b/docs/BUGS.md
index 37675267b5..071d4cd776 100644
--- a/docs/BUGS.md
+++ b/docs/BUGS.md
@@ -6673,3 +6673,87 @@ and user-facing outcome as four separate facts. Never infer approval from a
file, never discard a valid decision because a presentation field is verbose,
never review stale attempt logs, and never collapse retained unsigned work into
an unexplained error.
+
+---
+
+## BUG-097: realtime replies cut off after two seconds, resumed as untracked audio, then ended the call (CRITICAL, FIXED IN CODE 2026-07-19; LIVE DEPLOYMENT PENDING)
+
+**Symptom (macOS live forensic, platform-neutral code path).** Long replies were
+cut off roughly two seconds after first audio even though the user had not
+interrupted. Audio could then resume after the surface had returned to
+LISTENING, the user's next speech produced no visible transcript or answer, and
+the call ended with `hangup_reason=error`. The immediately preceding call had
+the same signature. The affected process was running managed-install commit
+`35fda998`, at least 25 commits behind the development line at diagnosis, so
+this is also a confirmed device-parity layer-1 version lag rather than a new
+macOS-only diagnosis.
+
+**Last five stored turns in session `163fca8b` (18:31-18:34).**
+
+| Turn | Outcome | Evidence |
+|---|---|---|
+| 4 | Cut off | First audio at 18:32:41.288; local VAD falsely declared barge-in 1.545 s later. Speaker echo was subsequently transcribed as the user's input. |
+| 6 | Completed | Surface TTS rendered the full 436-character reply and emitted `SpeechSpoken`. |
+| 7 | Completed | Native realtime reply completed; PortAudio reported a first-write underflow. |
+| 8 | Completed | The 21.5 s native reply completed; PortAudio again reported only a first-write underflow. |
+| 9 | Cut off, resumed, hung up | First audio at 18:34:25.732; false barge-in 1.607 s later; `OutputStream` reopened after cancellation; microphone send timed out; the call ended as an error. |
+
+Session `957b7fce` immediately before it reproduced the same sequence: first
+audio, false local barge-in after 1.736 s, post-cancel stream reopen, microphone
+send timeout, error hangup. This repetition and the stream timestamps rule out a
+random provider sentence boundary.
+
+**Root causes.** Three independent lifecycle defects chained together:
+
+1. `DesktopRealtimeBargeInDetector` began its 1.5 s grace window at the logical
+ SPEAKING transition. Surface synthesis and stream setup consumed about one
+ second of that window before physical playback existed. The detector then
+ had too little real speaker-echo calibration and classified the assistant's
+ own output as user speech.
+2. Surface fallback TTS called `AudioPlayer.play_chunks()` outside
+ `DesktopRealtimePlayback` ownership. `tts_cancel` stopped PortAudio but did
+ not cancel the async TTS producer. Its next chunk reopened the stream and
+ produced the untracked post-cancel speech.
+3. The old managed install treated the later write-only provider stall as a
+ terminal microphone error. The development line already contains the
+ in-place, key/provider-neutral transport rebuild and stale-timeout guard from
+ `b9023134` and `a1657225`; the running process contained neither.
+
+**Fix.** Commit `363be37c` starts grace and adaptive echo calibration from
+`level_tap.playback_active()`, so synthesis latency cannot consume it. The
+surface fallback now owns its complete playback task, invalidates older renders
+with an epoch, cancels the producer before stopping the shared player, and
+awaits generator shutdown. `AudioPlayer` independently generation-guards its
+worker-thread stream setup: if `stop()` wins while PortAudio is still opening,
+the late handle is closed instead of being published as the active stream. A
+terminal session teardown invalidates the pre-task synthesis window as well.
+The existing in-place transport recovery then keeps a write-only stall and any
+overlapping stale timeout from ending an otherwise healthy call.
+
+**Pause attribution.** The last five turns contain no logged mid-reply provider
+gap or embedded-silence event at the existing 400 ms threshold, so their
+reported half-second pauses cannot be reconstructed honestly from the available
+event granularity. Earlier same-day sessions do prove 400-600 ms provider gaps
+and embedded silent PCM; those remain the separate BUG-087 audio-flow issue.
+This fix removes the deterministic cut/restart/hangup chain but does not claim
+that every provider-generated pause is gone.
+
+**Guards and parity.** Detector tests delay synthesis past the old grace window
+and prove that a full physical-playback grace still follows. Surface tests
+cancel both before the first chunk and between chunks, require generator
+closure, reject a spoken receipt, forbid the second chunk, and keep the live
+call open. A pre-task cancel test pins the state-callback race. Audio-player
+coverage stops playback while a worker thread is opening PortAudio and proves
+the late stream is closed without one write. The transport test now forces two
+overlapping send deadlines, lets the first rebuild the transport, then delivers
+the second as a stale timeout and verifies the fresh session still accepts
+audio. These paths are pure Python plus the existing PortAudio abstraction and
+contain no OS branch; `stop()` remains an honest no-op without PortAudio on a
+headless install. Hardware validation on the updated managed installation is
+still required before changing the status to live-verified.
+
+**Class rule.** A cancel boundary owns the producer, buffer, device stream, and
+any in-flight stream-open operation. Stopping only the current device handle is
+not cancellation: an async producer or worker thread can recreate it after the
+surface has already changed state. Playback grace begins at physical playback,
+not at intent to play.
diff --git a/jarvis/audio/player.py b/jarvis/audio/player.py
index 0016762b20..09ac74a9cb 100644
--- a/jarvis/audio/player.py
+++ b/jarvis/audio/player.py
@@ -10,6 +10,7 @@ from __future__ import annotations
import asyncio
import logging
+import threading
import time
from collections.abc import AsyncIterator, Callable, Sequence
from typing import TYPE_CHECKING, Any
@@ -43,6 +44,11 @@ _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
+
+class _PlaybackSuperseded(RuntimeError):
+ """A stopped playback attempted to acquire a new output stream."""
+
+
# Audio devices we NEVER auto-select as headset output. These are
# locale-independent hardware/interface names: monitor speakers reached over
# HDMI/DisplayPort (GPU audio chips) and digital passthrough with no guaranteed
@@ -417,6 +423,12 @@ class AudioPlayer:
self._active_stream: sd.OutputStream | None = None
self._active_source_rate: int | None = None
self._active_device_rate: int | None = None
+ # ``OutputStream`` setup runs in a worker thread while stop() runs on
+ # the voice event loop. A stop can therefore land after setup began but
+ # before the worker publishes the new stream. The generation + lock
+ # make that late stream stale instead of letting it resurrect playback.
+ self._playback_generation = 0
+ self._stream_state_lock = threading.Lock()
# Most devices expose at least two output channels, but small USB DACs,
# accessibility devices, and virtual sinks may be genuinely mono. The
# value is refreshed whenever a stream opens; stereo remains the safe
@@ -467,6 +479,13 @@ class AudioPlayer:
self._play_lock = asyncio.Lock()
return self._play_lock
+ def _get_stream_state_lock(self) -> threading.Lock:
+ lock = getattr(self, "_stream_state_lock", None)
+ if lock is None:
+ lock = threading.Lock()
+ self._stream_state_lock = lock
+ return lock
+
def invalidate_device_cache(self) -> None:
"""Forget every cached device_rate and tear down the active stream.
@@ -479,11 +498,16 @@ class AudioPlayer:
success when the underlying device has vanished — the audio just
evaporates silently. Forcing the cascade on swap is the safe path.
"""
- if self._active_stream is not None:
- self._close_output_stream(self._active_stream)
+ with self._get_stream_state_lock():
+ self._playback_generation = (
+ getattr(self, "_playback_generation", 0) + 1
+ )
+ stream = self._active_stream
self._active_stream = None
self._active_source_rate = None
self._active_device_rate = None
+ if stream is not None:
+ self._close_output_stream(stream)
self._device_rate_cache.clear()
def set_device(self, device: int | str | None) -> None:
@@ -784,11 +808,11 @@ class AudioPlayer:
rejected by ``should_play``, returns ``False``. Callers use this receipt
to keep the audible transcript free of text that never reached output.
- ``should_play`` is an optional staleness predicate evaluated ONCE right
- after the play lock is acquired (and before any audio is written). When
- it returns False the playback is dropped silently — the ack preamble
- uses this so it is never voiced once the main answer has started
- speaking (2026-06-20 'preamble after the answer' defense-in-depth).
+ ``should_play`` is an optional staleness predicate evaluated after the
+ play lock is acquired and before each buffered write. When it returns
+ False the playback is dropped silently — the ack preamble uses this so
+ it is never voiced once the main answer has started speaking (2026-06-20
+ 'preamble after the answer' defense-in-depth).
History — what went wrong before:
* First version: ``sd.play(blocking=True)`` **per chunk** — each
@@ -811,6 +835,9 @@ class AudioPlayer:
appended seamlessly → no discontinuity, no clicks.
"""
self._log_device_once()
+ stream_state_lock = self._get_stream_state_lock()
+ with stream_state_lock:
+ playback_generation = getattr(self, "_playback_generation", 0)
owner_task = asyncio.current_task()
owner_task_id = id(owner_task) if owner_task is not None else None
# Reset the playback-progress watchdog signal at the START of every
@@ -868,36 +895,64 @@ class AudioPlayer:
# Reuse the persistent OutputStream across sentence-by-sentence
# play_chunks() calls — closing+reopening per sentence is what
# caused the "haaaaa lalala oooo" stretch (see __init__ comment).
- if (
- self._active_stream is not None
- and self._active_source_rate == needed_rate
- ):
- assert self._active_device_rate is not None
- return self._active_stream, self._active_device_rate
- # Rate change or initial open: close the old stream, open a new one
- if self._active_stream is not None:
- self._close_output_stream(self._active_stream)
+ with stream_state_lock:
+ if (
+ getattr(self, "_playback_generation", 0)
+ != playback_generation
+ ):
+ raise _PlaybackSuperseded
+ if (
+ self._active_stream is not None
+ and self._active_source_rate == needed_rate
+ ):
+ assert self._active_device_rate is not None
+ return self._active_stream, self._active_device_rate
+ old_stream = self._active_stream
self._active_stream = None
+ self._active_source_rate = None
+ self._active_device_rate = None
+ # Stream open is intentionally outside the state lock: stop()
+ # must remain immediate even when PortAudio setup is slow.
+ if old_stream is not None:
+ self._close_output_stream(old_stream)
new_stream, device_rate = self._open_output_stream(needed_rate)
- self._active_stream = new_stream
- self._active_source_rate = needed_rate
- self._active_device_rate = device_rate
- return new_stream, device_rate
+ with stream_state_lock:
+ if (
+ getattr(self, "_playback_generation", 0)
+ == playback_generation
+ ):
+ self._active_stream = new_stream
+ self._active_source_rate = needed_rate
+ self._active_device_rate = device_rate
+ return new_stream, device_rate
+ # stop() won while the worker opened PortAudio. Close the late
+ # handle locally; never publish it as the active stream.
+ self._close_output_stream(new_stream)
+ raise _PlaybackSuperseded
pending = bytearray()
pending_rate: int | None = None
first_audio_published = False
- async def _flush_pending(*, final: bool = False) -> None:
+ async def _flush_pending(*, final: bool = False) -> bool:
nonlocal pending, pending_rate, first_audio_published
if not pending or pending_rate is None:
- return
+ return True
min_bytes = int(pending_rate * TTS_WRITE_BUFFER_MS / 1000) * 2
if not final and len(pending) < min_bytes:
- return
+ return True
+ if should_play is not None and not should_play():
+ pending.clear()
+ return False
pcm = bytes(pending)
pending.clear()
- stm, dev_rate = await asyncio.to_thread(_ensure_stream, pending_rate)
+ try:
+ stm, dev_rate = await asyncio.to_thread(
+ _ensure_stream, pending_rate
+ )
+ except _PlaybackSuperseded:
+ pending.clear()
+ return False
arr = np.frombuffer(pcm, dtype=np.int16)
# Tell the UI how long this block will be audible BEFORE the
# blocking write below. _write_samples blocks for the whole
@@ -926,6 +981,7 @@ class AudioPlayer:
log.info("AudioOutFirst published")
except Exception as exc: # noqa: BLE001
log.debug("AudioOutFirst publish failed: %s", exc)
+ return True
# NOTE: no finally-close — the stream stays open across play_chunks
# calls and is only torn down by stop() (barge-in) or by the next
@@ -934,11 +990,14 @@ class AudioPlayer:
if not chunk.pcm:
continue
if pending_rate is not None and chunk.sample_rate != pending_rate:
- await _flush_pending(final=True)
+ if not await _flush_pending(final=True):
+ return False
pending_rate = chunk.sample_rate
pending.extend(chunk.pcm)
- await _flush_pending()
- await _flush_pending(final=True)
+ if not await _flush_pending():
+ return False
+ if not await _flush_pending(final=True):
+ return False
return self.frames_written > 0
def abort_active(self) -> None:
@@ -953,10 +1012,14 @@ class AudioPlayer:
(PortAudio abort behaves identically on Windows/macOS/Linux).
"""
level_tap.reset_playing()
- stream = self._active_stream
- self._active_stream = None
- self._active_source_rate = None
- self._active_device_rate = None
+ with self._get_stream_state_lock():
+ self._playback_generation = (
+ getattr(self, "_playback_generation", 0) + 1
+ )
+ stream = self._active_stream
+ self._active_stream = None
+ self._active_source_rate = None
+ self._active_device_rate = None
if stream is not None:
try:
stream.abort()
@@ -980,10 +1043,14 @@ class AudioPlayer:
# Barge-in discards the buffered tail, so the UI must stop showing the
# speaking equalizer for audio that will never play.
level_tap.reset_playing()
- stream = self._active_stream
- self._active_stream = None
- self._active_source_rate = None
- self._active_device_rate = None
+ with self._get_stream_state_lock():
+ self._playback_generation = (
+ getattr(self, "_playback_generation", 0) + 1
+ )
+ stream = self._active_stream
+ self._active_stream = None
+ self._active_source_rate = None
+ self._active_device_rate = None
if stream is not None:
try:
stream.abort()
diff --git a/jarvis/speech/pipeline.py b/jarvis/speech/pipeline.py
index 2b86241a79..1ad3c18f5c 100644
--- a/jarvis/speech/pipeline.py
+++ b/jarvis/speech/pipeline.py
@@ -6102,6 +6102,14 @@ class SpeechPipeline:
barge_feed_executor = ThreadPoolExecutor(
max_workers=1, thread_name_prefix=f"rt-barge-feed-{session_id}"
)
+ # Provider PCM is owned by ``playback``; the independent surface-TTS
+ # fallback used to bypass that adapter and was awaited inline. A barge
+ # then stopped PortAudio but left the TTS producer alive, so its next
+ # chunk reopened the stream and resumed untracked speech. Keep explicit
+ # ownership of that producer so every output-cancel boundary can stop
+ # generation before it aborts the shared player.
+ surface_playback_task: asyncio.Task[Any] | None = None
+ surface_playback_epoch = 0
turn_complete = asyncio.Event()
speaking = False
post_output_echo_guard_until = 0.0
@@ -6149,6 +6157,25 @@ class SpeechPipeline:
_warm_barge_detector(), name=f"rt-barge-warm-{session_id}"
)
+ async def _cancel_output_playback() -> None:
+ """Cancel surface generation and provider playback as one unit."""
+
+ nonlocal surface_playback_epoch, surface_playback_task
+ # Invalidate the parent callback before cancelling its child. A new
+ # surface fallback may start while the old callback is unwinding;
+ # only the newest epoch may close the shared speaking segment.
+ surface_playback_epoch += 1
+ surface_task = surface_playback_task
+ surface_playback_task = None
+ if surface_task is not None and not surface_task.done():
+ # Cancel before AudioPlayer.stop(): a blocked native write can
+ # still unwind after the abort, but the owning coroutine can no
+ # longer advance its async generator and reopen the stream.
+ surface_task.cancel()
+ await playback.cancel()
+ if surface_task is not None:
+ await asyncio.gather(surface_task, return_exceptions=True)
+
async def _send_binary(pcm: bytes) -> None:
nonlocal post_output_echo_guard_until
nonlocal semantic_turn_committed, speaking
@@ -6162,6 +6189,7 @@ class SpeechPipeline:
async def _send_json(message: dict[str, Any]) -> None:
nonlocal semantic_turn_committed, speaking
+ nonlocal surface_playback_epoch, surface_playback_task
kind = str(message.get("type", ""))
if kind == "audio_ready":
if speaking:
@@ -6219,12 +6247,12 @@ class SpeechPipeline:
await self._set_turn_state(TurnTakingState.PROCESSING)
elif kind == "tts_cancel":
_close_output_segment(preserve_echo_tail=False)
- await playback.cancel()
+ await _cancel_output_playback()
await self._set_turn_state(TurnTakingState.LISTENING)
elif kind == "hangup":
semantic_turn_committed = True
_close_output_segment(preserve_echo_tail=False)
- await playback.cancel()
+ await _cancel_output_playback()
elif kind == "turn_complete":
semantic_turn_committed = True
await playback.finish_turn()
@@ -6275,7 +6303,9 @@ class SpeechPipeline:
# AudioPlayer as an independent last mile. The existing mic
# pump and local barge detector remain active, so this does
# not open a second microphone or replay the user's request.
- await playback.cancel()
+ await _cancel_output_playback()
+ surface_playback_epoch += 1
+ active_surface_epoch = surface_playback_epoch
speaking = True
barge_detector.start_output()
# Pre-synthesis registration mirrors _speak (BUG-084): the
@@ -6284,6 +6314,11 @@ class SpeechPipeline:
# (BUG-089).
self._register_assistant_speech(cleaned)
await self._set_turn_state(TurnTakingState.JARVIS_SPEAKING)
+ if surface_playback_epoch != active_surface_epoch:
+ # A cancel can arrive while the state callback yields,
+ # before there is a child playback task to own. Its
+ # epoch invalidates this render before synthesis starts.
+ return
try:
# Voice-identity continuity: the realtime session names
# the voice it was speaking with, so this last mile does
@@ -6330,7 +6365,30 @@ class SpeechPipeline:
)
except TypeError:
chunks = surface_tts.synthesize(cleaned)
- playback_result = await self._player.play_chunks(chunks)
+ active_surface_task = asyncio.create_task(
+ self._player.play_chunks(
+ chunks,
+ should_play=lambda: (
+ surface_playback_epoch
+ == active_surface_epoch
+ ),
+ ),
+ name=f"rt-surface-tts-{session_id}",
+ )
+ surface_playback_task = active_surface_task
+ try:
+ playback_result = await active_surface_task
+ except asyncio.CancelledError:
+ current_task = asyncio.current_task()
+ if current_task is not None and current_task.cancelling():
+ raise
+ # A concurrent local barge-in cancels the owned child
+ # task, not this provider-pump callback. The turn stays
+ # alive and simply records no spoken receipt.
+ playback_result = False
+ finally:
+ if surface_playback_task is active_surface_task:
+ surface_playback_task = None
if self._playback_confirmed(playback_result):
self._emit_spoken(
cleaned,
@@ -6344,10 +6402,11 @@ class SpeechPipeline:
exc,
)
finally:
- _close_output_segment(
- preserve_echo_tail=speaking,
- )
- await self._set_turn_state(TurnTakingState.LISTENING)
+ if surface_playback_epoch == active_surface_epoch:
+ _close_output_segment(
+ preserve_echo_tail=speaking,
+ )
+ await self._set_turn_state(TurnTakingState.LISTENING)
elif kind == "provider_error":
log.warning("Realtime desktop status: %s", message)
@@ -6564,6 +6623,9 @@ class SpeechPipeline:
finally:
if getattr(self, "_active_realtime_handle", None) is session:
self._active_realtime_handle = None
+ # Invalidate even when synthesis is paused before child-task
+ # creation; terminal teardown must own that pre-playback window too.
+ await _cancel_output_playback()
barge_detector.stop_output()
barge_feed_executor.shutdown(wait=False, cancel_futures=True)
if not barge_warm_task.done():
diff --git a/tests/unit/audio/test_player_persistent_stream.py b/tests/unit/audio/test_player_persistent_stream.py
index 820753ee28..c4abbb9bf0 100644
--- a/tests/unit/audio/test_player_persistent_stream.py
+++ b/tests/unit/audio/test_player_persistent_stream.py
@@ -22,10 +22,12 @@ These tests pin that contract.
from __future__ import annotations
import asyncio
+import threading
from collections.abc import AsyncIterator
import pytest
+import jarvis.audio.player as player_module
from jarvis.audio.player import AudioPlayer
from jarvis.core.protocols import AudioChunk
@@ -178,6 +180,39 @@ async def test_stop_is_idempotent_when_no_stream(monkeypatch) -> None:
player.stop() # idempotent
+async def test_stop_rejects_stream_that_finishes_opening_after_cancel(
+ monkeypatch,
+) -> None:
+ """A worker-thread stream open cannot resurrect stopped playback."""
+
+ player, events = _make_player(monkeypatch)
+ open_entered = threading.Event()
+ release_open = threading.Event()
+
+ def delayed_open(needed_rate: int):
+ events.append(f"open@{needed_rate}")
+ open_entered.set()
+ assert release_open.wait(timeout=1.0)
+ return object(), needed_rate
+
+ monkeypatch.setattr(player, "_open_output_stream", delayed_open)
+ if player_module.sd is not None:
+ monkeypatch.setattr(player_module.sd, "stop", lambda: None)
+
+ pcm = b"\x01\x00" * 4000
+ play_task = asyncio.create_task(player.play_chunks(_one_chunk(pcm)))
+ assert await asyncio.to_thread(open_entered.wait, 1.0)
+
+ player.stop()
+ release_open.set()
+
+ assert await asyncio.wait_for(play_task, timeout=1.0) is False
+ assert [event for event in events if event == "close"] == ["close"]
+ assert [event for event in events if event.startswith("write@")] == []
+ assert player._active_stream is None
+
+
@pytest.mark.asyncio
async def test_multi_sentence_brain_response_keeps_one_stream(monkeypatch) -> None:
"""Simulates the streaming-TTS pipeline: 5 sentences in one brain
diff --git a/tests/unit/realtime/test_session.py b/tests/unit/realtime/test_session.py
index 82b71e2df4..137a8855f2 100644
--- a/tests/unit/realtime/test_session.py
+++ b/tests/unit/realtime/test_session.py
@@ -4695,13 +4695,27 @@ async def test_transport_death_rebuilds_the_session_in_place():
@pytest.mark.asyncio
async def test_audio_send_timeout_rebuilds_without_ending_the_call(monkeypatch):
- """A write-only Gemini stall must heal even while receive stays open."""
+ """A write-only stall and a later stale timeout preserve the live call."""
import jarvis.realtime.session as session_module
- monkeypatch.setattr(session_module, "_AUDIO_SEND_TIMEOUT_S", 0.01)
+ class _ObservedWriteStalledSession(WriteStalledSession):
+ def __init__(self):
+ super().__init__([])
+ self.send_entered = [asyncio.Event(), asyncio.Event()]
+ self._send_count = 0
+
+ async def send_audio(self, chunk):
+ del chunk
+ index = self._send_count
+ self._send_count += 1
+ self.send_entered[index].set()
+ await asyncio.Event().wait()
+
+ stalled = _ObservedWriteStalledSession()
+ monkeypatch.setattr(session_module, "_AUDIO_SEND_TIMEOUT_S", 0.02)
provider = RebuildingProvider(
[
- lambda: WriteStalledSession([]),
+ lambda: stalled,
lambda: StayOpenSession([]),
]
)
@@ -4721,17 +4735,24 @@ async def test_audio_send_timeout_rebuilds_without_ending_the_call(monkeypatch):
first_send = asyncio.create_task(
sess.handle_audio_frame(b"\x00\x01" * 16)
)
- await asyncio.sleep(0.01)
+ await asyncio.wait_for(stalled.send_entered[0].wait(), timeout=0.5)
+ # ``wait_for`` captured the short deadline for send one. Give send two a
+ # longer deadline so the first timeout deterministically rebuilds the
+ # transport before the overlapping stale timeout is delivered.
+ monkeypatch.setattr(session_module, "_AUDIO_SEND_TIMEOUT_S", 0.15)
overlapping_send = asyncio.create_task(
sess.handle_audio_frame(b"\x01\x02" * 16)
)
- await asyncio.gather(first_send, overlapping_send)
+ await asyncio.wait_for(stalled.send_entered[1].wait(), timeout=0.5)
+ await first_send
await _wait_until(lambda: provider.open_calls == 2)
+ await overlapping_send
assert sess._pump_task is pump
assert pump is not None and not pump.done()
assert not sess.failed
assert provider.sessions[0].closed
+ assert provider.open_calls == 2
assert len([item for item in jsons if item.get("type") == "audio_ready"]) == 2
await sess.handle_audio_frame(b"\x02\x03" * 16)
diff --git a/tests/unit/speech/test_realtime_mode.py b/tests/unit/speech/test_realtime_mode.py
index 77566c0dc1..64e8ef9f82 100644
--- a/tests/unit/speech/test_realtime_mode.py
+++ b/tests/unit/speech/test_realtime_mode.py
@@ -25,8 +25,10 @@ class _FakePlayer:
self.pcm: list[bytes] = []
self.stopped = 0
- async def play_chunks(self, chunks) -> None:
+ async def play_chunks(self, chunks, *, should_play=None) -> None:
async for chunk in chunks:
+ if should_play is not None and not should_play():
+ return
self.pcm.append(chunk.pcm)
def stop(self) -> None:
@@ -332,7 +334,10 @@ async def test_unsafe_output_cancel_stops_playback_and_returns_to_listening(
monkeypatch.setattr(pipeline_mod, "MicrophoneCapture", lambda **_kwargs: _SilentMic())
task = asyncio.create_task(pipe._active_realtime_session())
- await asyncio.wait_for(cancel_delivered.wait(), timeout=0.5)
+ # Session construction lazily imports the realtime stack and can exceed a
+ # 0.5 s wall-clock budget when this test follows other audio tests on the
+ # slower macOS CI runner. The event itself remains the deterministic gate.
+ await asyncio.wait_for(cancel_delivered.wait(), timeout=2.0)
await asyncio.sleep(0)
assert pipe._player.stopped >= 1
@@ -345,7 +350,7 @@ async def test_unsafe_output_cancel_stops_playback_and_returns_to_listening(
]
pipe._hangup_event.set()
- assert await asyncio.wait_for(task, timeout=0.5) == HANGUP_HOTKEY
+ assert await asyncio.wait_for(task, timeout=1.0) == HANGUP_HOTKEY
assert built["session"].end_reason == HANGUP_HOTKEY
@@ -408,6 +413,188 @@ async def test_error_spoken_renders_through_realtime_scoped_surface_tts(
assert await asyncio.wait_for(task, timeout=0.5) == HANGUP_HOTKEY
+ "cancel_before_first_chunk",
+ [True, False],
+ ids=("during-synthesis", "between-chunks"),
+)
+async def test_tts_cancel_stops_surface_generator_before_it_can_reopen_output(
+ monkeypatch: pytest.MonkeyPatch,
+ cancel_before_first_chunk: bool,
+) -> None:
+ """A local barge-in owns both PortAudio and the surface-TTS producer.
+
+ Stopping only the shared player left the async producer alive. Its next
+ chunk reopened PortAudio after the turn had returned to LISTENING, creating
+ untracked zombie speech and blocking the realtime callback behind it.
+ """
+
+ pipe = _pipe()
+ first_pcm = b"\x11\x00" * 32
+ zombie_pcm = b"\x22\x00" * 32
+ synthesis_started = asyncio.Event()
+ first_chunk_consumed = asyncio.Event()
+ release_first = asyncio.Event()
+ release_second = asyncio.Event()
+ generator_closed = asyncio.Event()
+ cancel_delivered = asyncio.Event()
+ spoken_receipts: list[str] = []
+ pipe._emit_spoken = ( # type: ignore[method-assign]
+ lambda text, *_args, **_kwargs: spoken_receipts.append(text)
+ )
+
+ class _TwoChunkSurfaceTTS:
+ def synthesize(
+ self,
+ _text: str,
+ *,
+ language_code: str | None = None,
+ ):
+ del language_code
+
+ async def _chunks():
+ try:
+ synthesis_started.set()
+ if cancel_before_first_chunk:
+ await release_first.wait()
+ yield AudioChunk(
+ pcm=first_pcm,
+ sample_rate=24_000,
+ timestamp_ns=0,
+ )
+ first_chunk_consumed.set()
+ await release_second.wait()
+ yield AudioChunk(
+ pcm=zombie_pcm,
+ sample_rate=24_000,
+ timestamp_ns=0,
+ )
+ finally:
+ generator_closed.set()
+
+ return _chunks()
+
+ surface_tts = _TwoChunkSurfaceTTS()
+ monkeypatch.setattr(
+ "jarvis.plugins.tts.build_realtime_surface_tts",
+ lambda _cfg, _provider: surface_tts,
+ )
+
+ class _SurfaceCancelSession(_HandshakeOnlyRealtimeSession):
+ async def handle_control(self, message) -> None:
+ await super().handle_control(message)
+ surface_callback = asyncio.create_task(
+ self._send_json(
+ {
+ "type": "error_spoken",
+ "text": "A grounded answer with two audio chunks.",
+ "language": "en",
+ }
+ )
+ )
+ if cancel_before_first_chunk:
+ await synthesis_started.wait()
+ else:
+ await first_chunk_consumed.wait()
+
+ await self._send_json({"type": "tts_cancel"})
+ release_first.set()
+ release_second.set()
+ await asyncio.wait_for(surface_callback, timeout=0.5)
+ cancel_delivered.set()
+
+ def _build(**kwargs):
+ return _SurfaceCancelSession(kwargs["send_binary"], kwargs["send_json"])
+
+ monkeypatch.setattr("jarvis.realtime.factory.build_realtime_session", _build)
+ monkeypatch.setattr(
+ pipeline_mod,
+ "MicrophoneCapture",
+ lambda **_kwargs: _SilentMic(),
+ )
+
+ task = asyncio.create_task(pipe._active_realtime_session())
+ await asyncio.wait_for(cancel_delivered.wait(), timeout=0.5)
+ await asyncio.sleep(0)
+
+ assert (first_pcm in pipe._player.pcm) is not cancel_before_first_chunk
+ assert zombie_pcm not in pipe._player.pcm
+ assert generator_closed.is_set()
+ assert spoken_receipts == []
+ assert pipe._player.stopped >= 1
+ assert not task.done(), "surface cancellation must not end the live call"
+
+ pipe._hangup_event.set()
+ assert await asyncio.wait_for(task, timeout=0.5) == HANGUP_HOTKEY
+
+
+async def test_tts_cancel_invalidates_surface_render_before_task_creation(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """A cancel during the speaking-state callback prevents late synthesis."""
+
+ pipe = _pipe()
+ surface_tts = _FakeTTS(b"\x33\x00" * 32)
+ speaking_state_entered = asyncio.Event()
+ release_speaking_state = asyncio.Event()
+ cancel_delivered = asyncio.Event()
+
+ async def _set_state(state) -> None:
+ pipe._test_states.append(state)
+ if state == pipeline_mod.TurnTakingState.JARVIS_SPEAKING:
+ speaking_state_entered.set()
+ await release_speaking_state.wait()
+
+ pipe._set_turn_state = _set_state # type: ignore[method-assign]
+ monkeypatch.setattr(
+ "jarvis.plugins.tts.build_realtime_surface_tts",
+ lambda _cfg, _provider: surface_tts,
+ )
+
+ class _PrePlaybackCancelSession(_HandshakeOnlyRealtimeSession):
+ async def handle_control(self, message) -> None:
+ await super().handle_control(message)
+ surface_callback = asyncio.create_task(
+ self._send_json(
+ {
+ "type": "error_spoken",
+ "text": "This render must never start.",
+ "language": "en",
+ }
+ )
+ )
+ await speaking_state_entered.wait()
+ await self._send_json({"type": "tts_cancel"})
+ release_speaking_state.set()
+ await asyncio.wait_for(surface_callback, timeout=0.5)
+ cancel_delivered.set()
+
+ def _build(**kwargs):
+ return _PrePlaybackCancelSession(
+ kwargs["send_binary"], kwargs["send_json"]
+ )
+
+ monkeypatch.setattr("jarvis.realtime.factory.build_realtime_session", _build)
+ monkeypatch.setattr(
+ pipeline_mod,
+ "MicrophoneCapture",
+ lambda **_kwargs: _SilentMic(),
+ )
+
+ task = asyncio.create_task(pipe._active_realtime_session())
+ await asyncio.wait_for(cancel_delivered.wait(), timeout=0.5)
+
+ assert surface_tts.calls == []
+ assert pipe._player.pcm == []
+ assert pipe._test_states[-1] == pipeline_mod.TurnTakingState.LISTENING
+ assert not task.done(), "pre-playback cancellation must not end the live call"
+
+ pipe._hangup_event.set()
+ assert await asyncio.wait_for(task, timeout=0.5) == HANGUP_HOTKEY
+
+
@pytest.mark.asyncio
async def test_error_spoken_without_realtime_scoped_tts_never_borrows_pipeline_voice(
monkeypatch: pytest.MonkeyPatch,