Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix(voice): drop TTS echoes in Web Speech STT so assistant stops looping on itself
Adam Eivydfd4b5274405
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 8d775959d4..ab04af7ed3 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -42,6 +42,8 @@## Fixed+- **Voice agent looped repeating itself because Web Speech STT was transcribing the bot's own TTS as user turns** — with the default `stt.engine: 'web-speech'`, the browser's SpeechRecognition kept listening while TTS played through the speaker, so short fragments of the reply ("specific block", "activity", "or") came back in as new user finals and `sendText()` routed them to the LLM — which re-ran the last tool and produced another TTS reply, which echoed again. Unlike continuous-VAD mode, Web Speech mode had NO echo rejection. `voiceClient.js` now tracks recently-spoken TTS sentences (8s ring buffer, normalized) and drops Web Speech finals on two gates: (1) time-based — TTS currently playing or within the existing echo-tail cooldown, or (2) content-based — the final is a substring of a recent TTS sentence. Late echoes that arrive after the time window (slow STT finalize, long reverb) still get rejected by the content gate. Dropped echoes log `🔇 [voice] dropping TTS echo "..."` so the pattern is visible if it recurs. Barge-in via voice while TTS plays is now disabled in Web Speech mode (the mic has no way to distinguish user voice from speaker bleed) — users can still interrupt via the dedicated interrupt button that appears while the bot is speaking.+- **Voice agent said "I opened that" / "Added to your inbox" but nothing actually happened** — small tool-use models (Qwen3-4B class) occasionally narrate an action as their spoken reply without ever issuing the matching `tool_call`. The system-prompt biasing (enumerated trigger phrases, NEVER-echo directives) catches most of these, but leaks remain on long tool lists and fuzzy phrasings. The user heard a confident confirmation but no navigation/capture/fill happened. `pipeline.js` now detects the pattern after the turn completes — when no tool ran, the final reply is non-empty, and the reply matches a narrow action-claim regex ("I opened", "I've saved", "Navigating to", "Adding that", etc.) — and emits a `voice:error` toast ("I said I'd do that but didn't actually call the tool. Try rephrasing — e.g. 'open my daily log' or 'go to tasks'.") so the user knows the action didn't land and can rephrase. The regex is intentionally narrow on first-person past/progressive action-claim phrasings to avoid false-positives on conversational replies that mention the same verbs ("You saved that yesterday", "Your daily log is a good habit"). Also logs `🎙️ [turnId] narrate-without-call user="..." reply="..."` so we can grep server logs for recurrences. New `detectNarrationWithoutCall` helper is exported for unit testing; 6 new tests cover first-person past, progressive tense, confirmed-by-tool-run (no flag), empty reply (no flag), conversational false-negative cases, and missing-input tolerance.- **Voice agent wrote to the brain inbox instead of filling the target form field, then captured its own TTS summary as a second brain entry** — two coupled bugs. (1) `brain_capture` was always-on in the per-turn tool list, so on UI form-fill turns ("fill description with X", "type Y in the title", "put Z in the body") the LLM saw both `ui_fill` and `brain_capture`. Because `brain_capture`'s description emphasizes "note/save/remember/jot" — words that overlap with field content — the model frequently picked capture over fill. Moved `brain_capture` into the `brain` group, expanded the brain intent regex to still catch natural phrasings ("remember to buy milk", "jot down", "note that…", "save this/that", "file this", "add this to my brain inbox"), and added a `UI_FILL_INTENT_RE` that detects form-fill verbs near a field-word ("description/name/title/subject/body/content/field/input/textarea/form/label/placeholder/caption") and forcibly suppresses `brain_capture` + `daily_log_append` for that turn (also force-activates the `ui` group so `ui_fill` reaches the LLM even when the verb wasn't already in the UI regex, e.g. "put Y in the body"). System prompt gains a CRITICAL section that explicitly forbids capture tools on field-fill turns regardless of content words. (2) In hands-free mode the VAD used `bargeInMul=1.15` and `ttsTailMs=300ms` — too permissive for typical speaker→mic coupling. The bot's TTS output crossed the raised threshold, VAD transitioned to "speaking", captured the bot's own voice, submitted it as a new `voice:turn`, and the LLM processed its own paraphrased summary as a user command — creating a duplicate brain entry. Raised `bargeInMul` to 2.5, extended `ttsTailMs` to 700ms for typical room reverb, and added `bargeInOnsetConfirmMs=220` so during TTS playback + echo tail the VAD requires sustained signal (not a brief echo spike) before confirming speech-onset. Deliberate barge-in still works (sustained speech above the raised threshold). 10 new tests cover the tool-filter behavior (fill patterns drop brain_capture; natural capture phrases keep it; UI-only turns exclude brain_capture; expanded brain regex matches "remember"/"jot"/"note that").diff --git a/client/src/services/voiceClient.js b/client/src/services/voiceClient.jsindex 919605320d..ab4986a6dd 100644--- a/client/src/services/voiceClient.js+++ b/client/src/services/voiceClient.js@@ -145,6 +145,38 @@ const enqueuePlay = async (bytes) => {const isTtsActive = () => ttsQueueDepth > 0 || currentSource !== null;const isInTtsEchoWindow = () => isTtsActive() || performance.now() < ttsCooldownUntil;+// Ring of recently-spoken TTS sentences (lowercased). Web Speech STT has no+// energy-based echo rejection like continuous-VAD mode, so short fragments+// from the bot's own speaker ("specific block", "or") get transcribed back+// as user turns. We compare each final against this buffer and drop+// substring matches even after the time-based echo window expires — late+// reverb or a slow STT result can still land outside the tail.+const TTS_ECHO_MEMORY_MS = 8000;+const recentTtsSentences = [];++const normalizeForEcho = (s) => (s || '').toLowerCase().replace(/[^\p{L}\p{N}\s]/gu, '').replace(/\s+/g, ' ').trim();++const rememberTtsSentence = (sentence) => {+ const text = normalizeForEcho(sentence);+ if (!text) return;+ const now = performance.now();+ while (recentTtsSentences.length && now - recentTtsSentences[0].t > TTS_ECHO_MEMORY_MS) {+ recentTtsSentences.shift();+ }+ recentTtsSentences.push({ text, t: now });+};++const looksLikeTtsEcho = (text) => {+ const needle = normalizeForEcho(text);+ if (!needle) return false;+ const now = performance.now();+ for (const entry of recentTtsSentences) {+ if (now - entry.t > TTS_ECHO_MEMORY_MS) continue;+ if (entry.text.includes(needle)) return true;+ }+ return false;+};+// socket.io may deliver a plain ArrayBuffer, a sliced TypedArray/DataView,// or a serialized Buffer-like { type: 'Buffer', data: [...] }. Using the raw// `wav.buffer` for a sliced view would pass extra bytes to decodeAudioData,@@ -160,8 +192,9 @@ const toExactArrayBuffer = (wav) => {return null;};-socket.on('voice:tts:audio', ({ wav }) => {+socket.on('voice:tts:audio', ({ sentence, wav }) => {if (rejectingTts) return; // stale chunk from a cancelled turn — drop it+ rememberTtsSentence(sentence);const ab = toExactArrayBuffer(wav);if (!ab) return;enqueuePlay(ab).catch((err) => console.warn('[voice] playback failed:', err));@@ -652,9 +685,17 @@ export const startWebSpeechCapture = ({ language, ...callbacks } = {}) => {if (interim) callbacks.onInterim?.(interim);if (final) {callbacks.onInterim?.('');- callbacks.onFinal?.(final);- // Any successful result resets the restart-failure counter.webSpeechRestartFailures = 0;+ // Drop finals that are the bot's own TTS echoed back through the mic.+ // Two gates: (1) TTS is currently playing or within the echo tail, or+ // (2) the text is a substring of a recently-spoken sentence. The+ // content gate catches late echoes that sneak past the time window.+ const ttsActive = isInTtsEchoWindow();+ if (ttsActive || looksLikeTtsEcho(final)) {+ console.warn(`🔇 [voice] dropping TTS echo "${final.trim()}" (ttsActive=${ttsActive})`);+ return;+ }+ callbacks.onFinal?.(final);// source='voice' so the server still treats this as a spoken utterance// for dictation-mode routing — the text path otherwise bypasses it.sendText(final, 'voice');