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
feat([issue-1928]): first-pass music bed generation for Creative Director auto-cast
[._.]/ Adam Eivyf250919e0893
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex bb31b87d0c..c2a25ab2e7 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -30,6 +30,7 @@- **CoS `claim-issue` swarm mode** — the schedule config (CoS → Schedule → Claim Issue, and the resolved `claim-work` flow) gains a **Swarm Mode** selector that runs each scheduled claim in slashdo `/do:next --swarm` mode: instead of claiming one issue per run, it partitions up to N (2–6) mutually-independent open issues, fans out one worktree subagent per issue (each running the unchanged single-issue claim → implement → review flow), and serializes only the merges. Configurable globally with a per-app override; GitHub/GitLab issue trackers only (plan-task / JIRA are a no-op). The swarm directive is prepended to the dispatched prompt only when enabled, so it's a pure opt-in wrapper with no prompt-default version bump; `swarmCount` is range-validated (0 = off, 2–6 = swarm size) in `sanitizeTaskMetadata`.- **Creative Director auto-compose** — the Overview tab's Auto-cast control now has a `+ treatment` toggle (shown only before a treatment exists): with it on, once the director seeds the cast from the catalog it autonomously writes a first-pass treatment + scene plan grounded in that cast, instead of stopping at cast seeding. Director-first — the autonomous treatment is a starting point you keep editing on the same board, and it never clobbers an existing treatment. (#1817)- **Creative Director first-pass portraits** — the Overview tab's Auto-cast control gains a `+ portraits` toggle: with it on, once the director seeds the cast from the catalog it queues an on-model portrait render for each newly-cast member that has no portrait yet, so the cast "arrives on-model" without hand-rendering each ingredient. Reuses the existing media-job queue and the durable catalog image-attach hook (the render lands as the ingredient's portrait even if you've navigated away), is strictly optional and idempotent (members that already have a portrait are skipped), and seeds only the queue-backed image-gen modes (local / codex) — external SD-API and a disabled codex are skipped gracefully rather than failing the auto-cast. (#1818)+- **[issue-1928] First-pass music bed** — auto-cast can now optionally generate a first-pass background-music render for the project itself (a new `'audio'` media-job kind backed by the existing local MusicGen/AudioLDM2/ACE-Step generators), landing on the project's `musicBed` field via a durable completion hook once the render finishes — even if you've navigated away. Skips gracefully when no local audio-gen engine is provisioned, and re-running auto-cast never clobbers an existing bed.- Shell page now has a **Fullscreen** button that promotes the terminal to a full-viewport overlay (above the sidebar), hiding the stacked header/tabs/quick-commands toolbars so the TUI gets the whole screen — a major mobile usability win where those toolbars previously ate most of the display. Fullscreen keeps a compact, horizontally-scrollable control bar (Exit, Ctrl+C, Paste, arrow/Enter keys) so you can still drive a TUI by thumb, and the Ctrl+C/Paste labels now collapse on small screens to save width.- OpenCode Ollama **TUI** provider for CoS tasks. The TUI completion workflow is now provider-aware: a slashdo-free TUI (OpenCode, which doesn't load Claude Code `/do:*` slash commands) gets a plain `git` + forge-CLI commit → push → open-PR-for-review → `.agent-done` sentinel handoff instead of `/do:pr` / `/do:push`, so an OpenCode TUI agent can actually complete an automated task. The manual path opens the PR/MR (GitHub `gh` or GitLab `glab`) for review without auto-merging. Ships `opencode-ollama-tui` to existing installs via migration 152. (#1814)diff --git a/server/index.js b/server/index.jsindex 7e4dca4bf3..337551af20 100644--- a/server/index.js+++ b/server/index.js@@ -121,6 +121,7 @@ import { initCatalogImageAttachHook } from './services/catalogImageAttachHook.jsimport { initWritersRoomSceneImageHook } from './services/writersRoomSceneImageHook.js';import { initMusicVideoSceneImageHook } from './services/musicVideoSceneImageHook.js';import { initMusicVideoSceneVideoHook } from './services/musicVideoSceneVideoHook.js';+import { initCreativeDirectorMusicBedHook } from './services/creativeDirectorMusicBedHook.js';import { initComicPagesFilenameHook } from './services/pipeline/comicPagesFilenameHook.js';import { initStoryboardsFilenameHook } from './services/pipeline/storyboardsFilenameHook.js';import { initSeasonCoverFilenameHook } from './services/pipeline/seasonCoverFilenameHook.js';@@ -749,6 +750,11 @@ ensureSelf()// board unmounted mid-render (#1760 Phase 1). Also depends on the queue// being loaded.initMusicVideoSceneVideoHook();+ // Creative Director music-bed hook — durably files a queued first-pass+ // audio render onto its project's `musicBed` field on completion, even if+ // the requesting client unmounted mid-render (#1928). Also depends on the+ // queue being loaded.+ initCreativeDirectorMusicBedHook();// Pipeline filename hooks — stamp `filename` onto stage records on// media-job completion so the UI can still render them after the// 24h media-job archive TTL elapses.diff --git a/server/lib/creativeDirectorValidation.js b/server/lib/creativeDirectorValidation.jsindex f39ef27dba..64b5d49e6f 100644--- a/server/lib/creativeDirectorValidation.js+++ b/server/lib/creativeDirectorValidation.js@@ -106,6 +106,12 @@ export const creativeDirectorAutoCastApplySchema = z.object({// Reuses the durable media-job → catalog attach hook (#1359); strictly optional// and only seeds queue-backed image-gen modes (local / codex).generateFirstPass: z.boolean().optional(),+ // First-pass music bed (#1928, split from #1867): when true, enqueue an+ // optional background audio render for the project so it "arrives" with a+ // mood-setting bed. Reuses the durable media-job → project attach hook+ // (creativeDirectorMusicBedHook); strictly optional and skips gracefully if+ // no local audio-gen engine is provisioned.+ generateFirstPassMusicBed: z.boolean().optional(),});// Update is restricted to a few editable fields. modelId / aspectRatio /diff --git a/server/routes/creativeDirector.js b/server/routes/creativeDirector.jsindex 8aaa7dfdac..dc09598cd3 100644--- a/server/routes/creativeDirector.js+++ b/server/routes/creativeDirector.js@@ -29,6 +29,7 @@ import {} from '../services/creativeDirector/local.js';import { suggestCastForBrief, applyAutoCastToProject, toSuggestionView } from '../services/creativeDirector/autoCast.js';import { enqueueFirstPassPortraits } from '../services/creativeDirector/firstPassGen.js';+import { enqueueFirstPassMusicBed } from '../services/creativeDirector/firstPassMusicGen.js';import { startCreativeDirectorProject } from '../services/creativeDirector/completionHook.js';import { createSmokeTestProject } from '../services/creativeDirector/smokeTest.js';@@ -107,7 +108,7 @@ router.delete('/:id', asyncHandler(async (req, res) => {// treatment as they land. The response carries `composing` so the UI can tell// the user the director took over.router.post('/:id/auto-cast', asyncHandler(async (req, res) => {- const { brief, types, limit, compose, generateFirstPass } = validateRequest(creativeDirectorAutoCastApplySchema, req.body);+ const { brief, types, limit, compose, generateFirstPass, generateFirstPassMusicBed } = validateRequest(creativeDirectorAutoCastApplySchema, req.body);const result = await applyAutoCastToProject(req.params.id, { brief, types, limit });const project = result.project;const cast = project?.cast;@@ -135,7 +136,26 @@ router.post('/:id/auto-cast', asyncHandler(async (req, res) => {return null;});}- res.json({ ...result, composing, ...(firstPass ? { firstPass } : {}) });+ // First-pass music bed (#1928, split from #1867): optional sibling step —+ // enqueue one background audio render for the project itself (not a catalog+ // ingredient, see firstPassMusicGen.js doc comment). Gated only on the+ // project existing (unlike portraits, it doesn't depend on auto-cast having+ // added new members — a re-running director may want a bed even when the+ // cast was already seeded).+ let firstPassMusicBed = null;+ if (generateFirstPassMusicBed && project) {+ firstPassMusicBed = await enqueueFirstPassMusicBed(project)+ .catch((e) => {+ console.log(`⚠️ CD first-pass music bed failed: ${e.message}`);+ return null;+ });+ }+ res.json({+ ...result,+ composing,+ ...(firstPass ? { firstPass } : {}),+ ...(firstPassMusicBed ? { firstPassMusicBed } : {}),+ });}));// Agent-callable: write the treatment doc.diff --git a/server/routes/creativeDirector.test.js b/server/routes/creativeDirector.test.jsindex 1346e92cfa..5cc0a2a84a 100644--- a/server/routes/creativeDirector.test.js+++ b/server/routes/creativeDirector.test.js@@ -31,10 +31,17 @@ vi.mock('../services/creativeDirector/firstPassGen.js', () => ({enqueueFirstPassPortraits: vi.fn(async () => ({ mode: 'local', enqueued: [], skipped: [] })),}));+// Mock first-pass music-bed gen (#1928) so the route test doesn't pull the+// real mediaJobQueue/musicGen graph; the route's job is to gate + dispatch.+vi.mock('../services/creativeDirector/firstPassMusicGen.js', () => ({+ enqueueFirstPassMusicBed: vi.fn(async () => ({ mode: 'musicgen', enqueued: false, reason: 'no-prompt' })),+}));+import * as cdService from '../services/creativeDirector/local.js';import * as autoCast from '../services/creativeDirector/autoCast.js';import * as hook from '../services/creativeDirector/completionHook.js';import * as firstPass from '../services/creativeDirector/firstPassGen.js';+import * as firstPassMusicBed from '../services/creativeDirector/firstPassMusicGen.js';import creativeDirectorRoutes from './creativeDirector.js';describe('creativeDirector routes', () => {@@ -408,4 +415,60 @@ describe('creativeDirector routes', () => {expect(autoCast.applyAutoCastToProject).not.toHaveBeenCalled();});});++ describe('POST /:id/auto-cast — first-pass music bed (#1928)', () => {+ it('enqueues a first-pass music bed and returns the summary', async () => {+ autoCast.applyAutoCastToProject.mockResolvedValue({+ project: { id: 'cd-1', name: 'A', cast: [{ ingredientId: 'p1' }] }, added: [{ ingredientId: 'p1' }], suggestions: [],+ });+ firstPassMusicBed.enqueueFirstPassMusicBed.mockResolvedValue({ mode: 'musicgen', enqueued: true, jobId: 'job-1' });+ const r = await request(app).post('/api/creative-director/cd-1/auto-cast').send({ generateFirstPassMusicBed: true });+ expect(r.status).toBe(200);+ expect(firstPassMusicBed.enqueueFirstPassMusicBed).toHaveBeenCalledWith(+ expect.objectContaining({ id: 'cd-1', name: 'A' }),+ );+ expect(r.body.firstPassMusicBed).toEqual({ mode: 'musicgen', enqueued: true, jobId: 'job-1' });+ });++ it('does not enqueue when generateFirstPassMusicBed is omitted', async () => {+ autoCast.applyAutoCastToProject.mockResolvedValue({+ project: { id: 'cd-1', cast: [{ ingredientId: 'p1' }] }, added: [{ ingredientId: 'p1' }], suggestions: [],+ });+ const r = await request(app).post('/api/creative-director/cd-1/auto-cast').send({});+ expect(r.status).toBe(200);+ expect(firstPassMusicBed.enqueueFirstPassMusicBed).not.toHaveBeenCalled();+ expect(r.body.firstPassMusicBed).toBeUndefined();+ });++ it('does not require added members — unlike portraits, it can run on a re-cast with no new members', async () => {+ autoCast.applyAutoCastToProject.mockResolvedValue({+ project: { id: 'cd-1', cast: [{ ingredientId: 'p1' }] }, added: [], suggestions: [],+ });+ firstPassMusicBed.enqueueFirstPassMusicBed.mockResolvedValue({ mode: 'musicgen', enqueued: true, jobId: 'job-1' });+ const r = await request(app).post('/api/creative-director/cd-1/auto-cast').send({ generateFirstPassMusicBed: true });+ expect(r.status).toBe(200);+ expect(firstPassMusicBed.enqueueFirstPassMusicBed).toHaveBeenCalled();+ expect(r.body.firstPassMusicBed).toEqual({ mode: 'musicgen', enqueued: true, jobId: 'job-1' });+ });++ it('composes, generates first-pass portraits, and the music bed together', async () => {+ autoCast.applyAutoCastToProject.mockResolvedValue({+ project: { id: 'cd-1', cast: [{ ingredientId: 'p1' }] }, added: [{ ingredientId: 'p1' }], suggestions: [],+ });+ firstPass.enqueueFirstPassPortraits.mockResolvedValue({ mode: 'local', enqueued: [{ ingredientId: 'p1', jobId: 'j' }], skipped: [] });+ firstPassMusicBed.enqueueFirstPassMusicBed.mockResolvedValue({ mode: 'musicgen', enqueued: true, jobId: 'job-2' });+ const r = await request(app).post('/api/creative-director/cd-1/auto-cast')+ .send({ compose: true, generateFirstPass: true, generateFirstPassMusicBed: true });+ expect(r.status).toBe(200);+ expect(r.body.composing).toBe(true);+ expect(r.body.firstPass).toEqual({ mode: 'local', enqueued: [{ ingredientId: 'p1', jobId: 'j' }], skipped: [] });+ expect(r.body.firstPassMusicBed).toEqual({ mode: 'musicgen', enqueued: true, jobId: 'job-2' });+ });++ it('400s on a non-boolean generateFirstPassMusicBed', async () => {+ const r = await request(app).post('/api/creative-director/cd-1/auto-cast').send({ generateFirstPassMusicBed: 'yes' });+ expect(r.status).toBe(400);+ expect(autoCast.applyAutoCastToProject).not.toHaveBeenCalled();+ });+ });});diff --git a/server/services/audioGen/events.js b/server/services/audioGen/events.jsnew file mode 100644index 0000000000..0c0c28c4c1--- /dev/null+++ b/server/services/audioGen/events.js@@ -0,0 +1,9 @@+import { EventEmitter } from 'events';++// Mirrors imageGenEvents/videoGenEvents/trainingEvents — the mediaJobQueue+// emitter contract every gen module rides (`progress`/`activity`/`completed`/+// `failed`, keyed by `generationId`). See server/services/imageGenEvents.js for+// the maxListeners rationale; audio jobs are lower-volume (no Codex-style+// parallel lane) but the cap is cheap insurance against the same warning.+export const audioGenEvents = new EventEmitter();+audioGenEvents.setMaxListeners(200);diff --git a/server/services/audioGen/local.js b/server/services/audioGen/local.jsnew file mode 100644index 0000000000..2023ef02da--- /dev/null+++ b/server/services/audioGen/local.js@@ -0,0 +1,54 @@+/**+ * Audio job-kind adapter for the media job queue (#1928).+ *+ * The queue (server/services/mediaJobQueue/index.js) dispatches every job kind+ * through an emitter contract shared with video/image/training:+ * `<kind>Events.emit('completed' | 'failed', { generationId, ... })`, optionally+ * preceded by `'activity'`/`'progress'` events the idle watchdog listens for.+ * `generateMusic` (server/services/pipeline/musicGen.js) is a plain awaited+ * function used directly by the Pipeline Audio routes — it has no queue+ * awareness and no reason to gain any, since it's also called synchronously+ * from a request handler. This module is the thin bridge: it calls the real+ * generator and translates its outcome into the queue's expected events, so+ * adding the `'audio'` job kind required zero changes to the actual generation+ * code path.+ *+ * `onActivity` threads through to `generateMusic`'s sidecar STAGE: lines so the+ * queue's idle watchdog resets on genuine progress instead of a flat timeout —+ * the same posture as the image/video gen modules' stderr-line activity pings.+ */++import { generateMusic } from '../pipeline/musicGen.js';+import { audioGenEvents } from './events.js';++// jobId → AbortController, so cancelJob() can interrupt an in-flight render.+const controllers = new Map();++export async function generateAudio({ jobId, prompt, lyrics, engine, durationSec, modelId, repo }) {+ const controller = new AbortController();+ controllers.set(jobId, controller);+ try {+ const result = await generateMusic({+ prompt,+ lyrics,+ engine,+ durationSec,+ modelId,+ repo,+ signal: controller.signal,+ onActivity: () => audioGenEvents.emit('activity', { generationId: jobId }),+ });+ audioGenEvents.emit('completed', { generationId: jobId, ...result });+ } catch (err) {+ audioGenEvents.emit('failed', { generationId: jobId, error: err.message });+ } finally {+ controllers.delete(jobId);+ }+}++// Cancel: aborts the sidecar via the same AbortSignal generateMusic threads to+// its child process. A no-op if the job already settled (controller removed in+// the `finally` above) — mirrors the other gen modules' cancel() contract.+export function cancel(jobId) {+ controllers.get(jobId)?.abort();+}diff --git a/server/services/audioGen/local.test.js b/server/services/audioGen/local.test.jsnew file mode 100644index 0000000000..6b961a8733--- /dev/null+++ b/server/services/audioGen/local.test.js@@ -0,0 +1,84 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';++vi.mock('../pipeline/musicGen.js', () => ({+ generateMusic: vi.fn(),+}));++import { generateMusic } from '../pipeline/musicGen.js';+import { generateAudio, cancel } from './local.js';+import { audioGenEvents } from './events.js';++beforeEach(() => {+ vi.clearAllMocks();+});++describe('generateAudio', () => {+ it('calls generateMusic and emits completed with the result merged onto generationId', async () => {+ generateMusic.mockResolvedValue({ filename: 'music-gen-x.wav', durationSec: 12, modelId: 'musicgen-medium', model: 'MusicGen Medium', engine: 'musicgen' });+ const onCompleted = vi.fn();+ audioGenEvents.once('completed', onCompleted);++ await generateAudio({ jobId: 'job-1', prompt: 'a moody synth bed', engine: 'musicgen', durationSec: 12 });++ expect(generateMusic).toHaveBeenCalledWith(expect.objectContaining({+ prompt: 'a moody synth bed', engine: 'musicgen', durationSec: 12,+ signal: expect.any(AbortSignal),+ onActivity: expect.any(Function),+ }));+ expect(onCompleted).toHaveBeenCalledWith({+ generationId: 'job-1', filename: 'music-gen-x.wav', durationSec: 12,+ modelId: 'musicgen-medium', model: 'MusicGen Medium', engine: 'musicgen',+ });+ });++ it('emits failed with the error message when generateMusic throws', async () => {+ generateMusic.mockRejectedValue(new Error('runtime not found'));+ const onFailed = vi.fn();+ audioGenEvents.once('failed', onFailed);++ await generateAudio({ jobId: 'job-2', prompt: 'x' });++ expect(onFailed).toHaveBeenCalledWith({ generationId: 'job-2', error: 'runtime not found' });+ });++ it('forwards onActivity pings as audioGenEvents activity events keyed by jobId', async () => {+ let capturedOnActivity;+ generateMusic.mockImplementation(async ({ onActivity }) => {+ capturedOnActivity = onActivity;+ onActivity();+ return { filename: 'f.wav' };+ });+ const onActivityEvent = vi.fn();+ audioGenEvents.once('activity', onActivityEvent);++ await generateAudio({ jobId: 'job-3', prompt: 'x' });++ expect(capturedOnActivity).toBeInstanceOf(Function);+ expect(onActivityEvent).toHaveBeenCalledWith({ generationId: 'job-3' });+ });+});++describe('cancel', () => {+ it('aborts the in-flight generateMusic signal for a known jobId', async () => {+ let capturedSignal;+ generateMusic.mockImplementation(({ signal }) => {+ capturedSignal = signal;+ return new Promise(() => {}); // hang until aborted+ });++ const pending = generateAudio({ jobId: 'job-4', prompt: 'x' });+ // Let generateAudio's synchronous setup (controller registration) run.+ await Promise.resolve();+ await Promise.resolve();++ expect(capturedSignal.aborted).toBe(false);+ cancel('job-4');+ expect(capturedSignal.aborted).toBe(true);++ void pending; // never resolves in this test; not awaited intentionally+ });++ it('is a no-op for an unknown / already-settled jobId', () => {+ expect(() => cancel('no-such-job')).not.toThrow();+ });+});diff --git a/server/services/creativeDirector/firstPassMusicGen.js b/server/services/creativeDirector/firstPassMusicGen.jsnew file mode 100644index 0000000000..8834b080a7--- /dev/null+++ b/server/services/creativeDirector/firstPassMusicGen.js@@ -0,0 +1,88 @@+/**+ * Creative Director — first-pass music-bed generation (#1928, split from+ * #1867's portrait/video first-pass work).+ *+ * Reuse, not a new pipeline (same constraint firstPassGen.js documents for+ * portraits). The actual generation call is the SAME generator-agnostic+ * `generateMusic` the Pipeline Audio stage already uses+ * (server/services/pipeline/musicGen.js) — this module only decides whether to+ * render, derives the prompt, and enqueues it onto the media job queue's new+ * `'audio'` kind so it runs as a background job instead of blocking the+ * auto-cast request.+ *+ * Unlike the portrait path, there is no catalog ingredient to attach the+ * result to — the issue explicitly calls this out ("no catalog-attach+ * equivalent yet"). The finished track attaches directly onto the Creative+ * Director PROJECT record's `musicBed` field via the durable+ * `creativeDirectorMusicBedHook` (mirrors catalogImageAttachHook, but for a+ * project instead of a catalog ingredient), so a render that completes after+ * the user has navigated away still lands.+ */++import { enqueueJob } from '../mediaJobQueue/index.js';+import { DEFAULT_ENGINE_ID, isEngineReady } from '../pipeline/musicGen.js';++// Keep the derived prompt bounded — a music-gen prompt is a short mood/style+// brief, not the full treatment. Mirrors PORTRAIT_PROMPT_CHARS' "enough+// descriptive text, not the whole payload" posture.+export const MUSIC_BED_PROMPT_CHARS = 400;++/**+ * Pure: derive a music-gen prompt for a project's first-pass bed. The project+ * name anchors the subject; the treatment logline (once auto-compose has run)+ * gives the richest mood/genre signal, falling back to the styleSpec the user+ * set at creation. Returns '' when neither is present, so the caller can skip+ * rather than queue a contentless render.+ */+export function buildMusicBedPrompt(project) {+ if (!project || typeof project !== 'object') return '';+ const name = typeof project.name === 'string' ? project.name.trim() : '';+ const logline = typeof project.treatment?.logline === 'string' ? project.treatment.logline.trim() : '';+ const styleSpec = typeof project.styleSpec === 'string' ? project.styleSpec.trim() : '';+ const detail = logline || styleSpec;+ const joined = name && detail ? `${name} — ${detail}` : (name || detail);+ if (!joined) return '';+ return joined.length > MUSIC_BED_PROMPT_CHARS+ ? `${joined.slice(0, MUSIC_BED_PROMPT_CHARS).trim()}…`+ : joined;+}++/**+ * Enqueue a first-pass music-bed render for the given project, or report why+ * it was skipped. Best-effort and self-contained — never throws, mirrors+ * enqueueFirstPassPortraits' "side-effect of auto-cast, must not fail the+ * seeding it follows" contract.+ *+ * 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 } = {}) {+ if (!project || typeof project !== 'object' || !project.id) {+ return { mode: engine, 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' };+ }+ if (!isEngineReady(engine)) {+ return { mode: engine, enqueued: false, reason: 'engine-not-ready' };+ }+ const prompt = buildMusicBedPrompt(project);+ if (!prompt) {+ return { mode: engine, enqueued: false, reason: 'no-prompt' };+ }+ const queued = enqueueJob({+ kind: 'audio',+ params: {+ prompt,+ engine,+ // 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 };+}diff --git a/server/services/creativeDirector/firstPassMusicGen.test.js b/server/services/creativeDirector/firstPassMusicGen.test.jsnew file mode 100644index 0000000000..25ba4c4287--- /dev/null+++ b/server/services/creativeDirector/firstPassMusicGen.test.js@@ -0,0 +1,102 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';++vi.mock('../mediaJobQueue/index.js', () => ({+ enqueueJob: vi.fn(),+}));+vi.mock('../pipeline/musicGen.js', () => ({+ DEFAULT_ENGINE_ID: 'musicgen',+ isEngineReady: vi.fn(),+}));++import { buildMusicBedPrompt, enqueueFirstPassMusicBed } from './firstPassMusicGen.js';+import { enqueueJob } from '../mediaJobQueue/index.js';+import { isEngineReady } from '../pipeline/musicGen.js';++let jobSeq = 0;++beforeEach(() => {+ vi.clearAllMocks();+ jobSeq = 0;+ enqueueJob.mockImplementation(() => ({ jobId: `job-${++jobSeq}`, position: 1, status: 'queued' }));+ isEngineReady.mockReturnValue(true);+});++describe('buildMusicBedPrompt', () => {+ it('joins the project name + treatment logline when present', () => {+ const prompt = buildMusicBedPrompt({+ name: 'Neon Drift', treatment: { logline: 'a noir detective chases a ghost across a rain-soaked city' },+ styleSpec: 'ignored when logline is present',+ });+ expect(prompt).toBe('Neon Drift — a noir detective chases a ghost across a rain-soaked city');+ });++ it('falls back to styleSpec when there is no treatment yet', () => {+ const prompt = buildMusicBedPrompt({ name: 'Neon Drift', styleSpec: 'moody synthwave, slow build' });+ expect(prompt).toBe('Neon Drift — moody synthwave, slow build');+ });++ it('uses the name alone when there is no logline or styleSpec', () => {+ expect(buildMusicBedPrompt({ name: 'Bare Project', styleSpec: '' })).toBe('Bare Project');+ });++ it('returns "" for a null / nameless+detailless project', () => {+ expect(buildMusicBedPrompt(null)).toBe('');+ expect(buildMusicBedPrompt({ name: ' ', styleSpec: '' })).toBe('');+ });++ it('truncates an overlong joined prompt to MUSIC_BED_PROMPT_CHARS', () => {+ const longLogline = 'x'.repeat(500);+ const prompt = buildMusicBedPrompt({ name: 'P', treatment: { logline: longLogline } });+ expect(prompt.length).toBeLessThanOrEqual(402); // 400 + ellipsis+ expect(prompt.endsWith('…')).toBe(true);+ });+});++describe('enqueueFirstPassMusicBed', () => {+ it('enqueues an audio job tagged with the project id', async () => {+ const project = { id: 'proj-1', name: 'Neon Drift', styleSpec: 'synthwave' };+ const out = await enqueueFirstPassMusicBed(project);+ expect(out).toEqual({ mode: 'musicgen', enqueued: true, jobId: 'job-1' });+ const call = enqueueJob.mock.calls[0][0];+ expect(call.kind).toBe('audio');+ expect(call.params.prompt).toBe('Neon Drift — synthwave');+ expect(call.params.engine).toBe('musicgen');+ expect(call.params.creativeDirectorMusicBed).toEqual({ projectId: 'proj-1' });+ });++ it('skips a project that already has a music bed (idempotent re-run)', async () => {+ const project = { id: 'proj-1', name: 'Neon Drift', musicBed: { filename: 'existing.wav' } };+ const out = await enqueueFirstPassMusicBed(project);+ expect(out).toEqual({ mode: 'musicgen', enqueued: false, reason: 'has-music-bed' });+ expect(enqueueJob).not.toHaveBeenCalled();+ });++ it('skips gracefully when no engine is ready', async () => {+ isEngineReady.mockReturnValue(false);+ const project = { id: 'proj-1', name: 'Neon Drift' };+ const out = await enqueueFirstPassMusicBed(project);+ expect(out).toEqual({ mode: 'musicgen', enqueued: false, reason: 'engine-not-ready' });+ expect(enqueueJob).not.toHaveBeenCalled();+ });++ it('skips a project with no usable prompt', async () => {+ const project = { id: 'proj-1', name: ' ', styleSpec: '' };+ const out = await enqueueFirstPassMusicBed(project);+ expect(out).toEqual({ mode: 'musicgen', enqueued: false, reason: 'no-prompt' });+ expect(enqueueJob).not.toHaveBeenCalled();+ });++ it('reports no-project for a missing / id-less project (never reads engine readiness)', async () => {+ expect(await enqueueFirstPassMusicBed(null)).toEqual({ mode: 'musicgen', enqueued: false, reason: 'no-project' });+ expect(await enqueueFirstPassMusicBed({ name: 'no id' })).toEqual({ mode: 'musicgen', enqueued: false, reason: 'no-project' });+ expect(isEngineReady).not.toHaveBeenCalled();+ });++ 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' });+ expect(out.mode).toBe('acestep');+ expect(enqueueJob.mock.calls[0][0].params.engine).toBe('acestep');+ expect(isEngineReady).toHaveBeenCalledWith('acestep');+ });+});diff --git a/server/services/creativeDirector/projectsLogic.js b/server/services/creativeDirector/projectsLogic.jsindex 98a627c421..3de09c1af7 100644--- a/server/services/creativeDirector/projectsLogic.js+++ b/server/services/creativeDirector/projectsLogic.js@@ -116,6 +116,13 @@ export function buildProjectRecord(input, { id, now, collectionId }) {collectionId,timelineProjectId: null,finalVideoId: null,+ // First-pass music bed (#1928) — populated by the durable+ // creativeDirectorMusicBedHook once an opt-in background render completes;+ // null on a bare project. Shape: { filename, durationSec, engine, modelId,+ // generatedAt }. Additive — the whole record round-trips through the JSONB+ // column verbatim (sanitizeProjectForSync / mergeProjectRecord), so this+ // needs no schema-version bump.+ musicBed: null,treatment: null,runs: [],// Soft-delete / LWW tombstone trio (#1564) — projects federate across peersdiff --git a/server/services/creativeDirectorMusicBedHook.js b/server/services/creativeDirectorMusicBedHook.jsnew file mode 100644index 0000000000..5936145ef8--- /dev/null+++ b/server/services/creativeDirectorMusicBedHook.js@@ -0,0 +1,64 @@+/**+ * Creative Director music-bed attach hook (#1928).+ *+ * Subscribes to mediaJobEvents and, for each completed AUDIO job that carries+ * `params.creativeDirectorMusicBed.projectId`, files the rendered track onto+ * that project's `musicBed` field — server-side, independent of any mounted+ * client. This is the project-level counterpart to `catalogImageAttachHook`+ * (#1359): instead of a catalog ingredient, the destination is a Creative+ * Director project record (there is no catalog-attach equivalent for a+ * project-wide music bed — see #1928).+ *+ * The shared completion-hook scaffold (tag-decode, per-project serialization,+ * best-effort error handling, idempotent init/reset) lives in+ * `createMediaJobImageHook` (#1791, generalized to non-image kinds in #1760) —+ * this file is just the music-bed-specific config. Mounted once at server boot+ * from server/index.js (after the media job queue is running).+ */++import { createMediaJobImageHook } from './mediaJobImageHook.js';+import { updateProject } from './creativeDirector/local.js';++const hook = createMediaJobImageHook({+ label: 'CD music-bed',+ initLog: '🎼 Creative Director music-bed hook initialized',+ kind: 'audio',+ tagKey: 'creativeDirectorMusicBed',+ identify: (tag) => (typeof tag?.projectId === 'string' && tag.projectId ? { projectId: tag.projectId } : null),+ // Serialize per PROJECT: a project only ever has one music-bed slot, so two+ // completions racing for the same project must not interleave their+ // load→modify→save.+ serializeKey: ({ projectId }) => projectId,+ describe: ({ projectId }) => projectId,+ // generateAudio's `completed` payload (stored as job.result) carries+ // generateMusic's return shape: { filename, durationSec, modelId, model,+ // engine }. `filename` is required to attach; the rest ride along as+ // metadata on the project record.+ extractResult: (job) => {+ const filename = job.result?.filename;+ if (typeof filename !== 'string' || !filename) return null;+ return {+ filename,+ durationSec: Number.isFinite(job.result?.durationSec) ? job.result.durationSec : null,+ engine: typeof job.result?.engine === 'string' ? job.result.engine : null,+ modelId: typeof job.result?.modelId === 'string' ? job.result.modelId : null,+ };+ },+ // 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, {+ musicBed: { filename, durationSec, engine, modelId, generatedAt: new Date().toISOString() },+ }).then(() => 'attached'),+ onAttached: ({ projectId, filename }) => {+ console.log(`🎼 CD project ${projectId.slice(0, 8)} ← music bed ${filename}`);+ },+});++export function initCreativeDirectorMusicBedHook() {+ hook.init();+}++// Test-only reset so suites that re-init can do so cleanly.+export const __testing = hook.__testing;diff --git a/server/services/creativeDirectorMusicBedHook.test.js b/server/services/creativeDirectorMusicBedHook.test.jsnew file mode 100644index 0000000000..6e85dc149b--- /dev/null+++ b/server/services/creativeDirectorMusicBedHook.test.js@@ -0,0 +1,105 @@+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.+const updateProject = vi.fn(async (id, patch) => ({ id, ...patch }));+vi.mock('./creativeDirector/local.js', () => ({ updateProject }));++const { mediaJobEvents } = await import('./mediaJobQueue/index.js');+const hook = await import('./creativeDirectorMusicBedHook.js');++async function waitFor(predicate, { timeoutMs = 1000, intervalMs = 5 } = {}) {+ const deadline = Date.now() + timeoutMs;+ while (Date.now() < deadline) {+ if (predicate()) return;+ await new Promise((r) => setTimeout(r, intervalMs));+ }+ throw new Error('waitFor: predicate never became true');+}++const tag = (over = {}) => ({ projectId: 'proj-1', ...over });+// A completed audio job: the queue stores generateAudio's 'completed' payload+// (generateMusic's return shape) as job.result.+const completedAudioJob = ({ params = {}, result = {} } = {}) => ({+ kind: 'audio',+ params,+ result: { filename: 'music-gen-x.wav', durationSec: 12, engine: 'musicgen', modelId: 'musicgen-medium', ...result },+});++describe('creativeDirectorMusicBedHook', () => {+ beforeEach(() => {+ hook.__testing.reset();+ hook.initCreativeDirectorMusicBedHook();+ updateProject.mockReset();+ updateProject.mockImplementation(async (id, patch) => ({ id, ...patch }));+ });++ afterEach(() => {+ hook.__testing.reset();+ });++ it('attaches the rendered track onto the project musicBed field', async () => {+ mediaJobEvents.emit('completed', completedAudioJob({ params: { creativeDirectorMusicBed: tag() } }));+ await waitFor(() => updateProject.mock.calls.length > 0);+ expect(updateProject).toHaveBeenCalledWith('proj-1', {+ musicBed: expect.objectContaining({+ filename: 'music-gen-x.wav', durationSec: 12, engine: 'musicgen', modelId: 'musicgen-medium',+ generatedAt: expect.any(String),+ }),+ });+ });++ it('ignores a completed job with no creativeDirectorMusicBed tag', async () => {+ mediaJobEvents.emit('completed', completedAudioJob({ params: { prompt: 'plain audio render' } }));+ await new Promise((r) => setTimeout(r, 20));+ expect(updateProject).not.toHaveBeenCalled();+ });++ it('ignores a non-audio job kind (other hooks own those)', async () => {+ mediaJobEvents.emit('completed', { kind: 'image', params: { creativeDirectorMusicBed: tag() }, result: { filename: 'img.png' } });+ await new Promise((r) => setTimeout(r, 20));+ expect(updateProject).not.toHaveBeenCalled();+ });++ it('skips a tag missing projectId', async () => {+ mediaJobEvents.emit('completed', completedAudioJob({ params: { creativeDirectorMusicBed: {} } }));+ await new Promise((r) => setTimeout(r, 20));+ expect(updateProject).not.toHaveBeenCalled();+ });++ it('skips a completed job whose result carries no filename', async () => {+ mediaJobEvents.emit('completed', completedAudioJob({ params: { creativeDirectorMusicBed: tag() }, result: { filename: undefined } }));+ await new Promise((r) => setTimeout(r, 20));+ expect(updateProject).not.toHaveBeenCalled();+ });++ it('does not throw when the attach fails — project deleted mid-render', async () => {+ updateProject.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 new Promise((r) => setTimeout(r, 20));+ // No throw escapes the listener; nothing further to assert beyond "didn't crash".+ });++ it('serializes attaches for the same project so concurrent completions do not clobber', async () => {+ const order = [];+ let resolveFirst;+ updateProject+ .mockImplementationOnce(() => new Promise((resolve) => {+ order.push('start-1');+ resolveFirst = () => { order.push('end-1'); resolve({}); };+ }))+ .mockImplementationOnce(async () => { order.push('start-2'); return {}; });++ mediaJobEvents.emit('completed', completedAudioJob({ params: { creativeDirectorMusicBed: tag() } }));+ mediaJobEvents.emit('completed', completedAudioJob({ params: { creativeDirectorMusicBed: tag() } }));++ await waitFor(() => order.includes('start-1'));+ await new Promise((r) => setTimeout(r, 20));+ expect(order).toEqual(['start-1']);+ resolveFirst();+ await waitFor(() => order.includes('start-2'));+ expect(order).toEqual(['start-1', 'end-1', 'start-2']);+ });+});diff --git a/server/services/mediaJobQueue/index.js b/server/services/mediaJobQueue/index.jsindex 4f26ffaec6..e9c91e1a90 100644--- a/server/services/mediaJobQueue/index.js+++ b/server/services/mediaJobQueue/index.js@@ -42,6 +42,7 @@ import {import { videoGenEvents } from '../videoGen/events.js';import { imageGenEvents } from '../imageGenEvents.js';import { trainingEvents } from '../loraTraining/events.js';+import { audioGenEvents } from '../audioGen/events.js';import { getSettings } from '../settings.js';import { IMAGE_GEN_MODE } from '../imageGen/modes.js';@@ -70,6 +71,13 @@ const WATCHDOG_CODEX_MS = watchdogMs(process.env.MEDIA_JOB_WATCHDOG_CODEX_MS, 20// heartbeat thread reset it, so 30 minutes only trips on true hangs (model// download stalls emit tqdm lines; GIL-pinned wedges emit nothing).const WATCHDOG_TRAINING_MS = watchdogMs(process.env.MEDIA_JOB_WATCHDOG_TRAINING_MS, 30 * 60 * 1000);+// Audio (music-bed) generation is a single short sidecar call (≤240s of+// rendered audio across all engines) but a cold model download can still take+// a while on a slow connection — mirrors the image-kind rationale. The+// sidecar's STAGE: lines reset the idle clock via 'activity' (audioGen/local.js+// threads them through), so this only trips on a genuine hang, not a slow+// first-run download.+const WATCHDOG_AUDIO_MS = watchdogMs(process.env.MEDIA_JOB_WATCHDOG_AUDIO_MS, 10 * 60 * 1000);const PROGRESS_PERSIST_DEBOUNCE_MS = 250;// Returns true if `p` resolves strictly under PATHS.uploads. Shared by@@ -106,7 +114,7 @@ async function safeUnlinkUpload(path) {await unlink(path).catch(() => {});}-export const JOB_KINDS = Object.freeze(['video', 'image', 'training']);+export const JOB_KINDS = Object.freeze(['video', 'image', 'training', 'audio']);export const JOB_STATUSES = Object.freeze(['queued', 'running', 'completed', 'failed', 'canceled']);// Returns a Promise that resolves to the gen module for the given job's@@ -116,6 +124,7 @@ export const JOB_STATUSES = Object.freeze(['queued', 'running', 'completed', 'fafunction getGenModuleForJob(job) {if (job.kind === 'video') return import('../videoGen/local.js');if (job.kind === 'training') return import('../loraTraining/index.js');+ if (job.kind === 'audio') return import('../audioGen/local.js');if (job.kind === 'image' && job.params?.mode === IMAGE_GEN_MODE.CODEX) return import('../imageGen/codex.js');if (job.kind === 'image') return import('../imageGen/local.js');return Promise.resolve(null);@@ -755,6 +764,7 @@ async function runJob(job) {const emitter = job.kind === 'video' ? videoGenEvents: job.kind === 'training' ? trainingEvents+ : job.kind === 'audio' ? audioGenEvents: imageGenEvents;const dispatcher = makeGenDispatcher(emitter, job, handlers);dispatcher.attach();@@ -770,6 +780,7 @@ async function runJob(job) {const idleTimeoutMs = (() => {if (job.kind === 'video') return WATCHDOG_VIDEO_MS * Math.max(1, Number(safeParams.chunks) || 1);if (job.kind === 'training') return WATCHDOG_TRAINING_MS;+ if (job.kind === 'audio') return WATCHDOG_AUDIO_MS;if (isCodexJob(job)) return WATCHDOG_CODEX_MS;return WATCHDOG_IMAGE_MS;})();@@ -835,6 +846,8 @@ async function runJob(job) {await mod.generateVideo({ ...safeParams, jobId: job.id });} else if (job.kind === 'training') {await mod.runTraining({ ...safeParams, jobId: job.id });+ } else if (job.kind === 'audio') {+ await mod.generateAudio({ ...safeParams, jobId: job.id });} else {await mod.generateImage({ ...safeParams, jobId: job.id });}diff --git a/server/services/mediaJobQueue/index.test.js b/server/services/mediaJobQueue/index.test.jsindex 9087277da1..a92caac16e 100644--- a/server/services/mediaJobQueue/index.test.js+++ b/server/services/mediaJobQueue/index.test.js@@ -42,9 +42,11 @@ tryReadFile: vi.fn().mockResolvedValue(null), jobId: 'whatever' })),generateChainedVideo: vi.fn(async () => ({ jobId: 'whatever' })),generateImage: vi.fn(async () => ({ jobId: 'whatever' })),generateImageCodex: vi.fn(async () => ({ jobId: 'whatever' })),+ generateAudio: vi.fn(async () => ({ jobId: 'whatever' })),cancelVideo: vi.fn(),cancelImage: vi.fn(),cancelImageCodex: vi.fn(),+ cancelAudio: vi.fn(),// #1332: loraTraining is dynamically imported by the queue for runTraining// (worker) and hasSurvivingTrainer (boot reconcile). Stub both so the boot// re-attach decision is testable without loading the real trainer module.@@ -68,6 +70,11 @@ vi.mock('../imageGen/codex.js', () => ({cancel: (...args) => stubs.cancelImageCodex(...args),}));+vi.mock('../audioGen/local.js', () => ({+ generateAudio: (...args) => stubs.generateAudio(...args),+ cancel: (...args) => stubs.cancelAudio(...args),+}));+vi.mock('../loraTraining/index.js', () => ({runTraining: (...args) => stubs.runTraining(...args),hasSurvivingTrainer: (...args) => stubs.hasSurvivingTrainer(...args),@@ -80,12 +87,14 @@ vi.mock('../loraTraining/index.js', () => ({let mediaJobQueue;let videoGenEvents;let imageGenEvents;+let audioGenEvents;async function importFresh() {vi.resetModules();mediaJobQueue = await import('./index.js');videoGenEvents = (await import('../videoGen/events.js')).videoGenEvents;imageGenEvents = (await import('../imageGenEvents.js')).imageGenEvents;+ audioGenEvents = (await import('../audioGen/events.js')).audioGenEvents;}const flush = () => new Promise((r) => setTimeout(r, 250));@@ -125,7 +134,7 @@ describe('mediaJobQueue', () => {});it('rejects unknown kinds', () => {- expect(() => mediaJobQueue.enqueueJob({ kind: 'audio', params: {} })).toThrow(/invalid kind/);+ expect(() => mediaJobQueue.enqueueJob({ kind: 'bogus', params: {} })).toThrow(/invalid kind/);});it('listJobs filters by kind / status / owner', async () => {@@ -755,6 +764,35 @@ describe('mediaJobQueue', () => {});});+describe('Audio kind (#1928)', () => {+ it('dispatches an audio job to audioGen/local.js#generateAudio and completes', async () => {+ const job = mediaJobQueue.enqueueJob({+ kind: 'audio',+ params: { prompt: 'a moody synth bed', engine: 'musicgen' },+ });+ await waitFor(() => stubs.generateAudio.mock.calls.length === 1);++ expect(stubs.generateAudio).toHaveBeenCalledWith(+ expect.objectContaining({ jobId: job.jobId, prompt: 'a moody synth bed', engine: 'musicgen' }),+ );+ // Audio shares the GPU lane (no parallel codex-style lane) — the other+ // gen modules must not have been invoked.+ expect(stubs.generateVideo).not.toHaveBeenCalled();+ expect(stubs.generateImage).not.toHaveBeenCalled();++ audioGenEvents.emit('completed', { generationId: job.jobId, filename: `${job.jobId}.wav`, durationSec: 12 });+ await waitFor(() => mediaJobQueue.getJob(job.jobId)?.status === 'completed');++ const settled = mediaJobQueue.getJob(job.jobId);+ expect(settled.result).toEqual({ generationId: job.jobId, filename: `${job.jobId}.wav`, durationSec: 12 });+ });++ // cancelJob's dispatch-by-kind (mod.cancel(jobId)) is exercised generically+ // by the Codex lane's cancel test below via the same getGenModuleForJob+ // mechanism; audioGen/local.js#cancel's own behavior (aborting the in-flight+ // generateMusic signal) is unit-tested directly in audioGen/local.test.js.+});+describe('Codex lane', () => {it('dispatches a Codex job to imageGen/codex.js#generateImage, not local', async () => {// Allow the codex job to resolve immediately so the worker can settle.diff --git a/server/services/pipeline/musicGen.js b/server/services/pipeline/musicGen.jsindex dc72b4d30b..44e2db95d8 100644--- a/server/services/pipeline/musicGen.js+++ b/server/services/pipeline/musicGen.js@@ -261,9 +261,15 @@ function parseResultLine(stdout) {* ids fall back to the default. `modelId` is resolved within that engine's* registry. `lyrics` is forwarded only to lyric-aware engines (ACE-Step); other* engines ignore it. `signal` (optional AbortSignal) SIGTERMs the child — wired- * through so a cancel button can abort a long render.+ * through so a cancel button can abort a long render. `onActivity` (optional)+ * fires once per `STAGE:` line the sidecar emits — the media-job queue's+ * generic idle watchdog resets its timer off it via the audio job-kind+ * adapter (server/services/audioGen/local.js), the same way the image/video+ * sidecars' stderr lines do, so a slow first-run model download doesn't trip a+ * flat timeout. Callers outside the queue (the Pipeline Audio routes) omit it+ * and behave exactly as before.*/-export async function generateMusic({ prompt, lyrics, engine: engineId = DEFAULT_ENGINE_ID, durationSec, modelId, repo, signal } = {}) {+export async function generateMusic({ prompt, lyrics, engine: engineId = DEFAULT_ENGINE_ID, durationSec, modelId, repo, signal, onActivity } = {}) {const text = (prompt || '').trim();if (!text) {throw new ServerError('prompt is required', { status: 400, code: 'PIPELINE_MUSIC_EMPTY_PROMPT' });@@ -297,7 +303,7 @@ export async function generateMusic({ prompt, lyrics, engine: engineId = DEFAULT// token isn't required — but pass it through when the user has one set so the// first download doesn't hit anonymous HF rate limits.const env = safeChildProcessEnv(await hfTokenEnv());- const result = await runSidecarProcess({ bin, args, env, signal, engineId: engine.id });+ const result = await runSidecarProcess({ bin, args, env, signal, engineId: engine.id, onActivity });// A clean exit isn't enough — the sidecar could exit 0 yet write nothing (or// a truncated file) if the runtime changes shape. Require both a parsed// RESULT line AND a non-empty file on disk before we persist the library@@ -327,7 +333,7 @@ export async function generateMusic({ prompt, lyrics, engine: engineId = DEFAULT// line and a bounded stderr tail for the failure reason. Not a route handler —// the spawn-error / close branches must not throw (they run outside the Express// lifecycle), so they resolve a structured result instead.-function runSidecarProcess({ bin, args, env, signal, engineId = DEFAULT_ENGINE_ID }) {+function runSidecarProcess({ bin, args, env, signal, engineId = DEFAULT_ENGINE_ID, onActivity }) {return new Promise((resolve) => {const proc = spawn(bin, args, { env, stdio: ['ignore', 'pipe', 'pipe'] });let stdout = '';@@ -349,7 +355,10 @@ function runSidecarProcess({ bin, args, env, signal, engineId = DEFAULT_ENGINE_IstderrTail = (stderrTail + s).slice(-STDERR_TAIL);for (const line of s.split(/\r?\n/)) {const t = line.trim();- if (t.startsWith('STAGE:')) console.log(`🎼 ${engineId} ${t.slice('STAGE:'.length)}`);+ if (t.startsWith('STAGE:')) {+ console.log(`🎼 ${engineId} ${t.slice('STAGE:'.length)}`);+ onActivity?.();+ }}});proc.on('error', (err) => finish({ ok: false, reason: `spawn failed: ${err.message}`, stdout }));