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

refactor: route Ask through shared OpenAI stream (#5618)

Adam Eivy14e3658b654c
diff --git a/server/lib/README.md b/server/lib/README.md
index 5979a65f30..64fb1010ea 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -182,7 +182,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `sglangQwenRecipe.js` | The `sglang serve` launch line PortOS owns, per NVIDIA card class. `buildSglangQwenRecipe({hw, contextLength, ssmDtype, spec, radixStrategy, host, port})` → `{image, modelName, modelPath, cell, mambaRatio, stateSlots, flags, env}`, and `sglangComposeYaml(recipe)` renders the `docker-compose.yml` from it (one source of truth; a test pins the doc against it). `mambaFullMemoryRatio(...)` derives `--mamba-full-memory-ratio` from the cookbook formula `(S + D) × state_bytes / (L × kv_bytes_per_token)` — load-bearing, because the cookbook default `0.9` under-sizes the GDN state pool at CoS prompt lengths and silently clamps `max_running_requests`. Both Qwen parsers (`--reasoning-parser qwen3`, `--tool-call-parser qwen3_coder` — NOT vLLM's `qwen3_xml`) are baked into every cell: getting them wrong fails silently, with the model emitting raw markup and the agent never calling a tool. `sglangCellForGpu(gpu)` maps a `cudaCapability.js` compute-cap row to a cell (SM 9.x → `h200`, SM ≥10 → `rtx6000`/`rtx5090` by VRAM, Ampere → `null`, which is a refusal: 24 GB stays on vLLM), and `sglangUnsupportedReason({platform, status, gpus})` is the prose for every no — never collapsing a probe `'unknown'` into "no GPU". Pure: no filesystem, no docker, no network. |
| `opencodeStream.js` | OpenCode's `--format json` event stream — ONE parser, shared by `services/localModelAgentBenchmark.js` (which wants chars/tokens) and `services/modelCapabilityTests.js` (which wants a readable transcript). `eventPart` (accepts the flat `{part}` and nested `{properties.part}` envelopes OpenCode has both used), `isToolEvent` / `eventText`, `parseAgentLine` / `parseAgentEvents` (blank and unparsable lines yield nothing rather than throwing), `formatAgentEvent` (one frame → a transcript line a person can read, with the path or command the tool acted on), and `summarizeOpenCodeEvents` (assistant chars, tool calls, and output tokens — `null`, never 0, when OpenCode reported no usage; tool ARGUMENTS are deliberately not counted as answer text). Pure. The runner that produces the stream is `services/opencodeTask.js`. |
| `openAiModelsProbe.js` | `probeOpenAiModels(baseUrl, { timeoutMs, apiKey })` → `{ reachable, models, error }` — the one `GET {base}/models` probe for the local OpenAI-compatible daemons, shared by `services/providerReadiness.js` and `services/llamaServerManager.js`. Distinguishes unreachable from reachable-but-unlistable (`models: null`) from up-with-nothing-loaded (`[]`), names the real transport failure via `describeFetchError` (undici reports every one as a bare `fetch failed`), and cancels an unread body on a non-OK response. `apiKey` attaches a Bearer header for a key-gated daemon (vLLM's compose stack), and a 401/403 answers `reachable: true` with `error: 'authentication required'` — a server that refused the request is definitively running, and calling it unreachable would send the user to start it again. Consolidated after the two copies drifted — one passed its timeout as a `timeout` key inside the fetch init object, where it is not an option, silently running a 500ms poll loop on the 15s default. |
-| `openAiChatStream.js` | `streamOpenAiChat({ endpoint, apiKey, model, messages, temperature, maxTokens, extraBody, signal, onChunk, onStats })` → the streamed text — one streaming `POST {base}/chat/completions` against any local OpenAI-compatible daemon; `streamOllamaChat(...)` is the assessment-only native `/api/chat` transport that preserves Ollama's exact eval counts and nanosecond timings. Also exports `buildMessages`, `parseStreamFrame`, `parseOllamaStreamFrame`, `normalizeUsage` (snake/camel/Ollama token-count keys → `{completionTokens, promptTokens}`, `null` = not reported), and `resolvePartialOutput`. Registering `onStats` on the OpenAI path asks for token counts; a daemon that rejects `stream_options` is retried once without it and remembered per endpoint. Sibling of `openAiModelsProbe.js`. Shared by `services/localLlmPlayground.js` (provider-backed runs with a `/runs` record) and its `runEndpointLlmTest` (a bare loopback daemon PortOS holds no provider record for, which is how `services/localModelAssessments.js` measures llama.cpp / MTPLX / vLLM). An abort mid-stream throws with `.partialOutput` carrying what already streamed. |
+| `openAiChatStream.js` | `iterateOpenAiChat(...)` → normalized async content/reasoning chunks and `streamOpenAiChat(...)` → the streamed text — one streaming `POST {base}/chat/completions` against any OpenAI-compatible endpoint; both own timeout/abort composition, retries, parsing, backpressure, and reader cleanup. `streamOllamaChat(...)` is the assessment-only native `/api/chat` transport that preserves Ollama's exact eval counts and nanosecond timings. Also exports `buildMessages`, `parseStreamFrame`, `parseOllamaStreamFrame`, `normalizeUsage` (snake/camel/Ollama token-count keys → `{completionTokens, promptTokens}`, `null` = not reported), and `resolvePartialOutput`. Registering `onStats` on the OpenAI path asks for token counts; a daemon that rejects `stream_options` is retried once without it and remembered per endpoint. Sibling of `openAiModelsProbe.js`. Shared by Ask (`services/askService.js`), `services/localLlmPlayground.js` (provider-backed runs with a `/runs` record), and its `runEndpointLlmTest` (a bare loopback daemon PortOS holds no provider record for, which is how `services/localModelAssessments.js` measures llama.cpp / MTPLX / vLLM). An abort mid-stream throws with `.partialOutput` carrying what already streamed. |
| `cliChildEnv.js` | The one place the AI-CLI child environment is composed, replacing the hand-rolled copy every spawn site carried — which made each env-level fix an N-file sweep (#3194). `buildCliChildEnv({ baseEnv, before, provider, model, cwd, extra, guard })` returns a COMPLETE env for `spawn`: filters the inherited base to runtime essentials/provider auth, then layers `baseEnv → before → Ollama-Claude defaults → provider.envVars → buildOpencodeEnvVars → extra`, pins `PWD` to `cwd`, strips `CLAUDECODE`, and (with `guard: true`) prepends the pm2 guard shim onto the final `PATH`. The Ollama-Claude layer raises Claude Code's default output ceiling to 65,536 tokens so a thinking-capable local model cannot finish its reasoning past the stock 32K ceiling and die before its final tool call; an explicit provider env value wins. `composeProviderEnv({ before, provider, model, extra })` returns just the ordered provider layers, for sites that build a DELTA someone else bases and spawns (the CoS runner payload, a shell-session overlay). The two slots are not interchangeable: `before` sits UNDER `provider.envVars` (forgeTokenEnv/claudeSettingsEnv, so a provider override still wins), `extra` sits OVER it (TERM/COLORTERM for a PTY). `cliChildEnv.test.js` asserts the composed order per call site and **discovers** any new site that hand-rolls the tuple instead of calling these — so the call-site list stays in the test, not in prose here. |
| `cliProviderArgs.js` | Per-CLI argv conventions (`buildCliArgs`) for stdin prompt delivery — dependency-light extraction from runner.js so out-of-process callers (autofixer) can import it. |
| `cliProviderRun.js` | One-shot CLI provider invocation (`pickCliProvider` + `runCliProviderPrompt`) — lightweight path for the autofixer + calendar MCP sync to honor the configured provider/model. |
diff --git a/server/lib/openAiChatStream.js b/server/lib/openAiChatStream.js
index 52478c69dd..a88a4e8e7b 100644
--- a/server/lib/openAiChatStream.js
+++ b/server/lib/openAiChatStream.js
@@ -8,7 +8,8 @@
* (llama.cpp, Ollama, LM Studio, MTPLX, vLLM) that share exactly one wire
* protocol and nothing else.
*
- * Two callers, deliberately:
+ * Three callers, deliberately:
+ * - `services/askService.js` — the Ask API's content-delta stream.
* - `services/localLlmPlayground.js` — a provider-backed run with a `/runs`
* record, for the backends PortOS configures as providers.
* - `services/localModelAssessments.js` — a measurement against a bare
@@ -197,8 +198,38 @@ export function buildMessages({ systemPrompt, prompt, images }) {
];
}
+/** Combine a caller abort with an optional whole-stream timeout. */
+function composeStreamSignal(signal, timeoutMs) {
+ const duration = Number.isFinite(timeoutMs) && timeoutMs > 0 ? timeoutMs : 0;
+ if (!duration) return { signal, cleanup: () => {} };
+
+ const timeoutController = new AbortController();
+ const timeoutId = setTimeout(() => timeoutController.abort(), duration);
+ let externalAbortHandler;
+ let requestSignal = timeoutController.signal;
+ if (signal) {
+ if (typeof AbortSignal !== 'undefined' && typeof AbortSignal.any === 'function') {
+ requestSignal = AbortSignal.any([timeoutController.signal, signal]);
+ } else {
+ externalAbortHandler = () => timeoutController.abort();
+ if (signal.aborted) timeoutController.abort();
+ else signal.addEventListener('abort', externalAbortHandler, { once: true });
+ }
+ }
+ return {
+ signal: requestSignal,
+ cleanup: () => {
+ clearTimeout(timeoutId);
+ if (externalAbortHandler) signal.removeEventListener('abort', externalAbortHandler);
+ },
+ };
+}
+
/**
- * Stream a chat completion and return the final text.
+ * Iterate normalized content/reasoning chunks from one OpenAI-compatible chat.
+ * The iterator owns request retries, SSE parsing, timeout/abort composition,
+ * reader cleanup, and backpressure: it does not read the next upstream chunk
+ * until its consumer asks for the next item.
*
* @param {object} options
* @param {string} options.endpoint OpenAI-compatible base ending in `/v1`
@@ -211,20 +242,13 @@ export function buildMessages({ systemPrompt, prompt, images }) {
* caller passes a backend-specific knob (Ollama's `num_ctx`) without this
* module growing a per-backend branch.
* @param {AbortSignal} [options.signal]
- * @param {(chunk: string, kind: 'content'|'reasoning') => any} [options.onChunk]
- * awaited, so a consumer's backpressure reaches the upstream read loop.
- * @param {(stats: object) => void} [options.onStats] registering one is what
- * asks the daemon for a terminal usage frame (`stream_options.include_usage`);
- * a daemon that rejects the key is retried once without it and remembered, so
- * no caller has to know which runtimes support it. Called exactly once, before
- * this resolves or throws, with `{ completionTokens, promptTokens, estimated }`.
- * Token counts are `null` when the daemon reported none AND nothing streamed
- * to estimate from — never 0, which would read as "generated nothing".
- * @returns {Promise<string>} the streamed text. Throws on transport/HTTP
- * failure; an abort mid-stream throws with `.partialOutput` carrying whatever
- * had already streamed.
+ * @param {number} [options.timeoutMs] abort the request and reader after this
+ * many milliseconds; the caller's signal remains independently effective.
+ * @param {(stats: object) => void} [options.onStats] registering one asks the
+ * daemon for a terminal usage frame (`stream_options.include_usage`).
+ * @returns {AsyncGenerator<{text:string,kind:'content'|'reasoning'}>}
*/
-export async function streamOpenAiChat({
+export async function* iterateOpenAiChat({
endpoint,
apiKey,
model,
@@ -233,9 +257,11 @@ export async function streamOpenAiChat({
maxTokens,
extraBody = {},
signal,
- onChunk,
+ timeoutMs,
onStats,
}) {
+ const composed = composeStreamSignal(signal, timeoutMs);
+ const requestSignal = composed.signal;
const headers = { 'Content-Type': 'application/json' };
if (apiKey) headers.Authorization = `Bearer ${apiKey}`;
const url = `${String(endpoint || '').replace(/\/+$/, '')}/chat/completions`;
@@ -246,7 +272,7 @@ export async function streamOpenAiChat({
const post = (withUsage) => fetchWithPreHeaderRetry(() => fetch(url, {
method: 'POST',
headers,
- signal,
+ signal: requestSignal,
body: JSON.stringify({
model,
messages,
@@ -257,148 +283,181 @@ export async function streamOpenAiChat({
...extraBody,
}),
}), {
- signal,
+ signal: requestSignal,
allowReplay: isReplaySafeLocalRequest({ endpoint, apiKey }),
}).catch((err) => ({ ok: false, status: 0, error: err.message }));
- let response = await post(includeUsage);
- // `stream_options` is standard OpenAI, but a stricter daemon (or an older
- // build) can reject an unknown body key outright. Token counts are a
- // nice-to-have; the generation is not — so drop the ask and retry once rather
- // than failing a run over a metric. Narrowed to the two codes that actually
- // mean "I did not like this body": a 401 (key-gated vLLM), a 404, a 5xx, or a
- // transport error all say nothing about `stream_options`, and retrying them
- // would double every real failure.
- let responseErrorBody = '';
- const mayRejectUsage = !response.ok
- && includeUsage
- && (response.status === 400 || response.status === 422)
- && !signal?.aborted;
- if (mayRejectUsage) {
- // A bad model or request can also be a 400/422. Inspect the body before
- // caching endpoint capability, otherwise one unrelated failure disables
- // exact usage collection for every later sample on this daemon.
- responseErrorBody = typeof response.clone === 'function'
- ? await response.clone().text().catch(() => '')
- : (response.text ? await response.text().catch(() => '') : response.error || '');
- if (/stream_options|include_usage/i.test(responseErrorBody)) {
- console.log(`⚠️ Local LLM: ${model} rejected stream_options (${response.status}) — retrying without usage reporting`);
- usageUnsupportedEndpoints.add(url);
- // Drain the rejected response so its socket is released before the retry.
- await response.body?.cancel?.().catch(() => {});
- responseErrorBody = '';
- response = await post(false);
+ try {
+ let response = await post(includeUsage);
+ // `stream_options` is standard OpenAI, but a stricter daemon (or an older
+ // build) can reject an unknown body key outright. Token counts are a
+ // nice-to-have; the generation is not — so drop the ask and retry once rather
+ // than failing a run over a metric. Narrowed to the two codes that actually
+ // mean "I did not like this body": a 401 (key-gated vLLM), a 404, a 5xx, or a
+ // transport error all say nothing about `stream_options`, and retrying them
+ // would double every real failure.
+ let responseErrorBody = '';
+ const mayRejectUsage = !response.ok
+ && includeUsage
+ && (response.status === 400 || response.status === 422)
+ && !requestSignal?.aborted;
+ if (mayRejectUsage) {
+ // A bad model or request can also be a 400/422. Inspect the body before
+ // caching endpoint capability, otherwise one unrelated failure disables
+ // exact usage collection for every later sample on this daemon.
+ responseErrorBody = typeof response.clone === 'function'
+ ? await response.clone().text().catch(() => '')
+ : (response.text ? await response.text().catch(() => '') : response.error || '');
+ if (/stream_options|include_usage/i.test(responseErrorBody)) {
+ console.log(`⚠️ Local LLM: ${model} rejected stream_options (${response.status}) — retrying without usage reporting`);
+ usageUnsupportedEndpoints.add(url);
+ // Drain the rejected response so its socket is released before the retry.
+ await response.body?.cancel?.().catch(() => {});
+ responseErrorBody = '';
+ response = await post(false);
+ }
}
- }
- if (!response.ok) {
- const body = responseErrorBody || (response.text ? await response.text().catch(() => '') : response.error || '');
- throw new Error(`Provider returned ${response.status || 0}: ${body || response.error || response.statusText || 'request failed'}`);
- }
+ if (!response.ok) {
+ const body = responseErrorBody || (response.text ? await response.text().catch(() => '') : response.error || '');
+ throw new Error(`Provider returned ${response.status || 0}: ${body || response.error || response.statusText || 'request failed'}`);
+ }
- // A stats listener must fire on EVERY exit path, including the abort/throw one
- // — a timed-out run still measured real tokens up to the cut, and dropping
- // them would report "not measured" for a sample that was in fact measured.
- // Guarded because a broken listener must not take down a live generation.
- const emitStats = (stats) => {
- if (typeof onStats !== 'function') return;
- try { onStats(stats); }
- catch (err) { console.error(`❌ Local LLM: usage listener failed: ${err.message}`); }
- };
+ // A stats listener must fire on EVERY exit path, including the abort/throw one
+ // — a timed-out run still measured real tokens up to the cut, and dropping
+ // them would report "not measured" for a sample that was in fact measured.
+ // Guarded because a broken listener must not take down a live generation.
+ const emitStats = (stats) => {
+ if (typeof onStats !== 'function') return;
+ try { onStats(stats); }
+ catch (err) { console.error(`❌ Local LLM: usage listener failed: ${err.message}`); }
+ };
- if (!response.body?.getReader) {
- // A non-streaming 200 (some daemons ignore `stream: true`). Read it whole
- // rather than reporting an empty generation, which a caller would persist as
- // a successful run that produced nothing — hence the `null` sentinel on both
- // a blank and an unparseable body, which throws rather than returning ''.
- const data = await readResponseJson(response, { fallback: null, emptyValue: null });
- if (!data) throw new Error(`Provider returned a non-JSON response (${response.status})`);
- const text = data.choices?.[0]?.message?.content || '';
- // A whole-body response reports usage the same way a non-streamed call does.
- // There is no per-chunk fallback here — nothing streamed — so an absent usage
- // block stays `null` rather than being estimated from a count we never made.
- emitStats({ ...normalizeUsage(data.usage), estimated: false });
- if (text) await onChunk?.(text, 'content');
- return text;
- }
+ if (!response.body?.getReader) {
+ // A non-streaming 200 (some daemons ignore `stream: true`). Read it whole
+ // rather than reporting an empty generation, which a caller would persist as
+ // a successful run that produced nothing — hence the `null` sentinel on both
+ // a blank and an unparseable body, which throws rather than returning ''.
+ const data = await readResponseJson(response, { fallback: null, emptyValue: null });
+ if (!data) throw new Error(`Provider returned a non-JSON response (${response.status})`);
+ const text = data.choices?.[0]?.message?.content || '';
+ // A whole-body response reports usage the same way a non-streamed call does.
+ // There is no per-chunk fallback here — nothing streamed — so an absent usage
+ // block stays `null` rather than being estimated from a count we never made.
+ emitStats({ ...normalizeUsage(data.usage), estimated: false });
+ if (text) yield { text, kind: 'content' };
+ return;
+ }
- const reader = response.body.getReader();
- const decoder = new TextDecoder();
- let buffer = '';
- let output = '';
- let reasoning = '';
- // Token counts as the daemon reported them, plus the streamed-frame fallback.
- // A frame carrying content is one decode step on every local runtime PortOS
- // talks to, so counting frames approximates the completion length closely —
- // but it is an ESTIMATE and is labelled as one, never merged into the reported
- // figure. `null` until a usage frame arrives keeps "reported none" distinct
- // from "reported zero".
- //
- // CONTENT frames only, deliberately: the text this returns is content-only
- // (`resolvePartialOutput` prefers it), so counting reasoning frames too would
- // report a tokens/s figure covering more output than the chars/s figure beside
- // it — the two would disagree systematically on every reasoning model.
- let usage = null;
- let contentFrames = 0;
- let runtimeTimings = null;
- let mtplxStats = null;
+ const reader = response.body.getReader();
+ const decoder = new TextDecoder();
+ let buffer = '';
+ let output = '';
+ let reasoning = '';
+ // Token counts as the daemon reported them, plus the streamed-frame fallback.
+ // A frame carrying content is one decode step on every local runtime PortOS
+ // talks to, so counting frames approximates the completion length closely —
+ // but it is an ESTIMATE and is labelled as one, never merged into the reported
+ // figure. `null` until a usage frame arrives keeps "reported none" distinct
+ // from "reported zero".
+ //
+ // CONTENT frames only, deliberately: the text this returns is content-only
+ // (`resolvePartialOutput` prefers it), so counting reasoning frames too would
+ // report a tokens/s figure covering more output than the chars/s figure beside
+ // it — the two would disagree systematically on every reasoning model.
+ let usage = null;
+ let contentFrames = 0;
+ let runtimeTimings = null;
+ let mtplxStats = null;
- const consumeLine = async (rawLine) => {
- const delta = parseStreamFrame(rawLine);
- if (!delta) return;
- if (delta.usage) usage = delta.usage;
- if (delta.timings) runtimeTimings = delta.timings;
- if (delta.mtplxStats) mtplxStats = delta.mtplxStats;
- if (delta.content) contentFrames += 1;
- if (delta.content) {
- output += delta.content;
- await onChunk?.(delta.content, 'content');
- }
- // Reasoning streams on its own channel so a reasoning-only model
- // (deepseek-r1, qwq, …) renders as it arrives instead of sitting on
- // "waiting for the first token", and so the final content-only text does
- // not inherit reasoning prose.
- if (delta.reasoning) {
- reasoning += delta.reasoning;
- await onChunk?.(delta.reasoning, 'reasoning');
+ const consumeLine = (rawLine) => {
+ const delta = parseStreamFrame(rawLine);
+ if (!delta) return [];
+ if (delta.usage) usage = delta.usage;
+ if (delta.timings) runtimeTimings = delta.timings;
+ if (delta.mtplxStats) mtplxStats = delta.mtplxStats;
+ if (delta.content) contentFrames += 1;
+ const chunks = [];
+ if (delta.content) {
+ output += delta.content;
+ chunks.push({ text: delta.content, kind: 'content' });
+ }
+ // Reasoning streams on its own channel so a reasoning-only model
+ // (deepseek-r1, qwq, …) renders as it arrives instead of sitting on
+ // "waiting for the first token", and so the final content-only text does
+ // not inherit reasoning prose.
+ if (delta.reasoning) {
+ reasoning += delta.reasoning;
+ chunks.push({ text: delta.reasoning, kind: 'reasoning' });
+ }
+ return chunks;
+ };
+
+ // Always release the reader (and tear down the socket) on every exit path — a
+ // normal finish, an abort via a timeout signal, or a throw mid-stream. On a
+ // throw, surface the tokens already streamed (attached to the error) instead
+ // of discarding them.
+ try {
+ while (true) {
+ const { done, value } = await reader.read();
+ if (done) break;
+ buffer += decoder.decode(value, { stream: true });
+ const lines = buffer.split('\n');
+ buffer = lines.pop() || '';
+ for (const line of lines) {
+ for (const chunk of consumeLine(line)) yield chunk;
+ }
+ }
+ buffer += decoder.decode();
+ if (buffer.trim()) {
+ for (const chunk of consumeLine(buffer)) yield chunk;
+ }
+ } catch (err) {
+ err.partialOutput = resolvePartialOutput({ output, reasoning });
+ throw err;
+ } finally {
+ const reported = normalizeUsage(usage);
+ const runtime = normalizeRuntimeTiming(runtimeTimings, mtplxStats);
+ emitStats(reported.completionTokens !== null
+ ? { ...reported, ...runtime, estimated: false }
+ // No usage block: fall back to the streamed-frame count, which is the only
+ // token-shaped evidence we have. `null` when nothing streamed at all —
+ // reporting 0 would file a transport failure as a zero-token generation.
+ : {
+ completionTokens: runtime.completionTokens ?? (contentFrames > 0 ? contentFrames : null),
+ promptTokens: runtime.promptTokens ?? reported.promptTokens,
+ ...(runtime.promptMs !== undefined ? { promptMs: runtime.promptMs } : {}),
+ ...(runtime.completionMs !== undefined ? { completionMs: runtime.completionMs } : {}),
+ estimated: runtime.completionTokens === undefined && contentFrames > 0,
+ });
+ await reader.cancel().catch(() => {});
}
- };
+ } finally {
+ composed.cleanup();
+ }
+}
- // Always release the reader (and tear down the socket) on every exit path — a
- // normal finish, an abort via a timeout signal, or a throw mid-stream. On a
- // throw, surface the tokens already streamed (attached to the error) instead
- // of discarding them.
+/**
+ * Stream a chat completion and return the final visible text.
+ *
+ * This convenience adapter preserves the established callback API while the
+ * iterator above remains available to callers, such as Ask, that already speak
+ * async iteration.
+ */
+export async function streamOpenAiChat(options) {
+ const { onChunk, ...transportOptions } = options;
+ let output = '';
+ let reasoning = '';
try {
- while (true) {
- const { done, value } = await reader.read();
- if (done) break;
- buffer += decoder.decode(value, { stream: true });
- const lines = buffer.split('\n');
- buffer = lines.pop() || '';
- for (const line of lines) await consumeLine(line);
+ for await (const chunk of iterateOpenAiChat(transportOptions)) {
+ if (chunk.kind === 'content') output += chunk.text;
+ else reasoning += chunk.text;
+ await onChunk?.(chunk.text, chunk.kind);
}
- if (buffer.trim()) await consumeLine(buffer);
} catch (err) {
- err.partialOutput = resolvePartialOutput({ output, reasoning });
+ if (!err.partialOutput) err.partialOutput = resolvePartialOutput({ output, reasoning });
throw err;
- } finally {
- const reported = normalizeUsage(usage);
- const runtime = normalizeRuntimeTiming(runtimeTimings, mtplxStats);
- emitStats(reported.completionTokens !== null
- ? { ...reported, ...runtime, estimated: false }
- // No usage block: fall back to the streamed-frame count, which is the only
- // token-shaped evidence we have. `null` when nothing streamed at all —
- // reporting 0 would file a transport failure as a zero-token generation.
- : {
- completionTokens: runtime.completionTokens ?? (contentFrames > 0 ? contentFrames : null),
- promptTokens: runtime.promptTokens ?? reported.promptTokens,
- ...(runtime.promptMs !== undefined ? { promptMs: runtime.promptMs } : {}),
- ...(runtime.completionMs !== undefined ? { completionMs: runtime.completionMs } : {}),
- estimated: runtime.completionTokens === undefined && contentFrames > 0,
- });
- await reader.cancel().catch(() => {});
}
-
return resolvePartialOutput({ output, reasoning });
}
diff --git a/server/lib/openAiChatStream.test.js b/server/lib/openAiChatStream.test.js
index 896913ca9d..22eb967ca8 100644
--- a/server/lib/openAiChatStream.test.js
+++ b/server/lib/openAiChatStream.test.js
@@ -12,6 +12,7 @@
import { describe, it, expect, vi } from 'vitest';
import {
buildMessages,
+ iterateOpenAiChat,
normalizeUsage,
normalizeRuntimeTiming,
parseOllamaStreamFrame,
@@ -161,6 +162,78 @@ describe('streamOpenAiChat — pre-header retries', () => {
});
});
+describe('iterateOpenAiChat', () => {
+ it('streams normalized chunks while skipping malformed frames and preserving usage', async () => {
+ const stats = vi.fn();
+ const payload = [
+ 'data: {not json',
+ 'data: {"choices":[{"delta":{"reasoning_content":"think"}}]}',
+ 'data: {"choices":[{"delta":{"content":"answer"}}]}',
+ 'data: {"choices":[],"usage":{"completion_tokens":1,"prompt_tokens":2}}',
+ 'data: [DONE]',
+ '',
+ ].join('\r\n');
+ global.fetch = vi.fn().mockResolvedValue(new Response(payload, {
+ status: 200,
+ headers: { 'Content-Type': 'text/event-stream' },
+ }));
+
+ const chunks = [];
+ for await (const chunk of iterateOpenAiChat({
+ endpoint: 'https://example.test/v1',
+ model: 'example-model',
+ messages: [],
+ onStats: stats,
+ })) chunks.push(chunk);
+
+ expect(chunks).toEqual([
+ { text: 'think', kind: 'reasoning' },
+ { text: 'answer', kind: 'content' },
+ ]);
+ expect(stats).toHaveBeenCalledWith({
+ completionTokens: 1,
+ promptTokens: 2,
+ estimated: false,
+ });
+ delete global.fetch;
+ });
+
+ it('aborts and cleans up a stalled reader at the whole-stream timeout', async () => {
+ vi.useFakeTimers();
+ const cancel = vi.fn(async () => {});
+ global.fetch = vi.fn(async (_url, { signal }) => ({
+ ok: true,
+ status: 200,
+ body: {
+ getReader: () => ({
+ read: () => new Promise((_resolve, reject) => {
+ signal.addEventListener('abort', () => reject(new Error('aborted')), { once: true });
+ }),
+ cancel,
+ }),
+ },
+ }));
+
+ const consume = async () => {
+ for await (const _chunk of iterateOpenAiChat({
+ endpoint: 'https://example.test/v1',
+ model: 'example-model',
+ messages: [],
+ timeoutMs: 25,
+ })) { /* drain */ }
+ };
+ const pending = consume();
+ const rejected = expect(pending).rejects.toMatchObject({ message: 'aborted', partialOutput: '' });
+ await Promise.resolve();
+ await vi.advanceTimersByTimeAsync(25);
+
+ await rejected;
+ expect(cancel).toHaveBeenCalledOnce();
+ delete global.fetch;
+ vi.useRealTimers();
+ });
+});
+
describe('parseStreamFrame', () => {
it('carries the usage block off the terminal frame (which has no choices)', () => {
const line = 'data: {"choices":[],"usage":{"completion_tokens":42,"prompt_tokens":900}}';
diff --git a/server/services/askService.js b/server/services/askService.js
index b30eb47ce4..411b8acb53 100644
--- a/server/services/askService.js
+++ b/server/services/askService.js
@@ -39,6 +39,7 @@ import { prepareCliSpawn } from '../lib/bufferedSpawn.js';
import { buildCliChildEnv } from '../lib/cliChildEnv.js';
import { ensureProviderReady as ensureOllamaProviderReady } from './ollamaManager.js';
import { evaluateSecretEndpoint } from '../lib/aiToolkit/internal/endpointGuard.js';
+import { iterateOpenAiChat } from '../lib/openAiChatStream.js';
// Re-export so the route can keep importing modes via askService — but
// askConversations is the source of truth (it owns the persistence schema).
@@ -456,111 +457,23 @@ async function* streamCompletion(provider, model, prompt, signal) {
throw new Error(`Provider endpoint blocked: ${guard.reason}`);
}
}
- const headers = { 'Content-Type': 'application/json' };
- if (provider.apiKey) headers['Authorization'] = `Bearer ${provider.apiKey}`;
- // Combine the per-provider timeout with the caller's abort signal so
- // either one tearing down propagates to the upstream fetch + reader.
- // The timeout stays armed through the entire stream-consumption window
- // — clearing it after the initial fetch resolved (the previous
- // implementation) wouldn't catch an upstream that opens the stream and
- // then stalls indefinitely. Mirrors the `AbortSignal.any` fallback in
- // `lib/fetchWithTimeout.js` so older Node builds without
- // `AbortSignal.any` keep working.
- const timeoutController = new AbortController();
- const timeoutId = setTimeout(() => timeoutController.abort(), provider.timeout || 300000);
- let fetchSignal = timeoutController.signal;
- let externalAbortHandler;
- if (signal) {
- if (typeof AbortSignal !== 'undefined' && typeof AbortSignal.any === 'function') {
- fetchSignal = AbortSignal.any([timeoutController.signal, signal]);
- } else {
- externalAbortHandler = () => timeoutController.abort();
- if (signal.aborted) timeoutController.abort();
- else signal.addEventListener('abort', externalAbortHandler, { once: true });
- }
- }
- const cleanup = () => {
- clearTimeout(timeoutId);
- if (signal && externalAbortHandler) signal.removeEventListener('abort', externalAbortHandler);
- };
- let response;
- try {
- const ready = await ensureOllamaProviderReady(provider);
- if (!ready.success) {
- throw new Error(`Ollama is not running and PortOS could not start it: ${ready.error || 'unknown error'}`);
- }
- response = await fetch(`${provider.endpoint}/chat/completions`, {
- method: 'POST',
- headers,
- body: JSON.stringify({
- model,
- messages: [{ role: 'user', content: prompt }],
- temperature: 0.4,
- stream: true,
- }),
- signal: fetchSignal,
- });
- } catch (err) {
- cleanup();
- throw err;
+ const ready = await ensureOllamaProviderReady(provider);
+ if (!ready.success) {
+ throw new Error(`Ollama is not running and PortOS could not start it: ${ready.error || 'unknown error'}`);
}
- if (!response.ok || !response.body) {
- cleanup();
- const text = await response.text().catch(() => '');
- throw new Error(`AI API error: ${response.status} - ${text.slice(0, 500)}`);
- }
- const reader = response.body.getReader();
- const decoder = new TextDecoder();
- let buffer = '';
- // Returns `{ delta, done }`. `done: true` means we hit `[DONE]` and
- // should stop. A single malformed/partial frame from the upstream
- // provider must not kill the whole stream — log and skip so subsequent
- // good frames still flow.
- const parseFrame = (frame) => {
- const trimmed = frame.trim();
- if (!trimmed.startsWith('data:')) return { delta: null, done: false };
- const payload = trimmed.slice(5).trim();
- if (payload === '[DONE]') return { delta: null, done: true };
- let parsed;
- try {
- parsed = JSON.parse(payload);
- } catch {
- console.warn(`⚠️ Ask: skipping malformed SSE frame from ${provider.id}`);
- return { delta: null, done: false };
- }
- return { delta: parsed?.choices?.[0]?.delta?.content || null, done: false };
- };
- try {
- while (true) {
- if (signal?.aborted) {
- await reader.cancel().catch(() => {});
- return;
- }
- const { value, done } = await reader.read();
- if (done) break;
- // Some SSE producers emit CRLF line terminators (`\r\n\r\n` between
- // frames); normalise to LF so the `\n\n` frame split below works
- // regardless of upstream.
- buffer += decoder.decode(value, { stream: true }).replace(/\r\n/g, '\n');
- let idx;
- while ((idx = buffer.indexOf('\n\n')) !== -1) {
- const frame = buffer.slice(0, idx);
- buffer = buffer.slice(idx + 2);
- const { delta, done: terminal } = parseFrame(frame);
- if (delta) yield delta;
- if (terminal) return;
- }
- }
- // Flush any final un-terminated frame — some upstreams close the
- // socket without a trailing `\n\n`, so the last delta would
- // otherwise sit forever in `buffer` and get dropped.
- buffer += decoder.decode().replace(/\r\n/g, '\n');
- if (buffer.trim()) {
- const { delta } = parseFrame(buffer);
- if (delta) yield delta;
- }
- } finally {
- cleanup();
+ for await (const chunk of iterateOpenAiChat({
+ endpoint: provider.endpoint,
+ apiKey: provider.apiKey,
+ model,
+ messages: [{ role: 'user', content: prompt }],
+ temperature: 0.4,
+ signal,
+ timeoutMs: provider.timeout || 300000,
+ })) {
+ // Ask's public SSE contract remains content-only. The shared transport
+ // still parses reasoning/usage frames so lifecycle and compatibility
+ // decisions stay canonical without exposing a new Ask event shape.
+ if (chunk.kind === 'content') yield chunk.text;
}
return;
}
diff --git a/server/services/askService.test.js b/server/services/askService.test.js
index ba32c4758f..d9bed00e25 100644
--- a/server/services/askService.test.js
+++ b/server/services/askService.test.js
@@ -272,6 +272,62 @@ describe('runAsk', () => {
expect(fullText).toBe('Hello, world.');
});
+ it('keeps streamed content and emits an error when the canonical reader fails', async () => {
+ providers.getActiveProvider.mockResolvedValue(fakeStreamProvider());
+ const encoded = new TextEncoder().encode('data: {"choices":[{"delta":{"content":"partial"}}]}\n');
+ let reads = 0;
+ const cancel = vi.fn(async () => {});
+ const fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue({
+ ok: true,
+ status: 200,
+ body: {
+ getReader: () => ({
+ read: vi.fn(async () => {
+ reads += 1;
+ if (reads === 1) return { done: false, value: encoded };
+ throw new Error('socket reset');
+ }),
+ cancel,
+ }),
+ },
+ });
+
+ const events = [];
+ for await (const evt of askService.runAsk({ question: 'hi' })) events.push(evt);
+ fetchSpy.mockRestore();
+
+ expect(events.find((event) => event.type === 'delta')).toEqual({ type: 'delta', text: 'partial' });
+ expect(events.find((event) => event.type === 'error')?.error).toContain('socket reset');
+ expect(events.find((event) => event.type === 'done')).toBeUndefined();
+ expect(cancel).toHaveBeenCalledOnce();
+ });
+
+ it('cancels the canonical reader without a terminal event after client abort', async () => {
+ providers.getActiveProvider.mockResolvedValue(fakeStreamProvider());
+ const controller = new AbortController();
+ const encoded = new TextEncoder().encode('data: {"choices":[{"delta":{"content":"partial"}}]}\n');
+ const cancel = vi.fn(async () => {});
+ const fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue({
+ ok: true,
+ status: 200,
+ body: {
+ getReader: () => ({
+ read: vi.fn(async () => ({ done: false, value: encoded })),
+ cancel,
+ }),
+ },
+ });
+
+ const stream = askService.runAsk({ question: 'hi', signal: controller.signal });
+ expect((await stream.next()).value.type).toBe('sources');
+ expect((await stream.next()).value).toEqual({ type: 'delta', text: 'partial' });
+ controller.abort();
+ expect(await stream.next()).toEqual({ done: true, value: undefined });
+ fetchSpy.mockRestore();
+
+ expect(cancel).toHaveBeenCalledOnce();
+ });
+
it('emits an error event for an empty question', async () => {
const events = [];
for await (const evt of askService.runAsk({ question: ' ' })) events.push(evt);