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
address review (claude): harden fast-path model selection + audio
Adam Eivya36b8d749a7d
diff --git a/client/src/components/voice/VoiceWidget.jsx b/client/src/components/voice/VoiceWidget.jsxindex 0468015bd7..e1f1b39bce 100644--- a/client/src/components/voice/VoiceWidget.jsx+++ b/client/src/components/voice/VoiceWidget.jsx@@ -9,7 +9,7 @@ import {enableVisionCapture, disableVisionCapture, isVisionCaptureEnabled, onVisionCaptureEnded,speakSynthesized,} from '../../services/voiceClient';-import { resolveTurn, TIER } from '../../services/voiceFastPath';+import { resolveTurn, buildRouterSystemPrompt, TIER } from '../../services/voiceFastPath';import { warmNano } from '../../services/browserLlm';import { getPaletteManifest } from '../../services/apiPalette';import { getVoiceConfig } from '../../services/apiVoice';@@ -158,23 +158,37 @@ export default function VoiceWidget() {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.+ // Load the palette nav manifest so tier-1 trigger navigation ("go to tasks")+ // can resolve against the same routes ⌘K uses. Memoized + self-healing: a+ // failed fetch clears the in-flight promise so the next turn retries, instead+ // of permanently disabling tier-1 nav for the session.+ const navFetchRef = useRef(null);+ const ensureNavEntries = useCallback(async () => {+ if (navEntriesRef.current.length) return;+ if (!navFetchRef.current) {+ navFetchRef.current = getPaletteManifest({ silent: true })+ .then((data) => { navEntriesRef.current = Array.isArray(data?.nav) ? data.nav : []; })+ .catch(() => { navFetchRef.current = null; }); // allow retry on the next turn+ }+ await navFetchRef.current;+ }, []);++ // Prefetch the manifest when the trigger tier is active so the first "go to X"+ // doesn't pay the fetch (falls back to the lazy retry in runFastPath on failure).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]);+ ensureNavEntries();+ }, [enabled, fastPath?.enabled, fastPath?.triggers, ensureNavEntries]);// 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).+ // first spoken turn doesn't pay session-creation latency. Use the SAME router+ // system prompt real turns use, so the warmed session isn't torn down and+ // rebuilt on the first turn (the session cache is keyed by the prompt). 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.',+ systemPrompt: buildRouterSystemPrompt(personalityRef.current || {}),temperature: fastPath?.browser?.temperature ?? 0.7,topK: fastPath?.browser?.topK ?? 3,}).catch(() => {});@@ -331,6 +345,9 @@ export default function VoiceWidget() {const runFastPath = useCallback(async (text) => {const fp = fastPathRef.current;if (!fp?.enabled) return false;+ // Ensure the nav manifest is loaded (retries if an earlier fetch failed) so+ // tier-1 trigger nav works even when the prefetch didn't land.+ if (fp.triggers) await ensureNavEntries();let decision;try {decision = await resolveTurn(text, {@@ -368,7 +385,7 @@ export default function VoiceWidget() {return true;}return false;- }, [navigate]);+ }, [navigate, ensureNavEntries]);// Proactive CoS speech — the server pushes a `voice:speak` event when the// assistant initiates a line (alerts, reminders, briefings). Audio playsdiff --git a/client/src/services/browserLlm.js b/client/src/services/browserLlm.jsindex d0bfb5be5c..9a83cc391a 100644--- a/client/src/services/browserLlm.js+++ b/client/src/services/browserLlm.js@@ -158,18 +158,36 @@ export const promptNano = async (text, {signal,} = {}) => {const s = await ensureNanoSession({ systemPrompt, temperature, topK });+ // A Prompt API session is single-in-flight: a second prompt() while one is+ // still running rejects. So a timed-out (or aborted) prompt must actually be+ // cancelled AND the session torn down — otherwise the next turn reuses a+ // wedged session and every subsequent turn rejects, silently killing the fast+ // tier. We drive cancellation through our own controller (chained to the+ // caller's signal) and destroy the session on ANY failure so the next call+ // rebuilds clean.+ const controller = new AbortController();+ if (signal) {+ if (signal.aborted) controller.abort();+ else signal.addEventListener('abort', () => controller.abort(), { once: true });+ }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).+ // retry bare — but never retry an abort (that would relaunch cancelled work).try {- return await s.prompt(text, { outputLanguage: 'en', ...(signal ? { signal } : {}) });+ return await s.prompt(text, { outputLanguage: 'en', signal: controller.signal });} catch (err) {- if (signal?.aborted) throw err;+ if (controller.signal.aborted) throw err;return s.prompt(text);}})();- return withTimeout(run, timeoutMs);+ try {+ return await withTimeout(run, timeoutMs, () => controller.abort());+ } catch (err) {+ // Timeout / abort / model error — the cached session may be mid-flight or+ // wedged; drop it so the next turn starts from a fresh session.+ destroyNanoSession();+ throw err;+ }};// Pre-build the session so the first real turn doesn't pay create() latency.diff --git a/client/src/services/browserLlm.test.js b/client/src/services/browserLlm.test.jsindex 6b4cfcd031..6d864fa870 100644--- a/client/src/services/browserLlm.test.js+++ b/client/src/services/browserLlm.test.js@@ -78,6 +78,17 @@ describe('promptNano', () => {await expect(promptNano('hi', { timeoutMs: 20 })).rejects.toThrow(/timeout/i);});+ it('tears down the (single-in-flight) session after a timeout so the next turn rebuilds', async () => {+ const create = vi.fn()+ .mockResolvedValueOnce({ prompt: vi.fn().mockImplementation(() => new Promise(() => {})), destroy: vi.fn() }) // stalls → timeout+ .mockResolvedValueOnce({ prompt: vi.fn().mockResolvedValue('ok'), destroy: vi.fn() });+ self.LanguageModel = { availability: vi.fn().mockResolvedValue('available'), create };+ await expect(promptNano('hi', { timeoutMs: 20 })).rejects.toThrow(/timeout/i);+ // A wedged session would make this reject too; instead it builds a fresh one.+ await expect(promptNano('again', { timeoutMs: 500 })).resolves.toBe('ok');+ expect(create).toHaveBeenCalledTimes(2);+ });+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 } };diff --git a/client/src/services/voiceClient.js b/client/src/services/voiceClient.jsindex 4a6528be35..743b1e063f 100644--- a/client/src/services/voiceClient.js+++ b/client/src/services/voiceClient.js@@ -21,6 +21,11 @@ let ttsCooldownUntil = 0;// turn. While raised, incoming voice:tts:audio is dropped — prevents// in-flight chunks from the old turn overlaying the new turn's audio.let rejectingTts = false;+// Generation counter for speakSynthesized (fast-path trigger/Nano replies).+// Bumped on every new synthesized reply AND on stopPlayback, so a reply whose+// TTS fetch is still in flight when a newer turn (or a barge-in) supersedes it+// is dropped instead of playing over/after the newer audio.+let synthGen = 0;const pickMime = () => {const candidates = ['audio/webm;codecs=opus', 'audio/webm', 'audio/ogg;codecs=opus', 'audio/mp4'];@@ -50,6 +55,8 @@ const stopPlayback = () => {// Any chunks still in-flight from the cancelled turn must not be played —// they'll arrive asynchronously after we've torn down local playback.rejectingTts = true;+ // Supersede any fast-path synthesized reply whose fetch is still in flight.+ synthGen += 1;};// whisper.cpp only accepts 16-bit PCM WAV — it has no built-in audio decoder.@@ -573,6 +580,9 @@ export const playWav = (arrayBuffer) => enqueuePlay(arrayBuffer);export const speakSynthesized = async (text, { engine, voice, rate, signal } = {}) => {const clean = (text || '').trim();if (!clean) return false;+ // Claim this generation; a newer reply or a stopPlayback/barge-in bumps+ // synthGen and supersedes us (checked after the fetch).+ const gen = ++synthGen;// 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@@ -591,6 +601,9 @@ export const speakSynthesized = async (text, { engine, voice, rate, signal } = {});if (!res.ok) throw new Error(`synthesize failed: ${res.status}`);const wav = await res.arrayBuffer();+ // Superseded while the synth was in flight — drop this stale audio rather than+ // playing it over/after the newer turn's reply.+ if (gen !== synthGen) return false;await enqueuePlay(wav);return true;};diff --git a/client/src/services/voiceFastPath.js b/client/src/services/voiceFastPath.jsindex fe4129f706..f94489bb2b 100644--- a/client/src/services/voiceFastPath.js+++ b/client/src/services/voiceFastPath.js@@ -86,7 +86,13 @@ export const resolveNavIntent = (text, navEntries = []) => {best = { path: e.path, label: e.label || label, exact: exactAlias || exactLabel, coversAll, score };}}- if (!best || !(best.exact || best.coversAll)) return null;+ // A single-word target is accepted ONLY on an exact alias/label match. A bare+ // common word ("log", "settings") is `coversAll` for every page that embeds+ // it, and the tie-break would silently pick one — so for one word, require an+ // exact hit and otherwise fall through to the server. Multi-word phrases may+ // resolve via full word-coverage.+ const accept = !!best && (best.exact || (best.coversAll && targetWords.length >= 2));+ if (!accept) return null;if (!hadLeadIn && (targetWords.length < 2 || targetWords.length > 5)) return null;return { path: best.path, label: best.label };};diff --git a/client/src/services/voiceFastPath.test.js b/client/src/services/voiceFastPath.test.jsindex 5bd41fb46b..6e03de8acf 100644--- a/client/src/services/voiceFastPath.test.js+++ b/client/src/services/voiceFastPath.test.js@@ -72,6 +72,12 @@ describe('resolveNavIntent', () => {expect(resolveNavIntent('go to settings', NAV)).toEqual({ path: '/settings/general', label: 'General' });});+ it('does not resolve a bare common word to a page that merely embeds it', () => {+ // "log" is not an exact alias of any entry (Daily Log's aliases are+ // daily-log/journal); a single common word must not resolve via coversAll.+ expect(resolveNavIntent('go to log', NAV)).toBeNull();+ });+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();diff --git a/server/services/voice/llm.js b/server/services/voice/llm.jsindex 1c3d4c6556..82672f0098 100644--- a/server/services/voice/llm.js+++ b/server/services/voice/llm.js@@ -72,12 +72,15 @@ export const TOOL_CAPABLE_PATTERNS = [// 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(?:[:-]|$)/,+ // instruct-tuned. Match the family only as a WHOLE tag token — anchored on+ // start / `/` / `:`, and terminated only by `:` (a tag) or end-of-string.+ // Deliberately NOT by `-`: a trailing `-` is what turns these families into+ // NON-chat variants (`qwen3-embedding`, `qwen3-reranker`, `qwen3-vl`,+ // `qwen2.5-omni`, `llama3.2-vision`) that can't do tool-calling. The+ // legitimate hyphenated instruct builds (`Qwen2.5-7B-Instruct-GGUF`) are+ // already covered by the `*instruct` patterns above.+ /(?:^|[\/:])qwen2\.5(?::|$)/,+ /(?:^|[\/:])qwen3(?::|$)/,/(?:^|[\/:])llama3\.[1-9](?::|$)/,/hermes-?3/,/mistral-small/,@@ -121,8 +124,11 @@ export const isReasoningModel = (id) => {export const isToolCapable = (id) => {const n = String(id).toLowerCase();- if (TOOL_CAPABLE_PATTERNS.some((re) => re.test(n))) return true;- return false;+ // Utility models (embeddings / rerankers) can't chat or call tools — never let+ // a broadened family pattern (e.g. bare `qwen3…`) select one as the voice+ // brain, which would hard-fail every tool turn. Mirrors sizeRank's guard.+ if (/embed|rerank/.test(n)) return false;+ return TOOL_CAPABLE_PATTERNS.some((re) => re.test(n));};const isToolIncompatible = (id) => {diff --git a/server/services/voice/llm.test.js b/server/services/voice/llm.test.jsindex 3b2f81a3e3..e8e7bdd423 100644--- a/server/services/voice/llm.test.js+++ b/server/services/voice/llm.test.js@@ -136,10 +136,15 @@ 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).+ // Vision / embedding / reranker variants of the bare-tag families must NOT+ // match the broadened Ollama patterns — they can't chat or call tools, and+ // auto-selecting one as the voice brain would hard-fail every tool turn.'qwen2.5vl:32b','llama3.2-vision',+ 'qwen3-embedding',+ 'dengcao/qwen3-embedding-8b:q4_k_m',+ 'qwen3-reranker',+ 'qwen2.5-omni',]) {expect(isToolCapable(id), id).toBe(false);}