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): stop speaker echo from confirming as barge-in mid-answer

Ruben Lütkeb1b78698d723
diff --git a/docs/BUGS.md b/docs/BUGS.md
index 0e45437662..4b052f7606 100644
--- a/docs/BUGS.md
+++ b/docs/BUGS.md
@@ -6939,3 +6939,67 @@ on updated macOS, Windows, and Linux installations remains pending.
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.
+
+---
+
+## BUG-101: loud speaker echo defeats the barge-in energy floor mid-answer — the assistant interrupts itself and answers its own words (CRITICAL, FIXED IN CODE 2026-07-20; HARDWARE VALIDATION PENDING)
+
+**Symptom.** Realtime voice session `c77b7a88-61b3-475d-98b1-7119bee0f03d`
+(Mac built-in speakers + built-in mic, 2026-07-20): while the assistant was
+speaking about Thanksgiving, a barge-in fired with user text `Thanksgiving` —
+a word only the speakers were saying — truncating the answer. The next
+answer's own opening (`...voraus, wofür sie dankbar sind`) <!-- i18n-allow: forensic quote --> then came back as
+the "user" turn `Voraus, wo...`, truncating that answer too. <!-- i18n-allow: forensic quotes from runtime voice transcripts -->
+Unlike BUG-100 (echo after the turn's speaker drain) this echo confirmed
+DURING active playback, through the barge path.
+
+**Reconstruction.** The desktop barge detector's only acoustic echo defense
+is a LEVEL discriminator: the adaptive RMS floor (BUG-084) learned during the
+1.5 s grace window. Speech has dynamics — on a strongly coupled speaker/mic
+pair the answer's louder syllables jump the learned 90th-percentile × 1.4
+floor after the grace window closes, Silero (which cannot tell whose voice it
+hears) confirms sustained speech, and the confirmed echo is forwarded as a
+user barge: playback cancel + phantom turn. The text backstop
+(`SelfEchoGuard`) deliberately never judged utterances under three tokens, and
+barge captures truncate echo to exactly such fragments (`Thanksgiving` = 1
+token, `Voraus, wo` = 2). <!-- i18n-allow: forensic tokens under test -->
+
+**Fix (three layers, all word-, language-, and OS-agnostic).**
+
+1. **Output envelope reference** (`jarvis/audio/echo_reference.py`):
+ `AudioPlayer._write_samples` records a timestamped RMS per ~60 ms played
+ block — the process's own ground truth of what the speakers emit. No OS
+ audio API, no model; identical on Windows/macOS/Linux.
+2. **Correlation gate in the barge detector**
+ (`DesktopRealtimeBargeInDetector._candidate_matches_output_envelope`):
+ before a confirmed candidate may cancel playback, its per-frame RMS series
+ is Pearson-correlated against the played envelope across the plausible
+ device-latency lag window (≤ 1.75 s, covering the 0.869 s worst case from
+ BUG-100). Correlation is scale-invariant — volume, mic gain, and distance
+ drop out; only the temporal loudness SHAPE decides. A match ≥ 0.70 is our
+ own echo: suppressed, detector stays armed. Every guard fails OPEN (no
+ reference, flat envelopes, snapshot error → the barge stands), so a real
+ user can always interrupt.
+3. **Strict short-echo judgment, barge-scoped** (`SelfEchoGuard`,
+ `RealtimeVoiceSession`): only when the input originated from a
+ surface-confirmed local barge during playback (`judge_short=True`), sub-3-
+ token transcripts are judged with EXACT containment (no fuzzy), a length-4
+ floor for single tokens, and a final-token prefix rule for mid-word cuts
+ (`wo` ← `wofür`). Ordinary short answers <!-- i18n-allow: forensic token -->
+ ("stopp" answering "Soll ich stoppen?") never <!-- i18n-allow: command fixture --> see the strict path — the
+ BUG-084 fail-open doctrine stands. <!-- i18n-allow: command fixture -->
+
+**Class rule (extends AP-27's lesson to barge-in).** A level threshold can
+never separate two voices sharing one microphone, and a transcript-content
+rule alone must stay fail-open — but the process OWNS the output signal, and
+correlating against that reference is the word-agnostic discriminator that
+needs no threshold tuned per room. When output audio exists, judge suspected
+echo against what was actually played, in the signal domain first.
+
+**Guards.** `tests/unit/realtime/test_desktop.py` (gate suppresses tracking
+candidates, passes uncorrelated speech, fails open without reference, stays
+armed after suppression), `tests/unit/audio/test_echo_reference.py` (tap +
+module contract), `tests/unit/speech/test_echo_guard.py` +
+`tests/unit/realtime/test_session_self_echo.py` (strict short judgment is
+barge-scoped; replay of session c77b7a88's turns 4/5). Physical validation on
+the Mac speakers+mic setup remains pending.
diff --git a/jarvis/audio/echo_reference.py b/jarvis/audio/echo_reference.py
new file mode 100644
index 0000000000..18686fb93c
--- /dev/null
+++ b/jarvis/audio/echo_reference.py
@@ -0,0 +1,67 @@
+"""Process-local envelope record of the audio Jarvis itself just played.
+
+The desktop surfaces are half-duplex because raw PortAudio capture has no
+portable acoustic echo cancellation — yet the one signal that separates the
+assistant's own speaker echo from a genuine user barge-in is the OUTPUT audio
+itself, and this process owns that signal end to end. ``AudioPlayer`` records
+one (timestamp, duration, RMS) sample per ~60 ms write block here; the
+barge-in detector correlates a confirmed speech candidate against this
+envelope before it is allowed to cancel playback (BUG-101).
+
+Deliberately NOT the EventBus (several samples per second, see
+``level_tap``) and deliberately dependency-light: plain floats under one
+lock, bounded ring, cheap no-ops when nothing has played. All platforms share
+this path — the discriminator is arithmetic on audio the process produced,
+never an OS audio API.
+"""
+
+from __future__ import annotations
+
+import threading
+import time
+from collections import deque
+
+# ~60 ms per player write block → 512 entries cover ~30 s, far beyond any
+# realistic device-latency lag window while staying tiny.
+_MAX_ENTRIES = 512
+
+_lock = threading.Lock()
+# (monotonic timestamp at write-return, block duration in s, block RMS 0..1)
+_entries: deque[tuple[float, float, float]] = deque(maxlen=_MAX_ENTRIES)
+
+
+def record(rms: float, duration_s: float, *, timestamp: float | None = None) -> None:
+ """Append one played output block's RMS to the envelope record.
+
+ ``timestamp`` defaults to ``time.monotonic()`` at call time — the player
+ calls this right after the blocking ``stream.write`` returns, so the stamp
+ marks when the block entered the device buffer (audibility lags by the
+ device's output latency, which the correlator's lag search covers).
+ """
+ if duration_s <= 0.0:
+ return
+ stamp = time.monotonic() if timestamp is None else float(timestamp)
+ with _lock:
+ _entries.append((stamp, float(duration_s), max(0.0, float(rms))))
+
+
+def snapshot(window_s: float) -> list[tuple[float, float, float]]:
+ """Return (timestamp, duration, rms) entries from the last ``window_s``.
+
+ Oldest first. An empty list means nothing was played recently — callers
+ must fail open (no echo judgment without a reference).
+ """
+ if window_s <= 0.0:
+ return []
+ horizon = time.monotonic() - float(window_s)
+ with _lock:
+ return [entry for entry in _entries if entry[0] >= horizon]
+
+
+def reset() -> None:
+ """Drop all recorded entries (tests, device teardown)."""
+ with _lock:
+ _entries.clear()
+
+
+__all__ = ["record", "snapshot", "reset"]
diff --git a/jarvis/audio/player.py b/jarvis/audio/player.py
index 7ed5822e1e..9d4607a237 100644
--- a/jarvis/audio/player.py
+++ b/jarvis/audio/player.py
@@ -28,7 +28,7 @@ else:
except Exception: # noqa: BLE001 — sounddevice/PortAudio (libportaudio2) absent (headless/slim)
sd = None # type: ignore[assignment]
-from jarvis.audio import level_tap
+from jarvis.audio import echo_reference, level_tap
from jarvis.audio.device_select import is_legacy_primary_mapper
from jarvis.audio.gain import apply_output_gain, clamp_volume
from jarvis.core.events import AudioOutFirst
@@ -538,6 +538,9 @@ class AudioPlayer:
if stream is not None:
self._close_output_stream(stream)
self._device_rate_cache.clear()
+ # A swapped device also invalidates the played-envelope record: echo
+ # correlation against a vanished device's output is meaningless.
+ echo_reference.reset()
def set_device(self, device: int | str | None) -> None:
"""Re-resolve the output device and drop any cached state tied to
@@ -834,6 +837,14 @@ class AudioPlayer:
pre = arr_f[start:start + block] # PRE-gain RMS for the visualizer
if pre.size:
level_tap.feed(float(np.sqrt(np.mean(np.square(pre)))))
+ # Echo-reference envelope (BUG-101): the barge-in detector needs
+ # what the speakers actually emit, so record the POST-gain block.
+ # One RMS + deque append per ~60 ms block — no model, no OS API.
+ if out.size:
+ echo_reference.record(
+ float(np.sqrt(np.mean(np.square(out)))),
+ out.shape[0] / device_rate,
+ )
def _close_output_stream(self, stream: sd.OutputStream) -> None:
"""Flush and stop: ``stream.stop()`` blocks until the buffer is empty."""
diff --git a/jarvis/realtime/desktop.py b/jarvis/realtime/desktop.py
index 3c5306ad63..0a5d629c96 100644
--- a/jarvis/realtime/desktop.py
+++ b/jarvis/realtime/desktop.py
@@ -4,6 +4,7 @@ from __future__ import annotations
import asyncio
import logging
+import math
import time
from collections import deque
from collections.abc import AsyncIterator, Callable
@@ -16,6 +17,9 @@ from jarvis.core.protocols import AudioChunk
log = logging.getLogger("jarvis.realtime.desktop")
+# Silero frames are fixed 512 samples at the 16 kHz capture rate.
+_VAD_FRAME_S = VAD_FRAME_SAMPLES / 16_000.0
+
class DesktopRealtimeBargeInDetector:
"""Detect deliberate desktop barge-in on the existing microphone stream.
@@ -74,6 +78,31 @@ class DesktopRealtimeBargeInDetector:
_ADAPTIVE_FLOOR_WINDOW_FRAMES = 96
_ADAPTIVE_FLOOR_MIN_BASELINE_FRAMES = 8
+ # Output-envelope correlation gate (BUG-101): the energy floor above is a
+ # LEVEL discriminator and leaks whenever the room's echo coupling beats the
+ # calibrated margin (loud built-in speakers next to a built-in mic: the
+ # assistant's own dynamics jump the 90th-percentile floor, Silero — which
+ # cannot tell whose voice it hears — confirms, and the false barge both
+ # truncates the answer and feeds the echo back as user input). The
+ # remaining word-agnostic discriminator this process owns is the SHAPE of
+ # what the speakers are emitting: ``AudioPlayer`` records a timestamped
+ # RMS envelope of every played block, and a confirmed candidate whose own
+ # envelope tracks that reference at some plausible device-latency lag is
+ # our echo, not a user. Pearson correlation is scale-invariant, so mic
+ # gain, distance, and volume do not matter; a genuine interruption is
+ # dominated by the user's uncorrelated speech and falls well below the
+ # threshold. Every guard fails OPEN (no reference, flat envelopes, poor
+ # coverage → the barge stands), so classic surfaces without the tap and
+ # tests keep today's behavior. The lag ceiling covers the largest reported
+ # device output latency observed in the field (0.869 s, BUG-100) plus
+ # acoustic path and capture buffering.
+ _ECHO_CORR_THRESHOLD = 0.70
+ _ECHO_CORR_MAX_LAG_S = 1.75
+ _ECHO_CORR_LAG_STEP_S = 0.016
+ _ECHO_CORR_MIN_FRAMES = 8
+ _ECHO_CORR_MIN_COVERAGE = 0.8
+ _ECHO_CORR_MIN_STD = 1e-4
+
def __init__(
self,
*,
@@ -85,6 +114,10 @@ class DesktopRealtimeBargeInDetector:
adaptive_floor_margin: float | None = None,
adaptive_floor_cap: float | None = None,
output_active: Callable[[], bool] | None = None,
+ echo_reference_snapshot: (
+ Callable[[float], list[tuple[float, float, float]]] | None
+ ) = None,
+ echo_correlation_threshold: float | None = None,
model: Any = None,
) -> None:
self._grace_s = max(0.0, float(grace_s))
@@ -113,6 +146,18 @@ class DesktopRealtimeBargeInDetector:
# probe; omitted keeps the detector usable in isolation and tests.
self._output_active = output_active
self._playback_started = False
+ # Default reference is the process-local player tap; injectable for
+ # tests and disabled entirely with a threshold <= 0.
+ if echo_reference_snapshot is None:
+ from jarvis.audio import echo_reference
+
+ echo_reference_snapshot = echo_reference.snapshot
+ self._echo_reference_snapshot = echo_reference_snapshot
+ self._echo_corr_threshold = (
+ self._ECHO_CORR_THRESHOLD
+ if echo_correlation_threshold is None
+ else float(echo_correlation_threshold)
+ )
# 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(
@@ -128,8 +173,12 @@ class DesktopRealtimeBargeInDetector:
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] = []
+ # Buffered frames carry their capture-time estimate so a confirmed
+ # candidate can be correlated against the timestamped output envelope.
+ self._pre_buffer: deque[tuple[np.ndarray, float]] = deque(
+ maxlen=self._pre_speech_frames
+ )
+ self._candidate_frames: list[tuple[np.ndarray, float]] = []
self._speech_run = 0
@property
@@ -209,7 +258,14 @@ class DesktopRealtimeBargeInDetector:
frames = samples[:framed_samples].reshape(frame_count, VAD_FRAME_SAMPLES)
trailing = samples[framed_samples:].copy()
+ # The batch just arrived from the live capture stream, so its last
+ # frame ends roughly "now"; earlier frames stack backwards in fixed
+ # VAD-frame steps. Millisecond-exact stamps are unnecessary — the
+ # correlation gate searches lags far coarser than executor jitter.
+ batch_now = time.monotonic()
+
for index, frame in enumerate(frames):
+ frame_ts = batch_now - (frame_count - 1 - index) * _VAD_FRAME_S
normalized = frame.astype(np.float32) / 32768.0
frame_rms = float(np.sqrt(np.mean(np.square(normalized))))
# Energy pre-gate (BUG-062) + adaptive echo floor (BUG-084):
@@ -225,12 +281,21 @@ class DesktopRealtimeBargeInDetector:
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._candidate_frames = [
+ (part.copy(), part_ts) for part, part_ts in self._pre_buffer
+ ]
+ self._candidate_frames.append((frame.copy(), frame_ts))
self._speech_run += 1
if self._speech_run >= self._consecutive_frames:
+ if self._candidate_matches_output_envelope():
+ # The confirmed "speech" tracks what the speakers are
+ # currently emitting — our own echo, not a user. Keep
+ # the detector armed; a real interruption on top of
+ # the echo decorrelates and still breaks through.
+ self._reset_buffers()
+ continue
tail_frames = frames[index + 1 :].reshape(-1)
- parts = [*self._candidate_frames]
+ parts = [part for part, _part_ts in self._candidate_frames]
if tail_frames.size:
parts.append(tail_frames.copy())
if trailing.size:
@@ -249,7 +314,7 @@ class DesktopRealtimeBargeInDetector:
self._pre_buffer.append(candidate)
self._candidate_frames = []
self._speech_run = 0
- self._pre_buffer.append(frame.copy())
+ self._pre_buffer.append((frame.copy(), frame_ts))
self._residual = trailing
return None
@@ -259,6 +324,87 @@ class DesktopRealtimeBargeInDetector:
normalized = frame.astype(np.float32) / 32768.0
return float(np.sqrt(np.mean(np.square(normalized))))
+ def _candidate_matches_output_envelope(self) -> bool:
+ """True when the confirmed candidate is the speakers' own envelope.
+
+ Correlates the candidate's per-frame RMS series against the player's
+ timestamped output envelope across the plausible device-latency lag
+ window. Pearson correlation is scale-invariant, so speaker volume,
+ mic gain, and distance drop out; only the temporal SHAPE of the
+ loudness decides — word- and language-agnostic by construction.
+ Every guard fails OPEN (returns False → the barge-in stands): no or
+ flat reference data, too few frames, poor time coverage, or any
+ snapshot error must never make interruption impossible.
+ """
+ threshold = self._echo_corr_threshold
+ if threshold <= 0.0:
+ return False
+ if len(self._candidate_frames) < self._ECHO_CORR_MIN_FRAMES:
+ return False
+ try:
+ window = (
+ len(self._candidate_frames) * _VAD_FRAME_S
+ + self._ECHO_CORR_MAX_LAG_S
+ + 1.0
+ )
+ reference = list(self._echo_reference_snapshot(window))
+ except Exception: # noqa: BLE001 — the gate must never break barge-in
+ log.debug("Echo-reference snapshot failed", exc_info=True)
+ return False
+ if len(reference) < 2:
+ return False
+ candidate = np.array(
+ [self._frame_rms(frame) for frame, _ts in self._candidate_frames],
+ dtype=np.float64,
+ )
+ times = np.array(
+ [ts for _frame, ts in self._candidate_frames], dtype=np.float64
+ )
+ if float(candidate.std()) < self._ECHO_CORR_MIN_STD:
+ return False
+ starts = np.array([entry[0] for entry in reference], dtype=np.float64)
+ ends = starts + np.array(
+ [entry[1] for entry in reference], dtype=np.float64
+ )
+ levels = np.array([entry[2] for entry in reference], dtype=np.float64)
+ min_cover = max(
+ self._ECHO_CORR_MIN_FRAMES,
+ int(len(candidate) * self._ECHO_CORR_MIN_COVERAGE),
+ )
+ best_r = 0.0
+ best_lag = 0.0
+ lag = 0.0
+ while lag <= self._ECHO_CORR_MAX_LAG_S:
+ query = times - lag
+ idx = np.searchsorted(starts, query, side="right") - 1
+ idx_clamped = np.clip(idx, 0, len(starts) - 1)
+ valid = (idx >= 0) & (query < ends[idx_clamped])
+ if int(valid.sum()) >= min_cover:
+ cand_values = candidate[valid]
+ ref_values = levels[idx_clamped[valid]]
+ if (
+ float(cand_values.std()) >= self._ECHO_CORR_MIN_STD
+ and float(ref_values.std()) >= self._ECHO_CORR_MIN_STD
+ ):
+ r = float(np.corrcoef(cand_values, ref_values)[0, 1])
+ if math.isfinite(r) and r > best_r:
+ best_r = r
+ best_lag = lag
+ lag += self._ECHO_CORR_LAG_STEP_S
+ if best_r >= threshold:
+ log.info(
+ "Barge-in candidate suppressed as speaker echo "
+ "(envelope correlation %.2f at %.0f ms output lag)",
+ best_r,
+ best_lag * 1000.0,
+ )
+ return True
+ log.debug(
+ "Barge-in candidate passed the echo gate (max correlation %.2f)",
+ best_r,
+ )
+ return False
+
def _effective_floor(self) -> float:
"""Current energy gate: static minimum or the learned echo floor.
diff --git a/jarvis/realtime/session.py b/jarvis/realtime/session.py
index f3f9f9899b..c9ff9b0f80 100644
--- a/jarvis/realtime/session.py
+++ b/jarvis/realtime/session.py
@@ -849,6 +849,12 @@ class RealtimeVoiceSession:
# a turn — otherwise the brain answers its own speaker echo forever.
self._echo_guard = SelfEchoGuard()
self._echo_playback_horizon = 0.0
+ # BUG-101: while this horizon is armed, the next final input transcript
+ # originated from the surface's LOCAL barge capture during active
+ # playback — the one context where a sub-3-token utterance may be
+ # judged (strictly) as our own truncated speaker echo. Ordinary short
+ # answers after playback never see the strict path.
+ self._local_barge_short_echo_until = 0.0
self._last_outage_notice_at = float("-inf")
self._provider_output_probe = ""
self._executed_tool_names: set[str] = set()
@@ -979,6 +985,11 @@ class RealtimeVoiceSession:
await self._publish_ready()
self._start_pump()
elif kind == "barge_in":
+ # Surface-confirmed local barge during playback: the audio that
+ # follows may be the speakers' own echo that beat the acoustic
+ # gates. Arm the strict short-echo judgment for the transcript
+ # this capture produces (BUG-101).
+ self._local_barge_short_echo_until = time.monotonic() + 6.0
await self._begin_user_speech_turn()
await self._barge_in()
elif kind == "audio_stop":
@@ -1481,7 +1492,15 @@ class RealtimeVoiceSession:
echo_probe = " ".join(
(*self._user_transcript_parts, transcript)
).strip()
- if self._echo_guard.is_echo(echo_probe):
+ judge_short = (
+ time.monotonic() < self._local_barge_short_echo_until
+ )
+ # One strict judgment per barge capture: consume the
+ # window so later ordinary short answers are exempt.
+ self._local_barge_short_echo_until = 0.0
+ if self._echo_guard.is_echo(
+ echo_probe, judge_short=judge_short
+ ):
log.info(
"realtime[%s] dropped provider-transcribed "
"self-echo before it became a turn: %r",
diff --git a/jarvis/speech/echo_guard.py b/jarvis/speech/echo_guard.py
index 54b05b701b..1a2137898c 100644
--- a/jarvis/speech/echo_guard.py
+++ b/jarvis/speech/echo_guard.py
@@ -40,6 +40,20 @@ class SelfEchoGuard:
# echo garble sits above 0.8:
# "misch"→"mich" 0.89, "hörn"→"hören" 0.89. # i18n-allow: garble anchors
FUZZY_CUTOFF = 0.8
+ # BUG-101: utterances below MIN_TOKENS used to be exempt entirely — and
+ # the observed during-playback echo phantoms are exactly that short (the
+ # barge capture window truncates the echo: a lone "Thanksgiving", a cut
+ # "Voraus, wo" of the assistant's own "voraus, wofür ..."). # i18n-allow: forensic quotes
+ # Short utterances are therefore judged on explicit caller opt-in
+ # (``judge_short=True``, barge-capture context only), and STRICTLY:
+ # exact token containment (no fuzzy matching — a garbled token fails open), a
+ # single-token utterance must be a substantial word (length floor below)
+ # so interjections ("ja", "ok") always reach their handlers, and only the
+ # FINAL token of a multi-token utterance may match as a word prefix
+ # (the capture cuts mid-word). Exactness is also what keeps command words
+ # safe: "stopp" never strictly matches a spoken "stoppen". # i18n-allow: command anchors
+ SHORT_SINGLE_TOKEN_MIN_LEN = 4
+ SHORT_PREFIX_MIN_LEN = 2
def __init__(self) -> None:
# (slot, tokens, registered_ns); slot=None entries are append-only.
@@ -85,7 +99,7 @@ class SelfEchoGuard:
else:
self.activity_ns = max(self.activity_ns, stamp)
- def is_echo(self, text: str) -> bool:
+ def is_echo(self, text: str, *, judge_short: bool = False) -> bool:
"""True when ``text`` is (fuzzily) contained in recent assistant speech.
Only consulted while playback activity is recent (``WINDOW_S``);
@@ -94,8 +108,14 @@ class SelfEchoGuard:
because STT garbles echo (see the ratio anchors at ``FUZZY_CUTOFF``
above), but every utterance token must still match. One genuinely novel
token can change the meaning of a short follow-up and therefore fails
- open. Utterances shorter than ``MIN_TOKENS`` are never judged — short
- commands ("stopp") must always reach their handlers. References are
+ open. Utterances shorter than ``MIN_TOKENS`` are by default never
+ judged — a short user ANSWER is legitimately built from the
+ assistant's own words, e.g. answering a yes/no offer with the
+ offer's own verb, and
+ must always reach its handler. Only a caller that KNOWS the input
+ originated from a local barge capture during active playback (the
+ echo path, BUG-101) opts in via ``judge_short=True``, which applies
+ the STRICT rules of ``_strictly_contained``. References are
checked per spoken phrase plus the concatenation of the two newest
phrases, so an echo spanning a sentence boundary still matches without
building a large session-wide vocabulary union.
@@ -106,7 +126,17 @@ class SelfEchoGuard:
if now_ns - self.activity_ns > int(self.WINDOW_S * 1e9):
return False
utterance = self.tokens(text)
- if len(utterance) < self.MIN_TOKENS:
+ if not utterance:
+ return False
+ strict_short = len(utterance) < self.MIN_TOKENS
+ if strict_short and not judge_short:
+ return False
+ if (
+ strict_short
+ and len(utterance) == 1
+ and len(utterance[0]) < self.SHORT_SINGLE_TOKEN_MIN_LEN
+ ):
+ # Interjections and command words ("ja", "ok") are never judged.
return False
ttl_ns = int(self.REF_TTL_S * 1e9)
fresh = [tokens for _slot, tokens, ref_ns in self._refs if now_ns - ref_ns <= ttl_ns]
@@ -116,7 +146,10 @@ class SelfEchoGuard:
if len(fresh) >= 2:
candidates.append(fresh[-2] + fresh[-1])
for reference in candidates:
- if all(
+ if strict_short:
+ if self._strictly_contained(utterance, reference):
+ return True
+ elif all(
token in reference
or difflib.get_close_matches(
token,
@@ -128,3 +161,29 @@ class SelfEchoGuard:
):
return True
return False
+
+ @classmethod
+ def _strictly_contained(
+ cls, utterance: list[str], reference: list[str]
+ ) -> bool:
+ """Exact-containment judgment for sub-``MIN_TOKENS`` utterances.
+
+ Every token must appear verbatim in the reference; only the FINAL
+ token of a multi-token utterance may instead be a prefix of a
+ reference word, because the barge capture window cuts echo mid-word
+ ("wo" ← "wofür"). No fuzzy matching: one # i18n-allow: forensic quote
+ garbled or novel token means this is not provably our echo, and the
+ guard fails open.
+ """
+ for index, token in enumerate(utterance):
+ if token in reference:
+ continue
+ is_final_of_many = len(utterance) > 1 and index == len(utterance) - 1
+ if (
+ is_final_of_many
+ and len(token) >= cls.SHORT_PREFIX_MIN_LEN
+ and any(word.startswith(token) for word in reference)
+ ):
+ continue
+ return False
+ return True
diff --git a/tests/unit/audio/test_echo_reference.py b/tests/unit/audio/test_echo_reference.py
new file mode 100644
index 0000000000..9970124044
--- /dev/null
+++ b/tests/unit/audio/test_echo_reference.py
@@ -0,0 +1,67 @@
+"""Unit tests for the played-output echo-reference envelope (BUG-101).
+
+The barge-in detector separates the assistant's own speaker echo from a real
+user interruption by correlating candidate audio against this process-local
+record of what the speakers just emitted. These tests pin the module contract
+(record/snapshot windowing, reset) and that ``AudioPlayer._write_samples``
+actually feeds it for every played block.
+"""
+from __future__ import annotations
+
+import time
+
+import numpy as np
+import pytest
+
+import jarvis.audio.echo_reference as echo_reference
+from jarvis.audio.player import AudioPlayer
+from tests.unit.audio.test_player_persistent_stream import _make_player
+
+
[email protected](autouse=True)
+def _clean_reference():
+ echo_reference.reset()
+ yield
+ echo_reference.reset()
+
+
+def test_record_and_snapshot_window() -> None:
+ now = time.monotonic()
+ echo_reference.record(0.05, 0.06, timestamp=now - 10.0)
+ echo_reference.record(0.07, 0.06, timestamp=now - 1.0)
+ echo_reference.record(0.09, 0.06, timestamp=now)
+
+ recent = echo_reference.snapshot(3.0)
+ assert [entry[2] for entry in recent] == [0.07, 0.09]
+ assert echo_reference.snapshot(30.0)[0][2] == 0.05
+
+
+def test_record_ignores_nonpositive_duration_and_reset_clears() -> None:
+ echo_reference.record(0.5, 0.0)
+ assert echo_reference.snapshot(5.0) == []
+ echo_reference.record(0.5, 0.06)
+ assert len(echo_reference.snapshot(5.0)) == 1
+ echo_reference.reset()
+ assert echo_reference.snapshot(5.0) == []
+
+
+def test_write_samples_records_played_envelope(monkeypatch) -> None:
+ player, _events = _make_player(monkeypatch)
+ monkeypatch.setattr(
+ player,
+ "_write_samples",
+ AudioPlayer._write_samples.__get__(player, AudioPlayer),
+ )
+
+ class _AcceptingStream:
+ def write(self, _samples) -> bool:
+ return False
+
+ # 200 ms of clearly audible int16 audio, no resample (source == device).
+ arr = np.full(4_800, 8_000, dtype=np.dtype("<i2"))
+ player._write_samples(_AcceptingStream(), arr, 24_000, 24_000)
+
+ entries = echo_reference.snapshot(5.0)
+ assert entries, "played audio must land in the echo reference"
+ assert sum(entry[1] for entry in entries) == pytest.approx(0.2, abs=0.02)
+ assert all(entry[2] > 0.1 for entry in entries)
diff --git a/tests/unit/realtime/test_desktop.py b/tests/unit/realtime/test_desktop.py
index 7c1abbf417..fa4182cc50 100644
--- a/tests/unit/realtime/test_desktop.py
+++ b/tests/unit/realtime/test_desktop.py
@@ -387,3 +387,96 @@ def test_grace_frames_calibrate_but_never_become_preroll() -> None:
assert len(detector._pre_buffer) == 0
assert detector._candidate_frames == []
assert model.calls == 0
+
+
+# --- BUG-101: output-envelope correlation gate -------------------------------
+
+
+def _ramp_reference(now: float, *, span_s: float = 2.5) -> list[tuple[float, float, float]]:
+ """A played-output envelope rising linearly until ``now`` (60 ms blocks)."""
+ block = 0.06
+ count = int(span_s / block)
+ return [
+ (now - span_s + index * block, block, 0.001 + 0.002 * index)
+ for index in range(count)
+ ]
+
+
+def _corr_detector(
+ snapshot, probabilities: int = 12
+) -> DesktopRealtimeBargeInDetector:
+ model = FakeVadModel([0.99] * probabilities)
+ detector = DesktopRealtimeBargeInDetector(
+ min_frame_rms=0.0,
+ grace_s=0,
+ consecutive_frames=12,
+ pre_speech_frames=2,
+ echo_reference_snapshot=snapshot,
+ model=model,
+ )
+ detector.warmup()
+ detector.start_output()
+ return detector
+
+
+def test_echo_gate_suppresses_candidate_tracking_the_output_envelope() -> None:
+ import time as _time
+
+ now = _time.monotonic()
+ reference = _ramp_reference(now + 0.5)
+ # Candidate loudness rises linearly exactly like the played output — a
+ # shifted linear ramp correlates ~1.0 at some lag in the search window.
+ ramp = _pcm_frames(*[1000 * (index + 1) for index in range(12)])
+
+ detector = _corr_detector(lambda _window: reference)
+ assert detector.feed(ramp) is None
+ # Suppressed as echo, but the detector stays armed for a real user.
+ assert detector.active is True
+
+
+def test_echo_gate_passes_candidate_uncorrelated_with_output() -> None:
+ import time as _time
+
+ now = _time.monotonic()
+ reference = _ramp_reference(now + 0.5)
+ # Alternating loud/quiet speech does not track the rising output ramp.
+ alternating = _pcm_frames(
+ *[9000 if index % 2 == 0 else 1500 for index in range(12)]
+ )
+
+ detector = _corr_detector(lambda _window: reference)
+ detected = detector.feed(alternating)
+ assert detected == alternating
+ assert detector.active is False
+
+
+def test_echo_gate_fails_open_without_reference_data() -> None:
+ ramp = _pcm_frames(*[1000 * (index + 1) for index in range(12)])
+ detector = _corr_detector(lambda _window: [])
+ assert detector.feed(ramp) == ramp
+
+
+def test_echo_gate_fails_open_when_snapshot_raises() -> None:
+ def _broken(_window: float) -> list[tuple[float, float, float]]:
+ raise RuntimeError("tap unavailable")
+
+ ramp = _pcm_frames(*[1000 * (index + 1) for index in range(12)])
+ detector = _corr_detector(_broken)
+ assert detector.feed(ramp) == ramp
+
+
+def test_echo_gate_suppression_keeps_scanning_for_real_speech() -> None:
+ import time as _time
+
+ now = _time.monotonic()
+ reference = _ramp_reference(now + 1.0)
+ ramp = _pcm_frames(*[1000 * (index + 1) for index in range(12)])
+ alternating = _pcm_frames(
+ *[9000 if index % 2 == 0 else 1500 for index in range(12)]
+ )
+
+ detector = _corr_detector(lambda _window: reference, probabilities=24)
+ assert detector.feed(ramp) is None
+ detected = detector.feed(alternating)
+ assert detected is not None
+ assert detector.active is False
diff --git a/tests/unit/realtime/test_session_self_echo.py b/tests/unit/realtime/test_session_self_echo.py
index 9d7c9fa50e..910941360c 100644
--- a/tests/unit/realtime/test_session_self_echo.py
+++ b/tests/unit/realtime/test_session_self_echo.py
@@ -379,3 +379,83 @@ async def test_barge_in_resets_the_horizon():
await sess._barge_in(interrupt_provider=False)
lead_ns = sess._echo_guard.activity_ns - time.time_ns()
assert lead_ns < int(1e9), "horizon must collapse to ~now after a barge"
+
+
+class GatedInputFakeSession(FakeSession):
+ """Holds back the input transcript until the test releases it."""
+
+ def __init__(self, events):
+ super().__init__(events)
+ self.input_gate = asyncio.Event()
+
+ async def receive(self):
+ for event in self._events:
+ if getattr(event, "type", "") == "input_transcript":
+ await self.input_gate.wait()
+ yield event
+ await asyncio.sleep(0)
+
+
+class GatedInputFakeProvider(FakeProvider):
+ session_cls = GatedInputFakeSession
+
+
+def _bug101_events():
+ return [
+ RealtimeEvent(
+ type="output_transcript_delta",
+ # i18n-allow: voice fixture
+ text="An Thanksgiving kommt traditionell die ganze Familie zusammen.",
+ ),
+ RealtimeEvent(
+ type="audio_delta",
+ audio=AudioChunk(pcm=b"\x01\x02" * 2_400, sample_rate=24000, timestamp_ns=0),
+ ),
+ RealtimeEvent(
+ type="input_transcript",
+ # Session c77b7a88 turn 4: the barge capture forwarded the
+ # speakers' own word, truncated to a single token.
+ text="Thanksgiving",
+ is_final=True,
+ ),
+ RealtimeEvent(type="turn_complete"),
+ ]
+
+
+async def _run_with_barge(provider, *, send_barge: bool):
+ jsons = []
+ sess = RealtimeVoiceSession(
+ session_id="echo-test",
+ 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": 16000})
+ await asyncio.sleep(0.05)
+ if send_barge:
+ await sess.handle_control({"type": "barge_in"})
+ provider.session.input_gate.set()
+ await asyncio.sleep(0.05)
+ await sess.end(reason="test")
+ return provider.session, jsons
+
+
+async def test_short_barge_capture_echo_is_dropped():
+ """BUG-101: a barge-forwarded single word of our own speech is no turn."""
+ fake, jsons = await _run_with_barge(
+ GatedInputFakeProvider(_bug101_events()), send_barge=True
+ )
+ assert fake.response_requests == 0
+ assert _user_transcripts(jsons) == []
+
+
+async def test_same_short_input_without_barge_context_stays_a_turn():
+ """The strict short judgment is barge-scoped: ordinary short input passes."""
+ fake, jsons = await _run_with_barge(
+ GatedInputFakeProvider(_bug101_events()), send_barge=False
+ )
+ assert _user_transcripts(jsons)
diff --git a/tests/unit/speech/test_echo_guard.py b/tests/unit/speech/test_echo_guard.py
index c5d408de8e..309d9a42ec 100644
--- a/tests/unit/speech/test_echo_guard.py
+++ b/tests/unit/speech/test_echo_guard.py
@@ -98,3 +98,59 @@ def test_forced_touch_resets_the_horizon() -> None:
guard.register("Das freut mich zu hören.") # i18n-allow: voice fixture
guard.touch(time.time_ns() - int(60e9), force=True)
assert guard.is_echo("freut mich zu hören") is False # i18n-allow
+
+
+# --- BUG-101: short truncated echo phantoms ---------------------------------
+
+
+def test_single_word_echo_of_active_playback_is_flagged() -> None:
+ # Session c77b7a88 turn 4: the mic heard the assistant's own
+ # "Thanksgiving" while the answer about Thanksgiving was still playing.
+ guard = SelfEchoGuard()
+ guard.register(
+ "An Thanksgiving kommt traditionell die ganze Familie zusammen" # i18n-allow: voice fixture
+ )
+ assert guard.is_echo("Thanksgiving", judge_short=True) is True
+ # Without the barge-capture opt-in, short utterances stay exempt.
+ assert guard.is_echo("Thanksgiving") is False
+
+
+def test_truncated_two_word_echo_matches_final_prefix() -> None:
+ # Session c77b7a88 turn 5: the capture window cut the echo mid-word —
+ # "Voraus, wo" ← "voraus, wofür sie dankbar sind". # i18n-allow: forensic quote
+ guard = SelfEchoGuard()
+ guard.register(
+ "reihum voraus, wofür sie dankbar sind" # i18n-allow: voice fixture
+ )
+ assert guard.is_echo("Voraus, wo", judge_short=True) is True
+
+
+def test_short_command_never_matches_an_inflected_reference() -> None:
+ # "stopp" must reach its handler even while the assistant is saying
+ # "stoppen" — short judgment is exact, never fuzzy.
+ guard = SelfEchoGuard()
+ guard.register("Soll ich die Wiedergabe stoppen?") # i18n-allow: voice fixture
+ assert guard.is_echo("stopp", judge_short=True) is False
+
+
+def test_tiny_interjections_are_never_judged() -> None:
+ guard = SelfEchoGuard()
+ guard.register("Ja, das ist ein Feiertag") # i18n-allow: voice fixture
+ assert guard.is_echo("ja", judge_short=True) is False
+
+
+def test_short_utterance_with_novel_word_fails_open() -> None:
+ guard = SelfEchoGuard()
+ guard.register(
+ "An Thanksgiving kommt die Familie zusammen" # i18n-allow: voice fixture
+ )
+ assert guard.is_echo("welches Wetter", judge_short=True) is False # i18n-allow: user fixture
+
+
+def test_short_prefix_rule_applies_only_to_the_final_token() -> None:
+ # A leading truncated token is not the capture-cut pattern; fail open.
+ guard = SelfEchoGuard()
+ guard.register(
+ "reihum voraus, wofür sie dankbar sind" # i18n-allow: voice fixture
+ )
+ assert guard.is_echo("wo voraus", judge_short=True) is False # i18n-allow: scrambled probe