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: preserve client abort stream semantics (#5618)

Adam Eivy86bf5c794185
diff --git a/server/lib/openAiChatStream.js b/server/lib/openAiChatStream.js
index 0a2ba7e42e..c4b99a404b 100644
--- a/server/lib/openAiChatStream.js
+++ b/server/lib/openAiChatStream.js
@@ -249,6 +249,9 @@ function composeStreamSignal(signal, timeoutMs) {
* @param {AbortSignal} [options.signal]
* @param {number} [options.timeoutMs] abort the request and reader after this
* many milliseconds; the caller's signal remains independently effective.
+ * @param {boolean} [options.stopOnAbort=true] return quietly without reading
+ * another buffered chunk after caller cancellation. The text adapter disables
+ * this to preserve its established AbortError plus partial-output contract.
* @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'}>}
@@ -263,6 +266,7 @@ export async function* iterateOpenAiChat({
extraBody = {},
signal,
timeoutMs,
+ stopOnAbort = true,
onStats,
}) {
const composed = composeStreamSignal(signal, timeoutMs);
@@ -405,9 +409,10 @@ export async function* iterateOpenAiChat({
// of discarding them.
try {
let terminal = false;
- while (!terminal) {
+ while (!terminal && (!stopOnAbort || !signal?.aborted)) {
const { done, value } = await reader.read();
if (done) break;
+ if (stopOnAbort && signal?.aborted) break;
buffer += decoder.decode(value, { stream: true });
const lines = buffer.split('\n');
buffer = lines.pop() || '';
@@ -445,6 +450,11 @@ export async function* iterateOpenAiChat({
});
await reader.cancel().catch(() => {});
}
+ } catch (err) {
+ // The iterator is the quiet cancellation seam used by Ask. The convenience
+ // adapter below restores its established AbortError contract for callers
+ // that await a final string instead of consuming chunks directly.
+ if (!stopOnAbort || !signal?.aborted) throw err;
} finally {
composed.cleanup();
}
@@ -462,7 +472,7 @@ export async function streamOpenAiChat(options) {
let output = '';
let reasoning = '';
try {
- for await (const chunk of iterateOpenAiChat(transportOptions)) {
+ for await (const chunk of iterateOpenAiChat({ ...transportOptions, stopOnAbort: false })) {
if (chunk.kind === 'content') output += chunk.text;
else reasoning += chunk.text;
await onChunk?.(chunk.text, chunk.kind);
diff --git a/server/lib/openAiChatStream.test.js b/server/lib/openAiChatStream.test.js
index c59435867c..27360b8b1c 100644
--- a/server/lib/openAiChatStream.test.js
+++ b/server/lib/openAiChatStream.test.js
@@ -160,6 +160,39 @@ describe('streamOpenAiChat — pre-header retries', () => {
expect(reader.cancel).toHaveBeenCalledOnce();
delete global.fetch;
});
+
+ it('preserves the callback adapter AbortError and partial-output contract', async () => {
+ const controller = new AbortController();
+ const chunk = new TextEncoder().encode('data: {"choices":[{"delta":{"content":"partial"}}]}\n');
+ const cancel = vi.fn(async () => {});
+ let reads = 0;
+ global.fetch = vi.fn().mockResolvedValue({
+ ok: true,
+ status: 200,
+ body: {
+ getReader: () => ({
+ read: vi.fn(async () => {
+ reads += 1;
+ if (reads === 1) return { done: false, value: chunk };
+ throw Object.assign(new Error('aborted'), { name: 'AbortError' });
+ }),
+ cancel,
+ }),
+ },
+ });
+
+ const error = await streamOpenAiChat({
+ endpoint: 'https://example.test/v1',
+ model: 'example-model',
+ messages: [],
+ signal: controller.signal,
+ onChunk: () => controller.abort(),
+ }).catch((err) => err);
+
+ expect(error).toMatchObject({ name: 'AbortError', partialOutput: 'partial' });
+ expect(cancel).toHaveBeenCalledOnce();
+ delete global.fetch;
+ });
});
describe('iterateOpenAiChat', () => {
diff --git a/server/services/askService.js b/server/services/askService.js
index 411b8acb53..22cc51c984 100644
--- a/server/services/askService.js
+++ b/server/services/askService.js
@@ -475,6 +475,7 @@ async function* streamCompletion(provider, model, prompt, signal) {
// decisions stay canonical without exposing a new Ask event shape.
if (chunk.kind === 'content') yield chunk.text;
}
+ if (signal?.aborted) return;
return;
}
@@ -679,6 +680,7 @@ export async function* runAsk({
yield { type: 'error', error: `Provider stream failed: ${err.message}` };
return;
}
+ if (signal?.aborted) return;
const answer = chunks.join('');
console.log(`✅ Ask complete: ${provider.id}/${effectiveModel} ${Date.now() - startedAt}ms ${answer.length} chars`);