Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

fix(voice): Chief-of-Staff silent when LM Studio `auto` picked a non-tool-calling model

Adam Eivy3780cef8c3b2
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 7c4484c730..93f0c1b2c3 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -38,6 +38,13 @@
## Fixed
+- **Voice agent silent after every question when `model: 'auto'`** — the Chief-of-Staff transcribed the user's speech but never replied (server log showed `ttft=—ms · tts=0ms (0 sentences)` with no error). Two root causes: (1) `'auto'` resolved to whichever LM Studio model had the smallest `B` suffix in its id — on IBM Granite 3.x installs that is Granite itself, which does not emit OpenAI-format `delta.tool_calls`; it emits its own `<tool_call>[{...}]</tool_call>` (and sometimes `<tool_request>[{...}]`, often unclosed) inline in `delta.content`. With the full 19-tool schema attached, Granite silently bailed with a single empty SSE chunk and closed the stream. (2) The pipeline only logged a turn-summary at the END, so a 60s reasoning loop looked like the server was dead. Fixes:
+ - `resolveModel` now prefers a curated tool-use allowlist (Qwen2.5-Instruct, Hermes-3, Mistral-Small, Devstral, Ministral, Llama-3.1+-Instruct, Command-R, Functionary) over size-ranked picks when `tools.enabled`, and steps past known-incompatible families (Granite, tiny non-instruct Gemmas).
+ - `extractInlineToolCalls` parses both `<tool_call>` and `<tool_request>` spellings in either closed or unclosed form and hoists them into structured `toolCalls`, with a balanced-bracket JSON scanner that survives `]` characters inside string arguments. A matching streaming stripper withholds those fragments from `onDelta` so raw JSON never reaches TTS.
+ - `ensureToolCapableModel` auto-installs a default tool-capable model the first time voice reconciles with no compatible model present — shells out to `lms get -y lmstudio-community/Qwen2.5-7B-Instruct-GGUF` (overridable via `PORTOS_VOICE_DEFAULT_TOOL_MODEL`). Runs fire-and-forget so whisper/TTS come up immediately.
+ - Per-event timing logs with a turn correlation id: `turn.start`, `stt.done`, `lmstudio.resolve`, `lmstudio.headers`, `llm.start`, `llm.ttft`, `llm.done`, `tool.start`/`tool.done`/`tool.fail`, `tts.start`/`tts.done`, `turn.summary`. Makes it obvious whether latency is in cold-load, reasoning, tool execution, or TTS.
+ - Empty-output guard — when the LLM produces no text and no tool runs, the server now emits `voice:error` with a specific model-switch hint (the existing VoiceWidget toast surfaces it) instead of going silent.
+
- **Voice widget covering page content on mobile** — the floating voice input bar (text field, hands-free toggle, mic button) was fixed at the bottom of the screen and spanned the full width on mobile, blocking form buttons (Cancel/Save) and navigation. On mobile (<768px) the widget now collapses to a single compact mic FAB in the bottom-right corner; tapping it expands the full controls and starts listening in one tap. An X button dismisses back to the FAB. Desktop behavior is unchanged.
- **Cmd prompt windows flashing on Windows** — `fetchJlist` in `pm2.js` was spawning a `node pm2.js jlist` subprocess every 400ms+ during app-status polling. Even with `windowsHide: true`, Windows briefly flashes the console for spawned Node.js processes on some configurations. Fixed by switching to the PM2 Node.js API (`pm2.list()` via IPC) for the default PM2_HOME case, eliminating subprocess spawning entirely. The CLI path is kept only for custom `pm2Home` (managed external apps).
diff --git a/server/services/voice/bootstrap.js b/server/services/voice/bootstrap.js
index 575b0735e9..9cdbe14f66 100644
--- a/server/services/voice/bootstrap.js
+++ b/server/services/voice/bootstrap.js
@@ -9,6 +9,7 @@ import { createServer } from 'net';
import { PATHS } from '../../lib/fileUtils.js';
import { execPm2, getAppStatus } from '../pm2.js';
import { expandPath, piperVoiceTildePath } from './config.js';
+import { isToolCapable } from './llm.js';
export const pexec = promisify(execFile);
@@ -195,6 +196,62 @@ export const stopWhisper = async () => {
return { stopped: true };
};
+// Default tool-capable model to auto-install via `lms get` when the user has
+// voice.enabled + tools.enabled + model='auto' but LM Studio has no model that
+// speaks OpenAI structured tool_calls. Qwen2.5-7B-Instruct is the smallest
+// widely-supported option with good tool-use training (~4.5 GB Q4). Can be
+// overridden via PORTOS_VOICE_DEFAULT_TOOL_MODEL.
+const DEFAULT_TOOL_MODEL = () =>
+ process.env.PORTOS_VOICE_DEFAULT_TOOL_MODEL || 'lmstudio-community/Qwen2.5-7B-Instruct-GGUF';
+
+const LMS_BASE = () => (process.env.LM_STUDIO_URL || 'http://localhost:1234')
+ .replace(/\/+$/, '').replace(/\/v1$/, '');
+
+const listLmStudioModels = async () => {
+ const res = await fetch(`${LMS_BASE()}/v1/models`).catch(() => null);
+ if (!res?.ok) return [];
+ const body = await res.json().catch(() => ({}));
+ return (body?.data || []).map((m) => m.id);
+};
+
+export const ensureToolCapableModel = async (cfg) => {
+ // Only intervene when the user opted in: tools on AND model is 'auto'.
+ // An explicit model id means they know what they want — respect it even
+ // if incompatible.
+ if (!cfg?.llm?.tools?.enabled) return { skipped: 'tools-disabled' };
+ if (cfg?.llm?.model && cfg.llm.model !== 'auto') return { skipped: 'explicit-model' };
+
+ const installed = await listLmStudioModels();
+ if (installed.length && installed.some(isToolCapable)) {
+ return { skipped: 'already-capable', model: installed.find(isToolCapable) };
+ }
+
+ const lms = await which('lms');
+ if (!lms) {
+ console.warn(`🎙️ voice: no tool-capable model installed and 'lms' CLI not on PATH — install LM Studio CLI or set voice.llm.model explicitly.`);
+ return { skipped: 'no-lms-cli' };
+ }
+
+ const target = DEFAULT_TOOL_MODEL();
+ console.log(`🎙️ voice: no tool-capable model found — installing ${target} via lms get (multi-GB download, this may take a while)`);
+ const { stdout, stderr } = await pexec(lms, ['get', '-y', target], {
+ maxBuffer: 64 * 1024 * 1024,
+ // 30 min cap — a 4-5 GB GGUF on a slow link can legitimately take this long.
+ timeout: 30 * 60 * 1000,
+ }).catch((err) => ({ stdout: '', stderr: err?.message || String(err) }));
+ if (stderr && /error|failed|not found/i.test(stderr)) {
+ console.warn(`🎙️ voice: lms get ${target} stderr — ${stderr.slice(0, 400)}`);
+ }
+ const after = await listLmStudioModels();
+ const got = after.find(isToolCapable);
+ if (got) {
+ console.log(`🎙️ voice: tool-capable model ready — ${got}`);
+ return { installed: got };
+ }
+ console.warn(`🎙️ voice: lms get completed but no tool-capable model detected — stdout=${(stdout || '').slice(0, 200)}`);
+ return { failed: target };
+};
+
/**
* Reconcile PM2 state with desired voice.enabled. Called from
* PUT /api/voice/config and at server boot.
@@ -202,6 +259,14 @@ export const stopWhisper = async () => {
export const reconcile = async (cfg) => {
if (!cfg.enabled) return stopWhisper();
+ // Don't block reconcile on this — it can take minutes on first install.
+ // The user will see a clear log line and their first turn may fail with the
+ // new `voice:error` hint until the model finishes downloading, but voice
+ // STT + TTS + whisper are ready immediately.
+ ensureToolCapableModel(cfg).catch((err) => {
+ console.warn(`🎙️ voice: ensureToolCapableModel failed: ${err.message}`);
+ });
+
const bins = await verifyBinaries(cfg);
const models = verifyModels(cfg);
const piperMissing = bins.piperRequired && (!bins.piper || !models.ttsVoice);
diff --git a/server/services/voice/llm.js b/server/services/voice/llm.js
index 2f9f3f05c6..0dd9aecfc2 100644
--- a/server/services/voice/llm.js
+++ b/server/services/voice/llm.js
@@ -21,7 +21,48 @@ const sizeRank = (id) => {
return Infinity;
};
-const resolveModel = async (requested) => {
+// Models known to speak OpenAI's structured `tool_calls` SSE fragments. When
+// tools are attached, prefer one of these over a model that would either emit
+// its own inline format (Granite's `<tool_call>[...]</tool_call>`) or silently
+// bail on large tool schemas. Match against lowercased model id — vendor
+// prefix (`lmstudio-community/`, `mistralai/`, `nousresearch/`, etc.) is
+// routinely present and varies, so anchor on the model family token.
+export const TOOL_CAPABLE_PATTERNS = [
+ /qwen2\.5.*instruct/,
+ /qwen3.*instruct/,
+ /hermes-?3/,
+ /mistral-small/,
+ /mistral.*instruct-v0\.[3-9]/,
+ /ministral.*instruct/,
+ /ministral.*reasoning/,
+ /devstral/,
+ /llama-?3\.[1-9].*instruct/,
+ /llama-?3\.[1-9].*tool/,
+ /command-r(\+|-plus)?/,
+ /functionary/,
+];
+
+// Explicit block-list for model families that do NOT emit OpenAI-format
+// tool_calls even when LM Studio accepts the `tools` argument. Extracted from
+// empirical testing; add new entries as they're observed. Still usable in
+// no-tools mode — just filter them out when we need tool calling.
+export const TOOL_INCOMPATIBLE_PATTERNS = [
+ /granite-?3/, // emits `<tool_call>[...]</tool_call>` inline content (parsed below)
+ /gemma-?[23].*\b\d+m\b/, // small non-instruct gemmas
+];
+
+export const isToolCapable = (id) => {
+ const n = String(id).toLowerCase();
+ if (TOOL_CAPABLE_PATTERNS.some((re) => re.test(n))) return true;
+ return false;
+};
+
+const isToolIncompatible = (id) => {
+ const n = String(id).toLowerCase();
+ return TOOL_INCOMPATIBLE_PATTERNS.some((re) => re.test(n));
+};
+
+const resolveModel = async (requested, { requireTools = false } = {}) => {
const res = await fetch(`${LM_STUDIO_BASE()}/v1/models`).catch(() => null);
if (!res || !res.ok) return requested && requested !== 'auto' ? requested : null;
const body = await res.json();
@@ -29,9 +70,115 @@ const resolveModel = async (requested) => {
if (requested && requested !== 'auto') {
return ids.includes(requested) ? requested : ids[0] || null;
}
- // 'auto' → smallest non-utility model, or first if no size info
- const sorted = ids.slice().sort((a, b) => sizeRank(a) - sizeRank(b));
- return sorted[0] || null;
+ // 'auto' with tools on → pick the smallest tool-capable model if one is
+ // available. Fall back to smallest non-utility model otherwise. This avoids
+ // the classic bug where 'auto' picks Granite (smallest B by name) and the
+ // stream silently returns empty because Granite doesn't emit OpenAI
+ // tool_calls. The inline-`<tool_call>` parser at stream end still rescues
+ // Granite for simple cases, but a proper tool-use model is the right default.
+ const sortBySize = (list) => list.slice().sort((a, b) => sizeRank(a) - sizeRank(b));
+ if (requireTools) {
+ const capable = ids.filter(isToolCapable);
+ const sorted = sortBySize(capable);
+ if (sorted[0]) return sorted[0];
+ // No known tool-capable model — fall through to size-ranked pick, but
+ // skip known-incompatible families so we at least get inline `<tool_call>`
+ // content rather than an empty stream on a base model.
+ const safe = sortBySize(ids.filter((id) => !isToolIncompatible(id)));
+ return safe[0] || ids[0] || null;
+ }
+ return sortBySize(ids)[0] || null;
+};
+
+// Parse IBM Granite / Llama-3 tool-use formats that are emitted as
+// `delta.content` rather than structured `delta.tool_calls`. Granite 3.2 in
+// practice emits BOTH `<tool_call>...</tool_call>` and `<tool_request>...`
+// (bare, unclosed) forms — observed varying between requests against the same
+// model with the same prompt. We handle: (a) the XML-tagged closed form, (b)
+// the unclosed form, (c) either tag spelling.
+const TOOL_TAG_SPELLINGS = ['tool_call', 'tool_request'];
+const TOOL_CALL_CLOSED_RE = /<(tool_call|tool_request)>\s*(\[[\s\S]*?\])\s*<\/\1>/g;
+
+const pushParsedCalls = (raw, toolCalls) => {
+ let parsed;
+ try { parsed = JSON.parse(raw); } catch { return false; }
+ const arr = Array.isArray(parsed) ? parsed : [parsed];
+ let pushed = 0;
+ for (const c of arr) {
+ if (!c || typeof c !== 'object' || typeof c.name !== 'string') continue;
+ toolCalls.push({
+ index: toolCalls.length,
+ id: `call_inline_${toolCalls.length}`,
+ type: 'function',
+ function: {
+ name: c.name,
+ arguments: JSON.stringify(c.arguments ?? c.parameters ?? {}),
+ },
+ });
+ pushed++;
+ }
+ return pushed > 0;
+};
+
+// Walk `text` starting at `start` to find a balanced top-level JSON array.
+// Returns [jsonText, endIdx] or null. Respects string quoting so a `]`
+// inside a string literal doesn't prematurely close. Cheaper than pulling a
+// full JSON parser just for boundary detection.
+const scanBalancedArray = (text, start) => {
+ let i = start;
+ while (i < text.length && /\s/.test(text[i])) i++;
+ if (text[i] !== '[') return null;
+ let depth = 0;
+ let inStr = false;
+ let escape = false;
+ for (; i < text.length; i++) {
+ const ch = text[i];
+ if (inStr) {
+ if (escape) { escape = false; continue; }
+ if (ch === '\\') { escape = true; continue; }
+ if (ch === '"') inStr = false;
+ continue;
+ }
+ if (ch === '"') { inStr = true; continue; }
+ if (ch === '[') depth++;
+ else if (ch === ']') {
+ depth--;
+ if (depth === 0) return [text.slice(start, i + 1).trim(), i + 1];
+ }
+ }
+ return null;
+};
+
+export const extractInlineToolCalls = (text) => {
+ if (!text) return { text: '', toolCalls: [] };
+ const toolCalls = [];
+ let cleaned = text;
+
+ // 1) Closed-form tags: strip each matched block (matches either spelling).
+ TOOL_CALL_CLOSED_RE.lastIndex = 0;
+ let m;
+ while ((m = TOOL_CALL_CLOSED_RE.exec(text)) !== null) {
+ if (pushParsedCalls(m[2], toolCalls)) {
+ cleaned = cleaned.split(m[0]).join('');
+ }
+ }
+
+ // 2) Unclosed tag: `<tool_call>[...]` or `<tool_request>[...]` with no
+ // matching close. Granite often stops generating before closing.
+ // Try each spelling in order; scan from the opener position.
+ for (const spelling of TOOL_TAG_SPELLINGS) {
+ const open = `<${spelling}>`;
+ const openAt = cleaned.indexOf(open);
+ if (openAt === -1) continue;
+ const arrStart = openAt + open.length;
+ const arr = scanBalancedArray(cleaned, arrStart);
+ if (arr && pushParsedCalls(arr[0], toolCalls)) {
+ const close = new RegExp(`</${spelling}>\\s*`, 'g');
+ cleaned = (cleaned.slice(0, openAt) + cleaned.slice(arr[1])).replace(close, '');
+ }
+ }
+
+ return { text: cleaned.trim(), toolCalls };
};
/**
@@ -48,8 +195,15 @@ const resolveModel = async (requested) => {
* @returns {Promise<{ text: string, toolCalls: Array<object>, model: string|null, ttfbMs: number|null, totalMs: number, finishReason: string|null }>}
*/
export const streamChat = async (messages, opts = {}) => {
- const model = await resolveModel(opts.model);
+ const resolveStart = Date.now();
+ const model = await resolveModel(opts.model, { requireTools: !!opts.tools?.length });
+ const resolveMs = Date.now() - resolveStart;
if (!model) throw new Error('No LM Studio model available');
+ // Surface resolution time — non-trivial when LM Studio is warming up a new
+ // model, and invisible otherwise because we only logged once the stream
+ // finished. opts.tag lets the pipeline inject its turn id for correlation.
+ const tag = opts.tag ? `[${opts.tag}] ` : '';
+ console.log(`🤖 ${tag}lmstudio.resolve requested=${opts.model || 'auto'} → ${model} in ${resolveMs}ms`);
const started = Date.now();
const body = {
@@ -64,12 +218,14 @@ export const streamChat = async (messages, opts = {}) => {
body.tool_choice = opts.toolChoice ?? 'auto';
}
+ const reqStart = Date.now();
const res = await fetch(`${LM_STUDIO_BASE()}/v1/chat/completions`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
signal: opts.signal,
});
+ console.log(`🤖 ${tag}lmstudio.headers ${res.status} in ${Date.now() - reqStart}ms`);
if (!res.ok || !res.body) {
const errBody = await res.text().catch(() => '');
throw new Error(`LM Studio chat failed: ${res.status} ${errBody.slice(0, 200)}`);
@@ -84,6 +240,75 @@ export const streamChat = async (messages, opts = {}) => {
// Tool calls stream as fragments keyed by index; accumulate until [DONE].
const toolCallFrags = new Map();
+ // Streaming tool-call stripper: when a model emits Granite-style inline
+ // `<tool_call>[...]</tool_call>` or `<tool_request>[...]` in `delta.content`,
+ // we must NOT forward those chunks to onDelta — the pipeline feeds deltas to
+ // TTS and would speak the raw JSON. We still accumulate everything into
+ // `text` so the post-stream parser can hoist into structured `toolCalls`.
+ // Tail characters that could be a partial open/close tag are held across
+ // chunks. Supports both tag spellings in parallel.
+ const OPEN_TAGS = TOOL_TAG_SPELLINGS.map((s) => `<${s}>`);
+ const CLOSE_TAGS = TOOL_TAG_SPELLINGS.map((s) => `</${s}>`);
+ let activeClose = null; // set when we entered a tool block
+ let tailHold = '';
+ // Find the earliest match of any candidate in `data`, starting at 0.
+ const earliestIndex = (data, candidates) => {
+ let best = -1;
+ let bestLen = 0;
+ for (const c of candidates) {
+ const i = data.indexOf(c);
+ if (i !== -1 && (best === -1 || i < best)) { best = i; bestLen = c.length; }
+ }
+ return best === -1 ? null : [best, bestLen];
+ };
+ // Longest suffix of `data` that is a prefix of any candidate — characters we
+ // must withhold because they might begin a real tag once more data arrives.
+ const longestPrefixHold = (data, candidates) => {
+ const max = Math.max(...candidates.map((c) => c.length - 1));
+ const limit = Math.min(data.length, max);
+ for (let k = limit; k > 0; k--) {
+ const tail = data.slice(data.length - k);
+ if (candidates.some((c) => c.startsWith(tail))) return k;
+ }
+ return 0;
+ };
+ const forwardClean = (chunk) => {
+ let data = tailHold + chunk;
+ tailHold = '';
+ let out = '';
+ while (data.length) {
+ if (!activeClose) {
+ const hit = earliestIndex(data, OPEN_TAGS);
+ if (hit) {
+ out += data.slice(0, hit[0]);
+ const spelling = data.slice(hit[0] + 1, hit[0] + hit[1] - 1); // strip '<' and '>'
+ activeClose = `</${spelling}>`;
+ data = data.slice(hit[0] + hit[1]);
+ continue;
+ }
+ const hold = longestPrefixHold(data, OPEN_TAGS);
+ if (hold) {
+ out += data.slice(0, data.length - hold);
+ tailHold = data.slice(data.length - hold);
+ } else {
+ out += data;
+ }
+ data = '';
+ } else {
+ const i = data.indexOf(activeClose);
+ if (i !== -1) {
+ data = data.slice(i + activeClose.length);
+ activeClose = null;
+ continue;
+ }
+ const hold = longestPrefixHold(data, [activeClose]);
+ if (hold) tailHold = data.slice(data.length - hold);
+ data = '';
+ }
+ }
+ if (out) opts.onDelta?.(out);
+ };
+
while (true) {
const { value, done } = await reader.read();
if (done) break;
@@ -96,8 +321,7 @@ export const streamChat = async (messages, opts = {}) => {
if (!line.startsWith('data:')) continue;
const payload = line.slice(5).trim();
if (payload === '[DONE]') {
- const toolCalls = [...toolCallFrags.values()].sort((a, b) => a.index - b.index);
- return { text, toolCalls, model, ttfbMs, totalMs: Date.now() - started, finishReason };
+ return finalizeReturn();
}
// Malformed SSE frames (proxy keep-alive, truncated write) would otherwise
// abort the whole turn; skip the line and keep streaming.
@@ -109,7 +333,7 @@ export const streamChat = async (messages, opts = {}) => {
if (delta.content) {
if (ttfbMs === null) ttfbMs = Date.now() - started;
text += delta.content;
- opts.onDelta?.(delta.content);
+ forwardClean(delta.content);
}
for (const tc of delta.tool_calls || []) {
const frag = toolCallFrags.get(tc.index) || {
@@ -128,6 +352,24 @@ export const streamChat = async (messages, opts = {}) => {
}
}
}
- const toolCalls = [...toolCallFrags.values()].sort((a, b) => a.index - b.index);
- return { text, toolCalls, model, ttfbMs, totalMs: Date.now() - started, finishReason };
+ return finalizeReturn();
+
+ function finalizeReturn() {
+ const streamed = [...toolCallFrags.values()].sort((a, b) => a.index - b.index);
+ // Post-stream: if the model emitted no structured tool_calls but wrote
+ // Granite-style `<tool_call>[...]</tool_call>` in content, extract them
+ // and clean the visible text. No-ops when the regex doesn't match.
+ const { text: cleanedText, toolCalls: inlineCalls } = streamed.length
+ ? { text, toolCalls: [] }
+ : extractInlineToolCalls(text);
+ const toolCalls = streamed.length ? streamed : inlineCalls;
+ return {
+ text: cleanedText,
+ toolCalls,
+ model,
+ ttfbMs,
+ totalMs: Date.now() - started,
+ finishReason,
+ };
+ }
};
diff --git a/server/services/voice/llm.test.js b/server/services/voice/llm.test.js
new file mode 100644
index 0000000000..745a9b08d9
--- /dev/null
+++ b/server/services/voice/llm.test.js
@@ -0,0 +1,127 @@
+import { describe, it, expect } from 'vitest';
+import { extractInlineToolCalls, isToolCapable, TOOL_CAPABLE_PATTERNS } from './llm.js';
+
+describe('extractInlineToolCalls', () => {
+ it('returns empty when no tag is present', () => {
+ const { text, toolCalls } = extractInlineToolCalls('Just plain prose.');
+ expect(text).toBe('Just plain prose.');
+ expect(toolCalls).toEqual([]);
+ });
+
+ it('extracts a single Granite-style tool call', () => {
+ const raw = 'Let me check. <tool_call>[{"name": "time_now", "arguments": {}}]</tool_call>';
+ const { text, toolCalls } = extractInlineToolCalls(raw);
+ expect(text).toBe('Let me check.');
+ expect(toolCalls).toHaveLength(1);
+ expect(toolCalls[0].function.name).toBe('time_now');
+ expect(JSON.parse(toolCalls[0].function.arguments)).toEqual({});
+ expect(toolCalls[0].type).toBe('function');
+ });
+
+ it('extracts multiple tool calls from one array', () => {
+ const raw = '<tool_call>[{"name":"a","arguments":{"x":1}},{"name":"b","arguments":{"y":"z"}}]</tool_call>';
+ const { text, toolCalls } = extractInlineToolCalls(raw);
+ expect(text).toBe('');
+ expect(toolCalls.map((t) => t.function.name)).toEqual(['a', 'b']);
+ expect(JSON.parse(toolCalls[0].function.arguments)).toEqual({ x: 1 });
+ expect(JSON.parse(toolCalls[1].function.arguments)).toEqual({ y: 'z' });
+ });
+
+ it('accepts `parameters` as an alias for `arguments`', () => {
+ const raw = '<tool_call>[{"name":"foo","parameters":{"q":"test"}}]</tool_call>';
+ const { toolCalls } = extractInlineToolCalls(raw);
+ expect(JSON.parse(toolCalls[0].function.arguments)).toEqual({ q: 'test' });
+ });
+
+ it('survives malformed JSON inside the tag', () => {
+ const raw = 'Prefix <tool_call>[not json]</tool_call> suffix.';
+ const { text, toolCalls } = extractInlineToolCalls(raw);
+ expect(toolCalls).toEqual([]);
+ expect(text).toContain('Prefix');
+ expect(text).toContain('suffix.');
+ });
+
+ it('skips array entries missing a name', () => {
+ const raw = '<tool_call>[{"arguments":{"x":1}},{"name":"ok","arguments":{}}]</tool_call>';
+ const { toolCalls } = extractInlineToolCalls(raw);
+ expect(toolCalls).toHaveLength(1);
+ expect(toolCalls[0].function.name).toBe('ok');
+ });
+
+ it('handles the unclosed tag form Granite 3.2 actually emits', () => {
+ const raw = '<tool_call>[{"name": "time_now", "arguments": {}}]';
+ const { text, toolCalls } = extractInlineToolCalls(raw);
+ expect(text).toBe('');
+ expect(toolCalls).toHaveLength(1);
+ expect(toolCalls[0].function.name).toBe('time_now');
+ });
+
+ it('also handles <tool_request> spelling (Granite varies between requests)', () => {
+ const raw = '<tool_request>[{"name": "time_now", "arguments": {}}]';
+ const { text, toolCalls } = extractInlineToolCalls(raw);
+ expect(text).toBe('');
+ expect(toolCalls).toHaveLength(1);
+ });
+
+ it('handles closed <tool_request>...</tool_request> form', () => {
+ const raw = 'OK. <tool_request>[{"name":"x","arguments":{}}]</tool_request>';
+ const { text, toolCalls } = extractInlineToolCalls(raw);
+ expect(text).toBe('OK.');
+ expect(toolCalls).toHaveLength(1);
+ });
+
+ it('unclosed tag with prose prefix keeps the prose', () => {
+ const raw = 'Sure, one sec. <tool_call>[{"name":"foo","arguments":{"a":1}}]';
+ const { text, toolCalls } = extractInlineToolCalls(raw);
+ expect(text).toBe('Sure, one sec.');
+ expect(toolCalls).toHaveLength(1);
+ });
+
+ it('handles nested arrays / brackets inside arguments', () => {
+ const raw = '<tool_call>[{"name":"q","arguments":{"xs":[1,2,3]}}]</tool_call>';
+ const { toolCalls } = extractInlineToolCalls(raw);
+ expect(toolCalls).toHaveLength(1);
+ expect(JSON.parse(toolCalls[0].function.arguments)).toEqual({ xs: [1, 2, 3] });
+ });
+
+ it('handles brackets inside JSON strings without false-closing', () => {
+ const raw = '<tool_call>[{"name":"q","arguments":{"note":"has ] bracket"}}]</tool_call>';
+ const { toolCalls } = extractInlineToolCalls(raw);
+ expect(toolCalls).toHaveLength(1);
+ expect(JSON.parse(toolCalls[0].function.arguments)).toEqual({ note: 'has ] bracket' });
+ });
+});
+
+describe('isToolCapable', () => {
+ it('accepts known tool-use families', () => {
+ for (const id of [
+ 'qwen2.5-7b-instruct',
+ 'Qwen2.5-14B-Instruct',
+ 'lmstudio-community/Qwen2.5-7B-Instruct-GGUF',
+ 'NousResearch/Hermes-3-Llama-3.1-8B',
+ 'mistralai/Mistral-Small-24B-Instruct',
+ 'mistralai/devstral-small-2-2512',
+ 'mistralai/ministral-3-14b-reasoning',
+ 'meta-llama/Llama-3.1-8B-Instruct',
+ ]) {
+ expect(isToolCapable(id), id).toBe(true);
+ }
+ });
+
+ it('rejects non-tool-use families', () => {
+ for (const id of [
+ 'ibm/granite-3.2-8b',
+ 'ibm/granite-3.1-2b-base',
+ 'gemma-3-270m-it',
+ 'l3.3-70b-euryale-v2.3-i1',
+ 'text-embedding-nomic-embed-text-v1.5',
+ ]) {
+ expect(isToolCapable(id), id).toBe(false);
+ }
+ });
+
+ it('exports the pattern list for introspection', () => {
+ expect(Array.isArray(TOOL_CAPABLE_PATTERNS)).toBe(true);
+ expect(TOOL_CAPABLE_PATTERNS.every((p) => p instanceof RegExp)).toBe(true);
+ });
+});
diff --git a/server/services/voice/pipeline.js b/server/services/voice/pipeline.js
index 85f80646cd..00bbd0ecff 100644
--- a/server/services/voice/pipeline.js
+++ b/server/services/voice/pipeline.js
@@ -73,18 +73,30 @@ export const isNonSpeechMarker = (text) => /^\s*\[[A-Z_ ]+\]\s*$/i.test(text);
// LLM. Intentionally narrow — "I'm done writing" shouldn't match.
const STOP_DICTATION_RE = /^(stop|end|exit|cancel|pause)\s+(dictation|dictating|logging|recording)[\.\!\s]*$/i;
+// Short correlation id so overlapping turns in the logs can be told apart
+// (user interrupts, late-arriving retries). 5 chars of base36 randomness is
+// plenty for single-user PortOS.
+const shortId = () => Math.random().toString(36).slice(2, 7);
+
export const runTurn = async ({ audio, text, mimeType, source, history = [], emit, signal, state }) => {
const cfg = await getVoiceConfig();
if (signal?.aborted) return { transcript: '', reply: '' };
const turnStart = Date.now();
+ const turnId = shortId();
+ const elapsed = () => Date.now() - turnStart;
+ const tlog = (msg) => console.log(`🎙️ [${turnId}] ${msg} +${elapsed()}ms`);
+
+ tlog(`turn.start source=${text ? 'text' : 'audio'} ${text ? `chars=${String(text).length}` : `bytes=${audio?.byteLength || audio?.length || 0} mime=${mimeType || '—'}`}`);
let userText = text;
let sttLatencyMs = 0;
if (!userText) {
+ tlog(`stt.start`);
const stt = await transcribe(audio, { mimeType, signal });
sttLatencyMs = stt.latencyMs;
userText = isNonSpeechMarker(stt.text) ? '' : stt.text;
+ tlog(`stt.done ${sttLatencyMs}ms chars=${userText.length} text="${userText.slice(0, 80)}${userText.length > 80 ? '…' : ''}"`);
emit('voice:transcript', { text: userText, latencyMs: stt.latencyMs });
} else {
// VoiceWidget treats transcripts with source !== 'text' as server-STT
@@ -93,6 +105,7 @@ export const runTurn = async ({ audio, text, mimeType, source, history = [], emi
// 'voice' would duplicate the message. Keep `source` stable and expose
// the caller's routing hint separately so dictation/Origin-aware code
// can still distinguish typed vs spoken without breaking chat history.
+ tlog(`input.text chars=${userText.length} source=${source || 'text'} text="${userText.slice(0, 80)}${userText.length > 80 ? '…' : ''}"`);
emit('voice:transcript', {
text: userText,
latencyMs: 0,
@@ -102,7 +115,7 @@ export const runTurn = async ({ audio, text, mimeType, source, history = [], emi
}
if (!userText) {
- console.log(`🎙️ voice: empty input (stt=${sttLatencyMs}ms)`);
+ tlog(`done empty-input stt=${sttLatencyMs}ms`);
emit('voice:idle', { reason: 'empty-transcript' });
return { transcript: '', reply: '' };
}
@@ -182,11 +195,16 @@ export const runTurn = async ({ audio, text, mimeType, source, history = [], emi
let pending = '';
const ttsTimings = [];
+ let ttsIdx = 0;
const speak = async (sentence) => {
if (signal?.aborted || !sentence) return;
+ const i = ++ttsIdx;
+ const t0 = Date.now();
+ tlog(`tts.start #${i} chars=${sentence.length}`);
const { wav, latencyMs } = await synthesize(sentence, { signal });
if (signal?.aborted) return;
ttsTimings.push(latencyMs);
+ tlog(`tts.done #${i} ${latencyMs}ms synth+queue=${Date.now() - t0}ms`);
emit('voice:tts:audio', { sentence, wav, latencyMs });
};
@@ -214,17 +232,28 @@ export const runTurn = async ({ audio, text, mimeType, source, history = [], emi
for (let iter = 0; iter < maxIterations; iter++) {
if (signal?.aborted) break;
+ const iterStart = Date.now();
+ let firstDeltaAt = null;
+ let deltaChars = 0;
+ tlog(`llm.start iter=${iter + 1}/${maxIterations} model=${cfg.llm.model} tools=${toolSpecs?.length || 0} msgs=${messages.length}`);
const llm = await streamChat(messages, {
model: cfg.llm.model,
signal,
tools: toolSpecs,
+ tag: turnId,
onDelta: (delta) => {
+ if (firstDeltaAt === null) {
+ firstDeltaAt = Date.now();
+ tlog(`llm.ttft iter=${iter + 1} ${firstDeltaAt - iterStart}ms model=${lastLlm?.model || cfg.llm.model}`);
+ }
+ deltaChars += delta.length;
emit('voice:llm:delta', { delta });
flushSentence(delta);
},
});
if (!firstLlm) firstLlm = llm;
lastLlm = llm;
+ tlog(`llm.done iter=${iter + 1} ${Date.now() - iterStart}ms model=${llm.model} text=${(llm.text || '').length}c spoken=${deltaChars}c tool_calls=${llm.toolCalls?.length || 0} finish=${llm.finishReason ?? '—'}`);
// Accumulate spoken text across tool-calling iterations. The old single-
// assignment version dropped every earlier segment, so the persisted
// `reply` (and next turn's history) diverged from what the user actually
@@ -264,11 +293,17 @@ export const runTurn = async ({ audio, text, mimeType, source, history = [], emi
const ctx = { sideEffects: [] };
try {
args = tc.function.arguments ? JSON.parse(tc.function.arguments) : {};
+ const argSummary = Object.keys(args).length ? Object.entries(args).map(([k, v]) => `${k}=${JSON.stringify(v).slice(0, 40)}`).join(' ') : '—';
+ tlog(`tool.start ${tc.function.name} ${argSummary}`);
result = await dispatchTool(tc.function.name, args, ctx);
- toolRuns.push({ name: tc.function.name, ok: true, ms: Date.now() - t0 });
+ const ms = Date.now() - t0;
+ toolRuns.push({ name: tc.function.name, ok: true, ms });
+ tlog(`tool.done ${tc.function.name} ok ${ms}ms`);
} catch (err) {
+ const ms = Date.now() - t0;
result = { ok: false, error: err.message };
- toolRuns.push({ name: tc.function.name, ok: false, ms: Date.now() - t0, error: err.message });
+ toolRuns.push({ name: tc.function.name, ok: false, ms, error: err.message });
+ tlog(`tool.fail ${tc.function.name} ${ms}ms err="${err.message}"`);
}
// Apply server-side side-effects (dictation state) and forward
// client-facing side-effects (navigation) over the socket.
@@ -306,13 +341,26 @@ export const runTurn = async ({ audio, text, mimeType, source, history = [], emi
? ` · tools=${toolRuns.map((r) => `${r.name}(${r.ok ? `${r.ms}ms` : 'err'})`).join(',')}`
: '';
console.log(
- `🎙️ ${inputKind} turn ${totalMs}ms — ` +
+ `🎙️ [${turnId}] turn.summary ${inputKind} ${totalMs}ms — ` +
`stt=${sttLatencyMs}ms · ` +
- `llm[${lastLlm?.model}] ttft=${firstLlm?.ttfbMs ?? '—'}ms total=${lastLlm?.totalMs}ms · ` +
+ `llm[${lastLlm?.model}] ttft=${firstLlm?.ttfbMs ?? '—'}ms total=${lastLlm?.totalMs}ms finish=${lastLlm?.finishReason ?? '—'} · ` +
`tts=${ttsTotal}ms (${ttsTimings.length} sentences)` +
toolSummary
);
+ // Surface the silent-empty-reply case — most commonly caused by picking a
+ // model that doesn't speak the OpenAI tool-calling API (e.g., IBM Granite,
+ // which emits `<tool_call>[...]</tool_call>` inline in content), especially
+ // when many tools are attached and the model bails with a zero-length
+ // stream. Without this the user sees their transcript, then silence.
+ if (!signal?.aborted && !finalText.trim() && toolRuns.length === 0) {
+ const hint = toolsEnabled
+ ? `Model ${lastLlm?.model || cfg.llm.model} returned no response. It may not support OpenAI tool-calling with ${toolSpecs?.length || 0} tools — try a tool-use model (Qwen2.5-Instruct, Hermes-3, Mistral) or disable voice tools in Settings.`
+ : `Model ${lastLlm?.model || cfg.llm.model} returned no response.`;
+ console.warn(`🎙️ empty LLM output — ${hint}`);
+ emit('voice:error', { stage: 'llm', message: hint });
+ }
+
emit('voice:llm:done', { text: finalText, model: lastLlm?.model, ttfbMs: firstLlm?.ttfbMs });
emit('voice:idle', { reason: 'turn-complete' });
return { transcript: userText, reply: finalText };