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

address review (codex): register-then-rollback install + reject unknown modelId

[._.]/ Adam Eivy1c32d33d8050
diff --git a/server/routes/music.js b/server/routes/music.js
index e1c2942bbe..a372729f9c 100644
--- a/server/routes/music.js
+++ b/server/routes/music.js
@@ -74,12 +74,14 @@ router.get('/models/:engine', asyncHandler(async (req, res) => {
res.json({ models: await listEngineModels(req.params.engine) });
}));
-// POST /api/music/models — STREAM the HF download as SSE (text/event-stream),
-// then register the repo only if it actually landed in the cache. Registering
-// AFTER a successful download (rather than up front) means a typo / private /
-// gated / auth-failed repo never persists into data/audio-models.json as a
-// bogus "installed" model that a later /engines list would surface and that
-// generation would fail on.
+// POST /api/music/models — register the repo, STREAM its HF download as SSE
+// (text/event-stream), then ROLL BACK the registration if the download didn't
+// actually land. Registering up front (before the stream's `complete` frame)
+// means the model is durably persisted by the time the client's post-stream
+// `/engines` refresh runs — no race. The rollback (de-register when the cache
+// is still empty after a failed/cancelled download) means a typo / private /
+// gated / auth-failed repo doesn't linger as a bogus "installed" model. Net:
+// a completed install is always registered, a failed one never is.
router.post('/models', asyncHandler(async (req, res) => {
const body = validateRequest(installSchema, req.body ?? {});
if (!ENGINES[body.engine]) throw new ServerError('Unknown audio engine', { status: 400, code: 'AUDIO_MODEL_UNKNOWN_ENGINE' });
@@ -90,16 +92,17 @@ router.post('/models', asyncHandler(async (req, res) => {
throw new ServerError(`${ENGINES[body.engine].name} does not support custom HuggingFace models`, { status: 400, code: 'AUDIO_MODEL_ENGINE_FIXED' });
}
if (!isValidRepoId(body.repo)) throw new ServerError('Invalid HuggingFace repo id', { status: 400, code: 'AUDIO_MODEL_INVALID_REPO' });
+ // Register first so it's durable before the stream signals completion.
+ await addAudioModel({ engine: body.engine, repo: body.repo, name: body.name });
// Hand the response to the shared SSE driver — it owns writeHead/end + the
- // in-flight dedupe + client-disconnect kill. It resolves after the stream ends
- // (the HTTP response is already closed by then, so the post-stream work below
- // is a side effect only — it can't change what the client received).
+ // in-flight dedupe + client-disconnect kill. Resolves after the stream ends.
await startHfDownloadStream({ req, res, repo: body.repo });
- // Register only if the weights are actually present now — a failed/cancelled
- // download leaves the cache empty and we must NOT persist the model.
+ // Roll back if the weights aren't actually present now (failed/cancelled
+ // download) so a bogus repo doesn't persist. Best-effort: a rollback failure
+ // is logged by the service, not surfaced (the response already closed).
const cached = await inspectModelCache(body.repo).catch(() => ({ cached: false }));
- if (cached.cached) {
- await addAudioModel({ engine: body.engine, repo: body.repo, name: body.name }).catch(() => {});
+ if (!cached.cached) {
+ await removeAudioModel({ engine: body.engine, id: body.repo }).catch(() => {});
}
}));
@@ -152,14 +155,20 @@ router.post('/generate', asyncHandler(async (req, res) => {
if (!existing) throw new ServerError('Track not found', { status: 404, code: 'NOT_FOUND' });
}
- // Resolve a USER-INSTALLED model id to its HF repo so the sidecar renders with
- // the installed checkpoint instead of falling back to the engine default. A
- // shipped model id leaves `repo` undefined (generateMusic uses the registry).
+ // Resolve the requested model against the engine's merged list. An unknown
+ // modelId (stale UI selection, removed model) must FAIL FAST — otherwise
+ // `repo` stays undefined and generateMusic silently renders the engine default,
+ // spending minutes producing audio from the wrong checkpoint. A user-installed
+ // id resolves to its HF repo (passed to the sidecar); a shipped id leaves
+ // `repo` undefined (generateMusic uses its own registry for shipped models).
let repo;
if (body.modelId) {
const merged = await listEngineModels(engine.id);
const picked = merged.find((m) => m.id === body.modelId);
- if (picked?.userAdded) repo = picked.repo || picked.id;
+ if (!picked) {
+ throw new ServerError(`Unknown model for ${engine.name}: ${body.modelId}`, { status: 400, code: 'PIPELINE_MUSIC_UNKNOWN_MODEL' });
+ }
+ if (picked.userAdded) repo = picked.repo || picked.id;
}
// generateMusic throws a typed ServerError (503 venv-missing / 500 sidecar
diff --git a/server/routes/music.test.js b/server/routes/music.test.js
index 5f37aa2f5a..decb459223 100644
--- a/server/routes/music.test.js
+++ b/server/routes/music.test.js
@@ -71,8 +71,10 @@ describe('music routes', () => {
// generateMusic leaks into the next test.
gen.generateMusic.mockReset();
models.list.mockReset();
- models.add.mockReset();
- models.remove.mockReset();
+ // add/remove return promises by default so the route's `.catch()` chains
+ // don't throw on an undefined return (mockReset clears the impl).
+ models.add.mockReset().mockResolvedValue({});
+ models.remove.mockReset().mockResolvedValue(true);
tracks.getTrack.mockReset();
tracks.createTrack.mockReset().mockImplementation(async (input) => ({ id: 'track-new', ...input }));
tracks.updateTrack.mockReset().mockImplementation(async (id, patch) => ({ id, ...patch }));
@@ -122,12 +124,15 @@ describe('music routes', () => {
expect(models.add).toHaveBeenCalledWith({ engine: 'musicgen', repo: 'facebook/musicgen-large', name: undefined });
});
- it('POST /models does NOT register the model when the download did not land', async () => {
+ it('POST /models rolls back the registration when the download did not land', async () => {
cache.cached = false; // download failed/cancelled → repo not in cache
const r = await request(app).post('/api/music/models').send({ engine: 'musicgen', repo: 'someorg/typo-repo' });
expect(r.status).toBe(200); // the SSE stream still completes (with its error frames)
expect(sse.run).toHaveBeenCalled();
- expect(models.add).not.toHaveBeenCalled();
+ // Registered up front (durable before the client's refresh), then rolled back
+ // because the weights never landed — net: not persisted.
+ expect(models.add).toHaveBeenCalled();
+ expect(models.remove).toHaveBeenCalledWith({ engine: 'musicgen', id: 'someorg/typo-repo' });
});
it('POST /models rejects an unknown engine / invalid repo before downloading', async () => {
@@ -212,6 +217,14 @@ describe('music routes', () => {
expect(gen.generateMusic).toHaveBeenCalledWith(expect.objectContaining({ repo: 'someorg/big-musicgen', modelId: 'someorg/big-musicgen' }));
});
+ it('POST /generate rejects an unknown modelId BEFORE rendering', async () => {
+ models.list.mockResolvedValueOnce([{ id: 'm', name: 'M', userAdded: false }]);
+ const r = await request(app).post('/api/music/generate').send({ prompt: 'x', engine: 'musicgen', modelId: 'gone/removed' });
+ expect(r.status).toBe(400);
+ expect(r.body.code).toBe('PIPELINE_MUSIC_UNKNOWN_MODEL');
+ expect(gen.generateMusic).not.toHaveBeenCalled();
+ });
+
it('POST /generate creating a track with albumId appends it to the album tracklist', async () => {
albums.getAlbum.mockResolvedValueOnce({ id: 'album-1', trackIds: ['track-0'] });
tracks.createTrack.mockResolvedValueOnce({ id: 'track-gen', title: 'x', albumId: 'album-1' });