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): BUG-084 — stop the assistant answering its own speaker echo
Ruben Lütkef2657df06722
diff --git a/docs/BUGS.md b/docs/BUGS.mdindex 075122b984..d26d671d63 100644--- a/docs/BUGS.md+++ b/docs/BUGS.md@@ -5777,3 +5777,84 @@ rebuild with a scoped `tccutil` reset (and long-term, a stable signingidentity). Never surface a permission request control the OS will ignore:macOS prompts exactly once per TCC state, and reads some probes only atprocess start — the UI must model both or it gaslights the user.++## BUG-084: Classic pipeline answers ITSELF on open speakers — false self-barge truncates the reply and its echo becomes the next "user" turn (CRITICAL, FIXED 2026-07-18)++**Symptom (Intel-Mac test machine, v1.0.12, built-in speakers + mic).** The+assistant's speech is severely chopped — mid-sentence pauses of 5-6 s,+skipped words — and the session transcript shows the assistant holding a+conversation WITH ITSELF across multiple turns: its reply tail comes back+(STT-garbled, e.g. "freut mich zu hören" heard as "Misch zu hören") as a <!-- i18n-allow: forensic quote of the garbled echo under test -->+"user" turn, which the brain politely answers, producing a new reply, a new+echo, and so on — an unbounded self-talk loop.++**Root cause — BUG-062 was fixed ONLY in the realtime path.** The classic+pipeline's `_barge_monitor` (`jarvis/speech/pipeline.py`) still had both+BUG-062 failure modes, plus a loop-amplifier of its own:++1. **No energy floor before Silero.** Every mic frame went straight to the+ VAD model, which cannot tell WHOSE voice it hears. On open speakers next+ to the built-in mic the assistant's own voice is loud, sustained and+ perfectly speech-shaped → prob ≥ 0.97 for ≥ 12 frames → false barge-in →+ `player.stop()` mid-sentence (the skipped words).+2. **Per-frame ONNX synchronously on the voice event loop** for the entire+ answer — starved the ~120 ms playback write batches on the slow CPU →+ PortAudio underruns (the stutter); a ≥ 5 s gap additionally tripped the+ `_TTS_PLAYBACK_STALL_S` watchdog and aborted the whole turn.+3. **The loop-amplifier:** a barge keeps the session LISTENING and skips+ `_suppress_session_input_after_tts` entirely (correct for a REAL+ interrupter — their words must not be dropped). After a FALSE barge that+ means: no echo lock, mic live, the room still carrying the assistant's+ own voice → the echo is transcribed → dispatched to the brain → answered.+ One false barge is enough to seed the endless self-conversation.++**Fix (three layers, all cross-platform).**++1. **Shared detector:** `_barge_monitor` now reuses+ `DesktopRealtimeBargeInDetector` (the tuned BUG-062 realtime fix — static+ RMS floor 0.010, grace, 0.97 × 12 frames) instead of its own bare Silero+ loop, and every `feed` runs via `asyncio.to_thread` so inference never+ shares the event loop with live playback writes.+2. **Adaptive echo floor (in the shared detector, so realtime gains it+ too):** a fixed floor cannot cover every speaker/mic coupling — loud+ built-in-speaker echo sails over 0.010. The detector now calibrates a+ per-answer floor from the grace-window frames (pure speaker echo by+ construction) and keeps updating it from a rolling window of frame RMS+ values: floor = clamp(1.4 × P90, static floor, 0.25). The newest ~16+ frames are EXCLUDED from the baseline (lag > confirm run), so a user+ starting to speak is judged against the pure-echo past, never against+ their own rising voice. `min_frame_rms=0.0` still disables all gating.+3. **Self-echo TEXT guard (last line of defense, `_looks_like_self_echo`):**+ inside the post-playback window, an utterance that is (fuzzily, cutoff+ 0.8 — STT garbles echo) contained in the assistant's own recently spoken+ words with essentially no novel token is dropped before the brain (log:+ "Own speaker echo suppressed"), keeping the session listening. Fail-open+ by design: < 3 tokens are never judged (short commands always pass), any+ novel content keeps the turn, and outside the 6 s activity window the+ user may quote Jarvis verbatim at will. This breaks the loop even when a+ false barge slips the acoustic gates — and covers the barge path's+ deliberate lack of post-TTS suppression.++**Latent bug exposed and fixed on the way:** when the barge monitor returned+WITHOUT barging while the streamed answer was still playing,+`_brain_streaming` fell through to its `finally` and cancelled the producer ++playback — beheading a healthy answer. Invisible before (the old monitor+slept through its grace before touching anything and practically never ended+early); `_speak` always had the wait-it-out branch. `_brain_streaming` now+mirrors it.++**Guards.** `tests/unit/speech/test_self_echo_guard.py` (garbled echo+flagged, novel-content answers kept, short commands immune, window lapse,+cross-sentence echo); `tests/unit/realtime/test_desktop.py` (adaptive floor+gates echo louder than the static floor, lag keeps sustained user speech+confirmable, `min_frame_rms=0.0` opt-out, `start_output` recalibration,+grace frames calibrate but never become preroll).++**Class rule (sharpens BUG-062's).** Half-duplex voice on open speakers must+treat its own output as hostile input on EVERY path that consumes the mic —+fixing one surface (realtime) while the sibling (classic pipeline) keeps the+bare detector just moves the bug. An interrupt detector needs an energy floor+*derived from the echo actually being measured*, not a hardcoded guess; and+any state transition that deliberately skips echo suppression (real barge-in)+needs a content-level backstop, because it will eventually be entered by+mistake.diff --git a/jarvis/realtime/desktop.py b/jarvis/realtime/desktop.pyindex 1f4d95e509..62c3965c5d 100644--- a/jarvis/realtime/desktop.py+++ b/jarvis/realtime/desktop.py@@ -43,6 +43,34 @@ class DesktopRealtimeBargeInDetector:# Trade-off (documented): whisper-quiet barge-in no longer triggers._DEFAULT_MIN_FRAME_RMS = 0.010+ # Adaptive echo floor (BUG-084): a FIXED floor cannot cover every+ # speaker/mic coupling — on built-in laptop speakers next to the built-in+ # mic the assistant's own voice lands far above 0.010, so the static gate+ # passes it, Silero (which cannot tell whose voice it hears) confirms, and+ # the false barge truncates the answer AND opens the self-talk loop. The+ # only word-agnostic discriminator we own is the echo's measured loudness:+ # while output is active the detector keeps a rolling window of recent+ # frame RMS values and derives the gate floor from its 90th percentile+ # times a safety margin — i.e. "louder than the loudest sustained thing+ # the room currently produces", which during playback IS our own echo.+ # The newest ``_ADAPTIVE_FLOOR_LAG_FRAMES`` frames are EXCLUDED from the+ # baseline so a user starting to speak is judged against the pure-echo+ # past, never against their own rising voice (the lag must stay above+ # ``consecutive_frames`` or sustained genuine speech would raise its own+ # bar before it can confirm). The floor is clamped to the static minimum+ # below and ``_DEFAULT_ADAPTIVE_FLOOR_CAP`` above so a shouting user can+ # always break through. The cap must sit ABOVE any realistic echo RMS+ # (loud open speakers reach ~0.06-0.15) — a cap below the echo level+ # would re-open the false-barge hole it exists to close; 0.25 still+ # leaves loud close-range speech (>0.25) able to interrupt worst-case+ # coupling. ``min_frame_rms=0.0`` disables both gates (test hook /+ # explicit opt-out).+ _DEFAULT_ADAPTIVE_FLOOR_MARGIN = 1.4+ _DEFAULT_ADAPTIVE_FLOOR_CAP = 0.25+ _ADAPTIVE_FLOOR_LAG_FRAMES = 16+ _ADAPTIVE_FLOOR_WINDOW_FRAMES = 96+ _ADAPTIVE_FLOOR_MIN_BASELINE_FRAMES = 8+def __init__(self,*,@@ -51,6 +79,8 @@ class DesktopRealtimeBargeInDetector:consecutive_frames: int = 12,pre_speech_frames: int = 10,min_frame_rms: float | None = None,+ adaptive_floor_margin: float | None = None,+ adaptive_floor_cap: float | None = None,model: Any = None,) -> None:self._grace_s = max(0.0, float(grace_s))@@ -60,6 +90,24 @@ class DesktopRealtimeBargeInDetector:self._min_frame_rms = (self._DEFAULT_MIN_FRAME_RMS if min_frame_rms is None else max(0.0, float(min_frame_rms)))+ self._adaptive_floor_margin = (+ self._DEFAULT_ADAPTIVE_FLOOR_MARGIN+ if adaptive_floor_margin is None+ else max(1.0, float(adaptive_floor_margin))+ )+ self._adaptive_floor_cap = (+ self._DEFAULT_ADAPTIVE_FLOOR_CAP+ if adaptive_floor_cap is None+ else max(self._min_frame_rms, float(adaptive_floor_cap))+ )+ # 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(+ self._consecutive_frames + 4, self._ADAPTIVE_FLOOR_LAG_FRAMES+ )+ self._rms_history: deque[float] = deque(+ maxlen=self._ADAPTIVE_FLOOR_WINDOW_FRAMES + self._adaptive_floor_lag+ )self._model = model or SileroEndpointer(speech_threshold=self._speech_threshold)@@ -91,6 +139,10 @@ class DesktopRealtimeBargeInDetector:self._active = Trueself._started_at = time.monotonic()self._reset_buffers()+ # Fresh echo calibration per response: the grace window (pure speaker+ # echo by construction) re-trains the adaptive floor for the volume /+ # coupling of THIS answer instead of trusting a stale estimate.+ self._rms_history.clear()def stop_output(self) -> None:self._active = False@@ -101,17 +153,28 @@ class DesktopRealtimeBargeInDetector: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 Noneusable = 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 time.monotonic() - self._started_at < self._grace_s:+ # Never let speaker echo collected during the grace period become+ # user preroll once detection arms — but DO measure it: grace-time+ # frames are our own playback echo, the calibration data the+ # adaptive floor is built from (BUG-084).+ if frame_count:+ framed_samples = frame_count * VAD_FRAME_SAMPLES+ grace_frames = samples[:framed_samples].reshape(+ frame_count, VAD_FRAME_SAMPLES+ )+ for frame in grace_frames:+ self._rms_history.append(self._frame_rms(frame))+ self._reset_buffers()+ return None+if frame_count == 0:self._residual = samples.copy()return None@@ -122,11 +185,15 @@ class DesktopRealtimeBargeInDetector:for index, frame in enumerate(frames):normalized = frame.astype(np.float32) / 32768.0- # Energy pre-gate (BUG-062): quiet frames never reach the ONNX- # model — this is both the loop-load fix and the echo damper.- if self._min_frame_rms > 0.0 and float(- np.sqrt(np.mean(np.square(normalized)))- ) < self._min_frame_rms:+ frame_rms = float(np.sqrt(np.mean(np.square(normalized))))+ # Energy pre-gate (BUG-062) + adaptive echo floor (BUG-084):+ # frames below the gate never reach the ONNX model — this is the+ # loop-load fix and the echo damper in one. The adaptive floor is+ # computed BEFORE this frame enters the history, so every frame is+ # judged against the lagged pure-echo past, never against itself.+ gate = self._effective_floor()+ self._rms_history.append(frame_rms)+ if gate > 0.0 and frame_rms < gate:probability = 0.0else:probability = float(self._model._prob(normalized))@@ -161,6 +228,29 @@ class DesktopRealtimeBargeInDetector:self._residual = trailingreturn None+ @staticmethod+ def _frame_rms(frame: np.ndarray) -> float:+ normalized = frame.astype(np.float32) / 32768.0+ return float(np.sqrt(np.mean(np.square(normalized))))++ def _effective_floor(self) -> float:+ """Current energy gate: static minimum or the learned echo floor.++ ``min_frame_rms == 0.0`` disables gating entirely (adaptive included) —+ the explicit logic-test / opt-out hook. Otherwise the floor is the 90th+ percentile of the lagged RMS history times the safety margin, clamped+ to [static minimum, cap]. With too little history (fresh detector, no+ playback echo measured yet) it falls back to the static minimum.+ """++ if self._min_frame_rms <= 0.0:+ return 0.0+ baseline = list(self._rms_history)[: -self._adaptive_floor_lag]+ if len(baseline) < self._ADAPTIVE_FLOOR_MIN_BASELINE_FRAMES:+ return self._min_frame_rms+ learned = self._adaptive_floor_margin * float(np.percentile(baseline, 90))+ return min(self._adaptive_floor_cap, max(self._min_frame_rms, learned))+def _reset_buffers(self) -> None:self._residual = np.empty(0, dtype=np.dtype("<i2"))self._pre_buffer.clear()diff --git a/jarvis/speech/pipeline.py b/jarvis/speech/pipeline.pyindex ddac9f0575..6d3952d13a 100644--- a/jarvis/speech/pipeline.py+++ b/jarvis/speech/pipeline.py@@ -12,6 +12,7 @@ hotkeys remain active alongside wake detection.from __future__ import annotationsimport asyncio+import difflibimport enumimport hashlibimport logging@@ -38,7 +39,7 @@ from jarvis.audio.capture import (from jarvis.audio.chime import CHIME_PCM, CHIME_SAMPLE_RATE, DISCONNECT_PCM, READY_PCMfrom jarvis.audio.device_init import wait_for_stable_audio_devicesfrom jarvis.audio.player import AudioPlayer-from jarvis.audio.vad import VAD_FRAME_SAMPLES, SileroEndpointer+from jarvis.audio.vad import SileroEndpointerfrom jarvis.audio.vad_reasons import FORCED_CUT_REASONSfrom jarvis.brain.output_filter import scrub_for_voicefrom jarvis.core.events import (@@ -3333,6 +3334,7 @@ class SpeechPipeline:# fall back to its English voice on German text (the British-accent# symptom; forensic 2026-06-23).lang_code = self._bcp47(ann_lang)+ self._register_assistant_speech(scrubbed.cleaned)try:chunks = self._tts.synthesize(scrubbed.cleaned, language_code=lang_code)except TypeError:@@ -3701,11 +3703,13 @@ class SpeechPipeline:if animate:await self._transition("SPEAKING")try:+ self._register_assistant_speech(cleaned)try:chunks = self._tts.synthesize(cleaned, language_code=self._bcp47(lang))except TypeError:chunks = self._tts.synthesize(cleaned)playback_result = await self._player.play_chunks(chunks)+ self._touch_assistant_speech_activity()if self._playback_confirmed(playback_result):self._emit_spoken(cleaned, lang, SPOKEN_KIND_SUBAGENT)except Exception as exc: # noqa: BLE001@@ -6934,7 +6938,102 @@ class SpeechPipeline:until_ns = time.time_ns() + int(seconds * 1_000_000_000)previous = getattr(self, "_input_suppressed_until_ns", 0)self._input_suppressed_until_ns = max(previous, until_ns)- log.info("TTS-Echo-Sperre aktiv: %.1fs (%s).", seconds, reason)+ log.info("TTS echo lock armed: %.1fs (%s).", seconds, reason)++ # --- Self-echo TEXT guard (BUG-084) --------------------------------- #+ # Last line of defense behind the acoustic gates (barge-in energy floor,+ # post-TTS suppression window): when a "user" utterance that arrives+ # during / right after our own playback consists — fuzzily, STT garbles+ # echo — of nothing but words Jarvis itself just spoke, it is the speaker+ # echo that slipped every acoustic gate, never a turn to answer. Without+ # this, ONE missed false barge loops forever: reply → echo transcribed →+ # brain answers itself → new reply → new echo (the Mac test machine's+ # multi-turn self-conversation, 2026-07-18). Conservative by design:+ # near-total containment in the assistant's own recent words is required,+ # so a genuine user answer that ADDS anything is always kept (fail-open).++ _ECHO_TEXT_GUARD_WINDOW_S = 6.0+ _ECHO_TEXT_REF_TTL_S = 30.0+ _ECHO_TEXT_MIN_TOKENS = 3+ _ECHO_TEXT_MIN_OVERLAP = 0.8+ # 0.8, not lower: at 0.75 near-misses like "gut"→"guten" (ratio exactly+ # 0.75) count as contained and a genuine short user answer built from the+ # assistant's own words plus one inflected token would be eaten. Real STT+ # echo garble sits above 0.8:+ # "misch"→"mich" 0.89, "hörn"→"hören" 0.89. # i18n-allow: German STT-garble ratio anchors under test+ _ECHO_TEXT_FUZZY_CUTOFF = 0.8++ @staticmethod+ def _echo_guard_tokens(text: str) -> list[str]:+ return re.findall(r"\w+", text.lower())++ def _register_assistant_speech(self, text: str) -> None:+ """Remember what Jarvis is about to voice as an echo-guard reference."""++ tokens = self._echo_guard_tokens(text)+ if not tokens:+ return+ refs = getattr(self, "_assistant_echo_refs", None)+ if refs is None:+ refs = deque(maxlen=8)+ self._assistant_echo_refs = refs+ refs.append((tokens, time.time_ns()))+ self._touch_assistant_speech_activity()++ def _touch_assistant_speech_activity(self) -> None:+ """Stamp 'assistant audio was active around now' for the echo guard."""++ self._assistant_speech_activity_ns = time.time_ns()++ def _looks_like_self_echo(self, text: str) -> bool:+ """True when ``text`` is (fuzzily) contained in Jarvis' recent speech.++ Only consulted while playback activity is recent+ (``_ECHO_TEXT_GUARD_WINDOW_S``); outside that window a user may echo+ Jarvis verbatim all they want. Tokens match fuzzily+ (``difflib``-ratio ≥ ``_ECHO_TEXT_FUZZY_CUTOFF``) because STT garbles+ echo (see the ratio anchors at ``_ECHO_TEXT_FUZZY_CUTOFF`` above).+ Utterances shorter than ``_ECHO_TEXT_MIN_TOKENS`` are never judged —+ short commands ("stopp") must always reach their handlers. 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 big vocabulary union that common words could+ false-match.+ """++ activity_ns = getattr(self, "_assistant_speech_activity_ns", 0)+ if activity_ns <= 0:+ return False+ now_ns = time.time_ns()+ if now_ns - activity_ns > int(self._ECHO_TEXT_GUARD_WINDOW_S * 1e9):+ return False+ utterance = self._echo_guard_tokens(text)+ if len(utterance) < self._ECHO_TEXT_MIN_TOKENS:+ return False+ refs = list(getattr(self, "_assistant_echo_refs", ()) or ())+ ttl_ns = int(self._ECHO_TEXT_REF_TTL_S * 1e9)+ fresh = [tokens for tokens, ref_ns in refs if now_ns - ref_ns <= ttl_ns]+ if not fresh:+ return False+ candidates = list(fresh)+ if len(fresh) >= 2:+ candidates.append(fresh[-2] + fresh[-1])+ allowed_novel = len(utterance) // 6+ for reference in candidates:+ matched = sum(+ 1+ for token in utterance+ if token in reference+ or difflib.get_close_matches(+ token, reference, n=1, cutoff=self._ECHO_TEXT_FUZZY_CUTOFF+ )+ )+ if (+ matched / len(utterance) >= self._ECHO_TEXT_MIN_OVERLAP+ and (len(utterance) - matched) <= allowed_novel+ ):+ return True+ return Falsedef _voice_confirm_pending(self) -> bool:"""True while the brain is awaiting a spoken yes/no for a deferred@@ -7307,7 +7406,17 @@ class SpeechPipeline:# Endcards. Diese Phrasen nie ans Brain — sonst ruft Gemini# open_app('WDR mediagroup GmbH im Auftrag des WDR, 2020').if _STT_HALLUCINATION_RE.search(text):- log.info("🚫 STT-Halluzination erkannt (%r) — skip Brain.", text[:80])+ log.info("🚫 STT hallucination detected (%r) — skip brain.", text[:80])+ await self._set_turn_state(TurnTakingState.LISTENING)+ return True++ # Self-echo TEXT guard (BUG-084): an utterance that is (fuzzily)+ # nothing but words Jarvis itself just voiced is speaker echo that+ # slipped the acoustic gates — answering it is how the assistant ends+ # up in a multi-turn conversation with itself. Skip the brain, keep+ # listening; a genuine user turn that adds anything new always passes.+ if self._looks_like_self_echo(text):+ log.info("🔁 Own speaker echo suppressed (%r) — skip brain.", text[:80])await self._set_turn_state(TurnTakingState.LISTENING)return True@@ -8478,6 +8587,9 @@ class SpeechPipeline:if tracker is not None and not tts_request_marked:tts_request_marked = Truetracker.mark(LatencyPhase.TTS_REQUEST_SENT)+ # Echo-guard reference (BUG-084): every voiced sentence may+ # come back through the mic as speaker echo.+ self._register_assistant_speech(sentence)try:gen = self._tts.synthesize(sentence, language_code=lang_code)except TypeError:@@ -8669,14 +8781,37 @@ class SpeechPipeline:and not barge_task.cancelled()and barge_task.result()):- log.info("🛑 Barge-in — stoppe TTS-Playback")+ log.info("🛑 Barge-in — stopping TTS playback")barged = Trueself._player.stop()+ elif (+ barge_task in done+ and not barge_task.cancelled()+ and not play_task.done()+ ):+ # Barge monitor returned WITHOUT barging (mic ended/error)+ # while the answer is still playing. Falling through to the+ # ``finally`` here used to cancel the producer + playback and+ # behead a perfectly healthy streamed answer (latent; exposed+ # once the monitor could finish fast, BUG-084). Mirror+ # ``_speak``: wait playback out under the same device-wedge+ # watchdog, still abortable by a hangup.+ tail_done = await self._await_playback(play_task, {hangup_task})+ if play_task not in tail_done:+ if hangup_task in tail_done and not hangup_task.cancelled():+ log.info("📵 Hangup during TTS — aborting turn")+ barged = True+ # else: watchdog already aborted the wedged device + logged.+ self._player.stop()+ elif not play_task.cancelled():+ exc = play_task.exception()+ if exc is not None:+ log.exception("Streaming playback error: %s", exc)elif play_task in done and not play_task.cancelled():# Whole turn played out naturally; surface any playback error.exc = play_task.exception()if exc is not None:- log.exception("Streaming-Playback-Fehler: %s", exc)+ log.exception("Streaming playback error: %s", exc)except Exception as exc: # noqa: BLE001log.exception("Streaming-TTS-Turn-Fehler: %s", exc)finally:@@ -8707,6 +8842,12 @@ class SpeechPipeline:# least one sentence reached TTS; an all-empty turn marks nothing.if tracker is not None and spoken_anything:tracker.mark(LatencyPhase.TTS_STREAM_DONE)+ # Echo-guard activity stamp (BUG-084) — unconditional: a barged turn+ # ends with NO post-TTS suppression (a real interrupter's words must+ # not be dropped), which is exactly the window where a FALSE barge's+ # echo tail becomes the next "user" turn. The text guard needs to+ # know audio was just active to catch that.+ self._touch_assistant_speech_activity()if not barged:self._suppress_session_input_after_tts("response")return "".join(full_text_parts), barged@@ -9658,6 +9799,9 @@ class SpeechPipeline:# Used by _emit_completeness_signal to pick earcon vs. spoken cue.self._session_has_assistant_spoken = Truelang_code = self._bcp47(language)+ # Echo-guard reference (BUG-084): whatever we voice may come back+ # through the mic as speaker echo.+ self._register_assistant_speech(text)try:chunks = self._tts.synthesize(text, language_code=lang_code)except TypeError:@@ -9733,6 +9877,11 @@ class SpeechPipeline:and self._playback_confirmed(play_task.result())):self._emit_spoken(text, language, kind)+ # Echo-guard activity stamp (BUG-084) — unconditional: after a FALSE+ # barge (our own echo confirmed as "user speech") there is no post-TTS+ # suppression at all, so the text guard is the only thing standing+ # between the echo tail and a brain turn.+ self._touch_assistant_speech_activity()if not barged:self._suppress_session_input_after_tts("response")return barged@@ -9740,26 +9889,44 @@ class SpeechPipeline:async def _barge_monitor(self, *, grace_s: float = 1.5, respect_input_suppression: bool = False) -> bool:- """Lauscht auf einer zweiten Mic-Instanz, ob der User während Jarvis'- TTS-Ausgabe zu sprechen beginnt. Returnt ``True`` sobald das der Fall ist.-- User-Feedback 2026-04-22: Barge-in feuerte fast sofort nach TTS-Start- (z.B. ~600 ms) und wuergte die Antwort ab — Ursache war Speaker→Mic-- Echo (Kopfhoerer-Leakage oder Open-Back). Ohne Hardware-AEC koennen- wir nur per Heuristik filtern. Jetzt aggressiv konservativ:- - 1500 ms Grace-Period (TTS-Start + initiale Echo-Phase)- - Silero-Threshold 0.97 (nur bei *sehr* klarem Speech)- - 12 consecutive Frames (~380 ms) — Echos sind kurz/fluktuierend- Ergebnis: Barge-in greift nur wenn User klar ueber die TTS-Ausgabe- spricht, nicht bei Lautsprecher-Rueckkopplung.+ """Listen on a second mic instance for the user speaking over Jarvis'+ TTS output. Returns ``True`` as soon as that is confirmed.++ History: barge-in used to fire almost immediately after TTS start+ (~600 ms) and truncated the answer — speaker→mic echo (user feedback+ 2026-04-22). The conservative policy (1.5 s grace, Silero 0.97, 12+ consecutive frames ≈ 380 ms) fixed headphone leakage but NOT open+ laptop speakers next to a built-in mic: there the assistant's own+ voice is loud, sustained, and perfectly speech-shaped, so Silero —+ which cannot tell whose voice it hears — confirmed a "barge" against+ the assistant itself. That false confirm truncated the audible answer+ AND (because a barge keeps the session listening with no post-TTS+ suppression) let the echo tail become the next "user" turn: the+ BUG-084 self-talk loop on the Mac test machine.++ This monitor therefore reuses the shared+ ``DesktopRealtimeBargeInDetector`` (the BUG-062 realtime fix) instead+ of a bare Silero loop, gaining its two defenses:++ - the static RMS energy pre-gate (quiet frames never reach ONNX), and+ - the BUG-084 adaptive echo floor, calibrated per answer from the+ grace-window frames — which during playback ARE our own echo.++ Every ``feed`` runs in a worker thread: the per-frame ONNX inference+ used to run synchronously on the voice event loop and starved the+ ~120 ms playback write batches on slow CPUs (BUG-062 cause #2 —+ constant stutter / multi-second pauses on the Intel-Mac test machine)."""+ from jarvis.realtime.desktop import DesktopRealtimeBargeInDetector++ detector = DesktopRealtimeBargeInDetector(grace_s=grace_s)try:- await asyncio.sleep(grace_s)+ # Model load off the event loop — it shares the turn with live+ # audio playback.+ await asyncio.to_thread(detector.warmup)except asyncio.CancelledError:return False-- detector = SileroEndpointer(speech_threshold=0.97)- detector._ensure_model()+ detector.start_output()try:async with MicrophoneCapture(@@ -9767,8 +9934,6 @@ class SpeechPipeline:max_queue_chunks=REALTIME_QUEUE_CHUNKS,device_priority=self._input_priority,) as mic:- residual = np.empty(0, dtype=np.float32)- speech_run = 0async for chunk in mic.stream():# Honour the global mute (orb double-click → _muted=True):# while muted the user has told us to stop listening, so a@@ -9777,7 +9942,6 @@ class SpeechPipeline:# _muted. Without this the thinking-interrupt monitor aborted a# muted-but-still-working turn (live bug 2026-07-01).if getattr(self, "_muted", False):- speech_run = 0continue# Echo-suppression (spec §4.2): while our own ACK/preamble# audio is still within the post-TTS suppression window, skip@@ -9789,28 +9953,13 @@ class SpeechPipeline:until_ns = getattr(self, "_input_suppressed_until_ns", 0)chunk_ts = getattr(chunk, "timestamp_ns", 0) or time.time_ns()if until_ns > 0 and chunk_ts < until_ns:- speech_run = 0continue- samples = pcm_bytes_to_np(chunk.pcm)- buf = np.concatenate([residual, samples])- n_full = len(buf) // VAD_FRAME_SAMPLES- if n_full == 0:- residual = buf- continue- frames = buf[: n_full * VAD_FRAME_SAMPLES].reshape(n_full, VAD_FRAME_SAMPLES)- residual = buf[n_full * VAD_FRAME_SAMPLES:]- for frame in frames:- prob = detector._prob(frame)- if prob >= 0.97:- speech_run += 1- if speech_run >= 12:- return True- else:- speech_run = 0+ if await asyncio.to_thread(detector.feed, chunk.pcm) is not None:+ return Trueexcept asyncio.CancelledError:return Falseexcept Exception as exc: # noqa: BLE001- log.warning("Barge-in-Monitor Fehler: %s", exc)+ log.warning("Barge-in monitor error: %s", exc)return Falsediff --git a/tests/unit/realtime/test_desktop.py b/tests/unit/realtime/test_desktop.pyindex 87453226a2..e0bac5b941 100644--- a/tests/unit/realtime/test_desktop.py+++ b/tests/unit/realtime/test_desktop.py@@ -233,3 +233,101 @@ def test_energy_pre_gate_passes_loud_speech_through() -> None:# Amplitude 2000/32768 ≈ 0.061 RMS — normal speaking volume.assert detector.feed(_pcm_frames(2000)) is not Noneassert calls # the model ran and confirmed+++# --- BUG-084: adaptive echo floor ----------------------------------------- #+# A FIXED RMS floor cannot cover every speaker/mic coupling: on built-in+# laptop speakers next to the built-in mic the assistant's own voice lands far+# above the static 0.010 gate, Silero (which cannot tell whose voice it hears)+# confirms, and the false barge truncates the answer and seeds the self-talk+# loop. The detector therefore calibrates a per-answer echo floor from the+# grace-window frames (pure speaker echo by construction) and keeps updating+# it from a LAGGED rolling window, so echo at the calibrated loudness is+# gated while a user speaking clearly above it still confirms.+++class _AlwaysSpeechModel:+ """Silero stand-in that calls every frame 'speech' — mirrors the real+ model's behavior on the assistant's own voice, so ONLY the energy gate+ can tell echo and user apart."""++ def __init__(self) -> None:+ self.calls = 0++ def _ensure_model(self) -> None: ...++ def _prob(self, _frame) -> float:+ self.calls += 1+ return 1.0+++def _echo_calibrated_detector(+ *, echo_amplitude: int, grace_frames: int = 30, **kwargs+) -> tuple[DesktopRealtimeBargeInDetector, _AlwaysSpeechModel]:+ model = _AlwaysSpeechModel()+ detector = DesktopRealtimeBargeInDetector(grace_s=60.0, model=model, **kwargs)+ detector.warmup()+ detector.start_output()+ # Grace window: playback echo only — calibration data, never preroll.+ assert detector.feed(_pcm_frames(*[echo_amplitude] * grace_frames)) is None+ # End the grace period deterministically (no sleeps in unit tests).+ detector._started_at = -1e9+ return detector, model+++def test_adaptive_floor_gates_echo_louder_than_the_static_floor() -> None:+ # Echo at amplitude 2000 (~0.061 RMS) sails over the static 0.010 gate —+ # exactly the Mac speakers+mic case. After grace calibration the learned+ # floor (~1.4 × 0.061) must keep gating it: no ONNX call, no confirm.+ detector, model = _echo_calibrated_detector(+ echo_amplitude=2000, consecutive_frames=3+ )+ assert detector.feed(_pcm_frames(*[2000] * 20)) is None+ assert model.calls == 0 # pure echo never reached the model+ # A user speaking clearly above the echo still confirms.+ assert detector.feed(_pcm_frames(*[6000] * 5)) is not None+ assert model.calls >= 3+++def test_adaptive_floor_lag_lets_sustained_user_speech_confirm() -> None:+ # Quiet room during grace → floor stays at the static minimum. Sustained+ # genuine speech must then confirm even though its own frames enter the+ # rolling history: the lag excludes them from their own baseline, so+ # speech can never raise its own bar before the confirm run completes.+ detector, model = _echo_calibrated_detector(+ echo_amplitude=100, consecutive_frames=12+ )+ assert detector.feed(_pcm_frames(*[2000] * 12)) is not None+ assert model.calls >= 12+++def test_adaptive_floor_disabled_with_zero_min_rms() -> None:+ # min_frame_rms=0.0 is the explicit logic-test / opt-out hook: it must+ # disable the adaptive floor as well, not only the static gate.+ detector, model = _echo_calibrated_detector(+ echo_amplitude=2000, consecutive_frames=3, min_frame_rms=0.0+ )+ assert detector.feed(_pcm_frames(*[2000] * 3)) is not None+ assert model.calls >= 3+++def test_start_output_resets_echo_calibration() -> None:+ detector, _model = _echo_calibrated_detector(+ echo_amplitude=2000, consecutive_frames=3+ )+ assert len(detector._rms_history) > 0+ detector.start_output()+ assert len(detector._rms_history) == 0+++def test_grace_frames_calibrate_but_never_become_preroll() -> None:+ detector, model = _echo_calibrated_detector(+ echo_amplitude=2000, grace_frames=10, consecutive_frames=3+ )+ # Calibration data was collected …+ assert len(detector._rms_history) == 10+ # … but nothing from the grace window is buffered as user preroll and+ # the model was never consulted during grace.+ assert len(detector._pre_buffer) == 0+ assert detector._candidate_frames == []+ assert model.calls == 0diff --git a/tests/unit/speech/test_self_echo_guard.py b/tests/unit/speech/test_self_echo_guard.pynew file mode 100644index 0000000000..e12b282525--- /dev/null+++ b/tests/unit/speech/test_self_echo_guard.py@@ -0,0 +1,83 @@+"""BUG-084: self-echo TEXT guard — last defense against the self-talk loop.++On open speakers next to a built-in mic (the Intel-Mac test machine,+2026-07-18) the assistant's own TTS can slip every acoustic gate, get+transcribed (garbled) and come back as a "user" turn — which the brain then+answers, spiralling into a multi-turn conversation with itself. These tests+pin the text-level guard: an utterance that is (fuzzily) nothing but words+Jarvis itself just voiced is dropped; anything that adds novel content is+kept (fail-open). German fixture strings quote the runtime voice product+surface (the actual Mac transcript).+"""++from __future__ import annotations++import time++from jarvis.speech.pipeline import SpeechPipeline+++def _pipeline() -> SpeechPipeline:+ # Same fixture pattern as test_thinking_interrupt_monitor: the guard+ # methods are getattr-defensive, so a bare instance is enough.+ return SpeechPipeline.__new__(SpeechPipeline)+++def test_garbled_echo_fragment_is_flagged() -> None:+ # The live loop's smoking gun: the reply tail came back STT-garbled+ # ("mich" heard as "misch") and was answered as a user turn.+ p = _pipeline()+ p._register_assistant_speech("Das freut mich zu hören.") # i18n-allow: voice fixture+ assert p._looks_like_self_echo("Misch zu hören") is True # i18n-allow: garbled echo+++def test_verbatim_echo_is_flagged() -> None:+ p = _pipeline()+ p._register_assistant_speech(+ "Guten Morgen, bei mir läuft alles bestens." # i18n-allow: voice fixture+ )+ assert p._looks_like_self_echo("bei mir läuft alles bestens") is True # i18n-allow+++def test_user_answer_with_novel_word_is_kept() -> None:+ # A genuine answer largely built from the assistant's own words must+ # survive: ONE novel token ("gut") keeps it a real turn — and the fuzzy+ # cutoff must not swallow it into "guten" (ratio exactly 0.75).+ p = _pipeline()+ p._register_assistant_speech(+ "Guten Morgen, bei mir läuft alles bestens. Was geht bei dir?" # i18n-allow+ )+ assert p._looks_like_self_echo("bei mir läuft alles gut") is False # i18n-allow+++def test_short_commands_are_never_judged() -> None:+ # Sub-3-token turns must always reach their handlers (barge "stopp",+ # hangup phrases), even when the assistant just spoke those very words.+ p = _pipeline()+ p._register_assistant_speech(+ "Soll ich wirklich stoppen und auflegen?" # i18n-allow: voice fixture+ )+ assert p._looks_like_self_echo("stoppen") is False # i18n-allow: voice fixture+ assert p._looks_like_self_echo("nicht auflegen") is False # i18n-allow: voice fixture+++def test_guard_lapses_outside_the_activity_window() -> None:+ # Long after playback the user may echo Jarvis verbatim all they want.+ p = _pipeline()+ p._register_assistant_speech("Das freut mich zu hören.") # i18n-allow: voice fixture+ p._assistant_speech_activity_ns = time.time_ns() - int(60e9)+ assert p._looks_like_self_echo("freut mich zu hören") is False # i18n-allow+++def test_echo_spanning_two_sentences_is_flagged() -> None:+ # Streaming TTS registers per sentence; an echo window can straddle the+ # boundary. The concatenation of the two newest references covers it.+ p = _pipeline()+ p._register_assistant_speech("Ich bin bereit für den Tag.") # i18n-allow+ p._register_assistant_speech("Was geht bei dir?") # i18n-allow: voice fixture+ assert p._looks_like_self_echo("für den Tag was geht") is True # i18n-allow+++def test_without_any_assistant_speech_nothing_is_flagged() -> None:+ p = _pipeline()+ assert p._looks_like_self_echo("bei mir läuft alles") is False # i18n-allow