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
delegate mid-stream errorMiddleware failures to finalhandler (#2845)
[._.]/ Adam Eivy994d1b4b9b44
diff --git a/server/lib/errorHandler.js b/server/lib/errorHandler.jsindex 13fd27f030..42ee1e74a6 100644--- a/server/lib/errorHandler.js+++ b/server/lib/errorHandler.js@@ -325,8 +325,15 @@ export function errorMiddleware(err, req, res, next) {// Emit the socket event and send the shared envelope — synchronous handlers// that throw a ServerError land here, not in asyncHandler, so both paths must- // produce the same body.+ // produce the same body. `sendErrorResponse` still emits to the UI when the+ // body can no longer be written.+ // Mid-response failure (SSE / streaming route) — nothing can be written, so+ // after emitting we hand back to Express's finalhandler, which destroys the+ // socket. Without this the request hangs open until a timeout. Read the flag+ // BEFORE sending: a successful write flips it to true.+ const alreadyStreaming = res.headersSent;sendErrorResponse(res, error, { io });+ if (alreadyStreaming) next(err);}/**diff --git a/server/lib/errorHandler.test.js b/server/lib/errorHandler.test.jsindex 783c0b1e83..1799122f09 100644--- a/server/lib/errorHandler.test.js+++ b/server/lib/errorHandler.test.js@@ -212,6 +212,32 @@ describe('errorHandler.js', () => {const body = res.json.mock.calls[0][0];expect(body).not.toHaveProperty('context');});++ // A streaming/SSE route that fails mid-response has no envelope left to+ // write — delegate to Express's finalhandler so it destroys the socket+ // rather than leaving the request hanging until a timeout.+ it('delegates to next(err) when the response is already streaming', () => {+ const res = makeRes();+ res.headersSent = true;+ const next = vi.fn();+ const err = new ServerError('mid-stream', { status: 500 });+ errorMiddleware(err, makeReq(), res, next);++ expect(res.json).not.toHaveBeenCalled();+ expect(next).toHaveBeenCalledWith(err);+ });++ it('does not delegate to next when the envelope was written', () => {+ const res = makeRes();+ // Express flips headersSent once the body is written — mirror that so the+ // middleware can't mistake its own write for a mid-stream failure.+ res.json = vi.fn(() => { res.headersSent = true; return res; });+ const next = vi.fn();+ errorMiddleware(new ServerError('nope', { status: 400 }), makeReq(), res, next);++ expect(res.json).toHaveBeenCalled();+ expect(next).not.toHaveBeenCalled();+ });});describe('emitErrorEvent', () => {diff --git a/server/routes/loraTraining.js b/server/routes/loraTraining.jsindex 4a5bd8b62a..9da34c4bfd 100644--- a/server/routes/loraTraining.js+++ b/server/routes/loraTraining.js@@ -159,7 +159,11 @@ router.get('/runs/:id/samples/:filename', asyncHandler(async (req, res) => {// promise has already resolved), so a throw here would have nothing to bubble// to — build the standard envelope directly instead.res.sendFile(join(runSamplesDir(run.id), req.params.filename), (err) => {- if (err) sendErrorResponse(res, new ServerError('Sample not found', { status: 404 }));+ if (!err) return;+ // A real I/O failure (EACCES/EIO) reads the same as a missing file to the+ // client — log the cause so it isn't invisible server-side.+ console.error(`❌ Sample send failed [${req.params.id}/${req.params.filename}]: ${err.message}`);+ sendErrorResponse(res, new ServerError('Sample not found', { status: 404 }));});}));diff --git a/server/routes/loraTraining.test.js b/server/routes/loraTraining.test.jsindex 064e1fe467..9921de129d 100644--- a/server/routes/loraTraining.test.js+++ b/server/routes/loraTraining.test.js@@ -1,8 +1,8 @@-import { describe, it, expect, vi, beforeEach } from 'vitest';+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';import express from 'express';import { tmpdir } from 'os';import { join } from 'path';-import { mkdtemp, writeFile } from 'fs/promises';+import { mkdtemp, rm, writeFile } from 'fs/promises';import { request } from '../lib/testHelper.js';// The route module pulls in the whole training service graph at import time —@@ -51,6 +51,9 @@ describe('lora-training sample serving', () => {app = makeApp();svc.samplesDir = await mkdtemp(join(tmpdir(), 'portos-lora-samples-'));});+ afterEach(async () => {+ await rm(svc.samplesDir, { recursive: true, force: true });+ });it('serves an existing sample', async () => {await writeFile(join(svc.samplesDir, 'step-1.png'), 'png-bytes');