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
fix: stop stale voice TTS after LLM timeout (#5497)
[._.]/ Adam Eivy3c4097b8c6f6
diff --git a/server/services/voice/llm.js b/server/services/voice/llm.jsindex b0566e95ac..db31c3df77 100644--- a/server/services/voice/llm.js+++ b/server/services/voice/llm.js@@ -372,6 +372,11 @@ export const streamChat = async (messages, opts = {}) => {}const timeoutId = setTimeout(() => {timedOut = true;+ try {+ opts.onTimeout?.();+ } catch (err) {+ console.error(`🤖 voice.llm.timeout_hook failed: ${err.message}`);+ }requestController.abort();}, VOICE_LLM_TIMEOUT_MS);@@ -393,6 +398,12 @@ export const streamChat = async (messages, opts = {}) => {const decoder = new TextDecoder();reader = res.body.getReader();if (requestController.signal.aborted) cancelReader();+ const throwIfAborted = () => {+ if (timedOut) throw new Error(VOICE_LLM_TIMEOUT_MESSAGE);+ if (requestController.signal.aborted) {+ throw requestController.signal.reason || new Error('The voice LLM request was aborted');+ }+ };let buffer = '';let text = '';let ttfbMs = null;@@ -473,7 +484,7 @@ export const streamChat = async (messages, opts = {}) => {while (true) {const { value, done } = await reader.read();- if (timedOut) throw new Error(VOICE_LLM_TIMEOUT_MESSAGE);+ throwIfAborted();if (done) break;buffer += decoder.decode(value, { stream: true });@@ -484,6 +495,7 @@ export const streamChat = async (messages, opts = {}) => {if (!line.startsWith('data:')) continue;const payload = line.slice(5).trim();if (payload === '[DONE]') {+ throwIfAborted();return finalizeReturn();}// Malformed SSE frames (proxy keep-alive, truncated write) would otherwise@@ -497,6 +509,7 @@ export const streamChat = async (messages, opts = {}) => {if (ttfbMs === null) ttfbMs = Date.now() - started;text += delta.content;forwardClean(delta.content);+ throwIfAborted();}for (const tc of delta.tool_calls || []) {const frag = toolCallFrags.get(tc.index) || {diff --git a/server/services/voice/llm.test.js b/server/services/voice/llm.test.jsindex 4408d72de0..74e3af2bdb 100644--- a/server/services/voice/llm.test.js+++ b/server/services/voice/llm.test.js@@ -316,12 +316,16 @@ describe('streamChat request lifecycle', () => {it('aborts a provider request that never returns headers', async () => {installFetch(({ signal }) => pendingUntilAbort(signal));+ const onTimeout = vi.fn();- const result = streamChat([], { provider: 'test-provider', model: 'test-model' });+ const result = streamChat([], {+ provider: 'test-provider', model: 'test-model', onTimeout,+ });const rejection = expect(result).rejects.toThrow(VOICE_LLM_TIMEOUT_MESSAGE);await vi.advanceTimersByTimeAsync(VOICE_LLM_TIMEOUT_MS);await rejection;+ expect(onTimeout).toHaveBeenCalledTimes(1);expect(chatSignal.aborted).toBe(true);expect(fetchMock).toHaveBeenCalledTimes(2);});@@ -351,6 +355,35 @@ describe('streamChat request lifecycle', () => {expect(reader.cancel).toHaveBeenCalledTimes(1);});+ it('preserves explicit cancellation when an active reader closes as done', async () => {+ let releaseRead;+ const reader = {+ read: vi.fn(() => new Promise((resolve) => { releaseRead = resolve; })),+ cancel: vi.fn(() => {+ releaseRead?.({ value: undefined, done: true });+ return Promise.resolve();+ }),+ };+ installFetch(() => Promise.resolve({+ ok: true,+ status: 200,+ body: { getReader: () => reader },+ }));++ const external = new AbortController();+ const result = streamChat([], {+ provider: 'test-provider', model: 'test-model', signal: external.signal,+ });+ await vi.waitFor(() => expect(reader.read).toHaveBeenCalledTimes(1));+ const rejection = expect(result).rejects.toMatchObject({ name: 'AbortError' });+ external.abort();++ await rejection;+ expect(chatSignal.aborted).toBe(true);+ expect(reader.cancel).toHaveBeenCalledTimes(1);+ await vi.advanceTimersByTimeAsync(VOICE_LLM_TIMEOUT_MS);+ });+it('clears the deadline and external abort listener after a successful stream', async () => {const external = new AbortController();const chunks = [diff --git a/server/services/voice/pipeline.js b/server/services/voice/pipeline.jsindex 1b28696081..6025189b2b 100644--- a/server/services/voice/pipeline.js+++ b/server/services/voice/pipeline.js@@ -14,6 +14,7 @@ import { getToolSpecsForIntent, classifyIntent, dispatchTool, getAllToolNames, Uimport { isEchoOfRecentTts, rememberTtsSentence } from './echo.js';import { appendJournal, getToday } from '../brainJournal.js';import { resolvePending, isExpired } from './confirmGate.js';+import { anyAbortSignal } from '../../lib/requestAbort.js';// getRelevantMemories is imported lazily inside buildMemoryContext — it only// runs for retrieval-shaped turns, so keep its memory-backend + embeddings// dependency graph out of voice startup / non-retrieval turns (same rationale@@ -610,13 +611,18 @@ export const runTurn = async ({ audio, text, mimeType, source, history = [], emilet pending = '';const ttsTimings = [];let ttsIdx = 0;+ // Keep TTS cancellation coupled to the turn, while retaining a separate+ // deadline path so a timed-out LLM can stop queued audio without making the+ // socket mistake the timeout for a user cancellation.+ const ttsController = new AbortController();+ const ttsSignal = anyAbortSignal([signal, ttsController.signal]);const speak = async (sentence) => {- if (signal?.aborted || !sentence) return;+ if (ttsSignal?.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;+ const { wav, latencyMs } = await synthesize(sentence, { signal: ttsSignal });+ if (ttsSignal?.aborted) return;ttsTimings.push(latencyMs);tlog(`tts.done #${i} ${latencyMs}ms synth+queue=${Date.now() - t0}ms`);// Track what we just said so the next inbound transcript can be checked@@ -636,7 +642,7 @@ export const runTurn = async ({ audio, text, mimeType, source, history = [], emi// Barge-in aborts the turn mid-synthesis — Kokoro throws Error('aborted')// and Piper rejects 'piper synthesis aborted'. That's expected, not a// real failure, so don't surface it as voice:error.- if (signal?.aborted || /aborted/i.test(err?.message || '')) return;+ if (ttsSignal?.aborted || /aborted/i.test(err?.message || '')) return;emit('voice:error', { stage: 'tts', message: err.message });});}@@ -663,6 +669,7 @@ export const runTurn = async ({ audio, text, mimeType, source, history = [], emiprovider: cfg.llm.provider,model: cfg.llm.model,signal,+ onTimeout: () => ttsController.abort(),tools: toolSpecs,tag: turnId,onDelta: (delta) => {diff --git a/server/services/voice/pipelineTimeout.test.js b/server/services/voice/pipelineTimeout.test.jsnew file mode 100644index 0000000000..a78e7357a3--- /dev/null+++ b/server/services/voice/pipelineTimeout.test.js@@ -0,0 +1,62 @@+import { describe, it, expect, vi } from 'vitest';++const mocks = vi.hoisted(() => ({+ getVoiceConfig: vi.fn(async () => ({+ enabled: true,+ llm: {+ model: 'test-model',+ provider: 'test-provider',+ usePersonality: false,+ systemPrompt: 'sys',+ tools: { enabled: false, maxIterations: 1 },+ },+ })),+ synthesize: vi.fn(async (text) => ({ wav: Buffer.alloc(8), latencyMs: 1, _text: text })),+ streamChat: vi.fn(),+}));++vi.mock('./config.js', () => ({ getVoiceConfig: mocks.getVoiceConfig }));+vi.mock('./stt.js', () => ({ transcribe: vi.fn() }));+vi.mock('./tts.js', () => ({ synthesize: (...args) => mocks.synthesize(...args) }));+vi.mock('./llm.js', () => ({ streamChat: (...args) => mocks.streamChat(...args) }));+vi.mock('./tools.js', () => ({+ getToolSpecsForIntent: () => ({ specs: undefined, activeGroups: new Set() }),+ classifyIntent: () => new Set(),+ dispatchTool: vi.fn(),+ getAllToolNames: () => [],+ UI_KINDS: ['tab', 'button', 'link', 'input', 'textarea', 'select', 'checkbox', 'radio'],+}));+vi.mock('./echo.js', () => ({+ isEchoOfRecentTts: () => false,+ rememberTtsSentence: vi.fn(),+}));+vi.mock('../brainJournal.js', () => ({ appendJournal: vi.fn(), getToday: vi.fn() }));+vi.mock('./confirmGate.js', () => ({ resolvePending: vi.fn(), isExpired: vi.fn() }));++const { runTurn } = await import('./pipeline.js');++describe('runTurn LLM timeout recovery', () => {+ it('cancels queued TTS without converting the timeout into user cancellation', async () => {+ mocks.synthesize.mockClear();+ mocks.streamChat.mockImplementationOnce(async (_messages, { onDelta, onTimeout }) => {+ onDelta('The provider stalled.');+ onTimeout();+ throw new Error('Voice LLM request timed out');+ });++ const events = [];+ const signal = new AbortController().signal;+ const turn = runTurn({+ text: 'hello',+ history: [],+ emit: (event, payload) => events.push({ event, payload }),+ signal,+ state: {},+ });++ await expect(turn).rejects.toThrow('Voice LLM request timed out');+ await vi.waitFor(() => expect(mocks.synthesize).not.toHaveBeenCalled());+ expect(signal.aborted).toBe(false);+ expect(events.some(({ event }) => event === 'voice:tts:audio')).toBe(false);+ });+});