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(realtime): stop the assistant from hearing its own voice

Ruben Lütke297f43d550cf
diff --git a/jarvis/audio/capture.py b/jarvis/audio/capture.py
index d1c2361413..0517c63771 100644
--- a/jarvis/audio/capture.py
+++ b/jarvis/audio/capture.py
@@ -48,6 +48,37 @@ DTYPE = "int16"
CAPTURE_BLOCK_DURATION_S = BLOCKSIZE / SAMPLE_RATE
+# Reported latency of the capture stream that is currently open. Half-duplex
+# echo protection needs it: a microphone frame handed over at time T was
+# recorded that much EARLIER, so without it the guard releases frames that
+# still carry the assistant's own voice and the model ends up answering
+# itself. Kept module-level because the mic is a process-wide singleton and
+# the consumers (realtime session, wake loop) never own the stream object.
+_INPUT_LATENCY_CAP_S = 1.0
+_last_input_latency_s = 0.0
+
+
+def last_input_latency_s() -> float:
+ """Capture latency of the open microphone stream, 0.0 when unknown."""
+ return _last_input_latency_s
+
+
+def _remember_input_latency(stream: Any) -> None:
+ global _last_input_latency_s
+ raw = getattr(stream, "latency", None)
+ # PortAudio reports a scalar for a single stream; be liberal anyway, since
+ # a wrong value here silently weakens echo protection rather than raising.
+ if isinstance(raw, (tuple, list)):
+ raw = raw[0] if raw else None
+ try:
+ latency = float(raw) # type: ignore[arg-type]
+ except (TypeError, ValueError):
+ latency = 0.0
+ if not (latency > 0.0):
+ latency = 0.0
+ _last_input_latency_s = min(_INPUT_LATENCY_CAP_S, latency)
+
+
def capture_chunks_for_duration(seconds: float) -> int:
"""Return the default-size chunk count covering at least ``seconds``."""
return max(1, math.ceil(max(0.0, float(seconds)) / CAPTURE_BLOCK_DURATION_S))
@@ -929,6 +960,7 @@ class MicrophoneCapture:
_guarded_open, attempt, capture_rate, capture_blocksize
)
self._stream = stream
+ _remember_input_latency(stream)
self._device = attempt
self._using_physical_fallback = physical_fallback
if not physical_fallback:
diff --git a/jarvis/speech/pipeline.py b/jarvis/speech/pipeline.py
index 66575fe7af..c11d952bbb 100644
--- a/jarvis/speech/pipeline.py
+++ b/jarvis/speech/pipeline.py
@@ -7752,21 +7752,52 @@ class SpeechPipeline:
)
assistant_transcript_parts.clear()
elif was_audible:
+ def _reported_input_latency_s() -> float:
+ try:
+ from jarvis.audio.capture import ( # noqa: PLC0415
+ last_input_latency_s,
+ )
+
+ return max(0.0, float(last_input_latency_s()))
+ except Exception: # noqa: BLE001 - a missing figure only costs margin
+ log.debug(
+ "Capture latency unavailable; echo tail keeps its fixed "
+ "margin only",
+ exc_info=True,
+ )
+ return 0.0
+
self._touch_assistant_speech_activity()
if preserve_echo_tail:
output_latency_s = _reported_output_latency_s()
- guard_s = _REALTIME_POST_OUTPUT_ECHO_GUARD_S + output_latency_s
+ # A frame handed to us now was RECORDED one capture latency
+ # ago, so the audible phase reaches that much further back.
+ # Without it the guard released frames still carrying the
+ # assistant's own voice, the provider heard itself, and the
+ # model answered its own last sentence.
+ input_latency_s = _reported_input_latency_s()
+ audible_s = (
+ output_latency_s
+ + input_latency_s
+ + _REALTIME_HW_ECHO_TAIL_MARGIN_S
+ )
+ # Never end the tail before the audible phase it protects; on a
+ # slow capture path that simply leaves nothing to buffer, which
+ # is correct - those frames are echo, not the user.
+ guard_s = max(
+ _REALTIME_POST_OUTPUT_ECHO_GUARD_S + output_latency_s,
+ audible_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
- )
+ post_output_hw_tail_until = now + audible_s
log.info(
- "Realtime echo tail armed for %.3fs "
- "(device output latency %.3fs, audible phase %.3fs).",
+ "Realtime echo tail armed for %.3fs (device output latency "
+ "%.3fs, capture latency %.3fs, audible phase %.3fs).",
guard_s,
output_latency_s,
- output_latency_s + _REALTIME_HW_ECHO_TAIL_MARGIN_S,
+ input_latency_s,
+ audible_s,
)
return
post_output_echo_guard_until = 0.0
diff --git a/tests/unit/speech/test_realtime_mode.py b/tests/unit/speech/test_realtime_mode.py
index 66618e15ac..eca035bc2c 100644
--- a/tests/unit/speech/test_realtime_mode.py
+++ b/tests/unit/speech/test_realtime_mode.py
@@ -1729,3 +1729,115 @@ async def test_hangup_cancels_realtime_start_while_builder_is_blocked(
assert await asyncio.wait_for(task, timeout=0.5) == HANGUP_HOTKEY
finally:
release_build.set()
+
+
+async def test_capture_latency_extends_the_audible_phase(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """A microphone frame handed over at time T was RECORDED earlier.
+
+ Ignoring that, the guard released frames that still carried the
+ assistant's own voice: the provider heard itself and the model answered
+ its own last sentence. With a slow capture path (MME reports ~0.3 s here)
+ the same frame that is safe on a fast one is still echo, and must stay
+ local - late, quiet, or not at all, but never uploaded.
+ """
+ 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)
+ monkeypatch.setattr(
+ "jarvis.audio.capture.last_input_latency_s", lambda: 0.3
+ )
+ output_finished = asyncio.Event()
+ echo_pcm = b"\x01\x00" * 32 # 0.05 s after the turn: echo either way
+ tail_pcm = b"\x02\x00" * 32 # 0.35 s: safe on a fast mic, echo on this one
+ live_pcm = b"\x04\x00" * 32 # past the whole tail: 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:
+ 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=tail_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_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())
+
+ await asyncio.wait_for(pipe._active_realtime_session(), timeout=4.0)
+
+ session = built["session"]
+ # Both early frames were inspected locally...
+ assert detector_inputs == [echo_pcm, tail_pcm]
+ # ...but only the frame recorded after the assistant had truly fallen
+ # silent reached the provider. Without the capture latency, tail_pcm was
+ # uploaded and the model answered its own echo.
+ assert session.audio_frames == [live_pcm]