Voice-to-text dictation app with local (Nvidia Parakeet/Whisper) and cloud models (BYOK). Privacy-first and available cross-platform.
JavaScript aianthropiccross-platformgeminigroqlinuxmacosnvidiaopen-sourceopenaiparakeetspeech-to-texttranscribewhisperwindows
fix(chat): use an idle timeout for streaming replies (#2651)
Atharva Vichare4e15c3860ec0
diff --git a/src/helpers/llmRequestTimeout.js b/src/helpers/llmRequestTimeout.jsindex 1c26cda62..875be88c3 100644--- a/src/helpers/llmRequestTimeout.js+++ b/src/helpers/llmRequestTimeout.js@@ -1,14 +1,16 @@const LLM_REQUEST_TIMEOUT_SECONDS = 30;const LLM_STREAMING_TIMEOUT_SECONDS = 60;// Note formatting sends a whole transcript through a model that may reason at-// length before writing: a 2,000-word meeting through GPT-5.6 Terra runs well-// past 30 seconds. OpenAI's own SDK defaults to a 10-minute request timeout.+// length before writing (a 2,000-word meeting through GPT-5.6 Terra runs well+// past 30 seconds), and a local model may prefill (a LAN server may also load+// the model) for minutes before its first streamed byte. OpenAI's own SDK+// defaults to a 10-minute request timeout.const LLM_LONG_TASK_TIMEOUT_SECONDS = 600;export const LLM_REQUEST_TIMEOUT_CODE = "LLM_REQUEST_TIMEOUT";/**- * Client-side deadline for one LLM request.+ * Client-side deadline for a non-streaming LLM request, or idle timeout for a stream.* @param {{ streaming?: boolean, scope?: string }} [options] `scope` is the* request's inference scope; note formatting gets the long deadline.*/@@ -17,6 +19,15 @@ export function getLlmRequestTimeoutSeconds({ streaming = false, scope } = {}) {return scope === "noteFormatting" ? LLM_LONG_TASK_TIMEOUT_SECONDS : LLM_REQUEST_TIMEOUT_SECONDS;}+/**+ * Local and self-hosted models can spend minutes loading or prefilling before+ * sending any bytes. Once bytes arrive, the regular streaming idle timeout applies.+ * @param {{ selfHosted?: boolean }} [options] Includes the built-in local server.+ */+export function getLlmStreamingFirstByteTimeoutSeconds({ selfHosted = false } = {}) {+ return selfHosted ? LLM_LONG_TASK_TIMEOUT_SECONDS : LLM_STREAMING_TIMEOUT_SECONDS;+}+/** The coded error a request raises when its client-side deadline expires; createApiRetryStrategy never retries it. */export function llmRequestTimeoutError(timeoutSeconds) {return Object.assign(new Error(`Request timed out after ${timeoutSeconds}s`), {diff --git a/src/services/ReasoningService.ts b/src/services/ReasoningService.tsindex 47577410b..7af5f0cec 100644--- a/src/services/ReasoningService.ts+++ b/src/services/ReasoningService.ts@@ -17,6 +17,7 @@ import { wrapCleanupTranscript } from "../config/prompts";import { stripThinkingTags } from "../helpers/stripThinking.js";import {getLlmRequestTimeoutSeconds,+ getLlmStreamingFirstByteTimeoutSeconds,llmRequestTimeoutError,} from "../helpers/llmRequestTimeout.js";import { streamText, stepCountIs } from "ai";@@ -672,11 +673,19 @@ class ReasoningService extends BaseReasoningService {const timeoutSeconds = getLlmRequestTimeoutSeconds({ streaming: true });let timeoutTriggered = false;- const timeoutId = setTimeout(() => {+ let timeoutId: ReturnType<typeof setTimeout>;+ const resetTimeout = (seconds: number) => {+ clearTimeout(timeoutId);if (abortController.signal.aborted) return;- timeoutTriggered = true;- abortController.abort();- }, timeoutSeconds * 1000);+ timeoutId = setTimeout(() => {+ if (abortController.signal.aborted) return;+ timeoutTriggered = true;+ abortController.abort();+ }, seconds * 1000);+ };+ resetTimeout(+ getLlmStreamingFirstByteTimeoutSeconds({ selfHosted: isLocalProvider || isLanChat })+ );const selfHostedErrorContext = {selfHosted: true,@@ -751,6 +760,10 @@ class ReasoningService extends BaseReasoningService {const { done, value } = await reader.read();if (done) break;+ // Reset on bytes, including keepalives, partial SSE frames and hidden+ // reasoning. A reply may stream for much longer than the idle timeout.+ if (value.byteLength > 0) resetTimeout(timeoutSeconds);+buffer += decoder.decode(value, { stream: true });const lines = buffer.split("\n");buffer = lines.pop() || "";diff --git a/test/helpers/llmRequestTimeout.test.js b/test/helpers/llmRequestTimeout.test.jsindex e825bfbc0..2e14941bb 100644--- a/test/helpers/llmRequestTimeout.test.js+++ b/test/helpers/llmRequestTimeout.test.js@@ -11,7 +11,7 @@ test("non-streaming LLM requests use the fixed 30-second timeout", async () => {assert.equal(getLlmRequestTimeoutSeconds({ scope: "dictationCleanup" }), 30);});-test("streaming LLM requests keep their fixed 60-second timeout", async () => {+test("streaming LLM requests use a 60-second idle timeout", async () => {const { getLlmRequestTimeoutSeconds } = await load();assert.equal(typeof getLlmRequestTimeoutSeconds, "function");@@ -20,6 +20,13 @@ test("streaming LLM requests keep their fixed 60-second timeout", async () => {assert.equal(getLlmRequestTimeoutSeconds({ streaming: true, scope: "noteFormatting" }), 60);});+test("local and self-hosted streams get a longer wait for the first bytes", async () => {+ const { getLlmStreamingFirstByteTimeoutSeconds } = await load();++ assert.equal(getLlmStreamingFirstByteTimeoutSeconds(), 60);+ assert.equal(getLlmStreamingFirstByteTimeoutSeconds({ selfHosted: true }), 600);+});+test("note formatting gets a long deadline, since a whole transcript can take minutes to reason over", async () => {const { getLlmRequestTimeoutSeconds } = await load();diff --git a/test/services/reasoningServiceStreamingThink.test.js b/test/services/reasoningServiceStreamingThink.test.jsindex 2ce7c96f0..9e4931949 100644--- a/test/services/reasoningServiceStreamingThink.test.js+++ b/test/services/reasoningServiceStreamingThink.test.js@@ -445,6 +445,8 @@ test("a timeout-owned abort during raw response reading remains a timeout error"globalThis.fetch = async (_input, init) => {const body = new ReadableStream({start(controller) {+ // The first bytes switch from the startup allowance to the idle timeout.+ controller.enqueue(new TextEncoder().encode(": keepalive\n\n"));init?.signal?.addEventListener("abort",() => controller.error(new DOMException("aborted", "AbortError")),diff --git a/test/services/reasoningServiceStreamingTimeout.test.js b/test/services/reasoningServiceStreamingTimeout.test.jsnew file mode 100644index 000000000..5b1dcd855--- /dev/null+++ b/test/services/reasoningServiceStreamingTimeout.test.js@@ -0,0 +1,183 @@+const test = require("node:test");+const assert = require("node:assert/strict");+const { createRendererServer, installBrowserGlobals } = require("../lib/rendererTestHarness");++const flush = () => new Promise((resolve) => setImmediate(resolve));+const contentEvent = (content) =>+ `data: ${JSON.stringify({ choices: [{ delta: { content } }] })}\n\n`;++async function startStream(t, provider, { holdHeaders = false } = {}) {+ // Restore real timers before Vite's server-close hook runs.+ t.after(() => t.mock.timers.reset());+ installBrowserGlobals(t, {+ window: {+ electronAPI: { llamaServerStart: async () => ({ success: true, port: 11434 }) },+ },+ });+ const vite = await createRendererServer(t);+ const service = (await vite.ssrLoadModule("/services/ReasoningService.ts")).default;+ const { usePolicyStore } = await vite.ssrLoadModule("/stores/policyStore.ts");+ usePolicyStore.setState({ status: "unmanaged", policy: null });+ t.after(() => service.destroy());+ t.mock.timers.enable({ apis: ["setTimeout"] });++ let signal;+ let controller;+ let sendHeaders;+ let fetchStarted;+ const started = new Promise((resolve) => (fetchStarted = resolve));+ const body = new ReadableStream({+ start(streamController) {+ controller = streamController;+ },+ });+ const response = new Response(body, { headers: { "content-type": "text/event-stream" } });+ t.mock.method(globalThis, "fetch", async (_url, init) => {+ signal = init.signal;+ const pendingHeaders = new Promise((resolve, reject) => {+ sendHeaders = () => resolve(response);+ signal.addEventListener(+ "abort",+ () => {+ const error = new DOMException("aborted", "AbortError");+ controller.error(error);+ reject(error);+ },+ { once: true }+ );+ });+ if (!holdHeaders) sendHeaders();+ fetchStarted();+ return pendingHeaders;+ });++ const chunks = [];+ // Exercise the no-tools Chat path that delegates to raw streaming.+ const outcome = (async () => {+ for await (const chunk of service.processTextStreamingAI(+ [{ role: "user", content: "Give a long answer." }],+ "qwen3-1.7b-q4_k_m",+ provider,+ {+ systemPrompt: "Answer the user.",+ ...(provider === "lan" ? { lanUrl: "http://127.0.0.1:11434/v1" } : {}),+ }+ )) {+ chunks.push(chunk);+ }+ })().then(+ () => ({ chunks }),+ (error) => ({ error, chunks })+ );+ await Promise.race([+ started,+ outcome.then(({ error }) => {+ throw error || new Error("stream finished before fetch started");+ }),+ ]);+ await flush();+ return {+ service,+ signal,+ body,+ chunks,+ outcome,+ sendHeaders: () => sendHeaders(),+ send: async (data) => {+ controller.enqueue(new TextEncoder().encode(data));+ await flush();+ },+ finish: async (withDone = true) => {+ if (withDone) controller.enqueue(new TextEncoder().encode("data: [DONE]\n\n"));+ controller.close();+ return outcome;+ },+ };+}++for (const provider of ["local", "lan"]) {+ test(`${provider} chat keeps streaming beyond 60 seconds while bytes arrive`, async (t) => {+ const stream = await startStream(t, provider);+ // 14 × 45 s outlasts the 600 s startup allowance, so only the idle reset keeps it alive.+ for (let i = 0; i < 14; i++) {+ t.mock.timers.tick(45_000);+ assert.equal(stream.signal.aborted, false);+ await stream.send(contentEvent(`Part ${i}. `));+ }+ const result = await stream.finish();+ assert.equal(result.error, undefined);+ assert.equal(result.chunks.filter((chunk) => chunk.type === "content").length, 14);+ assert.deepEqual(result.chunks.at(-1), { type: "done", finishReason: "stop" });+ t.mock.timers.tick(600_000);+ assert.equal(stream.signal.aborted, false, "completion must clear the idle timer");+ assert.equal(stream.body.locked, false);+ });++ for (const holdHeaders of [false, true]) {+ test(`${provider} chat allows slow prefill ${holdHeaders ? "before" : "after"} response headers`, async (t) => {+ const stream = await startStream(t, provider, { holdHeaders });+ t.mock.timers.tick(120_000);+ assert.equal(stream.signal.aborted, false, "self-hosted prefill may take over a minute");+ stream.sendHeaders();+ await stream.send(contentEvent("Answer"));+ assert.equal((await stream.finish()).error, undefined);+ });+ }++ test(`${provider} chat aborts after 60 seconds without bytes following stream activity`, async (t) => {+ const stream = await startStream(t, provider);+ await stream.send(contentEvent("First"));+ t.mock.timers.tick(45_000);+ await stream.send(contentEvent("Second"));+ t.mock.timers.tick(59_999);+ assert.equal(stream.signal.aborted, false);+ t.mock.timers.tick(1);+ const { error } = await stream.outcome;+ assert.equal(stream.signal.aborted, true);+ if (provider === "lan") {+ assert.equal(error.code, "PROVIDER_TIMEOUT");+ assert.equal(error.messageKey, "providerErrors.selfHosted.timeout");+ } else {+ assert.equal(error.message, "Streaming request timed out");+ }+ assert.equal(stream.body.locked, false);+ });+}++test("stream activity includes split SSE lines, keepalives and filtered thinking", async (t) => {+ const stream = await startStream(t, "local");+ // The first bytes arrive at 595 s, so each later gap only survives through the idle reset.+ t.mock.timers.tick(550_000);+ for (const data of [+ ": keepalive\n\n",+ "data: ",+ '{"choices":[',+ '{"delta":{"content":"<think>hidden"}}]}\n\n',+ ]) {+ t.mock.timers.tick(45_000);+ assert.equal(stream.signal.aborted, false);+ await stream.send(data);+ }+ assert.deepEqual(stream.chunks, [], "hidden reasoning is activity even without visible output");+ t.mock.timers.tick(45_000);+ await stream.send(contentEvent("</think>Answer"));+ assert.equal((await stream.finish(false)).error, undefined);+ t.mock.timers.tick(600_000);+ assert.equal(stream.signal.aborted, false, "EOF must clear the idle timer");+});++test("a local model that never sends bytes still times out after the startup allowance", async (t) => {+ const stream = await startStream(t, "local", { holdHeaders: true });+ t.mock.timers.tick(599_999);+ assert.equal(stream.signal.aborted, false);+ t.mock.timers.tick(1);+ assert.equal((await stream.outcome).error.message, "Streaming request timed out");+});++test("cancelling a raw stream ends normally", async (t) => {+ const stream = await startStream(t, "local");+ await stream.send(contentEvent("Partial answer"));+ stream.service.cancelActiveStream();+ assert.equal((await stream.outcome).error, undefined);+ assert.equal(stream.body.locked, false);+});