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.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
fix(realtime): restore portable barge-in and single responses
Ruben Lütke4d967f4d926d
diff --git a/jarvis/plugins/realtime/gemini_live.py b/jarvis/plugins/realtime/gemini_live.pyindex 9939163489..815a526b1d 100644--- a/jarvis/plugins/realtime/gemini_live.py+++ b/jarvis/plugins/realtime/gemini_live.py@@ -36,6 +36,7 @@ class _ProviderEvent:is_final: bool = Falsems_played: int | None = Noneerror: str | None = None+ item_id: str | None = Nonecall_id: str | None = Nonetool_name: str | None = Nonetool_args: dict[str, Any] | None = Nonediff --git a/jarvis/plugins/realtime/openai_realtime.py b/jarvis/plugins/realtime/openai_realtime.pyindex 4379421563..c41dcd5f23 100644--- a/jarvis/plugins/realtime/openai_realtime.py+++ b/jarvis/plugins/realtime/openai_realtime.py@@ -41,6 +41,7 @@ class _ProviderEvent:is_final: bool = Falsems_played: int | None = Noneerror: str | None = None+ item_id: str | None = Nonecall_id: str | None = Nonetool_name: str | None = Nonetool_args: dict[str, Any] | None = None@@ -195,6 +196,7 @@ class _OpenAIRealtimeSession:type="input_transcript",text=str(getattr(event, "transcript", "") or ""),is_final=True,+ item_id=str(getattr(event, "item_id", "") or "") or None,)elif event_type == "conversation.item.input_audio_transcription.failed":# The model still has the committed audio in conversation@@ -205,6 +207,7 @@ class _OpenAIRealtimeSession:text="",is_final=True,error=_error_message(event),+ item_id=str(getattr(event, "item_id", "") or "") or None,)elif event_type == "input_audio_buffer.speech_started":yield _ProviderEvent(type="speech_started")diff --git a/jarvis/realtime/desktop.py b/jarvis/realtime/desktop.pyindex 6aa5d863e5..e9275e254c 100644--- a/jarvis/realtime/desktop.py+++ b/jarvis/realtime/desktop.py@@ -3,12 +3,148 @@from __future__ import annotationsimport asyncio+import time+from collections import dequefrom collections.abc import AsyncIteratorfrom typing import Any+import numpy as np++from jarvis.audio.vad import VAD_FRAME_SAMPLES, SileroEndpointerfrom jarvis.core.protocols import AudioChunk+class DesktopRealtimeBargeInDetector:+ """Detect deliberate desktop barge-in on the existing microphone stream.++ Desktop realtime stays half-duplex at the provider boundary because raw+ PortAudio capture has no portable acoustic echo cancellation. Dropping the+ microphone entirely while the assistant speaks also makes interruption+ impossible, though. This detector therefore inspects those otherwise-dropped+ 16 kHz frames locally with the bundled torch-free Silero ONNX model.++ Detection deliberately matches the conservative classic-pipeline policy:+ a startup grace period, a high speech probability, and sustained speech.+ The returned PCM contains a short pre-speech window plus the confirmed speech+ frames, allowing the caller to cancel output and forward the user's opening+ syllables to any realtime provider without making the provider/model itself+ responsible for desktop echo suppression.+ """++ def __init__(+ self,+ *,+ grace_s: float = 1.5,+ speech_threshold: float = 0.97,+ consecutive_frames: int = 12,+ pre_speech_frames: int = 10,+ model: Any = None,+ ) -> None:+ self._grace_s = max(0.0, float(grace_s))+ self._speech_threshold = min(1.0, max(0.0, float(speech_threshold)))+ self._consecutive_frames = max(1, int(consecutive_frames))+ self._pre_speech_frames = max(1, int(pre_speech_frames))+ self._model = model or SileroEndpointer(+ speech_threshold=self._speech_threshold+ )+ self._ready = False+ self._active = False+ self._started_at = 0.0+ self._residual = np.empty(0, dtype=np.dtype("<i2"))+ self._pre_buffer: deque[np.ndarray] = deque(maxlen=self._pre_speech_frames)+ self._candidate_frames: list[np.ndarray] = []+ self._speech_run = 0++ @property+ def ready(self) -> bool:+ return self._ready++ @property+ def active(self) -> bool:+ return self._active++ def warmup(self) -> None:+ """Load the CPU ONNX session outside the realtime audio callback."""++ self._model._ensure_model()+ self._ready = True++ def start_output(self) -> None:+ """Arm a fresh detector window for one assistant audio response."""++ self._active = True+ self._started_at = time.monotonic()+ self._reset_buffers()++ def stop_output(self) -> None:+ self._active = False+ self._reset_buffers()++ def feed(self, pcm16: bytes) -> bytes | None:+ """Return buffered user PCM once sustained speech is confirmed."""++ if not self._active or not self._ready or len(pcm16) < 2:+ return None+ if time.monotonic() - self._started_at < self._grace_s:+ # Never let speaker echo collected during the grace period become+ # user preroll once detection arms.+ self._reset_buffers()+ return None++ usable = len(pcm16) - (len(pcm16) % 2)+ samples = np.frombuffer(pcm16[:usable], dtype=np.dtype("<i2"))+ if self._residual.size:+ samples = np.concatenate([self._residual, samples])+ frame_count = samples.size // VAD_FRAME_SAMPLES+ if frame_count == 0:+ self._residual = samples.copy()+ return None++ framed_samples = frame_count * VAD_FRAME_SAMPLES+ frames = samples[:framed_samples].reshape(frame_count, VAD_FRAME_SAMPLES)+ trailing = samples[framed_samples:].copy()++ for index, frame in enumerate(frames):+ normalized = frame.astype(np.float32) / 32768.0+ probability = float(self._model._prob(normalized))+ if probability >= self._speech_threshold:+ if self._speech_run == 0:+ self._candidate_frames = [part.copy() for part in self._pre_buffer]+ self._candidate_frames.append(frame.copy())+ self._speech_run += 1+ if self._speech_run >= self._consecutive_frames:+ tail_frames = frames[index + 1 :].reshape(-1)+ parts = [*self._candidate_frames]+ if tail_frames.size:+ parts.append(tail_frames.copy())+ if trailing.size:+ parts.append(trailing)+ detected = np.concatenate(parts).astype(+ np.dtype("<i2"), copy=False+ )+ self._active = False+ self._reset_buffers()+ return detected.tobytes()+ continue++ # A short high-probability burst is speaker bleed, not a barge-in.+ # Retain only the rolling pre-speech window for the next candidate.+ for candidate in self._candidate_frames:+ self._pre_buffer.append(candidate)+ self._candidate_frames = []+ self._speech_run = 0+ self._pre_buffer.append(frame.copy())++ self._residual = trailing+ return None++ def _reset_buffers(self) -> None:+ self._residual = np.empty(0, dtype=np.dtype("<i2"))+ self._pre_buffer.clear()+ self._candidate_frames = []+ self._speech_run = 0++class DesktopRealtimePlayback:"""Feed provider PCM deltas through one persistent ``AudioPlayer`` stream.@@ -61,7 +197,7 @@ class DesktopRealtimePlayback:self._sample_rate = rateasync def finish_turn(self) -> None:- queue, task = self._detach()+ queue, task = self._queue, self._taskif queue is None or task is None:returnawait queue.put(None)@@ -74,6 +210,19 @@ class DesktopRealtimePlayback:await taskexcept asyncio.CancelledError:pass+ except asyncio.CancelledError:+ current = asyncio.current_task()+ if current is not None and current.cancelling():+ raise+ # The playback worker was canceled by a concurrent barge-in.+ finally:+ # Keep the active task discoverable while it drains. A user can+ # barge in after the provider has sent turn_complete but before the+ # local speaker queue is empty; cancel() must still be able to stop+ # and drain this exact task during that window.+ if self._task is task:+ self._queue = None+ self._task = Noneasync def cancel(self) -> None:queue, task = self._detach()@@ -120,4 +269,4 @@ class DesktopRealtimePlayback:yield chunk-__all__ = ["DesktopRealtimePlayback"]+__all__ = ["DesktopRealtimeBargeInDetector", "DesktopRealtimePlayback"]diff --git a/jarvis/realtime/protocol.py b/jarvis/realtime/protocol.pyindex 3c4c4783df..fd34395405 100644--- a/jarvis/realtime/protocol.py+++ b/jarvis/realtime/protocol.py@@ -36,6 +36,7 @@ class RealtimeEvent:is_final: bool = Falsems_played: int | None = None # speech_started: ms of our audio already hearderror: str | None = None+ item_id: str | None = Nonecall_id: str | None = Nonetool_name: str | None = Nonetool_args: dict[str, Any] | None = Nonediff --git a/jarvis/realtime/session.py b/jarvis/realtime/session.pyindex 23fc23d379..788cbb2322 100644--- a/jarvis/realtime/session.py+++ b/jarvis/realtime/session.py@@ -271,6 +271,7 @@ class RealtimeVoiceSession:self._pending_tool_events: list[Any] = []self._tool_transcript_task: asyncio.Task[None] | None = Noneself._response_requested_for_turn = False+ self._response_requested_input_ids: set[str] = set()self._hangup_reason = ""self._turn_final_text = ""self._end_after_turn = False@@ -427,7 +428,22 @@ class RealtimeVoiceSession:async for event in self._session.receive():if event.type == "input_transcript":transcript = str(event.text or "").strip()- self._input_turn_observed = True+ transcription_failed = bool(event.error)+ input_observed = bool(transcript or transcription_failed)+ input_item_id = str(getattr(event, "item_id", "") or "")+ input_already_answered = bool(+ input_item_id+ and input_item_id in self._response_requested_input_ids+ )+ if event.is_final and input_already_answered:+ log.debug(+ "realtime[%s] ignored duplicate final input item %s",+ self.session_id,+ input_item_id,+ )+ continue+ if input_observed:+ self._input_turn_observed = Truenew_language = self._languageif transcript:new_language = self._resolve_lang(text=transcript)@@ -436,7 +452,7 @@ class RealtimeVoiceSession:self._gate = ScrubHoldGate(new_language)if self._tool_bridge is not None:self._tool_bridge.set_language(new_language)- if event.is_final:+ if event.is_final and input_observed:await self._session.update_session(instructions=_session_instructions(new_language,@@ -447,7 +463,7 @@ class RealtimeVoiceSession:),language=new_language,)- if transcript or event.is_final:+ if input_observed:mark_phase(LatencyPhase.REALTIME_INPUT_COMMITTED)if transcript:if event.is_final:@@ -461,7 +477,7 @@ class RealtimeVoiceSession:await self._tool_bridge.handle_user_transcript(self._last_user_text)- if transcript or event.is_final:+ if input_observed:await self._ensure_turn_started()if transcript:await self._publish_transcription(@@ -503,7 +519,7 @@ class RealtimeVoiceSession:)await self._finish_with_hangup()break- if event.is_final and self._pending_tool_events:+ if event.is_final and input_observed and self._pending_tool_events:self._cancel_tool_transcript_wait()pending = self._pending_tool_eventsself._pending_tool_events = []@@ -514,9 +530,15 @@ class RealtimeVoiceSession:await self._reject_untranscribed_tool_call(pending_event)- if event.is_final and not self._response_requested_for_turn:+ if (+ event.is_final+ and input_observed+ and not self._response_requested_for_turn+ ):await self._session.request_response()self._response_requested_for_turn = True+ if input_item_id:+ self._response_requested_input_ids.add(input_item_id)elif event.type == "output_transcript_delta" and event.text:await self._ensure_turn_started()mark_phase(LatencyPhase.REALTIME_FIRST_TRANSCRIPT)@@ -732,10 +754,13 @@ class RealtimeVoiceSession:)async def _begin_user_speech_turn(self) -> None:- """Close an interrupted reply before opening the user's next turn."""+ """Close an interrupted reply before the next transcript opens a turn."""if self._turn_id and self._turn_has_activity():await self._publish_turn_completed()- await self._ensure_turn_started()+ # Do not open the next persisted turn on VAD alone. A cancelled provider+ # response can still emit response.done after barge-in; opening here would+ # let that stale completion close an empty new turn before its transcript.+ # The next transcript/audio/tool event opens the real turn instead.async def _publish_turn_started(self) -> None:if self._bus is None:@@ -1088,6 +1113,13 @@ class RealtimeVoiceSession:else 0)if self._session is not None:+ try:+ # Explicit cancellation is part of the shared provider contract.+ # OpenAI maps it to response.cancel; Gemini is interrupted by the+ # user audio forwarded immediately after this local boundary.+ await self._session.interrupt()+ except Exception: # noqa: BLE001, S110 -- repeated VAD edges are safe+ passtry:await self._session.truncate(audio_end_ms=audio_end_ms)except Exception: # noqa: BLE001, S110 — best-effort context alignmentdiff --git a/jarvis/speech/pipeline.py b/jarvis/speech/pipeline.pyindex bfbd7224c7..c443d1f58e 100644--- a/jarvis/speech/pipeline.py+++ b/jarvis/speech/pipeline.py@@ -5851,22 +5851,42 @@ class SpeechPipeline:Audio echo cancellation."""try:- from jarvis.realtime.desktop import DesktopRealtimePlayback+ from jarvis.realtime.desktop import (+ DesktopRealtimeBargeInDetector,+ DesktopRealtimePlayback,+ )from jarvis.realtime.factory import build_realtime_sessionexcept ImportError as exc:log.warning("Realtime desktop stack is unavailable: %s", exc)return None+ session_id = getattr(self, "_current_voice_session_id", None) or str(uuid4())playback = DesktopRealtimePlayback(self._player)+ barge_detector = DesktopRealtimeBargeInDetector()turn_complete = asyncio.Event()speaking = Falsesemantic_turn_committed = False+ async def _warm_barge_detector() -> None:+ try:+ await asyncio.to_thread(barge_detector.warmup)+ except Exception as exc: # noqa: BLE001 -- voice still works without local VAD+ log.warning(+ "Realtime desktop barge-in detector unavailable; "+ "continuing half-duplex: %s",+ exc,+ )++ barge_warm_task = asyncio.create_task(+ _warm_barge_detector(), name=f"rt-barge-warm-{session_id}"+ )+async def _send_binary(pcm: bytes) -> None:nonlocal semantic_turn_committed, speakingsemantic_turn_committed = Trueif not speaking:speaking = True+ barge_detector.start_output()await self._set_turn_state(TurnTakingState.JARVIS_SPEAKING)await playback.send_binary(pcm)@@ -5903,25 +5923,31 @@ class SpeechPipeline:semantic_turn_committed = Trueelif kind == "tts_cancel":speaking = False+ barge_detector.stop_output()await playback.cancel()await self._set_turn_state(TurnTakingState.LISTENING)elif kind == "hangup":semantic_turn_committed = Truespeaking = False+ barge_detector.stop_output()await playback.cancel()elif kind == "turn_complete":semantic_turn_committed = Trueawait playback.finish_turn()+ interrupted_during_drain = not speakingspeaking = False+ barge_detector.stop_output()await self._set_turn_state(TurnTakingState.LISTENING)- if not self._continue_listening_after_response:+ if (+ not self._continue_listening_after_response+ and not interrupted_during_drain+ ):turn_complete.set()elif kind in {"provider_error", "error_spoken"}:if kind == "error_spoken":semantic_turn_committed = Truelog.warning("Realtime desktop status: %s", message)- session_id = getattr(self, "_current_voice_session_id", None) or str(uuid4())# Open the microphone BEFORE building the realtime session AND before# the provider handshake, buffering locally until the session accepts# audio. Both stages used to gate the mic open — measured live@@ -5963,6 +5989,18 @@ class SpeechPipeline:buffered = preroll.popleft()preroll_bytes = max(0, preroll_bytes - len(buffered))await session.handle_audio_frame(buffered)+ if speaking:+ interrupted_pcm = barge_detector.feed(chunk.pcm)+ if interrupted_pcm is None:+ # Provider half-duplex remains intact: speaker+ # echo is inspected locally but never uploaded.+ continue+ log.info(+ "Realtime desktop barge-in confirmed by local CPU VAD"+ )+ await session.handle_control({"type": "barge_in"})+ await session.handle_audio_frame(interrupted_pcm)+ continueawait session.handle_audio_frame(chunk.pcm)# A shared capture buffer already owns and meters production@@ -6096,6 +6134,13 @@ class SpeechPipeline:return HANGUP_ERRORreturn Nonefinally:+ barge_detector.stop_output()+ if not barge_warm_task.done():+ barge_warm_task.cancel()+ try:+ await barge_warm_task+ except asyncio.CancelledError:+ pass# The mic pump may not be in wait_tasks yet when the session# build/handshake failed — cancel it explicitly either way.if microphone_task is not None and not microphone_task.done():diff --git a/tests/unit/realtime/test_desktop.py b/tests/unit/realtime/test_desktop.pyindex 3505557e95..c8dbff6dcc 100644--- a/tests/unit/realtime/test_desktop.py+++ b/tests/unit/realtime/test_desktop.py@@ -2,9 +2,14 @@ from __future__ import annotationsimport asyncio+import numpy as npimport pytest-from jarvis.realtime.desktop import DesktopRealtimePlayback+from jarvis.audio.vad import VAD_FRAME_SAMPLES+from jarvis.realtime.desktop import (+ DesktopRealtimeBargeInDetector,+ DesktopRealtimePlayback,+)class FakePlayer:@@ -20,6 +25,56 @@ class FakePlayer:self.stopped += 1+class FakeVadModel:+ def __init__(self, probabilities: list[float]) -> None:+ self.probabilities = list(probabilities)+ self.warmed = False++ def _ensure_model(self) -> None:+ self.warmed = True++ def _prob(self, _frame: np.ndarray) -> float:+ return self.probabilities.pop(0)+++def _pcm_frames(*amplitudes: int) -> bytes:+ return np.concatenate(+ [np.full(VAD_FRAME_SAMPLES, value, dtype=np.dtype("<i2")) for value in amplitudes]+ ).tobytes()+++def test_cpu_barge_detector_returns_prespeech_and_confirmed_user_audio() -> None:+ model = FakeVadModel([0.1, 0.2, 0.99, 0.99, 0.99])+ detector = DesktopRealtimeBargeInDetector(+ grace_s=0,+ consecutive_frames=3,+ pre_speech_frames=2,+ model=model,+ )+ detector.warmup()+ detector.start_output()++ detected = detector.feed(_pcm_frames(1, 2, 3, 4, 5))++ assert model.warmed is True+ assert detected == _pcm_frames(1, 2, 3, 4, 5)+ assert detector.active is False+++def test_cpu_barge_detector_rejects_short_speaker_bleed() -> None:+ model = FakeVadModel([0.99, 0.1, 0.99, 0.99, 0.1])+ detector = DesktopRealtimeBargeInDetector(+ grace_s=0,+ consecutive_frames=3,+ model=model,+ )+ detector.warmup()+ detector.start_output()++ assert detector.feed(_pcm_frames(1, 2, 3, 4, 5)) is None+ assert detector.active is True++@pytest.mark.asyncioasync def test_turn_uses_one_stream_and_drains_in_order():player = FakePlayer()@@ -56,6 +111,33 @@ async def test_cancel_stops_player_and_discards_queued_audio():assert player.chunks == []+async def test_cancel_can_interrupt_a_turn_already_draining() -> None:+ stop_event = asyncio.Event()++ class SlowPlayer(FakePlayer):+ def stop(self) -> None:+ super().stop()+ stop_event.set()++ async def play_chunks(self, chunks) -> None:+ async for _chunk in chunks:+ await stop_event.wait()+ return++ player = SlowPlayer()+ playback = DesktopRealtimePlayback(player)+ await playback.send_binary(b"\x01\x00" * 8)+ drain = asyncio.create_task(playback.finish_turn())+ await asyncio.sleep(0)++ await playback.cancel()+ await drain++ assert player.stopped == 1+ assert player.chunks == []++@pytest.mark.asyncioasync def test_handshake_sample_rate_is_used_for_the_next_turn():player = FakePlayer()diff --git a/tests/unit/realtime/test_openai_realtime.py b/tests/unit/realtime/test_openai_realtime.pyindex b0826fffc8..4816ca93fa 100644--- a/tests/unit/realtime/test_openai_realtime.py+++ b/tests/unit/realtime/test_openai_realtime.py@@ -334,6 +334,7 @@ async def test_transcription_failure_is_a_final_input_event([SimpleNamespace(type="conversation.item.input_audio_transcription.failed",+ item_id="failed-input-1",error=SimpleNamespace(code="transcription_failed",message="Input transcription was unavailable",@@ -348,10 +349,39 @@ async def test_transcription_failure_is_a_final_input_event(assert event.type == "input_transcript"assert event.text == ""assert event.is_final is True+ assert event.item_id == "failed-input-1"assert "transcription_failed" in event.errorawait session.close()+async def test_completed_transcription_preserves_input_item_identity(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ holder = _patch_openai_client(monkeypatch)+ session = await OpenAIRealtimeProvider(api_key="test-key").open_session(+ RealtimeSessionConfig()+ )+ conn = holder["client"].realtime.last_conn+ conn._events = iter(+ [+ SimpleNamespace(+ type="conversation.item.input_audio_transcription.completed",+ item_id="input-item-1",+ transcript="One request",+ )+ ]+ )+ session._events = conn.__aiter__()++ event = await anext(session.receive())++ assert event.type == "input_transcript"+ assert event.item_id == "input-item-1"+ assert event.text == "One request"+ await session.close()++@pytest.mark.asyncioasync def test_tools_are_declared_mapped_and_answered(monkeypatch: pytest.MonkeyPatch):holder = _patch_openai_client(monkeypatch)diff --git a/tests/unit/realtime/test_session.py b/tests/unit/realtime/test_session.pyindex d013217690..1e01063f43 100644--- a/tests/unit/realtime/test_session.py+++ b/tests/unit/realtime/test_session.py@@ -18,6 +18,7 @@ class FakeSession:self.truncated = []self.session_updates = []self.response_requests = 0+ self.interrupts = 0self.closed = Falseasync def send_audio(self, chunk):@@ -40,7 +41,7 @@ class FakeSession:self.truncated.append(audio_end_ms)async def interrupt(self):- pass+ self.interrupts += 1async def send_tool_result(self, call_id, name, result):self.tool_results.append((call_id, name, result))@@ -438,6 +439,85 @@ async def test_missing_final_transcript_still_requests_a_response_without_tools(assert provider.session.tool_results[0][2]["success"] is False+async def test_empty_successful_final_does_not_open_or_request_a_turn():+ provider = FakeProvider(+ [+ RealtimeEvent(+ type="input_transcript",+ text="",+ is_final=True,+ item_id="empty-input",+ ),+ RealtimeEvent(type="turn_complete"),+ ]+ )+ sess = RealtimeVoiceSession(+ session_id="empty-success",+ send_binary=lambda _data: asyncio.sleep(0),+ send_json=lambda _message: asyncio.sleep(0),+ provider=provider,+ config=_cfg(),+ bus=None,+ )++ await sess.handle_control({"type": "audio_start", "sample_rate": 16_000})+ await sess.wait_finished()+ await sess.end(reason="test")++ assert provider.session.response_requests == 0+ assert sess._turn_index == 0+++async def test_duplicate_final_input_item_requests_exactly_one_response():+ duplicate = RealtimeEvent(+ type="input_transcript",+ text="Tell me once",+ is_final=True,+ item_id="input-1",+ )+ provider = FakeProvider(+ [duplicate, RealtimeEvent(type="turn_complete"), duplicate]+ )+ sess = RealtimeVoiceSession(+ session_id="duplicate-input",+ send_binary=lambda _data: asyncio.sleep(0),+ send_json=lambda _message: asyncio.sleep(0),+ provider=provider,+ config=_cfg(),+ bus=None,+ )++ await sess.handle_control({"type": "audio_start", "sample_rate": 16_000})+ await sess.wait_finished()+ await sess.end(reason="test")++ assert provider.session.response_requests == 1+ assert sess._turn_index == 1+++async def test_barge_in_calls_provider_interrupt_before_local_cancel():+ jsons: list[dict[str, object]] = []+ provider = FakeProvider([])+ sess = RealtimeVoiceSession(+ session_id="provider-interrupt",+ send_binary=lambda _data: asyncio.sleep(0),+ send_json=lambda message: jsons.append(message) or asyncio.sleep(0),+ provider=provider,+ config=_cfg(),+ bus=None,+ )++ await sess.handle_control({"type": "audio_start", "sample_rate": 16_000})+ await sess.handle_control({"type": "barge_in"})+ await sess.end(reason="test")++ assert provider.session.interrupts == 1+ assert {"type": "tts_cancel"} in jsons++@pytest.mark.asyncioasync def test_hard_leak_transcript_drops_audio():events = [diff --git a/tests/unit/realtime/test_transcript_persistence.py b/tests/unit/realtime/test_transcript_persistence.pyindex 67b1e01fb1..79cb67ada7 100644--- a/tests/unit/realtime/test_transcript_persistence.py+++ b/tests/unit/realtime/test_transcript_persistence.py@@ -497,6 +497,8 @@ async def test_barge_in_finalizes_previous_turn_before_next_user_transcript(]assert all(turn.tier == "realtime" for turn in turns)assert all(turn.ended_ms is not None for turn in turns)+ assert provider.session is not None+ assert provider.session.interrupts >= 1finally:store.close()diff --git a/tests/unit/speech/test_realtime_mode.py b/tests/unit/speech/test_realtime_mode.pyindex 67e3bc0e65..a754071907 100644--- a/tests/unit/speech/test_realtime_mode.py+++ b/tests/unit/speech/test_realtime_mode.py@@ -216,6 +216,98 @@ async def test_desktop_realtime_handshake_streams_audio_and_ends_single_turn(assert built["session"].end_reason == HANGUP_TURN_COMPLETE+async def test_desktop_cpu_barge_in_cancels_and_forwards_user_preroll(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ pipe = _pipe()+ output_started = asyncio.Event()+ forwarded = b"\x09\x00" * 32++ class _Detector:+ def warmup(self) -> None:+ return None++ def start_output(self) -> None:+ return None++ def stop_output(self) -> None:+ return None++ def feed(self, _pcm: bytes) -> bytes:+ return forwarded++ class _Mic:+ async def __aenter__(self):+ return self++ async def __aexit__(self, *_exc: object) -> bool:+ return False++ async def stream(self):+ await output_started.wait()+ yield AudioChunk(+ pcm=b"\x01\x00" * 32, sample_rate=16_000, timestamp_ns=0+ )+ await asyncio.sleep(0.05)+ yield AudioChunk(+ pcm=b"\x02\x00" * 32, sample_rate=16_000, timestamp_ns=0+ )+ await asyncio.Event().wait()++ class _Session(_HandshakeOnlyRealtimeSession):+ def __init__(self, send_binary, send_json) -> None:+ super().__init__(send_binary, send_json)+ self.audio_frames: list[bytes] = []+ self.forwarded = asyncio.Event()++ async def handle_control(self, message) -> None:+ self.controls.append(message)+ if message.get("type") == "audio_start":+ await self._send_json(+ {+ "type": "audio_ready",+ "provider": "fake-live",+ "input_sample_rate": 16_000,+ "output_sample_rate": 24_000,+ }+ )+ await self._send_binary(b"\x03\x00" * 32)+ output_started.set()+ elif message.get("type") == "barge_in":+ await self._send_json({"type": "tts_cancel"})++ async def handle_audio_frame(self, pcm: bytes) -> None:+ self.audio_frames.append(pcm)+ if pcm == forwarded:+ self.forwarded.set()++ async def wait_finished(self) -> None:+ await self.forwarded.wait()++ built: dict[str, object] = {}++ def _build(**kwargs):+ built.update(kwargs)+ session = _Session(kwargs["send_binary"], kwargs["send_json"])+ built["session"] = session+ return session++ monkeypatch.setattr("jarvis.realtime.factory.build_realtime_session", _build)+ monkeypatch.setattr(+ "jarvis.realtime.desktop.DesktopRealtimeBargeInDetector", _Detector+ )+ monkeypatch.setattr(pipeline_mod, "MicrophoneCapture", lambda **_kwargs: _Mic())++ reason = await asyncio.wait_for(pipe._active_realtime_session(), timeout=2.0)++ session = built["session"]+ assert reason == HANGUP_ERROR+ assert {"type": "barge_in"} in session.controls+ assert session.audio_frames[-1] == forwarded+ assert built["half_duplex"] is True++@pytest.mark.asyncioasync def test_completed_startup_tasks_do_not_end_healthy_realtime_session(monkeypatch: pytest.MonkeyPatch,