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

close the same mid-stream hang in asyncHandler and the sample sendFile path (#2845)

[._.]/ Adam Eivy216aa3a85919
diff --git a/server/lib/errorHandler.js b/server/lib/errorHandler.js
index 42ee1e74a6..2bc3619793 100644
--- a/server/lib/errorHandler.js
+++ b/server/lib/errorHandler.js
@@ -127,7 +127,13 @@ export function asyncHandler(fn) {
console.error(details ? `${logMsg}: ${JSON.stringify(details)}` : logMsg);
}
- return sendErrorResponse(res, error, { io });
+ // Read BEFORE sending — a successful write flips the flag. A handler that
+ // throws after it started streaming (SSE routes) has no envelope left to
+ // write, so hand off to Express's finalhandler to destroy the socket
+ // instead of leaving the request hanging.
+ 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.js
index 1799122f09..7b7505fefa 100644
--- a/server/lib/errorHandler.test.js
+++ b/server/lib/errorHandler.test.js
@@ -385,6 +385,19 @@ describe('errorHandler.js', () => {
expect(body.error).toBe('kaboom');
});
+ it('delegates to next(err) when the handler throws mid-stream', async () => {
+ const { req, res } = makeReqRes(null);
+ res.headersSent = true;
+ const next = vi.fn();
+ const boom = new ServerError('mid-stream', { status: 500 });
+
+ await asyncHandler(async () => { throw boom; })(req, res, next);
+ await flushMicrotasks();
+
+ expect(res.json).not.toHaveBeenCalled();
+ expect(next).toHaveBeenCalledWith(boom);
+ });
+
it('does not touch res when the wrapped handler resolves successfully', async () => {
const { req, res } = makeReqRes({ emit: vi.fn() });
diff --git a/server/routes/loraTraining.js b/server/routes/loraTraining.js
index 9da34c4bfd..394f12d421 100644
--- a/server/routes/loraTraining.js
+++ b/server/routes/loraTraining.js
@@ -160,6 +160,13 @@ router.get('/runs/:id/samples/:filename', asyncHandler(async (req, res) => {
// to — build the standard envelope directly instead.
res.sendFile(join(runSamplesDir(run.id), req.params.filename), (err) => {
if (!err) return;
+ // Client cancelled (routine when the gallery unmounts an <img>) or the body
+ // was already streaming when the read failed — nothing left to say, just
+ // drop the socket rather than logging a false failure.
+ if (err.code === 'ECONNABORTED' || res.headersSent) {
+ res.destroy();
+ 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}`);