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: bound voice LLM streams so turns recover (#5497)

[._.]/ Adam Eivybf24186e8dc8
diff --git a/server/services/voice/llm.js b/server/services/voice/llm.js
index 51274ed04d..35056c4b00 100644
--- a/server/services/voice/llm.js
+++ b/server/services/voice/llm.js
@@ -53,6 +53,12 @@ export const resolveLlmEndpoint = async (providerId = 'lmstudio') => {
export const authHeaders = (apiKey) => (apiKey ? { Authorization: `Bearer ${apiKey}` } : {});
+// A voice turn must eventually release its socket state even when an upstream
+// accepts the request but never sends headers or stops its SSE stream. This is
+// a total request-plus-stream budget, rather than an idle-chunk timeout.
+export const VOICE_LLM_TIMEOUT_MS = 30_000;
+export const VOICE_LLM_TIMEOUT_MESSAGE = 'Voice LLM request timed out';
+
// Approximate parameter count from LM Studio model id so 'auto' avoids a 70B
// when smaller, faster models are available. Returns Infinity for non-matches
// and utility models so they sort last rather than silently winning ties.
@@ -345,166 +351,206 @@ export const streamChat = async (messages, opts = {}) => {
body.tool_choice = opts.toolChoice ?? 'auto';
}
- const reqStart = Date.now();
- const res = await fetch(`${apiBase}/chat/completions`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json', ...authHeaders(apiKey) },
- body: JSON.stringify(body),
- signal: opts.signal,
- });
- console.log(`🤖 ${tag}voice.llm.headers ${res.status} in ${Date.now() - reqStart}ms`);
- if (!res.ok || !res.body) {
- const errBody = await res.text().catch(() => '');
- throw new Error(`${providerName} chat failed: ${res.status} ${errBody.slice(0, 200)}`);
- }
-
- const decoder = new TextDecoder();
- const reader = res.body.getReader();
- let buffer = '';
- let text = '';
- let ttfbMs = null;
- let finishReason = null;
- // 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. Reasoning models likewise emit `<think>`
- // blocks that should be hidden even when our disable directives don't take.
- // 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. All tag spellings handled in parallel.
- const STRIP_TAGS = [...TOOL_TAG_SPELLINGS, 'think', 'thinking', 'reasoning'];
- const OPEN_TAGS = STRIP_TAGS.map((s) => `<${s}>`);
- const CLOSE_TAGS = STRIP_TAGS.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; }
+ const requestController = new AbortController();
+ let timedOut = false;
+ const onExternalAbort = opts.signal
+ ? () => requestController.abort(opts.signal.reason)
+ : null;
+ let reader = null;
+ const cancelReader = () => {
+ if (typeof reader?.cancel !== 'function') return;
+ try {
+ void Promise.resolve(reader.cancel()).catch(() => {});
+ } catch (err) {
+ console.error(`🤖 voice.llm.reader_cancel failed: ${err.message}`);
}
- 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;
+ requestController.signal.addEventListener('abort', cancelReader, { once: true });
+ if (opts.signal) {
+ if (opts.signal.aborted) onExternalAbort();
+ else opts.signal.addEventListener('abort', onExternalAbort, { once: true });
+ }
+ const timeoutId = setTimeout(() => {
+ timedOut = true;
+ requestController.abort();
+ }, VOICE_LLM_TIMEOUT_MS);
+
+ const requestPromise = (async () => {
+ const reqStart = Date.now();
+ const res = await fetch(`${apiBase}/chat/completions`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...authHeaders(apiKey) },
+ body: JSON.stringify(body),
+ signal: requestController.signal,
+ });
+ console.log(`🤖 ${tag}voice.llm.headers ${res.status} in ${Date.now() - reqStart}ms`);
+ if (!res.ok || !res.body) {
+ const errBody = await res.text().catch(() => '');
+ throw new Error(`${providerName} chat failed: ${res.status} ${errBody.slice(0, 200)}`);
}
- 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);
+
+ const decoder = new TextDecoder();
+ reader = res.body.getReader();
+ if (requestController.signal.aborted) cancelReader();
+ let buffer = '';
+ let text = '';
+ let ttfbMs = null;
+ let finishReason = null;
+ // 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. Reasoning models likewise emit `<think>`
+ // blocks that should be hidden even when our disable directives don't take.
+ // 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. All tag spellings handled in parallel.
+ const STRIP_TAGS = [...TOOL_TAG_SPELLINGS, 'think', 'thinking', 'reasoning'];
+ const OPEN_TAGS = STRIP_TAGS.map((s) => `<${s}>`);
+ const CLOSE_TAGS = STRIP_TAGS.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 {
- out += data;
+ 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 = '';
}
- data = '';
- } else {
- const i = data.indexOf(activeClose);
- if (i !== -1) {
- data = data.slice(i + activeClose.length);
- activeClose = null;
- continue;
+ }
+ if (out) opts.onDelta?.(out);
+ };
+
+ while (true) {
+ const { value, done } = await reader.read();
+ if (done) break;
+ buffer += decoder.decode(value, { stream: true });
+
+ let idx;
+ while ((idx = buffer.indexOf('\n')) >= 0) {
+ const line = buffer.slice(0, idx).trim();
+ buffer = buffer.slice(idx + 1);
+ if (!line.startsWith('data:')) continue;
+ const payload = line.slice(5).trim();
+ if (payload === '[DONE]') {
+ return finalizeReturn();
+ }
+ // Malformed SSE frames (proxy keep-alive, truncated write) would otherwise
+ // abort the whole turn; skip the line and keep streaming.
+ let obj;
+ try { obj = JSON.parse(payload); } catch { continue; }
+ const choice = obj?.choices?.[0];
+ if (choice?.finish_reason) finishReason = choice.finish_reason;
+ const delta = choice?.delta || {};
+ if (delta.content) {
+ if (ttfbMs === null) ttfbMs = Date.now() - started;
+ text += delta.content;
+ forwardClean(delta.content);
+ }
+ for (const tc of delta.tool_calls || []) {
+ const frag = toolCallFrags.get(tc.index) || {
+ index: tc.index,
+ id: '',
+ type: 'function',
+ function: { name: '', arguments: '' },
+ };
+ if (tc.id) frag.id = tc.id;
+ if (tc.type) frag.type = tc.type;
+ // `name` is sent once per tool call per the OpenAI spec; set-once
+ // rather than concatenate so a split fragment can't produce garbage.
+ if (tc.function?.name && !frag.function.name) frag.function.name = tc.function.name;
+ if (tc.function?.arguments) frag.function.arguments += tc.function.arguments;
+ toolCallFrags.set(tc.index, frag);
}
- const hold = longestPrefixHold(data, [activeClose]);
- if (hold) tailHold = data.slice(data.length - hold);
- data = '';
}
}
- if (out) opts.onDelta?.(out);
- };
+ return finalizeReturn();
- while (true) {
- const { value, done } = await reader.read();
- if (done) break;
- buffer += decoder.decode(value, { stream: true });
-
- let idx;
- while ((idx = buffer.indexOf('\n')) >= 0) {
- const line = buffer.slice(0, idx).trim();
- buffer = buffer.slice(idx + 1);
- if (!line.startsWith('data:')) continue;
- const payload = line.slice(5).trim();
- if (payload === '[DONE]') {
- return finalizeReturn();
- }
- // Malformed SSE frames (proxy keep-alive, truncated write) would otherwise
- // abort the whole turn; skip the line and keep streaming.
- let obj;
- try { obj = JSON.parse(payload); } catch { continue; }
- const choice = obj?.choices?.[0];
- if (choice?.finish_reason) finishReason = choice.finish_reason;
- const delta = choice?.delta || {};
- if (delta.content) {
- if (ttfbMs === null) ttfbMs = Date.now() - started;
- text += delta.content;
- forwardClean(delta.content);
- }
- for (const tc of delta.tool_calls || []) {
- const frag = toolCallFrags.get(tc.index) || {
- index: tc.index,
- id: '',
- type: 'function',
- function: { name: '', arguments: '' },
- };
- if (tc.id) frag.id = tc.id;
- if (tc.type) frag.type = tc.type;
- // `name` is sent once per tool call per the OpenAI spec; set-once
- // rather than concatenate so a split fragment can't produce garbage.
- if (tc.function?.name && !frag.function.name) frag.function.name = tc.function.name;
- if (tc.function?.arguments) frag.function.arguments += tc.function.arguments;
- toolCallFrags.set(tc.index, frag);
- }
+ 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;
+ // Strip any `<think>...`/`<reasoning>...` blocks from the canonical text
+ // too — the streaming stripper kept them out of TTS, but they'd still
+ // pollute conversation history and the assistant.content we persist.
+ const finalText = stripReasoningTags(cleanedText);
+ return {
+ text: finalText,
+ 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;
- // Strip any `<think>...`/`<reasoning>...` blocks from the canonical text
- // too — the streaming stripper kept them out of TTS, but they'd still
- // pollute conversation history and the assistant.content we persist.
- const finalText = stripReasoningTags(cleanedText);
- return {
- text: finalText,
- toolCalls,
- model,
- ttfbMs,
- totalMs: Date.now() - started,
- finishReason,
- };
- }
+ })();
+
+ return requestPromise
+ .catch((err) => {
+ if (timedOut) throw new Error(VOICE_LLM_TIMEOUT_MESSAGE);
+ throw err;
+ })
+ .finally(() => {
+ clearTimeout(timeoutId);
+ requestController.signal.removeEventListener('abort', cancelReader);
+ if (opts.signal && onExternalAbort) {
+ opts.signal.removeEventListener('abort', onExternalAbort);
+ }
+ });
};
const REASONING_TAG_RE = /<(think|thinking|reasoning)>[\s\S]*?(?:<\/\1>|$)/gi;
diff --git a/server/services/voice/llm.test.js b/server/services/voice/llm.test.js
index a89a970d78..c03a666348 100644
--- a/server/services/voice/llm.test.js
+++ b/server/services/voice/llm.test.js
@@ -8,6 +8,7 @@ import { getProviderById } from '../providers.js';
import {
extractInlineToolCalls, isToolCapable, isReasoningModel,
TOOL_CAPABLE_PATTERNS, REASONING_PATTERNS, resolveLlmEndpoint,
+ streamChat, VOICE_LLM_TIMEOUT_MS, VOICE_LLM_TIMEOUT_MESSAGE,
} from './llm.js';
describe('extractInlineToolCalls', () => {
@@ -267,3 +268,128 @@ describe('resolveLlmEndpoint', () => {
expect(ep.apiBase).toBe('http://localhost:1234/v1');
});
});
+
+describe('streamChat request lifecycle', () => {
+ let fetchMock;
+ let chatSignal;
+
+ const provider = {
+ id: 'test-provider',
+ type: 'api',
+ endpoint: 'https://example.com/v1',
+ apiKey: '',
+ defaultModel: 'test-model',
+ name: 'Test Provider',
+ };
+
+ const modelResponse = () => Promise.resolve({
+ ok: true,
+ json: async () => ({ data: [{ id: 'test-model' }] }),
+ });
+
+ const pendingUntilAbort = (signal) => new Promise((_, reject) => {
+ const abort = () => reject(signal.reason);
+ if (signal.aborted) abort();
+ else signal.addEventListener('abort', abort, { once: true });
+ });
+
+ const installFetch = (chatFetch) => {
+ fetchMock.mockImplementation((url, options = {}) => {
+ if (url.endsWith('/models')) return modelResponse();
+ chatSignal = options.signal;
+ return chatFetch(options);
+ });
+ };
+
+ beforeEach(() => {
+ vi.useFakeTimers();
+ getProviderById.mockReset();
+ getProviderById.mockResolvedValue(provider);
+ fetchMock = vi.fn();
+ vi.stubGlobal('fetch', fetchMock);
+ });
+
+ afterEach(() => {
+ vi.useRealTimers();
+ vi.unstubAllGlobals();
+ });
+
+ it('aborts a provider request that never returns headers', async () => {
+ installFetch(({ signal }) => pendingUntilAbort(signal));
+
+ const result = streamChat([], { provider: 'test-provider', model: 'test-model' });
+ const rejection = expect(result).rejects.toThrow(VOICE_LLM_TIMEOUT_MESSAGE);
+ await vi.advanceTimersByTimeAsync(VOICE_LLM_TIMEOUT_MS);
+
+ await rejection;
+ expect(chatSignal.aborted).toBe(true);
+ expect(fetchMock).toHaveBeenCalledTimes(2);
+ });
+
+ it('aborts a provider stream that stops yielding SSE data', async () => {
+ const reader = {
+ read: vi.fn(({ signal } = {}) => pendingUntilAbort(signal || chatSignal)),
+ cancel: vi.fn(),
+ };
+ installFetch(({ signal }) => Promise.resolve({
+ ok: true,
+ status: 200,
+ body: { getReader: () => reader },
+ }));
+
+ const result = streamChat([], { provider: 'test-provider', model: 'test-model' });
+ await vi.waitFor(() => expect(reader.read).toHaveBeenCalledTimes(1));
+ const rejection = expect(result).rejects.toThrow(VOICE_LLM_TIMEOUT_MESSAGE);
+ await vi.advanceTimersByTimeAsync(VOICE_LLM_TIMEOUT_MS);
+
+ await rejection;
+ expect(chatSignal.aborted).toBe(true);
+ expect(reader.cancel).toHaveBeenCalledTimes(1);
+ });
+
+ it('clears the deadline and external abort listener after a successful stream', async () => {
+ const external = new AbortController();
+ const chunks = [
+ { value: new TextEncoder().encode('data: {"choices":[{"delta":{"content":"Hello"}}]}\n\n'), done: false },
+ { value: new TextEncoder().encode('data: [DONE]\n\n'), done: false },
+ ];
+ const reader = { read: vi.fn(async () => chunks.shift() || { value: undefined, done: true }) };
+ installFetch(() => Promise.resolve({ ok: true, status: 200, body: { getReader: () => reader } }));
+
+ await expect(streamChat([], {
+ provider: 'test-provider', model: 'test-model', signal: external.signal,
+ })).resolves.toMatchObject({ text: 'Hello', model: 'test-model' });
+
+ expect(chatSignal.aborted).toBe(false);
+ external.abort();
+ await vi.advanceTimersByTimeAsync(VOICE_LLM_TIMEOUT_MS);
+ expect(chatSignal.aborted).toBe(false);
+ });
+
+ it('clears the deadline after a provider failure', async () => {
+ const providerError = new Error('provider unavailable');
+ installFetch(() => Promise.reject(providerError));
+
+ await expect(streamChat([], { provider: 'test-provider', model: 'test-model' }))
+ .rejects.toBe(providerError);
+
+ expect(chatSignal.aborted).toBe(false);
+ await vi.advanceTimersByTimeAsync(VOICE_LLM_TIMEOUT_MS);
+ expect(chatSignal.aborted).toBe(false);
+ });
+
+ it('preserves an explicit caller cancellation instead of reporting a timeout', async () => {
+ const external = new AbortController();
+ installFetch(({ signal }) => pendingUntilAbort(signal));
+
+ const result = streamChat([], {
+ provider: 'test-provider', model: 'test-model', signal: external.signal,
+ });
+ await vi.waitFor(() => expect(chatSignal).toBeInstanceOf(AbortSignal));
+ external.abort();
+
+ await expect(result).rejects.toMatchObject({ name: 'AbortError' });
+ expect(chatSignal.aborted).toBe(true);
+ await vi.advanceTimersByTimeAsync(VOICE_LLM_TIMEOUT_MS);
+ });
+});
diff --git a/server/sockets/voice.test.js b/server/sockets/voice.test.js
index aa6d6fbdc9..9ce0c1ec79 100644
--- a/server/sockets/voice.test.js
+++ b/server/sockets/voice.test.js
@@ -226,6 +226,30 @@ describe('voice:text validation', () => {
});
});
+describe('voice:text turn recovery', () => {
+ afterEach(() => runTurn.mockClear());
+
+ it('emits voice:error and voice:idle when the LLM deadline expires', async () => {
+ const socket = makeFakeSocket();
+ registerVoiceHandlers(socket);
+ runTurn.mockImplementationOnce(async () => {
+ throw new Error('Voice LLM request timed out');
+ });
+
+ socket.fire('voice:text', { text: 'hello' });
+ await vi.waitFor(() => expect(socket.emitted.filter((e) => e.event === 'voice:idle')).toHaveLength(1));
+
+ expect(socket.emitted.filter((e) => e.event === 'voice:error')).toEqual([{
+ event: 'voice:error',
+ payload: { stage: 'text', message: 'Voice LLM request timed out' },
+ }]);
+ expect(socket.emitted.filter((e) => e.event === 'voice:idle')).toEqual([{
+ event: 'voice:idle',
+ payload: { reason: 'error' },
+ }]);
+ });
+});
+
describe('voice:output single-recipient wiring', () => {
beforeEach(() => __resetVoiceOutput());