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): prevent realtime speaker feedback

Ruben Lütke0d86446ee8a3
diff --git a/docs/BUGS.md b/docs/BUGS.md
index 61fc8fa055..0e45437662 100644
--- a/docs/BUGS.md
+++ b/docs/BUGS.md
@@ -6880,3 +6880,62 @@ all three desktop platforms before removing the pending qualifier.
not normalize every newly observed peak to full scale. Peak auto-gain is useful
for recognition input; it destroys the relative amplitude information that a
user-facing level indicator exists to show.
+
+---
+
+## BUG-100: high-latency speaker drain becomes a phantom user turn, and terminal teardown leaks a PortAudio task (CRITICAL, FIXED IN CODE 2026-07-20; HARDWARE VALIDATION PENDING)
+
+**Symptom.** Realtime voice session
+`fe594a99-3d8b-4b37-bb62-d481f02ba595` answered normally, then transcribed the
+last words coming from its own speakers as new user input. The assistant reply
+ending in `Was ansteht.` was followed by a user-role transcript containing
+exactly `Was ansteht.`. Earlier sessions show the same suffix pattern with
+`Bescheid.` and `dir?`. <!-- i18n-allow: forensic quotes from runtime voice transcripts -->
+The same run also emitted an unobserved task exception while the hotkey ended
+playback: `sounddevice.PortAudioError: Internal PortAudio error [PaErrorCode
+-9986]`.
+
+**Reconstruction.** The affected Mac used its built-in speakers and microphone.
+PortAudio reported `0.869 s` of output latency, while the realtime half-duplex
+tail was a fixed `0.5 s`. `DesktopRealtimePlayback.finish_turn()` established
+that queued PCM had been accepted by the output stream, but did not establish
+that the physical device buffer was silent. The microphone therefore reopened
+about `0.369 s` before the reported hardware horizon ended. One- and two-word
+suffixes also fall below the text `SelfEchoGuard` minimum of three tokens, so
+the later transcript layer correctly did not guess that those short utterances
+were echo. Separately, terminal cancellation aborted a blocking native write
+while a provider callback was still unwinding. That callback could recreate
+the desktop playback task, and Core Audio surfaced the intentional abort as
+PortAudio error `-9986` after its owner had already detached.
+
+**Fix.** `AudioPlayer` now exposes the active stream's validated, bounded
+PortAudio output latency. Every completed realtime output segment keeps
+microphone frames local for that device latency plus the existing acoustic
+tail. The local CPU barge-in detector remains active throughout the interval,
+so confirmed human speech is forwarded immediately instead of being muted with
+the echo. Missing or malformed latency metadata falls back to zero and retains
+the conservative fixed tail.
+
+`DesktopRealtimePlayback.close()` is now terminal: it latches the surface
+closed before cancellation, rejects every later provider PCM callback, and
+observes detached task results. Pipeline teardown closes this boundary before
+quiescing the provider and repeats the idempotent close after `session.end()`.
+`AudioPlayer` tags native writes with their playback generation and suppresses
+a PortAudio write error only when the generation or stream owner proves that
+an intentional cancellation already won; unrelated live-device failures still
+propagate.
+
+**Guards and platform parity.** Regression coverage reproduces a `150 ms`
+device latency against a deliberately expired fixed guard, proves both the
+speaker suffix and an immediate real interruption stay on the correct paths,
+rejects PCM delivered by `session.end()`, and raises PortAudio `-9986` from a
+write concurrently aborted by `stop()`. The output-latency property is part of
+PortAudio's cross-platform stream contract and adds no macOS-only import or
+device selection. Windows and Linux use the same path; a headless player with
+no active stream reports zero and retains the fixed guard. Physical validation
+on updated macOS, Windows, and Linux installations remains pending.
+
+**Class rule.** Queue drain is not acoustic drain. A half-duplex boundary must
+cover the output device's reported hardware latency, while terminal teardown
+must seal every producer callback before aborting its native stream. Expected
+abort errors may be suppressed only with positive ownership evidence.
diff --git a/jarvis/audio/player.py b/jarvis/audio/player.py
index 09ac74a9cb..7ed5822e1e 100644
--- a/jarvis/audio/player.py
+++ b/jarvis/audio/player.py
@@ -10,6 +10,7 @@ from __future__ import annotations
import asyncio
import logging
+import math
import threading
import time
from collections.abc import AsyncIterator, Callable, Sequence
@@ -43,6 +44,7 @@ _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
class _PlaybackSuperseded(RuntimeError):
@@ -486,6 +488,33 @@ class AudioPlayer:
self._stream_state_lock = lock
return lock
+ @property
+ def output_latency_s(self) -> float:
+ """Return the active device's bounded PortAudio output latency.
+
+ Blocking ``OutputStream.write()`` returns after PortAudio accepts a
+ buffer, not necessarily after the device has made every accepted frame
+ audible. Realtime half-duplex uses this value to keep microphone audio
+ local until that hardware buffer has drained. Missing, malformed, or
+ implausible backend values fail safely to zero so headless and test
+ players retain the conservative fixed tail guard.
+ """
+
+ try:
+ with self._get_stream_state_lock():
+ stream = getattr(self, "_active_stream", None)
+ if stream is None:
+ return 0.0
+ raw_latency = getattr(stream, "latency", 0.0)
+ if isinstance(raw_latency, (tuple, list)):
+ raw_latency = raw_latency[-1] if raw_latency else 0.0
+ latency = float(raw_latency)
+ except (AttributeError, TypeError, ValueError, _PortAudioError):
+ return 0.0
+ if not math.isfinite(latency) or latency <= 0.0:
+ return 0.0
+ return min(latency, _MAX_REPORTED_OUTPUT_LATENCY_S)
+
def invalidate_device_cache(self) -> None:
"""Forget every cached device_rate and tear down the active stream.
@@ -702,6 +731,8 @@ class AudioPlayer:
arr: np.ndarray,
source_rate: int,
device_rate: int,
+ *,
+ playback_generation: int | None = None,
) -> None:
"""Int16 mono → float32 device channels + resample + ``stream.write()``.
@@ -764,7 +795,27 @@ class AudioPlayer:
block = max(1, int(device_rate * 0.06))
for start in range(0, arr_out.shape[0], block):
out = arr_out[start:start + block]
- underflowed = stream.write(out)
+ try:
+ underflowed = stream.write(out)
+ except _PortAudioError:
+ # ``stop()`` deliberately aborts the native stream while this
+ # blocking write may still be running in a worker thread. Core
+ # Audio and several Windows backends report that expected abort
+ # as a PortAudio error. Suppress it only when the generation or
+ # stream owner proves cancellation won; a live-device failure
+ # still propagates to the caller.
+ if playback_generation is None:
+ raise
+ with self._get_stream_state_lock():
+ cancelled = (
+ getattr(self, "_playback_generation", 0)
+ != playback_generation
+ or getattr(self, "_active_stream", None) is not stream
+ )
+ if not cancelled:
+ raise
+ log.debug("PortAudio write ended after playback cancellation")
+ return
# Playback progress for the pipeline stall watchdog: a healthy
# ~60 ms sub-block returns well inside the watchdog's stall window;
# only a wedged device leaves ``last_write_ns`` frozen. ``getattr``
@@ -968,8 +1019,21 @@ class AudioPlayer:
# level per flush). Nothing to feed here.
self.last_write_owner_task_id = owner_task_id
await asyncio.to_thread(
- self._write_samples, stm, arr, pending_rate, dev_rate
+ self._write_samples,
+ stm,
+ arr,
+ pending_rate,
+ dev_rate,
+ playback_generation=playback_generation,
)
+ with stream_state_lock:
+ playback_superseded = (
+ getattr(self, "_playback_generation", 0)
+ != playback_generation
+ or getattr(self, "_active_stream", None) is not stm
+ )
+ if playback_superseded:
+ return False
# First audible sample reached PortAudio — tell the bus so the
# mascot mouth + SPEAKING bubble sync to actual audio start
# instead of the speculative SPEAKING state-transition.
diff --git a/jarvis/realtime/desktop.py b/jarvis/realtime/desktop.py
index a326f36145..3c5306ad63 100644
--- a/jarvis/realtime/desktop.py
+++ b/jarvis/realtime/desktop.py
@@ -3,6 +3,7 @@
from __future__ import annotations
import asyncio
+import logging
import time
from collections import deque
from collections.abc import AsyncIterator, Callable
@@ -13,6 +14,8 @@ import numpy as np
from jarvis.audio.vad import VAD_FRAME_SAMPLES, SileroEndpointer
from jarvis.core.protocols import AudioChunk
+log = logging.getLogger("jarvis.realtime.desktop")
+
class DesktopRealtimeBargeInDetector:
"""Detect deliberate desktop barge-in on the existing microphone stream.
@@ -303,9 +306,10 @@ class DesktopRealtimePlayback:
self._finish_timeout_s = max(1.0, float(finish_timeout_s))
self._queue: asyncio.Queue[AudioChunk | None] | None = None
self._task: asyncio.Task[None] | None = None
+ self._closed = False
async def send_binary(self, pcm: bytes) -> None:
- if not pcm:
+ if not pcm or self._closed:
return
if self._task is None or self._task.done():
self._queue = asyncio.Queue(maxsize=self._max_queue_chunks)
@@ -313,6 +317,11 @@ class DesktopRealtimePlayback:
self._player.play_chunks(self._chunks(self._queue)),
name="realtime-desktop-playback",
)
+ # A terminal surface cancellation can race a provider callback
+ # that is already unwinding. Always retrieve the native playback
+ # result even if that callback loses its final await; explicit
+ # ``finish_turn`` callers still receive the same exception.
+ self._task.add_done_callback(self._observe_playback_result)
assert self._queue is not None
await self._queue.put(
AudioChunk(pcm=bytes(pcm), sample_rate=self._sample_rate, timestamp_ns=0)
@@ -398,8 +407,23 @@ class DesktopRealtimePlayback:
# playback exception while the task unwinds.
async def close(self) -> None:
+ # Terminal close differs from an ordinary barge-in ``cancel``: later
+ # provider callbacks belong to a dead voice surface and must never
+ # create a fresh OutputStream after teardown has started.
+ self._closed = True
await self.cancel()
+ @staticmethod
+ def _observe_playback_result(task: asyncio.Task[None]) -> None:
+ if task.cancelled():
+ return
+ try:
+ exc = task.exception()
+ except asyncio.CancelledError:
+ return
+ if exc is not None:
+ log.debug("Realtime desktop playback task ended with %r", exc)
+
def _detach(
self,
) -> tuple[asyncio.Queue[AudioChunk | None] | None, asyncio.Task[None] | None]:
diff --git a/jarvis/speech/pipeline.py b/jarvis/speech/pipeline.py
index 1ad3c18f5c..f65363edb1 100644
--- a/jarvis/speech/pipeline.py
+++ b/jarvis/speech/pipeline.py
@@ -604,6 +604,7 @@ def _stt_retry_delay(exc: BaseException | None, attempt: int) -> float:
_SESSION_START_BUFFER_MAX_BYTES = 16_000 * 2 * 30 # 30 s of mono PCM16
_REALTIME_POST_OUTPUT_ECHO_GUARD_S = 0.5
+_REALTIME_OUTPUT_LATENCY_CAP_S = 5.0
def _feed_live_mic_level(chunk: AudioChunk) -> None:
@@ -6110,6 +6111,7 @@ class SpeechPipeline:
# generation before it aborts the shared player.
surface_playback_task: asyncio.Task[Any] | None = None
surface_playback_epoch = 0
+ terminal_output_closed = False
turn_complete = asyncio.Event()
speaking = False
post_output_echo_guard_until = 0.0
@@ -6120,14 +6122,21 @@ class SpeechPipeline:
# answer a late speaker echo of realtime output (BUG-089).
assistant_transcript_parts: list[str] = []
+ def _reported_output_latency_s() -> float:
+ try:
+ latency = float(getattr(self._player, "output_latency_s", 0.0))
+ except (TypeError, ValueError):
+ return 0.0
+ return min(_REALTIME_OUTPUT_LATENCY_CAP_S, max(0.0, latency))
+
def _close_output_segment(*, preserve_echo_tail: bool) -> None:
"""Keep half-duplex protection through physical speaker drain."""
nonlocal post_output_echo_guard_until, speaking
was_audible = speaking or bool(assistant_transcript_parts)
speaking = False
- # The physical drain has completed here (callers await
- # playback.finish_turn() first), so the guard's activity stamp is
- # accurate at this moment.
+ # The provider queue has drained here, but a persistent PortAudio
+ # stream may still hold up to one reported device-latency of audio.
+ # Include that hardware horizon before the ordinary acoustic tail.
if assistant_transcript_parts:
self._register_assistant_speech(
" ".join(assistant_transcript_parts)
@@ -6136,8 +6145,14 @@ class SpeechPipeline:
elif was_audible:
self._touch_assistant_speech_activity()
if preserve_echo_tail:
- post_output_echo_guard_until = (
- time.monotonic() + _REALTIME_POST_OUTPUT_ECHO_GUARD_S
+ output_latency_s = _reported_output_latency_s()
+ guard_s = _REALTIME_POST_OUTPUT_ECHO_GUARD_S + output_latency_s
+ post_output_echo_guard_until = time.monotonic() + guard_s
+ log.info(
+ "Realtime echo tail armed for %.3fs "
+ "(device output latency %.3fs).",
+ guard_s,
+ output_latency_s,
)
return
post_output_echo_guard_until = 0.0
@@ -6157,10 +6172,13 @@ class SpeechPipeline:
_warm_barge_detector(), name=f"rt-barge-warm-{session_id}"
)
- async def _cancel_output_playback() -> None:
+ async def _cancel_output_playback(*, terminal: bool = False) -> None:
"""Cancel surface generation and provider playback as one unit."""
nonlocal surface_playback_epoch, surface_playback_task
+ nonlocal terminal_output_closed
+ if terminal:
+ terminal_output_closed = True
# 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.
@@ -6172,19 +6190,26 @@ class SpeechPipeline:
# 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 terminal:
+ await playback.close()
+ else:
+ 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
+ if terminal_output_closed:
+ return
semantic_turn_committed = True
if not speaking:
post_output_echo_guard_until = 0.0
speaking = True
barge_detector.start_output()
await self._set_turn_state(TurnTakingState.JARVIS_SPEAKING)
+ if terminal_output_closed:
+ return
await playback.send_binary(pcm)
async def _send_json(message: dict[str, Any]) -> None:
@@ -6267,6 +6292,8 @@ class SpeechPipeline:
):
turn_complete.set()
elif kind == "error_spoken":
+ if terminal_output_closed:
+ return
semantic_turn_committed = True
text = str(message.get("text", "") or "").strip()
language = _phrase_lang(
@@ -6304,6 +6331,8 @@ class SpeechPipeline:
# pump and local barge detector remain active, so this does
# not open a second microphone or replay the user's request.
await _cancel_output_playback()
+ if terminal_output_closed:
+ return
surface_playback_epoch += 1
active_surface_epoch = surface_playback_epoch
speaking = True
@@ -6314,7 +6343,10 @@ class SpeechPipeline:
# (BUG-089).
self._register_assistant_speech(cleaned)
await self._set_turn_state(TurnTakingState.JARVIS_SPEAKING)
- if surface_playback_epoch != active_surface_epoch:
+ if (
+ terminal_output_closed
+ or 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.
@@ -6625,7 +6657,10 @@ class SpeechPipeline:
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()
+ try:
+ await _cancel_output_playback(terminal=True)
+ except Exception as exc: # noqa: BLE001 -- teardown remains best-effort
+ log.warning("Realtime terminal playback close failed: %s", exc)
barge_detector.stop_output()
barge_feed_executor.shutdown(wait=False, cancel_futures=True)
if not barge_warm_task.done():
@@ -6653,18 +6688,14 @@ class SpeechPipeline:
pass
if session is not None:
await session.end(reason=reason)
- if reason != "shutdown":
- # A provider failure tears the session down while already
- # scrub-cleared PCM can still sit in the local playback queue.
- # Drain it (bounded) instead of hard-stopping so the spoken
- # reply keeps every word that was already safe to say.
- # User-initiated stops (hangup/barge-in) have cancel()ed the
- # queue earlier, which makes this a fast no-op for them.
- try:
- await asyncio.wait_for(playback.finish_turn(), timeout=15.0)
- except (asyncio.CancelledError, Exception): # noqa: BLE001, S110 - teardown
- pass
- await playback.close()
+ # ``session.end`` quiesces the provider pump. Close once more to
+ # collect any callback that had already crossed the surface
+ # boundary when terminal teardown began. ``close`` is idempotent
+ # and permanently rejects later audio.
+ try:
+ await _cancel_output_playback(terminal=True)
+ except Exception as exc: # noqa: BLE001 -- teardown remains best-effort
+ log.warning("Realtime final playback cleanup failed: %s", exc)
async def _ptt_session(
self, *, input_buffer: _SessionInputBuffer | None = None
diff --git a/tests/unit/audio/test_player_persistent_stream.py b/tests/unit/audio/test_player_persistent_stream.py
index c4abbb9bf0..bf19b1036a 100644
--- a/tests/unit/audio/test_player_persistent_stream.py
+++ b/tests/unit/audio/test_player_persistent_stream.py
@@ -68,7 +68,7 @@ def _make_player(monkeypatch) -> tuple[AudioPlayer, list[str]]:
def fake_close(stream):
events.append("close")
- def fake_write(stream, arr, src_rate, dev_rate):
+ def fake_write(stream, arr, src_rate, dev_rate, **_kwargs):
events.append(f"write@{src_rate}")
monkeypatch.setattr(player, "_open_output_stream", fake_open)
@@ -180,6 +180,108 @@ async def test_stop_is_idempotent_when_no_stream(monkeypatch) -> None:
player.stop() # idempotent
+def test_output_latency_reports_the_active_stream_value(monkeypatch) -> None:
+ """Half-duplex callers can cover a device buffer longer than 500 ms."""
+
+ player, _ = _make_player(monkeypatch)
+
+ class _HighLatencyStream:
+ latency = 0.869
+
+ player._active_stream = _HighLatencyStream()
+
+ assert player.output_latency_s == pytest.approx(0.869)
+
+
+async def test_stop_absorbs_expected_portaudio_error_from_inflight_write(
+ monkeypatch,
+) -> None:
+ """A native write aborted by this playback generation is not a failure."""
+
+ player, _ = _make_player(monkeypatch)
+ monkeypatch.setattr(
+ player,
+ "_write_samples",
+ AudioPlayer._write_samples.__get__(player, AudioPlayer),
+ )
+ write_entered = threading.Event()
+ release_write = threading.Event()
+
+ class _AbortRaceStream:
+ latency = 0.869
+
+ def write(self, _samples) -> bool:
+ write_entered.set()
+ assert release_write.wait(timeout=1.0)
+ raise player_module._PortAudioError(
+ "Internal PortAudio error",
+ -9986,
+ )
+
+ def abort(self) -> None:
+ release_write.set()
+
+ def close(self) -> None:
+ return None
+
+ stream = _AbortRaceStream()
+ monkeypatch.setattr(
+ player,
+ "_open_output_stream",
+ lambda needed_rate: (stream, needed_rate),
+ )
+ if player_module.sd is not None:
+ monkeypatch.setattr(player_module.sd, "stop", lambda: None)
+
+ play_task = asyncio.create_task(
+ player.play_chunks(_one_chunk(b"\x01\x00" * 4_000))
+ )
+ assert await asyncio.to_thread(write_entered.wait, 1.0)
+
+ player.stop()
+
+ assert await asyncio.wait_for(play_task, timeout=1.0) is False
+
+
+async def test_live_portaudio_write_error_still_propagates(monkeypatch) -> None:
+ """Cancellation handling must not hide an active device failure."""
+
+ player, _ = _make_player(monkeypatch)
+ monkeypatch.setattr(
+ player,
+ "_write_samples",
+ AudioPlayer._write_samples.__get__(player, AudioPlayer),
+ )
+
+ class _FailingStream:
+ latency = 0.2
+
+ def write(self, _samples) -> bool:
+ raise player_module._PortAudioError("Output device failed", -9986)
+
+ def abort(self) -> None:
+ return None
+
+ def close(self) -> None:
+ return None
+
+ stream = _FailingStream()
+ monkeypatch.setattr(
+ player,
+ "_open_output_stream",
+ lambda needed_rate: (stream, needed_rate),
+ )
+ if player_module.sd is not None:
+ monkeypatch.setattr(player_module.sd, "stop", lambda: None)
+
+ with pytest.raises(player_module._PortAudioError, match="Output device failed"):
+ await player.play_chunks(_one_chunk(b"\x01\x00" * 4_000))
+
+ player.stop()
+
+
@pytest.mark.asyncio
async def test_stop_rejects_stream_that_finishes_opening_after_cancel(
monkeypatch,
diff --git a/tests/unit/realtime/test_desktop.py b/tests/unit/realtime/test_desktop.py
index 186bca034a..7c1abbf417 100644
--- a/tests/unit/realtime/test_desktop.py
+++ b/tests/unit/realtime/test_desktop.py
@@ -113,6 +113,23 @@ async def test_cancel_stops_player_and_discards_queued_audio():
assert player.chunks == []
+async def test_close_is_terminal_and_rejects_late_provider_audio() -> None:
+ """A dead desktop surface cannot be reopened by a stale callback."""
+
+ player = FakePlayer()
+ playback = DesktopRealtimePlayback(player)
+
+ await playback.send_binary(b"\x01\x00" * 8)
+ await playback.finish_turn()
+ await playback.close()
+ await playback.send_binary(b"\x09\x00" * 8)
+ await playback.finish_turn()
+
+ assert [chunk.pcm for chunk in player.chunks] == [b"\x01\x00" * 8]
+ assert player.stopped == 1
+
+
@pytest.mark.asyncio
async def test_cancel_can_interrupt_a_turn_already_draining() -> None:
stop_event = asyncio.Event()
diff --git a/tests/unit/speech/test_realtime_mode.py b/tests/unit/speech/test_realtime_mode.py
index 64e8ef9f82..cdba4bca58 100644
--- a/tests/unit/speech/test_realtime_mode.py
+++ b/tests/unit/speech/test_realtime_mode.py
@@ -24,6 +24,7 @@ class _FakePlayer:
def __init__(self) -> None:
self.pcm: list[bytes] = []
self.stopped = 0
+ self.output_latency_s = 0.0
async def play_chunks(self, chunks, *, should_play=None) -> None:
async for chunk in chunks:
@@ -867,6 +868,11 @@ async def test_post_output_echo_tail_stays_local_and_preserves_immediate_user(
"""Hardware playback tail must not become a phantom realtime turn."""
pipe = _pipe()
pipe._continue_listening_after_response = True
+ # The old fixed 10 ms guard has expired before the microphone yields at
+ # 50 ms. The active device's 150 ms PortAudio latency must keep both the
+ # echo and a confirmed immediate user interruption local until then.
+ monkeypatch.setattr(pipeline_mod, "_REALTIME_POST_OUTPUT_ECHO_GUARD_S", 0.01)
+ pipe._player.output_latency_s = 0.15
output_finished = asyncio.Event()
echo_pcm = b"\x01\x00" * 32
user_pcm = b"\x02\x00" * 32
@@ -970,6 +976,62 @@ async def test_post_output_echo_tail_stays_local_and_preserves_immediate_user(
assert {"type": "barge_in"} in session.controls
+async def test_terminal_teardown_rejects_audio_from_late_provider_callback(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """A provider unwinding after hotkey cannot resurrect the output stream."""
+
+ pipe = _pipe()
+ pipe._continue_listening_after_response = True
+ initial_pcm = b"\x01\x00" * 32
+ late_pcm = b"\x09\x00" * 32
+ output_sent = asyncio.Event()
+ built: dict[str, object] = {}
+
+ class _LateOnEndSession(_HandshakeOnlyRealtimeSession):
+ async def handle_control(self, message) -> None:
+ self.controls.append(message)
+ await self._send_json(
+ {
+ "type": "audio_ready",
+ "provider": "fake-live",
+ "input_sample_rate": 16_000,
+ "output_sample_rate": 24_000,
+ }
+ )
+ await self._send_binary(initial_pcm)
+ output_sent.set()
+
+ async def end(self, *, reason: str = "") -> None:
+ self.end_reason = reason
+ # Simulates a callback already queued by the provider while the
+ # terminal hotkey boundary is quiescing its receive pump.
+ await self._send_binary(late_pcm)
+
+ def _build(**kwargs):
+ session = _LateOnEndSession(kwargs["send_binary"], kwargs["send_json"])
+ built["session"] = session
+ return session
+
+ 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(output_sent.wait(), timeout=1.0)
+ await asyncio.sleep(0)
+ pipe._hangup_event.set()
+
+ assert await asyncio.wait_for(task, timeout=1.0) == HANGUP_HOTKEY
+ assert initial_pcm in pipe._player.pcm
+ assert late_pcm not in pipe._player.pcm
+ assert built["session"].end_reason == HANGUP_HOTKEY
+
+
@pytest.mark.asyncio
async def test_completed_startup_tasks_do_not_end_healthy_realtime_session(
monkeypatch: pytest.MonkeyPatch,