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

address review (round 4): keep stream timeout armed, drain cleanup, reader.cancel, CLI stdin prompt

Adam Eivy4c21c342d4b4
diff --git a/client/src/services/apiAsk.js b/client/src/services/apiAsk.js
index 7d537ea393..02cd2fb885 100644
--- a/client/src/services/apiAsk.js
+++ b/client/src/services/apiAsk.js
@@ -57,17 +57,24 @@ export async function streamAskTurn(payload, { onEvent, signal } = {}) {
onEvent?.({ event: eventName, data });
};
- while (true) {
- const { value, done } = await reader.read();
- if (done) break;
- buffer += decoder.decode(value, { stream: true });
- const parts = buffer.split(/\r?\n\r?\n/);
- buffer = parts.pop() || '';
- for (const part of parts) flushFrame(part);
- }
+ // Wrap the read loop so an abort or a thrown error still cancels the
+ // underlying ReadableStream — otherwise the connection can stay half-open
+ // longer than necessary. Mirrors the pattern in `apiOpenClaw.js`.
+ try {
+ while (true) {
+ const { value, done } = await reader.read();
+ if (done) break;
+ buffer += decoder.decode(value, { stream: true });
+ const parts = buffer.split(/\r?\n\r?\n/);
+ buffer = parts.pop() || '';
+ for (const part of parts) flushFrame(part);
+ }
- // Flush any final un-terminated frame (server closed without a trailing
- // double newline).
- buffer += decoder.decode();
- if (buffer.trim()) flushFrame(buffer);
+ // Flush any final un-terminated frame (server closed without a
+ // trailing double newline).
+ buffer += decoder.decode();
+ if (buffer.trim()) flushFrame(buffer);
+ } finally {
+ await reader.cancel().catch(() => {});
+ }
}
diff --git a/server/routes/ask.js b/server/routes/ask.js
index c52ac062dc..5420c8d6b8 100644
--- a/server/routes/ask.js
+++ b/server/routes/ask.js
@@ -122,15 +122,21 @@ router.post('/', asyncHandler(async (req, res) => {
// Honour socket backpressure — for long answers with many delta frames,
// a slow reader could otherwise force Node to buffer unbounded SSE data
// in memory. If `res.write` returns false, await the next `drain` (or
- // `close`) before queuing more frames.
+ // `close`) before queuing more frames. Both listeners are torn down on
+ // settle so a slow client that disconnects mid-drain doesn't leak
+ // listeners.
const send = async (event, data) => {
if (aborted) return;
const frame = `event: ${event}\ndata: ${JSON.stringify(data)}\n\n`;
if (!res.write(frame)) {
await new Promise((resolve) => {
- const onDrain = () => { res.off('close', onDrain); resolve(); };
- res.once('drain', onDrain);
- res.once('close', onDrain);
+ const settle = () => {
+ res.off('drain', settle);
+ res.off('close', settle);
+ resolve();
+ };
+ res.once('drain', settle);
+ res.once('close', settle);
});
}
};
diff --git a/server/services/askConversations.js b/server/services/askConversations.js
index 3c3c0bdc6f..eb3f9c0b0a 100644
--- a/server/services/askConversations.js
+++ b/server/services/askConversations.js
@@ -14,9 +14,12 @@
* { id, role: 'user'|'assistant', content, sources?, mode?, providerId?, model?, createdAt }
*
* Conversation ids are sortable: `ask_<base36-ms>_<hex>`. Lexically sorting
- * filenames descending therefore returns newest-first without reading any
- * file — `listConversations` exploits this so it doesn't have to parse every
- * JSON in the directory just to honour `limit`.
+ * filenames descending returns newest-first without reading any file, which
+ * lets `listConversations` collect its `limit` summaries from the head of
+ * the list. The expiry-prune pass still has to walk the full directory
+ * (otherwise stale unpinned conversations beyond the first page would
+ * persist past 30 days) — bounded by max-30-day's worth of files in a
+ * single-user app, so cost is negligible in practice.
*/
import { join } from 'path';
@@ -73,8 +76,9 @@ export async function listConversations({ limit = 50 } = {}) {
// Filenames carry a sortable timestamp prefix (`ask_<base36-ms>_…`) so a
// descending lexical sort gives newest-first ordering without reading any
- // file. This caps the number of disk reads at `limit` instead of scanning
- // every conversation just to satisfy a paginated UI.
+ // file. The full sweep below still reads every conversation — we need it
+ // to enforce the 30-day expiry on stale unpinned entries beyond the first
+ // page — but the sort lets us fill `summaries` from the head.
const ids = entries
.filter((f) => f.endsWith('.json'))
.map((f) => f.slice(0, -5))
diff --git a/server/services/askService.js b/server/services/askService.js
index c6e2bc7f60..70ac6813e7 100644
--- a/server/services/askService.js
+++ b/server/services/askService.js
@@ -351,9 +351,13 @@ async function* streamCompletion(provider, model, prompt, signal) {
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. Mirrors the
- // `AbortSignal.any` fallback in `lib/fetchWithTimeout.js` so older Node
- // builds without `AbortSignal.any` keep working.
+ // 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;
@@ -367,6 +371,10 @@ async function* streamCompletion(provider, model, prompt, signal) {
else signal.addEventListener('abort', externalAbortHandler, { once: true });
}
}
+ const cleanup = () => {
+ clearTimeout(timeoutId);
+ if (signal && externalAbortHandler) signal.removeEventListener('abort', externalAbortHandler);
+ };
let response;
try {
response = await fetch(`${provider.endpoint}/chat/completions`, {
@@ -380,71 +388,77 @@ async function* streamCompletion(provider, model, prompt, signal) {
}),
signal: fetchSignal,
});
- } finally {
- clearTimeout(timeoutId);
- if (signal && externalAbortHandler) signal.removeEventListener('abort', externalAbortHandler);
+ } catch (err) {
+ cleanup();
+ throw err;
}
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 = '';
- 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).trim();
- buffer = buffer.slice(idx + 2);
- if (!frame.startsWith('data:')) continue;
- const payload = frame.slice(5).trim();
- if (payload === '[DONE]') return;
- // A single malformed/partial frame from the upstream provider must
- // not kill the whole stream — log and skip so subsequent good
- // frames still flow.
- let parsed;
- try {
- parsed = JSON.parse(payload);
- } catch {
- console.warn(`⚠️ Ask: skipping malformed SSE frame from ${provider.id}`);
- continue;
+ 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).trim();
+ buffer = buffer.slice(idx + 2);
+ if (!frame.startsWith('data:')) continue;
+ const payload = frame.slice(5).trim();
+ if (payload === '[DONE]') return;
+ // A single malformed/partial frame from the upstream provider must
+ // not kill the whole stream — log and skip so subsequent good
+ // frames still flow.
+ let parsed;
+ try {
+ parsed = JSON.parse(payload);
+ } catch {
+ console.warn(`⚠️ Ask: skipping malformed SSE frame from ${provider.id}`);
+ continue;
+ }
+ const delta = parsed?.choices?.[0]?.delta?.content;
+ if (delta) yield delta;
}
- const delta = parsed?.choices?.[0]?.delta?.content;
- if (delta) yield delta;
}
+ } finally {
+ cleanup();
}
return;
}
// CLI providers can't stream chunked text out of a child process without
// a lot more wiring; fall back to a single-shot call via the shared
- // brain-style invocation pattern.
+ // brain-style invocation pattern. The prompt goes via stdin (not argv)
+ // because Ask prompts can run tens of thousands of characters once
+ // sources + history are concatenated, which exceeds OS argv limits
+ // (especially on Windows ~32k).
const { spawn } = await import('child_process');
const args = [...(provider.args || [])];
if (provider.headlessArgs?.length) args.push(...provider.headlessArgs);
if (provider.id === 'gemini-cli') {
if (!args.includes('--output-format') && !args.includes('-o')) args.push('--output-format', 'text');
if (model) args.push('--model', model);
- args.push('--prompt', prompt);
- } else {
- if (model) args.push('--model', model);
- args.push(prompt);
+ } else if (model) {
+ args.push('--model', model);
}
const out = await new Promise((resolve, reject) => {
let buf = '';
const child = spawn(provider.command, args, {
env: (() => { const e = { ...process.env, ...provider.envVars }; delete e.CLAUDECODE; return e; })(),
- stdio: ['ignore', 'pipe', 'pipe'],
+ stdio: ['pipe', 'pipe', 'pipe'],
shell: false,
windowsHide: true,
});
@@ -463,6 +477,10 @@ async function* streamCompletion(provider, model, prompt, signal) {
else reject(new Error(`CLI exited ${code}: ${buf.slice(0, 500)}`));
});
child.on('error', (err) => { clearTimeout(timer); signal?.removeEventListener('abort', onAbort); reject(err); });
+ // Pipe the prompt in via stdin so we never blow the OS argv limit on
+ // long retrieval-augmented prompts.
+ child.stdin.on('error', () => { /* child may close stdin first; the close handler resolves */ });
+ child.stdin.end(prompt);
});
yield out;
}