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
route proactive voice output to a single tab instead of broadcasting to all
[._.]/ Adam Eivye1661142d666
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex ffc939a3e0..f24606182b 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -61,6 +61,8 @@- **[issue-2681] POST daily status now uses your timezone, not the server's UTC day.** `completedToday`, `todayScore`, and the POST streaks in the MeatSpace POST service derived the day boundary from the server's UTC day (the process runs `TZ=UTC`), so for anyone outside UTC a POST completed the previous local evening could read as "done today," or a just-completed local-day POST could read as incomplete — and the Daily Post widget and the Daily Driver card (#2666), which both render `completedToday` from `getPostStats()`, inherited the drift. The day boundary now threads your configured timezone (`getUserTimezone`/`todayInTimezone`, via a shared `userLocalToday()` helper) through both sides: every writer that stamps a day (`submitPostSession`, `submitTrainingEntry`, memory-practice `submitPractice`, and Morse `appendMorseRound`) records a new record's `date` in your local day — derived from the same instant it stamps into `timestamp`/`startedAt` so a midnight boundary can't split the two — and every reader (`getPostStats`/`getPostProgress`/`getUnifiedActivityStreak`/`getTrainingStats`/`getMorseProgress`, plus the mastery-window cutoffs) derives "today" in your local day, mirroring the Daily Driver's tz-correct first-visit/handled markers so every surface agrees. All window cutoffs use DST-safe day math off the local today. The POST launcher's "completed today"/today's-minutes and the history range floor also derive their day key in your configured timezone (new `useUserTimezone` hook + `dayKeyInTimezone` util) so the client agrees with the server instead of computing "today" in UTC. A one-time migration (`192-post-dates-to-local-timezone`) re-derives existing session, training-log, and Morse-round day-strings from each record's stored UTC timestamp in your timezone (preferring the retry-stable `startedAt`, and preserving a legacy practice entry's only instant into `timestamp` before rewriting `date`), so historical streaks stay correct and don't collide with newly-written local-day records; it falls back to UTC (matching the server's `TZ=UTC` runtime), making it a no-op for UTC/unconfigured installs.+- **Proactive voice speech no longer plays on every open tab/device at once.** Server-initiated voice lines (reminders, briefings, task-completion alerts) were broadcast with `io.emit('voice:speak', …)`, so every browser tab and every device connected to the instance spoke the same line simultaneously. Proactive audio is now routed to a single designated recipient tab, mirroring the shell's single-attached-socket pattern (new `server/services/voice/voiceOutput.js`): each tab registers as a candidate on connect, and the tab you're actively looking at claims output — the client emits `voice:output:claim` on focus, on becoming visible, and on reconnect-while-visible. When the recipient tab disconnects, output is promoted to the tab you focused most recently so audio always has exactly one home. Per-turn TTS (`voice:tts:audio`) was already single-socket and is unaffected. The voice widget shows a **speaker / muted** control so you can see which tab is the speaker and click to move it to the current tab. (Scope: dedup is per-instance — every client of one PortOS instance; it does not coordinate proactive lines independently fired by separate federated peers.)+- **[issue-2567] Stop double error toasts across the Settings tabs and the JIRA integration page.** Several Settings surfaces routed a request through the auto-toasting `request()` helper AND showed their own `toast.error` in a custom catch, so a failure stacked two toasts. Every such call now passes `{ silent: true }` so the caller's catch is the single error layer — covering VoiceTab (config load/save, Piper voice download), ImageGenTab (settings/tools load, save, tool register/update, test render), TelegramTab (settings load, method/config/test/disconnect, forward-types), BackupTab (settings load + save), DatabaseTab (status load), EmbeddingsTab (save), MortalLoomTab and CaptionModelPicker (save), and the JIRA instances page (load/save/delete/test — mirroring the DataDog fix from #2520). Loaders and callers without a custom toast are unchanged (single default-helper layer preserved). The `getVoiceConfig`/`updateVoiceConfig`/`fetchPiperVoice`, telegram, `registerTool`/`updateTool`/`getToolsList`, and `getDatabaseStatus` wrappers gained a backward-compatible trailing `options` param so callers can opt into silent. Follow-up sweep of the remaining pipeline/writers-room/universe/media/etc. areas is tracked in #2669.- **[issue-2669] Stop double error toasts across the writers-room, universe, digital-twin, media, and brain areas.** Continues the #2567 sweep into the non-settings feature areas: every caller that showed its own `toast.error` in a custom `.catch`/`catch` while its API call also routed through the auto-toasting `request()` helper now passes `{ silent: true }`, so a failure surfaces one toast instead of two stacked ones. Covered across writers-room (folders/works/characters/objects/places CRUD, exercises, polish, drafts, analysis, promote-to-pipeline), universe canon + universeBuilder (extract/differentiate/refine/expand, lock toggles, world/reference-sheet renders, draft save + expand/refine auto-saves), digital-twin (confidence, enrichment lists, autobiography, writing-style/import/assessment analysis, taste + behavioral feedback, soul tests/documents), media/image/video (collections, timeline projects, media jobs queue, gallery hide/clean/upscale/stitch, image-gen cancel + submit, annotations, last-frame extract), and brain (links, daily log, brain graph). Loaders and callers without a custom toast are unchanged (single default-helper layer preserved). Wrappers in `apiWritersRoom.js`, `apiUniverseBuilder.js`, `apiDigitalTwin.js`, `apiImageVideo.js`, `apiMediaJobs.js`, and `apiBrain.js` gained a backward-compatible trailing `options` param so callers can opt into silent. Pipeline toast sites are intentionally deferred (a concurrent PR is reworking `client/src/**/pipeline/**`) and remain tracked in #2669, along with the other still-unswept areas (apps, cos, messages, meatspace, sharing, music/songs, privacy, calendar, and misc pages).diff --git a/client/src/components/voice/VoiceWidget.jsx b/client/src/components/voice/VoiceWidget.jsxindex e1f1b39bce..fc6021fc1b 100644--- a/client/src/components/voice/VoiceWidget.jsx+++ b/client/src/components/voice/VoiceWidget.jsx@@ -1,13 +1,13 @@import { useState, useEffect, useLayoutEffect, useRef, useCallback } from 'react';import { useNavigate } from 'react-router-dom';-import { Mic, MicOff, Brain, Volume2, Square, Trash2, ChevronDown, ChevronUp, Send, Infinity as InfinityIcon, NotebookPen, X, EyeOff, Monitor, MonitorOff } from 'lucide-react';+import { Mic, MicOff, Brain, Volume2, VolumeX, Square, Trash2, ChevronDown, ChevronUp, Send, Infinity as InfinityIcon, NotebookPen, X, EyeOff, Monitor, MonitorOff } from 'lucide-react';import {startCapture, stopCapture, interrupt, resetConversation, sendText, onVoiceEvent, isCapturing,startContinuous, stopContinuous, isContinuous, whenPlaybackDrained, getVadLevel,webSpeechSupported, startWebSpeechCapture, stopWebSpeechCapture, isWebSpeechCapturing,onProactiveSpeech, captureScreenForVision, sendScreenshotResult,enableVisionCapture, disableVisionCapture, isVisionCaptureEnabled, onVisionCaptureEnded,- speakSynthesized,+ speakSynthesized, onVoiceOutputPrimary, claimVoiceOutput,} from '../../services/voiceClient';import { resolveTurn, buildRouterSystemPrompt, TIER } from '../../services/voiceFastPath';import { warmNano } from '../../services/browserLlm';@@ -94,6 +94,11 @@ export default function VoiceWidget() {// ui_describe_visually ("what's on this chart?"). Must be enabled from a click// (user gesture) — getDisplayMedia can't run from the server-initiated turn.const [visionEnabled, setVisionEnabled] = useState(false);+ // Whether THIS tab is the current recipient of proactive voice output. The+ // server routes server-initiated speech (reminders/briefings) to a single+ // tab; this reflects (and lets the user claim) that role so the same line+ // doesn't play on every open tab/machine at once.+ const [isVoiceOutputTab, setIsVoiceOutputTab] = useState(false);const scrollRef = useRef(null);const useWebSpeech = sttEngine === 'web-speech' && webSpeechSupported;@@ -324,6 +329,11 @@ export default function VoiceWidget() {return () => { off(); disableVisionCapture(); };}, []);+ // Track whether this tab currently owns proactive voice output. Subscribing+ // fires immediately with the current value, so the indicator is correct on+ // mount without waiting for the next handoff.+ useEffect(() => onVoiceOutputPrimary(setIsVoiceOutputTab), []);+// Auto-scroll to bottom on new contentuseEffect(() => {if (scrollRef.current) scrollRef.current.scrollTop = scrollRef.current.scrollHeight;@@ -802,6 +812,20 @@ export default function VoiceWidget() {{visionEnabled ? <Monitor size={12} /> : <MonitorOff size={12} />}{visionEnabled ? 'vision' : 'no vision'}</button>+ <button+ onClick={() => { if (!isVoiceOutputTab) claimVoiceOutput(); }}+ disabled={isVoiceOutputTab}+ aria-pressed={isVoiceOutputTab}+ title={isVoiceOutputTab+ ? 'This tab plays the assistant\'s proactive speech (reminders, briefings). Only one tab speaks at a time.'+ : 'Proactive speech plays on another tab. Click to make this tab the speaker.'}+ className={`flex items-center gap-1 px-2 py-1 rounded-full text-[10px] font-medium ${isVoiceOutputTab+ ? 'text-port-success bg-port-success/10'+ : 'text-gray-400 hover:text-white hover:bg-port-border/70'}`}+ >+ {isVoiceOutputTab ? <Volume2 size={12} /> : <VolumeX size={12} />}+ {isVoiceOutputTab ? 'speaker' : 'muted'}+ </button>{history.length > 0 && (<buttononClick={() => setCollapsed((c) => !c)}diff --git a/client/src/services/voiceClient.js b/client/src/services/voiceClient.jsindex 743b1e063f..6616d43331 100644--- a/client/src/services/voiceClient.js+++ b/client/src/services/voiceClient.js@@ -6,6 +6,7 @@// Both emit 'voice:turn' over Socket.IO and play incoming TTS via Web Audio.import socket from './socket';+import { subscribeVisibility } from '../hooks/useVisibilityEvent.js';let stream = null;let recorder = null;@@ -364,6 +365,56 @@ export const onProactiveSpeech = (handler) => {return () => proactiveListeners.delete(handler);};+// ─── Voice-output ownership (single-recipient proactive speech) ────────────+// Proactive server-pushed lines (voice:speak) must play on exactly ONE tab —+// otherwise every open tab and every federated machine speaks the same reminder+// at once. The server routes voice:speak to a single designated "primary" tab;+// the tab the user is actively looking at claims that role. We claim on focus,+// on becoming visible, and on (re)connect while visible — so audio follows the+// user's attention — and expose an explicit claim() for a "speak on this tab"+// button. The server confirms ownership with voice:output:primary and tells the+// displaced tab via voice:output:detached.+let isVoiceOutputPrimary = false;+const voiceOutputPrimaryListeners = new Set();++const notifyVoiceOutputPrimary = () => {+ for (const fn of voiceOutputPrimaryListeners) fn(isVoiceOutputPrimary);+};++export const claimVoiceOutput = () => {+ if (socket.connected) socket.emit('voice:output:claim');+};++// Subscribe to voice-output ownership changes. Fires immediately with the+// current value so a late subscriber (widget mount) reflects state without+// waiting for the next handoff. Returns an unsubscribe function.+export const onVoiceOutputPrimary = (handler) => {+ voiceOutputPrimaryListeners.add(handler);+ handler(isVoiceOutputPrimary);+ return () => voiceOutputPrimaryListeners.delete(handler);+};++socket.on('voice:output:primary', () => {+ if (isVoiceOutputPrimary) return;+ isVoiceOutputPrimary = true;+ notifyVoiceOutputPrimary();+});+socket.on('voice:output:detached', () => {+ 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+// app) rather than adding another `visibilitychange` handler. `focus` has no+// shared singleton, so it stays a direct listener. Guard for non-browser+// (test/SSR) contexts.+if (typeof window !== 'undefined' && typeof document !== 'undefined') {+ window.addEventListener('focus', claimVoiceOutput);+ subscribeVisibility((state) => { if (state === 'visible') claimVoiceOutput(); });+}+// voice:transcript marks the start of a new turn's outputs — any pending// rejection from a previous cancellation should be lifted now so this turn's// TTS chunks actually play.@@ -446,6 +497,15 @@ socket.on('connect', () => {if (lastDictationRequest.enabled) {socket.emit('voice:dictation:set', lastDictationRequest);}+ // On (re)connect, re-claim voice output if this tab is the one the user is+ // looking at — otherwise a reconnect could leave audio pointed at a stale+ // primary. Only a visible+focused tab claims so a backgrounded reconnect+ // doesn't steal output from the foreground tab.+ if (typeof document !== 'undefined'+ && document.visibilityState === 'visible'+ && (document.hasFocus?.() ?? true)) {+ claimVoiceOutput();+ }});export const interrupt = () => {diff --git a/server/services/voice/proactiveSpeech.js b/server/services/voice/proactiveSpeech.jsindex 20a0bfba4d..658b216173 100644--- a/server/services/voice/proactiveSpeech.js+++ b/server/services/voice/proactiveSpeech.js@@ -18,6 +18,7 @@import { synthesize } from './tts.js';import { getVoiceConfig } from './config.js';import { rememberTtsForAllSockets } from './echo.js';+import { emitVoiceOutput } from './voiceOutput.js';import { getUserTimezone, getLocalParts, isWithinTimeWindow } from '../../lib/timezone.js';// HH:MM helpers live in server/lib/timezone.js (single source of truth shared@@ -73,8 +74,11 @@ export const shouldSpeak = (cfg, nowMinutes, { solicited = false } = {}) => {return { ok: true };};-// Speak a line to every connected client. `io` is the Socket.IO server-// passed from socket.js (no global stash so tests can inject a fake).+// Speak a line to the single designated voice-output tab. `io` is the Socket.IO+// server passed from socket.js (no global stash so tests can inject a fake).+// Proactive audio is NOT broadcast — `emitVoiceOutput` (voiceOutput.js) routes+// it to the one tab currently claiming output, so a reminder/briefing plays on+// exactly one browser tab / machine instead of all of them at once.//// `priority` is informational for now — clients can decide whether to// surface a toast for high-priority lines or just speak. Reserved field;@@ -113,8 +117,9 @@ export const speakProactive = async ({ io, text, priority = 'normal', source = '// `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- // it as part of the dialogue history.- io.emit('voice:speak', {+ // it as part of the dialogue history. Routed to the single voice-output tab+ // (not io.emit) so it doesn't play on every connected tab/machine at once.+ const delivery = emitVoiceOutput(io, 'voice:speak', {sentence: trimmed,wav,latencyMs,@@ -122,6 +127,7 @@ export const speakProactive = async ({ io, text, priority = 'normal', source = 'source,ts: Date.now(),});- console.log(`🔔 voice: proactive sent (${priority}) "${trimmed.slice(0, 80)}" (${latencyMs}ms synth)`);+ 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.jsindex 9d8159cab2..e9e43608bf 100644--- a/server/services/voice/proactiveSpeech.test.js+++ b/server/services/voice/proactiveSpeech.test.js@@ -1,4 +1,4 @@-import { describe, it, expect, vi } from 'vitest';+import { describe, it, expect, vi, beforeEach } from 'vitest';// Stub config + tts + timezone before importing the module — the pure-function// branches need no mocks but speakProactive integration does.@@ -26,6 +26,7 @@ const {speakProactive,MAX_PROACTIVE_TEXT_LEN,} = await import('./proactiveSpeech.js');+const { registerVoiceOutputCandidate, __resetVoiceOutput } = await import('./voiceOutput.js');describe('parseHHMM', () => {it.each([@@ -139,11 +140,18 @@ describe('shouldSpeak — decision matrix', () => {});describe('speakProactive', () => {+ // emitVoiceOutput routes proactive audio to the single registered recipient+ // tab (it no longer broadcasts via io.emit), so register a fake connected+ // socket and assert on ITS emit. io.emit must never be called.const makeIo = () => {const emit = vi.fn();- return { io: { emit }, emit };+ const socketEmit = vi.fn();+ registerVoiceOutputCandidate({ id: 'recipient', connected: true, emit: socketEmit });+ return { io: { emit }, emit, socketEmit };};+ beforeEach(() => __resetVoiceOutput());+it('returns no-io when io missing', async () => {const r = await speakProactive({ io: null, text: 'hi' });expect(r.ok).toBe(false);@@ -162,29 +170,30 @@ describe('speakProactive', () => {// bypass that. The same bound must hold at the function boundary so a// runaway caller can't trigger multi-minute synthesis.it('rejects text longer than MAX_PROACTIVE_TEXT_LEN', async () => {- const { io, emit } = makeIo();+ const { io, socketEmit } = makeIo();const oversized = 'x'.repeat(MAX_PROACTIVE_TEXT_LEN + 1);const r = await speakProactive({ io, text: oversized });expect(r.ok).toBe(false);expect(r.reason).toBe('too-long');expect(r.chars).toBe(oversized.length);expect(r.maxChars).toBe(MAX_PROACTIVE_TEXT_LEN);- expect(emit).not.toHaveBeenCalled();+ expect(socketEmit).not.toHaveBeenCalled();});it('accepts text exactly at MAX_PROACTIVE_TEXT_LEN', async () => {- const { io, emit } = makeIo();+ const { io, socketEmit } = makeIo();const r = await speakProactive({ io, text: 'x'.repeat(MAX_PROACTIVE_TEXT_LEN) });expect(r.ok).toBe(true);- expect(emit).toHaveBeenCalledTimes(1);+ expect(socketEmit).toHaveBeenCalledTimes(1);});- it('emits voice:speak with audio when allowed', async () => {- const { io, emit } = makeIo();+ it('routes voice:speak with audio to the recipient tab (never io.emit)', async () => {+ const { io, emit, socketEmit } = makeIo();const r = await speakProactive({ io, text: 'Heads up — meeting in five.' });expect(r.ok).toBe(true);- expect(emit).toHaveBeenCalledTimes(1);- const [event, payload] = emit.mock.calls[0];+ expect(emit).not.toHaveBeenCalled(); // no broadcast+ expect(socketEmit).toHaveBeenCalledTimes(1);+ const [event, payload] = socketEmit.mock.calls[0];expect(event).toBe('voice:speak');expect(payload.sentence).toBe('Heads up — meeting in five.');expect(payload.wav).toBeInstanceOf(Buffer);@@ -219,11 +228,11 @@ describe('speakProactive', () => {enabled: true,llm: { proactive: { enabled: false } },});- const { io, emit } = makeIo();+ const { io, socketEmit } = makeIo();const r = await speakProactive({ io, text: 'hi' });expect(r.ok).toBe(false);expect(r.reason).toBe('proactive-disabled');- expect(emit).not.toHaveBeenCalled();+ expect(socketEmit).not.toHaveBeenCalled();});// Avoidable-overhead guard: when quiet hours are off the decision can't@@ -266,10 +275,10 @@ describe('speakProactive', () => {llm: { proactive: { enabled: true, quietHours: { enabled: true, start: '22:00', end: '07:00' } } },});getLocalParts.mockReturnValueOnce({ hour: 23, minute: 30 });- const { io, emit } = makeIo();+ const { io, socketEmit } = makeIo();const r = await speakProactive({ io, text: 'late night ping' });expect(r.ok).toBe(false);expect(r.reason).toBe('quiet-hours');- expect(emit).not.toHaveBeenCalled();+ expect(socketEmit).not.toHaveBeenCalled();});});diff --git a/server/services/voice/voiceOutput.js b/server/services/voice/voiceOutput.jsnew file mode 100644index 0000000000..13f193303a--- /dev/null+++ b/server/services/voice/voiceOutput.js@@ -0,0 +1,122 @@+// Single designated recipient for proactive (server-initiated) voice output.+//+// 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.+//+// 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.+//+// 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.+const candidates = new Set();+let primary = null;++// A socket is a viable recipient unless it has explicitly disconnected. Real+// Socket.IO sockets expose `.connected`; test doubles omit it, so `!== false`+// 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;+ for (const s of candidates) {+ if (isLive(s)) latest = s;+ else candidates.delete(s);+ }+ return latest;+};++// Register a socket as a possible voice-output recipient. Does NOT make it+// primary — opening a new tab shouldn't steal audio from the tab you're using.+// Promotion to primary happens lazily (getVoiceOutputSocket) or explicitly+// (claimVoiceOutput on focus/click).+export const registerVoiceOutputCandidate = (socket) => {+ if (!socket) return;+ candidates.add(socket);+};++// Make `socket` the sole proactive-output recipient. The user's active tab+// calls this (via the `voice:output:claim` socket event) on focus / visibility+// / explicit request. The previous primary is told it lost the binding so its+// 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);+ if (primary === socket) return socket;+ const prev = primary;+ primary = socket;+ if (isLive(prev) && prev !== socket) {+ prev.emit('voice:output:detached', { reason: 'claimed-elsewhere' });+ }+ socket.emit('voice:output:primary', { primary: true });+ console.log(`🔊 voice: output primary → ${socket.id ?? 'socket'}`);+ return 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.+export const releaseVoiceOutput = (socket) => {+ if (!socket) return;+ candidates.delete(socket);+ if (primary !== socket) return;+ primary = pruneAndPickLatest();+ if (primary) {+ primary.emit('voice:output:primary', { primary: true });+ console.log(`🔊 voice: output primary promoted → ${primary.id ?? 'socket'}`);+ }+};++// The current proactive-output recipient, or null when no tab is connected.+// Lazily promotes when there is no primary (or it has gone stale) so the very+// first proactive line after a connect still reaches exactly one tab even if no+// explicit claim has arrived yet.+export const getVoiceOutputSocket = () => {+ if (isLive(primary) && candidates.has(primary)) return primary;+ primary = pruneAndPickLatest();+ 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.+export const emitVoiceOutput = (io, event, payload) => {+ const target = getVoiceOutputSocket();+ if (target) {+ target.emit(event, payload);+ return { delivered: true, socketId: target.id ?? null };+ }+ return { delivered: false };+};++// Test helper — reset module state between cases.+export const __resetVoiceOutput = () => {+ candidates.clear();+ primary = null;+};diff --git a/server/services/voice/voiceOutput.test.js b/server/services/voice/voiceOutput.test.jsnew file mode 100644index 0000000000..df530020cd--- /dev/null+++ b/server/services/voice/voiceOutput.test.js@@ -0,0 +1,145 @@+import { describe, it, expect, beforeEach, vi } from 'vitest';+import {+ registerVoiceOutputCandidate,+ claimVoiceOutput,+ releaseVoiceOutput,+ getVoiceOutputSocket,+ emitVoiceOutput,+ __resetVoiceOutput,+} from './voiceOutput.js';++// Minimal socket double: records emitted events and carries a stable id ++// `connected` flag (real Socket.IO sockets expose both).+const makeSocket = (id) => ({+ id,+ connected: true,+ emitted: [],+ emit(event, payload) { this.emitted.push({ event, payload }); },+});++const emittedEvents = (sock) => sock.emitted.map((e) => e.event);++describe('voiceOutput single-recipient routing', () => {+ beforeEach(() => __resetVoiceOutput());++ it('getVoiceOutputSocket is null with no candidates', () => {+ 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.+ const io = { emit: vi.fn() };+ const res = emitVoiceOutput(io, 'voice:speak', { sentence: 'hi' });+ expect(io.emit).not.toHaveBeenCalled();+ expect(res).toMatchObject({ delivered: false });+ });++ it('registering a candidate does NOT auto-steal primary, but is promoted lazily', () => {+ const a = makeSocket('a');+ registerVoiceOutputCandidate(a);+ // No explicit claim, no voice:output:primary emitted yet.+ expect(emittedEvents(a)).not.toContain('voice:output:primary');+ // But the sole candidate is the lazy recipient so audio has a home.+ expect(getVoiceOutputSocket()).toBe(a);+ });++ it('emitVoiceOutput routes to the single primary, not other candidates', () => {+ const a = makeSocket('a');+ const b = makeSocket('b');+ registerVoiceOutputCandidate(a);+ registerVoiceOutputCandidate(b);+ claimVoiceOutput(b);++ const io = { emit: vi.fn() };+ const res = emitVoiceOutput(io, 'voice:speak', { sentence: 'hello' });++ expect(io.emit).not.toHaveBeenCalled();+ expect(res).toMatchObject({ delivered: true, socketId: 'b' });+ expect(a.emitted.filter((e) => e.event === 'voice:speak')).toHaveLength(0);+ expect(b.emitted.filter((e) => e.event === 'voice:speak')).toHaveLength(1);+ });++ it('claim hands off primary: detaches the previous holder, notifies the new one', () => {+ const a = makeSocket('a');+ const b = makeSocket('b');+ registerVoiceOutputCandidate(a);+ registerVoiceOutputCandidate(b);++ claimVoiceOutput(a);+ expect(emittedEvents(a)).toContain('voice:output:primary');++ claimVoiceOutput(b);+ expect(emittedEvents(a)).toContain('voice:output:detached');+ expect(emittedEvents(b)).toContain('voice:output:primary');+ expect(getVoiceOutputSocket()).toBe(b);+ });++ it('re-claiming by the current primary is a no-op (no duplicate events)', () => {+ const a = makeSocket('a');+ registerVoiceOutputCandidate(a);+ claimVoiceOutput(a);+ a.emitted = [];+ claimVoiceOutput(a);+ expect(a.emitted).toHaveLength(0);+ });++ it('releasing the primary promotes the latest remaining candidate', () => {+ const a = makeSocket('a');+ const b = makeSocket('b');+ const c = makeSocket('c');+ registerVoiceOutputCandidate(a);+ registerVoiceOutputCandidate(b);+ registerVoiceOutputCandidate(c);+ claimVoiceOutput(a);++ releaseVoiceOutput(a);+ // Latest remaining candidate (c, registered last) is promoted.+ const next = getVoiceOutputSocket();+ expect(next).toBe(c);+ expect(emittedEvents(c)).toContain('voice:output:primary');+ });++ it('promotion follows the most-recently-focused (claimed) tab, not connect order', () => {+ const a = makeSocket('a');+ const b = makeSocket('b');+ const c = makeSocket('c');+ registerVoiceOutputCandidate(a);+ registerVoiceOutputCandidate(b);+ registerVoiceOutputCandidate(c);+ // User focuses a, then b — b is primary, but a was focused more recently+ // than c (which was only ever connected, never claimed).+ claimVoiceOutput(a);+ claimVoiceOutput(b);+ // b (the primary tab) disconnects.+ releaseVoiceOutput(b);+ // a inherits output (last focused survivor), NOT c (newest connected).+ expect(getVoiceOutputSocket()).toBe(a);+ });++ it('releasing a NON-primary candidate leaves primary unchanged', () => {+ const a = makeSocket('a');+ const b = makeSocket('b');+ registerVoiceOutputCandidate(a);+ registerVoiceOutputCandidate(b);+ claimVoiceOutput(a);++ releaseVoiceOutput(b);+ expect(getVoiceOutputSocket()).toBe(a);+ });++ it('a disconnected primary is pruned and not chosen', () => {+ const a = makeSocket('a');+ const b = makeSocket('b');+ registerVoiceOutputCandidate(a);+ registerVoiceOutputCandidate(b);+ claimVoiceOutput(a);++ a.connected = false; // socket dropped without a release call+ expect(getVoiceOutputSocket()).toBe(b);+ });++ it('emitVoiceOutput returns not-delivered when io is absent and no candidate', () => {+ expect(emitVoiceOutput(null, 'voice:speak', {})).toMatchObject({ delivered: false });+ });+});diff --git a/server/sockets/voice.js b/server/sockets/voice.jsindex d01888ff79..1f6e2e5728 100644--- a/server/sockets/voice.js+++ b/server/sockets/voice.js@@ -1,17 +1,23 @@// Per-socket voice handlers.// Inbound: voice:turn | voice:text | voice:interrupt | voice:reset// | voice:dictation:set | voice:ui:index | voice:screenshot:result-// | voice:ui:read-response+// | voice:ui:read-response | voice:output:claim// Outbound: voice:transcript | voice:llm:delta | voice:llm:done | voice:tts:audio// | voice:tool | voice:dictation | voice:navigate// | voice:ui:click | voice:ui:fill | voice:ui:select | voice:ui:check// | voice:ui:read-request// | voice:dailyLog:appended | voice:error | voice:idle// | voice:screenshot:request+// | voice:speak | voice:output:primary | voice:output:detachedimport { runTurn } from '../services/voice/pipeline.js';import { getVoiceConfig } from '../services/voice/config.js';import { registerEchoBuffer, unregisterEchoBuffer } from '../services/voice/echo.js';+import {+ registerVoiceOutputCandidate,+ claimVoiceOutput,+ releaseVoiceOutput,+} from '../services/voice/voiceOutput.js';import { isIsoDate } from '../services/brainJournal.js';// Cap by messages (each user utterance + assistant reply is ~2). 24 → ~12 turns.@@ -87,6 +93,12 @@ export const registerVoiceHandlers = (socket) => {};registerEchoBuffer(state.recentTts);+ // Register this tab as a possible recipient of proactive (server-initiated)+ // voice output. It does NOT become the sole recipient until it claims output+ // (below) — proactive audio is routed to exactly ONE tab so a reminder doesn't+ // play on every open tab/machine at once. See services/voice/voiceOutput.js.+ registerVoiceOutputCandidate(socket);+const pushHistory = (role, content) => {if (!content) return;state.history.push({ role, content });@@ -325,7 +337,19 @@ export const registerVoiceHandlers = (socket) => {}});+ // The user's active tab claims proactive voice output — whichever tab is+ // focused/visible (or where the user explicitly clicked "speak here") becomes+ // the single recipient of `voice:speak`. Last claim wins; the previous holder+ // is notified via voice:output:detached so its UI can reflect the handoff.+ socket.on('voice:output:claim', () => {+ claimVoiceOutput(socket);+ });+socket.on('disconnect', () => {+ // Drop this tab from the voice-output registry; if it was the sole+ // recipient, output is promoted to another live tab so proactive audio+ // keeps exactly one home.+ releaseVoiceOutput(socket);state.ctrl?.abort();// Abort any pending UI refresh waiters so their turns don't hang.const waiters = state.uiWaiters;diff --git a/server/sockets/voice.test.js b/server/sockets/voice.test.jsindex 45085f3d83..57b1a02fbf 100644--- a/server/sockets/voice.test.js+++ b/server/sockets/voice.test.js@@ -1,4 +1,4 @@-import { describe, it, expect, vi } from 'vitest';+import { describe, it, expect, vi, beforeEach } from 'vitest';// Force the enabled-gate open so the validation tests below deterministically// exercise the size/text guards (ensureEnabled runs BEFORE every guard; with@@ -13,6 +13,11 @@ vi.mock(import('../services/voice/config.js'), async (importOriginal) => {});const { truncateOnWordBoundary, registerVoiceHandlers } = await import('./voice.js');+const {+ getVoiceOutputSocket,+ emitVoiceOutput,+ __resetVoiceOutput,+} = await import('../services/voice/voiceOutput.js');// Minimal fake socket: records on() handlers so tests can fire inbound events,// and captures emit() calls. No real Socket.IO needed — the voice:ui:index /@@ -192,3 +197,41 @@ describe('voice:text validation', () => {expect(errors[0].payload).toEqual({ stage: 'text', message: 'text is required' });});});++describe('voice:output single-recipient wiring', () => {+ beforeEach(() => __resetVoiceOutput());++ it('registers the voice:output:claim handler and a candidate on connect', () => {+ const socket = makeFakeSocket();+ registerVoiceHandlers(socket);+ expect(socket.has('voice:output:claim')).toBe(true);+ // Registered as the sole candidate → lazily eligible to receive output.+ expect(getVoiceOutputSocket()).toBe(socket);+ });++ it('claiming routes proactive output to the claiming tab, not another', () => {+ const a = makeFakeSocket();+ const b = makeFakeSocket();+ registerVoiceHandlers(a);+ registerVoiceHandlers(b);+ // b is the active tab and claims output.+ b.fire('voice:output:claim');++ const io = { emit: () => { throw new Error('must not broadcast'); } };+ emitVoiceOutput(io, 'voice:speak', { sentence: 'ping' });+ expect(a.emitted.filter((e) => e.event === 'voice:speak')).toHaveLength(0);+ expect(b.emitted.filter((e) => e.event === 'voice:speak')).toHaveLength(1);+ });++ it('disconnecting the primary promotes another live tab', () => {+ const a = makeFakeSocket();+ const b = makeFakeSocket();+ registerVoiceHandlers(a);+ registerVoiceHandlers(b);+ a.fire('voice:output:claim');+ expect(getVoiceOutputSocket()).toBe(a);++ a.fire('disconnect');+ expect(getVoiceOutputSocket()).toBe(b);+ });+});