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: prevent music-bed double-enqueue clobber, prefer any ready engine over the default

[._.]/ Adam Eivy76d02c14f73f
diff --git a/server/services/creativeDirector/firstPassMusicGen.js b/server/services/creativeDirector/firstPassMusicGen.js
index 8834b080a7..5b50f59c72 100644
--- a/server/services/creativeDirector/firstPassMusicGen.js
+++ b/server/services/creativeDirector/firstPassMusicGen.js
@@ -20,7 +20,16 @@
*/
import { enqueueJob } from '../mediaJobQueue/index.js';
-import { DEFAULT_ENGINE_ID, isEngineReady } from '../pipeline/musicGen.js';
+import { ENGINES, DEFAULT_ENGINE_ID, isEngineReady } from '../pipeline/musicGen.js';
+
+// First provisioned engine in ENGINES' declared order (musicgen, audioldm2,
+// acestep), so a project where only a non-default local backend is installed
+// (e.g. AudioLDM2 but not MusicGen) still gets a first-pass bed instead of
+// silently skipping on a hardcoded DEFAULT_ENGINE_ID check. Returns null when
+// nothing is provisioned.
+function firstReadyEngineId() {
+ return Object.keys(ENGINES).find((id) => isEngineReady(id)) || null;
+}
// Keep the derived prompt bounded — a music-gen prompt is a short mood/style
// brief, not the full treatment. Mirrors PORTRAIT_PROMPT_CHARS' "enough
@@ -56,33 +65,37 @@ export function buildMusicBedPrompt(project) {
* Returns `{ mode, enqueued, jobId? , reason? }`. `mode` echoes the resolved
* engine id (even when skipped) so the response shape stays predictable.
*/
-export async function enqueueFirstPassMusicBed(project, { engine = DEFAULT_ENGINE_ID } = {}) {
+export async function enqueueFirstPassMusicBed(project, { engine } = {}) {
if (!project || typeof project !== 'object' || !project.id) {
- return { mode: engine, enqueued: false, reason: 'no-project' };
+ return { mode: engine || DEFAULT_ENGINE_ID, enqueued: false, reason: 'no-project' };
}
// Never clobber an existing bed — re-running auto-cast with the toggle on
// stays idempotent, same posture as firstPassGen's portrait-exists check.
if (project.musicBed && typeof project.musicBed.filename === 'string' && project.musicBed.filename) {
- return { mode: engine, enqueued: false, reason: 'has-music-bed' };
+ return { mode: engine || DEFAULT_ENGINE_ID, enqueued: false, reason: 'has-music-bed' };
}
- if (!isEngineReady(engine)) {
- return { mode: engine, enqueued: false, reason: 'engine-not-ready' };
+ // Resolve the engine once the project is known to need a render. An
+ // explicit `engine` wins; otherwise prefer any provisioned local backend
+ // over assuming the default (musicgen) is the one installed.
+ const resolvedEngine = engine || firstReadyEngineId() || DEFAULT_ENGINE_ID;
+ if (!isEngineReady(resolvedEngine)) {
+ return { mode: resolvedEngine, enqueued: false, reason: 'engine-not-ready' };
}
const prompt = buildMusicBedPrompt(project);
if (!prompt) {
- return { mode: engine, enqueued: false, reason: 'no-prompt' };
+ return { mode: resolvedEngine, enqueued: false, reason: 'no-prompt' };
}
const queued = enqueueJob({
kind: 'audio',
params: {
prompt,
- engine,
+ engine: resolvedEngine,
// Tag the job so the durable creativeDirectorMusicBedHook files the
// finished track onto this project's `musicBed` field — no mounted
// client required.
creativeDirectorMusicBed: { projectId: project.id },
},
});
- console.log(`🎼 CD first-pass music bed: queued for project ${project.id.slice(0, 8)} (${engine})`);
- return { mode: engine, enqueued: true, jobId: queued.jobId };
+ console.log(`🎼 CD first-pass music bed: queued for project ${project.id.slice(0, 8)} (${resolvedEngine})`);
+ return { mode: resolvedEngine, enqueued: true, jobId: queued.jobId };
}
diff --git a/server/services/creativeDirector/firstPassMusicGen.test.js b/server/services/creativeDirector/firstPassMusicGen.test.js
index 25ba4c4287..a19cfe5930 100644
--- a/server/services/creativeDirector/firstPassMusicGen.test.js
+++ b/server/services/creativeDirector/firstPassMusicGen.test.js
@@ -4,6 +4,7 @@ vi.mock('../mediaJobQueue/index.js', () => ({
enqueueJob: vi.fn(),
}));
vi.mock('../pipeline/musicGen.js', () => ({
+ ENGINES: { musicgen: {}, audioldm2: {}, acestep: {} },
DEFAULT_ENGINE_ID: 'musicgen',
isEngineReady: vi.fn(),
}));
@@ -92,6 +93,14 @@ describe('enqueueFirstPassMusicBed', () => {
expect(isEngineReady).not.toHaveBeenCalled();
});
+ it('prefers a ready non-default engine over the default when the default is not provisioned', async () => {
+ isEngineReady.mockImplementation((id) => id === 'audioldm2');
+ const project = { id: 'proj-1', name: 'Neon Drift', styleSpec: 'synthwave' };
+ const out = await enqueueFirstPassMusicBed(project);
+ expect(out).toEqual({ mode: 'audioldm2', enqueued: true, jobId: 'job-1' });
+ expect(enqueueJob.mock.calls[0][0].params.engine).toBe('audioldm2');
+ });
+
it('honors an explicit engine override', async () => {
const project = { id: 'proj-1', name: 'Neon Drift', styleSpec: 'ace-step full song' };
const out = await enqueueFirstPassMusicBed(project, { engine: 'acestep' });
diff --git a/server/services/creativeDirectorMusicBedHook.js b/server/services/creativeDirectorMusicBedHook.js
index 5936145ef8..1de9ff3a86 100644
--- a/server/services/creativeDirectorMusicBedHook.js
+++ b/server/services/creativeDirectorMusicBedHook.js
@@ -17,7 +17,7 @@
*/
import { createMediaJobImageHook } from './mediaJobImageHook.js';
-import { updateProject } from './creativeDirector/local.js';
+import { getProject, updateProject } from './creativeDirector/local.js';
const hook = createMediaJobImageHook({
label: 'CD music-bed',
@@ -45,12 +45,22 @@ const hook = createMediaJobImageHook({
};
},
// The project may have been deleted between enqueue and completion —
- // updateProject throws 404 in that case; treat it the same as the catalog
- // hook's "gone" case (best-effort, never surfaces past the factory's catch).
- attach: ({ projectId, filename, durationSec, engine, modelId }) =>
- updateProject(projectId, {
+ // getProject/updateProject throw 404 in that case; treat it the same as the
+ // catalog hook's "gone" case (best-effort, never surfaces past the
+ // factory's catch). Re-read the CURRENT project inside this serialized
+ // section first: a project only has one music-bed slot, so if a second
+ // first-pass request queued a duplicate job before the first one finished,
+ // the first completion to attach wins and this later one must not clobber
+ // it (return null — the factory's "nothing applied" signal — instead of
+ // overwriting the existing musicBed).
+ attach: async ({ projectId, filename, durationSec, engine, modelId }) => {
+ const current = await getProject(projectId);
+ if (current?.musicBed?.filename) return null;
+ await updateProject(projectId, {
musicBed: { filename, durationSec, engine, modelId, generatedAt: new Date().toISOString() },
- }).then(() => 'attached'),
+ });
+ return 'attached';
+ },
onAttached: ({ projectId, filename }) => {
console.log(`🎼 CD project ${projectId.slice(0, 8)} ← music bed ${filename}`);
},
diff --git a/server/services/creativeDirectorMusicBedHook.test.js b/server/services/creativeDirectorMusicBedHook.test.js
index 6e85dc149b..073af039a7 100644
--- a/server/services/creativeDirectorMusicBedHook.test.js
+++ b/server/services/creativeDirectorMusicBedHook.test.js
@@ -1,10 +1,12 @@
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
// Mock the project store so the hook's tag-decode + serialize + attach logic
-// is exercised without touching disk or a DB. `updateProject` is reprogrammed
-// per-test to stand in for the durable attach.
+// is exercised without touching disk or a DB. `updateProject`/`getProject` are
+// reprogrammed per-test to stand in for the durable attach + its idempotency
+// re-read.
const updateProject = vi.fn(async (id, patch) => ({ id, ...patch }));
-vi.mock('./creativeDirector/local.js', () => ({ updateProject }));
+const getProject = vi.fn(async () => ({ id: 'proj-1' }));
+vi.mock('./creativeDirector/local.js', () => ({ updateProject, getProject }));
const { mediaJobEvents } = await import('./mediaJobQueue/index.js');
const hook = await import('./creativeDirectorMusicBedHook.js');
@@ -33,6 +35,8 @@ describe('creativeDirectorMusicBedHook', () => {
hook.initCreativeDirectorMusicBedHook();
updateProject.mockReset();
updateProject.mockImplementation(async (id, patch) => ({ id, ...patch }));
+ getProject.mockReset();
+ getProject.mockImplementation(async (id) => ({ id }));
});
afterEach(() => {
@@ -75,11 +79,20 @@ describe('creativeDirectorMusicBedHook', () => {
});
it('does not throw when the attach fails — project deleted mid-render', async () => {
- updateProject.mockRejectedValueOnce(Object.assign(new Error('Project not found'), { status: 404 }));
+ getProject.mockRejectedValueOnce(Object.assign(new Error('Project not found'), { status: 404 }));
mediaJobEvents.emit('completed', completedAudioJob({ params: { creativeDirectorMusicBed: tag() } }));
- await waitFor(() => updateProject.mock.calls.length > 0);
+ await waitFor(() => getProject.mock.calls.length > 0);
await new Promise((r) => setTimeout(r, 20));
// No throw escapes the listener; nothing further to assert beyond "didn't crash".
+ expect(updateProject).not.toHaveBeenCalled();
+ });
+
+ it('does not clobber an already-attached music bed — re-checks inside the serialized section', async () => {
+ getProject.mockImplementationOnce(async (id) => ({ id, musicBed: { filename: 'already-there.wav' } }));
+ mediaJobEvents.emit('completed', completedAudioJob({ params: { creativeDirectorMusicBed: tag() } }));
+ await waitFor(() => getProject.mock.calls.length > 0);
+ await new Promise((r) => setTimeout(r, 20));
+ expect(updateProject).not.toHaveBeenCalled();
});
it('serializes attaches for the same project so concurrent completions do not clobber', async () => {