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
address review (round 3): full prune pass, AbortSignal.any fallback, robust SSE parser, inbox field names
Adam Eivy877390d346bb
diff --git a/client/src/pages/Ask.jsx b/client/src/pages/Ask.jsxindex b2f1a774a9..fffd43555b 100644--- a/client/src/pages/Ask.jsx+++ b/client/src/pages/Ask.jsx@@ -206,7 +206,14 @@ export default function Ask() {return;}pendingDeleteRef.current = { id: null, expiresAt: 0 };- await api.deleteAskConversation(id).catch(() => null);+ // Only mutate local state if the server confirms the delete — otherwise+ // a transient failure would hide a row that's still on disk and would+ // pop back on the next list refresh.+ const ok = await api.deleteAskConversation(id).then(() => true, (err) => {+ toast.error(err?.message || 'Failed to delete conversation');+ return false;+ });+ if (!ok) return;setConversations((prev) => prev.filter((c) => c.id !== id));if (id === conversationId) navigate('/ask');}, [activeConv?.id, conversationId, navigate, streaming]);diff --git a/client/src/services/apiAsk.js b/client/src/services/apiAsk.jsindex ccda860310..7d537ea393 100644--- a/client/src/services/apiAsk.js+++ b/client/src/services/apiAsk.js@@ -34,27 +34,40 @@ export async function streamAskTurn(payload, { onEvent, signal } = {}) {const reader = response.body.getReader();const decoder = new TextDecoder();let buffer = '';- let currentEvent = 'message';++ // Match the SSE parser used in `apiOpenClaw.js`: tolerate `\r\n\r\n`+ // separators (some proxies normalise line endings), preserve multi-line+ // `data:` frames by joining with `\n`, and strip the optional single+ // leading space from each data line per the SSE spec.+ const flushFrame = (frame) => {+ const lines = frame.split(/\r?\n/);+ let eventName = 'message';+ const dataLines = [];+ for (const line of lines) {+ if (line.startsWith('event:')) eventName = line.slice(6).trim() || 'message';+ else if (line.startsWith('data:')) {+ const raw = line.slice(5);+ dataLines.push(raw.startsWith(' ') ? raw.slice(1) : raw);+ }+ }+ if (!dataLines.length) return;+ const rawData = dataLines.join('\n');+ let data;+ try { data = JSON.parse(rawData); } catch { data = { raw: rawData }; }+ onEvent?.({ event: eventName, data });+ };while (true) {const { value, done } = await reader.read();if (done) break;buffer += decoder.decode(value, { stream: true });-- let frameEnd;- while ((frameEnd = buffer.indexOf('\n\n')) !== -1) {- const frame = buffer.slice(0, frameEnd);- buffer = buffer.slice(frameEnd + 2);- currentEvent = 'message';- let dataLine = '';- for (const line of frame.split('\n')) {- if (line.startsWith('event:')) currentEvent = line.slice(6).trim();- else if (line.startsWith('data:')) dataLine += line.slice(5).trim();- }- if (!dataLine) continue;- let data = null;- try { data = JSON.parse(dataLine); } catch { data = { raw: dataLine }; }- onEvent?.({ event: currentEvent, data });- }+ 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);}diff --git a/server/routes/ask.js b/server/routes/ask.jsindex 20bcbe7116..c52ac062dc 100644--- a/server/routes/ask.js+++ b/server/routes/ask.js@@ -105,9 +105,12 @@ router.post('/', asyncHandler(async (req, res) => {res.flushHeaders?.();// Propagate client disconnects (browser nav, tab close, abort) into- // retrieval + provider streaming so we don't keep burning tokens/CPU on- // a stream nobody's reading. `aborted` short-circuits the post-loop- // persistence too.+ // provider streaming and the post-retrieval generator loop so we don't+ // keep burning tokens/CPU on a stream nobody's reading. The retrieval+ // fan-out itself doesn't currently take a signal — those queries are+ // bounded (~hundreds of ms) so we let them finish; once retrieval+ // returns, the abort short-circuits before any further SSE writes or+ // provider work. `aborted` also gates the post-loop persistence.const abortController = new AbortController();let aborted = false;const onClose = () => {diff --git a/server/services/askConversations.js b/server/services/askConversations.jsindex acb7f61dfa..3c3c0bdc6f 100644--- a/server/services/askConversations.js+++ b/server/services/askConversations.js@@ -85,8 +85,11 @@ export async function listConversations({ limit = 50 } = {}) {const now = Date.now();const expiryMs = EXPIRY_DAYS * 24 * 60 * 60 * 1000;+ // Walk the whole directory so expired+unpinned conversations get pruned+ // even if they live past the first `limit` results — otherwise a user with+ // >limit conversations would silently violate the 30-day auto-expire+ // contract (old files would persist indefinitely on disk).for (const id of ids) {- if (summaries.length >= limit) break;const conv = await readConversation(id);if (!conv) continue;@@ -97,15 +100,17 @@ export async function listConversations({ limit = 50 } = {}) {continue;}- summaries.push({- id: conv.id,- title: conv.title || '(untitled)',- mode: conv.mode,- createdAt: conv.createdAt,- updatedAt: conv.updatedAt,- turnCount: Array.isArray(conv.turns) ? conv.turns.length : 0,- promoted: !!conv.promoted,- });+ if (summaries.length < limit) {+ summaries.push({+ id: conv.id,+ title: conv.title || '(untitled)',+ mode: conv.mode,+ createdAt: conv.createdAt,+ updatedAt: conv.updatedAt,+ turnCount: Array.isArray(conv.turns) ? conv.turns.length : 0,+ promoted: !!conv.promoted,+ });+ }}return summaries;diff --git a/server/services/askService.js b/server/services/askService.jsindex 092dd288e7..c6e2bc7f60 100644--- a/server/services/askService.js+++ b/server/services/askService.js@@ -140,9 +140,12 @@ async function retrieveBrainNotes(question, queryTokens) {candidates.push({ kind: 'brain-note', subkind: 'project', recordId: proj.id, title: proj.title || '(project)', snippet: text, href: `/brain/memory?type=projects&id=${encodeURIComponent(proj.id)}`, updatedAt: proj.updatedAt || proj.createdAt });}for (const entry of inbox || []) {- const text = entry.text || entry.summary || '';+ // Brain inbox records use `capturedText` / `capturedAt` (see+ // brainStorage.getInboxLog). Fall back to legacy field names for+ // forward-compat with any older entries that may exist on disk.+ const text = entry.capturedText || entry.text || entry.summary || '';if (!text) continue;- candidates.push({ kind: 'brain-note', subkind: 'inbox', recordId: entry.id, title: text.slice(0, 80), snippet: text, href: '/brain/inbox', updatedAt: entry.timestamp || entry.createdAt });+ candidates.push({ kind: 'brain-note', subkind: 'inbox', recordId: entry.id, title: text.slice(0, 80), snippet: text, href: '/brain/inbox', updatedAt: entry.capturedAt || entry.timestamp || entry.createdAt });}for (const c of candidates) {@@ -348,20 +351,39 @@ 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.- const timeoutSignal = AbortSignal.timeout(provider.timeout || 300000);- const fetchSignal = signal ? AbortSignal.any([signal, timeoutSignal]) : timeoutSignal;- const 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,- });+ // 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.+ 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 });+ }+ }+ let response;+ try {+ 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,+ });+ } finally {+ clearTimeout(timeoutId);+ if (signal && externalAbortHandler) signal.removeEventListener('abort', externalAbortHandler);+ }if (!response.ok || !response.body) {const text = await response.text().catch(() => '');throw new Error(`AI API error: ${response.status} - ${text.slice(0, 500)}`);