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(speech): align barge-in grace with playback
Ruben Lütke7cceeb7092eb
diff --git a/jarvis/realtime/desktop.py b/jarvis/realtime/desktop.pyindex 62c3965c5d..a326f36145 100644--- a/jarvis/realtime/desktop.py+++ b/jarvis/realtime/desktop.py@@ -5,7 +5,7 @@ from __future__ import annotationsimport asyncioimport timefrom collections import deque-from collections.abc import AsyncIterator+from collections.abc import AsyncIterator, Callablefrom typing import Anyimport numpy as np@@ -81,6 +81,7 @@ class DesktopRealtimeBargeInDetector:min_frame_rms: float | None = None,adaptive_floor_margin: float | None = None,adaptive_floor_cap: float | None = None,+ output_active: Callable[[], bool] | None = None,model: Any = None,) -> None:self._grace_s = max(0.0, float(grace_s))@@ -100,6 +101,15 @@ class DesktopRealtimeBargeInDetector:if adaptive_floor_cap is Noneelse max(self._min_frame_rms, float(adaptive_floor_cap)))+ # Surface TTS can spend more than a second synthesizing and opening the+ # output stream after the response is logically marked SPEAKING. The+ # grace window must begin at physical playback, not at that early state+ # edge, or synthesis latency consumes the echo-calibration period and+ # the assistant's first sentence is misclassified as a barge-in. The+ # desktop pipeline supplies the AudioPlayer's process-local playback+ # probe; omitted keeps the detector usable in isolation and tests.+ self._output_active = output_active+ self._playback_started = False# The lag must exceed the confirm run so genuine sustained speech is# always judged against a baseline formed BEFORE it started.self._adaptive_floor_lag = max(@@ -138,6 +148,7 @@ class DesktopRealtimeBargeInDetector:self._active = Trueself._started_at = time.monotonic()+ self._playback_started = self._output_active is Noneself._reset_buffers()# Fresh echo calibration per response: the grace window (pure speaker# echo by construction) re-trains the adaptive floor for the volume /@@ -146,6 +157,7 @@ class DesktopRealtimeBargeInDetector:def stop_output(self) -> None:self._active = False+ self._playback_started = Falseself._reset_buffers()def feed(self, pcm16: bytes) -> bytes | None:@@ -154,6 +166,17 @@ class DesktopRealtimeBargeInDetector:if not self._active or not self._ready or len(pcm16) < 2:return None+ if not self._playback_started:+ # Keep half-duplex input local while synthesis/stream setup is+ # pending, but do not let that silent lead-in age the grace clock.+ # The first frame observed during real playback starts a full,+ # fresh calibration window built only from speaker echo.+ if self._output_active is not None and not self._output_active():+ self._reset_buffers()+ return None+ self._playback_started = True+ self._started_at = time.monotonic()+usable = len(pcm16) - (len(pcm16) % 2)samples = np.frombuffer(pcm16[:usable], dtype=np.dtype("<i2"))if self._residual.size:diff --git a/jarvis/speech/pipeline.py b/jarvis/speech/pipeline.pyindex 4ec55cc308..2b86241a79 100644--- a/jarvis/speech/pipeline.py+++ b/jarvis/speech/pipeline.py@@ -30,7 +30,7 @@ from uuid import uuid4import numpy as np-from jarvis.audio import mic_level+from jarvis.audio import level_tap, mic_levelfrom jarvis.audio.capture import (REALTIME_QUEUE_CHUNKS,MicrophoneCapture,@@ -6090,7 +6090,9 @@ class SpeechPipeline:session_id = getattr(self, "_current_voice_session_id", None) or str(uuid4())playback = DesktopRealtimePlayback(self._player)- barge_detector = DesktopRealtimeBargeInDetector()+ barge_detector = DesktopRealtimeBargeInDetector(+ output_active=level_tap.playback_active+ )# Per-frame Silero inference runs OFF the voice event loop — the same# BUG-062/BUG-084 class the classic barge monitor already fixed with# to_thread; inline it stalled playback on slow CPUs (Intel-Mac test@@ -10043,7 +10045,10 @@ class SpeechPipeline:"""from jarvis.realtime.desktop import DesktopRealtimeBargeInDetector- detector = DesktopRealtimeBargeInDetector(grace_s=grace_s)+ detector = DesktopRealtimeBargeInDetector(+ grace_s=grace_s,+ output_active=level_tap.playback_active,+ )try:# Model load off the event loop — it shares the turn with live# audio playback.diff --git a/tests/unit/realtime/test_desktop.py b/tests/unit/realtime/test_desktop.pyindex e0bac5b941..186bca034a 100644--- a/tests/unit/realtime/test_desktop.py+++ b/tests/unit/realtime/test_desktop.py@@ -320,6 +320,45 @@ def test_start_output_resets_echo_calibration() -> None:assert len(detector._rms_history) == 0+def test_synthesis_delay_cannot_consume_echo_calibration(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """The grace clock starts only once output is physically active."""+ now = 100.0+ output_is_active = False+ monkeypatch.setattr(+ "jarvis.realtime.desktop.time.monotonic", lambda: now+ )+ model = _AlwaysSpeechModel()+ detector = DesktopRealtimeBargeInDetector(+ grace_s=1.5,+ consecutive_frames=3,+ output_active=lambda: output_is_active,+ model=model,+ )+ detector.warmup()+ detector.start_output()++ # Surface synthesis and stream setup can exceed the nominal grace period.+ # Loud microphone frames during that lead-in must remain local without+ # arming Silero or aging the calibration clock.+ now = 102.0+ assert detector.feed(_pcm_frames(*[2000] * 20)) is None+ assert model.calls == 0+ assert len(detector._rms_history) == 0++ # Physical playback begins now. Its first 1.5 seconds are a fresh echo-only+ # calibration window even though start_output() happened two seconds ago.+ output_is_active = True+ assert detector.feed(_pcm_frames(*[2000] * 30)) is None+ assert model.calls == 0+ assert len(detector._rms_history) == 30++ now = 104.0+ assert detector.feed(_pcm_frames(*[2000] * 20)) is None+ assert model.calls == 0++def test_grace_frames_calibrate_but_never_become_preroll() -> None:detector, model = _echo_calibrated_detector(echo_amplitude=2000, grace_frames=10, consecutive_frames=3diff --git a/tests/unit/speech/test_realtime_mode.py b/tests/unit/speech/test_realtime_mode.pyindex f404a3329a..77566c0dc1 100644--- a/tests/unit/speech/test_realtime_mode.py+++ b/tests/unit/speech/test_realtime_mode.py@@ -540,8 +540,12 @@ async def test_desktop_cpu_barge_in_cancels_and_forwards_user_preroll(pipe = _pipe()output_started = asyncio.Event()forwarded = b"\x09\x00" * 32+ detector_kwargs: dict[str, object] = {}class _Detector:+ def __init__(self, **kwargs: object) -> None:+ detector_kwargs.update(kwargs)+def warmup(self) -> None:return None@@ -623,6 +627,50 @@ async def test_desktop_cpu_barge_in_cancels_and_forwards_user_preroll(assert {"type": "barge_in"} in session.controlsassert session.audio_frames[-1] == forwardedassert built["half_duplex"] is True+ assert detector_kwargs["output_active"] is pipeline_mod.level_tap.playback_active+++async def test_classic_barge_grace_uses_physical_playback_probe(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ pipe = _pipe(mode="pipeline")+ detector_kwargs: dict[str, object] = {}++ class _Detector:+ def __init__(self, **kwargs: object) -> None:+ detector_kwargs.update(kwargs)++ def warmup(self) -> None:+ return None++ def start_output(self) -> None:+ return None++ def feed(self, _pcm: bytes) -> bytes:+ return b"confirmed"++ class _Mic:+ async def __aenter__(self):+ return self++ async def __aexit__(self, *_exc: object) -> bool:+ return False++ async def stream(self):+ yield AudioChunk(+ pcm=b"\x01\x00" * 32,+ sample_rate=16_000,+ timestamp_ns=0,+ )++ monkeypatch.setattr(+ "jarvis.realtime.desktop.DesktopRealtimeBargeInDetector", _Detector+ )+ monkeypatch.setattr(pipeline_mod, "MicrophoneCapture", lambda **_kwargs: _Mic())++ assert await pipe._barge_monitor() is True+ assert detector_kwargs["output_active"] is pipeline_mod.level_tap.playback_active@pytest.mark.asyncio@@ -639,7 +687,7 @@ async def test_post_output_echo_tail_stays_local_and_preserves_immediate_user(detector_inputs: list[bytes] = []class _Detector:- def __init__(self) -> None:+ def __init__(self, **_kwargs: object) -> None:self.active = Falsedef warmup(self) -> None: