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
voice: add fast-resolution cascade (trigger → browser Nano → server)
Adam Eivy3409173400fb
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 7f2261efc3..f5433c4bd4 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -3,6 +3,7 @@## Added- **First-run tutorial for POST cognitive drills.** The timed, stimulus-driven cognitive drills (n-back, digit-span, stroop, schulte-table, mental-rotation, reaction-time) start flashing a stimulus the instant they mount, which is disorienting the first time you meet one. Each drill type now shows a one-time how-to card — a plain-language goal, numbered steps, and the controls — the first time it's encountered, and holds the drill (and its timers) until you tap **Start drill**. The card is config-aware (it names the n-back lag, the digit-span direction, and the reaction-time mode), then never shows again for that type (tracked per type in `localStorage`). Non-timed drills (math/memory, LLM/verbal) are self-explanatory and are not gated.+- **Voice fast-resolution cascade (lower CoS latency, opt-in).** The voice Chief of Staff can now triage each spoken/typed turn through fast client-side tiers before the (slow) server LLM: **tier 1 triggers** resolve navigation commands ("go to tasks", "open the daily log") instantly in the browser with no LLM; **tier 2** runs Chrome's on-device **Gemini Nano** (Prompt API — `window.LanguageModel` / legacy `self.ai.languageModel`) for simple/conversational turns, entirely local and private; **tier 3** is the existing server pipeline (recommend Ollama), which still handles every tool/action turn, personal-data retrieval, dictation, and confirmations. Off by default (existing installs keep all-server behavior); enable under **Settings → Voice → Fast resolution**, which also shows a live on-device-model availability pill with the `chrome://flags` hint. Applies to Web-Speech STT and typed input (whisper/hands-free audio turns stay server-driven); trigger/Nano replies are spoken through the configured TTS and keep barge-in + echo-suppression working. New `llm.fastPath` config (`enabled`/`triggers`/`browserLlm`/`browser.{temperature,topK}`); new client modules `browserLlm.js` (Nano client) and `voiceFastPath.js` (routing decision). Nothing runs a model the user hasn't triggered (no cold-bootstrap).## Fixeddiff --git a/client/src/components/settings/VoiceTab.jsx b/client/src/components/settings/VoiceTab.jsxindex a6ba6f71c4..e0cb706213 100644--- a/client/src/components/settings/VoiceTab.jsx+++ b/client/src/components/settings/VoiceTab.jsx@@ -8,6 +8,7 @@ import {} from '../../services/apiVoice';import { getProviders, refreshProviderModels } from '../../services/apiProviders';import { playWav, webSpeechSupported } from '../../services/voiceClient';+import { nanoAvailability } from '../../services/browserLlm';import { readVoiceHidden, writeVoiceHidden } from '../../services/voiceVisibility';import { formatVoiceLabel } from '../../lib/voiceLabel';@@ -45,6 +46,15 @@ const WHISPER_MODELS = [{ value: 'large-v3', file: 'ggml-large-v3.bin', label: 'large-v3 — 3 GB, multilingual, best' },];+// On-device (Gemini Nano) availability → [label, text tone, dot tone].+const NANO_STATUS_UI = {+ available: ['On-device model ready', 'text-port-success', 'bg-port-success'],+ downloadable: ['Available — downloads on first use', 'text-port-warning', 'bg-port-warning'],+ downloading: ['Downloading…', 'text-port-warning', 'bg-port-warning'],+ unavailable: ['Not available on this device', 'text-gray-500', 'bg-gray-500'],+ 'no-api': ['Chrome built-in AI not detected', 'text-gray-500', 'bg-gray-500'],+};+const ServiceBadge = ({ label, probe }) => {if (!probe) return null;const ok = probe.ok;@@ -94,6 +104,8 @@ export function VoiceTab() {const [apiProviders, setApiProviders] = useState([]);const [codeProviders, setCodeProviders] = useState([]);const [refreshingModels, setRefreshingModels] = useState(false);+ // On-device (Gemini Nano) availability for the fast-resolution tier-2 pill.+ const [nanoStatus, setNanoStatus] = useState(null);const toggleWidgetHidden = (next) => {writeVoiceHidden(next);@@ -153,6 +165,18 @@ export function VoiceTab() {});};+ // Probe on-device (Gemini Nano) availability for the fast-resolution pill.+ // Re-checks when the browser-LLM tier is toggled on — the user may have just+ // enabled the Chrome flag and come back to this tab.+ const fastBrowserLlm = cfg?.llm?.fastPath?.browserLlm;+ useEffect(() => {+ let live = true;+ nanoAvailability()+ .then((s) => { if (live) setNanoStatus(s); })+ .catch(() => { if (live) setNanoStatus('unavailable'); });+ return () => { live = false; };+ }, [fastBrowserLlm]);+const handleSave = async () => {setSaving(true);try {@@ -264,6 +288,10 @@ export function VoiceTab() {const codeProviderModels = selectedCodeProvider?.models || [];const codeModelMissing = !!codeModel && !codeProviderModels.includes(codeModel);+ // Fast-resolution cascade config + on-device availability pill.+ const fastPathCfg = cfg.llm.fastPath || {};+ const nanoUi = NANO_STATUS_UI[nanoStatus] || ['Checking…', 'text-gray-500', 'bg-gray-500'];+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">@@ -759,6 +787,119 @@ export function VoiceTab() {</div></label>)}++ {/* Fast-resolution cascade — lower spoken-turn latency by triaging most+ turns before the (slow) server LLM. */}+ <div className="md:col-span-2 border-t border-port-border/50 pt-4 space-y-3">+ <div className="flex items-center gap-2 text-white">+ <Zap size={15} className="text-port-accent" />+ <span className="text-sm font-medium">Fast resolution (lower latency)</span>+ </div>+ <p className="text-xs text-gray-500 -mt-1">+ Triage each turn through fast tiers before the server LLM: instant trigger commands →+ on-device browser model (Gemini Nano) → your server provider above. Common turns+ ("go to tasks", quick questions) skip the slow model entirely. Uses browser speech+ recognition, so set the STT engine to Web Speech.+ </p>++ <label className="flex items-start gap-3 cursor-pointer">+ <input+ type="checkbox"+ checked={fastPathCfg.enabled === true}+ onChange={(e) => patch('llm.fastPath.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 fast-resolution cascade</span>+ <span className="text-xs text-gray-500">Off by default — turns run entirely on the server LLM.</span>+ </div>+ </label>++ {fastPathCfg.enabled === true && (+ <div className="pl-7 space-y-3">+ {sttEngine !== 'web-speech' && (+ <p className="text-xs text-port-warning">+ Fast resolution needs browser speech recognition. Set the STT engine to+ “Web Speech API” above, or spoken turns fall back to the server.+ </p>+ )}++ <label className="flex items-start gap-3 cursor-pointer">+ <input+ type="checkbox"+ checked={fastPathCfg.triggers !== false}+ onChange={(e) => patch('llm.fastPath.triggers', 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">Tier 1 — trigger commands (instant, offline)</span>+ <span className="text-xs text-gray-500">"go to tasks", "open daily log" navigate immediately — no LLM.</span>+ </div>+ </label>++ <label className="flex items-start gap-3 cursor-pointer">+ <input+ type="checkbox"+ checked={fastPathCfg.browserLlm !== false}+ onChange={(e) => patch('llm.fastPath.browserLlm', 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">Tier 2 — on-device browser model (Gemini Nano)</span>+ <span className="text-xs text-gray-500">Answers simple/conversational turns in the browser; escalates actions to the server.</span>+ </div>+ </label>++ {fastPathCfg.browserLlm !== false && (+ <div className="pl-7 space-y-2">+ <div className="flex items-center gap-2">+ <span className={`w-2 h-2 rounded-full ${nanoUi[2]}`} />+ <span className={`text-xs ${nanoUi[1]}`}>{nanoUi[0]}</span>+ </div>+ {(nanoStatus === 'no-api' || nanoStatus === 'unavailable') && (+ <p className="text-xs text-gray-500">+ Requires Chrome/Edge with the on-device model. Enable+ <code className="mx-1 text-gray-400">chrome://flags/#prompt-api-for-gemini-nano</code>+ and+ <code className="mx-1 text-gray-400">chrome://flags/#optimization-guide-on-device-model</code>,+ then restart the browser. Turns fall back to the server model when unavailable.+ </p>+ )}+ <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">+ <Field label="Temperature" hint="0 = deterministic, higher = more varied. Default 0.7.">+ <input+ type="number"+ min="0"+ max="2"+ step="0.1"+ value={fastPathCfg.browser?.temperature ?? 0.7}+ onChange={(e) => {+ const v = parseFloat(e.target.value);+ patch('llm.fastPath.browser.temperature', Number.isFinite(v) ? Math.min(2, Math.max(0, v)) : 0.7);+ }}+ className={inputCls}+ />+ </Field>+ <Field label="Top-K" hint="Sampling breadth. Default 3.">+ <input+ type="number"+ min="1"+ max="128"+ step="1"+ value={fastPathCfg.browser?.topK ?? 3}+ onChange={(e) => {+ const v = parseInt(e.target.value, 10);+ patch('llm.fastPath.browser.topK', Number.isFinite(v) ? Math.min(128, Math.max(1, v)) : 3);+ }}+ className={inputCls}+ />+ </Field>+ </div>+ </div>+ )}+ </div>+ )}+ </div></div><div className="flex flex-wrap items-center gap-2 sm:gap-3 pt-2">diff --git a/client/src/components/voice/VoiceWidget.jsx b/client/src/components/voice/VoiceWidget.jsxindex e8d490e46b..0468015bd7 100644--- a/client/src/components/voice/VoiceWidget.jsx+++ b/client/src/components/voice/VoiceWidget.jsx@@ -7,7 +7,11 @@ import {webSpeechSupported, startWebSpeechCapture, stopWebSpeechCapture, isWebSpeechCapturing,onProactiveSpeech, captureScreenForVision, sendScreenshotResult,enableVisionCapture, disableVisionCapture, isVisionCaptureEnabled, onVisionCaptureEnded,+ speakSynthesized,} from '../../services/voiceClient';+import { resolveTurn, TIER } from '../../services/voiceFastPath';+import { warmNano } from '../../services/browserLlm';+import { getPaletteManifest } from '../../services/apiPalette';import { getVoiceConfig } from '../../services/apiVoice';import toast from '../ui/Toast';import { useVoiceUiSync, pushUiIndexAfterAction } from '../../hooks/useVoiceUiSync';@@ -93,6 +97,18 @@ export default function VoiceWidget() {const scrollRef = useRef(null);const useWebSpeech = sttEngine === 'web-speech' && webSpeechSupported;+ // Fast-resolution cascade config (trigger → on-device Nano → server). Kept in+ // refs alongside state so the routeFinal closure handed to+ // startWebSpeechCapture always reads the latest values without re-binding the+ // recognizer on every config change.+ const [fastPath, setFastPath] = useState(null);+ const fastPathRef = useRef(null);+ const personalityRef = useRef(null);+ const ttsRef = useRef({});+ const navEntriesRef = useRef([]);+ const dictationActiveRef = useRef(false);+ const lastAssistantReplyRef = useRef('');+// Keep the server's UI index fresh so the LLM knows what's on the page// and can drive it with ui_click / ui_fill / ui_select / ui_check.useVoiceUiSync(enabled);@@ -117,20 +133,53 @@ export default function VoiceWidget() {setHotkey(cfg?.hotkey || 'Space');if (cfg?.stt?.engine) setSttEngine(cfg.stt.engine);if (cfg?.stt?.language) setSttLanguage(cfg.stt.language);+ setFastPath(cfg?.llm?.fastPath || null);+ personalityRef.current = cfg?.llm?.personality || null;+ const engine = cfg?.tts?.engine;+ ttsRef.current = { engine, voice: engine ? cfg?.tts?.[engine]?.voice : undefined, rate: cfg?.tts?.rate };}).catch(() => {});// Settings → Voice writes via PUT /api/voice/config and the route broadcasts- // voice:config:changed — keep the widget's enabled/engine/hotkey in sync so- // toggling voice mode mid-session takes effect without a reload.+ // voice:config:changed — keep the widget's enabled/engine/hotkey/fastPath in+ // sync so toggling voice mode mid-session takes effect without a reload.const off = onVoiceEvent('voice:config:changed', (cfg) => {if (typeof cfg?.enabled === 'boolean') setEnabled(cfg.enabled);if (cfg?.hotkey) setHotkey(cfg.hotkey);if (cfg?.sttEngine) setSttEngine(cfg.sttEngine);if (cfg?.sttLanguage) setSttLanguage(cfg.sttLanguage);+ if ('fastPath' in (cfg || {})) setFastPath(cfg.fastPath || null);+ if (cfg?.ttsEngine) ttsRef.current = { engine: cfg.ttsEngine, voice: cfg.ttsVoice, rate: cfg.ttsRate };});return off;}, []);+ // Keep the cascade refs pointed at the latest config so the routeFinal closure+ // (bound once at capture start) always triages against current settings.+ useLayoutEffect(() => { fastPathRef.current = fastPath; }, [fastPath]);+ useLayoutEffect(() => { dictationActiveRef.current = dictationActive; }, [dictationActive]);++ // Load the palette nav manifest once the fast path is active so tier-1 trigger+ // navigation ("go to tasks") can resolve against the same routes ⌘K uses.+ useEffect(() => {+ if (!enabled || !fastPath?.enabled || !fastPath?.triggers) return;+ if (navEntriesRef.current.length) return;+ getPaletteManifest({ silent: true })+ .then((data) => { navEntriesRef.current = Array.isArray(data?.nav) ? data.nav : []; })+ .catch(() => {});+ }, [enabled, fastPath?.enabled, fastPath?.triggers]);++ // Pre-warm the on-device model when the browser-LLM tier is active so the+ // first spoken turn doesn't pay session-creation latency. No-op unless Nano+ // is already downloaded (we never kick off a download here).+ useEffect(() => {+ if (!enabled || !fastPath?.enabled || !fastPath?.browserLlm) return;+ warmNano({+ systemPrompt: 'You are a fast voice assistant.',+ temperature: fastPath?.browser?.temperature ?? 0.7,+ topK: fastPath?.browser?.topK ?? 3,+ }).catch(() => {});+ }, [enabled, fastPath?.enabled, fastPath?.browserLlm]);+useEffect(() => {if (!enabled) return;const appendUser = (text) => setHistory((h) => [...h, { role: 'user', text }].slice(-MAX_HISTORY));@@ -266,6 +315,61 @@ export default function VoiceWidget() {if (scrollRef.current) scrollRef.current.scrollTop = scrollRef.current.scrollHeight;}, [history]);+ // Track the most recent completed assistant reply so the cascade can detect a+ // destructive-confirmation follow-up ("yes"/"cancel" after a gate prompt) and+ // route it to the server instead of the on-device model.+ useEffect(() => {+ for (let i = history.length - 1; i >= 0; i--) {+ if (history[i]?.role === 'assistant') { lastAssistantReplyRef.current = history[i].text || ''; return; }+ }+ }, [history]);++ // Fast-resolution cascade executor. Triages one client transcript through+ // trigger → Nano → server and, when a fast tier owns it, executes locally+ // (navigate + speak, or speak). Returns true when handled; false means "send+ // to the server pipeline as usual". Reads config via refs so it stays stable.+ const runFastPath = useCallback(async (text) => {+ const fp = fastPathRef.current;+ if (!fp?.enabled) return false;+ let decision;+ try {+ decision = await resolveTurn(text, {+ fastPath: fp,+ personality: personalityRef.current || {},+ navEntries: navEntriesRef.current,+ dictationActive: dictationActiveRef.current,+ lastAssistantReply: lastAssistantReplyRef.current,+ });+ } catch {+ return false;+ }+ if (decision.tier === TIER.SERVER) return false;++ // A fast tier owns this turn. Stop any lingering playback, speak the reply+ // through the same queue as server TTS, and settle the stage on drain.+ const speak = (line) => {+ interrupt();+ setHistory((h) => [...h, { role: 'assistant', text: line }].slice(-MAX_HISTORY));+ setStage('speaking');+ speakSynthesized(line, ttsRef.current)+ .catch(() => {})+ .finally(() => whenPlaybackDrained().then(() => setStage((c) => (+ ACTIVE_STAGES.has(c) ? c : (isWebSpeechCapturing() ? 'listening' : 'idle')+ ))));+ };++ if (decision.tier === TIER.TRIGGER && decision.kind === 'navigate') {+ navigate(decision.path);+ speak(`Opening ${decision.label}.`);+ return true;+ }+ if (decision.tier === TIER.NANO) {+ speak(decision.reply);+ return true;+ }+ return false;+ }, [navigate]);+// 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@@ -296,6 +400,14 @@ export default function VoiceWidget() {setHistory((h) => [...h, { role: 'user', text }].slice(-MAX_HISTORY));setStage('thinking');},+ // routeFinal owns the turn: try the fast-resolution cascade first, and+ // fall through to the server pipeline when no fast tier handles it.+ // Gated on the live ref so toggling fast resolution in Settings takes+ // effect on the next utterance without restarting the recognizer.+ routeFinal: async (text) => {+ const handled = fastPathRef.current?.enabled ? await runFastPath(text) : false;+ if (!handled) sendText(text, 'voice');+ },onError: (err) => {toast.error(`Mic: ${err}`);setStage('idle');@@ -329,7 +441,7 @@ export default function VoiceWidget() {toast.error(`Mic: ${err.message}`);setStage('idle');});- }, [enabled, handsFree, useWebSpeech, sttLanguage]);+ }, [enabled, handsFree, useWebSpeech, sttLanguage, runFastPath]);const handleStop = useCallback(async () => {if (useWebSpeech) {@@ -391,14 +503,17 @@ export default function VoiceWidget() {setHistory([]);};- const handleSend = useCallback(() => {+ const handleSend = useCallback(async () => {const text = draft.trim();if (!text) return;setHistory((h) => [...h, { role: 'user', text }].slice(-MAX_HISTORY));- sendText(text);setDraft('');setStage('thinking');- }, [draft]);+ // Typed turns run through the same cascade (a typed "go to tasks" navigates+ // instantly). Falls through to the server pipeline when unhandled.+ const handled = fastPathRef.current?.enabled ? await runFastPath(text) : false;+ if (!handled) sendText(text);+ }, [draft, runFastPath]);const toggleCapture = useCallback(() => {if (isWebSpeechCapturing() || isCapturing() || isContinuous()) handleStop();diff --git a/client/src/services/README.md b/client/src/services/README.mdindex ec3033c5b7..fa6f358323 100644--- a/client/src/services/README.md+++ b/client/src/services/README.md@@ -126,6 +126,8 @@ toasts on throw). **Custom catch ⇒ `silent: true`** — otherwise toasts fire| File | Purpose ||---|---|| `voiceClient.js` | Browser-side voice capture + playback (two modes). |+| `browserLlm.js` | Client for Chrome's on-device "Gemini Nano" (Prompt API): dual-shape detection, availability enum, cached `promptNano()` with timeout. Tier 2 of the voice fast-resolution cascade. |+| `voiceFastPath.js` | Voice fast-resolution cascade: trigger nav → on-device Nano → server LLM. Decides how each spoken/typed turn is resolved. || `voiceVisibility.js` | Voice UI state manager. || `uiInteract.js` | Execute voice `ui_click` / `ui_fill` / `ui_select` against live DOM. || `domIndex.js` | DOM indexer for voice accessibility mode. |diff --git a/client/src/services/browserLlm.js b/client/src/services/browserLlm.jsnew file mode 100644index 0000000000..d0bfb5be5c--- /dev/null+++ b/client/src/services/browserLlm.js@@ -0,0 +1,182 @@+// Client for Chrome's built-in, on-device LLM ("Gemini Nano") via the Prompt+// API. Feature-detects BOTH the current global `LanguageModel` and the legacy+// `self.ai.languageModel`, normalizes availability into one enum, and exposes a+// small session-cached `promptNano()` with a timeout + bare-call fallback.+//+// This is tier 2 of the voice fast-resolution cascade (see voiceFastPath.js):+// a fast, private responder/router that runs entirely in the browser, so it+// never touches a provider the user hasn't triggered. There is deliberately no+// cloud fallback here — when Nano is unavailable the cascade falls through to+// the server LLM. Callers decide the fallback; this module only speaks to the+// on-device model.++// Availability states, normalized across both API generations. Only AVAILABLE+// means "usable right now" — DOWNLOADABLE/DOWNLOADING mean the model isn't on+// disk yet, and we never trigger the download implicitly (the user opts into+// the fast path in Settings, and Chrome downloads on first real create()).+export const NANO_AVAILABILITY = Object.freeze({+ AVAILABLE: 'available',+ DOWNLOADABLE: 'downloadable',+ DOWNLOADING: 'downloading',+ UNAVAILABLE: 'unavailable',+ NO_API: 'no-api',+});++// Detect either API generation. Prefer the newer global `LanguageModel`+// (Chrome 128+ origin trial → stable); fall back to the legacy+// `self.ai.languageModel` shape used by earlier Canary builds. Guarded so the+// module imports cleanly in a non-browser (test/SSR) context where `self` is+// undefined.+const getApi = () => {+ if (typeof self === 'undefined') return null;+ if (self.LanguageModel) return { kind: 'global', api: self.LanguageModel };+ const legacy = self.ai && self.ai.languageModel;+ return legacy ? { kind: 'legacy', api: legacy } : null;+};++export const isBrowserLlmApiPresent = () => !!getApi();++// Declared once so availability() and create() advertise the SAME I/O languages+// — Chrome warns (and newer builds refuse) when the output language is left+// unspecified.+const LANG_OPTS = Object.freeze({+ expectedInputs: [{ type: 'text', languages: ['en'] }],+ expectedOutputs: [{ type: 'text', languages: ['en'] }],+});++/**+ * @returns {Promise<'available'|'downloadable'|'downloading'|'unavailable'|'no-api'>}+ */+export const nanoAvailability = async () => {+ const found = getApi();+ if (!found) return NANO_AVAILABILITY.NO_API;+ try {+ if (found.kind === 'global') {+ // New API: LanguageModel.availability(opts) → status string. Older builds+ // reject the opts arg, so retry bare before giving up.+ let a;+ try { a = await found.api.availability(LANG_OPTS); }+ catch { a = await found.api.availability(); }+ return a || NANO_AVAILABILITY.UNAVAILABLE;+ }+ // Legacy API: capabilities().available is 'readily'|'after-download'|'no'.+ const caps = await found.api.capabilities();+ return ({+ readily: NANO_AVAILABILITY.AVAILABLE,+ 'after-download': NANO_AVAILABILITY.DOWNLOADABLE,+ no: NANO_AVAILABILITY.UNAVAILABLE,+ })[caps?.available] || NANO_AVAILABILITY.UNAVAILABLE;+ } catch (err) {+ console.warn(`⚠️ [voice] browser-LLM availability check failed: ${err.message}`);+ return NANO_AVAILABILITY.UNAVAILABLE;+ }+};++export const isNanoReady = async () => (await nanoAvailability()) === NANO_AVAILABILITY.AVAILABLE;++// ─── Session cache ─────────────────────────────────────────────────────────+// One warm session reused across turns (create() has real latency). Keyed by+// system prompt + generation params; when any change, the stale session is+// destroyed and rebuilt. A creation latch collapses concurrent ensureSession()+// calls onto a single in-flight create().+let session = null;+let sessionKey = null;+let creating = null;++const keyOf = ({ systemPrompt, temperature, topK }) => `${temperature}|${topK}|${systemPrompt || ''}`;++const createSession = ({ systemPrompt, temperature, topK }) => {+ const found = getApi();+ if (!found) throw new Error('browser LLM API not present');+ const sys = systemPrompt || '';+ if (found.kind === 'global') {+ // New global API: the system prompt is an initial 'system' message.+ return found.api.create({+ ...(sys ? { initialPrompts: [{ role: 'system', content: sys }] } : {}),+ ...LANG_OPTS,+ temperature,+ topK,+ });+ }+ // Legacy API: system prompt is a top-level string.+ return found.api.create({ systemPrompt: sys, temperature, topK });+};++export const destroyNanoSession = () => {+ try { session?.destroy?.(); } catch { /* already gone */ }+ session = null;+ sessionKey = null;+};++export const ensureNanoSession = async ({ systemPrompt = '', temperature = 0.7, topK = 3 } = {}) => {+ const key = keyOf({ systemPrompt, temperature, topK });+ if (session && sessionKey === key) return session;+ // Params/prompt changed — tear down the stale session before building a new+ // one so we don't leak the old on-device context window.+ if (session && sessionKey !== key) destroyNanoSession();+ if (creating) return creating;+ creating = Promise.resolve()+ .then(() => createSession({ systemPrompt, temperature, topK }))+ .then((s) => { session = s; sessionKey = key; return s; })+ .finally(() => { creating = null; });+ return creating;+};++// Reject after `ms` so a wedged on-device model can't stall a voice turn — the+// caller treats a timeout the same as "Nano declined" and escalates to the+// server. `onTimeout` lets the caller cancel the underlying prompt.+const withTimeout = (promise, ms, onTimeout) => {+ if (!ms) return promise;+ return new Promise((resolve, reject) => {+ const t = setTimeout(() => { onTimeout?.(); reject(new Error('browser LLM timeout')); }, ms);+ promise.then(+ (v) => { clearTimeout(t); resolve(v); },+ (e) => { clearTimeout(t); reject(e); },+ );+ });+};++/**+ * One non-streaming prompt against the on-device model. Returns the raw string+ * reply. Throws on timeout / abort / model error — the caller decides whether+ * to escalate to the server.+ *+ * @param {string} text+ * @param {object} [opts]+ * @param {string} [opts.systemPrompt]+ * @param {number} [opts.temperature=0.7]+ * @param {number} [opts.topK=3]+ * @param {number} [opts.timeoutMs=8000]+ * @param {AbortSignal} [opts.signal]+ * @returns {Promise<string>}+ */+export const promptNano = async (text, {+ systemPrompt = '',+ temperature = 0.7,+ topK = 3,+ timeoutMs = 8000,+ signal,+} = {}) => {+ const s = await ensureNanoSession({ systemPrompt, temperature, topK });+ const run = (async () => {+ // Per-request output-language hint; older builds reject the opts arg, so+ // retry bare — but never retry an abort (that would relaunch the work the+ // user just cancelled).+ try {+ return await s.prompt(text, { outputLanguage: 'en', ...(signal ? { signal } : {}) });+ } catch (err) {+ if (signal?.aborted) throw err;+ return s.prompt(text);+ }+ })();+ return withTimeout(run, timeoutMs);+};++// Pre-build the session so the first real turn doesn't pay create() latency.+// No-op (returns false) unless the model is fully downloaded — we never kick+// off a download here. Swallows errors so warming is best-effort.+export const warmNano = async (opts = {}) => {+ if ((await nanoAvailability()) !== NANO_AVAILABILITY.AVAILABLE) return false;+ await ensureNanoSession(opts).catch(() => null);+ return !!session;+};diff --git a/client/src/services/browserLlm.test.js b/client/src/services/browserLlm.test.jsnew file mode 100644index 0000000000..6b4cfcd031--- /dev/null+++ b/client/src/services/browserLlm.test.js@@ -0,0 +1,99 @@+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';+import {+ isBrowserLlmApiPresent, nanoAvailability, isNanoReady, promptNano,+ destroyNanoSession, warmNano, NANO_AVAILABILITY,+} from './browserLlm';++// jsdom exposes `self` (=== window). We stub the Prompt API on it per test.+const clearApi = () => {+ delete self.LanguageModel;+ if (self.ai) delete self.ai;+};++beforeEach(() => { destroyNanoSession(); clearApi(); });+afterEach(() => { destroyNanoSession(); clearApi(); vi.restoreAllMocks(); });++describe('detection', () => {+ it('reports no-api when neither shape is present', async () => {+ expect(isBrowserLlmApiPresent()).toBe(false);+ expect(await nanoAvailability()).toBe(NANO_AVAILABILITY.NO_API);+ expect(await isNanoReady()).toBe(false);+ });++ it('detects the modern global LanguageModel', async () => {+ self.LanguageModel = { availability: vi.fn().mockResolvedValue('available') };+ expect(isBrowserLlmApiPresent()).toBe(true);+ expect(await nanoAvailability()).toBe('available');+ expect(await isNanoReady()).toBe(true);+ });++ it('falls back to the bare availability() call on older builds', async () => {+ const availability = vi.fn()+ .mockRejectedValueOnce(new Error('opts not supported'))+ .mockResolvedValueOnce('downloadable');+ self.LanguageModel = { availability };+ expect(await nanoAvailability()).toBe('downloadable');+ expect(availability).toHaveBeenCalledTimes(2);+ });++ it('maps the legacy capabilities() shape onto the enum', async () => {+ self.ai = { languageModel: { capabilities: vi.fn().mockResolvedValue({ available: 'readily' }) } };+ expect(await nanoAvailability()).toBe('available');+ });++ it('returns unavailable when the availability probe throws', async () => {+ self.LanguageModel = { availability: vi.fn().mockRejectedValue(new Error('boom')) };+ expect(await nanoAvailability()).toBe(NANO_AVAILABILITY.UNAVAILABLE);+ });+});++describe('promptNano', () => {+ it('creates a session (global shape) and returns the reply', async () => {+ const prompt = vi.fn().mockResolvedValue('hello there');+ const create = vi.fn().mockResolvedValue({ prompt, destroy: vi.fn() });+ self.LanguageModel = { availability: vi.fn().mockResolvedValue('available'), create };+ const out = await promptNano('hi', { systemPrompt: 'be nice', temperature: 0.5, topK: 2 });+ expect(out).toBe('hello there');+ expect(create).toHaveBeenCalledOnce();+ // System prompt is passed as an initial system message on the global API.+ expect(create.mock.calls[0][0].initialPrompts[0]).toMatchObject({ role: 'system', content: 'be nice' });+ // Reuses the warm session on a second call with the same params.+ await promptNano('again', { systemPrompt: 'be nice', temperature: 0.5, topK: 2 });+ expect(create).toHaveBeenCalledOnce();+ });++ it('retries bare when the per-request options arg is rejected', async () => {+ const prompt = vi.fn()+ .mockImplementationOnce((_t, opts) => (opts ? Promise.reject(new Error('no opts')) : Promise.resolve('x')))+ .mockResolvedValue('bare-ok');+ self.LanguageModel = { availability: vi.fn().mockResolvedValue('available'), create: vi.fn().mockResolvedValue({ prompt }) };+ const out = await promptNano('hi');+ expect(out).toBe('bare-ok');+ expect(prompt).toHaveBeenCalledTimes(2);+ });++ it('rejects on timeout when the model stalls', async () => {+ const prompt = vi.fn().mockImplementation(() => new Promise(() => {})); // never resolves+ self.LanguageModel = { availability: vi.fn().mockResolvedValue('available'), create: vi.fn().mockResolvedValue({ prompt }) };+ await expect(promptNano('hi', { timeoutMs: 20 })).rejects.toThrow(/timeout/i);+ });++ it('uses the legacy top-level systemPrompt shape', async () => {+ const create = vi.fn().mockResolvedValue({ prompt: vi.fn().mockResolvedValue('ok') });+ self.ai = { languageModel: { capabilities: vi.fn().mockResolvedValue({ available: 'readily' }), create } };+ await promptNano('hi', { systemPrompt: 'persona' });+ expect(create.mock.calls[0][0]).toMatchObject({ systemPrompt: 'persona' });+ });+});++describe('warmNano', () => {+ it('no-ops (false) unless the model is fully available', async () => {+ self.LanguageModel = { availability: vi.fn().mockResolvedValue('downloadable'), create: vi.fn() };+ expect(await warmNano()).toBe(false);+ });++ it('builds a session when available', async () => {+ self.LanguageModel = { availability: vi.fn().mockResolvedValue('available'), create: vi.fn().mockResolvedValue({ prompt: vi.fn(), destroy: vi.fn() }) };+ expect(await warmNano({ systemPrompt: 'x' })).toBe(true);+ });+});diff --git a/client/src/services/voiceClient.js b/client/src/services/voiceClient.jsindex ecb86671c1..4a6528be35 100644--- a/client/src/services/voiceClient.js+++ b/client/src/services/voiceClient.js@@ -564,6 +564,37 @@ export const sendScreenshotResult = (requestId, dataUrl) => {export const playWav = (arrayBuffer) => enqueuePlay(arrayBuffer);+// Speak arbitrary text through the server's configured TTS WITHOUT running the+// LLM. Used by the fast-resolution cascade to voice trigger confirmations and+// on-device Nano replies (see voiceFastPath.js). Reuses the same playback queue+// + echo memory as server-streamed TTS, so barge-in (stopPlayback) and+// echo-suppression keep working exactly as they do for normal turns. Resolves+// once the audio is decoded and queued (not when playback finishes).+export const speakSynthesized = async (text, { engine, voice, rate, signal } = {}) => {+ const clean = (text || '').trim();+ if (!clean) return false;+ // We're starting a fresh reply — lift any sticky rejection left by a prior+ // barge-in (normally cleared by voice:transcript, which a client-side turn+ // never emits), then remember the sentence so the next inbound STT result+ // that echoes it back through the mic is suppressed.+ rejectingTts = false;+ rememberTtsSentence(clean);+ const body = { text: clean };+ if (engine) body.engine = engine;+ if (voice) body.voice = voice;+ if (typeof rate === 'number') body.rate = rate;+ const res = await fetch('/api/voice/public/synthesize', {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify(body),+ signal,+ });+ if (!res.ok) throw new Error(`synthesize failed: ${res.status}`);+ const wav = await res.arrayBuffer();+ await enqueuePlay(wav);+ return true;+};+// Resolves once every currently-queued TTS chunk has finished playing locally.// Used by continuous mode to know when to return from 'speaking' → listening.export const whenPlaybackDrained = () => playQueue.then(() => !isTtsActive());@@ -956,9 +987,13 @@ export const startWebSpeechCapture = ({ language, ...callbacks } = {}) => {return;}callbacks.onFinal?.(final);+ // Fast-resolution cascade: when the caller supplies routeFinal it OWNS+ // this turn (triage through trigger/Nano/server itself). Otherwise fall+ // back to the default — send straight to the server pipeline.// source='voice' so the server still treats this as a spoken utterance// for dictation-mode routing — the text path otherwise bypasses it.- sendText(final, 'voice');+ if (typeof callbacks.routeFinal === 'function') callbacks.routeFinal(final);+ else sendText(final, 'voice');}};diff --git a/client/src/services/voiceFastPath.js b/client/src/services/voiceFastPath.jsnew file mode 100644index 0000000000..fe4129f706--- /dev/null+++ b/client/src/services/voiceFastPath.js@@ -0,0 +1,222 @@+// Voice fast-resolution cascade. A spoken/typed turn is triaged CLIENT-SIDE+// through three tiers so common turns never wait on the (slow) server LLM:+//+// tier 1 trigger — deterministic nav/command matching (instant, offline).+// "go to tasks" → navigate, no LLM at all.+// tier 2 nano — Chrome's on-device "Gemini Nano" answers simple/chatty+// turns in the browser (fast, private). It can also reply+// ESCALATE to punt a turn it shouldn't handle.+// tier 3 server — the existing pipeline (recommend Ollama) handles every+// tool/action turn, retrieval, and anything the fast tiers+// decline or can't run.+//+// This module is the pure DECISION layer: given a transcript + context it+// returns a `{ tier, ... }` decision. The caller (VoiceWidget) executes it —+// navigate + speak for trigger, speak for nano, send-to-server for server.+// Kept side-effect-free (aside from the injected Nano call) so the routing+// rules are unit-testable.++import { promptNano, nanoAvailability, NANO_AVAILABILITY } from './browserLlm';++export const TIER = Object.freeze({ TRIGGER: 'trigger', NANO: 'nano', SERVER: 'server' });++// ─── Tier 1: trigger nav ───────────────────────────────────────────────────+// Only fire on an explicit navigation verb ("go to X", "open X") so a+// conversational turn that merely mentions a page name doesn't teleport the+// user. The remainder after the verb is matched against the palette nav+// manifest (same entries ⌘K uses), so this stays in sync with real routes.+const NAV_LEAD_IN = /^\s*(?:go\s+to|open(?:\s+up)?|take\s+me\s+to|show\s+me|navigate\s+to|switch\s+to|bring\s+up|jump\s+to|pull\s+up|let'?s\s+go\s+to)\s+(?:the\s+|my\s+|our\s+)?(.+?)\s*$/i;+const NAV_TRAILING = /\s+(?:page|tab|screen|view|section)\s*$/i;++// Normalize a label / alias / spoken target to a comparable form: lowercase,+// with every run of non-alphanumerics (hyphens, underscores, punctuation,+// spaces) collapsed to a single space. This is what lets the spoken "voice+// settings" match the hyphenated alias "voice-settings" as an EXACT hit —+// without it the phrase fell through to a loose substring match on the generic+// "settings" and navigated to the wrong page.+const normNav = (s) => String(s || '').toLowerCase().replace(/[^a-z0-9]+/g, ' ').replace(/\s+/g, ' ').trim();++// Resolve a spoken/typed phrase to a nav entry by WORD OVERLAP against each+// entry's label + aliases (keywords are deliberately ignored — too broad).+// Word-set matching is what makes "catalog settings" beat the generic+// "settings": the Catalog page shares BOTH words ("catalog" + "settings") via+// its `settings-catalog` alias, while the generic Settings page shares only+// "settings" — regardless of word order or hyphenation.+//+// Acceptance is deliberately high-precision (better to fall through to the+// server than navigate somewhere wrong):+// • an EXACT alias/label match, or+// • an entry whose names cover ALL the spoken words.+// A nav lead-in ("go to X") isn't required — a terse "database settings" also+// resolves — but WITHOUT a lead-in we additionally require ≥2 spoken words (and+// ≤5) so ordinary one-word chatter and long sentences never teleport.+export const resolveNavIntent = (text, navEntries = []) => {+ const m = String(text || '').match(NAV_LEAD_IN);+ const hadLeadIn = !!m;+ const target = (hadLeadIn ? normNav(m[1]) : normNav(text)).replace(NAV_TRAILING, '').trim();+ if (!target || !Array.isArray(navEntries)) return null;+ const targetWords = target.split(' ').filter(Boolean);+ const targetSet = new Set(targetWords);+ const targetCompact = target.replace(/\s+/g, '');+ const isExact = (n) => n === target || n.replace(/\s+/g, '') === targetCompact;++ let best = null;+ for (const e of navEntries) {+ if (!e || typeof e.path !== 'string') continue;+ const label = normNav(e.label);+ const aliases = (Array.isArray(e.aliases) ? e.aliases : []).map(normNav).filter(Boolean);+ const words = new Set();+ let exactAlias = false;+ let exactLabel = false;+ if (label) { if (isExact(label)) exactLabel = true; for (const w of label.split(' ')) if (w) words.add(w); }+ for (const a of aliases) { if (isExact(a)) exactAlias = true; for (const w of a.split(' ')) if (w) words.add(w); }+ let shared = 0;+ for (const w of targetSet) if (words.has(w)) shared += 1;+ const coversAll = shared > 0 && shared === targetSet.size;+ // An explicit alias hit outranks an incidental label hit ("settings" as an+ // alias of General beats the MeatSpace page that merely has the label+ // "Settings"). Full word-coverage beats partial; tighter entries (fewer+ // extra words) break ties.+ let score;+ if (exactAlias) score = 1000 - words.size;+ else if (exactLabel) score = 990 - words.size;+ else if (coversAll) score = 500 + shared * 10 - words.size;+ else score = shared * 100 - words.size; // partial: ranked, but gated out below+ if (score > (best?.score ?? -Infinity)) {+ best = { path: e.path, label: e.label || label, exact: exactAlias || exactLabel, coversAll, score };+ }+ }+ if (!best || !(best.exact || best.coversAll)) return null;+ if (!hadLeadIn && (targetWords.length < 2 || targetWords.length > 5)) return null;+ return { path: best.path, label: best.label };+};++// ─── Escalation gate: clear action/tool intents ─────────────────────────────+// Turns that need the server's tool pipeline (capture, dictation, UI-driving,+// personal-data retrieval, system control, timers, goals). Deliberately BROAD+// and biased toward escalation: over-escalating just forgoes a latency win+// (server still answers correctly), while under-escalating would let Nano give+// a chatty non-action reply to a turn that needed a tool.+const ACTION_INTENT = /\b(save|capture|remember|note (this|that|down)|jot|file (this|that|it)|add (a |an |the )?(note|task|reminder|event|goal|entry|item)|create (a |an |the )|make (a |an )?(note|task|list|log|entry|goal)|dictate|dictation|record (my|the) (log|journal)|log (this|that|it|today)|append|delete|remove|rename|restart|reboot|shut ?down|kill|pm2|(update|log).{0,20}\bgoal\b|set (a |an )?(timer|reminder|alarm)|remind me|what did i|when did i|have i|do i (prefer|usually|normally|like|tend)|my (goals?|tasks?|notes?|schedule|calendar|inbox|preferences|journal|log)|read (this|the page|it aloud|to me)|fill (in|out|the)|type .* (in|into)|click (the|on)|select .* from|check the|uncheck)\b/i;++export const isActionIntent = (text) => ACTION_INTENT.test(String(text || '').toLowerCase());++// Meta / capability questions ("what can you do", "what tools do you have",+// "what are my options"). The on-device Nano tier has no knowledge of the+// server's tools, so if it answered it would wrongly say "I don't have any+// tools." Route these to the server, which knows its real tool set + persona.+const CAPABILITY_QUERY = /\bwhat (?:can|do) you (?:do|help|assist|offer)\b|\bwhat (?:tools|capabilities|abilities|options|features|commands)\b|\bwhich tools\b|\byour (?:tools|capabilities|abilities)\b|\bwhat can i (?:ask|say|do|tell)\b|\bwhat are (?:my|your) (?:options|tools|capabilities|features)\b/i;++export const isCapabilityQuery = (text) => CAPABILITY_QUERY.test(String(text || '').toLowerCase());++// ─── Server-only follow-ups (confirmation / bare yes-no) ────────────────────+// A destructive-action confirmation gate lives server-side; the "yes"/"cancel"+// that answers it MUST reach the server, not Nano. Detect it two ways: the+// prior assistant line looked like the gate prompt, or the utterance is a bare+// affirmation/denial (rare as genuine chat, safe to route server-side).+const CONFIRM_PROMPT_RE = /confirm by saying|say ["']?yes["']? or ["']?cancel["']?|looks destructive/i;+const BARE_CONFIRM_RE = /^(yes|yeah|yep|yup|sure|confirm|confirmed|do it|go ahead|okay do|no|nope|cancel|nevermind|never mind)\b[.!\s]*$/i;++export const looksLikeConfirmationFollowup = (text, lastAssistantReply) =>+ CONFIRM_PROMPT_RE.test(String(lastAssistantReply || '')) || BARE_CONFIRM_RE.test(String(text || '').trim());++// ─── Tier 2: Nano routing prompt + reply hygiene ────────────────────────────+export const buildRouterSystemPrompt = (personality = {}) => {+ const name = personality?.name || 'the assistant';+ const style = personality?.speechStyle ? ` Speak in a ${personality.speechStyle} tone.` : '';+ return [+ `You are ${name}, a fast voice assistant. Your replies are spoken aloud, so keep them to one or two short plain-prose sentences — no markdown, lists, or headings.${style}`,+ 'You can ONLY chat and answer general questions. You CANNOT take actions in the app.',+ 'If the user asks you to DO something in the app — open or go to a page, save/capture/remember a note, dictate, add a task or reminder, check their personal data, control apps or services, set a timer, or run any tool — reply with EXACTLY the single word ESCALATE and nothing else.',+ "Also reply with EXACTLY ESCALATE if the request is about the user's own past, notes, preferences, goals, schedule, or files — you don't have access to those.",+ 'Otherwise answer briefly.',+ ].join(' ');+};++// Escalate when the reply leads with ESCALATE, or is a short reply that is+// essentially just the ESCALATE token (models sometimes wrap it in quotes or+// add a trailing period).+export const isEscalate = (raw) => {+ const s = String(raw || '').trim();+ if (/^["'`]*\s*escalate\b/i.test(s)) return true;+ return s.length < 40 && /\bescalate\b/i.test(s);+};++// Trim Nano's reply to something speakable: drop wrapping quotes, keep at most+// two sentences, cap length (Nano over-talks past a "1–2 sentences" prompt).+export const cleanNanoReply = (raw) => {+ let s = String(raw || '').trim();+ if (!s) return '';+ s = s.replace(/^["'“”]+|["'“”]+$/g, '').trim();+ const sentences = s.match(/[^.!?]+[.!?]+/g);+ const trimmed = sentences ? sentences.slice(0, 2).map((x) => x.trim()).join(' ') : s;+ return trimmed.slice(0, 300);+};++/**+ * Triage one turn. Returns a decision the caller executes.+ * { tier:'trigger', kind:'navigate', path, label }+ * { tier:'nano', reply }+ * { tier:'server', reason }+ *+ * @param {string} transcript+ * @param {object} ctx+ * @param {object} ctx.fastPath cfg.llm.fastPath ({ triggers, browserLlm, browser })+ * @param {object} [ctx.personality] cfg.llm.personality (name/speechStyle for Nano)+ * @param {Array} [ctx.navEntries] palette nav manifest entries+ * @param {boolean}[ctx.dictationActive] server dictation in progress → always server+ * @param {string} [ctx.lastAssistantReply] prior assistant line (confirmation detection)+ * @param {AbortSignal} [ctx.signal]+ */+export const resolveTurn = async (transcript, {+ fastPath = {},+ personality = {},+ navEntries = [],+ dictationActive = false,+ lastAssistantReply = '',+ signal,+} = {}) => {+ const text = String(transcript || '').trim();+ if (!text) return { tier: TIER.SERVER, reason: 'empty' };++ // State the server owns — never intercept these.+ if (dictationActive) return { tier: TIER.SERVER, reason: 'dictation' };+ if (looksLikeConfirmationFollowup(text, lastAssistantReply)) return { tier: TIER.SERVER, reason: 'confirm-followup' };++ // Tier 1 — deterministic trigger nav.+ if (fastPath.triggers) {+ const nav = resolveNavIntent(text, navEntries);+ if (nav) return { tier: TIER.TRIGGER, kind: 'navigate', path: nav.path, label: nav.label };+ }++ // Clear action/tool intents need the server tool pipeline — skip Nano.+ if (isActionIntent(text)) return { tier: TIER.SERVER, reason: 'action-intent' };+ // Capability/meta questions must be answered by the server (Nano doesn't know+ // the CoS tool set and would falsely claim it has none).+ if (isCapabilityQuery(text)) return { tier: TIER.SERVER, reason: 'capability-query' };++ // Tier 2 — on-device Nano for conversational turns.+ if (fastPath.browserLlm) {+ const avail = await nanoAvailability();+ if (avail !== NANO_AVAILABILITY.AVAILABLE) return { tier: TIER.SERVER, reason: `nano-${avail}` };+ const browser = fastPath.browser || {};+ let raw;+ try {+ raw = await promptNano(text, {+ systemPrompt: buildRouterSystemPrompt(personality),+ temperature: browser.temperature ?? 0.7,+ topK: browser.topK ?? 3,+ timeoutMs: 8000,+ signal,+ });+ } catch (err) {+ return { tier: TIER.SERVER, reason: `nano-error:${err.message}` };+ }+ if (isEscalate(raw)) return { tier: TIER.SERVER, reason: 'nano-escalate' };+ const reply = cleanNanoReply(raw);+ if (!reply) return { tier: TIER.SERVER, reason: 'nano-empty' };+ return { tier: TIER.NANO, reply };+ }++ return { tier: TIER.SERVER, reason: 'no-fast-tier' };+};diff --git a/client/src/services/voiceFastPath.test.js b/client/src/services/voiceFastPath.test.jsnew file mode 100644index 0000000000..5bd41fb46b--- /dev/null+++ b/client/src/services/voiceFastPath.test.js@@ -0,0 +1,245 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';++// Mock the on-device model client so the routing decision is tested in+// isolation (no real Prompt API in the test environment).+vi.mock('./browserLlm', () => ({+ promptNano: vi.fn(),+ nanoAvailability: vi.fn(),+ NANO_AVAILABILITY: {+ AVAILABLE: 'available',+ DOWNLOADABLE: 'downloadable',+ DOWNLOADING: 'downloading',+ UNAVAILABLE: 'unavailable',+ NO_API: 'no-api',+ },+}));++import { promptNano, nanoAvailability } from './browserLlm';+import {+ resolveTurn, resolveNavIntent, isActionIntent, isCapabilityQuery, looksLikeConfirmationFollowup,+ cleanNanoReply, isEscalate, buildRouterSystemPrompt, TIER,+} from './voiceFastPath';++const NAV = [+ { id: 'nav.system.tasks', path: '/tasks', label: 'Tasks', aliases: ['tasks', 'todo', 'task list'] },+ { id: 'nav.brain.daily', path: '/brain/daily-log', label: 'Daily Log', aliases: ['daily-log', 'journal'] },+ { id: 'nav.system.pipeline', path: '/pipeline', label: 'Pipeline', aliases: ['pipeline'] },+ // Real-manifest shapes that exposed the matching bugs: the specific settings+ // sub-pages (hyphenated / reversed-word-order aliases) must beat the generic+ // "settings", and a bare-label "Settings" (MeatSpace) must not win over them.+ { id: 'nav.meatspace.settings', path: '/meatspace/settings', label: 'Settings', aliases: ['meatspace-settings'] },+ { id: 'nav.settings.general', path: '/settings/general', label: 'General', aliases: ['settings', 'settings-general', 'general'] },+ { id: 'nav.settings.voice', path: '/settings/voice', label: 'Voice', aliases: ['settings-voice', 'voice', 'voice-settings'] },+ { id: 'nav.settings.catalog', path: '/settings/catalog', label: 'Catalog Types', aliases: ['settings-catalog', 'catalog-types'] },+ { id: 'nav.settings.database', path: '/settings/database', label: 'Database', aliases: ['settings-database', 'database'] },+];++describe('resolveNavIntent', () => {+ it('navigates on an explicit lead-in verb + alias', () => {+ expect(resolveNavIntent('go to tasks', NAV)).toEqual({ path: '/tasks', label: 'Tasks' });+ expect(resolveNavIntent('open the daily log', NAV)).toEqual({ path: '/brain/daily-log', label: 'Daily Log' });+ expect(resolveNavIntent('take me to the tasks page', NAV)).toEqual({ path: '/tasks', label: 'Tasks' });+ });++ it('matches on the label case-insensitively', () => {+ expect(resolveNavIntent('open Pipeline', NAV)).toEqual({ path: '/pipeline', label: 'Pipeline' });+ });++ it('returns null without a navigation lead-in (a mere mention should not teleport)', () => {+ expect(resolveNavIntent('how are my tasks going', NAV)).toBeNull();+ expect(resolveNavIntent('tasks', NAV)).toBeNull();+ });++ it('matches a hyphenated alias spoken with a space, beating the generic word it embeds', () => {+ // "voice settings" must resolve to /settings/voice (alias "voice-settings"),+ // NOT the generic "Settings" (meatspace) it happens to contain. Regression.+ expect(resolveNavIntent('open voice settings', NAV)).toEqual({ path: '/settings/voice', label: 'Voice' });+ expect(resolveNavIntent('take me to the voice settings', NAV)).toEqual({ path: '/settings/voice', label: 'Voice' });+ });++ it('word-overlaps a reversed-order alias — "catalog settings" → Catalog, not generic Settings', () => {+ // alias is "settings-catalog" (reversed word order); word overlap still wins.+ expect(resolveNavIntent('go to catalog settings', NAV)).toEqual({ path: '/settings/catalog', label: 'Catalog Types' });+ });++ it('resolves a terse "<page> settings" WITHOUT a nav lead-in', () => {+ // "database settings" (no "go to") must navigate rather than fall to the+ // server — this was the phrase that hit the tool-calling error path.+ expect(resolveNavIntent('database settings', NAV)).toEqual({ path: '/settings/database', label: 'Database' });+ });++ it('prefers the explicit "settings" alias (General) over the incidental "Settings" label (MeatSpace)', () => {+ expect(resolveNavIntent('go to settings', NAV)).toEqual({ path: '/settings/general', label: 'General' });+ });++ it('does not navigate on ordinary chatter without a lead-in', () => {+ expect(resolveNavIntent('tell me a joke', NAV)).toBeNull();+ expect(resolveNavIntent('what time is it', NAV)).toBeNull();+ expect(resolveNavIntent('good daily settings', NAV)).toBeNull(); // partial word overlap only+ });++ it('returns null when the target matches nothing', () => {+ expect(resolveNavIntent('go to the moon base', NAV)).toBeNull();+ });++ it('tolerates a missing/empty manifest', () => {+ expect(resolveNavIntent('go to tasks', [])).toBeNull();+ expect(resolveNavIntent('go to tasks', undefined)).toBeNull();+ });+});++describe('isActionIntent', () => {+ it('flags clear tool/action turns', () => {+ ['save this note', 'remind me to call mom', 'add a task called foo', 'start dictation',+ 'what did I say yesterday', 'delete that', "restart the server", "what's on my calendar"]+ .forEach((t) => expect(isActionIntent(t), t).toBe(true));+ });++ it('does not flag plain conversation / general questions', () => {+ ["what's the capital of France", 'how are you today', 'tell me a joke', "what's two plus two"]+ .forEach((t) => expect(isActionIntent(t), t).toBe(false));+ });+});++describe('isCapabilityQuery', () => {+ it('flags meta/capability questions (so the server answers, not tool-less Nano)', () => {+ ['what tools do you have', 'what are my options', 'what can you do', 'what are your capabilities', 'which tools do you have']+ .forEach((t) => expect(isCapabilityQuery(t), t).toBe(true));+ });+ it('does not flag ordinary questions', () => {+ ['what time is it', "what's the weather", 'what did you say']+ .forEach((t) => expect(isCapabilityQuery(t), t).toBe(false));+ });+});++describe('looksLikeConfirmationFollowup', () => {+ it('is true after a gate prompt', () => {+ expect(looksLikeConfirmationFollowup('do it', 'That looks destructive — confirm by saying "yes" or "cancel".')).toBe(true);+ });+ it('is true for a bare yes/no/cancel', () => {+ expect(looksLikeConfirmationFollowup('yes', '')).toBe(true);+ expect(looksLikeConfirmationFollowup('cancel', '')).toBe(true);+ });+ it('is false for a normal sentence that merely starts with yes', () => {+ expect(looksLikeConfirmationFollowup('yes I really like that idea', '')).toBe(false);+ });+});++describe('cleanNanoReply', () => {+ it('strips wrapping quotes and caps at two sentences', () => {+ expect(cleanNanoReply('"Sure thing. Here is more. And even more."')).toBe('Sure thing. Here is more.');+ });+ it('returns empty for blank input', () => {+ expect(cleanNanoReply('')).toBe('');+ expect(cleanNanoReply(null)).toBe('');+ });+});++describe('isEscalate', () => {+ it('detects the escalate token (leading, quoted, or short)', () => {+ expect(isEscalate('ESCALATE')).toBe(true);+ expect(isEscalate('"ESCALATE"')).toBe(true);+ expect(isEscalate('escalate.')).toBe(true);+ });+ it('does not treat a normal reply as escalate', () => {+ expect(isEscalate('The weather is sunny today.')).toBe(false);+ expect(isEscalate('You could escalate that issue to your manager if it keeps happening.')).toBe(false);+ });+});++describe('buildRouterSystemPrompt', () => {+ it('includes the persona name and the ESCALATE contract', () => {+ const p = buildRouterSystemPrompt({ name: 'Alfred', speechStyle: 'warm' });+ expect(p).toContain('Alfred');+ expect(p).toContain('ESCALATE');+ expect(p).toContain('warm');+ });+});++describe('resolveTurn', () => {+ const base = {+ fastPath: { enabled: true, triggers: true, browserLlm: true, browser: { temperature: 0.7, topK: 3 } },+ personality: { name: 'Alfred' },+ navEntries: NAV,+ };++ beforeEach(() => {+ vi.clearAllMocks();+ nanoAvailability.mockResolvedValue('available');+ });++ it('routes an empty transcript to the server', async () => {+ expect(await resolveTurn(' ', base)).toMatchObject({ tier: TIER.SERVER });+ });++ it('always defers to the server while dictation is active', async () => {+ const d = await resolveTurn('go to tasks', { ...base, dictationActive: true });+ expect(d).toMatchObject({ tier: TIER.SERVER, reason: 'dictation' });+ expect(promptNano).not.toHaveBeenCalled();+ });++ it('defers a confirmation follow-up to the server', async () => {+ const d = await resolveTurn('yes', { ...base, lastAssistantReply: 'confirm by saying yes or cancel' });+ expect(d).toMatchObject({ tier: TIER.SERVER, reason: 'confirm-followup' });+ });++ it('resolves nav via tier 1 without touching Nano', async () => {+ const d = await resolveTurn('go to tasks', base);+ expect(d).toEqual({ tier: TIER.TRIGGER, kind: 'navigate', path: '/tasks', label: 'Tasks' });+ expect(promptNano).not.toHaveBeenCalled();+ });++ it('escalates a clear action intent to the server without touching Nano', async () => {+ const d = await resolveTurn('save this to my brain inbox', base);+ expect(d).toMatchObject({ tier: TIER.SERVER, reason: 'action-intent' });+ expect(promptNano).not.toHaveBeenCalled();+ });++ it('escalates capability/meta questions to the server (Nano would falsely claim no tools)', async () => {+ const d = await resolveTurn('what tools do you have', base);+ expect(d).toMatchObject({ tier: TIER.SERVER, reason: 'capability-query' });+ expect(promptNano).not.toHaveBeenCalled();+ });++ it('answers a conversational turn via Nano (tier 2)', async () => {+ promptNano.mockResolvedValue('It is sunny and warm today.');+ const d = await resolveTurn('what is the weather like', base);+ expect(d).toEqual({ tier: TIER.NANO, reply: 'It is sunny and warm today.' });+ expect(promptNano).toHaveBeenCalledOnce();+ });++ it('escalates to the server when Nano replies ESCALATE', async () => {+ promptNano.mockResolvedValue('ESCALATE');+ const d = await resolveTurn('what is on my calendar tomorrow', base);+ // (this particular phrase also trips the action regex, but prove the Nano+ // escalate path too with a phrase that does not)+ expect(d).toMatchObject({ tier: TIER.SERVER });+ });++ it('escalates when Nano is unavailable', async () => {+ nanoAvailability.mockResolvedValue('no-api');+ const d = await resolveTurn('tell me something interesting', base);+ expect(d).toMatchObject({ tier: TIER.SERVER, reason: 'nano-no-api' });+ expect(promptNano).not.toHaveBeenCalled();+ });++ it('escalates when Nano throws / times out', async () => {+ promptNano.mockRejectedValue(new Error('browser LLM timeout'));+ const d = await resolveTurn('tell me a joke', base);+ expect(d.tier).toBe(TIER.SERVER);+ expect(d.reason).toMatch(/nano-error/);+ });++ it('skips tier 1 when triggers are disabled', async () => {+ promptNano.mockResolvedValue('Sure.');+ const d = await resolveTurn('go to the pipeline', { ...base, fastPath: { ...base.fastPath, triggers: false } });+ // No nav match → falls to Nano (this phrase is not an action intent).+ expect(d.tier).toBe(TIER.NANO);+ });++ it('goes straight to the server when the browser tier is disabled and no trigger matches', async () => {+ const d = await resolveTurn('tell me a joke', { ...base, fastPath: { ...base.fastPath, browserLlm: false } });+ expect(d).toMatchObject({ tier: TIER.SERVER, reason: 'no-fast-tier' });+ expect(promptNano).not.toHaveBeenCalled();+ });+});diff --git a/docs/features/voice.md b/docs/features/voice.mdindex 7e798fa1d0..e0fa54fa88 100644--- a/docs/features/voice.md+++ b/docs/features/voice.md@@ -64,6 +64,11 @@ All options live in `data/settings.json` under `voice` (Settings UI patches this| `tts.piper.voicePath` | `~/.portos/voice/voices/<voice>.onnx` | ONNX file location || `llm.model` | `auto` | `auto` picks first loaded LM Studio model || `llm.systemPrompt` | (concise voice prompt) | Edit to change personality |+| `llm.fastPath.enabled` | `false` | Fast-resolution cascade (see below). Off = every turn runs on the server LLM. |+| `llm.fastPath.triggers` | `true` | Tier 1: resolve navigation commands ("go to tasks") in the browser, no LLM. |+| `llm.fastPath.browserLlm` | `true` | Tier 2: answer simple/conversational turns with Chrome's on-device Gemini Nano. |+| `llm.fastPath.browser.temperature` | `0.7` | Nano sampling temperature (0–2). |+| `llm.fastPath.browser.topK` | `3` | Nano sampling top-K (1–128). |## Using voice mode@@ -76,6 +81,24 @@ Either mode: start speaking while the assistant is replying to interrupt it (barWith `stt.engine = 'web-speech'` the browser's SpeechRecognition handles STT entirely client-side; PortOS sends the final transcript as `voice:text` instead of shipping audio, which skips whisper.cpp and avoids a 250–800 ms server-side round-trip.+## Fast-resolution cascade (lower latency)++The server LLM is the slowest part of a turn — a local model with tools attached can take several seconds. When `llm.fastPath.enabled` is on, the **client** triages each turn through faster tiers first and only falls through to the server LLM when it has to:++1. **Trigger** (`fastPath.triggers`) — deterministic, offline. A navigation command ("go to tasks", "open the daily log") is matched against the ⌘K palette nav manifest and navigates immediately. No LLM.+2. **Browser LLM** (`fastPath.browserLlm`) — Chrome's on-device **Gemini Nano** (the Prompt API: `window.LanguageModel` / legacy `self.ai.languageModel`) answers simple/conversational turns entirely in the browser (fast, private, offline). Nano is also asked to reply `ESCALATE` for anything that needs a real action.+3. **Server** — the configured provider/model (recommend **Ollama** with a small model) via the existing pipeline. Handles every tool/action turn, personal-data retrieval, dictation, confirmations, and anything the fast tiers decline or can't run.++Notes:++- The cascade only applies to **client-produced transcripts** — Web Speech STT or typed input. Whisper / hands-free audio turns have no client transcript to triage, so they stay fully server-driven. Set `stt.engine = 'web-speech'` to get the benefit.+- Trigger/Nano replies are spoken through the server's configured TTS (`POST /api/voice/public/synthesize`), reusing the normal playback queue and echo-suppression, so barge-in keeps working.+- Fast-tier turns are handled without a server round-trip, so they are **not** added to the server-side conversation history; a later server turn won't have that chit-chat in its context. Action turns (which always hit the server) are unaffected.+- Nano availability is surfaced in **Settings → Voice → Fast resolution**. When it isn't downloaded/enabled (`chrome://flags/#prompt-api-for-gemini-nano` + `#optimization-guide-on-device-model`), tier 2 transparently falls through to the server.+- Nothing here runs a model the user hasn't triggered — Nano only executes on a real spoken/typed turn, consistent with the no-cold-bootstrap AI policy.++Client modules: `client/src/services/browserLlm.js` (Nano client), `client/src/services/voiceFastPath.js` (the routing decision), wired into `VoiceWidget.jsx`.+## Architecture```diff --git a/server/lib/localLlmCatalog.js b/server/lib/localLlmCatalog.jsindex a90c3e102c..3452107f0a 100644--- a/server/lib/localLlmCatalog.js+++ b/server/lib/localLlmCatalog.js@@ -81,6 +81,33 @@ export const LOCAL_LLM_CATALOG = [ollama: 'qwen2.5',lmstudio: 'lmstudio-community/Qwen2.5-7B-Instruct-GGUF'},+ {+ key: 'qwen2.5-3b',+ name: 'Qwen2.5 3B',+ category: 'lightweight',+ params: '3B',+ size: '2.0 GB',+ family: 'qwen',+ description: 'Compact Qwen2.5 instruct model with solid tool use and no "thinking" delay — a fast, low-memory tool-calling brain for the voice agent.',+ capabilities: ['chat', 'tools', 'multilingual'],+ // hf.co/…-Instruct id (like the other 2507/instruct cards) so the model id+ // reported by the backend carries the "instruct" token the voice+ // tool-capability detector keys on — a bare `qwen2.5:3b` tag would not.+ ollama: 'hf.co/lmstudio-community/Qwen2.5-3B-Instruct-GGUF:Q4_K_M',+ lmstudio: 'lmstudio-community/Qwen2.5-3B-Instruct-GGUF'+ },+ {+ key: 'hermes-3-llama-3.1-8b',+ name: 'Hermes 3 8B',+ category: 'chat',+ params: '8B',+ size: '4.9 GB',+ family: 'hermes',+ description: 'NousResearch Hermes 3 (Llama 3.1 8B) — tuned for reliable function-calling and structured tool use, with no "thinking" delay. A robust pick for the voice agent\'s tool turns.',+ capabilities: ['chat', 'tools'],+ ollama: 'hermes3',+ lmstudio: 'NousResearch/Hermes-3-Llama-3.1-8B-GGUF'+ },{key: 'qwen3.6-35b-a3b',name: 'Qwen3.6 35B-A3B',diff --git a/server/lib/localLlmCatalog.test.js b/server/lib/localLlmCatalog.test.jsindex dac16b71e2..052b4d40e3 100644--- a/server/lib/localLlmCatalog.test.js+++ b/server/lib/localLlmCatalog.test.js@@ -49,6 +49,26 @@ describe('localLlmCatalog', () => {expect(getCatalog('nope')).toEqual([]);});+ it('ships the small tool-calling models recommended for the voice fast-path tier-3', () => {+ const ollama = getCatalog('ollama');+ const lms = getCatalog('lmstudio');+ const hermesO = ollama.find((m) => m.key === 'hermes-3-llama-3.1-8b');+ const qwen3bO = ollama.find((m) => m.key === 'qwen2.5-3b');+ // Present on both backends…+ expect(hermesO?.id).toBe('hermes3');+ expect(lms.find((m) => m.key === 'hermes-3-llama-3.1-8b')?.id).toBe('NousResearch/Hermes-3-Llama-3.1-8B-GGUF');+ expect(qwen3bO?.id).toBe('hf.co/lmstudio-community/Qwen2.5-3B-Instruct-GGUF:Q4_K_M');+ expect(lms.find((m) => m.key === 'qwen2.5-3b')?.id).toBe('lmstudio-community/Qwen2.5-3B-Instruct-GGUF');+ // …and both advertise tool use (the reason they're recommended here).+ expect(hermesO.capabilities).toContain('tools');+ expect(qwen3bO.capabilities).toContain('tools');+ });++ it('keeps catalog keys unique', () => {+ const keys = LOCAL_LLM_CATALOG.map((e) => e.key);+ expect(new Set(keys).size).toBe(keys.length);+ });+it('surfaces a documented context window as contextLength, null otherwise', () => {const ollama = getCatalog('ollama');// mistral-large's description documents a 128K window.diff --git a/server/routes/voice.js b/server/routes/voice.jsindex f080fd7f63..849ee60a48 100644--- a/server/routes/voice.js+++ b/server/routes/voice.js@@ -97,6 +97,18 @@ const voiceConfigPatchSchema = z.object({end: z.string().regex(HHMM_RE).optional(),}).partial().optional(),}).partial().optional(),+ // Fast-resolution cascade (client-side tiers before the server LLM). The+ // browser tier's temperature/topK are bounded to the Prompt API's accepted+ // ranges (topK is a small integer; temperature 0–2).+ fastPath: z.object({+ enabled: z.boolean().optional(),+ triggers: z.boolean().optional(),+ browserLlm: z.boolean().optional(),+ browser: z.object({+ temperature: z.number().min(0).max(2).optional(),+ topK: z.number().int().min(1).max(128).optional(),+ }).partial().optional(),+ }).partial().optional(),}).partial().optional(),vad: z.object({endOfSpeechMs: z.number().int().min(100).max(5000).optional(),@@ -128,7 +140,12 @@ router.put('/config', asyncHandler(async (req, res) => {sttEngine: next.stt?.engine,sttLanguage: next.stt?.language,ttsEngine: next.tts?.engine,+ ttsVoice: next.tts?.[next.tts?.engine]?.voice,+ ttsRate: next.tts?.rate,hotkey: next.hotkey,+ // Fast-resolution cascade — the widget routes turns through client-side+ // tiers when enabled, so it needs the fresh flags without a page reload.+ fastPath: next.llm?.fastPath || null,});res.json({ config: next, reconciliation });}));diff --git a/server/routes/voice.test.js b/server/routes/voice.test.jsindex 96e5d3b74d..5a81e13a9b 100644--- a/server/routes/voice.test.js+++ b/server/routes/voice.test.js@@ -135,6 +135,24 @@ describe('Voice Routes', () => {expect(health.invalidateHealthCache).toHaveBeenCalled();});+ it('accepts a valid llm.fastPath patch (fast-resolution cascade)', async () => {+ config.updateVoiceConfig.mockResolvedValue({ ...DEFAULT_CFG });+ bootstrap.reconcile.mockResolvedValue({ skipped: true });+ const patch = { llm: { fastPath: { enabled: true, triggers: true, browserLlm: true, browser: { temperature: 0.5, topK: 4 } } } };+ const res = await request(buildApp()).put('/api/voice/config').send(patch);+ expect(res.status).toBe(200);+ expect(config.updateVoiceConfig).toHaveBeenCalledWith(patch);+ });++ it('rejects out-of-range fastPath.browser params', async () => {+ const res = await request(buildApp())+ .put('/api/voice/config')+ .send({ llm: { fastPath: { browser: { temperature: 9 } } } });+ expect(res.status).toBe(400);+ expect(res.body.code).toBe('VALIDATION_ERROR');+ expect(config.updateVoiceConfig).not.toHaveBeenCalled();+ });+it('reports reconcile failures without 500-ing the route', async () => {config.updateVoiceConfig.mockResolvedValue({ ...DEFAULT_CFG, enabled: true });bootstrap.reconcile.mockRejectedValue(new Error('whisper-server not on PATH'));diff --git a/server/services/voice/config.js b/server/services/voice/config.jsindex 08d83428f8..5cf28d0f7c 100644--- a/server/services/voice/config.js+++ b/server/services/voice/config.js@@ -107,6 +107,29 @@ export const VOICE_DEFAULTS = Object.freeze({end: '07:00',},},+ // Fast-resolution cascade — front-tier fast paths the CLIENT tries before+ // the (slow) server LLM above, to cut spoken-turn latency:+ // tier 1 triggers — deterministic client-side nav/command matching+ // (instant, offline; e.g. "go to tasks").+ // tier 2 browserLlm — on-device Chrome built-in "Gemini Nano" for+ // simple/conversational turns (fast, private).+ // tier 3 server — the provider/model above (recommend Ollama) via+ // the existing pipeline, used for tool/action turns+ // and whenever the fast tiers decline/are absent.+ // OFF by default: existing installs keep the all-server behavior until the+ // user opts in under Settings → Voice. Tiers 1–2 run entirely in the+ // browser and never touch a provider the user hasn't triggered, so this is+ // consistent with the no-cold-bootstrap AI policy (Nano only runs on a real+ // spoken/typed turn). `browser` holds the Nano generation params.+ fastPath: {+ enabled: false,+ triggers: true,+ browserLlm: true,+ browser: {+ temperature: 0.7,+ topK: 3,+ },+ },},vad: { endOfSpeechMs: 700, minUtteranceMs: 250 },diff --git a/server/services/voice/llm.js b/server/services/voice/llm.jsindex a715c13a06..1c3d4c6556 100644--- a/server/services/voice/llm.js+++ b/server/services/voice/llm.js@@ -69,6 +69,16 @@ export const TOOL_CAPABLE_PATTERNS = [/qwen3(\.\d+)?-?\d+b-2507/, // Qwen3 / 3.5 / 3.6 non-thinking dated variants/qwen3\.5/, // Qwen3.5 family (e.g., qwen3.5-9b)/qwen3\.6/, // Qwen3.6 family+ // Bare Ollama registry tags carry no "instruct" token (`qwen2.5:latest`,+ // `qwen3:30b`, `llama3.1|3.2|3.3:<tag>`) so the *-instruct patterns above miss+ // them — but Ollama's default builds for these tool-capable families ARE+ // instruct-tuned. Match them as whole tokens (anchored on start / `/` / `:`)+ // so vision & base variants (`qwen2.5vl`, `llama3.2-vision`) don't+ // false-positive. The `-` branch also re-covers the LM Studio ids already+ // matched above (harmless overlap).+ /(?:^|[\/:])qwen2\.5(?:[:-]|$)/,+ /(?:^|[\/:])qwen3(?:[:-]|$)/,+ /(?:^|[\/:])llama3\.[1-9](?::|$)/,/hermes-?3/,/mistral-small/,/mistral.*instruct-v0\.[3-9]/,diff --git a/server/services/voice/llm.test.js b/server/services/voice/llm.test.jsindex 447c526c2a..3b2f81a3e3 100644--- a/server/services/voice/llm.test.js+++ b/server/services/voice/llm.test.js@@ -111,6 +111,15 @@ describe('isToolCapable', () => {'qwen/qwen3.5-9b','qwen/qwen3.6-35b-a3b','NousResearch/Hermes-3-Llama-3.1-8B',+ 'hermes3', // bare Ollama registry tag for the Hermes 3 catalog card+ 'lmstudio-community/Qwen2.5-3B-Instruct-GGUF', // Qwen2.5 3B catalog card+ // Bare Ollama registry tags (no "instruct" token) for tool-capable families.+ 'qwen2.5:latest',+ 'qwen2.5',+ 'qwen3:30b',+ 'llama3.1:8b',+ 'llama3.2:latest',+ 'llama3.3:70b','mistralai/Mistral-Small-24B-Instruct','mistralai/devstral-small-2-2512','mistralai/ministral-3-14b-reasoning',@@ -127,6 +136,10 @@ describe('isToolCapable', () => {'gemma-3-270m-it','l3.3-70b-euryale-v2.3-i1','text-embedding-nomic-embed-text-v1.5',+ // Vision variants of the bare-tag families must NOT match the broadened+ // Ollama patterns (their catalog entries carry no `tools` capability).+ 'qwen2.5vl:32b',+ 'llama3.2-vision',]) {expect(isToolCapable(id), id).toBe(false);}