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): dispatch coding tasks to a CLI agent by voice
Adam Eivyc14de0c24b8a
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex b1ae232c45..bdba39d5bd 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -8,6 +8,7 @@ TBD## Added+- **Hand coding tasks to an agent by voice.** Settings → Voice has a new "Enable coding-agent delegation" toggle (under Tools). With it on, you can say things like "have the agent fix the failing backup test" or "refactor the widget registry and open a PR" — the voice Chief-of-Staff hands the task to a CLI coding agent (Claude Code, Codex, Gemini) that works in an isolated git worktree and opens a pull request for review. Your fast local voice model stays the conversational layer; only the heavy coding work delegates out, so the chat stays snappy. Pick which coding agent runs the task (defaults to your active AI provider → model from Settings → Providers), and the assistant speaks the result when the task finishes (this completion announcement still respects quiet hours, and you can turn it off). The work runs in the background — your working tree is never touched; you review the PR.- **Set your home location in Settings → General.** Enter a latitude and longitude and the voice assistant's weather command ("what's the weather?") reports conditions for where you are instead of a default city. Leave both fields blank to fall back to the default location.## Changeddiff --git a/PLAN.md b/PLAN.mdindex 3f50b3f8a9..8abd46cb97 100644--- a/PLAN.md+++ b/PLAN.md@@ -8,6 +8,10 @@ _Batch-cleared 2026-05-25: 23 Next Up items shipped together via parallel sub-ag- [ ] [flux2-multi-reference-python-runner] **FLUX.2 multi-reference Python runner.** The UI + server contract for multi-reference editing shipped 2026-05-17 (slug `multi-reference-image-editing-for-flux-2-ui`); the Python runner (`scripts/flux2_macos.py`) currently ignores the `--reference-images`/`--reference-strengths` args that `local.js` now passes. Wire diffusers' multi-reference API in the runner and swap `server/lib/mediaModels.js#flux2-klein-9b` `tokenizerRepo` to `FLUX.2-klein-9B-kv` (gated repo — requires the user to accept the license on HF). Validate end-to-end with 2–4 uploaded refs. _(Deferred 2026-05-25 from the batch-clear: blocked on gated HF model + GPU validation; can't be verified autonomously.)_- [ ] [apple-health-integration-live-sync] **Apple Health integration for MeatSpace.** iOS live sync (HealthKit Shortcut → `POST /api/meatspace/apple-health` endpoint) plus a bulk historical import path for an exported `export.xml`. Wire into existing MeatSpace tabs so steps / sleep / heart rate / VO2 max / resting HR show alongside the alcohol / blood / body / epigenetic tracks already shipped. GOALS.md flags this as a documented Secondary Goal ("Apple Health integration planned") but no implementation tracking existed until this entry. When this lands, also fold an Apple-Health-imported signal into the Capabilities page "Genome & Health" row (`server/lib/capabilityMap.js#genomeRow` + the route's `genome` fetch) so a health-only setup no longer reports "Not set up" purely because no genome is uploaded (codex review of `[codex5-onboarding-capability-map]`, 2026-05-24). _(Deferred 2026-05-25 from the batch-clear: multi-file feature with an iOS Shortcut component that needs a device to verify.)_+- [ ] [voice-code-agent-target-managed-app] **Voice code-agent delegation can't target a managed app yet.** The `dispatch_code_agent` voice tool (`server/services/voice/tools.js`) creates a CoS user task with no `app` set, so the agent always runs against the PortOS repo (the CoS default workspace). Add an optional spoken target ("…in BookLoom") → resolve to an app id and pass `app` through to `addTask` (cos.js already persists `metadata.app`, and `agentLifecycle.js#registerAgent` already reads it). Needs a phrase→app resolver (fuzzy match against managed app names) and a guard for "app not found." Deferred from the initial build (2026-05-26) to keep v1 scoped to the self-repo case.+- [ ] [voice-code-agent-completion-rate-limit-drop] **Two voice-dispatched tasks finishing within 30s: the second completion announcement is silently dropped.** `proactiveTriggers.js` rate-limits the `task-complete` source at 30s and `allowBySource` DROPS (doesn't queue) throttled lines, so if two distinct dispatched tasks reach a terminal status within the window the user is never told about the second. Coding tasks usually take minutes so it's rare, but a solicited completion shouldn't be dropped — consider a small per-(task-id) dedupe + a short queue for `task-complete` lines instead of a hard throttle, or drop the rate limit for this source (solicited completions are low-frequency and user-wanted). Surfaced by the xhigh code review (2026-05-26).+- [ ] [voice-code-agent-status-query] **No mid-task voice status query for dispatched coding agents.** Once a task is dispatched via `dispatch_code_agent`, the user can only learn the outcome from the completion announcement — there's no "how's that coding task going?" tool. Add a `code_agent_status` voice tool that reads `data/cos/state.json` for running agents tagged `metadata.voiceDispatch` and reports phase/elapsed. Deferred from the initial build (2026-05-26); the completion announcement covers the common case.+- [ ] [voice-code-agent-announce-pr-url] **Completion announcement can't speak the PR link.** `agent:completed` (cosAgents.js) fires BEFORE `cleanupAgentWorktree` creates the PR (agentLifecycle.js), so `formatAgentCompletionLine` (proactiveTriggers.js) only speaks success/failure + the task description, not the PR. To include "PR #512 is up," either (a) emit a later `agent:pr-opened` event from the cleanup path carrying `{ taskId, prUrl, voiceDispatch }` and announce on that instead, or (b) have the announcement defer until the agent record gains a `prUrl`. Deferred 2026-05-26 — a spoken GitHub URL is poor UX anyway and the user reviews the PR visually; the "done" announcement is enough for v1.- [ ] [mediacard-use-mediaimage-for-syncing-assets] **`MediaCard.jsx` grid thumbnails still use a raw `<img src={previewUrl}>`.** Same peer-sync placeholder/live-swap gap that `[peer-sync-medialightbox-use-mediaimage-for-syncing-assets]` fixed for the lightbox — `client/src/components/media/MediaCard.jsx` (~line 42) doesn't get the "Syncing" placeholder or the `peerSync:asset-arrived` atomic swap. Swap the raw `<img>` for `MediaImage`. Surfaced by that item's cross-check during the batch-clear (2026-05-25); was outside its stated scope.- [ ] [chrome-canary-followups] **Hardening for the custom-Chrome-binary feature (xhigh code-review 2026-05-25).** _DONE in the v2.10.0 release review: (b) both `spawn()` calls now have `.on('error', …)` listeners; (d) `browser/server.js#loadConfig` now try/catches the `JSON.parse`; (e) `setup-browser.js#loadConfig` now warns + returns `null` and `applyCanaryToConfig` skips the save when the existing config is unreadable; (f) top-level `runCanarySetup()` is now `.catch()`-wrapped. (c) is tracked separately in `[setup-browser-canary-headless]`. Remaining: (a), (g)–(o)._ **High-severity:** (a) On macOS headed mode (the default), `browser/server.js:208` uses `macAppBundle` only and silently ignores `chromePath` — a UI user who fills in `chromePath` for Canary/Chromium/Brave but leaves `macAppBundle` empty gets stock Chrome and the log misreports the binary; couple the two fields in the UI (or auto-derive `macAppBundle` from `chromePath` when the latter is inside a `.app`). (b) Neither `spawn(chromePath, …)` (line 216) nor `spawn('/usr/bin/open', …)` (line 208) has an `.on('error', …)` listener — a typo in `chromePath` emits 'error' with no listener → `uncaughtException` → portos-browser PM2 child crashes and restart-loops. (c) `scripts/setup-browser.js#applyCanaryToConfig` writes `chromePath` + `macAppBundle` but doesn't flip `headless: false`; combined with the seed default of `headless: true` (`data.reference/browser-config.json`), a fresh install accepting Canary runs Canary invisibly. (d) `browser/server.js#loadConfig` does bare `JSON.parse(raw)` with no try/catch — combined with setup-browser's non-atomic `writeFileSync` and the `cachedConfig` race, a partial-file write crashes the supervisor on next start (PM2 restart-loop forever). **Medium-severity:** (e) `setup-browser.js#loadConfig` silently catches all JSON parse errors and returns `{}`, then `applyCanaryToConfig` saves `{chromePath, macAppBundle}` only — wiping every other user-customized key. (f) Top-level `await runCanarySetup()` has no try/catch — any EACCES on data/browser-config.json aborts `npm run setup` / `update.sh` at what was previously a no-op step. (g) Idempotency guard only checks `chromePath`: users who decline get re-prompted on every update, and users who set only `macAppBundle` keep getting re-prompted. (h) `PORTOS_USE_CANARY` only matches literal `'0'`/`'false'` (opt-out) or `'1'`/`'true'` (opt-in) — `'no'`/`'off'`/`'yes'`/`'on'`/`'True'` fall through both branches. (i) `spawnSync(install.cmd, …, { stdio: 'inherit' })` for brew/winget can hang on a sudo password prompt under non-TTY + `PORTOS_USE_CANARY=1` (update.sh stalls). (j) `cachedConfig` in `browserService.js` is stale relative to setup-browser's direct write — GET /api/browser/config returns pre-update values until process restart. (k) `saveConfig` uses bare `writeFileSync` — switch to the canonical `atomicWrite` pattern (`server/lib/fileUtils.js`). **Low-severity:** (l) `spawnSync` failure-status check `result.status !== 0` treats `status: null` (spawn-failure / signal kill) identically to a non-zero exit and never logs `result.error` — masks ENOENT/EPERM/SIGKILL. (m) `optionalPath` Zod schema accepts any string up to 1024 chars; no `.app`/`.exe` sanity check — user pastes the bundle into `chromePath` → spawn() EISDIR. (n) `launchBrowser`'s reuse-existing-Chrome early-return (line 167) fires BEFORE `headlessMode = config.headless === true` (line 170), leaving the module-level default `false` after a PM2 restart that reuses Chrome — /health reports wrong mode (pre-existing, but in a function touched by this change). (o) `detectCanary` on macOS only checks `/Applications/...`; misses per-user `~/Applications/Google Chrome Canary.app` installs (corporate Macs, `HOMEBREW_CASK_OPTS=--appdir=$HOME/Applications`).diff --git a/client/src/components/settings/VoiceTab.jsx b/client/src/components/settings/VoiceTab.jsxindex 7b7080d906..9ef1fd67d7 100644--- a/client/src/components/settings/VoiceTab.jsx+++ b/client/src/components/settings/VoiceTab.jsx@@ -91,6 +91,7 @@ export function VoiceTab() {// API-type providers only — voice needs low-latency streaming chat, which// CLI/TUI providers can't deliver.const [apiProviders, setApiProviders] = useState([]);+ const [codeProviders, setCodeProviders] = useState([]);const [refreshingModels, setRefreshingModels] = useState(false);const toggleWidgetHidden = (next) => {@@ -114,12 +115,18 @@ export function VoiceTab() {.then(([config, s]) => { setCfg(config); setStatus(s); }).catch(() => toast.error('Failed to load voice settings')).finally(() => setLoading(false));- // Load the provider registry for the LLM provider picker. Voice can only- // stream through `api`-type providers — filter the rest out here. Silent:- // the empty-list fallback is the error UI, so don't also pop a toast.+ // Load the provider registry once. The conversational brain can only+ // stream through `api`-type providers (filtered here); the code-agent+ // picker draws from `cli`/`tui` providers (Claude Code, Codex, Gemini) —+ // those are the ones that can actually edit code. Silent: the empty-list+ // fallback is the error UI, so don't also pop a toast.getProviders({ silent: true })- .then((data) => setApiProviders((data?.providers || []).filter((p) => p.type === 'api')))- .catch(() => setApiProviders([]));+ .then((data) => {+ const all = data?.providers || [];+ setApiProviders(all.filter((p) => p.type === 'api'));+ setCodeProviders(all.filter((p) => p.type === 'cli' || p.type === 'tui'));+ })+ .catch(() => { setApiProviders([]); setCodeProviders([]); });}, []);// Refetch the voice catalog whenever the user flips TTS engine so the picker@@ -240,6 +247,20 @@ export function VoiceTab() {const providerModels = selectedProvider?.models || [];const modelMissing = llmModel !== 'auto' && !providerModels.includes(llmModel);+ // Code-agent delegation picker. Empty provider/model = "system default" (the+ // CoS spawner's activeProvider + selectModelForTask). The saved choice is+ // shown even when absent from the registry so the select never drops it.+ const codeAgentCfg = cfg.llm.codeAgent || {};+ const codeProvider = codeAgentCfg.provider || '';+ const codeModel = codeAgentCfg.model || '';+ const selectedCodeProvider = codeProviders.find((p) => p.id === codeProvider);+ // Only flag a missing provider AFTER the registry loads — otherwise a saved+ // agent is briefly mislabeled "(not a coding agent)" during the fetch (or if+ // it fails and codeProviders stays []). Mirrors providerMissing above.+ const codeProviderMissing = codeProviders.length > 0 && !!codeProvider && !selectedCodeProvider;+ const codeProviderModels = selectedCodeProvider?.models || [];+ const codeModelMissing = !!codeModel && !codeProviderModels.includes(codeModel);+return (<div className="bg-port-card border border-port-border rounded-xl p-4 sm:p-6 space-y-6"><div className="flex items-center gap-2 text-white">@@ -565,6 +586,74 @@ export function VoiceTab() {</div></label>+ <label className="flex items-start gap-3 cursor-pointer md:col-span-2">+ <input+ type="checkbox"+ checked={cfg.llm.codeAgent?.enabled === true}+ onChange={(e) => patch('llm.codeAgent.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">Enable coding-agent delegation</span>+ <span className="text-xs text-gray-500">+ Lets you say "have the agent fix X" — dispatches a CLI coding agent in an isolated worktree that opens a PR. Needs tools enabled above.+ </span>+ </div>+ </label>++ {cfg.llm.codeAgent?.enabled === true && (+ <div className="md:col-span-2 grid grid-cols-1 sm:grid-cols-2 gap-3 pl-7">+ <Field label="Coding agent" hint="Which CLI/TUI agent runs the task. 'System default' uses your active AI provider (Settings → Providers).">+ <select+ value={codeProvider}+ onChange={(e) => {+ // Switching agent invalidates the old model — reset to default.+ patch('llm.codeAgent.provider', e.target.value);+ patch('llm.codeAgent.model', '');+ }}+ className={inputCls}+ >+ <option value="">System default</option>+ {codeProviderMissing && (+ <option value={codeProvider}>{codeProvider} (not a coding agent)</option>+ )}+ {codeProviders.map((p) => (+ <option key={p.id} value={p.id}>+ {p.name}{p.enabled === false ? ' (disabled)' : ''}+ </option>+ ))}+ </select>+ </Field>+ <Field label="Model" hint="'System default' lets the agent pick per task complexity.">+ <select+ value={codeModel}+ onChange={(e) => patch('llm.codeAgent.model', e.target.value)}+ className={inputCls}+ >+ <option value="">System default</option>+ {codeModelMissing && <option value={codeModel}>{codeModel} (current)</option>}+ {codeProviderModels.map((m) => (+ <option key={m} value={m}>{m}</option>+ ))}+ </select>+ </Field>+ <label className="flex items-start gap-3 cursor-pointer sm:col-span-2">+ <input+ type="checkbox"+ checked={cfg.llm.codeAgent?.announceOnComplete !== false}+ onChange={(e) => patch('llm.codeAgent.announceOnComplete', 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">Announce when a dispatched task finishes</span>+ <span className="text-xs text-gray-500">+ Speaks the result when the agent completes. Still honors quiet hours.+ </span>+ </div>+ </label>+ </div>+ )}+<label className="flex items-start gap-3 cursor-pointer md:col-span-2"><inputtype="checkbox"diff --git a/server/routes/palette.js b/server/routes/palette.jsindex a334ec5c8b..6b0844aee6 100644--- a/server/routes/palette.js+++ b/server/routes/palette.js@@ -50,6 +50,7 @@ const PALETTE_ACTIONS = [{ id: 'daily_log_append', label: 'Append to daily log', section: 'Brain' },{ id: 'ui_ask', label: 'Ask Yourself', section: 'Ask' },{ id: 'image_generate', label: 'Generate Image', section: 'Create' },+ { id: 'dispatch_code_agent', label: 'Dispatch coding agent', section: 'Agents' },{ id: 'time_now', label: 'Current time', section: 'System' },];diff --git a/server/routes/voice.js b/server/routes/voice.jsindex 4a0e11b4c4..46e2a797e7 100644--- a/server/routes/voice.js+++ b/server/routes/voice.js@@ -77,6 +77,16 @@ const voiceConfigPatchSchema = z.object({enabled: z.boolean().optional(),maxIterations: z.number().int().min(1).max(10).optional(),}).partial().optional(),+ // Code-agent delegation. provider/model default to '' (= system default);+ // tolerate the UI's empty-string sentinel rather than forcing undefined.+ // 80-char provider cap matches the provider-registry id cap (same as the+ // llm.provider field above).+ codeAgent: z.object({+ enabled: z.boolean().optional(),+ provider: z.string().max(80).optional(),+ model: z.string().max(128).optional(),+ announceOnComplete: z.boolean().optional(),+ }).partial().optional(),proactive: z.object({enabled: z.boolean().optional(),quietHours: z.object({diff --git a/server/services/cos.js b/server/services/cos.jsindex a2c161d49d..4cddc3dc2e 100644--- a/server/services/cos.js+++ b/server/services/cos.js@@ -2392,6 +2392,9 @@ export async function addTask(taskData, taskType = 'user', { raw = false } = {})if (taskData.model) metadata.model = taskData.model;if (taskData.provider) metadata.provider = taskData.provider;if (taskData.app) metadata.app = taskData.app;+ // Tags a task dispatched by the voice code-agent tool so the proactive+ // speech layer can announce its completion (see voice/proactiveTriggers.js).+ if (taskData.voiceDispatch === true) metadata.voiceDispatch = true;if (taskData.isRecovery === true) metadata.isRecovery = true;if (taskData.createJiraTicket) metadata.createJiraTicket = true;// Boolean flags: persist both true and false so users can explicitly override defaults.diff --git a/server/services/voice/config.js b/server/services/voice/config.jsindex e79989326a..cd6411eb24 100644--- a/server/services/voice/config.js+++ b/server/services/voice/config.js@@ -75,6 +75,23 @@ export const VOICE_DEFAULTS = Object.freeze({enabled: false,maxIterations: 3,},+ // Code-agent delegation — lets the voice CoS hand a coding task to a+ // CLI/TUI agent (Claude Code, Codex, Gemini) via the CoS task system.+ // The conversational brain (llm.provider above) stays the fast local+ // router; this is the heavyweight agent that does the actual edits in an+ // isolated worktree and opens a PR. OFF by default. Empty provider/model+ // mean "use the system default AI provider → model" (providers.json+ // activeProvider + selectModelForTask) — exactly what a CoS task does+ // when no override is pinned. announceOnComplete speaks the result when+ // the task finishes (solicited, so it bypasses the proactive-enabled gate+ // but still respects quiet hours). Requires tools.enabled + a tool-use+ // model, same as every other voice tool.+ codeAgent: {+ enabled: false,+ provider: '',+ model: '',+ announceOnComplete: true,+ },// 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 (adiff --git a/server/services/voice/pipeline.js b/server/services/voice/pipeline.jsindex f9236374e5..d5c715b4fa 100644--- a/server/services/voice/pipeline.js+++ b/server/services/voice/pipeline.js@@ -559,7 +559,13 @@ export const runTurn = async ({ audio, text, mimeType, source, history = [], emiconst toolsEnabled = !!cfg.llm.tools?.enabled;const intent = toolsEnabled ? getToolSpecsForIntent(userText) : { specs: undefined, activeGroups: classifyIntent(userText) };- const toolSpecs = intent.specs;+ let toolSpecs = intent.specs;+ // Code-agent delegation is a separate opt-in. When it's off, never offer the+ // tool to the LLM even if the utterance matched the `code` intent group —+ // otherwise the model could try to dispatch an agent the user hasn't enabled.+ if (toolSpecs && !cfg.llm.codeAgent?.enabled) {+ toolSpecs = toolSpecs.filter((s) => s.function?.name !== 'dispatch_code_agent');+ }const messages = [{ role: 'system', content: buildSystemPrompt(cfg) },diff --git a/server/services/voice/proactiveSpeech.js b/server/services/voice/proactiveSpeech.jsindex 4e7ed6ef0b..20a0bfba4d 100644--- a/server/services/voice/proactiveSpeech.js+++ b/server/services/voice/proactiveSpeech.js@@ -52,11 +52,16 @@ const getLocalMinutes = async () => {// 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) => {+//+// `solicited` marks a line the user explicitly asked for (e.g. the completion+// of a coding task they dispatched by voice). Such lines skip the+// proactive-enabled gate — the user opted in by issuing the request — but+// still honor voice-disabled and quiet hours (no piping up at 3am, PR or not).+export const shouldSpeak = (cfg, nowMinutes, { solicited = false } = {}) => {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 (!solicited && !proactive?.enabled) return { ok: false, reason: 'proactive-disabled' };+ if (proactive?.quietHours?.enabled) {if (isWithinQuietHours({start: proactive.quietHours.start,end: proactive.quietHours.end,@@ -77,7 +82,7 @@ export const shouldSpeak = (cfg, nowMinutes) => {//// 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' }) => {+export const speakProactive = async ({ io, text, priority = 'normal', source = 'cos', solicited = false }) => {if (!io) return { ok: false, reason: 'no-io' };const trimmed = (text || '').trim();if (!trimmed) return { ok: false, reason: 'empty' };@@ -95,7 +100,7 @@ export const speakProactive = async ({ io, text, priority = 'normal', source = 'const nowMinutes = cfg?.llm?.proactive?.quietHours?.enabled? await getLocalMinutes(): 0;- const decision = shouldSpeak(cfg, nowMinutes);+ const decision = shouldSpeak(cfg, nowMinutes, { solicited });if (!decision.ok) {console.log(`🔕 voice: proactive suppressed (${decision.reason}) "${trimmed.slice(0, 60)}"`);return decision;diff --git a/server/services/voice/proactiveSpeech.test.js b/server/services/voice/proactiveSpeech.test.jsindex 16a232836a..9d8159cab2 100644--- a/server/services/voice/proactiveSpeech.test.js+++ b/server/services/voice/proactiveSpeech.test.js@@ -122,6 +122,20 @@ describe('shouldSpeak — decision matrix', () => {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);});++ it('solicited bypasses the proactive-disabled gate but not voice-disabled', () => {+ // proactive off + solicited → still speaks (user asked for it).+ expect(shouldSpeak({ enabled: true, llm: { proactive: { enabled: false } } }, 0, { solicited: true }).ok).toBe(true);+ // voice itself off → solicited can't override.+ expect(shouldSpeak({ enabled: false }, 0, { solicited: true }).ok).toBe(false);+ });++ it('solicited still respects quiet hours', () => {+ const cfg = { enabled: true, llm: { proactive: { enabled: false, quietHours: { enabled: true, start: '22:00', end: '07:00' } } } };+ const d = shouldSpeak(cfg, 23 * 60, { solicited: true });+ expect(d.ok).toBe(false);+ expect(d.reason).toBe('quiet-hours');+ });});describe('speakProactive', () => {diff --git a/server/services/voice/proactiveTriggers.js b/server/services/voice/proactiveTriggers.jsindex 9833fd113c..815e2eff16 100644--- a/server/services/voice/proactiveTriggers.js+++ b/server/services/voice/proactiveTriggers.js@@ -30,6 +30,7 @@ import { errorEvents } from '../../lib/errorHandler.js';import { cosEvents } from '../cosEvents.js';import { notificationEvents } from '../notifications.js';import { speakProactive as defaultSpeak } from './proactiveSpeech.js';+import { getVoiceConfig } from './config.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@@ -38,6 +39,10 @@ export const RATE_LIMIT_MS = {error: 90_000,'task:ready': 60_000,notification: 60_000,+ // Completion of a voice-dispatched coding task. A 30s floor keeps two+ // tasks finishing back-to-back from talking over each other while still+ // letting the user hear about each within a normal review cadence.+ 'task-complete': 30_000,};// Spoken lines should be short — synthesis is capped at MAX_PROACTIVE_TEXT_LEN@@ -83,6 +88,32 @@ export const formatNotificationLine = (notification) => {return description ? `${title}. ${description}` : title;};+// Truthy check mirroring isTruthyMeta — task metadata round-trips through+// TASKS.md, so `voiceDispatch: true` comes back as the STRING 'true'. Kept+// inline so this module stays decoupled from the agent-state helpers.+const isMetaTrue = (v) => v === true || v === 'true';++// Completion of a voice-dispatched coding task, keyed off the task's TERMINAL+// status (completed / blocked) rather than per-agent-attempt — so a task that+// retries doesn't announce on every attempt, and a user-cancelled task is+// suppressed by the caller. The PR URL is NOT spoken — it isn't created until+// cleanup runs after completion, and a GitHub URL is poor speech anyway; the+// user reviews the PR visually. Uses the first line of the description so a+// multi-line task spec doesn't get read out.+export const formatTaskCompletionLine = (task) => {+ if (!task) return '';+ const desc = clip((task.description || '').split('\n')[0]);+ const success = task.status === 'completed';+ if (!desc) {+ return success+ ? 'Your coding task is done.'+ : "Heads up — a coding task you dispatched didn't finish cleanly.";+ }+ return success+ ? `Your coding task is done: ${desc}.`+ : `Heads up — the coding task "${desc}" didn't finish cleanly.`;+};+/*** Subscribe proactive speech to live event sources.*@@ -112,7 +143,7 @@ export const wireProactiveTriggers = ({ io, speak = defaultSpeak, limits = RATE_// event already claimed the slot) so the budget isn't spent on a non-line.// try/finally only — a synthesis rejection still propagates to the caller's// catch.- const dispatch = async (source, text, priority) => {+ const dispatch = async (source, text, priority, { solicited = false } = {}) => {if (!text) return;const now = Date.now();if (!allowBySource(source, lastSpokenAt.get(source), now, limits)) return;@@ -120,7 +151,7 @@ export const wireProactiveTriggers = ({ io, speak = defaultSpeak, limits = RATE_lastSpokenAt.set(source, now);let ok = false;try {- const result = await speak({ io, text, priority, source });+ const result = await speak({ io, text, priority, source, solicited });ok = !!result?.ok;} finally {if (!ok && lastSpokenAt.get(source) === now) lastSpokenAt.set(source, previous);@@ -141,15 +172,45 @@ export const wireProactiveTriggers = ({ io, speak = defaultSpeak, limits = RATE_const onTaskReady = (task) => fire('task:ready', formatTaskLine(task), 'normal');const onNotification = (notification) => fire('notification', formatNotificationLine(notification), 'high');+ // Announce completion of a coding task the user dispatched by voice. Keyed+ // off the TERMINAL task status (tasks:changed → updated → completed/blocked)+ // rather than agent:completed, so a task that retries on a transient failure+ // announces once (at its terminal outcome), not on every attempt. Gated on+ // cheap synchronous checks first (action / terminal status / voiceDispatch)+ // before the config read. A user-cancelled task lands as blocked with+ // blockedCategory 'user-terminated' — suppress it (the user stopped it on+ // purpose; "didn't finish cleanly" would be wrong). Solicited: bypasses+ // proactive-enabled but not voice-disabled / quiet hours. dispatch() (not+ // fire) so we can await the config read and still route the rejection+ // through the same catch.+ const onTaskUpdated = (evt) => {+ if (evt?.action !== 'updated') return;+ const task = evt.task;+ const status = task?.status;+ if (status !== 'completed' && status !== 'blocked') return;+ if (!isMetaTrue(task.metadata?.voiceDispatch)) return;+ if (status === 'blocked' && task.metadata?.blockedCategory === 'user-terminated') return;+ (async () => {+ const cfg = await getVoiceConfig();+ if (cfg?.llm?.codeAgent?.announceOnComplete === false) return;+ const priority = status === 'completed' ? 'normal' : 'high';+ await dispatch('task-complete', formatTaskCompletionLine(task), priority, { solicited: true });+ })().catch((err) =>+ console.error(`🔕 voice: proactive task-complete trigger failed: ${err?.message || err}`),+ );+ };+errorEvents.on('error', onError);cosEvents.on('task:ready', onTaskReady);+ cosEvents.on('tasks:changed', onTaskUpdated);notificationEvents.on('added', onNotification);- console.log('🔔 voice: proactive triggers wired (error/task:ready/notification)');+ console.log('🔔 voice: proactive triggers wired (error/task:ready/tasks:changed/notification)');return () => {errorEvents.off('error', onError);cosEvents.off('task:ready', onTaskReady);+ cosEvents.off('tasks:changed', onTaskUpdated);notificationEvents.off('added', onNotification);};};diff --git a/server/services/voice/proactiveTriggers.test.js b/server/services/voice/proactiveTriggers.test.jsindex bd713e5ee1..6406d95212 100644--- a/server/services/voice/proactiveTriggers.test.js+++ b/server/services/voice/proactiveTriggers.test.js@@ -1,17 +1,27 @@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.+// singletons) but injects a fake `speak`, so no tts/timezone mocking is needed+// — the delivery primitive never runs. Only `getVoiceConfig` is overridden+// (the agent:completed handler reads it for the announceOnComplete gate);+// the rest of config.js (voiceHome, PIPER_BIN_NAME) must stay real because+// the proactiveSpeech → tts import chain reads those at module load.+vi.mock('./config.js', async (importActual) => ({+ ...(await importActual()),+ getVoiceConfig: vi.fn(async () => ({ enabled: true, llm: { codeAgent: { announceOnComplete: true } } })),+}));+import { errorEvents } from '../../lib/errorHandler.js';import { cosEvents } from '../cosEvents.js';import { notificationEvents } from '../notifications.js';+import { getVoiceConfig } from './config.js';import {allowBySource,isHighPriorityNotification,formatErrorLine,formatTaskLine,formatNotificationLine,+ formatTaskCompletionLine,wireProactiveTriggers,RATE_LIMIT_MS,} from './proactiveTriggers.js';@@ -92,12 +102,35 @@ describe('formatNotificationLine', () => {});});+describe('formatTaskCompletionLine', () => {+ it('reports success with the first line of the task description', () => {+ const line = formatTaskCompletionLine({+ status: 'completed',+ description: 'Fix the flaky backup test\n\nmore detail here',+ });+ expect(line).toBe('Your coding task is done: Fix the flaky backup test.');+ });++ it('reports a blocked task as a failure', () => {+ const line = formatTaskCompletionLine({ status: 'blocked', description: 'Refactor the registry' });+ expect(line).toMatch(/didn't finish cleanly/i);+ expect(line).toMatch(/Refactor the registry/);+ });++ it('falls back to a generic line when no description is present', () => {+ expect(formatTaskCompletionLine({ status: 'completed', description: '' }))+ .toBe('Your coding task is done.');+ expect(formatTaskCompletionLine(null)).toBe('');+ });+});+describe('wireProactiveTriggers', () => {let unwire;let speak;beforeEach(() => {speak = vi.fn(async () => ({ ok: true }));+ getVoiceConfig.mockResolvedValue({ enabled: true, llm: { codeAgent: { announceOnComplete: true } } });});afterEach(() => {@@ -213,9 +246,79 @@ describe('wireProactiveTriggers', () => {}});- it('default RATE_LIMIT_MS covers all three wired sources', () => {+ it('default RATE_LIMIT_MS covers all wired sources', () => {expect(RATE_LIMIT_MS).toHaveProperty('error');expect(RATE_LIMIT_MS).toHaveProperty('task:ready');expect(RATE_LIMIT_MS).toHaveProperty('notification');+ expect(RATE_LIMIT_MS).toHaveProperty('task-complete');+ });++ // Helper: a tasks:changed 'updated' event payload for a voice-dispatched task.+ const taskUpdate = (status, extra = {}) => ({+ type: 'user',+ action: 'updated',+ task: { id: 't1', status, description: 'Fix the backup test', metadata: { voiceDispatch: true, ...extra } },+ });++ it('announces a voice-dispatched task completion as a solicited line', async () => {+ unwire = wireProactiveTriggers({ io: {}, speak });++ // A non-voice task completing must NOT speak.+ cosEvents.emit('tasks:changed', { type: 'user', action: 'updated', task: { status: 'completed', description: 'x', metadata: {} } });+ await flush();+ expect(speak).not.toHaveBeenCalled();++ // A voice-dispatched one does, flagged solicited so it bypasses the+ // proactive-enabled gate downstream.+ cosEvents.emit('tasks:changed', taskUpdate('completed'));+ await flush();+ expect(speak).toHaveBeenCalledTimes(1);+ expect(speak.mock.calls[0][0]).toMatchObject({ source: 'task-complete', solicited: true, priority: 'normal' });+ expect(speak.mock.calls[0][0].text).toMatch(/Fix the backup test/);+ });++ it('accepts the string "true" voiceDispatch flag (markdown round-trip)', async () => {+ unwire = wireProactiveTriggers({ io: {}, speak });+ cosEvents.emit('tasks:changed', { type: 'user', action: 'updated', task: { status: 'completed', description: 'y', metadata: { voiceDispatch: 'true' } } });+ await flush();+ expect(speak).toHaveBeenCalledTimes(1);+ });++ it('uses high priority for a blocked (failed) dispatched task', async () => {+ unwire = wireProactiveTriggers({ io: {}, speak });+ cosEvents.emit('tasks:changed', taskUpdate('blocked'));+ await flush();+ expect(speak).toHaveBeenCalledTimes(1);+ expect(speak.mock.calls[0][0].priority).toBe('high');+ });++ it('does NOT announce on non-terminal updates (retry → pending, spawn → in_progress)', async () => {+ unwire = wireProactiveTriggers({ io: {}, speak });+ cosEvents.emit('tasks:changed', taskUpdate('pending'));+ cosEvents.emit('tasks:changed', taskUpdate('in_progress'));+ await flush();+ expect(speak).not.toHaveBeenCalled();+ });++ it('suppresses the failure line for a user-terminated task', async () => {+ unwire = wireProactiveTriggers({ io: {}, speak });+ cosEvents.emit('tasks:changed', taskUpdate('blocked', { blockedCategory: 'user-terminated' }));+ await flush();+ expect(speak).not.toHaveBeenCalled();+ });++ it('ignores non-update actions (added/deleted/reordered)', async () => {+ unwire = wireProactiveTriggers({ io: {}, speak });+ cosEvents.emit('tasks:changed', { type: 'user', action: 'added', task: { status: 'completed', metadata: { voiceDispatch: true } } });+ await flush();+ expect(speak).not.toHaveBeenCalled();+ });++ it('does not announce when announceOnComplete is disabled', async () => {+ getVoiceConfig.mockResolvedValue({ enabled: true, llm: { codeAgent: { announceOnComplete: false } } });+ unwire = wireProactiveTriggers({ io: {}, speak });+ cosEvents.emit('tasks:changed', taskUpdate('completed'));+ await flush();+ expect(speak).not.toHaveBeenCalled();});});diff --git a/server/services/voice/tools.js b/server/services/voice/tools.jsindex 817c7ce224..6717568690 100644--- a/server/services/voice/tools.js+++ b/server/services/voice/tools.js@@ -20,6 +20,7 @@ import { runAsk, VALID_MODES as ASK_VALID_MODES } from '../askService.js';import * as imageGen from '../imageGen/index.js';import { createImageGenWaiter } from '../imageGenWaiter.js';import { getSettings } from '../settings.js';+import { getVoiceConfig } from './config.js';import { isDestructiveLabel, buildPending } from './confirmGate.js';const DAILY_LOG_PATH = '/brain/daily-log';@@ -201,6 +202,7 @@ const TOOL_GROUPS = {pipeline_next_stage: 'pipeline',pipeline_prev_stage: 'pipeline',pipeline_open_stage: 'pipeline',+ dispatch_code_agent: 'code',// UNGROUPED = always-on: time_now, daily_log_append, ui_navigate.// brain_capture used to be always-on, but that caused form-fill turns// ("fill description with X") to be misrouted to brain_capture because@@ -284,6 +286,15 @@ const GROUP_INTENT = {// Alias list must mirror PIPELINE_STAGE_ALIASES below so any alias// accepted by pipeline_open_stage actually triggers the group.pipeline: /\b(?:next stage|previous stage|prev stage|stage (?:advance|forward|back)|(?:open|go to|back to)(?: the)? (?:idea|prose|story|comic ?script|comicscript|comics|tv ?script|tvscript|teleplay|comic ?pages?|comicpages|pages?|storyboards?|scenes|episode ?video|episodevideo|episode|video)(?: stage)?)\b/i,+ // Code-agent delegation — software-engineering requests and explicit+ // "have <agent> …" phrasing. The ambiguous verbs (implement/debug/rewrite/+ // patch) require a following code-domain object within ~40 chars, so+ // "implement my morning routine" / "debug my relationship" / "add a feature+ // to my calendar" do NOT match; `refactor` stays standalone (rarely non-code+ // in speech). A false positive only OFFERS the tool to the LLM (which still+ // has to choose it), and the tool is a no-op unless codeAgent.enabled+ // (pipeline.js strips it from the spec list when off).+ code: /\b(?:have (?:claude|codex|gemini|the agent|an agent)\b|dispatch (?:a |an )?(?:coding |code )?agent|spin up an agent|code (?:it )?up|open a pr|pull request|refactor|(?:implement|debug|rewrite|patch)\b[^.!?\n]{0,40}\b(?:bug|tests?|function|method|build|lint|type ?error|error|code|file|module|endpoint|route|component|class|api|schema|migration|script|flag|regression|handler|parser|service|hook|query|registry|config)\b|fix (?:the |a |an |my )?(?:bug|test|tests|failing|function|method|build|lint|type|error|code|file|module|endpoint|route|component)|write (?:a |the |some )?(?:unit |integration )?tests?|add (?:a |an |the )?(?:flag|function|method|endpoint|route|test|migration)\b)/i,ui: UI_INTENT_RE,};@@ -1791,6 +1802,86 @@ const TOOLS = [};},},++ {+ name: 'dispatch_code_agent',+ description:+ 'Hand a software-engineering task to an autonomous coding agent that works in an isolated git worktree and opens a pull request for review. Use when the user asks you to write, fix, refactor, debug, or test CODE — e.g. "fix the failing test in X", "add a --dry-run flag to the backup script", "refactor the widget registry". Do NOT use for capturing notes/ideas (that is brain_capture) or for clicking/navigating the UI. The work runs in the background and the user is told when it finishes — do not wait for it. State the task in the user\'s own words with enough detail to act on it. The coding agent and model come from the user\'s configured default; never put a provider or model in this call.',+ parameters: {+ type: 'object',+ properties: {+ task: {+ type: 'string',+ description: 'The coding task to perform, phrased as a clear, self-contained instruction (file/feature names, the desired outcome). The agent reads this verbatim as its prompt.',+ },+ },+ required: ['task'],+ },+ execute: async ({ task } = {}) => {+ const text = typeof task === 'string' ? task.trim() : '';+ if (!text) {+ return { ok: false, error: 'task is required', summary: "I didn't catch what you want the coding agent to do." };+ }++ // Backstop for the palette path — pipeline.js already strips this tool+ // from the LLM's spec list when codeAgent is disabled, but the command+ // palette dispatches by id regardless, so re-check here.+ const cfg = await getVoiceConfig();+ const codeAgent = cfg?.llm?.codeAgent || {};+ if (!codeAgent.enabled) {+ return { ok: false, error: 'code-agent disabled', summary: 'Coding-agent dispatch is off — turn it on under Settings, Voice, Coding agent.' };+ }++ // Dynamic import: cos.js is a large module with its own import graph;+ // importing it lazily keeps tools.js load-time light and dodges any+ // cos → voice cycle.+ const { addTask, isRunning } = await import('../cos.js');+ const provider = typeof codeAgent.provider === 'string' ? codeAgent.provider.trim() : '';+ const model = typeof codeAgent.model === 'string' ? codeAgent.model.trim() : '';++ const created = await addTask({+ description: text,+ priority: 'HIGH',+ position: 'top',+ voiceDispatch: true,+ // The promise of this tool (and the changelog / spoken copy) is+ // isolated work that opens a PR and never touches the user's working+ // tree. spawnAgentForTask only honors that when the task explicitly+ // opts in — without these flags it runs in the shared workspace and+ // auto-merges. Set both so the dispatched agent always works in a+ // worktree and surfaces a PR for review.+ useWorktree: true,+ openPR: true,+ // Pin only when configured. Omitting provider/model lets the CoS+ // spawner fall back to the system default (providers.json+ // activeProvider) + selectModelForTask — the "default to system AI+ // provider → model" behavior.+ ...(provider ? { provider } : {}),+ ...(model ? { model } : {}),+ }, 'user');++ // addTask auto-spawns user tasks, but only while the CoS runner is up.+ // isRunning() is a synchronous daemon-state check. Surface a stopped+ // runner on BOTH paths so a re-issue of an already-queued task isn't+ // falsely reassuring when nothing is actually running it.+ const running = isRunning();+ const stoppedNote = ' — but the Chief-of-Staff runner is stopped, so start it to run it';++ if (created?.duplicate) {+ return {+ ok: true,+ taskId: created.id,+ duplicate: true,+ summary: `That coding task is already queued${running ? ', so I left it as is.' : `${stoppedNote}.`}`,+ };+ }++ const summary = running+ ? "Queued a coding task — I'll let you know when it's done."+ : `Queued the coding task${stoppedNote}.`;+ return { ok: true, taskId: created?.id, running, summary };+ },+ },];const toSpec = (t) => ({diff --git a/server/services/voice/tools.test.js b/server/services/voice/tools.test.jsindex f264a49e9e..e79c976f54 100644--- a/server/services/voice/tools.test.js+++ b/server/services/voice/tools.test.js@@ -133,8 +133,21 @@ vi.mock('../askService.js', () => ({}),}));+// dispatch_code_agent reads voice config (codeAgent gate + provider/model) and+// lazily imports cos.js for addTask/isRunning. Mock both so the tool can be+// exercised without a real settings file or CoS daemon.+vi.mock('./config.js', () => ({+ getVoiceConfig: vi.fn(async () => ({ llm: { codeAgent: { enabled: true, provider: '', model: '' } } })),+}));+vi.mock('../cos.js', () => ({+ addTask: vi.fn(async (data) => ({ id: 'task-test', ...data })),+ isRunning: vi.fn(() => true),+}));+const { dispatchTool, getToolSpecs, getToolSpecsForIntent, classifyIntent, anchorLocalMidnightUtc } = await import('./tools.js');const { getUtcOffsetMs: mockedGetUtcOffsetMs } = await import('../../lib/timezone.js');+const { getVoiceConfig: mockedGetVoiceConfig } = await import('./config.js');+const { addTask: mockedAddTask, isRunning: mockedIsRunning } = await import('../cos.js');describe('getToolSpecs', () => {it('returns OpenAI-format function specs', () => {@@ -154,6 +167,72 @@ describe('dispatchTool unknown tool', () => {});});+describe('dispatch_code_agent', () => {+ afterEach(() => {+ mockedAddTask.mockClear();+ mockedIsRunning.mockReturnValue(true);+ mockedGetVoiceConfig.mockResolvedValue({ llm: { codeAgent: { enabled: true, provider: '', model: '' } } });+ });++ it('rejects an empty task without creating a CoS task', async () => {+ const r = await dispatchTool('dispatch_code_agent', { task: ' ' });+ expect(r.ok).toBe(false);+ expect(mockedAddTask).not.toHaveBeenCalled();+ });++ it('refuses when codeAgent is disabled', async () => {+ mockedGetVoiceConfig.mockResolvedValue({ llm: { codeAgent: { enabled: false } } });+ const r = await dispatchTool('dispatch_code_agent', { task: 'fix the build' });+ expect(r.ok).toBe(false);+ expect(r.error).toMatch(/disabled/);+ expect(mockedAddTask).not.toHaveBeenCalled();+ });++ it('creates a voice-dispatched user task without pinning provider/model by default', async () => {+ const r = await dispatchTool('dispatch_code_agent', { task: 'fix the failing backup test' });+ expect(r.ok).toBe(true);+ expect(r.taskId).toBe('task-test');+ expect(mockedAddTask).toHaveBeenCalledTimes(1);+ const [data, taskType] = mockedAddTask.mock.calls[0];+ expect(taskType).toBe('user');+ // Contract: isolated worktree + PR (never edits the working tree in place).+ expect(data).toMatchObject({ description: 'fix the failing backup test', voiceDispatch: true, useWorktree: true, openPR: true });+ // System-default behavior: no provider/model keys when none configured.+ expect(data).not.toHaveProperty('provider');+ expect(data).not.toHaveProperty('model');+ });++ it('pins provider/model when configured', async () => {+ mockedGetVoiceConfig.mockResolvedValue({ llm: { codeAgent: { enabled: true, provider: 'codex-cli', model: 'gpt-5' } } });+ await dispatchTool('dispatch_code_agent', { task: 'add a flag' });+ expect(mockedAddTask.mock.calls[0][0]).toMatchObject({ provider: 'codex-cli', model: 'gpt-5' });+ });++ it('warns in the summary when the CoS runner is stopped', async () => {+ mockedIsRunning.mockReturnValue(false);+ const r = await dispatchTool('dispatch_code_agent', { task: 'refactor X' });+ expect(r.ok).toBe(true);+ expect(r.summary).toMatch(/stopped/i);+ });+});++describe('code intent classification', () => {+ it('routes coding requests to the code group', () => {+ expect([...classifyIntent('have the agent fix the failing test')]).toContain('code');+ expect([...classifyIntent('refactor the widget registry')]).toContain('code');+ expect([...classifyIntent('write a unit test for the echo filter')]).toContain('code');+ });++ it('does not route plain reminders/notes/ambiguous-verb phrases to the code group', () => {+ expect([...classifyIntent('remind me to call mom')]).not.toContain('code');+ expect([...classifyIntent('what is on my calendar today')]).not.toContain('code');+ // Ambiguous verbs require a code-domain object — these must NOT match.+ expect([...classifyIntent('implement my morning routine')]).not.toContain('code');+ expect([...classifyIntent('debug my relationship with my mom')]).not.toContain('code');+ expect([...classifyIntent('add a feature to my calendar')]).not.toContain('code');+ });+});+describe('brain_capture validation', () => {it('rejects missing text', async () => {await expect(dispatchTool('brain_capture', {})).rejects.toThrow(/text is required/);