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): break TTS echo feedback loop and stop daily-log navigation hallucinations
Adam Eivy27e582dcb300
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex a1b4b6a452..8c1e755d19 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -2,6 +2,8 @@## Fixed+- **Voice agent no longer feedback-loops on laptop speakers.** When the user ran the voice widget without headphones, TTS played through the laptop speakers, the built-in mic picked it up, STT transcribed the bot's own voice as a "user" turn, the bot replied to itself, and the loop repeated until the user manually stopped it. The existing substring-based echo gate in `voiceClient.js` was too brittle — STT mistranscribes TTS just enough that the heard text wasn't a clean substring of any spoken sentence, so the gate let the echo through. Replaced with a length-gate + trigram-overlap algorithm: utterances under 4 tokens always pass (so short barge-ins like "wait" / "stop" still interrupt the bot even if those words appear in TTS), and longer utterances are flagged as echo when they share ≥ 2 trigrams (3-word windows) with a recently-spoken sentence OR are a clean substring. Same algorithm runs server-side in a new `server/services/voice/echo.js` (per-socket `state.recentTts` ring) so continuous-mode whisper transcripts are also gated, not just Web Speech. Also added device-route detection: when the active mic shares a `groupId` with an audiooutput device AND the label looks headset-y (AirPods, Jabra, etc.), the gate is bypassed entirely (no acoustic echo path on real headphones); a `devicechange` listener re-evaluates on plug/unplug. Default-tight on uncertainty — false-headset would re-open the loop, false-built-in just makes barge-in slightly less twitchy. Files: `server/services/voice/echo.js` (new), `server/services/voice/echo.test.js` (new, 16 tests), `server/services/voice/pipeline.js`, `server/sockets/voice.js`, `client/src/services/voiceClient.js`.+- **Voice agent now navigates to the daily log via `ui_navigate`.** Three related issues caused "take me to the daily log" to fail or behave unexpectedly. (1) The `dailylog` intent regex used `\bdaily ?log\b`, which doesn't match STT typos like "daily login" / "daily logs" — so `daily_log_open` was filtered out of the offered toolset, the LLM only had `ui_navigate`, but `ui_navigate`'s description told it NOT to use that tool for daily log, leaving the model to fabricate a refusal ("Daily log isn't a valid page"). Loosened to `daily ?logi?n?s?` to absorb the drift. (2) Removed the contradictory "EXCEPT Daily Log (use daily_log_open)" carve-out from `ui_navigate`'s description and from the system prompt; the nav resolver already maps "daily log" / "journal" → `/brain/daily-log` correctly. The new rule: plain "go to / open / take me to my daily log" → `ui_navigate`; only pick `daily_log_open` when the user clearly wants to write/dictate ("start", "new", "entry", "make", "dictate"). (3) Extended `detectNarrationWithoutCall` to also catch the second narrate-without-call shape — the LLM emitting a literal tool name in its prose (e.g. `ui_navigate page="daily_log"`) without actually invoking it. The regex is now built dynamically from `getAllToolNames()` so it can't drift behind new tools. Files: `server/services/voice/tools.js`, `server/services/voice/pipeline.js`.- **Reverting a peer to plain IP (after enabling Tailnet DNS) is now sticky.** When a user cleared a peer's `host` on the Instances page to switch the federation hop back to `http://<ip>`, the next inbound `peers/announce` from that peer would silently re-adopt the DNS name — the only safeguard was "is `existing.host` empty?", which couldn't distinguish "user explicitly cleared" from "never set yet." Added a `hostManual` flag on each peer record: latched to `true` whenever the user sets or clears the host via `PUT /api/instances/peers/:id`, and respected by `handleAnnounce` (auto-adoption is gated on `!existing.host && !existing.hostManual`). Fresh peers and peers that were auto-learned still receive automatic host updates from announces; only explicit user intervention pins the choice. Also added a one-click `use IP only` inline action on each peer's host editor and a discoverable banner at the top of the Instances page that summarizes Tailnet DNS state, surfaces the local instance's MagicDNS name in the SelfCard, and walks through the three-step setup (MagicDNS admin toggle → `npm run setup:cert` → click `use <host>` per peer). Files: `server/services/instances.js`, `server/services/instances.test.js`, `client/src/pages/Instances.jsx`.- **LM Studio auto-loads a model on "No models loaded" 400.** Any caller of `callProviderAISimple` (taste questionnaire, identity, autobiography, insights, jiraReports, goalCheckIn) that hit a cold LM Studio used to error out with `Provider returned 400: { ... "No models loaded" ... }`. Now on that specific error pattern, the helper lists LM Studio's downloaded LLMs via `/api/v0/models`, picks one (preferring `provider.defaultModel`, then any id in `provider.models` that's downloaded, else the first downloaded LLM), loads it via `POST /api/v1/models/load`, and retries the chat-completion. Mirrors the existing pattern in `services/memoryClassifier.js` but driven from the provider config so every API caller benefits. File: `server/lib/aiProvider.js`.- **Stop showing the same error toast 3-4 times.** A single failing API call could surface its error message multiple times because three independent channels all toasted the same payload: `apiCore.request` toasts on every non-OK response, the server emits both `io.emit('error:occurred')` (broadcast) and `errorEvents → broadcastToErrors('error:notified')` (subscriber) for the same error, and `useErrorNotifications` listened to *both* socket events with the same handler. Two changes: (1) `useErrorNotifications` now subscribes to the targeted `error:notified` channel only — `error:occurred` was the duplicate broadcast leg — and (2) the Toast layer added a content-based dedup window (1.5s) so any duplicate from any source is silently dropped. Explicit-`id` toasts (loading→success swaps) skip dedup so progress toasts still update in place. Files: `client/src/components/ui/Toast.jsx`, `client/src/hooks/useErrorNotifications.js`.diff --git a/client/src/services/voiceClient.js b/client/src/services/voiceClient.jsindex ab4986a6dd..58071cb63b 100644--- a/client/src/services/voiceClient.js+++ b/client/src/services/voiceClient.js@@ -145,38 +145,163 @@ 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.+// Ring of recently-spoken TTS sentences (with cached trigrams). Echo+// detection uses two stacked filters:+// 1. Length gate: utterances < MIN_TOKENS_FOR_ECHO_CHECK words bypass the+// check entirely, so short barge-ins ("wait", "stop", "hold on") still+// interrupt the bot even if those words appear in TTS.+// 2. Trigram overlap: for longer utterances, require ≥ 2 shared 3-word+// windows with a recent TTS sentence. Two contiguous 3-word matches+// are strong evidence — coincidental overlap on common words rarely+// produces multiple shared trigrams. A clean substring match also+// counts (handles the case where STT picks up a clean slice of TTS).+//+// This client gate runs only on the Web Speech path where transcripts are+// produced in-browser and sent as voice:text. Whisper-based continuous mode+// sends audio to the server, so its echo gate lives in+// server/services/voice/echo.js — KEEP THE TWO IN SYNC. Both implement the+// same algorithm so tuning one (threshold, window, tokenizer) requires the+// other to match.const TTS_ECHO_MEMORY_MS = 8000;+const MIN_TOKENS_FOR_ECHO_CHECK = 4;+const MIN_SHARED_TRIGRAMS = 2;const recentTtsSentences = [];-const normalizeForEcho = (s) => (s || '').toLowerCase().replace(/[^\p{L}\p{N}\s]/gu, '').replace(/\s+/g, ' ').trim();+const tokenizeForEcho = (s) => (s || '')+ .toLowerCase()+ .replace(/[^\p{L}\p{N}\s]/gu, ' ')+ .split(/\s+/)+ .filter(Boolean);++const buildTrigrams = (tokens) => {+ if (tokens.length < 3) return [];+ const out = [];+ for (let i = 0; i + 3 <= tokens.length; i++) {+ out.push(`${tokens[i]} ${tokens[i + 1]} ${tokens[i + 2]}`);+ }+ return out;+};const rememberTtsSentence = (sentence) => {- const text = normalizeForEcho(sentence);- if (!text) return;+ const tokens = tokenizeForEcho(sentence);+ if (!tokens.length) return;const now = performance.now();while (recentTtsSentences.length && now - recentTtsSentences[0].t > TTS_ECHO_MEMORY_MS) {recentTtsSentences.shift();}- recentTtsSentences.push({ text, t: now });+ recentTtsSentences.push({+ text: tokens.join(' '),+ trigrams: new Set(buildTrigrams(tokens)),+ t: now,+ });};const looksLikeTtsEcho = (text) => {- const needle = normalizeForEcho(text);- if (!needle) return false;+ // Headphone setups have no acoustic echo path — the speaker output goes+ // into the user's ears, not the open air around the mic. Bypass the+ // content gate entirely so we never misclassify the user's actual speech.+ if (audioRoute.likelyHeadset) return false;++ const tokens = tokenizeForEcho(text);+ if (tokens.length < MIN_TOKENS_FOR_ECHO_CHECK) return false;+ const heardText = tokens.join(' ');+ const heardTrigrams = buildTrigrams(tokens);+ if (!heardTrigrams.length) 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;+ if (entry.text.includes(heardText)) return true;+ let shared = 0;+ for (const tg of heardTrigrams) {+ if (entry.trigrams.has(tg)) {+ shared += 1;+ if (shared >= MIN_SHARED_TRIGRAMS) return true;+ }+ }}return false;};+// ─── Audio route detection (headset vs built-in) ────────────────────────+// Headphones eliminate the speaker-into-mic acoustic path that causes the+// echo loop, so we can relax echo gates when we're confident the user is+// on a headset. Default-tight on uncertainty: a false "headset" detection+// re-opens the loop, while a false "built-in" detection only makes barge-in+// slightly less twitchy.+//+// Strong signal: the active mic shares a `groupId` with an audiooutput+// device AND the device label looks headset-y (AirPods, headset, buds, …).+// `groupId` alone isn't enough — a laptop's built-in mic + built-in speakers+// also share a groupId. Labels alone aren't enough either — a custom-named+// device ("Adam's USB Mic") won't match. Both required → high confidence.++const HEADSET_LABEL_RE = /(headphone|headset|airpods|buds|earphone|in[- ]?ear|jabra|sennheiser|bose|sony wh-|sony wf-)/i;+const BUILTIN_LABEL_RE = /(macbook|built[- ]?in|internal)/i;++const audioRoute = {+ likelyHeadset: false,+ label: null,+ reason: 'not detected',+ checkedAt: 0,+};++const detectAudioRoute = async (activeStream) => {+ if (!navigator.mediaDevices?.enumerateDevices) {+ audioRoute.likelyHeadset = false;+ audioRoute.reason = 'enumerateDevices unsupported';+ return audioRoute;+ }+ const devices = await navigator.mediaDevices.enumerateDevices().catch(() => []);+ const mics = devices.filter((d) => d.kind === 'audioinput');+ const outs = devices.filter((d) => d.kind === 'audiooutput');+ const settings = activeStream?.getAudioTracks?.()?.[0]?.getSettings?.() || {};+ const activeMic = mics.find((d) => d.deviceId === settings.deviceId)+ || mics.find((d) => d.deviceId === 'default')+ || mics[0];+ if (!activeMic) {+ audioRoute.likelyHeadset = false;+ audioRoute.reason = 'no active mic';+ return audioRoute;+ }+ const sameGroup = activeMic.groupId+ && outs.some((o) => o.groupId === activeMic.groupId);+ const label = activeMic.label || '';+ const headsetByLabel = HEADSET_LABEL_RE.test(label);+ const builtInByLabel = BUILTIN_LABEL_RE.test(label);+ // Require BOTH groupId match AND headset-y label, AND not explicitly a+ // built-in device. This is the conservative configuration.+ audioRoute.likelyHeadset = !!(sameGroup && headsetByLabel && !builtInByLabel);+ audioRoute.label = label;+ audioRoute.reason = audioRoute.likelyHeadset+ ? 'groupId+label match'+ : `sameGroup=${!!sameGroup} headsetByLabel=${headsetByLabel} builtInByLabel=${builtInByLabel}`;+ audioRoute.checkedAt = performance.now();+ console.log(`🎧 [voice] audio route: ${audioRoute.likelyHeadset ? 'headset' : 'open-air'} (${audioRoute.reason}) label="${label}"`);+ return audioRoute;+};++// Re-detect when the user plugs/unplugs hardware mid-session. Without this,+// disconnecting headphones leaves us in "headset" mode and the loop returns.+if (typeof navigator !== 'undefined' && navigator.mediaDevices?.addEventListener) {+ navigator.mediaDevices.addEventListener('devicechange', () => {+ // We don't have an active stream reference here, so re-detect against+ // whatever device the next getUserMedia() picks. Until then, be safe+ // and assume open-air.+ audioRoute.likelyHeadset = false;+ audioRoute.reason = 'devicechange — pending re-detect';+ });+}++// Live introspection from the browser console: `window.__portosAudioRoute`.+// Mirrors the existing `__portosVadDebug` pattern so both diagnostics live+// at the same handle.+if (typeof window !== 'undefined') {+ Object.defineProperty(window, '__portosAudioRoute', {+ configurable: true,+ get: () => ({ ...audioRoute }),+ });+}+// 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,@@ -220,6 +345,9 @@ export const startCapture = async () => {autoGainControl: true,},});+ // Run after permission is granted — `enumerateDevices` only returns+ // device labels post-grant, and the headset heuristic relies on labels.+ detectAudioRoute(stream).catch(() => {});const mimeType = pickMime();chunks = [];recorder = new MediaRecorder(stream, { mimeType });@@ -470,7 +598,9 @@ const handleFrame = (frame) => {if (vadState === 'idle') {// Raise the bar while TTS plays AND during the echo tail so neither the// bot's live audio nor reverb through the mic trigger a false barge-in.- const inEcho = isInTtsEchoWindow();+ // Skip the bump entirely on a confirmed headset — there's no acoustic+ // path from speaker to mic, so the user can interrupt at normal volume.+ const inEcho = isInTtsEchoWindow() && !audioRoute.likelyHeadset;const effectiveOnRms = inEcho ? onRms * VAD.bargeInMul : onRms;const effectiveConfirmMs = inEcho ? VAD.bargeInOnsetConfirmMs : VAD.onsetConfirmMs;if (rms > effectiveOnRms) {@@ -548,6 +678,7 @@ export const startContinuous = async (callbacks = {}) => {autoGainControl: false,},});+ detectAudioRoute(continuousStream).catch(() => {});const Ctor = window.AudioContext || window.webkitAudioContext;continuousCtx = new Ctor();diff --git a/server/services/voice/echo.js b/server/services/voice/echo.jsnew file mode 100644index 0000000000..1ad032923e--- /dev/null+++ b/server/services/voice/echo.js@@ -0,0 +1,86 @@+// Detect when an inbound voice transcript is actually the bot's own TTS being+// picked up by the user's microphone (laptop speakers + built-in mic, no+// headphones). Without this, the bot replies to its own speech and runs in a+// feedback loop until the user manually stops it.+//+// A mirror of this algorithm runs client-side in+// client/src/services/voiceClient.js for the Web Speech STT path (which+// produces transcripts in-browser and never sends audio to the server).+// KEEP THE TWO IN SYNC — same tokenizer, same thresholds, same window.+//+// Strategy — two stacked filters:+// 1. Length gate: utterances shorter than MIN_TOKENS_FOR_ECHO_CHECK words+// are NEVER classified as echo. Barge-ins are typically short+// ("wait", "stop", "actually no") while echoes are full sentences.+// This single rule preserves user interrupts even when their words also+// appear in TTS.+// 2. Trigram match: for longer utterances, share-counting against the+// trigrams of recently-spoken TTS sentences. Two contiguous 3-word+// windows aligning is strong evidence — coincidental overlap on common+// words rarely produces multiple shared trigrams.+//+// Time-windowed: TTS sentences older than `windowMs` are ignored so an echo+// from 30 seconds ago can't suppress a legitimate later utterance.++export const ECHO_WINDOW_MS = 8000;+export const MIN_TOKENS_FOR_ECHO_CHECK = 4;+export const MIN_SHARED_TRIGRAMS = 2;++export const tokenize = (s) => (s || '')+ .toLowerCase()+ .replace(/[^\p{L}\p{N}\s]/gu, ' ')+ .split(/\s+/)+ .filter(Boolean);++export const trigramsOf = (tokens) => {+ if (!Array.isArray(tokens) || tokens.length < 3) return [];+ const out = [];+ for (let i = 0; i + 3 <= tokens.length; i++) {+ out.push(`${tokens[i]} ${tokens[i + 1]} ${tokens[i + 2]}`);+ }+ return out;+};++// Push a freshly-spoken TTS sentence into the per-socket echo memory and+// drop entries that have aged out. Mutates `recent` in place and returns it.+export const rememberTtsSentence = (recent, sentence, { now = Date.now(), windowMs = ECHO_WINDOW_MS } = {}) => {+ const tokens = tokenize(sentence);+ if (!tokens.length) return recent;+ // Expire stale entries before appending so the buffer doesn't grow unbounded.+ for (let i = recent.length - 1; i >= 0; i--) {+ if (now - recent[i].t > windowMs) recent.splice(i, 1);+ }+ recent.push({+ text: tokens.join(' '),+ trigrams: new Set(trigramsOf(tokens)),+ t: now,+ });+ return recent;+};++// Returns true iff the transcript is almost certainly the bot's own TTS+// echoed back. Default-false on any uncertainty so we never silently drop+// legitimate user input.+export const isEchoOfRecentTts = (transcript, recent, { now = Date.now(), windowMs = ECHO_WINDOW_MS } = {}) => {+ const tokens = tokenize(transcript);+ if (tokens.length < MIN_TOKENS_FOR_ECHO_CHECK) return false;+ if (!Array.isArray(recent) || !recent.length) return false;++ const heardText = tokens.join(' ');+ const heardTrigrams = trigramsOf(tokens);+ if (!heardTrigrams.length) return false;++ for (const entry of recent) {+ if (now - entry.t > windowMs) continue;+ // Substring fallback: clean echo where heard ⊆ said.+ if (entry.text.includes(heardText)) return true;+ let shared = 0;+ for (const tg of heardTrigrams) {+ if (entry.trigrams.has(tg)) {+ shared += 1;+ if (shared >= MIN_SHARED_TRIGRAMS) return true;+ }+ }+ }+ return false;+};diff --git a/server/services/voice/echo.test.js b/server/services/voice/echo.test.jsnew file mode 100644index 0000000000..0dfa4cfb9e--- /dev/null+++ b/server/services/voice/echo.test.js@@ -0,0 +1,121 @@+import { describe, it, expect } from 'vitest';+import {+ tokenize,+ trigramsOf,+ rememberTtsSentence,+ isEchoOfRecentTts,+ MIN_SHARED_TRIGRAMS,+} from './echo.js';++describe('tokenize', () => {+ it('lowercases and strips punctuation', () => {+ expect(tokenize('Hello, World!')).toEqual(['hello', 'world']);+ });++ it('returns empty array for empty / nullish input', () => {+ expect(tokenize('')).toEqual([]);+ expect(tokenize(null)).toEqual([]);+ expect(tokenize(undefined)).toEqual([]);+ });++ it('handles unicode letters and digits', () => {+ expect(tokenize('Café 2026 — déjà vu')).toEqual(['café', '2026', 'déjà', 'vu']);+ });+});++describe('trigramsOf', () => {+ it('returns empty when fewer than 3 tokens', () => {+ expect(trigramsOf(['a', 'b'])).toEqual([]);+ expect(trigramsOf([])).toEqual([]);+ });++ it('produces sliding 3-word windows', () => {+ expect(trigramsOf(['a', 'b', 'c', 'd'])).toEqual(['a b c', 'b c d']);+ });+});++describe('rememberTtsSentence', () => {+ it('appends a normalized entry with trigrams', () => {+ const recent = [];+ rememberTtsSentence(recent, 'Hello there friend!', { now: 1000 });+ expect(recent).toHaveLength(1);+ expect(recent[0].text).toBe('hello there friend');+ expect(recent[0].trigrams.has('hello there friend')).toBe(true);+ expect(recent[0].t).toBe(1000);+ });++ it('skips empty / whitespace-only sentences', () => {+ const recent = [];+ rememberTtsSentence(recent, ' ', { now: 1 });+ rememberTtsSentence(recent, '', { now: 1 });+ expect(recent).toEqual([]);+ });++ it('drops entries older than windowMs before appending', () => {+ const recent = [];+ rememberTtsSentence(recent, 'old sentence here', { now: 0, windowMs: 1000 });+ rememberTtsSentence(recent, 'newer sentence appears', { now: 2000, windowMs: 1000 });+ expect(recent).toHaveLength(1);+ expect(recent[0].text).toBe('newer sentence appears');+ });+});++describe('isEchoOfRecentTts', () => {+ const NOW = 1_700_000_000_000;+ const seed = (sentences, now = NOW) => {+ const recent = [];+ for (const s of sentences) rememberTtsSentence(recent, s, { now });+ return recent;+ };++ it('returns false for empty / no-tts state', () => {+ expect(isEchoOfRecentTts('anything goes here', [], { now: NOW })).toBe(false);+ expect(isEchoOfRecentTts('', seed(['hello world friend']), { now: NOW })).toBe(false);+ });++ it('lets short barge-ins through even when words appear in TTS', () => {+ // Bot said: "you should wait for the database, that's wrong syntax"+ // User barges in with "wait" → must not be flagged as echo.+ const recent = seed(['you should wait for the database thats wrong syntax']);+ expect(isEchoOfRecentTts('wait', recent, { now: NOW })).toBe(false);+ expect(isEchoOfRecentTts('stop', recent, { now: NOW })).toBe(false);+ expect(isEchoOfRecentTts('hold on', recent, { now: NOW })).toBe(false);+ expect(isEchoOfRecentTts('actually no', recent, { now: NOW })).toBe(false);+ });++ it('lets a 4-word barge-in through when only 1 trigram matches', () => {+ // User: "wait thats wrong syntax" (4 tokens → 2 trigrams)+ // Bot: "wait for the database thats wrong syntax" (7 tokens → 5 trigrams)+ // Shared: only "thats wrong syntax" → 1 trigram → below threshold of 2.+ // (No substring match either — the bot inserts "for the database" between.)+ const recent = seed(['wait for the database thats wrong syntax']);+ expect(isEchoOfRecentTts('wait thats wrong syntax', recent, { now: NOW })).toBe(false);+ });++ it('flags long transcripts that share 2+ trigrams as echo', () => {+ const recent = seed(['the meeting starts at three pm in the conference room']);+ expect(isEchoOfRecentTts('the meeting starts at three pm', recent, { now: NOW })).toBe(true);+ });++ it('flags clean substring echo even with exactly 4 tokens', () => {+ const recent = seed(['you have three tasks due tomorrow']);+ // 4 tokens — passes length gate. Substring of TTS → echo.+ expect(isEchoOfRecentTts('have three tasks due', recent, { now: NOW })).toBe(true);+ });++ it('ignores tts entries older than the window', () => {+ const recent = seed(['the meeting starts at three pm in the conference room'], 0);+ expect(isEchoOfRecentTts('the meeting starts at three pm', recent, { now: 9001 })).toBe(false);+ });++ it('handles minor STT punctuation drift via tokenization', () => {+ const recent = seed(['Note that the report is due Friday afternoon.']);+ expect(isEchoOfRecentTts('note, that the report is due Friday afternoon', recent, { now: NOW })).toBe(true);+ });++ it(`requires at least ${MIN_SHARED_TRIGRAMS} shared trigrams for the trigram path`, () => {+ // Heard: 5 tokens → 3 trigrams. Bot: completely different except 1 trigram.+ const recent = seed(['quick brown fox jumps over fence', 'unrelated content here today now']);+ expect(isEchoOfRecentTts('the quick brown fox runs', recent, { now: NOW })).toBe(false);+ });+});diff --git a/server/services/voice/pipeline.js b/server/services/voice/pipeline.jsindex 92789739bb..ac7a746756 100644--- a/server/services/voice/pipeline.js+++ b/server/services/voice/pipeline.js@@ -10,7 +10,8 @@ import { transcribe } from './stt.js';import { synthesize } from './tts.js';import { streamChat } from './llm.js';import { getVoiceConfig } from './config.js';-import { getToolSpecsForIntent, classifyIntent, dispatchTool, UI_KINDS } from './tools.js';+import { getToolSpecsForIntent, classifyIntent, dispatchTool, getAllToolNames, UI_KINDS } from './tools.js';+import { isEchoOfRecentTts, rememberTtsSentence } from './echo.js';import { appendJournal, getToday } from '../brainJournal.js';// Compact per-page UI summary the LLM uses to drive ui_* tools. Keep it@@ -117,7 +118,7 @@ const buildSystemPrompt = (cfg) => {'You MUST call the matching tool whenever the user requests an action — ' +'never describe the action in words instead of calling the tool. ' +'Trigger phrases that REQUIRE a tool call: ' +- '"open"/"go to"/"take me to"/"show me"/"navigate to" X → call ui_navigate with page=X (NOT daily_log_open — that tool is ONLY for the Daily Log / dictation). "Take me to tasks" → ui_navigate page="tasks". "Chief of staff agents" → ui_navigate page="agents". "Open calendar" → ui_navigate page="calendar". Only pick daily_log_open when the user explicitly says "daily log", "log entry", or "journal". ' ++ '"open"/"go to"/"take me to"/"show me"/"navigate to" X → call ui_navigate with page=X. "Take me to tasks" → ui_navigate page="tasks". "Chief of staff agents" → ui_navigate page="agents". "Open calendar" → ui_navigate page="calendar". "Take me to the daily log" → ui_navigate page="daily log". Pick daily_log_open INSTEAD of ui_navigate only when the user clearly wants to WRITE/DICTATE — phrases like "start a new daily log", "let\'s make a log entry", "new daily log", "let me dictate to my log". Plain navigation to the daily log goes through ui_navigate. ' +'"Select X tab"/"switch to the X tab"/"click X"/"press the X button"/"pick Y from the Z dropdown"/"fill X with Y"/"check/uncheck X" — the LLM receives a compact "Current UI state" summary at the start of UI-driving turns listing Tabs, Buttons, Links, Inputs, Selects, Checkboxes. Use ui_click for tabs/buttons/links, ui_fill for text inputs, ui_select for dropdowns, ui_check for checkboxes. Pass the EXACT label shown in the UI summary. Prefer the `kind` argument when you have it (tab vs button). If the label isn\'t in the current UI summary, call ui_list_interactables OR ui_navigate first — do NOT guess. Active tab is marked with * in the summary; don\'t click it again. ' +'FORM FILL vs CAPTURE — CRITICAL: When the user directs content INTO a visible field ("fill description with X", "type X in the name field", "put X in the body", "enter X into title", "set the subject to X"), the target is the FIELD and X is the new value. ALWAYS call ui_fill with label=<field> and value=<X>. NEVER call brain_capture or daily_log_append for these turns — even when X contains words like "remember", "note", "save", or "jot", those are field content, not a request to capture to the inbox. Only use brain_capture when the user captures without referring to a page field ("remember to buy milk", "add this to my brain inbox", "save that for later"). ' +'CHAINED UI FLOWS: after a ui_navigate / ui_click / ui_fill / ui_select / ui_check succeeds, its tool result includes a `ui` field with the FRESH page state (a new page has loaded, a modal may have opened, a tab may have switched, new fields may be visible). Always re-read this `ui` field before choosing the next action — don\'t rely on the original per-turn UI summary after an action has fired. For multi-step flows like "create a task called Foo with description Bar": ui_click New Task → read result.ui → ui_fill Name=Foo → read result.ui → ui_fill Description=Bar → ui_click Save. Do it all in ONE turn, not one action per turn. Same for cross-page flows like "go to tasks and add a task called Foo": ui_navigate page="tasks" → read result.ui → ui_click New Task → read result.ui → ui_fill Name=Foo → ui_click Save, all in ONE turn. ' +@@ -192,8 +193,18 @@ const STOP_DICTATION_RE = /^(stop|end|exit|cancel|pause)\s+(dictation|dictating|// file last year") don't false-positive. Exported for unit testing.const ACTION_CLAIM_RE = /\b(?:I(?:'ve| have| just| already)?\s+(?:open(?:ed|ing)?|navigat(?:ed|ing)|sav(?:ed|ing)|add(?:ed|ing)|not(?:ed|ing)|captur(?:ed|ing)|remember(?:ed|ing)?|fill(?:ed|ing)|click(?:ed|ing)|select(?:ed|ing)|switch(?:ed|ing)|set|filed|logg(?:ed|ing))|(?:opening|navigating|saving|adding|noting|capturing|filing|logging|filling|clicking|selecting|switching)\s+(?:to\s+|your|the|that|this|it))\b/i;+// Catches the second narrate-without-call failure mode: the model emits the+// literal tool name as plain text ("ui_navigate page=\"daily_log\"",+// "I'll call daily_log_open"). Different shape from ACTION_CLAIM_RE — the+// model isn't claiming the action happened, it's writing the tool call out+// loud as if dictating to itself. Only fires when no tool actually ran.+//+// Built from the canonical tool list so it can't drift behind new tools.+const TOOL_NAME_AS_TEXT_RE = new RegExp(`\\b(?:${getAllToolNames().join('|')})\\b`, 'i');+export const detectNarrationWithoutCall = ({ finalText, toolRuns }) =>- toolRuns?.length === 0 && !!finalText?.trim() && ACTION_CLAIM_RE.test(finalText);+ toolRuns?.length === 0 && !!finalText?.trim()+ && (ACTION_CLAIM_RE.test(finalText) || TOOL_NAME_AS_TEXT_RE.test(finalText));// Short correlation id so overlapping turns in the logs can be told apart// (user interrupts, late-arriving retries). 5 chars of base36 randomness is@@ -243,6 +254,22 @@ export const runTurn = async ({ audio, text, mimeType, source, history = [], emi}if (signal?.aborted) return { transcript: userText, reply: '' };+ // Echo gate: if the transcript looks like the bot's own TTS being picked+ // up by a laptop mic (built-in mic + speakers, no headphones), drop the+ // turn rather than feeding it to the LLM. Without this gate the bot+ // replies to its own voice and runs in a feedback loop.+ //+ // Only applies to spoken input — typed text never echoes. The detector is+ // length-gated (< 4 words always passes) so short barge-ins like "wait"+ // and "stop" still interrupt even if those words appear in TTS.+ if (state?.recentTts?.length && (!text || source === 'voice')) {+ if (isEchoOfRecentTts(userText, state.recentTts)) {+ console.warn(`🔇 [${turnId}] dropping TTS echo "${userText.slice(0, 80)}"`);+ emit('voice:idle', { reason: 'echo-suppressed' });+ return { transcript: userText, reply: '' };+ }+ }+// Dictation mode short-circuits the LLM: the user's speech goes straight// into the daily-log entry unless they say the stop phrase, which ends// dictation and falls through to a normal confirmation turn.@@ -336,6 +363,10 @@ export const runTurn = async ({ audio, text, mimeType, source, history = [], emiif (signal?.aborted) return;ttsTimings.push(latencyMs);tlog(`tts.done #${i} ${latencyMs}ms synth+queue=${Date.now() - t0}ms`);+ // Track what we just said so the next inbound transcript can be checked+ // for echo. Done before emit so an immediately-arriving STT result on+ // the next event-loop tick already sees this sentence in the buffer.+ if (state?.recentTts) rememberTtsSentence(state.recentTts, sentence);emit('voice:tts:audio', { sentence, wav, latencyMs });};diff --git a/server/services/voice/tools.js b/server/services/voice/tools.jsindex c8b3a19cd4..628fd55f66 100644--- a/server/services/voice/tools.js+++ b/server/services/voice/tools.js@@ -90,7 +90,11 @@ const GROUP_INTENT = {goals: /\b(goals?|progress|objective)\b/i,system: /\b(restart|crash(?:ed)?|pm2|process|service|is.*(?:running|down|up)|status)\b/i,feeds: /\b(feeds?|news|unread|article|rss|digest)\b/i,- dailylog: /\b(daily ?log|journal|dictat|log entry|log something|to my log|read (?:back )?my log)\b/i,+ // `daily ?logi?n?s?` absorbs whisper/Web-Speech transcription drift on+ // "daily log": variants like "daily logs" (plural), "daily login" (heard as+ // a familiar word), "daily logins" all gate the daily-log toolset on. The+ // \b anchors keep it from matching inside unrelated words like "logging".+ dailylog: /\b(daily ?logi?n?s?|journal|dictat|log entry|log something|to my log|read (?:back )?my log)\b/i,ui: UI_INTENT_RE,};@@ -745,9 +749,10 @@ const TOOLS = [{name: 'ui_navigate',description:- 'Navigate the UI to a page. Use for "take me to X" / "open X" / "go to X" EXCEPT Daily Log (use daily_log_open). ' +- 'Pass `page` as a short name the user would say: tasks, agents, gsd, briefing, calendar, goals, brain, meatspace, memory, messages, settings, shell, instances, wiki, character, health, body, alcohol, etc. ' +- 'Server resolves fuzzy — "chief of staff tasks", "cos tasks", "task page" all map to tasks. If no match, the error lists valid names.',+ 'Navigate the UI to a page. Use for "take me to X" / "open X" / "go to X" — including the Daily Log when the user just wants to VIEW it without writing. ' ++ 'Pass `page` as a short name the user would say: tasks, agents, gsd, briefing, calendar, goals, brain, meatspace, memory, messages, settings, shell, instances, wiki, character, health, body, alcohol, daily log, journal, etc. ' ++ 'Server resolves fuzzy — "chief of staff tasks", "cos tasks", "task page" all map to tasks. If no match, the error lists valid names. ' ++ 'Only prefer daily_log_open over this tool when the user clearly wants to write/dictate ("start", "new", "entry", "make", "dictate"); plain "open my daily log" or "go to the daily log" should use ui_navigate.',parameters: {type: 'object',properties: {@@ -916,6 +921,11 @@ const toSpec = (t) => ({export const getToolSpecs = () => TOOLS.map(toSpec);+// Canonical list of tool names, used by pipeline.js to detect the+// "narrate-instead-of-call" failure where the LLM emits a literal tool name+// in its prose. Exported so the regex can't drift when tools are added.+export const getAllToolNames = () => TOOLS.map((t) => t.name);+// Plain-format metadata for non-LLM consumers (the command palette) so routes// don't need to reach through OpenAI-shaped function specs to get to the same// fields. Shape-independent from getToolSpecs.diff --git a/server/sockets/voice.js b/server/sockets/voice.jsindex e1f383b87b..b347e08ee5 100644--- a/server/sockets/voice.js+++ b/server/sockets/voice.js@@ -36,6 +36,10 @@ export const registerVoiceHandlers = (socket) => {// ui:click, wait for the client's fresh index before the next tool// runs so the LLM can see the modal/new content it just opened.uiWaiters: [],+ // Ring of recently-spoken TTS sentences (with cached trigrams). The+ // pipeline uses this to detect the bot's own voice being echoed back+ // through the user's mic when laptop speakers are in play.+ recentTts: [],};const pushHistory = (role, content) => {