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

fix(multipart): guard tick() against re-entry while file flush pending

Adam Eivy9ebd63ad37bf
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 8de0f13eb0..d2de11c663 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -2,6 +2,8 @@
## Fixed
+- **Multipart upload server crash: `Cannot read properties of null (reading 'write')`.** Streaming multipart parser (`server/lib/multipart.js`) crashed with an uncaught `TypeError` when the request stream's `'end'` event fired while a file part's `ws.end()` flush was still in flight. After consuming a part boundary, `endPart()` synchronously nulled `writeStream` but kept `state` at `STATE_BODY` until the async `ws.end` callback ran. If `req.on('end')` fired during that window, the end handler called `tick()`, which re-entered `STATE_BODY`, found another boundary in the trailing buffer, and called `writePartChunk()` → `writeStream.write(chunk)` on a `null` stream → process-killing `uncaughtException`. Fix: `tick()` now returns early when `pendingFlush > 0`; the existing `endPart` callback already re-invokes `tick()` once the flush completes and state has advanced. Added a regression test that defers the mocked `ws.end()` callback so the bug reproduces without the fix. File: `server/lib/multipart.js`.
+
- **Image Gen status badge stuck on "SD API unreachable" when Local mode is selected.** The page mounts before settings load, so the first `refreshStatus` call goes out with `mode=external` (the fallback in `effectiveMode = selectedMode || status?.mode || 'external'`). The local-mode probe that fires moments later (after settings populate `selectedMode='local'`) returns instantly because it just checks if the Python path is set — but the original external-mode probe is still in flight, blocking on a TCP timeout against the unconfigured SD API URL. When that slow response finally arrived, it overwrote the green "mflux/local" badge with the red "SD API unreachable — Settings" message, even though the Local chip was clearly selected. Token-guarded `refreshStatus` so each call records a monotonically incrementing token and only applies its `setStatus` if its token still matches the latest one — stale responses get silently dropped. File: `client/src/pages/ImageGen.jsx`.
## Changed
diff --git a/server/lib/multipart.js b/server/lib/multipart.js
index ef1ca5ff3e..ad102fb996 100644
--- a/server/lib/multipart.js
+++ b/server/lib/multipart.js
@@ -264,6 +264,11 @@ function streamMultipart(req, boundary, fileFieldName, maxSize, fileFilter, next
const tick = () => {
if (done) return;
+ // Defer while a file flush is in flight: state is still STATE_BODY but
+ // writeStream has been nulled by endPart. Re-entering tick (e.g. from
+ // req.on('end')) would crash on writeStream.write. The endPart callback
+ // re-invokes tick once state has advanced.
+ if (pendingFlush > 0) return;
while (true) {
if (state === STATE_PREAMBLE) {
@@ -325,10 +330,18 @@ function streamMultipart(req, boundary, fileFieldName, maxSize, fileFilter, next
// Found end of part. Emit everything before the boundary, then advance.
if (!writePartChunk(buf.slice(0, idx))) return;
buf = buf.slice(idx + PART_DELIM.length);
- // endPart may be async (file flush) — pause the request, resume after.
+ // Transition state SYNCHRONOUSLY before endPart's async ws.end() runs.
+ // endPart sets writeStream = null synchronously, but its file-flush
+ // callback (which used to set this state) may not fire before
+ // req.on('end') re-enters tick. Without this sync transition, tick
+ // would re-process buf (which now contains the NEXT part) as if we
+ // were still inside the previous part's body and crash on
+ // writeStream.write(chunk) with writeStream === null.
+ state = STATE_AFTER_BOUNDARY;
+ // endPart may still be async (file flush) — pause the request,
+ // resume after the flush completes.
req.pause();
endPart(() => {
- state = STATE_AFTER_BOUNDARY;
req.resume();
tick(); // process anything already buffered
});
diff --git a/server/lib/multipart.test.js b/server/lib/multipart.test.js
index d4535e0c4d..8efa1f2c2c 100644
--- a/server/lib/multipart.test.js
+++ b/server/lib/multipart.test.js
@@ -94,6 +94,51 @@ describe('uploadSingle multipart parser', () => {
expect(req.file?.originalname).toBe('a.png');
});
+ it('does not crash when req end fires while file flush is pending', async () => {
+ // Regression: previously, if the file write stream's end() callback ran
+ // asynchronously (real disk I/O) and `req.on('end')` fired first, the
+ // end handler called tick() while writeStream was already null, crashing
+ // with "Cannot read properties of null (reading 'write')".
+ vi.resetModules();
+ vi.doMock('fs', () => ({
+ createWriteStream: () => {
+ const handlers = {};
+ return {
+ write: () => true,
+ end: (data, cb) => {
+ const callback = typeof data === 'function' ? data : cb;
+ // Defer the callback past the current macrotask so the request's
+ // 'end' event can fire while we're still "flushing".
+ if (callback) setTimeout(callback, 5);
+ },
+ destroy: () => {},
+ on: (evt, fn) => { handlers[evt] = fn; },
+ once: (evt, fn) => { handlers[evt] = fn; },
+ };
+ },
+ }));
+ const { uploadSingle: uploadSingleAsync } = await import('./multipart.js');
+ const req = makeMultipartReq([
+ { name: 'sourceImage', filename: 'a.png', contentType: 'image/png', body: Buffer.from([0xaa, 0xbb, 0xcc]) },
+ { name: 'prompt', body: 'after-file' },
+ ]);
+ let uncaught = null;
+ const onUncaught = (err) => { uncaught = err; };
+ process.once('uncaughtException', onUncaught);
+ await new Promise((resolve, reject) => {
+ const mw = uploadSingleAsync('sourceImage', { limits: { fileSize: 1024 * 1024 } });
+ mw(req, {}, (err) => err ? reject(err) : resolve());
+ });
+ // Wait for any deferred ws.end callbacks to flush so a stray uncaught
+ // exception surfaces before we assert.
+ await new Promise((r) => setTimeout(r, 30));
+ process.removeListener('uncaughtException', onUncaught);
+ expect(uncaught).toBeNull();
+ expect(req.file?.originalname).toBe('a.png');
+ expect(req.body.prompt).toBe('after-file');
+ vi.doUnmock('fs');
+ });
+
it('rejects requests without the multipart Content-Type', async () => {
const stream = Readable.from(['nope']);
stream.headers = { 'content-type': 'application/json' };