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

review: address self-review findings — proactive-TTS echo gap + 3 DRY fixes

[._.]/ Adam Eivyab1ebe66d058
diff --git a/server/lib/objects.js b/server/lib/objects.js
index 88469cec36..3ad0620902 100644
--- a/server/lib/objects.js
+++ b/server/lib/objects.js
@@ -26,10 +26,19 @@
const isPlainObject = (v) => !!v && typeof v === 'object' && !Array.isArray(v);
+// Prototype-pollution guard: skip keys that would mutate Object.prototype
+// when assigned through normal property access. Every current call site
+// gates input through a Zod schema (which strips unknown keys), but the
+// helper is shared across three routes and a future caller could hand it
+// `req.body` directly or an LLM tool-call payload — defense in depth is
+// cheap. Reflects no behavioral change for valid input.
+const POLLUTING_KEYS = new Set(['__proto__', 'constructor', 'prototype']);
+
export const deepMerge = (base, patch) => {
if (!isPlainObject(patch)) return patch === undefined ? base : patch;
const out = { ...(isPlainObject(base) ? base : {}) };
for (const [k, v] of Object.entries(patch)) {
+ if (POLLUTING_KEYS.has(k)) continue;
out[k] = isPlainObject(base?.[k]) && isPlainObject(v) ? deepMerge(base[k], v) : v;
}
return out;
diff --git a/server/services/civitaiSuggestions.js b/server/services/civitaiSuggestions.js
index 77923e0e28..55581be342 100644
--- a/server/services/civitaiSuggestions.js
+++ b/server/services/civitaiSuggestions.js
@@ -17,10 +17,11 @@ import {
searchCivitaiLoras,
extractSamplePrompt,
} from '../lib/civitai.js';
+import { RUNNER_FAMILIES } from '../lib/runners.js';
import { resolveCivitaiKey } from './loras.js';
const TTL_MS = 60 * 60 * 1000; // 1 hour
-const RUNNER_FAMILIES = ['mflux', 'flux2', 'z-image', 'ernie'];
+const RUNNER_FAMILY_LIST = Object.values(RUNNER_FAMILIES);
// Hand-curated picks that always lead the suggestion panel regardless of
// whether they crack Civitai's "Most Downloaded" leaderboard. Compat per
@@ -187,7 +188,7 @@ const fetchSuggestionsFor = async (runnerFamily, { fetchImpl, force = false } =
export const getSuggestions = async ({ fetchImpl, limit = 4, force = false } = {}) => {
const [curated, runnerEntries] = await Promise.all([
getCurated({ fetchImpl, force }),
- Promise.all(RUNNER_FAMILIES.map(async (family) => {
+ Promise.all(RUNNER_FAMILY_LIST.map(async (family) => {
const cards = await fetchSuggestionsFor(family, { fetchImpl, force })
.catch((err) => {
console.log(`⚠️ Civitai suggestion fetch failed for ${family}: ${err?.message || err}`);
diff --git a/server/services/messageEvaluator.js b/server/services/messageEvaluator.js
index 34cc8677fa..97fe2baa86 100644
--- a/server/services/messageEvaluator.js
+++ b/server/services/messageEvaluator.js
@@ -5,6 +5,7 @@ import { getProviderById, getAllProviders } from './providers.js';
import { buildRulesPromptSection } from './messageTriageRules.js';
import { PATHS } from '../lib/fileUtils.js';
import { runPromptThroughProvider } from '../lib/promptRunner.js';
+import { extractJson } from '../lib/jsonExtract.js';
const EVAL_PROMPT = `You are an email triage assistant. For each email below, recommend ONE action and a brief reason.
@@ -79,11 +80,15 @@ async function runPrompt(provider, model, prompt, source) {
}
function parseEvalResponse(text, messageIds) {
- // Extract JSON array from response (may have markdown fences)
- const jsonMatch = text.match(/\[[\s\S]*\]/);
- if (!jsonMatch) return null;
-
- const parsed = JSON.parse(jsonMatch[0]);
+ // Route through the shared extractor so banner-stripping, trailing-comma
+ // repair, and the `[...]` placeholder elision the rest of PortOS's LLM
+ // callers benefit from also apply here. Without it, a Codex banner before
+ // the JSON or a stray trailing comma throws SyntaxError instead of
+ // surfacing the cleaner "Failed to parse AI evaluation response" upstream.
+ const { value: parsed } = extractJson(text, {
+ blockType: 'array',
+ shapePredicate: Array.isArray,
+ });
if (!Array.isArray(parsed)) return null;
// Index by message ID, only keep valid entries
diff --git a/server/services/voice/echo.js b/server/services/voice/echo.js
index 1ad032923e..9c0a663c3d 100644
--- a/server/services/voice/echo.js
+++ b/server/services/voice/echo.js
@@ -58,6 +58,28 @@ 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();
+
+export const registerEchoBuffer = (buf) => {
+ if (Array.isArray(buf)) echoBuffers.add(buf);
+};
+
+export const unregisterEchoBuffer = (buf) => {
+ echoBuffers.delete(buf);
+};
+
+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
// echoed back. Default-false on any uncertainty so we never silently drop
// legitimate user input.
diff --git a/server/services/voice/echo.test.js b/server/services/voice/echo.test.js
index 0dfa4cfb9e..d010bf6641 100644
--- a/server/services/voice/echo.test.js
+++ b/server/services/voice/echo.test.js
@@ -4,6 +4,9 @@ import {
trigramsOf,
rememberTtsSentence,
isEchoOfRecentTts,
+ registerEchoBuffer,
+ unregisterEchoBuffer,
+ rememberTtsForAllSockets,
MIN_SHARED_TRIGRAMS,
} from './echo.js';
@@ -119,3 +122,36 @@ describe('isEchoOfRecentTts', () => {
expect(isEchoOfRecentTts('the quick brown fox runs', recent, { now: NOW })).toBe(false);
});
});
+
+describe('echo buffer registry (proactive-speech echo suppression)', () => {
+ it('fans out a sentence to every registered buffer', () => {
+ const a = [];
+ const b = [];
+ registerEchoBuffer(a);
+ registerEchoBuffer(b);
+ try {
+ rememberTtsForAllSockets('proactive briefing sentence', { now: 5000 });
+ expect(a).toHaveLength(1);
+ expect(b).toHaveLength(1);
+ expect(a[0].text).toBe('proactive briefing sentence');
+ } finally {
+ unregisterEchoBuffer(a);
+ unregisterEchoBuffer(b);
+ }
+ });
+
+ it('stops writing to a buffer after it is unregistered', () => {
+ const a = [];
+ registerEchoBuffer(a);
+ unregisterEchoBuffer(a);
+ rememberTtsForAllSockets('proactive briefing sentence', { now: 5000 });
+ expect(a).toEqual([]);
+ });
+
+ it('ignores non-array registrations', () => {
+ // No throw; nothing observable to assert beyond "doesn't crash".
+ 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 3df685470a..eac63a709f 100644
--- a/server/services/voice/proactiveSpeech.js
+++ b/server/services/voice/proactiveSpeech.js
@@ -17,6 +17,7 @@
import { synthesize } from './tts.js';
import { getVoiceConfig } from './config.js';
+import { rememberTtsForAllSockets } from './echo.js';
import { getUserTimezone, getLocalParts } from '../../lib/timezone.js';
// 24-hour HH:MM regex shared with the route-level Zod schema in
@@ -116,6 +117,13 @@ export const speakProactive = async ({ io, text, priority = 'normal', source = '
}
const { wav, latencyMs } = await synthesize(trimmed);
+ // Register this proactive line in every connected socket's echo buffer so
+ // the next user turn picks it up as TTS echo if the laptop mic catches the
+ // playback — without this, the bot's own voice would round-trip back into
+ // the LLM as user input. Per-turn TTS already does the equivalent via
+ // `state.recentTts`; proactive speech has no socket context, so it goes
+ // through the module-scope registry instead.
+ 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
diff --git a/server/services/voice/proactiveSpeech.test.js b/server/services/voice/proactiveSpeech.test.js
index 036c7f1b00..3114f7ec30 100644
--- a/server/services/voice/proactiveSpeech.test.js
+++ b/server/services/voice/proactiveSpeech.test.js
@@ -175,6 +175,27 @@ 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('suppresses when proactive disabled', async () => {
const { getVoiceConfig } = await import('./config.js');
getVoiceConfig.mockResolvedValueOnce({
diff --git a/server/sockets/voice.js b/server/sockets/voice.js
index e9edb678ab..b2fd98c5df 100644
--- a/server/sockets/voice.js
+++ b/server/sockets/voice.js
@@ -8,6 +8,7 @@
import { runTurn } from '../services/voice/pipeline.js';
import { getVoiceConfig } from '../services/voice/config.js';
+import { registerEchoBuffer, unregisterEchoBuffer } from '../services/voice/echo.js';
import { isIsoDate } from '../services/brainJournal.js';
// Cap by messages (each user utterance + assistant reply is ~2). 24 → ~12 turns.
@@ -64,9 +65,13 @@ export const registerVoiceHandlers = (socket) => {
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.
+ // through the user's mic when laptop speakers are in play. The buffer is
+ // also registered in the module-scope echo registry so server-broadcast
+ // proactive speech can remember itself across every connected socket
+ // without needing a per-socket context.
recentTts: [],
};
+ registerEchoBuffer(state.recentTts);
const pushHistory = (role, content) => {
if (!content) return;
@@ -253,5 +258,6 @@ export const registerVoiceHandlers = (socket) => {
const waiters = state.uiWaiters;
state.uiWaiters = [];
waiters.forEach((resolve) => resolve(null));
+ unregisterEchoBuffer(state.recentTts);
});
};