Skip to content

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

address review (codex): scope proactive echo memory to the recipient tab; clear client ownership on disconnect

[._.]/ Adam Eivy8daa5262ee5f
diff --git a/client/src/services/voiceClient.js b/client/src/services/voiceClient.js
index a2677ff4f0..53fdbf1ace 100644
--- a/client/src/services/voiceClient.js
+++ b/client/src/services/voiceClient.js
@@ -413,6 +413,17 @@ socket.on('voice:output:detached', () => {
isVoiceOutputPrimary = false;
notifyVoiceOutputPrimary();
});
+// A disconnect ends this socket's ownership — the server released it and, on
+// reconnect, this tab gets a fresh socket with no claim (it only re-announces
+// availability, and re-claims only if focused). Clear the flag so the widget
+// doesn't keep showing "speaker" while output is routed to another tab. The
+// server's voice:output:detached can't reach an already-disconnected socket, so
+// this local reset is the only signal.
+socket.on('disconnect', () => {
+ if (!isVoiceOutputPrimary) return;
+ isVoiceOutputPrimary = false;
+ notifyVoiceOutputPrimary();
+});
// Claim on focus / visibility so proactive audio follows the active tab. Reuse
// the shared visibility singleton (one document-level listener for the whole
diff --git a/server/services/voice/echo.js b/server/services/voice/echo.js
index 9c0a663c3d..26264f0a34 100644
--- a/server/services/voice/echo.js
+++ b/server/services/voice/echo.js
@@ -58,26 +58,30 @@ export const rememberTtsSentence = (recent, sentence, { now = Date.now(), window
return recent;
};
-// Per-socket echo buffers registered by `sockets/voice.js`. Server-emitted
-// proactive speech (`speakProactive`) broadcasts to every connected client
-// but has no socket context of its own, so it can't reach into a single
-// socket's `state.recentTts`. This module-scope registry lets the proactive
-// path write a remembered sentence into every active socket's buffer in one
-// call, so the next user turn picks up echoed proactive audio and drops it
-// just like an in-turn TTS line. Single-instance app, so a process-wide
-// registry is fine.
-const echoBuffers = new Set();
+// Per-socket echo buffers keyed by their owning socket, registered by
+// `sockets/voice.js`. Server-emitted proactive speech (`speakProactive`) has no
+// socket context of its own, so this module-scope registry lets the proactive
+// path reach the RECIPIENT socket's `state.recentTts` — proactive audio plays
+// on exactly one tab, so only that tab's mic can echo it back; remembering the
+// line in that one buffer suppresses the echo on the next user turn without
+// falsely flagging a different device's legitimate speech (which never heard
+// it). Single-instance app, so a process-wide registry is fine.
+const echoBuffers = new Map(); // socket -> recentTts buffer
-export const registerEchoBuffer = (buf) => {
- if (Array.isArray(buf)) echoBuffers.add(buf);
+export const registerEchoBuffer = (socket, buf) => {
+ if (socket && Array.isArray(buf)) echoBuffers.set(socket, buf);
};
-export const unregisterEchoBuffer = (buf) => {
- echoBuffers.delete(buf);
+export const unregisterEchoBuffer = (socket) => {
+ echoBuffers.delete(socket);
};
-export const rememberTtsForAllSockets = (sentence, opts = {}) => {
- for (const buf of echoBuffers) rememberTtsSentence(buf, sentence, opts);
+// Remember a spoken line in a single socket's echo buffer — the tab that will
+// actually play the audio. No-op when the socket has no registered buffer
+// (e.g. no tab is currently the voice-output recipient).
+export const rememberTtsForSocket = (socket, sentence, opts = {}) => {
+ const buf = echoBuffers.get(socket);
+ if (buf) rememberTtsSentence(buf, sentence, opts);
};
// Returns true iff the transcript is almost certainly the bot's own TTS
diff --git a/server/services/voice/echo.test.js b/server/services/voice/echo.test.js
index d010bf6641..4d4efc3157 100644
--- a/server/services/voice/echo.test.js
+++ b/server/services/voice/echo.test.js
@@ -6,7 +6,7 @@ import {
isEchoOfRecentTts,
registerEchoBuffer,
unregisterEchoBuffer,
- rememberTtsForAllSockets,
+ rememberTtsForSocket,
MIN_SHARED_TRIGRAMS,
} from './echo.js';
@@ -124,34 +124,43 @@ describe('isEchoOfRecentTts', () => {
});
describe('echo buffer registry (proactive-speech echo suppression)', () => {
- it('fans out a sentence to every registered buffer', () => {
+ it('remembers a sentence only in the recipient socket buffer, not others', () => {
+ const sockA = { id: 'a' };
+ const sockB = { id: 'b' };
const a = [];
const b = [];
- registerEchoBuffer(a);
- registerEchoBuffer(b);
+ registerEchoBuffer(sockA, a);
+ registerEchoBuffer(sockB, b);
try {
- rememberTtsForAllSockets('proactive briefing sentence', { now: 5000 });
+ // Proactive audio plays on sockA only — remember only in its buffer, so a
+ // matching turn from sockB's device isn't falsely dropped as an echo.
+ rememberTtsForSocket(sockA, 'proactive briefing sentence', { now: 5000 });
expect(a).toHaveLength(1);
- expect(b).toHaveLength(1);
expect(a[0].text).toBe('proactive briefing sentence');
+ expect(b).toHaveLength(0);
} finally {
- unregisterEchoBuffer(a);
- unregisterEchoBuffer(b);
+ unregisterEchoBuffer(sockA);
+ unregisterEchoBuffer(sockB);
}
});
- it('stops writing to a buffer after it is unregistered', () => {
+ it('stops writing to a buffer after its socket is unregistered', () => {
+ const sock = { id: 'a' };
const a = [];
- registerEchoBuffer(a);
- unregisterEchoBuffer(a);
- rememberTtsForAllSockets('proactive briefing sentence', { now: 5000 });
+ registerEchoBuffer(sock, a);
+ unregisterEchoBuffer(sock);
+ rememberTtsForSocket(sock, 'proactive briefing sentence', { now: 5000 });
expect(a).toEqual([]);
});
- it('ignores non-array registrations', () => {
+ it('is a no-op for an unregistered socket', () => {
+ expect(() => rememberTtsForSocket({ id: 'ghost' }, 'hi', { now: 5000 })).not.toThrow();
+ });
+
+ it('ignores registrations with a missing socket or non-array buffer', () => {
// No throw; nothing observable to assert beyond "doesn't crash".
- expect(() => registerEchoBuffer(null)).not.toThrow();
- expect(() => registerEchoBuffer(undefined)).not.toThrow();
- expect(() => registerEchoBuffer({})).not.toThrow();
+ expect(() => registerEchoBuffer(null, [])).not.toThrow();
+ expect(() => registerEchoBuffer({ id: 'x' }, null)).not.toThrow();
+ expect(() => registerEchoBuffer({ id: 'x' }, {})).not.toThrow();
});
});
diff --git a/server/services/voice/proactiveSpeech.js b/server/services/voice/proactiveSpeech.js
index 658b216173..cd41333f53 100644
--- a/server/services/voice/proactiveSpeech.js
+++ b/server/services/voice/proactiveSpeech.js
@@ -17,7 +17,7 @@
import { synthesize } from './tts.js';
import { getVoiceConfig } from './config.js';
-import { rememberTtsForAllSockets } from './echo.js';
+import { rememberTtsForSocket } from './echo.js';
import { emitVoiceOutput } from './voiceOutput.js';
import { getUserTimezone, getLocalParts, isWithinTimeWindow } from '../../lib/timezone.js';
@@ -111,9 +111,6 @@ export const speakProactive = async ({ io, text, priority = 'normal', source = '
}
const { wav, latencyMs } = await synthesize(trimmed);
- // Mirror the per-turn `state.recentTts` write so a proactive line bleeding
- // from speakers back into the mic gets dropped as echo on the next turn.
- rememberTtsForAllSockets(trimmed);
// `voice:speak` is the proactive-speech channel — distinct from per-turn
// `voice:tts:audio` so the client can render a different visual cue
// (subtle pill instead of full conversation entry) and skip recording
@@ -127,6 +124,12 @@ export const speakProactive = async ({ io, text, priority = 'normal', source = '
source,
ts: Date.now(),
});
+ // Mirror the per-turn `state.recentTts` write so a proactive line bleeding
+ // from speakers back into the mic gets dropped as echo on the next turn — but
+ // ONLY on the recipient tab. Only that tab plays the audio, so only its mic
+ // can echo it; recording it on other connected devices would falsely suppress
+ // their legitimate speech (they never heard the line).
+ if (delivery.socket) rememberTtsForSocket(delivery.socket, trimmed);
const dest = delivery.socketId ?? 'none';
console.log(`🔔 voice: proactive sent (${priority}) → ${dest} "${trimmed.slice(0, 80)}" (${latencyMs}ms synth)`);
return { ok: true, latencyMs };
diff --git a/server/services/voice/proactiveSpeech.test.js b/server/services/voice/proactiveSpeech.test.js
index 85c837d103..73ec17f976 100644
--- a/server/services/voice/proactiveSpeech.test.js
+++ b/server/services/voice/proactiveSpeech.test.js
@@ -27,6 +27,7 @@ const {
MAX_PROACTIVE_TEXT_LEN,
} = await import('./proactiveSpeech.js');
const { registerVoiceOutputCandidate, __resetVoiceOutput } = await import('./voiceOutput.js');
+const { registerEchoBuffer } = await import('./echo.js');
describe('parseHHMM', () => {
it.each([
@@ -146,8 +147,11 @@ describe('speakProactive', () => {
const makeIo = () => {
const emit = vi.fn();
const socketEmit = vi.fn();
- registerVoiceOutputCandidate({ id: 'recipient', connected: true, emit: socketEmit });
- return { io: { emit }, emit, socketEmit };
+ const recipient = { id: 'recipient', connected: true, emit: socketEmit };
+ const recent = [];
+ registerVoiceOutputCandidate(recipient);
+ registerEchoBuffer(recipient, recent);
+ return { io: { emit }, emit, socketEmit, recipient, recent };
};
beforeEach(() => __resetVoiceOutput());
@@ -205,25 +209,20 @@ describe('speakProactive', () => {
expect(payload.source).toBe('cos');
});
- it('registers the spoken sentence in every registered echo buffer', async () => {
- // Proactive lines play through laptop speakers and can bleed back into
- // the mic. Without registering in the per-socket echo buffers, the next
- // user turn would forward the bot's own utterance to the LLM as input.
- const { registerEchoBuffer, unregisterEchoBuffer, isEchoOfRecentTts } = await import('./echo.js');
- const recent = [];
- registerEchoBuffer(recent);
- try {
- const { io } = makeIo();
- const sentence = 'The meeting starts at three pm in the conference room';
- const r = await speakProactive({ io, text: sentence });
- expect(r.ok).toBe(true);
- expect(recent).toHaveLength(1);
- // And the buffer is wired into the echo detector — a transcript that
- // looks like the proactive line would be flagged as echo.
- expect(isEchoOfRecentTts('the meeting starts at three pm', recent)).toBe(true);
- } finally {
- unregisterEchoBuffer(recent);
- }
+ it('registers the spoken sentence in the recipient tab echo buffer only', async () => {
+ // Proactive lines play through the recipient's speakers and can bleed back
+ // into its mic. The line is remembered in that one tab's echo buffer so its
+ // next user turn drops the bot's own utterance instead of forwarding it to
+ // the LLM — but NOT in other devices' buffers (they never heard it).
+ const { isEchoOfRecentTts } = await import('./echo.js');
+ const { io, recent } = makeIo();
+ const sentence = 'The meeting starts at three pm in the conference room';
+ const r = await speakProactive({ io, text: sentence });
+ expect(r.ok).toBe(true);
+ expect(recent).toHaveLength(1);
+ // And the buffer is wired into the echo detector — a transcript that
+ // looks like the proactive line would be flagged as echo.
+ expect(isEchoOfRecentTts('the meeting starts at three pm', recent)).toBe(true);
});
it('suppresses when proactive disabled', async () => {
diff --git a/server/services/voice/voiceOutput.js b/server/services/voice/voiceOutput.js
index 474162536c..f58c241a78 100644
--- a/server/services/voice/voiceOutput.js
+++ b/server/services/voice/voiceOutput.js
@@ -113,7 +113,7 @@ export const emitVoiceOutput = (io, event, payload) => {
const target = getVoiceOutputSocket();
if (target) {
target.emit(event, payload);
- return { delivered: true, socketId: target.id ?? null };
+ return { delivered: true, socket: target, socketId: target.id ?? null };
}
return { delivered: false };
};
diff --git a/server/sockets/voice.js b/server/sockets/voice.js
index ba168f3c29..61120fe023 100644
--- a/server/sockets/voice.js
+++ b/server/sockets/voice.js
@@ -91,7 +91,7 @@ export const registerVoiceHandlers = (socket) => {
// without needing a per-socket context.
recentTts: [],
};
- registerEchoBuffer(state.recentTts);
+ registerEchoBuffer(socket, state.recentTts);
const pushHistory = (role, content) => {
if (!content) return;
@@ -369,6 +369,6 @@ export const registerVoiceHandlers = (socket) => {
const textWaiters = Array.from(state.uiTextWaiters.values());
state.uiTextWaiters.clear();
textWaiters.forEach((resolve) => resolve(null));
- unregisterEchoBuffer(state.recentTts);
+ unregisterEchoBuffer(socket);
});
};