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
reassemble SSE frames split across reads instead of failing the run
Adam Eivy5a06d319879b
diff --git a/server/lib/aiToolkit/runner.js b/server/lib/aiToolkit/runner.jsindex 996aa89bad..bea547ee44 100644--- a/server/lib/aiToolkit/runner.js+++ b/server/lib/aiToolkit/runner.js@@ -819,38 +819,81 @@ export function createRunnerService(config = {}) {let reasoning = '';+ // Asked on BOTH terminal paths (a clean finish and a mid-stream throw),+ // so it is stated once: a reasoning model that produced no content still+ // produced an answer, and the run's text is its reasoning. Restating the+ // test at each site is how the two drift.+ const reasoningIsTheOutput = () => !output.trim() && reasoning.trim().length > 0;++ // A read returns an arbitrary SLICE of bytes, never a whole SSE frame, so+ // both boundaries have to be carried across iterations:+ // - `buffer` holds the partial trailing LINE. Parsing per-chunk instead+ // fed JSON.parse a frame cut in half at the ~8KB read boundary, which+ // threw `Unterminated string in JSON at position 8064` and failed a+ // 220s NVIDIA NIM nemotron run with outputSize 0 — a reasoning model's+ // `delta.reasoning` frames are big enough to straddle a read routinely.+ // - `{ stream: true }` holds the partial trailing CHARACTER, so a+ // multi-byte rune split across reads doesn't decode to U+FFFD.+ // This mirrors every other SSE consumer in the tree (openAiChatStream.js,+ // ollamaManager.js, voice/llm.js); this loop was the lone holdout.+ let buffer = '';++ const consumeLine = (rawLine) => {+ // A CRLF transport leaves `\r` on each line: it has to come off before+ // the terminal-sentinel comparison, or `[DONE]\r` falls through to+ // JSON.parse and throws at the very end of an otherwise-good stream.+ const line = rawLine.endsWith('\r') ? rawLine.slice(0, -1) : rawLine;+ if (!line.startsWith('data: ')) return;++ const data = line.slice(6);+ if (data === '✅' || data === '[DONE]') return;++ // One malformed frame must not discard the tokens around it. Before the+ // buffering above, every truncated frame reached here and its throw+ // aborted the whole run; now a parse failure can only mean the provider+ // actually emitted a bad frame, which is worth a log line, not the run.+ const parsed = safeJsonParse(data, null);+ if (!parsed) {+ console.error(`❌ Run ${runId} skipped an unparseable stream frame (${data.length} chars)`);+ return;+ }+ const delta = parsed?.choices?.[0]?.delta;++ if (delta?.content) {+ const text = delta.content;+ output += text;+ onData?.({ text });+ }++ if (delta?.reasoning) {+ reasoning += delta.reasoning;+ }+ };+const processStream = async () => {while (true) {const { done, value } = await reader.read();if (done) break;- const chunk = decoder.decode(value);- const lines = chunk.split('\n').filter(line => line.startsWith('data: '));-- for (const line of lines) {- const data = line.slice(6);- if (data === '✅' || data === '[DONE]') continue;-- const parsed = JSON.parse(data);- const delta = parsed?.choices?.[0]?.delta;+ buffer += decoder.decode(value, { stream: true });+ const lines = buffer.split('\n');+ // The last element is either an incomplete line or '' — either way it+ // is not ready to parse, so it becomes the next iteration's prefix.+ buffer = lines.pop() || '';- if (delta?.content) {- const text = delta.content;- output += text;- onData?.({ text });- }-- if (delta?.reasoning) {- reasoning += delta.reasoning;- }- }+ for (const line of lines) consumeLine(line);}+ // A stream that ends without a trailing newline (or without [DONE])+ // still has a complete frame sitting in the carry buffer; dropping it+ // would silently truncate the tail of the answer.+ buffer += decoder.decode();+ if (buffer.trim()) consumeLine(buffer);+// Capture the fallback decision BEFORE mutating `output` — otherwise- // the metadata check below (`!output.trim() && reasoning.trim()`) is- // always false on the reasoning-only path because `output` was just- // overwritten with the reasoning text.- const usedReasoningAsFallback = !output.trim() && reasoning.trim().length > 0;+ // the metadata check below is always false on the reasoning-only path+ // because `output` was just overwritten with the reasoning text.+ const usedReasoningAsFallback = reasoningIsTheOutput();if (usedReasoningAsFallback) {console.log(`🧠 Reasoning model detected - using reasoning as output (${reasoning.length} chars)`);output = reasoning;@@ -926,8 +969,16 @@ export function createRunnerService(config = {}) {activeRuns.delete(runId);- if (output) {- await atomicWrite(outputPath, output).catch(() => {});+ // A reasoning model emits `delta.reasoning` well before its first+ // content token, so a mid-stream failure routinely finds `output`+ // empty while the generation so far sits in `reasoning`. The success+ // path already falls back to it; doing the same here is the+ // difference between salvaging a long run and reporting+ // `outputSize: 0` after minutes of streaming.+ const usedReasoningAsFallback = reasoningIsTheOutput();+ const partialOutput = usedReasoningAsFallback ? reasoning : output;+ if (partialOutput) {+ await atomicWrite(outputPath, partialOutput).catch(() => {});}const metadata = safeJsonParse(await readFile(metadataPath, 'utf-8').catch(() => '{}'));@@ -939,19 +990,23 @@ export function createRunnerService(config = {}) {metadata.error = errorAnalysis.message || err.message;metadata.errorCategory = errorAnalysis.category;metadata.errorAnalysis = errorAnalysis;- metadata.outputSize = Buffer.byteLength(output);+ metadata.outputSize = Buffer.byteLength(partialOutput);+ metadata.hadReasoning = reasoning.length > 0;+ metadata.usedReasoningAsFallback = usedReasoningAsFallback;if (errorAnalysis.hasError &&(errorAnalysis.category === ERROR_CATEGORIES.RATE_LIMIT ||errorAnalysis.category === ERROR_CATEGORIES.USAGE_LIMIT)) {- await handleProviderError(provider.id, errorAnalysis, output);+ await handleProviderError(provider.id, errorAnalysis, partialOutput);}await atomicWrite(metadataPath, metadata);// Isolate the hook + onComplete so a throwing onRunFailed doesn't// bounce into the recovery path and call onRunFailed a second time.- safeSettle(() => hooks.onRunFailed?.(metadata, metadata.error, output), `Run ${runId} onRunFailed hook`);+ // The hook's third arg is the output tail the host quotes into an+ // investigation task, so it gets the salvaged text too.+ safeSettle(() => hooks.onRunFailed?.(metadata, metadata.error, partialOutput), `Run ${runId} onRunFailed hook`);safeSettle(() => onComplete?.(metadata), `Run ${runId} onComplete`);} catch (handlerErr) {console.error(`❌ Run ${runId} failure handler error: ${handlerErr.message}`);diff --git a/server/lib/aiToolkit/runner.test.js b/server/lib/aiToolkit/runner.test.jsindex d0d739a165..9471c44110 100644--- a/server/lib/aiToolkit/runner.test.js+++ b/server/lib/aiToolkit/runner.test.js@@ -860,6 +860,221 @@ describe('AI Toolkit runner service', () => {expect(second.canceled).toBeUndefined();expect(onRunFailed).not.toHaveBeenCalled();});+ // A `data:` frame is NOT guaranteed to arrive whole: the reader hands back+ // arbitrary byte-sized chunks (~8KB from undici), so a long frame — a+ // reasoning model's `delta.reasoning`, a big content burst — routinely+ // straddles two reads. Parsing per-chunk instead of per-LINE fed JSON.parse a+ // half frame and threw `Unterminated string in JSON at position 8064`,+ // failing a 220s NVIDIA NIM nemotron run with outputSize 0. Every other SSE+ // consumer in the tree already carries the remainder forward.+ it('reassembles a data frame split across two reads instead of failing the run', async () => {+ const dataDir = await mkdtemp(join(tmpdir(), 'ai-toolkit-runner-'));+ tempDirs.push(dataDir);+ const encoder = new TextEncoder();+ const frame = `data: ${JSON.stringify({ choices: [{ delta: { content: 'split-across-reads' } }] })}\n`;+ const cut = frame.indexOf('split') + 5;+ const chunks = [+ encoder.encode(frame.slice(0, cut)),+ encoder.encode(frame.slice(cut)),+ encoder.encode('data: [DONE]\n'),+ ];+ let i = 0;+ vi.stubGlobal('fetch', vi.fn(async () => ({+ ok: true,+ body: { getReader: () => ({ read: async () => (i < chunks.length+ ? { done: false, value: chunks[i++] }+ : { done: true, value: undefined }) }) },+ })));+ const runner = createRunnerService({+ dataDir, hooks: { ensureProviderReady: async () => ({ success: true }) },+ });+ let complete;+ const completed = new Promise(resolve => { complete = resolve; });++ await runner.executeApiRun({+ runId: 'run-split-frame', provider: runReady(), model: null, prompt: 'hi',+ workspacePath: process.cwd(), screenshots: [], onData: undefined, onComplete: complete,+ });+ const metadata = await completed;++ expect(metadata.success).toBe(true);+ expect(await readFile(join(dataDir, 'runs', 'run-split-frame', 'output.txt'), 'utf-8'))+ .toBe('split-across-reads');+ });++ // Same boundary, one layer down: a multi-byte character cut in half by the+ // read boundary needs the decoder's own streaming carry, or it lands as U+FFFD.+ it('decodes a multi-byte character split across two reads', async () => {+ const dataDir = await mkdtemp(join(tmpdir(), 'ai-toolkit-runner-'));+ tempDirs.push(dataDir);+ const encoder = new TextEncoder();+ const frame = encoder.encode(`data: ${JSON.stringify({ choices: [{ delta: { content: 'café — 日本' } }] })}\n`);+ // Cut inside the 3-byte encoding of "—".+ const cut = frame.indexOf(0xe2) + 1;+ const chunks = [frame.slice(0, cut), frame.slice(cut), encoder.encode('data: [DONE]\n')];+ let i = 0;+ vi.stubGlobal('fetch', vi.fn(async () => ({+ ok: true,+ body: { getReader: () => ({ read: async () => (i < chunks.length+ ? { done: false, value: chunks[i++] }+ : { done: true, value: undefined }) }) },+ })));+ const runner = createRunnerService({+ dataDir, hooks: { ensureProviderReady: async () => ({ success: true }) },+ });+ let complete;+ const completed = new Promise(resolve => { complete = resolve; });++ await runner.executeApiRun({+ runId: 'run-split-utf8', provider: runReady(), model: null, prompt: 'hi',+ workspacePath: process.cwd(), screenshots: [], onData: undefined, onComplete: complete,+ });+ await completed;++ expect(await readFile(join(dataDir, 'runs', 'run-split-utf8', 'output.txt'), 'utf-8'))+ .toBe('café — 日本');+ });++ // A CRLF transport leaves `\r` on every line; `[DONE]\r` missed the terminal+ // check and reached JSON.parse, and a trailing `\r` rode into the output text.+ it('tolerates CRLF frame separators', async () => {+ const dataDir = await mkdtemp(join(tmpdir(), 'ai-toolkit-runner-'));+ tempDirs.push(dataDir);+ const encoder = new TextEncoder();+ const chunks = [+ encoder.encode(`data: ${JSON.stringify({ choices: [{ delta: { content: 'crlf' } }] })}\r\n\r\n`),+ encoder.encode('data: [DONE]\r\n'),+ ];+ let i = 0;+ vi.stubGlobal('fetch', vi.fn(async () => ({+ ok: true,+ body: { getReader: () => ({ read: async () => (i < chunks.length+ ? { done: false, value: chunks[i++] }+ : { done: true, value: undefined }) }) },+ })));+ const runner = createRunnerService({+ dataDir, hooks: { ensureProviderReady: async () => ({ success: true }) },+ });+ let complete;+ const completed = new Promise(resolve => { complete = resolve; });++ await runner.executeApiRun({+ runId: 'run-crlf', provider: runReady(), model: null, prompt: 'hi',+ workspacePath: process.cwd(), screenshots: [], onData: undefined, onComplete: complete,+ });+ const metadata = await completed;++ expect(metadata.success).toBe(true);+ expect(await readFile(join(dataDir, 'runs', 'run-crlf', 'output.txt'), 'utf-8')).toBe('crlf');+ });++ // One corrupt frame mid-stream must not throw away the tokens around it — the+ // old code let a single JSON.parse throw abort the whole run.+ it('skips an unparseable frame and keeps the surrounding output', async () => {+ const dataDir = await mkdtemp(join(tmpdir(), 'ai-toolkit-runner-'));+ tempDirs.push(dataDir);+ const encoder = new TextEncoder();+ const chunks = [+ encoder.encode(`data: ${JSON.stringify({ choices: [{ delta: { content: 'before ' } }] })}\n`),+ encoder.encode('data: {"choices":[{"delta":{"content":"oops\n'),+ encoder.encode(`data: ${JSON.stringify({ choices: [{ delta: { content: 'after' } }] })}\n`),+ encoder.encode('data: [DONE]\n'),+ ];+ let i = 0;+ vi.stubGlobal('fetch', vi.fn(async () => ({+ ok: true,+ body: { getReader: () => ({ read: async () => (i < chunks.length+ ? { done: false, value: chunks[i++] }+ : { done: true, value: undefined }) }) },+ })));+ const runner = createRunnerService({+ dataDir, hooks: { ensureProviderReady: async () => ({ success: true }) },+ });+ let complete;+ const completed = new Promise(resolve => { complete = resolve; });++ await runner.executeApiRun({+ runId: 'run-bad-frame', provider: runReady(), model: null, prompt: 'hi',+ workspacePath: process.cwd(), screenshots: [], onData: undefined, onComplete: complete,+ });+ const metadata = await completed;++ expect(metadata.success).toBe(true);+ expect(await readFile(join(dataDir, 'runs', 'run-bad-frame', 'output.txt'), 'utf-8'))+ .toBe('before after');+ });++ // A reasoning model streams `delta.reasoning` before any content, so a+ // mid-stream failure finds `output` empty and the real work sitting in+ // `reasoning`. The success path already falls back to it; the failure path+ // discarded it, which is how the NVIDIA NIM nemotron run lost 220s of+ // generation to `outputSize: 0`.+ it('salvages reasoning-only partial output when the stream fails mid-run', async () => {+ const dataDir = await mkdtemp(join(tmpdir(), 'ai-toolkit-runner-'));+ tempDirs.push(dataDir);+ const encoder = new TextEncoder();+ const chunks = [+ encoder.encode(`data: ${JSON.stringify({ choices: [{ delta: { reasoning: 'thought so far' } }] })}\n`),+ ];+ let i = 0;+ vi.stubGlobal('fetch', vi.fn(async () => ({+ ok: true,+ body: { getReader: () => ({ read: async () => (i < chunks.length+ ? { done: false, value: chunks[i++] }+ : Promise.reject(new Error('socket hang up'))) }) },+ })));+ const runner = createRunnerService({+ dataDir, hooks: { ensureProviderReady: async () => ({ success: true }) },+ });+ let complete;+ const completed = new Promise(resolve => { complete = resolve; });++ await runner.executeApiRun({+ runId: 'run-reasoning-salvage', provider: runReady(), model: null, prompt: 'hi',+ workspacePath: process.cwd(), screenshots: [], onData: undefined, onComplete: complete,+ });+ const metadata = await completed;++ expect(metadata.success).toBe(false);+ expect(metadata.outputSize).toBeGreaterThan(0);+ expect(await readFile(join(dataDir, 'runs', 'run-reasoning-salvage', 'output.txt'), 'utf-8'))+ .toBe('thought so far');+ });++ // A stream that ends without [DONE] still has a complete frame sitting in the+ // carry buffer; dropping it silently truncates the tail of the answer.+ it('flushes a trailing frame left unterminated by the final read', async () => {+ const dataDir = await mkdtemp(join(tmpdir(), 'ai-toolkit-runner-'));+ tempDirs.push(dataDir);+ const encoder = new TextEncoder();+ const chunks = [+ encoder.encode(`data: ${JSON.stringify({ choices: [{ delta: { content: 'head ' } }] })}\n`),+ encoder.encode(`data: ${JSON.stringify({ choices: [{ delta: { content: 'tail' } }] })}`),+ ];+ let i = 0;+ vi.stubGlobal('fetch', vi.fn(async () => ({+ ok: true,+ body: { getReader: () => ({ read: async () => (i < chunks.length+ ? { done: false, value: chunks[i++] }+ : { done: true, value: undefined }) }) },+ })));+ const runner = createRunnerService({+ dataDir, hooks: { ensureProviderReady: async () => ({ success: true }) },+ });+ let complete;+ const completed = new Promise(resolve => { complete = resolve; });++ await runner.executeApiRun({+ runId: 'run-tail-frame', provider: runReady(), model: null, prompt: 'hi',+ workspacePath: process.cwd(), screenshots: [], onData: undefined, onComplete: complete,+ });+ const metadata = await completed;++ expect(metadata.success).toBe(true);+ expect(await readFile(join(dataDir, 'runs', 'run-tail-frame', 'output.txt'), 'utf-8'))+ .toBe('head tail');+ });+});describe('AI Toolkit runner — declared extension points', () => {