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
fix: stop SSE downloads aborting instantly on a POST (#4255)
[._.]/ Adam Eivy8e722b7609dc
diff --git a/.changelog/next/fixed-main.md b/.changelog/next/fixed-main.mdindex b6246ea258..1a928c3338 100644--- a/.changelog/next/fixed-main.md+++ b/.changelog/next/fixed-main.md@@ -8,3 +8,4 @@- Music engines whose install failed partway now report as not installed instead of ready — the Install button comes back, generation gives an actionable setup message instead of a Python traceback, and the installer stops refusing with 'already installed'- Local music runtimes now build on a standalone Python instead of a conda base on Windows, where torch installs but cannot load (WinError 1114); an already-broken venv is rebuilt automatically- MusicGen is now shown as unavailable on non-Apple-Silicon machines rather than offering an Install button whose installer skips and reports a confusing failure+- Installing MiniMax Music 3's model weights now actually downloads — the request was aborted before its first byte and the UI reported the no-op as a successful installdiff --git a/server/lib/README.md b/server/lib/README.mdindex 1f02fa52c9..b3235e1c17 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -146,7 +146,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `hfDownload.js` | `downloadHfRepo({repo,revision?,only?,onEvent,pythonPath?})` returning `{promise,kill}` — spawns `scripts/hf_download_repo.py` in a caller-preferred runtime or the shared fallback venvs and emits SSE-friendly stage/progress/complete events. Powers the inline "Download" button next to the model picker. `parseHfDownloadLine(line)` is the wire decoder (`STAGE:download` / `STAGE:bytes` / `STAGE:verify` / `STAGE:complete` / `USER_ERROR`) so a single-file multi-GB pull reports byte progress instead of sitting at 100% for the whole transfer. || `icLoraWeights.js` | IC-LoRA weight registry for the local LTX-2 remix modes (`IC_LORA_MODES`, `IC_LORA_MODE_VALUES`, `listIcLoraWeights()`, `isIcLoraMode(mode)`, `icLoraSpecForMode(mode)`, `icLoraRepos()`, `icLoraWeightCandidates(spec)`, `findCachedIcLoraWeight(spec)`, `resolveIcLoraWeight(mode)` → `{path,cached,spec}`). Single source of truth mapping each remix mode (`ic-control`, `ic-colorize`, `ic-ingredients`) → its HF repo/filename, reference-count rule, per-weight `referenceDownscaleFactor` (read from the weight's safetensors metadata, never assumed), and input surface (`referenceKind: 'video' | 'image'`). A `requiresPreDownload` spec (Ingredients) suppresses `resolveIcLoraWeight`'s bare-repo-id fallback — the pipeline would `snapshot_download` it, and its candidates are a gated first-party repo plus a ~708 GB aggregate mirror, so the weight must be pre-fetched single-file instead. Also owns the two rules derived from that data: `assertIcReferenceCount(spec,count,fail)` / `describeIcReferenceRange(spec)` and `icResolutionIssue(spec,w,h)` (the output-resolution divisibility its reference encoder imposes). Mirrored to `client/src/lib/videoGenParams.js`; `icLoraWeights.parity.test.js` diffs the two. || `sseHeaders.js` | `SSE_HEADERS` — the canonical SSE response headers (incl. `X-Accel-Buffering:no`) in a dependency-free module so any producer (`sseDownload.js`, `sseUtils.js`) can share them without pulling in a heavier module's transitive imports. |-| `sseDownload.js` | `startHfDownloadStream({req,res,repo|repos|fallbacks,alreadyDownloadedMessage,pythonPath?})`, `openSseStream(res)` — shared SSE driver for model downloads. Required targets may name an immutable `revision` and exact `only` files, fallback chains are first-success, and the cross-route in-flight Map deduplicates pulls. |+| `sseDownload.js` | `startHfDownloadStream({req,res,repo|repos|fallbacks,alreadyDownloadedMessage,pythonPath?})`, `openSseStream(res)`, `onClientDisconnect(req,res,cb)` — shared SSE driver for model downloads. **Use `onClientDisconnect`, never `req.on('close')`**: on a POST whose body `express.json()` already consumed, `req` is complete at handler entry and emits `close` immediately, which reads as an instant disconnect and cancels work that never started. Required targets may name an immutable `revision` and exact `only` files, fallback chains are first-success, and the cross-route in-flight Map deduplicates pulls. || `installLogger.js` | `createInstallLogger({installer,target})` → `{start,onEvent,success,failure,cancel}` — server-console chokepoint for install/venv-setup SSE flows (the install-side analogue of `sseDownload.js`). Logs a START line, throttled heartbeats + `stage` milestones (not every raw pip/bash line), and the OUTCOME (success/fail/cancel) with elapsed time. `onEvent(ev)` auto-detects terminal `complete`/`error` SSE events. Used by the music/video runtime installers and the FLUX.2 venv bootstrap. |## File & I/Odiff --git a/server/lib/sseDownload.js b/server/lib/sseDownload.jsindex 428f101938..9509df860f 100644--- a/server/lib/sseDownload.js+++ b/server/lib/sseDownload.js@@ -29,6 +29,34 @@ export function openSseStream(res) {return { send, safeEnd };}+/**+ * Run `onDisconnect` when the CLIENT goes away mid-stream.+ *+ * Use this instead of `req.on('close', …)`. On a POST whose JSON body+ * `express.json()` has already consumed, the request is complete before the+ * handler runs (`req.complete === true`), so Node emits `'close'` on the very+ * next tick — a handler that attaches the listener before its first `await`+ * reads that as an instant client disconnect and cancels work that never+ * started. `POST /api/music/models` did exactly that: the download aborted+ * before its first frame, the stream closed empty, and the UI reported the+ * install as a success. GET routes are unaffected (nothing to consume), which+ * is why every other SSE endpoint here looked fine.+ *+ * The response is the right thing to watch: `res` `'close'` fires only when the+ * response actually closes, and `writableEnded` separates our own `safeEnd()`+ * from a genuine disconnect.+ *+ * @param {import('http').IncomingMessage} _req - unused; kept so call sites read as (req, res)+ * @param {import('http').ServerResponse} res+ * @param {() => void} onDisconnect+ */+export function onClientDisconnect(_req, res, onDisconnect) {+ res.on('close', () => {+ if (res.writableEnded) return; // we ended it — normal completion+ onDisconnect();+ });+}+export async function startHfDownloadStream({ req, res, repo, repos, fallbacks, cachedFile = null, alreadyDownloadedMessage, force = false, pythonPath = null }) {// Three input shapes, two semantics:// - `repo` (single string) / `repos` (ordered array) — ALL must succeed. Used@@ -75,11 +103,11 @@ export async function startHfDownloadStream({ req, res, repo, repos, fallbacks,// client closing mid-await would land after spawn with no kill path.let currentHandle = null;let aborted = false;- req.on('close', () => {+ onClientDisconnect(req, res, () => {aborted = true;- // Only a live handle means a download was mid-flight — `close` also fires- // on normal completion (currentHandle is nulled after each repo), so this- // guard keeps the cancel line out of the log on a clean finish.+ // Only a live handle means a download was mid-flight, so this keeps the+ // cancel line out of the log when the client simply navigated away between+ // repos.if (currentHandle) {console.log(`🛑 HuggingFace download cancelled (client disconnect)`);currentHandle.kill();diff --git a/server/lib/sseDownload.test.js b/server/lib/sseDownload.test.jsindex 5584abadca..48225fc0ba 100644--- a/server/lib/sseDownload.test.js+++ b/server/lib/sseDownload.test.js@@ -21,18 +21,22 @@ import { startHfDownloadStream } from './sseDownload.js';import { inspectModelCache } from './hfCache.js';import { downloadHfRepo } from './hfDownload.js';-// Minimal req/res doubles — req only needs `.on('close')`; res captures the-// SSE frames written so we can assert the terminal `complete` message.+// Minimal req/res doubles. Disconnect detection lives on `res` (see+// onClientDisconnect), so `res.on` records handlers and `disconnect()` fires+// them the way a real client hang-up would.const makeReqRes = () => {const frames = [];const req = { on: vi.fn() };+ const handlers = {};const res = {writableEnded: false,writeHead: vi.fn(),write: vi.fn((chunk) => { frames.push(chunk); }),end: vi.fn(function end() { res.writableEnded = true; }),+ on: vi.fn((event, cb) => { handlers[event] = cb; }),};- return { req, res, frames };+ const disconnect = () => handlers.close?.();+ return { req, res, frames, disconnect };};const parseFrames = (frames) => frames@@ -87,16 +91,18 @@ describe('startHfDownloadStream server-side logging', () => {let logSpy;let errorSpy;- // req double whose `close` handler we can fire on demand (to simulate the- // EventSource client hanging up mid-download).+ // res double whose `close` handler we can fire on demand (to simulate the+ // EventSource client hanging up mid-download). The handler lives on `res`,+ // not `req` — see onClientDisconnect.const makeLoggingReqRes = () => {let closeHandler;- const req = { on: vi.fn((ev, cb) => { if (ev === 'close') closeHandler = cb; }) };+ const req = { on: vi.fn() };const res = {writableEnded: false,writeHead: vi.fn(),write: vi.fn(() => true),end: vi.fn(function end() { res.writableEnded = true; }),+ on: vi.fn((ev, cb) => { if (ev === 'close') closeHandler = cb; }),};return { req, res, fireClose: () => closeHandler?.() };};@@ -429,3 +435,74 @@ describe('startHfDownloadStream repos (ALL must succeed)', () => {expect(parseFrames(frames).at(-1)).toMatchObject({ type: 'complete' });});});++// The bug this guards was invisible to the doubles above: it depended on Node's+// real `IncomingMessage` lifecycle, so it needs a real socket. `express.json()`+// finishes reading a POST body before the handler runs, leaving `req.complete+// === true` — so a `req.on('close')` listener attached before the first `await`+// fired immediately and read as a client disconnect. The download aborted+// before its first frame, the stream closed empty, and because an empty stream+// carries no `error` event the UI reported the install as a success.+describe('startHfDownloadStream over a real socket (POST body already consumed)', () => {+ let server;+ let baseUrl;++ const startServer = async () => {+ const express = (await import('express')).default;+ const app = express();+ app.use(express.json());+ app.post('/download', (req, res) => {+ // Mirrors POST /api/music/models: hand the response straight to the driver.+ startHfDownloadStream({ req, res, repo: 'org/model' });+ });+ app.get('/download', (req, res) => {+ startHfDownloadStream({ req, res, repo: 'org/model' });+ });+ server = app.listen(0);+ await new Promise((resolve) => server.once('listening', resolve));+ baseUrl = `http://127.0.0.1:${server.address().port}`;+ };++ const collect = async (init) => {+ const res = await fetch(`${baseUrl}/download`, init);+ const text = await res.text();+ return text.split('\n\n').map((f) => f.replace(/^data: /, '').trim()).filter(Boolean).map((f) => JSON.parse(f));+ };++ beforeEach(async () => {+ vi.clearAllMocks();+ inspectModelCache.mockResolvedValue({ cached: false, sizeBytes: 0 });+ downloadHfRepo.mockImplementation(({ onEvent }) => ({+ promise: Promise.resolve().then(() => {+ onEvent({ type: 'progress', stage: 'download', step: 1, total: 1, file: 'weights.safetensors' });+ return { ok: true, sizeBytes: 1234 };+ }),+ kill: vi.fn(),+ }));+ await startServer();+ });++ afterEach(async () => {+ await new Promise((resolve) => server.close(resolve));+ });++ it('downloads on a POST instead of closing an empty stream', async () => {+ const events = await collect({+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ engine: 'minimax-music3', repo: 'org/model' }),+ });++ expect(downloadHfRepo).toHaveBeenCalledTimes(1);+ expect(events.length).toBeGreaterThan(0);+ expect(events.at(-1)).toMatchObject({ type: 'complete' });+ // The exact shape of the old failure: a 200 that streamed nothing at all.+ expect(events).not.toHaveLength(0);+ });++ it('still downloads on a GET (the shape every other caller uses)', async () => {+ const events = await collect({ method: 'GET' });+ expect(downloadHfRepo).toHaveBeenCalledTimes(1);+ expect(events.at(-1)).toMatchObject({ type: 'complete' });+ });+});