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 r2): restore stale-client fallback, revert echo scoping, fix promotion recency

[._.]/ Adam Eivyef61e1c7cf16
diff --git a/server/services/voice/echo.js b/server/services/voice/echo.js
index 26264f0a34..9c0a663c3d 100644
--- a/server/services/voice/echo.js
+++ b/server/services/voice/echo.js
@@ -58,30 +58,26 @@ export const rememberTtsSentence = (recent, sentence, { now = Date.now(), window
return recent;
};
-// 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
+// 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();
-export const registerEchoBuffer = (socket, buf) => {
- if (socket && Array.isArray(buf)) echoBuffers.set(socket, buf);
+export const registerEchoBuffer = (buf) => {
+ if (Array.isArray(buf)) echoBuffers.add(buf);
};
-export const unregisterEchoBuffer = (socket) => {
- echoBuffers.delete(socket);
+export const unregisterEchoBuffer = (buf) => {
+ echoBuffers.delete(buf);
};
-// 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);
+export const rememberTtsForAllSockets = (sentence, opts = {}) => {
+ for (const buf of echoBuffers) 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 4d4efc3157..d010bf6641 100644
--- a/server/services/voice/echo.test.js
+++ b/server/services/voice/echo.test.js
@@ -6,7 +6,7 @@ import {
isEchoOfRecentTts,
registerEchoBuffer,
unregisterEchoBuffer,
- rememberTtsForSocket,
+ rememberTtsForAllSockets,
MIN_SHARED_TRIGRAMS,
} from './echo.js';
@@ -124,43 +124,34 @@ describe('isEchoOfRecentTts', () => {
});
describe('echo buffer registry (proactive-speech echo suppression)', () => {
- it('remembers a sentence only in the recipient socket buffer, not others', () => {
- const sockA = { id: 'a' };
- const sockB = { id: 'b' };
+ it('fans out a sentence to every registered buffer', () => {
const a = [];
const b = [];
- registerEchoBuffer(sockA, a);
- registerEchoBuffer(sockB, b);
+ registerEchoBuffer(a);
+ registerEchoBuffer(b);
try {
- // 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 });
+ rememberTtsForAllSockets('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(sockA);
- unregisterEchoBuffer(sockB);
+ unregisterEchoBuffer(a);
+ unregisterEchoBuffer(b);
}
});
- it('stops writing to a buffer after its socket is unregistered', () => {
- const sock = { id: 'a' };
+ it('stops writing to a buffer after it is unregistered', () => {
const a = [];
- registerEchoBuffer(sock, a);
- unregisterEchoBuffer(sock);
- rememberTtsForSocket(sock, 'proactive briefing sentence', { now: 5000 });
+ registerEchoBuffer(a);
+ unregisterEchoBuffer(a);
+ rememberTtsForAllSockets('proactive briefing sentence', { now: 5000 });
expect(a).toEqual([]);
});
- 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', () => {
+ it('ignores non-array registrations', () => {
// No throw; nothing observable to assert beyond "doesn't crash".
- expect(() => registerEchoBuffer(null, [])).not.toThrow();
- expect(() => registerEchoBuffer({ id: 'x' }, null)).not.toThrow();
- expect(() => registerEchoBuffer({ id: 'x' }, {})).not.toThrow();
+ expect(() => registerEchoBuffer(null)).not.toThrow();
+ expect(() => registerEchoBuffer(undefined)).not.toThrow();
+ expect(() => registerEchoBuffer({})).not.toThrow();
});
});
diff --git a/server/services/voice/proactiveSpeech.js b/server/services/voice/proactiveSpeech.js
index cd41333f53..6964319b24 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 { rememberTtsForSocket } from './echo.js';
+import { rememberTtsForAllSockets } from './echo.js';
import { emitVoiceOutput } from './voiceOutput.js';
import { getUserTimezone, getLocalParts, isWithinTimeWindow } from '../../lib/timezone.js';
@@ -130,7 +130,18 @@ export const speakProactive = async ({ io, text, priority = 'normal', source = '
// 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';
+ // 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.
+ // Deliberately remembered on EVERY socket, not just the recipient: only the
+ // recipient tab plays the audio, but a *sibling tab on the same machine* that
+ // is hands-free listening hears it through the shared speakers/mic, and must
+ // also suppress it or the bot answers its own voice in a feedback loop. The
+ // cost is that a different device speaking a 4+ word phrase closely matching
+ // the line within the 8s window could be falsely dropped — a rare, transient
+ // miss, strictly safer than re-opening the feedback loop echo suppression
+ // exists to prevent.
+ rememberTtsForAllSockets(trimmed);
+ const dest = delivery.broadcast ? 'broadcast' : (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 73ec17f976..e2cc74c2c0 100644
--- a/server/services/voice/proactiveSpeech.test.js
+++ b/server/services/voice/proactiveSpeech.test.js
@@ -27,7 +27,6 @@ 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([
@@ -147,11 +146,8 @@ describe('speakProactive', () => {
const makeIo = () => {
const emit = vi.fn();
const socketEmit = vi.fn();
- const recipient = { id: 'recipient', connected: true, emit: socketEmit };
- const recent = [];
- registerVoiceOutputCandidate(recipient);
- registerEchoBuffer(recipient, recent);
- return { io: { emit }, emit, socketEmit, recipient, recent };
+ registerVoiceOutputCandidate({ id: 'recipient', connected: true, emit: socketEmit });
+ return { io: { emit }, emit, socketEmit };
};
beforeEach(() => __resetVoiceOutput());
@@ -209,20 +205,26 @@ describe('speakProactive', () => {
expect(payload.source).toBe('cos');
});
- it('registers the spoken sentence in the recipient tab echo buffer only', async () => {
+ it('registers the spoken sentence in every registered echo buffer', 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);
+ // into the mic of any same-machine listening tab, so the line is remembered
+ // in every socket's echo buffer — the next user turn then drops the bot's
+ // own utterance instead of forwarding it to the LLM.
+ 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('suppresses when proactive disabled', async () => {
diff --git a/server/services/voice/voiceOutput.js b/server/services/voice/voiceOutput.js
index f58c241a78..14fc1d05a7 100644
--- a/server/services/voice/voiceOutput.js
+++ b/server/services/voice/voiceOutput.js
@@ -2,27 +2,39 @@
//
// The bug this fixes: proactive speech (proactiveSpeech.js) used
// `io.emit('voice:speak', …)`, which fans the audio to EVERY connected browser
-// tab and EVERY federated machine at once — so a reminder/briefing plays
-// simultaneously on all of them. Per-turn TTS (`voice:tts:audio`) is already
-// single-socket (it replies to the tab that took the turn); only the proactive
-// channel broadcast.
+// tab and EVERY device at once — so a reminder/briefing plays simultaneously on
+// all of them. Per-turn TTS (`voice:tts:audio`) is already single-socket (it
+// replies to the tab that took the turn); only the proactive channel broadcast.
//
// The fix mirrors the single-attached-socket pattern in services/shell.js: a
-// registry tracks every connected socket as a candidate, exactly one is the
-// `primary` recipient, and proactive audio is routed only to that socket.
-// Which tab is primary follows the user's focus — the tab you're actively
-// looking at claims output (client emits `voice:output:claim` on focus /
-// visibility / an explicit "make this tab the speaker" click). On the primary's
-// disconnect, output is promoted to another live candidate so audio always has
-// exactly one home while any tab is connected.
+// registry tracks each browser tab that announced itself (`voice:output:
+// available`) as a candidate, exactly one is the `primary` recipient, and
+// proactive audio is routed only to that socket. Which tab is primary follows
+// the user's focus — the tab you're actively looking at claims output (client
+// emits `voice:output:claim` on focus / visibility / an explicit "make this tab
+// the speaker" click). On the primary's disconnect, output is promoted to the
+// tab you focused most recently so audio always has exactly one home while any
+// candidate is connected.
+//
+// Only sockets that announce are eligible: a federated peer's Socket.IO relay
+// client lands on the same io.on('connection') but never announces, so it can't
+// be elected and silently swallow audio. A client running a PRE-UPGRADE bundle
+// (which predates the announce/claim protocol) also never announces — the
+// `emitVoiceOutput` fallback covers that transient case.
//
// Single-user trust model (see CLAUDE.md): no locking/atomicity needed here —
// one server process, one human. This is a re-entrancy-free in-memory registry.
-// Insertion-ordered set of every connected socket. Insertion order lets
-// promotion prefer the most-recently-registered live candidate (roughly "the
-// newest tab") when the primary goes away without an explicit successor.
+// Membership set of announced candidate sockets. Iteration order is connection
+// order, used ONLY as the tiebreak when no candidate has ever claimed.
const candidates = new Set();
+// Claim recency, keyed by socket — a monotonic sequence stamped each time a tab
+// claims (focuses). Promotion prefers the highest sequence (most-recently
+// focused) so a background tab that merely reconnected later can't inherit audio
+// over a tab the user actually looked at. Connection order is the fallback only
+// when NO surviving candidate has claimed.
+const claimSeq = new Map();
+let claimCounter = 0;
let primary = null;
// A socket is a viable recipient unless it has explicitly disconnected. Real
@@ -30,16 +42,25 @@ let primary = null;
// treats an absent flag as live.
const isLive = (socket) => !!socket && socket.connected !== false;
-// Prune any candidate that has gone away without a release call (defensive —
-// disconnect normally calls releaseVoiceOutput). Returns the last live
-// candidate as a promotion pick.
-const pruneAndPickLatest = () => {
- let latest = null;
+const forget = (socket) => {
+ candidates.delete(socket);
+ claimSeq.delete(socket);
+};
+
+// Pick the promotion successor: the live candidate with the most recent claim,
+// or — when none has ever claimed — the latest-connected live candidate. Prunes
+// dead candidates along the way (defensive — disconnect normally forgets them).
+const pickSuccessor = () => {
+ let latest = null; // connection-order fallback
+ let bestClaimed = null;
+ let bestSeq = -1;
for (const s of candidates) {
- if (isLive(s)) latest = s;
- else candidates.delete(s);
+ if (!isLive(s)) { forget(s); continue; }
+ latest = s;
+ const seq = claimSeq.get(s) ?? -1;
+ if (seq > bestSeq) { bestSeq = seq; bestClaimed = s; }
}
- return latest;
+ return bestSeq >= 0 ? bestClaimed : latest;
};
// Register a socket as a possible voice-output recipient. Does NOT make it
@@ -57,12 +78,10 @@ export const registerVoiceOutputCandidate = (socket) => {
// UI can reflect the change; the new primary is told it now owns output.
export const claimVoiceOutput = (socket) => {
if (!socket) return null;
- // Move to the end of the insertion order so promotion (pruneAndPickLatest)
- // prefers the most-recently-FOCUSED tab, not the most-recently-connected —
- // keeping "the tab you're looking at speaks" true through the disconnect path
- // (when the primary dies, the last tab you focused inherits output).
- candidates.delete(socket);
candidates.add(socket);
+ // Stamp claim recency so a later disconnect promotes the most-recently-focused
+ // survivor (not merely the newest connection). Re-stamped on every claim.
+ claimSeq.set(socket, ++claimCounter);
if (primary === socket) return socket;
const prev = primary;
primary = socket;
@@ -75,13 +94,13 @@ export const claimVoiceOutput = (socket) => {
};
// Drop a socket from the registry (on disconnect). If it was the primary,
-// promote the latest remaining live candidate so proactive audio keeps a
-// single home, and notify the successor that it now owns output.
+// promote the most-recently-focused remaining candidate so proactive audio keeps
+// a single home, and notify the successor that it now owns output.
export const releaseVoiceOutput = (socket) => {
if (!socket) return;
- candidates.delete(socket);
+ forget(socket);
if (primary !== socket) return;
- primary = pruneAndPickLatest();
+ primary = pickSuccessor();
if (primary) {
primary.emit('voice:output:primary', { primary: true });
console.log(`🔊 voice: output primary promoted → ${primary.id ?? 'socket'}`);
@@ -96,24 +115,33 @@ export const releaseVoiceOutput = (socket) => {
// would play proactive audio while its indicator still read "muted").
export const getVoiceOutputSocket = () => {
if (isLive(primary) && candidates.has(primary)) return primary;
- primary = pruneAndPickLatest();
+ primary = pickSuccessor();
if (primary) primary.emit('voice:output:primary', { primary: true });
return primary;
};
-// Route one voice-output event to the single designated recipient. Deliberately
-// does NOT fall back to `io.emit` when no candidate is registered — broadcasting
-// is the exact bug this module exists to prevent, and with any tab connected
-// getVoiceOutputSocket() always returns one socket, so the only time there's no
-// target is when nobody is connected (where a broadcast would reach nobody
-// anyway). A proactive line reaching no one beats one reaching every
-// tab/machine. `io` is retained in the signature for the caller/tests. Returns
-// delivery metadata for logging/tests.
+// Route one voice-output event to the single designated recipient.
+//
+// Fallback to `io.emit` ONLY when no announced candidate exists. In normal
+// operation every current-bundle browser tab announces, so there is always a
+// candidate and this broadcast path is never taken — the single-recipient
+// routing above is what fixes the play-on-every-tab bug. The fallback exists for
+// backward compatibility: a client running a PRE-UPGRADE bundle (server was just
+// updated, tab not yet reloaded) speaks the same unchanged `voice:speak` event
+// but never announces, so without this its proactive audio would be silently
+// dropped until the user reloads. Broadcasting reaches that stale tab; it also
+// harmlessly reaches peer-relay sockets (they ignore `voice:speak`). Any
+// transient multi-tab duplication only recurs among pre-upgrade tabs during an
+// upgrade window and self-heals on reload.
export const emitVoiceOutput = (io, event, payload) => {
const target = getVoiceOutputSocket();
if (target) {
target.emit(event, payload);
- return { delivered: true, socket: target, socketId: target.id ?? null };
+ return { delivered: true, socketId: target.id ?? null };
+ }
+ if (io) {
+ io.emit(event, payload);
+ return { delivered: true, broadcast: true };
}
return { delivered: false };
};
@@ -121,5 +149,7 @@ export const emitVoiceOutput = (io, event, payload) => {
// Test helper — reset module state between cases.
export const __resetVoiceOutput = () => {
candidates.clear();
+ claimSeq.clear();
+ claimCounter = 0;
primary = null;
};
diff --git a/server/services/voice/voiceOutput.test.js b/server/services/voice/voiceOutput.test.js
index bdabc1f488..b97547f47e 100644
--- a/server/services/voice/voiceOutput.test.js
+++ b/server/services/voice/voiceOutput.test.js
@@ -26,13 +26,16 @@ describe('voiceOutput single-recipient routing', () => {
expect(getVoiceOutputSocket()).toBe(null);
});
- it('emitVoiceOutput never broadcasts via io.emit when nobody is registered', () => {
- // The whole point of the module: proactive audio reaching nobody (no tab
- // connected) is strictly better than a broadcast to every tab/machine.
+ it('emitVoiceOutput falls back to io.emit only when no candidate is announced', () => {
+ // Backward-compat path: a pre-upgrade client speaks the same voice:speak
+ // event but never announces, so with no candidate we broadcast rather than
+ // silently drop its proactive audio. In normal operation a tab always
+ // announces, so this path is not taken (see the routing test below).
const io = { emit: vi.fn() };
const res = emitVoiceOutput(io, 'voice:speak', { sentence: 'hi' });
- expect(io.emit).not.toHaveBeenCalled();
- expect(res).toMatchObject({ delivered: false });
+ expect(io.emit).toHaveBeenCalledTimes(1);
+ expect(io.emit).toHaveBeenCalledWith('voice:speak', { sentence: 'hi' });
+ expect(res).toMatchObject({ delivered: true, broadcast: true });
});
it('registering a candidate does NOT auto-steal primary, but is promoted lazily', () => {
@@ -120,6 +123,24 @@ describe('voiceOutput single-recipient routing', () => {
expect(getVoiceOutputSocket()).toBe(a);
});
+ it('promotes a focused survivor over a background tab that reconnected later', () => {
+ const a = makeSocket('a');
+ const c = makeSocket('c');
+ registerVoiceOutputCandidate(a);
+ registerVoiceOutputCandidate(c);
+ claimVoiceOutput(a); // user focused a
+ claimVoiceOutput(c); // then focused c → c is primary
+ // A background tab announces AFTER the last claim (e.g. a hidden tab
+ // reconnecting) — newest in connection order, but never focused.
+ const bg = makeSocket('bg');
+ registerVoiceOutputCandidate(bg);
+
+ releaseVoiceOutput(c); // primary disconnects
+ // a (last-focused survivor) inherits output, NOT the newer background tab —
+ // claim recency wins over connection order.
+ expect(getVoiceOutputSocket()).toBe(a);
+ });
+
it('releasing a NON-primary candidate leaves primary unchanged', () => {
const a = makeSocket('a');
const b = makeSocket('b');
diff --git a/server/sockets/voice.js b/server/sockets/voice.js
index 61120fe023..ba168f3c29 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(socket, state.recentTts);
+ registerEchoBuffer(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(socket);
+ unregisterEchoBuffer(state.recentTts);
});
};