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
feat(voice): ui_read + destructive-confirm gate + proactive CoS speech (#220)
[._.]/ Adam Eivy7a0e6cd4a87b
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex f0def46d1f..69f42e959d 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -6,6 +6,12 @@## Added+- **Voice agent — read the page aloud.** A new `ui_read` voice tool extracts the visible text of the current page (main content area, excluding nav rails and the voice widget) and returns it verbatim. Ask "what does this say?", "read this aloud", or "what's on the page?" and the assistant speaks the content back. Text is captured from the same client-side index that already powers `ui_click` / `ui_fill`, so no extra round-trip and no new permissions. Output is capped at ~8 KB on a word boundary; longer pages get a graceful ellipsis tail.++- **Voice agent — destructive-action confirmation.** When the voice agent is about to click a button whose label matches Delete / Remove / Discard / Reset / Clear, the click is paused and the assistant asks for spoken confirmation ("say yes or confirm to delete, or cancel to skip"). Your next spoken word resolves the prompt: *yes / confirm / do it / go ahead* fires the click, *no / cancel / stop / never mind* drops the pending action, and anything else (a new request like "what time is it?") quietly discards the pending click and answers the new question. Pending confirmations expire after one minute so a forgotten "yes" minutes later can't re-fire a stale destructive click.++- **Voice agent — proactive Chief-of-Staff speech.** The CoS can now speak first — alerts, briefings, reminders — without waiting for you to ask. Disabled by default; turn it on in Settings → Voice. A quiet-hours window (also off by default, defaults 22:00 → 07:00 in your local time) suppresses proactive speech during sleep hours, and barge-in works the same as a normal turn — start talking and the in-flight proactive line stops immediately. New `POST /api/voice/speak` endpoint lets internal subsystems (and integration tests) trigger a proactive line; suppressed lines return `{ ok: false, reason }` so callers can react.+- **Favorite + note any generated image or video.** Every MediaCard now has a star toggle in the corner; clicking the tile opens the lightbox where a single editable note (max 2000 chars, 500ms debounced save) lives next to the prompt. Favorites and notes are surfaced across all four gallery surfaces — Media History, Image Gen, Video Gen, and Media Collection Detail — and a "Favorites" filter chip on each scopes the grid to starred items only. Press `s` while a lightbox is open to toggle favorite. Annotations persist to a new sidecar `data/media-annotations.json` keyed by `<kind>:<ref>` (same scheme as collections) so they survive when the underlying job records get pruned. Empty annotations (`!starred && !note`) get removed from disk on write to keep the file lean. Backed by `server/services/mediaAnnotations.js` + `server/routes/mediaAnnotations.js` (GET / PATCH with prune-on-empty + 2000-char note cap), the shared `useMediaAnnotations()` hook with optimistic-update + revert, and `MediaCard` / `MediaLightbox` prop extensions (`starred`, `hasNote`, `onToggleStar`, `annotation`, `onAnnotationChange`).- **World Builder — per-element Render buttons.** Each composite board, each category item (variation), and each category header now has its own inline Render button — no need to render the whole batch when you just want to iterate on one image. Per-board and per-variation buttons render exactly one prompt; the per-category header button renders every variation in that category. All three reuse the page's existing render-options panel (backend, model, resolution, batch-per-prompt) and route through the same job-queue + collection-tagging path as the full batch render, so toast + run history behave identically. Buttons disable themselves when the world isn't saved, no backend is configured, or a render is already in flight; per-category disables when the category has no variations yet.diff --git a/PLAN.md b/PLAN.mdindex 2d9d64cb7a..2e2fa00b92 100644--- a/PLAN.md+++ b/PLAN.md@@ -6,7 +6,7 @@ For project goals, see [GOALS.md](./GOALS.md). For completed work, see [DONE.md]## Next Up-1. **Voice agent next power-ups** — `ui_read` (extract visible page text so "what does this say?" works without hand-navigation), destructive-action confirmation gate (pause and require spoken "confirm" when `ui_click` matches `/delete|remove|discard|reset|clear/i`), proactive CoS speech (server-pushed voice with quiet-hours policy + barge-in contract).+_(empty — pick the next chunk from Backlog)_## Backlog@@ -32,6 +32,8 @@ The dgrauet/ltx-2-mlx runtime ships with FFLF (true keyframe interpolation), aud- [ ] **Writers Room (Phase 4–5)** — Phases 1–3 shipped (authoring core, storyboard companion, character/world/objects bibles, per-stage LLM picker, paragraph-grain Adapt, auto-queue scene image gen, Read view + render dock). Remaining: Phase 4 synced prose/script/media review, Phase 5 realtime CD feedback. See [writers-room.md](./docs/features/writers-room.md). Phase 4 now lands on the unified bible/scene model that the DRY-unification work (DONE.md 2026-05-10) brought in.- [ ] **Voice CoS tool expansion** — `calendar_today` / `calendar_next` (Google Calendar via existing MCP), `meatspace_log_workout` (wraps `meatspaceHealth.js`), `weather_now` (needs API choice — OpenWeather / WeatherKit / NWS), `timer_set` (reuses `agentActionExecutor.js` scheduled actions).+- [ ] **Wire proactive CoS speech to real triggers.** The plumbing landed in this PR (`POST /api/voice/speak` + `server/services/voice/proactiveSpeech.js` + `voice:speak` socket event), but nothing in the CoS calls it yet. Hook points to consider: high-severity error events from `errorEvents` (read-only suppression to high-priority alerts only), `cosEvents.emit('task:ready', ...)` for "ready to start <task>?", `notificationEvents` for whatever passes the priority bar. Each integration should keep a per-source rate-limit so a stuck loop can't spam audio. Priority field is plumbed end-to-end (low/normal/high) but currently only influences the toast icon — pick a real semantic before hooking high-volume sources.+- [ ] **Optimize `voice:ui:index` text payload.** `ui_read` works by piggy-backing visible page text on the existing UI index push (`client/src/services/domIndex.js#extractVisibleText`). For text-heavy pages this adds ~6-8 KB to every index push (route change + DOM mutation debounce), which is fine on a private network but wasteful. Switch to lazy: only run `extractVisibleText` when the server requests it via a new `voice:ui:read-request` side-effect that the client responds to. Keep the current behavior as a fallback so `ui_read` never returns "no page text".- [ ] **Voice agent vision fallback** — `ui_describe_visually` tool: screenshot the current tab (or a named canvas/chart) and send to a vision-capable model so "what's on this chart?" works on non-DOM content (CyberCity, graph views). Depends on a vision provider in `portos-ai-toolkit`.- [ ] **Voice agent — explicit long-term memory routing** — pipeline already routes capture verbs to `brain_capture`. Remaining: on retrieval-shaped voice turns, inject top-N relevant memories into the system prompt via `brain_search` so it's self-improving rather than ambient.- [ ] **CyberCity v2 — Phase 2+** — Phase 1 operational legibility shipped (per-building health glyphs, attention pane, search overlay, filter chips, hover quick-actions, mobile). Remaining: deeper drill-down (per-agent spatial trail, system flow lines between buildings, recent-action timeline overlay). See [cybercity-v2.md](./docs/features/cybercity-v2.md).diff --git a/client/src/components/settings/VoiceTab.jsx b/client/src/components/settings/VoiceTab.jsxindex aa37ca5ec5..f0e66c7bef 100644--- a/client/src/components/settings/VoiceTab.jsx+++ b/client/src/components/settings/VoiceTab.jsx@@ -489,6 +489,53 @@ export function VoiceTab() {</div></label>+ <label className="flex items-start gap-3 cursor-pointer md:col-span-2">+ <input+ type="checkbox"+ checked={cfg.llm.proactive?.enabled === true}+ onChange={(e) => patch('llm.proactive.enabled', e.target.checked)}+ className="w-4 h-4 mt-0.5 shrink-0"+ />+ <div className="flex flex-col sm:flex-row sm:flex-wrap sm:items-baseline gap-x-3 gap-y-0.5 min-w-0 flex-1">+ <span className="text-sm text-white">Allow proactive speech</span>+ <span className="text-xs text-gray-500">+ CoS can speak first for alerts and reminders. Disabled by default.+ </span>+ </div>+ </label>++ {cfg.llm.proactive?.enabled === true && (+ <div className="md:col-span-2 grid grid-cols-1 sm:grid-cols-3 gap-3 pl-7">+ <label className="flex items-center gap-2 cursor-pointer">+ <input+ type="checkbox"+ checked={cfg.llm.proactive?.quietHours?.enabled === true}+ onChange={(e) => patch('llm.proactive.quietHours.enabled', e.target.checked)}+ className="w-4 h-4 shrink-0"+ />+ <span className="text-sm text-white">Quiet hours</span>+ </label>+ <Field label="Start (HH:MM)" hint="Local time">+ <input+ type="time"+ value={cfg.llm.proactive?.quietHours?.start || '22:00'}+ onChange={(e) => patch('llm.proactive.quietHours.start', e.target.value)}+ disabled={!cfg.llm.proactive?.quietHours?.enabled}+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded text-white text-sm disabled:opacity-50"+ />+ </Field>+ <Field label="End (HH:MM)" hint="Local time">+ <input+ type="time"+ value={cfg.llm.proactive?.quietHours?.end || '07:00'}+ onChange={(e) => patch('llm.proactive.quietHours.end', e.target.value)}+ disabled={!cfg.llm.proactive?.quietHours?.enabled}+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded text-white text-sm disabled:opacity-50"+ />+ </Field>+ </div>+ )}+{sttEngine === 'whisper' && (<label className="flex items-start gap-3 cursor-pointer md:col-span-2"><inputdiff --git a/client/src/components/voice/VoiceWidget.jsx b/client/src/components/voice/VoiceWidget.jsxindex 65593475b0..5f804ae288 100644--- a/client/src/components/voice/VoiceWidget.jsx+++ b/client/src/components/voice/VoiceWidget.jsx@@ -5,6 +5,7 @@ import {startCapture, stopCapture, interrupt, resetConversation, sendText, onVoiceEvent, isCapturing,startContinuous, stopContinuous, isContinuous, whenPlaybackDrained, getVadLevel,webSpeechSupported, startWebSpeechCapture, stopWebSpeechCapture, isWebSpeechCapturing,+ onProactiveSpeech,} from '../../services/voiceClient';import { getVoiceConfig } from '../../services/apiVoice';import toast from '../ui/Toast';@@ -228,6 +229,20 @@ export default function VoiceWidget() {if (scrollRef.current) scrollRef.current.scrollTop = scrollRef.current.scrollHeight;}, [history]);+ // Proactive CoS speech — the server pushes a `voice:speak` event when the+ // assistant initiates a line (alerts, reminders, briefings). Audio plays+ // automatically via voiceClient; surface a transient toast so the user has+ // visual context for unexpected speech, and append to history so the line+ // shows up in the conversation pane just like a normal assistant reply.+ useEffect(() => {+ if (!enabled) return undefined;+ return onProactiveSpeech(({ sentence, priority }) => {+ setHistory((h) => [...h, { role: 'assistant', text: sentence, proactive: true }].slice(-MAX_HISTORY));+ const icon = priority === 'high' ? '🔔' : '🤖';+ toast(`${icon} ${sentence.length > 80 ? `${sentence.slice(0, 80)}…` : sentence}`);+ });+ }, [enabled]);+const handleStart = useCallback(async () => {if (!enabled) return;@@ -489,7 +504,11 @@ export default function VoiceWidget() {const fabSurface = 'border-violet-500/50 shadow-[0_0_24px_-4px_rgba(168,85,247,0.55)]';return (- <div className="fixed bottom-4 right-4 z-50 flex flex-col items-end gap-2">+ // data-voice-widget marker is used by client/src/services/domIndex.js+ // TEXT_EXCLUDE_SELECTORS to keep the widget's own conversation transcript+ // out of the ui_read visible-text snapshot — otherwise the voice agent+ // would "read the page" and recite its own dialog back to the user.+ <div data-voice-widget className="fixed bottom-4 right-4 z-50 flex flex-col items-end gap-2">{!expanded && (<div className="md:hidden flex items-center gap-2">{capturing && <span className={`text-xs ${tone} bg-port-card/95 backdrop-blur border rounded-full px-2 py-1 ${fabSurface}`}>{label}</span>}diff --git a/client/src/services/domIndex.js b/client/src/services/domIndex.jsindex 792f31152a..de6efc074c 100644--- a/client/src/services/domIndex.js+++ b/client/src/services/domIndex.js@@ -122,6 +122,80 @@ const findTitle = () => {return truncate(document.title, 60);};+// Cap on visible-text snapshot we ship to the server alongside the+// interactable index. The `ui_read` voice tool returns this so the LLM can+// answer "what does this say?" without an extra DOM trip. The same 8000+// cap (and the same word-boundary truncation) is enforced server-side in+// `server/sockets/voice.js` so the ~8 KB limit documented on `ui_read`+// holds end-to-end whether the truncation happens here (well-behaved+// widget) or there (runaway / malicious client).+const MAX_TEXT_CHARS = 8000;++// Drop chrome the user almost certainly didn't mean — nav rails, the floating+// voice widget, toast banners. Keep <main> and dialogs so what's visually+// front-and-center is what shows up in the snapshot. Falls back to whole-+// body text for pages that don't put content in <main>.+const TEXT_BLOCK_SELECTORS = ['main', '[role="dialog"]'];+// Exclude:+// - chrome the user didn't mean (nav rails, asides, the floating voice widget)+// - non-rendered DOM (script/style/noscript)+// - explicitly hidden subtrees: [hidden] is the spec-blessed HTML attribute+// for hidden content (e.g., inactive tab panels in component libraries),+// and aria-hidden="true" covers content hidden from assistive tech.+// Without these, ui_read would include the textContent of tab panels that+// aren't visually on the page — the agent would then "read the page" and+// recite content from inactive tabs.+const TEXT_EXCLUDE_SELECTORS = [+ 'nav',+ 'aside',+ 'script',+ 'style',+ 'noscript',+ '[hidden]',+ '[aria-hidden="true"]',+ '[data-voice-widget]',+];++// Combined selector built once at module load so extractText doesn't pay the+// O(selectors × DOM) cost of N separate querySelectorAll passes on every+// snapshot. With ~8 exclude selectors and a deep page, that was the dominant+// cost in the ui_read path.+const TEXT_EXCLUDE_QUERY = TEXT_EXCLUDE_SELECTORS.join(',');++// Extract visible textual content from a subtree. We clone the node first so+// we can prune nav/aside/script subtrees without mutating the live DOM, then+// pull textContent and collapse whitespace.+const extractText = (node) => {+ const clone = node.cloneNode(true);+ clone.querySelectorAll(TEXT_EXCLUDE_QUERY).forEach((n) => n.remove());+ const raw = clone.textContent || '';+ return raw.replace(/\s+/g, ' ').trim();+};++const extractVisibleText = () => {+ const blocks = [];+ for (const sel of TEXT_BLOCK_SELECTORS) {+ document.querySelectorAll(sel).forEach((node) => {+ if (!isVisible(node)) return;+ const t = extractText(node);+ if (t) blocks.push(t);+ });+ }+ if (!blocks.length) {+ const fallback = document.body ? extractText(document.body) : '';+ if (fallback) blocks.push(fallback);+ }+ const joined = blocks.join('\n\n');+ if (joined.length <= MAX_TEXT_CHARS) return joined;+ // Truncate on a word boundary so the tail isn't a partial token. Match+ // ANY whitespace (space/newline/tab) as a boundary — `joined` inserts+ // `\n\n` between blocks, so a strict space-only search would hard-cut+ // mid-token when the closest break is the block separator.+ const cut = joined.slice(0, MAX_TEXT_CHARS);+ const lastWs = cut.search(/\s[^\s]*$/);+ return `${cut.slice(0, lastWs > 0 ? lastWs : MAX_TEXT_CHARS)}…`;+};+export const buildIndex = () => {clearRefs();const root = pickRoot();@@ -165,6 +239,7 @@ export const buildIndex = () => {path: window.location.pathname + window.location.search,title: findTitle(),elements,+ text: extractVisibleText(),};};diff --git a/client/src/services/voiceClient.js b/client/src/services/voiceClient.jsindex a4e2a96bd6..725efc5bb4 100644--- a/client/src/services/voiceClient.js+++ b/client/src/services/voiceClient.js@@ -325,6 +325,38 @@ socket.on('voice:tts:audio', ({ sentence, wav }) => {enqueuePlay(ab).catch((err) => console.warn('[voice] playback failed:', err));});+// Proactive CoS speech. Server-pushed lines (alerts/briefings/reminders) come+// in on a separate channel so the client can render a distinct visual cue;+// VoiceWidget decides whether/how to display them (toast + history appending).+// Reuse the same audio playback queue + TTS echo memory as user-initiated+// turns so mic barge-in (voice:interrupt → stopPlayback) cancels proactive+// audio for free.+//+// NOTE: deliberately NOT gated by `rejectingTts`. That flag suppresses stale+// chunks from a CANCELLED turn (it stays sticky after stopPlayback() until the+// next voice:transcript), but a proactive alert is its own event — gating it+// would silently drop reminders/briefings whenever the user had recently+// interrupted a turn, which is exactly when proactive nudges are most useful.+const proactiveListeners = new Set();+socket.on('voice:speak', ({ sentence, wav, priority, source, ts }) => {+ rememberTtsSentence(sentence);+ const ab = toExactArrayBuffer(wav);+ if (!ab) return;+ enqueuePlay(ab).catch((err) => console.warn('[voice] proactive playback failed:', err));+ for (const fn of proactiveListeners) {+ fn({ sentence, priority: priority || 'normal', source: source || 'cos', ts: ts || Date.now() });+ }+});++// Subscribe to proactive-speech UI events. Returns an unsubscribe function.+// The CoS speech audio plays unconditionally (it's the whole point), but+// surfaces (toast, pill, conversation pane) decide independently whether to+// render a visual hint.+export const onProactiveSpeech = (handler) => {+ proactiveListeners.add(handler);+ return () => proactiveListeners.delete(handler);+};+// 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.diff --git a/server/routes/voice.js b/server/routes/voice.jsindex 80ea5b5f63..d914cb6222 100644--- a/server/routes/voice.js+++ b/server/routes/voice.js@@ -13,15 +13,21 @@ import { checkAll, invalidateHealthCache } from '../services/voice/health.js';import { reconcile, verifyBinaries, verifyModels, downloadPiperVoice } from '../services/voice/bootstrap.js';import { synthesize, listVoices } from '../services/voice/tts.js';import { findPiperVoice } from '../services/voice/piper-voices.js';+import { speakProactive, HHMM_RE, MAX_PROACTIVE_TEXT_LEN } from '../services/voice/proactiveSpeech.js';const router = Router();const VALID_TTS_ENGINES = new Set(['kokoro', 'piper']);const validEngine = (v) => VALID_TTS_ENGINES.has(v) ? v : undefined;-// Match the Socket.IO-side cap so /test can't be used to bypass it with a-// multi-megabyte string that would then take minutes to synthesize.-const MAX_TEST_TEXT_LEN = 4000;+// Shared cap for every REST endpoint that turns a text payload into TTS+// audio (/test and /speak). Imported from proactiveSpeech.js so the+// HTTP-layer cap and the function-boundary cap can't drift apart — if+// someone bumps the proactive limit, the route cap moves with it. Both+// caps exist on purpose: route-level for early rejection (no synthesis+// work wasted), function-level as defense in depth for direct in-process+// callers (CoS, scheduler) that bypass the route.+const MAX_VOICE_TEXT_LEN = MAX_PROACTIVE_TEXT_LEN;// Partial schema — deepMerge fills in anything omitted, so every field is// optional. The point here is to reject unknown engine values and obvious@@ -69,6 +75,14 @@ const voiceConfigPatchSchema = z.object({enabled: z.boolean().optional(),maxIterations: z.number().int().min(1).max(10).optional(),}).partial().optional(),+ proactive: z.object({+ enabled: z.boolean().optional(),+ quietHours: z.object({+ enabled: z.boolean().optional(),+ start: z.string().regex(HHMM_RE).optional(),+ end: z.string().regex(HHMM_RE).optional(),+ }).partial().optional(),+ }).partial().optional(),}).partial().optional(),vad: z.object({endOfSpeechMs: z.number().int().min(100).max(5000).optional(),@@ -145,8 +159,8 @@ router.post('/piper/fetch', asyncHandler(async (req, res) => {router.post('/test', asyncHandler(async (req, res) => {const text = (req.body?.text || '').toString().trim();if (!text) return res.status(400).json({ error: 'text is required' });- if (text.length > MAX_TEST_TEXT_LEN) {- return res.status(400).json({ error: `text too long (${text.length} > ${MAX_TEST_TEXT_LEN} chars)` });+ if (text.length > MAX_VOICE_TEXT_LEN) {+ return res.status(400).json({ error: `text too long (${text.length} > ${MAX_VOICE_TEXT_LEN} chars)` });}const voice = (req.body?.voice || '').toString().trim() || undefined;const engine = validEngine((req.body?.engine || '').toString().trim());@@ -168,4 +182,49 @@ router.post('/test', asyncHandler(async (req, res) => {res.send(wav);}));+// POST /api/voice/speak — server-pushed proactive speech. The CoS (or any+// internal subsystem) uses this to make the assistant speak first; clients+// pick up the audio over the `voice:speak` socket event. Suppressed by+// quiet hours / disabled flag — those return 200 with `{ ok: false, reason }`+// rather than an HTTP error because suppression is the documented contract.+const speakBodySchema = z.object({+ // Trim first so whitespace-only payloads (" ") fail the .min(1) check+ // at the HTTP boundary with a 400, matching /api/voice/test's behavior+ // instead of falling through to a 200 { ok:false, reason:'empty' }.+ text: z.string().trim().min(1).max(MAX_VOICE_TEXT_LEN),+ priority: z.enum(['low', 'normal', 'high']).optional(),+ // Empty / whitespace-only `source` would otherwise satisfy `.optional()`+ // and override speakProactive's default of `'cos'`, emitting payloads+ // with `source: ''`. Treat whitespace-only as omitted so the default+ // applies. (`.trim().min(1)` would have rejected the same input with+ // a 400 — we prefer silent fall-through for an internal route.)+ source: z.string().max(64).optional()+ .transform((s) => {+ const t = (s ?? '').trim();+ return t === '' ? undefined : t;+ }),+});+router.post('/speak', asyncHandler(async (req, res) => {+ const parsed = speakBodySchema.safeParse(req.body || {});+ if (!parsed.success) {+ throw new ServerError(+ `Invalid speak payload: ${parsed.error.issues.map((i) => `${i.path.join('.')} ${i.message}`).join('; ')}`,+ { status: 400, code: 'VALIDATION_ERROR' },+ );+ }+ const io = req.app.get('io');+ // Fail fast on missing io — that's a server misconfiguration (Socket.IO+ // never attached) and a 200 { ok:false, reason:'no-io' } would silently+ // mask the bad state from monitoring. Quiet-hours / proactive-disabled+ // still return 200 because those ARE expected suppression outcomes.+ if (!io) {+ throw new ServerError(+ 'voice subsystem misconfigured: io not attached',+ { status: 500, code: 'VOICE_IO_UNAVAILABLE' },+ );+ }+ const result = await speakProactive({ io, ...parsed.data });+ res.json(result);+}));+export default router;diff --git a/server/routes/voice.test.js b/server/routes/voice.test.jsindex f6cd97bb49..3ae44a8557 100644--- a/server/routes/voice.test.js+++ b/server/routes/voice.test.js@@ -25,13 +25,27 @@ vi.mock('../services/voice/tts.js', () => ({vi.mock('../services/voice/piper-voices.js', () => ({findPiperVoice: vi.fn(),}));+vi.mock('../services/voice/proactiveSpeech.js', async () => {+ const actual = await vi.importActual('../services/voice/proactiveSpeech.js');+ return {+ ...actual,+ speakProactive: vi.fn(),+ };+});import * as config from '../services/voice/config.js';import * as health from '../services/voice/health.js';import * as bootstrap from '../services/voice/bootstrap.js';import * as tts from '../services/voice/tts.js';import * as piperVoices from '../services/voice/piper-voices.js';+import * as proactiveSpeech from '../services/voice/proactiveSpeech.js';import voiceRoutes from './voice.js';+import { errorEvents } from '../lib/errorHandler.js';++// Node's EventEmitter throws if 'error' is emitted with zero listeners.+// asyncHandler emits to errorEvents on every route failure, so swallow it+// here — assertions go through the HTTP response, not the emitter.+errorEvents.on('error', () => {});const DEFAULT_CFG = {enabled: false,@@ -39,9 +53,14 @@ const DEFAULT_CFG = {tts: { engine: 'kokoro' },};-const buildApp = () => {+const buildApp = ({ io = { emit: () => {} } } = {}) => {const app = express();app.use(express.json());+ // /speak fails fast when io is missing (a 500 misconfiguration error+ // rather than a 200 { ok:false, reason:'no-io' } that monitoring would+ // miss). Attach a stub io by default; pass io:null to exercise the+ // misconfiguration branch.+ if (io) app.set('io', io);app.use('/api/voice', voiceRoutes);return app;};@@ -209,4 +228,79 @@ describe('Voice Routes', () => {expect(res.body.error).toMatch(/unknown piper voice/);});});++ describe('POST /api/voice/speak', () => {+ it('rejects empty text via the Zod schema', async () => {+ const res = await request(buildApp()).post('/api/voice/speak').send({ text: '' });+ expect(res.status).toBe(400);+ expect(res.body.code).toBe('VALIDATION_ERROR');+ expect(proactiveSpeech.speakProactive).not.toHaveBeenCalled();+ });++ // Regression: schema trims before .min(1) so whitespace-only payloads+ // fail at the HTTP boundary with a 400, not at the downstream+ // speakProactive empty-text branch with a 200 {ok:false}.+ it.each([' ', '\t', '\n', ' \t \n '])('rejects whitespace-only text "%s"', async (text) => {+ const res = await request(buildApp()).post('/api/voice/speak').send({ text });+ expect(res.status).toBe(400);+ expect(res.body.code).toBe('VALIDATION_ERROR');+ expect(proactiveSpeech.speakProactive).not.toHaveBeenCalled();+ });++ it('rejects invalid priority enum', async () => {+ const res = await request(buildApp())+ .post('/api/voice/speak')+ .send({ text: 'hi', priority: 'urgent' });+ expect(res.status).toBe(400);+ expect(res.body.code).toBe('VALIDATION_ERROR');+ });++ it('forwards text + priority to speakProactive and returns its result', async () => {+ proactiveSpeech.speakProactive.mockResolvedValue({ ok: true, latencyMs: 18 });+ const res = await request(buildApp())+ .post('/api/voice/speak')+ .send({ text: 'Heads up — meeting in five.', priority: 'high', source: 'cos' });+ expect(res.status).toBe(200);+ expect(res.body).toEqual({ ok: true, latencyMs: 18 });+ expect(proactiveSpeech.speakProactive).toHaveBeenCalledTimes(1);+ const [args] = proactiveSpeech.speakProactive.mock.calls[0];+ expect(args.text).toBe('Heads up — meeting in five.');+ expect(args.priority).toBe('high');+ expect(args.source).toBe('cos');+ });++ it('propagates suppression results (ok:false) without throwing', async () => {+ proactiveSpeech.speakProactive.mockResolvedValue({ ok: false, reason: 'quiet-hours' });+ const res = await request(buildApp()).post('/api/voice/speak').send({ text: 'late night ping' });+ expect(res.status).toBe(200);+ expect(res.body).toEqual({ ok: false, reason: 'quiet-hours' });+ });++ // Misconfiguration must surface as a real HTTP error so monitoring+ // sees it — a 200 ok:false here would silently mask a Socket.IO that+ // never attached.+ it('returns 500 VOICE_IO_UNAVAILABLE when io is not configured', async () => {+ proactiveSpeech.speakProactive.mockResolvedValue({ ok: true, latencyMs: 1 });+ const res = await request(buildApp({ io: null }))+ .post('/api/voice/speak')+ .send({ text: 'hi' });+ expect(res.status).toBe(500);+ expect(res.body.code).toBe('VOICE_IO_UNAVAILABLE');+ expect(proactiveSpeech.speakProactive).not.toHaveBeenCalled();+ });++ // Empty / whitespace-only source must NOT override speakProactive's+ // default of 'cos'. The schema transforms it to undefined so the+ // default kicks in.+ it.each(['', ' ', '\t'])('drops empty/whitespace source "%s" so default applies', async (source) => {+ proactiveSpeech.speakProactive.mockResolvedValue({ ok: true });+ const res = await request(buildApp())+ .post('/api/voice/speak')+ .send({ text: 'hi', source });+ expect(res.status).toBe(200);+ expect(proactiveSpeech.speakProactive).toHaveBeenCalledTimes(1);+ const [args] = proactiveSpeech.speakProactive.mock.calls[0];+ expect(args.source).toBeUndefined();+ });+ });});diff --git a/server/services/voice/config.js b/server/services/voice/config.jsindex 5f9333b820..e79989326a 100644--- a/server/services/voice/config.js+++ b/server/services/voice/config.js@@ -75,6 +75,19 @@ export const VOICE_DEFAULTS = Object.freeze({enabled: false,maxIterations: 3,},+ // Proactive speech — the CoS speaks first (alerts, briefings, reminders).+ // OFF by default so a fresh install doesn't blurt at the user; opt in via+ // Settings → Voice. Quiet hours suppress proactive lines; barge-in (a+ // user-initiated utterance) cancels in-flight proactive audio through the+ // existing voice:interrupt path.+ proactive: {+ enabled: false,+ quietHours: {+ enabled: false,+ start: '22:00',+ end: '07:00',+ },+ },},vad: { endOfSpeechMs: 700, minUtteranceMs: 250 },diff --git a/server/services/voice/confirmGate.js b/server/services/voice/confirmGate.jsnew file mode 100644index 0000000000..e45837f0dd--- /dev/null+++ b/server/services/voice/confirmGate.js@@ -0,0 +1,108 @@+// Destructive-action confirmation gate.+//+// When the voice agent fires a `ui_click` whose resolved element label looks+// destructive (delete / remove / discard / reset / clear) we don't blindly+// click — instead the tool stashes a `pendingDestructive` record on the+// session state and returns a result asking the LLM to prompt the user for+// spoken confirmation. The user's NEXT spoken turn is intercepted by the+// voice pipeline (before the LLM runs) and routed through resolvePending():+//+// "confirm" / "yes do it" / "go ahead" → re-issue the click side-effect+// "no" / "cancel" / "stop" → drop the pending click and send a+// short spoken acknowledgement+// ("Cancelled.") without running the+// LLM+// anything else (ambiguous) → clear the pending state and fall+// through to the normal LLM turn so+// the user can do something else.+//+// Keeping this as a pure module (no I/O, no socket emits; the clock is+// injectable via `createdAt` / `now` parameters and only defaults to+// `Date.now()` for ergonomics at call sites) makes the state machine+// trivially testable.++// Conservative on purpose — false-negatives only mean the user clicks a Delete+// button without an extra confirm prompt, which mirrors a normal mouse click.+// False-positives ("Reset filters" → confirm gate) are mildly annoying but+// safe. Anchored on word boundaries so labels like "Cleared" / "Resettable"+// don't trip it.+export const DESTRUCTIVE_LABEL_RE = /\b(delete|remove|discard|reset|clear)\b/i;++// Both regex sets are anchored at start (^) AND end ($) so only short,+// stand-alone yes/no utterances are treated as a confirmation or cancellation.+// Sentences that *start* with a yes/no token but then keep going ("cancel the+// meeting", "stop the music", "yes I want to go to lunch") fall through to+// `passthrough` so the LLM can answer the new request — matching the+// module's documented contract that ambiguous input means the user has+// moved on. Trailing punctuation is stripped before matching.+// Optional leading "ok/okay " filler is allowed in NEGATIVE_RE so that+// "okay cancel" / "okay never mind" are correctly classified as cancellations+// rather than being eaten by AFFIRM_RE's bare "ok/okay" branch. resolvePending+// also checks negative BEFORE affirmative as belt-and-suspenders for any+// future affirmative tokens that happen to share a prefix with a negative.+const AFFIRM_RE = /^(?:confirm|yes(?:[, ]+(?:do it|please|delete|remove|clear|reset|discard))?|do it|go ahead|proceed|continue|affirmative|ok(?:ay)?)$/i;+const NEGATIVE_RE = /^(?:(?:ok(?:ay)?[, ]+)?(?:no|cancel|stop|nope|never ?mind|don'?t|abort|negative))$/i;++// Strip wrapping quotes AND trailing punctuation in either order:+// `"confirm".` / `"confirm."` / `confirm.` / `yes,` / `cancel;` /+// `yes:` should all normalize to the bare token. STT engines (Whisper+// especially) frequently emit a trailing comma after a yes/no when the+// user takes a beat ("yes, … delete it"), so commas/colons/semicolons+// have to be stripped too — otherwise `yes,` falls through to+// passthrough and the pending destructive action is silently discarded.+// Running the pair twice handles cases where punctuation is outside the+// closing quote AND where it's inside.+const normalize = (text) => {+ let s = (text || '').trim();+ for (let i = 0; i < 2; i++) {+ s = s.replace(/^["']+|["']+$/g, '').replace(/[.!?,;:]+$/, '');+ }+ return s;+};++export const isDestructiveLabel = (label) => DESTRUCTIVE_LABEL_RE.test(label || '');++export const isAffirmative = (text) => AFFIRM_RE.test(normalize(text));+export const isNegative = (text) => NEGATIVE_RE.test(normalize(text));++// Build the pending record. Caller (tools.js / pipeline.js) is responsible+// for placing it on `state.pendingDestructive` AND for supplying `createdAt`+// (defaults to Date.now() for ergonomics, but tests inject a fixed clock to+// keep the module deterministic). Keeping the shape canonical here means+// the pipeline never has to know the internal fields.+export const buildPending = ({ tool, args, target, createdAt = Date.now() }) => ({+ tool,+ args,+ target, // resolved DOM target: { ref, label, kind }+ createdAt,+});++// Decide what to do with the user's next utterance given a pending record.+// Returns one of:+// { action: 'execute', pending } — affirmative: re-issue the side effect+// { action: 'cancel', pending } — negative: drop pending, send a short+// acknowledgement instead of LLM turn+// { action: 'passthrough' } — no pending or ambiguous: clear pending+// and let the normal LLM turn run+//+// Ambiguous input is treated as cancellation OF THE PENDING (the user moved on),+// but a passthrough rather than a cancel — the LLM should answer the new+// utterance normally without speaking a "cancelled" confirmation.+export const resolvePending = (pending, userText) => {+ if (!pending) return { action: 'passthrough' };+ // Check negative BEFORE affirmative — `AFFIRM_RE` matches bare leading+ // "ok"/"okay", so "okay cancel" / "okay never mind" would otherwise+ // execute the destructive action. Safe-by-default: if the user uttered+ // any cancel word in the sentence-leading position, take the cancel.+ if (isNegative(userText)) return { action: 'cancel', pending };+ if (isAffirmative(userText)) return { action: 'execute', pending };+ return { action: 'passthrough' };+};++// Stale-pending GC: a confirmation that's been waiting more than this long+// is treated as expired so a forgotten "yes" two minutes later can't re-fire+// a destructive action the user has moved past.+export const PENDING_TTL_MS = 60_000;++export const isExpired = (pending, now = Date.now()) =>+ !!pending && (now - (pending.createdAt || 0)) > PENDING_TTL_MS;diff --git a/server/services/voice/confirmGate.test.js b/server/services/voice/confirmGate.test.jsnew file mode 100644index 0000000000..1b1c68cbaf--- /dev/null+++ b/server/services/voice/confirmGate.test.js@@ -0,0 +1,256 @@+import { describe, it, expect } from 'vitest';+import {+ DESTRUCTIVE_LABEL_RE,+ isDestructiveLabel,+ isAffirmative,+ isNegative,+ buildPending,+ resolvePending,+ isExpired,+ PENDING_TTL_MS,+} from './confirmGate.js';++describe('isDestructiveLabel', () => {+ it.each([+ ['Delete', true],+ ['delete account', true],+ ['Remove member', true],+ ['Discard changes', true],+ ['Reset to defaults', true],+ ['Clear filters', true],+ ['DELETE', true],+ ])('matches %s → %s', (label, expected) => {+ expect(isDestructiveLabel(label)).toBe(expected);+ });++ it.each([+ ['Save', false],+ ['Cancel', false],+ ['Cancellation', false],+ ['Resettable', false], // word boundary blocks substring+ ['Removable', false],+ ['Cleared session', false], // trailing "ed" breaks the word boundary+ ['', false],+ ])('correctly classifies %s → %s', (label, expected) => {+ expect(isDestructiveLabel(label)).toBe(expected);+ });++ it('matches the exact words clear/delete/remove/discard/reset', () => {+ // Word boundary on both sides — "Clear filters" matches; "Cleared" does not.+ // Safe-by-default: a false-positive (extra confirm) is fine; a false-negative+ // (no gate) means a destructive click fires silently. We pick narrow matching.+ expect(DESTRUCTIVE_LABEL_RE.test('Clear filters')).toBe(true);+ expect(DESTRUCTIVE_LABEL_RE.test('Cleared session')).toBe(false);+ });+});++describe('isAffirmative / isNegative', () => {+ it.each([+ 'confirm',+ 'yes',+ 'yes do it',+ 'yes, please',+ 'do it',+ 'go ahead',+ 'proceed',+ 'continue',+ 'affirmative',+ 'OK',+ 'okay',+ 'Confirm.',+ ])('treats "%s" as affirmative', (s) => {+ expect(isAffirmative(s)).toBe(true);+ expect(isNegative(s)).toBe(false);+ });++ it.each([+ 'no',+ 'cancel',+ 'stop',+ 'nope',+ 'never mind',+ 'nevermind',+ "don't",+ 'dont',+ 'abort',+ 'negative',+ ])('treats "%s" as negative', (s) => {+ expect(isNegative(s)).toBe(true);+ expect(isAffirmative(s)).toBe(false);+ });++ it('rejects unrelated sentences as neither', () => {+ for (const s of [+ 'what time is it?',+ 'open my brain inbox',+ 'tell me a joke',+ 'remember to buy milk',+ ]) {+ expect(isAffirmative(s)).toBe(false);+ expect(isNegative(s)).toBe(false);+ }+ });++ it('strips surrounding quotes and trailing punctuation', () => {+ expect(isAffirmative('"confirm"')).toBe(true);+ expect(isAffirmative('yes!')).toBe(true);+ expect(isNegative('cancel.')).toBe(true);+ });++ // Regression guard: quote-then-punctuation AND punctuation-then-quote both+ // need to normalize down to the bare token. A single-pass strip that+ // removes quotes before trailing punctuation drops `"confirm".` to+ // `confirm"`, which silently fails the AFFIRM_RE match and discards a+ // pending destructive action.+ it.each([+ '"confirm".', // punctuation outside the closing quote+ '"confirm."', // punctuation inside the closing quote+ "'yes'.", // single quotes + outside punctuation+ '"yes!"', // exclamation inside quotes+ '"go ahead."', // multi-word affirmative inside quotes + punctuation+ ])('handles quote/punctuation ordering "%s" as affirmative', (s) => {+ expect(isAffirmative(s)).toBe(true);+ });++ it.each([+ '"cancel".',+ '"cancel."',+ "'stop'.",+ '"no!"',+ ])('handles quote/punctuation ordering "%s" as negative', (s) => {+ expect(isNegative(s)).toBe(true);+ });++ // STT engines (Whisper) commonly emit a trailing comma after a yes/no+ // when the user takes a brief pause ("yes, delete it" gets transcribed+ // with the comma intact even when the rest of the sentence is missing).+ // Comma/colon/semicolon must be stripped along with sentence-terminator+ // punctuation, otherwise the gate silently discards the pending action.+ it.each(['yes,', 'yes;', 'yes:', 'confirm,', 'okay,', 'ok,'])(+ 'treats yes-with-trailing-punctuation "%s" as affirmative',+ (s) => {+ expect(isAffirmative(s)).toBe(true);+ },+ );++ it.each(['no,', 'cancel,', 'stop,', 'cancel;', 'no:', 'never mind,'])(+ 'treats no-with-trailing-punctuation "%s" as negative',+ (s) => {+ expect(isNegative(s)).toBe(true);+ },+ );++ // "okay cancel" / "ok no" etc. — bare "ok/okay" matches AFFIRM_RE, so+ // without filler-tolerance in NEGATIVE_RE the user's intended cancel would+ // be mis-executed as a destructive confirmation.+ it.each([+ 'okay cancel',+ 'okay never mind',+ 'ok no',+ 'okay stop',+ 'ok cancel',+ ])('treats filler "%s" as negative, not affirmative', (s) => {+ expect(isNegative(s)).toBe(true);+ });+});++describe('resolvePending', () => {+ const pending = buildPending({+ tool: 'ui_click',+ args: { label: 'Delete' },+ target: { ref: 5, label: 'Delete', kind: 'button' },+ });++ it('returns passthrough when no pending', () => {+ expect(resolvePending(null, 'yes').action).toBe('passthrough');+ });++ it('execute on affirmative', () => {+ const d = resolvePending(pending, 'yes');+ expect(d.action).toBe('execute');+ expect(d.pending).toBe(pending);+ });++ it('cancel on negative', () => {+ const d = resolvePending(pending, 'cancel');+ expect(d.action).toBe('cancel');+ });++ it('passthrough on ambiguous (user moved on without yes/no)', () => {+ const d = resolvePending(pending, 'what time is it?');+ expect(d.action).toBe('passthrough');+ });++ it('execute on "confirm"', () => {+ expect(resolvePending(pending, 'confirm').action).toBe('execute');+ });++ it('cancel on "stop"', () => {+ expect(resolvePending(pending, 'stop').action).toBe('cancel');+ });++ // Regression guard for the "okay cancel" class: negative must win over+ // affirmative when the user prefixes a cancel word with "ok/okay".+ it.each([+ ['okay cancel', 'cancel'],+ ['ok no', 'cancel'],+ ['okay never mind', 'cancel'],+ ])('classifies "%s" as %s (negative beats affirmative filler)', (utterance, expected) => {+ expect(resolvePending(pending, utterance).action).toBe(expected);+ });++ // Regression guard for the "cancel meeting" class: sentences that start+ // with a yes/no token but keep going must passthrough so the LLM can+ // handle the new request, rather than being short-circuited with a+ // synthetic "Cancelled." reply that drops the rest of the utterance.+ it.each([+ 'cancel the meeting',+ 'stop the music',+ 'no problem with that',+ 'yes I want to go to lunch',+ 'delete the email from yesterday',+ ])('passes through "%s" (yes/no prefix but full sentence)', (utterance) => {+ expect(resolvePending(pending, utterance).action).toBe('passthrough');+ });+});++describe('buildPending shape', () => {+ it('records tool/args/target with createdAt', () => {+ const before = Date.now();+ const p = buildPending({+ tool: 'ui_click',+ args: { label: 'Reset' },+ target: { ref: 7, label: 'Reset', kind: 'button' },+ });+ expect(p.tool).toBe('ui_click');+ expect(p.args).toEqual({ label: 'Reset' });+ expect(p.target).toEqual({ ref: 7, label: 'Reset', kind: 'button' });+ expect(p.createdAt).toBeGreaterThanOrEqual(before);+ });++ it('accepts an injected createdAt for deterministic tests', () => {+ const p = buildPending({+ tool: 'ui_click',+ args: { label: 'Delete' },+ target: { ref: 1, label: 'Delete', kind: 'button' },+ createdAt: 12345,+ });+ expect(p.createdAt).toBe(12345);+ });+});++describe('isExpired', () => {+ it('returns false for fresh pending', () => {+ const p = buildPending({ tool: 'ui_click', args: {}, target: {} });+ expect(isExpired(p, Date.now())).toBe(false);+ });++ it('returns true when older than TTL', () => {+ const p = { tool: 'ui_click', args: {}, target: {}, createdAt: Date.now() - PENDING_TTL_MS - 1 };+ expect(isExpired(p)).toBe(true);+ });++ it('returns false for null pending', () => {+ expect(isExpired(null)).toBe(false);+ });+});diff --git a/server/services/voice/pipeline.js b/server/services/voice/pipeline.jsindex 2c76ca812f..fe871a9f28 100644--- a/server/services/voice/pipeline.js+++ b/server/services/voice/pipeline.js@@ -13,6 +13,7 @@ import { getVoiceConfig } from './config.js';import { getToolSpecsForIntent, classifyIntent, dispatchTool, getAllToolNames, UI_KINDS } from './tools.js';import { isEchoOfRecentTts, rememberTtsSentence } from './echo.js';import { appendJournal, getToday } from '../brainJournal.js';+import { resolvePending, isExpired } from './confirmGate.js';// Compact per-page UI summary the LLM uses to drive ui_* tools. Keep it// short — every turn pays the token cost. Groups elements by kind and shows@@ -128,6 +129,8 @@ const buildSystemPrompt = (cfg) => {'When the user describes a daily-life event in first person ("I did X today", "X happened today", "set up Y for Z today", "I had a nice walk", "the dishwasher broke") AND no specific tool fits better, the right tool is daily_log_append (NOT goal_log_note unless they explicitly named a goal). goal_log_note is ONLY for "log progress on my <goal-name> goal" / "update my <goal-name> goal with X" — there must be a real goal title in the user\'s words. Random life events like "set up the cat litter box" are daily_log_append, not goals. ' +'"save"/"capture"/"add"/"remember"/"note"/"file"/"log it" → matching capture tool (e.g., brain_capture, meatspace_log_*, daily_log_append, goal_log_note). ' +'"start dictation"/"dictate"/"record my log" → daily_log_start_dictation. ' ++ '"what does this say"/"read this aloud"/"read the page to me"/"what\'s on this page" → ui_read, then speak the returned `content` verbatim (do NOT paraphrase or summarize unless the user asked "what is this page about?"). ' ++ 'DESTRUCTIVE-ACTION FLOW: when ui_click returns `confirmation_required: true` the gate has fired — speak the returned `summary` (it tells the user how to confirm) and STOP. The user\'s next utterance ("yes"/"confirm"/"cancel") is handled BY THE SERVER, not by you — do not re-issue ui_click on the same target unless the user rephrases the request after cancelling. ' +'"what time"/"what day"/"what date" → time_now. ' +'"what are my goals"/"my goals" → goal_list. ' +'"is anything crashed"/"pm2 status"/"are services up" → pm2_status. ' +@@ -332,6 +335,60 @@ export const runTurn = async ({ audio, text, mimeType, source, history = [], emireturn { transcript: userText, reply: '' };}+ // Short, hand-crafted assistant reply that bypasses the LLM. Used by the+ // confirmation gate (and any other future synchronous responses) so the+ // user hears the canonical "Confirmed — Delete account." / "Cancelled."+ // line via TTS plus the same llm:delta/done/idle event sequence a normal+ // turn produces.+ const speakSyntheticReply = async (reply) => {+ const { wav, latencyMs } = await synthesize(reply, { signal });+ if (signal?.aborted) return;+ // Track what we just said in the echo-suppression buffer so the next+ // inbound transcript ("Confirmed — Delete." round-tripping through the+ // mic) is dropped as TTS echo instead of being misclassified as user+ // intent. Mirrors the normal `speak()` path.+ if (state?.recentTts) rememberTtsSentence(state.recentTts, reply);+ emit('voice:tts:audio', { sentence: reply, wav, latencyMs });+ emit('voice:llm:delta', { delta: reply });+ emit('voice:llm:done', { text: reply });+ emit('voice:idle', { reason: 'turn-complete' });+ };++ // Destructive-action confirmation gate. A previous turn stashed a pending+ // click on the session; this turn's utterance either confirms it (re-issue+ // the side effect) or cancels (drop pending and continue normally). Stale+ // pending records are GC'd so a forgotten "yes" minutes later can't fire+ // a destructive action.+ if (state?.pendingDestructive) {+ const pending = state.pendingDestructive;+ state.pendingDestructive = null; // consume up-front; every branch clears it+ if (isExpired(pending)) {+ console.log(`🛑 [${turnId}] dropping expired pending destructive (${pending.tool})`);+ } else {+ const decision = resolvePending(pending, userText);+ if (decision.action === 'execute') {+ const { target } = pending;+ tlog(`confirm.execute ${pending.tool} target="${target.label}"`);+ // Confirmation happens on the user's NEXT spoken turn, by which time+ // the client may have re-indexed the DOM and reassigned refs — the+ // stale `target.ref` could now point at a different element. Emit+ // only the `label` so the client falls through to label-based+ // resolution (uiInteract.resolve() prefers ref when present).+ emit('voice:ui:click', { target: { label: target.label } });+ const reply = `Confirmed — ${target.label}.`;+ await speakSyntheticReply(reply);+ return { transcript: userText, reply };+ }+ if (decision.action === 'cancel') {+ tlog(`confirm.cancel ${pending.tool}`);+ const reply = 'Cancelled.';+ await speakSyntheticReply(reply);+ return { transcript: userText, reply };+ }+ tlog(`confirm.passthrough — discarding pending ${pending.tool}`);+ }+ }+const toolsEnabled = !!cfg.llm.tools?.enabled;const intent = toolsEnabled ? getToolSpecsForIntent(userText) : { specs: undefined, activeGroups: classifyIntent(userText) };const toolSpecs = intent.specs;@@ -390,6 +447,11 @@ export const runTurn = async ({ audio, text, mimeType, source, history = [], emilet lastLlm = null;let finalText = '';const toolRuns = []; // [{ name, ok, ms, error }]+ // Set when a tool returned confirmation_required:true. We short-circuit the+ // turn server-side rather than trusting system-prompt instructions to keep+ // the LLM from issuing further tool calls in the same turn. The pending+ // record was already stashed on state by the tool itself.+ let confirmationPrompt = null;for (let iter = 0; iter < maxIterations; iter++) {if (signal?.aborted) break;@@ -518,7 +580,33 @@ export const runTurn = async ({ audio, text, mimeType, source, history = [], emitool_call_id: tc.resolvedId,content: JSON.stringify(result),});+ // Destructive-action short-circuit: the tool stashed a pending record on+ // state and returned a deterministic confirmation prompt. Stop executing+ // further tool calls in this turn AND skip the next LLM iteration so the+ // model can't (a) issue more tool calls that overwrite pendingDestructive+ // or fire unrelated side effects, or (b) paraphrase the prompt in its+ // own voice. The next user utterance ("yes"/"cancel") is handled by the+ // pre-LLM gate in this same function.+ if (result?.confirmation_required) {+ confirmationPrompt = result.summary || 'That looks destructive — confirm by saying "yes" or "cancel" to skip.';+ break;+ }}+ if (confirmationPrompt) break;+ }++ // Destructive-confirm short-circuit: drain any already-streamed sentences+ // (the model may have spoken "Okay, deleting that" before the tool call),+ // then speak the deterministic confirmation prompt and end the turn. This+ // replaces relying on system-prompt instructions to keep the LLM from+ // continuing tool iterations — the gate is enforced server-side regardless+ // of what the model would have done next.+ if (confirmationPrompt && !signal?.aborted) {+ if (pending.trim()) synthQueue = synthQueue.then(() => speak(pending.trim()));+ await synthQueue;+ tlog(`confirm.prompt "${confirmationPrompt.slice(0, 80)}"`);+ await speakSyntheticReply(confirmationPrompt);+ return { transcript: userText, reply: confirmationPrompt };}if (pending.trim()) synthQueue = synthQueue.then(() => speak(pending.trim()));diff --git a/server/services/voice/pipelineConfirmShortCircuit.test.js b/server/services/voice/pipelineConfirmShortCircuit.test.jsnew file mode 100644index 0000000000..a1212764cf--- /dev/null+++ b/server/services/voice/pipelineConfirmShortCircuit.test.js@@ -0,0 +1,185 @@+import { describe, it, expect, vi } from 'vitest';++// Server-side enforcement of the destructive-action confirmation gate:+// when a tool result includes `confirmation_required: true`, the pipeline+// must (a) stop iterating the LLM in the same turn, (b) NOT execute any+// further queued tool calls, and (c) speak the deterministic `summary`+// prompt via the synthetic-reply path. Relying on the system prompt alone+// is brittle — the model can still chain another tool call in the same+// iteration that would overwrite `state.pendingDestructive` or fire an+// unrelated side effect. This test pins the server-side short-circuit so a+// future refactor can't silently regress.++vi.mock('./config.js', () => ({+ getVoiceConfig: vi.fn(async () => ({+ enabled: true,+ llm: {+ model: 'test-model',+ usePersonality: false,+ systemPrompt: 'sys',+ tools: { enabled: true, maxIterations: 3 },+ },+ })),+}));++vi.mock('./stt.js', () => ({+ transcribe: vi.fn(async () => ({ text: 'delete the account', latencyMs: 5 })),+}));++vi.mock('./tts.js', () => ({+ synthesize: vi.fn(async (text) => ({ wav: Buffer.alloc(8), latencyMs: 1, _text: text })),+}));++// Two-iteration LLM mock: first iteration emits a tool call, second iteration+// (which should NOT run when the gate fires) would emit text. If the+// short-circuit works, streamChat is only invoked once.+const streamChatMock = vi.fn();+vi.mock('./llm.js', () => ({+ streamChat: (...args) => streamChatMock(...args),+}));++// dispatchTool returns the confirmation_required result the real ui_click+// would. We also include a second tool call in the same LLM iteration to+// verify the short-circuit also stops executing siblings.+const dispatchToolMock = vi.fn();+vi.mock('./tools.js', () => ({+ getToolSpecsForIntent: () => ({ specs: [{ type: 'function', function: { name: 'ui_click' } }], activeGroups: new Set(['ui']) }),+ classifyIntent: () => new Set(),+ dispatchTool: (...args) => dispatchToolMock(...args),+ getAllToolNames: () => ['ui_click'],+ UI_KINDS: ['tab', 'button', 'link', 'input', 'textarea', 'select', 'checkbox', 'radio'],+}));++vi.mock('./echo.js', () => ({+ isEchoOfRecentTts: () => false,+ rememberTtsSentence: () => {},+}));++vi.mock('../brainJournal.js', () => ({+ appendJournal: vi.fn(),+ getToday: vi.fn(async () => '2026-05-12'),+}));++const { runTurn } = await import('./pipeline.js');++describe('runTurn — destructive confirmation short-circuit', () => {+ it('stops further tool execution and skips the next LLM iteration when a tool returns confirmation_required', async () => {+ streamChatMock.mockReset();+ dispatchToolMock.mockReset();++ // First (and should be ONLY) LLM iteration returns two tool calls. The+ // first is a destructive ui_click that returns confirmation_required;+ // the second would be a stray tool call the gate must NOT execute.+ streamChatMock.mockImplementationOnce(async () => ({+ text: '',+ toolCalls: [+ { id: 'a', type: 'function', function: { name: 'ui_click', arguments: '{"label":"Delete account"}' }, index: 0 },+ { id: 'b', type: 'function', function: { name: 'ui_click', arguments: '{"label":"Some Other Button"}' }, index: 1 },+ ],+ model: 'test-model',+ ttfbMs: 10,+ totalMs: 20,+ finishReason: 'tool_calls',+ }));+ // If the short-circuit fails, streamChat would be called a second time+ // for a follow-up iteration. We make that throw to force a loud failure.+ streamChatMock.mockImplementationOnce(async () => {+ throw new Error('LLM iterated past confirmation_required — short-circuit broken');+ });++ // dispatchTool returns confirmation_required:true for the first call. If+ // the second sibling call ever executes, the test will see a second+ // dispatchTool invocation in the call list.+ dispatchToolMock.mockResolvedValueOnce({+ ok: true,+ confirmation_required: true,+ label: 'Delete account',+ kind: 'button',+ summary: 'That looks destructive — confirm by saying "yes" or "confirm" to Delete account, or "cancel" to skip.',+ });++ const events = [];+ const emit = (event, payload) => events.push({ event, payload });+ const state = {};++ const result = await runTurn({+ audio: Buffer.alloc(8),+ mimeType: 'audio/webm',+ history: [],+ emit,+ state,+ });++ // streamChat invoked exactly once — the second iteration was skipped.+ expect(streamChatMock).toHaveBeenCalledTimes(1);++ // Only the destructive tool ran. The sibling tool call in the same+ // assistant turn was NOT dispatched.+ expect(dispatchToolMock).toHaveBeenCalledTimes(1);+ expect(dispatchToolMock.mock.calls[0][0]).toBe('ui_click');+ expect(dispatchToolMock.mock.calls[0][1]).toEqual({ label: 'Delete account' });++ // The deterministic confirmation summary was spoken (via the synthetic+ // reply path), and the returned reply matches it.+ expect(result.reply).toContain('Delete account');+ expect(result.reply.toLowerCase()).toContain('confirm');++ const llmDone = events.find((e) => e.event === 'voice:llm:done');+ expect(llmDone).toBeTruthy();+ expect(llmDone.payload.text).toContain('Delete account');++ // Exactly one voice:idle (turn-complete) — the synthetic reply emits its+ // own idle and the main path does NOT emit a second one after returning.+ const idleEvents = events.filter((e) => e.event === 'voice:idle');+ expect(idleEvents.length).toBe(1);+ expect(idleEvents[0].payload.reason).toBe('turn-complete');+ });++ it('does NOT short-circuit when no tool result has confirmation_required (regression guard)', async () => {+ streamChatMock.mockReset();+ dispatchToolMock.mockReset();++ // Iter 1: one tool call (non-destructive). Iter 2: text only, no tool+ // calls, ending the loop normally.+ streamChatMock.mockImplementationOnce(async () => ({+ text: '',+ toolCalls: [+ { id: 'a', type: 'function', function: { name: 'ui_click', arguments: '{"label":"Save"}' }, index: 0 },+ ],+ model: 'test-model',+ ttfbMs: 10,+ totalMs: 20,+ finishReason: 'tool_calls',+ }));+ streamChatMock.mockImplementationOnce(async ({ onDelta } = {}) => {+ // No tool calls — natural loop termination.+ return {+ text: 'Done.',+ toolCalls: [],+ model: 'test-model',+ ttfbMs: 10,+ totalMs: 20,+ finishReason: 'stop',+ };+ });++ dispatchToolMock.mockResolvedValueOnce({ ok: true, label: 'Save', summary: 'Clicked Save.' });++ const events = [];+ const emit = (event, payload) => events.push({ event, payload });+ const state = {};++ const result = await runTurn({+ audio: Buffer.alloc(8),+ mimeType: 'audio/webm',+ history: [],+ emit,+ state,+ });++ // Both iterations ran — no short-circuit.+ expect(streamChatMock).toHaveBeenCalledTimes(2);+ expect(dispatchToolMock).toHaveBeenCalledTimes(1);+ expect(result.reply).toBe('Done.');+ });+});diff --git a/server/services/voice/proactiveSpeech.js b/server/services/voice/proactiveSpeech.jsnew file mode 100644index 0000000000..3df685470a--- /dev/null+++ b/server/services/voice/proactiveSpeech.js@@ -0,0 +1,133 @@+// Server-pushed voice output for the Chief of Staff.+//+// Normal voice turns are user-initiated: the user speaks/types, the LLM+// streams a reply, TTS goes back over the socket. Proactive speech lets the+// CoS speak FIRST — alerts, briefings, reminders — without a user turn.+//+// Three things make this non-trivial:+// 1. Quiet hours. Users don't want the bot piping up at 2am.+// 2. Barge-in. If the user is mid-utterance the proactive line yields.+// 3. Delivery channel. It uses the same Socket.IO `voice:speak` event the+// client already plays back from the TTS pipeline, so the existing+// barge-in path (voice:interrupt → stopPlayback) cancels proactive+// audio for free.+//+// Pure-function quiet-hour / barge-in helpers are exported separately so+// they can be unit-tested without spinning up a server.++import { synthesize } from './tts.js';+import { getVoiceConfig } from './config.js';+import { getUserTimezone, getLocalParts } from '../../lib/timezone.js';++// 24-hour HH:MM regex shared with the route-level Zod schema in+// `routes/voice.js`. Both ends of the config write path validate the same+// shape so a passing schema is guaranteed to parse here.+export const HHMM_RE = /^([01]?\d|2[0-3]):([0-5]\d)$/;++// Parse "HH:MM" → minutes-from-midnight. Returns null for malformed input so+// the caller can decide whether to fall through (quiet hours off) or error.+export const parseHHMM = (s) => {+ if (typeof s !== 'string') return null;+ const m = s.match(HHMM_RE);+ if (!m) return null;+ return Number(m[1]) * 60 + Number(m[2]);+};++// Maximum spoken-text length for proactive lines. The /api/voice/speak Zod+// schema already caps HTTP payloads at 4000 chars, but `speakProactive` is+// also called directly by internal subsystems (CoS, scheduler, etc.) that+// bypass the route validator. Enforce the same bound here so a runaway+// caller can't trigger multi-minute synthesis and a multi-megabyte socket+// payload. Exposed so the route can import the same constant if it ever+// needs to.+export const MAX_PROACTIVE_TEXT_LEN = 4000;++// Quiet-hours window inclusion check. Handles the overnight case (start>end,+// e.g. 22:00 → 07:00) by wrapping. Same-value start/end means "the window is+// empty" — proactive speech is always allowed.+export const isWithinQuietHours = ({ start, end, nowMinutes }) => {+ const s = parseHHMM(start);+ const e = parseHHMM(end);+ if (s === null || e === null) return false;+ if (s === e) return false;+ if (s < e) return nowMinutes >= s && nowMinutes < e;+ // Overnight wrap: in-window if at-or-after start OR before end.+ return nowMinutes >= s || nowMinutes < e;+};++// Pull the user's current local minutes-from-midnight via Intl. Server runs+// TZ=UTC, so a naive `new Date().getHours()` would compare quiet hours+// against UTC and silently let the bot speak during the user's bedtime.+const getLocalMinutes = async () => {+ const tz = await getUserTimezone();+ const parts = getLocalParts(new Date(), tz);+ return parts.hour * 60 + parts.minute;+};++// Pure decision helper — given a config snapshot + current local minutes,+// should this proactive speech go out? Tested directly without time mocking.+export const shouldSpeak = (cfg, nowMinutes) => {+ if (!cfg?.enabled) return { ok: false, reason: 'voice-disabled' };+ const proactive = cfg.llm?.proactive;+ if (!proactive?.enabled) return { ok: false, reason: 'proactive-disabled' };+ if (proactive.quietHours?.enabled) {+ if (isWithinQuietHours({+ start: proactive.quietHours.start,+ end: proactive.quietHours.end,+ nowMinutes,+ })) {+ return { ok: false, reason: 'quiet-hours' };+ }+ }+ 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).+//+// `priority` is informational for now — clients can decide whether to+// surface a toast for high-priority lines or just speak. Reserved field;+// keep the API surface ready for it.+//+// Returns { ok, reason?, latencyMs? } so callers know whether the line+// went out or was suppressed.+export const speakProactive = async ({ io, text, priority = 'normal', source = 'cos' }) => {+ if (!io) return { ok: false, reason: 'no-io' };+ const trimmed = (text || '').trim();+ if (!trimmed) return { ok: false, reason: 'empty' };+ if (trimmed.length > MAX_PROACTIVE_TEXT_LEN) {+ console.warn(`🔕 voice: proactive too-long (${trimmed.length} > ${MAX_PROACTIVE_TEXT_LEN}) "${trimmed.slice(0, 60)}…"`);+ return { ok: false, reason: 'too-long', chars: trimmed.length, maxChars: MAX_PROACTIVE_TEXT_LEN };+ }++ const cfg = await getVoiceConfig();+ // Only resolve the user's local time when the decision actually depends on+ // it. getLocalMinutes() reads settings via getUserTimezone() and is the+ // only async work in the suppression path; skipping it when quiet hours+ // are disabled keeps proactive sends cheap (one fewer fs read + Intl call+ // per line) and removes an avoidable async failure surface.+ const nowMinutes = cfg?.llm?.proactive?.quietHours?.enabled+ ? await getLocalMinutes()+ : 0;+ const decision = shouldSpeak(cfg, nowMinutes);+ if (!decision.ok) {+ console.log(`🔕 voice: proactive suppressed (${decision.reason}) "${trimmed.slice(0, 60)}"`);+ return decision;+ }++ const { wav, latencyMs } = await synthesize(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+ // it as part of the dialogue history.+ io.emit('voice:speak', {+ sentence: trimmed,+ wav,+ latencyMs,+ priority,+ source,+ ts: Date.now(),+ });+ console.log(`🔔 voice: proactive sent (${priority}) "${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.jsnew file mode 100644index 0000000000..036c7f1b00--- /dev/null+++ b/server/services/voice/proactiveSpeech.test.js@@ -0,0 +1,237 @@+import { describe, it, expect, vi } from 'vitest';++// Stub config + tts + timezone before importing the module — the pure-function+// branches need no mocks but speakProactive integration does.+vi.mock('./config.js', () => ({+ getVoiceConfig: vi.fn(async () => ({+ enabled: true,+ llm: { proactive: { enabled: true, quietHours: { enabled: false, start: '22:00', end: '07:00' } } },+ })),+}));+vi.mock('./tts.js', () => ({+ synthesize: vi.fn(async () => ({ wav: Buffer.alloc(64), latencyMs: 12 })),+}));+vi.mock('../../lib/timezone.js', () => ({+ getUserTimezone: vi.fn(async () => 'UTC'),+ getLocalParts: vi.fn(() => ({ hour: 14, minute: 0 })),+}));++const {+ parseHHMM,+ isWithinQuietHours,+ shouldSpeak,+ speakProactive,+ MAX_PROACTIVE_TEXT_LEN,+} = await import('./proactiveSpeech.js');++describe('parseHHMM', () => {+ it.each([+ ['00:00', 0],+ ['07:00', 420],+ ['22:00', 1320],+ ['23:59', 23 * 60 + 59],+ ['9:30', 9 * 60 + 30],+ ])('parses %s → %s', (s, expected) => {+ expect(parseHHMM(s)).toBe(expected);+ });++ it.each(['', '24:00', '12:60', 'abc', null, undefined, '12'])('rejects %s', (s) => {+ expect(parseHHMM(s)).toBeNull();+ });+});++describe('isWithinQuietHours — same-day window', () => {+ const win = { start: '09:00', end: '17:00' };++ it('inside window', () => {+ expect(isWithinQuietHours({ ...win, nowMinutes: 10 * 60 })).toBe(true);+ });++ it('exactly at start (inclusive)', () => {+ expect(isWithinQuietHours({ ...win, nowMinutes: 9 * 60 })).toBe(true);+ });++ it('exactly at end (exclusive)', () => {+ expect(isWithinQuietHours({ ...win, nowMinutes: 17 * 60 })).toBe(false);+ });++ it('before window', () => {+ expect(isWithinQuietHours({ ...win, nowMinutes: 8 * 60 })).toBe(false);+ });++ it('after window', () => {+ expect(isWithinQuietHours({ ...win, nowMinutes: 18 * 60 })).toBe(false);+ });+});++describe('isWithinQuietHours — overnight wrap', () => {+ const win = { start: '22:00', end: '07:00' };++ it('late-evening inside', () => {+ expect(isWithinQuietHours({ ...win, nowMinutes: 23 * 60 })).toBe(true);+ });++ it('early-morning inside', () => {+ expect(isWithinQuietHours({ ...win, nowMinutes: 5 * 60 })).toBe(true);+ });++ it('midday outside', () => {+ expect(isWithinQuietHours({ ...win, nowMinutes: 14 * 60 })).toBe(false);+ });++ it('exactly at end (exclusive)', () => {+ expect(isWithinQuietHours({ ...win, nowMinutes: 7 * 60 })).toBe(false);+ });+});++describe('isWithinQuietHours — malformed/empty', () => {+ it('start==end is empty window', () => {+ expect(isWithinQuietHours({ start: '08:00', end: '08:00', nowMinutes: 8 * 60 })).toBe(false);+ });++ it('malformed start returns false', () => {+ expect(isWithinQuietHours({ start: 'abc', end: '07:00', nowMinutes: 5 * 60 })).toBe(false);+ });+});++describe('shouldSpeak — decision matrix', () => {+ it('blocks when voice disabled', () => {+ expect(shouldSpeak({ enabled: false }, 0).ok).toBe(false);+ });++ it('blocks when proactive disabled', () => {+ expect(shouldSpeak({ enabled: true, llm: { proactive: { enabled: false } } }, 0).ok).toBe(false);+ });++ it('allows when proactive enabled and quiet hours off', () => {+ const cfg = { enabled: true, llm: { proactive: { enabled: true, quietHours: { enabled: false, start: '22:00', end: '07:00' } } } };+ expect(shouldSpeak(cfg, 14 * 60)).toEqual({ ok: true });+ });++ it('blocks during quiet hours when enabled', () => {+ const cfg = { enabled: true, llm: { proactive: { enabled: true, quietHours: { enabled: true, start: '22:00', end: '07:00' } } } };+ const d = shouldSpeak(cfg, 23 * 60);+ expect(d.ok).toBe(false);+ expect(d.reason).toBe('quiet-hours');+ });++ it('allows during awake hours when quiet hours enabled', () => {+ const cfg = { enabled: true, llm: { proactive: { enabled: true, quietHours: { enabled: true, start: '22:00', end: '07:00' } } } };+ expect(shouldSpeak(cfg, 14 * 60).ok).toBe(true);+ });+});++describe('speakProactive', () => {+ const makeIo = () => {+ const emit = vi.fn();+ return { io: { emit }, emit };+ };++ it('returns no-io when io missing', async () => {+ const r = await speakProactive({ io: null, text: 'hi' });+ expect(r.ok).toBe(false);+ expect(r.reason).toBe('no-io');+ });++ it('returns empty when text blank', async () => {+ const { io } = makeIo();+ const r = await speakProactive({ io, text: ' ' });+ expect(r.ok).toBe(false);+ expect(r.reason).toBe('empty');+ });++ // Defense in depth — the route validator caps payloads at 4000 chars, but+ // internal subsystems (CoS, scheduler) call speakProactive directly and+ // 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 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();+ });++ it('accepts text exactly at MAX_PROACTIVE_TEXT_LEN', async () => {+ const { io, emit } = makeIo();+ const r = await speakProactive({ io, text: 'x'.repeat(MAX_PROACTIVE_TEXT_LEN) });+ expect(r.ok).toBe(true);+ expect(emit).toHaveBeenCalledTimes(1);+ });++ it('emits voice:speak with audio when allowed', async () => {+ const { io, emit } = 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(event).toBe('voice:speak');+ expect(payload.sentence).toBe('Heads up — meeting in five.');+ expect(payload.wav).toBeInstanceOf(Buffer);+ expect(payload.priority).toBe('normal');+ expect(payload.source).toBe('cos');+ });++ it('suppresses when proactive disabled', async () => {+ const { getVoiceConfig } = await import('./config.js');+ getVoiceConfig.mockResolvedValueOnce({+ enabled: true,+ llm: { proactive: { enabled: false } },+ });+ const { io, emit } = makeIo();+ const r = await speakProactive({ io, text: 'hi' });+ expect(r.ok).toBe(false);+ expect(r.reason).toBe('proactive-disabled');+ expect(emit).not.toHaveBeenCalled();+ });++ // Avoidable-overhead guard: when quiet hours are off the decision can't+ // depend on local time, so getUserTimezone()/getLocalParts() must NOT be+ // called. Skipping them removes a settings-file read + Intl call per+ // proactive line and one async failure surface.+ it('does not resolve local time when quiet hours are disabled', async () => {+ const { getUserTimezone, getLocalParts } = await import('../../lib/timezone.js');+ getUserTimezone.mockClear();+ getLocalParts.mockClear();+ const { io } = makeIo();+ const r = await speakProactive({ io, text: 'noon ping' });+ expect(r.ok).toBe(true);+ expect(getUserTimezone).not.toHaveBeenCalled();+ expect(getLocalParts).not.toHaveBeenCalled();+ });++ it('resolves local time only when quiet hours are enabled', async () => {+ const { getVoiceConfig } = await import('./config.js');+ const { getUserTimezone, getLocalParts } = await import('../../lib/timezone.js');+ getUserTimezone.mockClear();+ getLocalParts.mockClear();+ getVoiceConfig.mockResolvedValueOnce({+ enabled: true,+ llm: { proactive: { enabled: true, quietHours: { enabled: true, start: '22:00', end: '07:00' } } },+ });+ getLocalParts.mockReturnValueOnce({ hour: 14, minute: 0 });+ const { io } = makeIo();+ const r = await speakProactive({ io, text: 'midday ping' });+ expect(r.ok).toBe(true);+ expect(getUserTimezone).toHaveBeenCalledTimes(1);+ expect(getLocalParts).toHaveBeenCalledTimes(1);+ });++ it('suppresses during quiet hours', async () => {+ const { getVoiceConfig } = await import('./config.js');+ const { getLocalParts } = await import('../../lib/timezone.js');+ getVoiceConfig.mockResolvedValueOnce({+ enabled: true,+ llm: { proactive: { enabled: true, quietHours: { enabled: true, start: '22:00', end: '07:00' } } },+ });+ getLocalParts.mockReturnValueOnce({ hour: 23, minute: 30 });+ const { io, emit } = 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();+ });+});diff --git a/server/services/voice/tools.js b/server/services/voice/tools.jsindex 5eaf017eb9..167c413312 100644--- a/server/services/voice/tools.js+++ b/server/services/voice/tools.js@@ -17,6 +17,7 @@ import { runAsk, VALID_MODES as ASK_VALID_MODES } from '../askService.js';import * as imageGen from '../imageGen/index.js';import { imageGenEvents } from '../imageGenEvents.js';import { getSettings } from '../settings.js';+import { isDestructiveLabel, buildPending } from './confirmGate.js';const DAILY_LOG_PATH = '/brain/daily-log';@@ -171,6 +172,7 @@ const TOOL_GROUPS = {daily_log_stop_dictation: 'dailylog',daily_log_read: 'dailylog',ui_list_interactables: 'ui',+ ui_read: 'ui',ui_click: 'ui',ui_fill: 'ui',ui_select: 'ui',@@ -190,7 +192,7 @@ const TOOL_GROUPS = {// Loose on purpose — false positives are cheap (one extra tool), false// negatives are expensive (LLM guesses wrong or can't act).-export const UI_INTENT_RE = /\b(click|press|tap|hit|open|go to|take me|show me|navigate|select|pick|switch|choose|tab|button|dropdown|field|input|fill|enter|type|write|check|uncheck|toggle|link|option|on (?:this|the) page|what(?:'s)? (?:on|here))\b/i;+export const UI_INTENT_RE = /\b(click|press|tap|hit|open|go to|take me|show me|navigate|select|pick|switch|choose|tab|button|dropdown|field|input|fill|enter|type|write|check|uncheck|toggle|link|option|on (?:this|the) page|what(?:'s)? (?:on|here|does (?:this|the page))|read (?:this|the page|me (?:this|the page|what))|read (?:it )?(?:aloud|out))\b/i;// Strong form-fill signal: when the user is clearly directing content INTO// a specific field, brain_capture/daily_log_append must be suppressed even// if capture verbs appear inside the value (e.g. "fill description with@@ -1035,6 +1037,46 @@ const TOOLS = [},},+ {+ name: 'ui_read',+ description:+ 'Read back the visible text on the current page. Use when the user asks "what does this say?", "read this aloud", "what\'s on the page?", "read me the page". ' ++ 'Returns the user-visible textual content of the main content area (excluding nav rails, asides, and the voice widget itself). ' ++ 'Output is capped at ~8 KB; longer pages are tail-trimmed on a word boundary with an ellipsis. ' ++ 'Default behavior (summarize=false): read the returned `content` verbatim — do NOT summarize. ' ++ 'When the user asks for a summary instead ("what is this page about?", "summarize this page"), pass summarize=true and produce a short summary of `content` rather than reading it verbatim.',+ parameters: {+ type: 'object',+ properties: {+ summarize: {+ type: 'boolean',+ description: 'If true, the LLM may summarize before reading aloud (use when the user asks "what is this page about?" rather than "read this to me"). Default false — speak `content` verbatim.',+ },+ },+ },+ execute: async ({ summarize = false } = {}, ctx = {}) => {+ const ui = ctx?.state?.ui;+ if (!ui || typeof ui.text !== 'string' || !ui.text.trim()) {+ return {+ ok: false,+ error: 'No page text available',+ summary: "I can't see the page content right now — make sure the voice widget is loaded and try again.",+ };+ }+ return {+ ok: true,+ path: ui.path,+ title: ui.title,+ content: ui.text,+ chars: ui.text.length,+ summarize: !!summarize,+ // Keep `summary` short so the LLM message history isn't doubled — the+ // full body lives in `content`.+ summary: `Read page "${ui.title || ui.path || 'current page'}" (${ui.text.length} chars).`,+ };+ },+ },+{name: 'ui_click',description: 'Click a tab, button, or link on the current page by visible label. "Select Memory tab" → label="Memory", kind="tab".',@@ -1049,6 +1091,26 @@ const TOOLS = [execute: async ({ label, kind } = {}, ctx = {}) => {const hit = findUiElement(ctx, label, kind);if (!hit.entry) return hit.err;+ // Destructive-action confirmation gate. If the resolved label looks+ // destructive (delete/remove/discard/reset/clear), stash a pending+ // record on the per-session state and ask the LLM to prompt the user+ // for spoken confirmation. The next user turn is intercepted by+ // pipeline.js → resolvePending() which either re-issues the click or+ // cancels. Skip if the caller already confirmed (re-issue path).+ if (ctx.state && !ctx.confirmed && isDestructiveLabel(hit.entry.label)) {+ ctx.state.pendingDestructive = buildPending({+ tool: 'ui_click',+ args: { label: hit.entry.label, kind: hit.entry.kind },+ target: { ref: hit.entry.ref, label: hit.entry.label, kind: hit.entry.kind },+ });+ return {+ ok: true,+ confirmation_required: true,+ label: hit.entry.label,+ kind: hit.entry.kind,+ summary: `That looks destructive — confirm by saying "yes" or "confirm" to ${hit.entry.label}, or "cancel" to skip.`,+ };+ }ctx.sideEffects?.push({ type: 'ui:click', target: { ref: hit.entry.ref, label: hit.entry.label } });return { ok: true, label: hit.entry.label, kind: hit.entry.kind, summary: `Clicked ${hit.entry.label}.` };},diff --git a/server/services/voice/tools.test.js b/server/services/voice/tools.test.jsindex b94fb5df01..dac189956f 100644--- a/server/services/voice/tools.test.js+++ b/server/services/voice/tools.test.js@@ -460,6 +460,101 @@ describe('getToolSpecsForIntent — ui_ask gating', () => {});});+describe('ui_read', () => {+ it('returns ok:false when no UI index is loaded', async () => {+ const r = await dispatchTool('ui_read', {}, { state: { ui: null } });+ expect(r.ok).toBe(false);+ expect(r.summary).toMatch(/can't see/i);+ });++ it('returns ok:false when UI index has empty/missing text', async () => {+ const r = await dispatchTool('ui_read', {}, { state: { ui: { text: '' } } });+ expect(r.ok).toBe(false);+ });++ it('returns the page text content verbatim', async () => {+ const text = 'Welcome to Tasks. Three tasks pending. Click to add another.';+ const ctx = { state: { ui: { text, path: '/tasks', title: 'Tasks' } } };+ const r = await dispatchTool('ui_read', {}, ctx);+ expect(r.ok).toBe(true);+ expect(r.content).toBe(text);+ expect(r.path).toBe('/tasks');+ expect(r.title).toBe('Tasks');+ expect(r.chars).toBe(text.length);+ expect(r.summary).toMatch(/Read page "Tasks"/);+ });++ it('honors summarize=true flag without altering content', async () => {+ const text = 'long content here';+ const ctx = { state: { ui: { text } } };+ const r = await dispatchTool('ui_read', { summarize: true }, ctx);+ expect(r.ok).toBe(true);+ expect(r.summarize).toBe(true);+ expect(r.content).toBe(text);+ });++ it('is gated on UI intent (read this page → ui_read present)', async () => {+ const { specs } = getToolSpecsForIntent('read me what does this page say');+ const names = specs.map((s) => s.function.name);+ expect(names).toContain('ui_read');+ });+});++describe('ui_click — destructive confirmation gate', () => {+ const makeState = () => ({+ ui: {+ elements: [+ { ref: 1, kind: 'button', label: 'Save' },+ { ref: 2, kind: 'button', label: 'Delete account' },+ { ref: 3, kind: 'button', label: 'Reset filters' },+ ],+ },+ });++ it('clicks non-destructive labels immediately', async () => {+ const state = makeState();+ const sideEffects = [];+ const r = await dispatchTool('ui_click', { label: 'Save' }, { state, sideEffects });+ expect(r.ok).toBe(true);+ expect(r.confirmation_required).toBeUndefined();+ expect(sideEffects).toHaveLength(1);+ expect(sideEffects[0].type).toBe('ui:click');+ expect(state.pendingDestructive).toBeUndefined();+ });++ it('stashes pending and asks for confirmation on destructive label', async () => {+ const state = makeState();+ const sideEffects = [];+ const r = await dispatchTool('ui_click', { label: 'Delete account' }, { state, sideEffects });+ expect(r.ok).toBe(true);+ expect(r.confirmation_required).toBe(true);+ expect(sideEffects).toHaveLength(0);+ expect(state.pendingDestructive).toBeTruthy();+ expect(state.pendingDestructive.tool).toBe('ui_click');+ expect(state.pendingDestructive.target.label).toBe('Delete account');+ });++ it('also gates "Reset filters"', async () => {+ const state = makeState();+ const r = await dispatchTool('ui_click', { label: 'Reset' }, { state, sideEffects: [] });+ expect(r.confirmation_required).toBe(true);+ });++ it('skips the gate when ctx.confirmed flag is set (re-issue path)', async () => {+ const state = makeState();+ const sideEffects = [];+ const r = await dispatchTool(+ 'ui_click',+ { label: 'Delete account' },+ { state, sideEffects, confirmed: true },+ );+ expect(r.ok).toBe(true);+ expect(r.confirmation_required).toBeUndefined();+ expect(sideEffects).toHaveLength(1);+ expect(state.pendingDestructive).toBeUndefined();+ });+});+// image_generate uses imageGen.generateImage under the hood; mocked// above. The codexEnabledRef toggle drives the disabled-gate test.describe("image_generate", () => {diff --git a/server/sockets/voice.js b/server/sockets/voice.jsindex b347e08ee5..e9edb678ab 100644--- a/server/sockets/voice.js+++ b/server/sockets/voice.js@@ -17,6 +17,32 @@ const HISTORY_MESSAGES = 24;// short; 4 KB covers any realistic spoken turn and rejects prompt-stuffing.const MAX_AUDIO_BYTES = 8 * 1024 * 1024;const MAX_TEXT_LEN = 4000;+// Cap on the visible-text snapshot the client ships alongside each UI index.+// Matches `MAX_TEXT_CHARS` in `client/src/services/domIndex.js` so the ~8 KB+// limit documented on the `ui_read` tool is enforced consistently whether the+// truncation happens client-side (well-behaved widget) or server-side here+// (runaway / malicious client). The client already does word-boundary+// truncation; we re-do it server-side so the guarantee holds end-to-end.+const MAX_UI_TEXT_CHARS = 8000;++// Truncate on the last whitespace boundary (space / newline / tab) so the+// tail isn't a partial token, then append an ellipsis. Mirrors the+// client-side truncation in `domIndex.js` so the shape of `ui.text` is+// identical regardless of which side trimmed it. We match ANY whitespace,+// not just space, because the client's `joined` snapshot inserts `\n\n`+// between blocks — a strict space-only search would hard-cut mid-token+// whenever the nearest break is a block separator.+// Exported for direct unit testing without standing up a real socket.+export const truncateOnWordBoundary = (text, max) => {+ if (text.length <= max) return text;+ const cut = text.slice(0, max);+ // /\s\S*$/ finds the LAST whitespace character (followed by zero or more+ // non-whitespace chars to end-of-string). Returns -1 when no whitespace+ // exists at all (a single mega-token longer than `max`), in which case+ // we hard-cut at `max` rather than emit an empty string.+ const lastWs = cut.search(/\s\S*$/);+ return `${cut.slice(0, lastWs > 0 ? lastWs : max)}…`;+};const audioByteLength = (audio) => {if (Buffer.isBuffer(audio)) return audio.byteLength;@@ -145,6 +171,10 @@ export const registerVoiceHandlers = (socket) => {socket.on('voice:interrupt', () => {state.ctrl?.abort();+ // Clear any pending destructive-confirmation gate — after an interrupt+ // the user's next "yes" should NOT be consumed as confirmation of a+ // stale, abandoned destructive action.+ state.pendingDestructive = null;socket.emit('voice:idle', { reason: 'interrupted' });});@@ -152,6 +182,10 @@ export const registerVoiceHandlers = (socket) => {state.ctrl?.abort();state.history = [];state.dictation = { enabled: false, date: null };+ // Same safety guard as voice:interrupt — a reset wipes conversation+ // context, so a pending destructive click from the prior turn must+ // not survive into the next utterance.+ state.pendingDestructive = null;socket.emit('voice:dictation', { enabled: false });socket.emit('voice:idle', { reason: 'reset' });});@@ -189,17 +223,21 @@ export const registerVoiceHandlers = (socket) => {// (ui_click, ui_fill, ui_select, ui_check).socket.on('voice:ui:index', (payload) => {if (!payload || typeof payload !== 'object') return;- const { path, title, elements } = payload;+ const { path, title, elements, text } = payload;if (!Array.isArray(elements)) return;- // Cap to avoid prompt bloat from a malicious or runaway client.- const MAX = 200;+ // Cap elements at 200 to bound prompt size from a malicious or runaway+ // client. (The visible-text `text` field has its own ~8 KB cap, enforced+ // below via `truncateOnWordBoundary(MAX_UI_TEXT_CHARS)` — see the+ // module-level constant for the rationale.)+ const MAX_ELEMENTS = 200;const filtered = elements.filter((e) => e && typeof e === 'object' && typeof e.ref === 'number' && typeof e.label === 'string')- .slice(0, MAX);+ .slice(0, MAX_ELEMENTS);state.ui = {path: typeof path === 'string' ? path.slice(0, 256) : null,title: typeof title === 'string' ? title.slice(0, 120) : null,elements: filtered,+ text: typeof text === 'string' ? truncateOnWordBoundary(text, MAX_UI_TEXT_CHARS) : null,updatedAt: Date.now(),};if (state.uiWaiters.length) {diff --git a/server/sockets/voice.test.js b/server/sockets/voice.test.jsnew file mode 100644index 0000000000..70562e4de2--- /dev/null+++ b/server/sockets/voice.test.js@@ -0,0 +1,61 @@+import { describe, it, expect } from 'vitest';+import { truncateOnWordBoundary } from './voice.js';++describe('truncateOnWordBoundary', () => {+ it('returns input untouched when shorter than the cap', () => {+ expect(truncateOnWordBoundary('hello world', 100)).toBe('hello world');+ });++ it('returns input untouched when exactly the cap', () => {+ const s = 'a'.repeat(10);+ expect(truncateOnWordBoundary(s, 10)).toBe(s);+ });++ it('truncates on the last space and appends an ellipsis', () => {+ // 'one two three four' length=18; cap=11 → 'one two thr' → last space at 7 → 'one two…'+ const out = truncateOnWordBoundary('one two three four', 11);+ expect(out).toBe('one two…');+ });++ it('falls back to a hard cut when there is no space before the cap', () => {+ // No spaces in the prefix → can't find a word boundary, hard-cut.+ const out = truncateOnWordBoundary('abcdefghij more words', 5);+ expect(out).toBe('abcde…');+ });++ // The client's extractVisibleText joins blocks with '\n\n', so the+ // truncation must find the LAST whitespace of any kind — not just a+ // literal space. Without this, a newline-separated block boundary+ // landing before the cap would still hard-cut mid-token.+ it('truncates on a newline boundary when no later space exists', () => {+ // 'block one\n\nblock two longword' — cap=15 → 'block one\n\nbloc'+ // The last whitespace before the partial 'bloc' is the second \n+ // at index 10. Slice(0,10) = 'block one\n', then '…'.+ const text = 'block one\n\nblock two longword';+ const out = truncateOnWordBoundary(text, 15);+ expect(out.endsWith('…')).toBe(true);+ // Tail (before the ellipsis) is not a partial token from "block two".+ expect(out).not.toMatch(/bloc…$/);+ expect(out.startsWith('block one')).toBe(true);+ });++ it('truncates on a tab boundary when present', () => {+ const text = 'col1\tcol2\tcol3-very-long-cell';+ const out = truncateOnWordBoundary(text, 12);+ expect(out.endsWith('…')).toBe(true);+ // Whatever the tail is, it should not be a partial 'col3-very-long-cell' token.+ expect(out).not.toMatch(/col3-…$/);+ });++ it('matches the documented ~8 KB end-to-end cap', () => {+ // Build a long string of 5-char words separated by spaces.+ const word = 'aaaaa';+ const text = Array(2000).fill(word).join(' ');+ const out = truncateOnWordBoundary(text, 8000);+ // Output never exceeds cap + ellipsis (1 char).+ expect(out.length).toBeLessThanOrEqual(8001);+ expect(out.endsWith('…')).toBe(true);+ // Tail isn't a partial token — character before the ellipsis is in the word charset.+ expect(out[out.length - 2]).toMatch(/[a]/);+ });+});