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

feat([wire-proactive-cos-speech-to-real-triggers]): hook proactive CoS speech to error/task/notification events

Adam Eivybd509f402744
diff --git a/server/services/socket.js b/server/services/socket.js
index 44cf7fc2eb..01ad343642 100644
--- a/server/services/socket.js
+++ b/server/services/socket.js
@@ -21,6 +21,7 @@ import { loopEvents } from './loops.js';
import { imageGenEvents } from './imageGenEvents.js';
import { videoGenEvents } from './videoGen/events.js';
import { aiStatusEvents } from './aiStatusEvents.js';
+import { wireProactiveTriggers } from './voice/proactiveTriggers.js';
import * as shellService from './shell.js';
import {
validateSocketData,
@@ -559,6 +560,10 @@ export function initSocket(io) {
// Set up AI status event forwarding (broadcast to all clients)
setupAIStatusEventForwarding();
+
+ // Wire proactive voice (CoS speaks first on high-severity errors, new tasks,
+ // and high-priority notifications — rate-limited per source).
+ setupProactiveSpeechForwarding();
}
let aiStatusForwardingSetup = false;
@@ -570,6 +575,13 @@ function setupAIStatusEventForwarding() {
});
}
+let proactiveSpeechForwardingSetup = false;
+function setupProactiveSpeechForwarding() {
+ if (proactiveSpeechForwardingSetup) return;
+ proactiveSpeechForwardingSetup = true;
+ wireProactiveTriggers({ io: ioInstance });
+}
+
function cleanupStream(socketId) {
const stream = activeStreams.get(socketId);
if (stream) {
diff --git a/server/services/voice/proactiveTriggers.js b/server/services/voice/proactiveTriggers.js
new file mode 100644
index 0000000000..36593ef8e0
--- /dev/null
+++ b/server/services/voice/proactiveTriggers.js
@@ -0,0 +1,142 @@
+// Wire proactive CoS speech to real subsystem events.
+//
+// `speakProactive` (proactiveSpeech.js) is the delivery primitive — it knows
+// how to suppress for quiet hours / disabled voice and push a line over the
+// `voice:speak` socket event. This module decides WHEN the CoS speaks first,
+// by subscribing to three live event sources and turning select events into
+// spoken lines:
+//
+// 1. errorEvents 'error' — only `severity: 'critical'` (the rest are
+// routine 4xx/5xx the user shouldn't hear).
+// 2. cosEvents 'task:ready' — a new task became spawnable.
+// 3. notificationEvents 'added' — only high/critical priority notifications.
+//
+// Each source has its OWN rate-limit bucket so a burst from one source can't
+// starve another, and a storm within a source can't talk over the user. The
+// rate-limit is applied BEFORE `speakProactive` (so we skip the config read +
+// synthesis cost on a throttled event) and the bucket only advances on a line
+// that actually went out — a quiet-hours/disabled suppression doesn't consume
+// the budget.
+//
+// EventEmitter does NOT await async listeners: a rejection from the synthesis
+// path inside `speakProactive` would surface as an unhandled rejection
+// (process-killing on Node ≥15). Listeners here stay synchronous and route the
+// awaited work through `dispatch`, which try/catches internally (sanctioned
+// out-of-request-lifecycle boundary per CLAUDE.md) and never rejects; a `.catch`
+// backstop on the call site guards the rest.
+
+import { errorEvents } from '../../lib/errorHandler.js';
+import { cosEvents } from '../cosEvents.js';
+import { notificationEvents } from '../notifications.js';
+import { speakProactive as defaultSpeak } from './proactiveSpeech.js';
+
+// Per-source minimum interval between spoken lines (ms). Tuned for an opt-in
+// assistant: critical errors are rare so a wide spacing is fine; tasks and
+// notifications can cluster, so a one-minute floor keeps them from chattering.
+export const RATE_LIMIT_MS = {
+ error: 90_000,
+ 'task:ready': 60_000,
+ notification: 60_000,
+};
+
+// Spoken lines should be short — synthesis is capped at MAX_PROACTIVE_TEXT_LEN
+// upstream, but for the ear a sentence or two is plenty. Trim long source text.
+const SPEECH_CLIP_LEN = 240;
+
+const clip = (text) => {
+ const s = (text || '').toString().trim().replace(/\s+/g, ' ');
+ return s.length > SPEECH_CLIP_LEN ? `${s.slice(0, SPEECH_CLIP_LEN - 1)}…` : s;
+};
+
+// Pure rate-limit predicate — given a source, its last-spoken timestamp, and
+// "now", may it speak? Unknown sources have no limit. Exported for unit tests.
+export const allowBySource = (source, lastSpokenAt, now, limits = RATE_LIMIT_MS) => {
+ const limit = limits[source];
+ if (!limit) return true;
+ if (lastSpokenAt == null) return true;
+ return now - lastSpokenAt >= limit;
+};
+
+// High-severity notification gate — only `high` / `critical` get spoken.
+export const isHighPriorityNotification = (priority) =>
+ priority === 'high' || priority === 'critical';
+
+// --- Pure formatters: event payload → spoken line (or '' to skip) ---
+
+export const formatErrorLine = (error) => {
+ if (error?.severity !== 'critical') return '';
+ const msg = clip(error.message);
+ return msg ? `Heads up. A critical error just occurred. ${msg}` : '';
+};
+
+export const formatTaskLine = (task) => {
+ const label = clip(task?.title || task?.description);
+ return label ? `A new task is ready: ${label}.` : '';
+};
+
+export const formatNotificationLine = (notification) => {
+ if (!isHighPriorityNotification(notification?.priority)) return '';
+ const title = clip(notification?.title);
+ if (!title) return '';
+ const description = clip(notification?.description);
+ return description ? `${title}. ${description}` : title;
+};
+
+/**
+ * Subscribe proactive speech to live event sources.
+ *
+ * @param {object} opts
+ * @param {object} opts.io Socket.IO server (passed to speakProactive).
+ * @param {Function} [opts.speak] Override the delivery primitive (tests).
+ * @param {object} [opts.limits] Override per-source rate limits (tests).
+ * @returns {Function} unwire — removes the listeners (boot wires once; tests
+ * and hot-reload use this to avoid double-wiring).
+ */
+export const wireProactiveTriggers = ({ io, speak = defaultSpeak, limits = RATE_LIMIT_MS } = {}) => {
+ if (!io) {
+ console.warn('🔕 voice: proactive triggers not wired (no io)');
+ return () => {};
+ }
+
+ // Per-source last-spoken timestamps live in this closure so each wiring gets
+ // isolated state and a rewire starts fresh.
+ const lastSpokenAt = new Map();
+
+ // Single async boundary — never rejects, so the synchronous listeners that
+ // call it can't leak an unhandled rejection. Advances the source's bucket
+ // only when a line actually went out.
+ const dispatch = async (source, text, priority) => {
+ if (!text) return;
+ const now = Date.now();
+ if (!allowBySource(source, lastSpokenAt.get(source), now, limits)) return;
+ const result = await speak({ io, text, priority, source }).catch((err) => {
+ console.error(`🔕 voice: proactive ${source} synth failed: ${err?.message || err}`);
+ return { ok: false, reason: 'error' };
+ });
+ if (result?.ok) lastSpokenAt.set(source, Date.now());
+ };
+
+ // Backstop: if dispatch itself somehow throws synchronously, swallow + log
+ // rather than letting an unhandled rejection escape the listener.
+ const fire = (source, text, priority) => {
+ dispatch(source, text, priority).catch((err) =>
+ console.error(`🔕 voice: proactive ${source} trigger failed: ${err?.message || err}`),
+ );
+ };
+
+ const onError = (error) => fire('error', formatErrorLine(error), 'high');
+ const onTaskReady = (task) => fire('task:ready', formatTaskLine(task), 'normal');
+ const onNotification = (notification) => fire('notification', formatNotificationLine(notification), 'high');
+
+ errorEvents.on('error', onError);
+ cosEvents.on('task:ready', onTaskReady);
+ notificationEvents.on('added', onNotification);
+
+ console.log('🔔 voice: proactive triggers wired (error/task:ready/notification)');
+
+ return () => {
+ errorEvents.off('error', onError);
+ cosEvents.off('task:ready', onTaskReady);
+ notificationEvents.off('added', onNotification);
+ };
+};
diff --git a/server/services/voice/proactiveTriggers.test.js b/server/services/voice/proactiveTriggers.test.js
new file mode 100644
index 0000000000..a84e5ef889
--- /dev/null
+++ b/server/services/voice/proactiveTriggers.test.js
@@ -0,0 +1,198 @@
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
+
+// The wiring test exercises the REAL event emitters (they're module
+// singletons) but injects a fake `speak`, so no config/tts/timezone mocking is
+// needed — the delivery primitive never runs.
+import { errorEvents } from '../../lib/errorHandler.js';
+import { cosEvents } from '../cosEvents.js';
+import { notificationEvents } from '../notifications.js';
+import {
+ allowBySource,
+ isHighPriorityNotification,
+ formatErrorLine,
+ formatTaskLine,
+ formatNotificationLine,
+ wireProactiveTriggers,
+ RATE_LIMIT_MS,
+} from './proactiveTriggers.js';
+
+// Let the fire-and-forget dispatch promise chain settle after a synchronous
+// emit before asserting.
+const flush = () => new Promise((r) => setTimeout(r, 0));
+
+describe('allowBySource', () => {
+ it('allows the first line for a known source (no prior timestamp)', () => {
+ expect(allowBySource('error', null, 1000)).toBe(true);
+ expect(allowBySource('error', undefined, 1000)).toBe(true);
+ });
+
+ it('throttles within the per-source window and allows past it', () => {
+ const limits = { error: 1000 };
+ expect(allowBySource('error', 5000, 5500, limits)).toBe(false);
+ expect(allowBySource('error', 5000, 6000, limits)).toBe(true);
+ expect(allowBySource('error', 5000, 6500, limits)).toBe(true);
+ });
+
+ it('never throttles an unknown source', () => {
+ expect(allowBySource('mystery', 5000, 5001)).toBe(true);
+ });
+});
+
+describe('isHighPriorityNotification', () => {
+ it('passes high and critical only', () => {
+ expect(isHighPriorityNotification('high')).toBe(true);
+ expect(isHighPriorityNotification('critical')).toBe(true);
+ expect(isHighPriorityNotification('medium')).toBe(false);
+ expect(isHighPriorityNotification('low')).toBe(false);
+ expect(isHighPriorityNotification(undefined)).toBe(false);
+ });
+});
+
+describe('formatErrorLine', () => {
+ it('speaks only critical errors', () => {
+ expect(formatErrorLine({ severity: 'critical', message: 'DB down' })).toMatch(/critical error.*DB down/i);
+ expect(formatErrorLine({ severity: 'error', message: 'minor' })).toBe('');
+ expect(formatErrorLine({ severity: 'warning', message: 'meh' })).toBe('');
+ });
+
+ it('returns empty when a critical error has no message', () => {
+ expect(formatErrorLine({ severity: 'critical', message: '' })).toBe('');
+ });
+
+ it('clips very long messages', () => {
+ const long = 'x'.repeat(500);
+ const line = formatErrorLine({ severity: 'critical', message: long });
+ expect(line.length).toBeLessThan(300);
+ expect(line.endsWith('…')).toBe(true);
+ });
+});
+
+describe('formatTaskLine', () => {
+ it('prefers title, falls back to description', () => {
+ expect(formatTaskLine({ title: 'Ship it' })).toBe('A new task is ready: Ship it.');
+ expect(formatTaskLine({ description: 'Fix the bug' })).toBe('A new task is ready: Fix the bug.');
+ });
+
+ it('returns empty when neither title nor description present', () => {
+ expect(formatTaskLine({})).toBe('');
+ expect(formatTaskLine(null)).toBe('');
+ });
+});
+
+describe('formatNotificationLine', () => {
+ it('speaks high-priority notifications, appending description when present', () => {
+ expect(formatNotificationLine({ priority: 'high', title: 'Backup failed' })).toBe('Backup failed');
+ expect(formatNotificationLine({ priority: 'critical', title: 'Disk full', description: 'Act now' }))
+ .toBe('Disk full. Act now');
+ });
+
+ it('skips low/medium priority and title-less notifications', () => {
+ expect(formatNotificationLine({ priority: 'medium', title: 'meh' })).toBe('');
+ expect(formatNotificationLine({ priority: 'high', title: '' })).toBe('');
+ });
+});
+
+describe('wireProactiveTriggers', () => {
+ let unwire;
+ let speak;
+
+ beforeEach(() => {
+ speak = vi.fn(async () => ({ ok: true }));
+ });
+
+ afterEach(() => {
+ if (unwire) unwire();
+ unwire = null;
+ vi.restoreAllMocks();
+ });
+
+ it('returns a no-op and warns when io is missing', () => {
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ const off = wireProactiveTriggers({ io: null, speak });
+ off(); // must not throw
+ expect(warn).toHaveBeenCalled();
+ expect(speak).not.toHaveBeenCalled();
+ });
+
+ it('speaks on a critical error but not a routine one', async () => {
+ unwire = wireProactiveTriggers({ io: {}, speak });
+
+ errorEvents.emit('error', { severity: 'error', message: 'routine 500' });
+ await flush();
+ expect(speak).not.toHaveBeenCalled();
+
+ errorEvents.emit('error', { severity: 'critical', message: 'meltdown' });
+ await flush();
+ expect(speak).toHaveBeenCalledTimes(1);
+ expect(speak.mock.calls[0][0]).toMatchObject({ source: 'error', priority: 'high' });
+ expect(speak.mock.calls[0][0].text).toMatch(/meltdown/);
+ });
+
+ it('speaks on task:ready and high-priority notifications', async () => {
+ unwire = wireProactiveTriggers({ io: {}, speak });
+
+ cosEvents.emit('task:ready', { title: 'Render scene 3' });
+ notificationEvents.emit('added', { priority: 'high', title: 'Sync complete' });
+ notificationEvents.emit('added', { priority: 'low', title: 'ignored' });
+ await flush();
+
+ const sources = speak.mock.calls.map((c) => c[0].source).sort();
+ expect(sources).toEqual(['notification', 'task:ready']);
+ });
+
+ it('rate-limits a burst from one source to a single line', async () => {
+ unwire = wireProactiveTriggers({ io: {}, speak, limits: { error: 60_000 } });
+
+ errorEvents.emit('error', { severity: 'critical', message: 'first' });
+ await flush();
+ errorEvents.emit('error', { severity: 'critical', message: 'second' });
+ await flush();
+
+ expect(speak).toHaveBeenCalledTimes(1);
+ expect(speak.mock.calls[0][0].text).toMatch(/first/);
+ });
+
+ it('does not advance the bucket when a line was suppressed (ok:false)', async () => {
+ speak = vi.fn(async () => ({ ok: false, reason: 'quiet-hours' }));
+ unwire = wireProactiveTriggers({ io: {}, speak, limits: { error: 60_000 } });
+
+ errorEvents.emit('error', { severity: 'critical', message: 'first' });
+ await flush();
+ errorEvents.emit('error', { severity: 'critical', message: 'second' });
+ await flush();
+
+ // Both attempts reach speak because the first never went out.
+ expect(speak).toHaveBeenCalledTimes(2);
+ });
+
+ it('does not leak an unhandled rejection when speak rejects', async () => {
+ speak = vi.fn(async () => { throw new Error('synthesis exploded'); });
+ const errorLog = vi.spyOn(console, 'error').mockImplementation(() => {});
+
+ let unhandled = null;
+ const onUnhandled = (reason) => { unhandled = reason; };
+ process.on('unhandledRejection', onUnhandled);
+
+ unwire = wireProactiveTriggers({ io: {}, speak, limits: { error: 60_000 } });
+ errorEvents.emit('error', { severity: 'critical', message: 'boom' });
+
+ // Give the rejected promise time to surface as an unhandled rejection
+ // if the guard ever regresses.
+ await new Promise((r) => setTimeout(r, 50));
+ process.off('unhandledRejection', onUnhandled);
+
+ expect(unhandled).toBeNull(); // load-bearing: locks in the no-leak guard
+ expect(errorLog).toHaveBeenCalled();
+
+ // Bucket did not advance — a later critical can still try.
+ errorEvents.emit('error', { severity: 'critical', message: 'again' });
+ await flush();
+ expect(speak).toHaveBeenCalledTimes(2);
+ });
+
+ it('default RATE_LIMIT_MS covers all three wired sources', () => {
+ expect(RATE_LIMIT_MS).toHaveProperty('error');
+ expect(RATE_LIMIT_MS).toHaveProperty('task:ready');
+ expect(RATE_LIMIT_MS).toHaveProperty('notification');
+ });
+});