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): close the 1-2s post-turn deaf window on the desktop mic path
Personal Jarvis Maintainerad5b1efaca68
diff --git a/jarvis/speech/pipeline.py b/jarvis/speech/pipeline.pyindex 10384f3426..e15ad5320f 100644--- a/jarvis/speech/pipeline.py+++ b/jarvis/speech/pipeline.py@@ -605,6 +605,20 @@ 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+# The post-output echo tail splits into two phases. Only its leading part is+# physically audible speaker audio (the device's reported output latency plus+# an acoustic-decay/capture-buffering margin); microphone frames captured there+# are genuine echo territory and stay detector-only. Frames captured in the+# REMAINDER of the tail are silent-room or user speech: they are buffered and+# forwarded to the provider when the tail expires instead of being dropped —+# dropping them was the "the first 1-2 s after Jarvis stops talking are deaf"+# defect (a user answering immediately lost the whole utterance onset unless+# it survived the strict local barge confirm).+_REALTIME_HW_ECHO_TAIL_MARGIN_S = 0.25+# Bound on buffered tail audio; the tail itself is capped at+# _REALTIME_POST_OUTPUT_ECHO_GUARD_S + _REALTIME_OUTPUT_LATENCY_CAP_S (~5.5 s+# of 16 kHz mono PCM16 ≈ 176 kB), so this never truncates in practice.+_REALTIME_TAIL_PENDING_MAX_BYTES = 256_000def _feed_live_mic_level(chunk: AudioChunk) -> None:@@ -6198,6 +6212,12 @@ class SpeechPipeline:turn_complete = asyncio.Event()speaking = Falsepost_output_echo_guard_until = 0.0+ # End of the tail's physically-audible phase (device latency residue);+ # frames captured past it but still inside the echo guard are buffered+ # in ``tail_pending`` and flushed once the guard expires.+ post_output_hw_tail_until = 0.0+ tail_pending: deque[bytes] = deque()+ tail_pending_bytes = 0semantic_turn_committed = False# Per-segment accumulator of the session's assistant transcript# deltas: registered with the PIPELINE's own text echo guard when the@@ -6212,9 +6232,15 @@ class SpeechPipeline:return 0.0return min(_REALTIME_OUTPUT_LATENCY_CAP_S, max(0.0, latency))+ def _clear_tail_pending() -> None:+ nonlocal tail_pending_bytes+ tail_pending.clear()+ tail_pending_bytes = 0+def _close_output_segment(*, preserve_echo_tail: bool) -> None:"""Keep half-duplex protection through physical speaker drain."""- nonlocal post_output_echo_guard_until, speaking+ nonlocal post_output_echo_guard_until, post_output_hw_tail_until+ nonlocal speakingwas_audible = speaking or bool(assistant_transcript_parts)speaking = False# The provider queue has drained here, but a persistent PortAudio@@ -6230,15 +6256,22 @@ class SpeechPipeline:if preserve_echo_tail: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+ now = time.monotonic()+ post_output_echo_guard_until = now + guard_s+ post_output_hw_tail_until = (+ now + output_latency_s + _REALTIME_HW_ECHO_TAIL_MARGIN_S+ )log.info("Realtime echo tail armed for %.3fs "- "(device output latency %.3fs).",+ "(device output latency %.3fs, audible phase %.3fs).",guard_s,output_latency_s,+ output_latency_s + _REALTIME_HW_ECHO_TAIL_MARGIN_S,)returnpost_output_echo_guard_until = 0.0+ post_output_hw_tail_until = 0.0+ _clear_tail_pending()barge_detector.stop_output()async def _warm_barge_detector() -> None:@@ -6281,13 +6314,19 @@ class SpeechPipeline:await asyncio.gather(surface_task, return_exceptions=True)async def _send_binary(pcm: bytes) -> None:- nonlocal post_output_echo_guard_until+ nonlocal post_output_echo_guard_until, post_output_hw_tail_untilnonlocal semantic_turn_committed, speakingif terminal_output_closed:returnsemantic_turn_committed = Trueif not speaking:post_output_echo_guard_until = 0.0+ post_output_hw_tail_until = 0.0+ # Frames buffered during the previous turn's tail belong to a+ # user moment the provider has already moved past; uploading+ # them under fresh assistant output would interleave stale+ # audio into the new turn.+ _clear_tail_pending()speaking = Truebarge_detector.start_output()await self._set_turn_state(TurnTakingState.JARVIS_SPEAKING)@@ -6546,8 +6585,32 @@ class SpeechPipeline:microphone_task: asyncio.Task[Any] | None = Nonetry:async with self._session_input_source(input_buffer) as input_chunks:+ async def _flush_tail_pending() -> None:+ """Forward microphone audio buffered during the echo tail.++ The tail's post-audible phase holds no speaker echo by+ construction, so its frames are the user's own words (or+ room silence the provider VAD ignores). Delivering them+ late — instead of never — is what closes the post-turn+ deaf window.+ """+ nonlocal tail_pending_bytes+ if not tail_pending:+ return+ frames = list(tail_pending)+ _clear_tail_pending()+ log.info(+ "Realtime echo tail expired; forwarding %d buffered "+ "microphone frames (%.2fs).",+ len(frames),+ sum(len(f) for f in frames) / (16_000 * 2),+ )+ for pcm in frames:+ await session.handle_audio_frame(pcm)+async def _send_microphone() -> None:nonlocal post_output_echo_guard_until, preroll_bytes+ nonlocal tail_pending_bytesasync for chunk in self._session_input_stream(input_chunks):if not provider_ready.is_set():if (@@ -6566,9 +6629,9 @@ class SpeechPipeline:buffered = preroll.popleft()preroll_bytes = max(0, preroll_bytes - len(buffered))await session.handle_audio_frame(buffered)+ now = time.monotonic()echo_guard_active = bool(- speaking- or time.monotonic() < post_output_echo_guard_until+ speaking or now < post_output_echo_guard_until)if echo_guard_active:interrupted_pcm = await asyncio.get_running_loop(@@ -6581,16 +6644,36 @@ class SpeechPipeline:# Provider half-duplex remains intact: speaker# echo, including the hardware playback tail,# is inspected locally but never uploaded.+ # Past the audible phase the frame cannot be+ # echo anymore — retain it for the tail flush+ # instead of dropping the user's first words.+ if (+ not speaking+ and now >= post_output_hw_tail_until+ ):+ tail_pending.append(chunk.pcm)+ tail_pending_bytes += len(chunk.pcm)+ while (+ tail_pending_bytes+ > _REALTIME_TAIL_PENDING_MAX_BYTES+ and len(tail_pending) > 1+ ):+ dropped = tail_pending.popleft()+ tail_pending_bytes -= len(dropped)continuelog.info("Realtime desktop barge-in confirmed by local CPU VAD")+ # The detector's capture supersedes the buffered+ # tail frames (they overlap its pre-speech window).+ _clear_tail_pending()post_output_echo_guard_until = 0.0await session.handle_control({"type": "barge_in"})await session.handle_audio_frame(interrupted_pcm)continueif bool(getattr(barge_detector, "active", False)):barge_detector.stop_output()+ await _flush_tail_pending()await session.handle_audio_frame(chunk.pcm)# A shared capture buffer already owns and meters productiondiff --git a/tests/unit/speech/test_realtime_mode.py b/tests/unit/speech/test_realtime_mode.pyindex cdba4bca58..8d17ab7375 100644--- a/tests/unit/speech/test_realtime_mode.py+++ b/tests/unit/speech/test_realtime_mode.py@@ -976,6 +976,125 @@ async def test_post_output_echo_tail_stays_local_and_preserves_immediate_user(assert {"type": "barge_in"} in session.controls+async def test_post_output_tail_speech_is_buffered_and_flushed_not_dropped(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """Quiet user speech right after a turn must reach the provider late, not never.++ The post-drain echo tail used to drop every microphone frame the local+ barge detector did not confirm — a user answering within ~1-2 s of the+ assistant finishing lost their utterance onset entirely. Frames captured+ past the physically-audible phase are now buffered and forwarded when the+ tail expires.+ """+ pipe = _pipe()+ pipe._continue_listening_after_response = True+ monkeypatch.setattr(pipeline_mod, "_REALTIME_POST_OUTPUT_ECHO_GUARD_S", 0.7)+ monkeypatch.setattr(pipeline_mod, "_REALTIME_HW_ECHO_TAIL_MARGIN_S", 0.2)+ output_finished = asyncio.Event()+ echo_pcm = b"\x01\x00" * 32 # audible phase: genuine echo territory+ user_pcm = b"\x02\x00" * 32 # post-audible tail: quiet user speech+ live_pcm = b"\x04\x00" * 32 # after tail expiry: normal pass-through+ detector_inputs: list[bytes] = []++ class _Detector:+ def __init__(self, **_kwargs: object) -> None:+ self.active = False++ def warmup(self) -> None:+ return None++ def start_output(self) -> None:+ self.active = True++ def stop_output(self) -> None:+ self.active = False++ def feed(self, pcm: bytes) -> bytes | None:+ # Never confirms a barge-in: the user's answer is too quiet for+ # the strict local confirm — the exact deaf-window scenario.+ detector_inputs.append(pcm)+ return None++ class _Mic:+ async def __aenter__(self):+ return self++ async def __aexit__(self, *_exc: object) -> bool:+ return False++ async def stream(self):+ await output_finished.wait()+ await asyncio.sleep(0.05)+ yield AudioChunk(pcm=echo_pcm, sample_rate=16_000, timestamp_ns=0)+ await asyncio.sleep(0.3)+ yield AudioChunk(pcm=user_pcm, sample_rate=16_000, timestamp_ns=0)+ await asyncio.sleep(0.45)+ yield AudioChunk(pcm=live_pcm, 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.received_live = 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_json(+ {+ "type": "transcript",+ "role": "user",+ "text": "simple question",+ "is_final": True,+ }+ )+ await self._send_binary(b"\x03\x00" * 32)+ await self._send_json({"type": "turn_complete"})+ output_finished.set()++ async def handle_audio_frame(self, pcm: bytes) -> None:+ self.audio_frames.append(pcm)+ if pcm == live_pcm:+ self.received_live.set()++ async def wait_finished(self) -> None:+ await self.received_live.wait()++ built: dict[str, object] = {}++ def _build(**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=4.0)++ session = built["session"]+ assert reason == HANGUP_ERROR+ # The audible-phase frame stayed local; the tail frame was inspected but+ # NOT dropped: it reaches the provider ahead of the first live frame.+ assert detector_inputs == [echo_pcm, user_pcm]+ assert session.audio_frames == [user_pcm, live_pcm]+ assert {"type": "barge_in"} not in session.controls++@pytest.mark.asyncioasync def test_terminal_teardown_rejects_audio_from_late_provider_callback(monkeypatch: pytest.MonkeyPatch,