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

feat: autonomous music-video shot planner seeds scenes from audio sections

[._.]/ Adam Eivy28fae742f4ed
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index b2133cb78e..125bfb4e7b 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -12,6 +12,8 @@
- **[issue-1915] Auto-arrange scenes across song sections by energy.** A one-click **Auto-arrange** button on the Music Video scene board distributes every scene across the analyzed song's sections weighted by each section's energy — louder sections get more (shorter) cuts, calmer sections get fewer (longer) ones — and writes the same persisted `startSec`/`endSec`/`beatAligned` fields the manual drag-snap arranger (#1854) writes, so the result is a director-tunable starting point honored exactly at render time. The offline audio analysis now records a normalized 0..1 `energy` per section (additive/optional — older cached analyses fall back to an even spread; re-run **Analyze** to populate it). The distribution is a pure, isolated helper — `autoArrangeScenes(scenes, audioAnalysis)` in `client/src/lib/beatGrid.js` (largest-remainder allocation by energy weight, interior cuts snapped to the beat grid) — unit-tested independently of the UI. (Closes #1915)
+- **[issue-1855] Autonomous shot planner: AI proposes a scene per song section.** A new **AI Plan** button (and `POST /api/music-video/:id/plan`) seeds the director scene board from the analyzed track in one click — one scene per audio section, with each scene's duration set to that section's exact span (energy-aware for free, since the cached sections already come from energy-novelty segmentation: louder, more eventful stretches were already split into more/shorter sections). It also best-effort asks the active AI provider for a first-pass `framePrompt`/shot `prompt` per scene from the project's concept and section context; a missing/disabled provider or an unparsable response degrades gracefully to plain, empty-prompt scenes rather than failing the request. Director-first — every seeded scene is an ordinary, fully-editable board entry, identical to a hand-added one. (Closes #1855)
+
## Architecture
- **[issue-1878] CoS runner now wires the process-level `unhandledRejection`/`uncaughtException` net (defense-in-depth).** The main server (`server/index.js`) already registered a process-level net via the shared `setupProcessErrorHandlers()` helper (`server/lib/errorHandler.js`) — but the standalone CoS runner (`server/cos-runner/index.js`), a separate long-lived PM2 process that spawns and supervises child agents, had none, so a stray async handler that rejected/threw outside the request lifecycle would crash it with Node's default unhandled output. The runner now calls the same shared helper, giving it the identical, already-tested convention: log via the emoji-prefixed `console.error` style, log-and-stay-alive on an unhandled rejection, and log-then-exit-cleanly on an uncaught exception (after flushing, so PM2 restarts a process that would otherwise be left in an undefined state and reaps any orphaned agents on boot). Reusing the shared helper (rather than rolling inline handlers) keeps the two long-lived processes consistent and routes arbitrary non-Error throw values through `normalizeError`, so the net can't itself throw on a `reason` with no `.stack`. This is the backstop for the per-handler try/catch wrapping done in #1825 — not a replacement for it. While wiring this up, hardened the shared helper's `uncaughtException` branch, which dereferenced `error.stack` on the raw thrown value — a non-Error throw (`throw null`) made the net itself throw, masking the original exception and skipping the clean exit/flush; it now guards `error instanceof Error` (mirroring the existing `unhandledRejection` branch). A regression test (`server/process-safety-net.test.js`) asserts the shared helper registers both handlers, that both entry processes wire it up, and that the `uncaughtException` listener tolerates a non-Error throw value. (Closes #1878)
diff --git a/client/src/pages/MusicVideo.jsx b/client/src/pages/MusicVideo.jsx
index 2c04b9a6e1..60ded85f43 100644
--- a/client/src/pages/MusicVideo.jsx
+++ b/client/src/pages/MusicVideo.jsx
@@ -7,6 +7,7 @@ import {
createMusicVideoProject,
deleteMusicVideoProject,
analyzeMusicVideoProject,
+ planMusicVideoProject,
addMusicVideoScene,
updateMusicVideoScene,
deleteMusicVideoScene,
@@ -45,6 +46,7 @@ export default function MusicVideo() {
const [loading, setLoading] = useState(true);
const [analyzing, setAnalyzing] = useState(false);
const [arranging, setArranging] = useState(false);
+ const [planning, setPlanning] = useState(false);
const [form, setForm] = useState({ name: '', mode: 'director', trackId: '' });
const selected = projects.find((p) => p.id === selectedId) || null;
const replaceProject = (next) => setProjects((prev) => prev.map((p) => (p.id === next.id ? next : p)));
@@ -129,6 +131,24 @@ export default function MusicVideo() {
.finally(() => setAnalyzing(false));
};
+ // Autonomous shot planner (#1855): propose one scene per analyzed audio
+ // section (energy-aware durations fall out of the section boundaries
+ // themselves) and seed them onto the board, optionally with a first-pass
+ // framePrompt/prompt per scene. Director-first — seeded scenes are
+ // ordinary, fully-editable board entries, same as a hand-added one.
+ const handlePlan = () => {
+ if (!selected?.audioAnalysis) return;
+ setPlanning(true);
+ planMusicVideoProject(selected.id, { seedPrompts: true })
+ .then(({ project, scenesAdded, promptsSeeded }) => {
+ replaceProject(project);
+ const suffix = promptsSeeded ? ' with first-pass prompts' : '';
+ toast.success(`Planned ${scenesAdded} scene${scenesAdded === 1 ? '' : 's'}${suffix}`);
+ })
+ .catch((err) => toast.error(err?.message || 'Plan failed'))
+ .finally(() => setPlanning(false));
+ };
+
// Auto-arrange (#1915): distribute every scene across the analyzed song
// sections weighted by each section's energy, writing the same persisted
// startSec/endSec/beatAligned fields the manual drag-snap arranger (#1854)
@@ -410,6 +430,11 @@ export default function MusicVideo() {
className="flex items-center gap-1 bg-port-bg border border-port-border rounded px-2 py-1.5 text-sm min-h-[40px] sm:min-h-0 disabled:opacity-50">
<Activity size={15} /> {analyzing ? 'Analyzing…' : 'Analyze'}
</button>
+ <button onClick={handlePlan} disabled={planning || !selected.audioAnalysis}
+ title={!selected.audioAnalysis ? 'Analyze the track first' : 'AI-propose a scene per song section'}
+ className="flex items-center gap-1 bg-port-bg border border-port-border rounded px-2 py-1.5 text-sm min-h-[40px] sm:min-h-0 disabled:opacity-50">
+ <Wand2 size={15} /> {planning ? 'Planning…' : 'AI Plan'}
+ </button>
<button onClick={handleAutoArrange}
disabled={arranging || !selected.audioAnalysis || (selected.scenes || []).length === 0}
title={!selected.audioAnalysis
diff --git a/client/src/pages/MusicVideo.test.jsx b/client/src/pages/MusicVideo.test.jsx
index f67984c05c..5a0a2b0ac5 100644
--- a/client/src/pages/MusicVideo.test.jsx
+++ b/client/src/pages/MusicVideo.test.jsx
@@ -22,6 +22,7 @@ vi.mock('../services/apiMusicVideo.js', () => ({
createMusicVideoProject: vi.fn(),
deleteMusicVideoProject: vi.fn(),
analyzeMusicVideoProject: vi.fn(),
+ planMusicVideoProject: vi.fn(),
addMusicVideoScene: vi.fn(),
updateMusicVideoScene: vi.fn(),
deleteMusicVideoScene: vi.fn(),
@@ -41,7 +42,14 @@ vi.mock('../components/ui/Toast', () => ({ default: { success: vi.fn(), error: v
vi.mock('../components/PageHeader', () => ({ default: ({ title }) => <div>{title}</div> }));
import MusicVideo from './MusicVideo.jsx';
-import { listMusicVideoProjects, renderMusicVideoProject } from '../services/apiMusicVideo.js';
+import { listMusicVideoProjects, renderMusicVideoProject, planMusicVideoProject } from '../services/apiMusicVideo.js';
+
+const PROJECT_ANALYZED = {
+ ...PROJECT_NO_CLIP,
+ id: 'mv-3',
+ name: 'Analyzed Track',
+ audioAnalysis: { bpm: 120, beats: [], downbeats: [], sections: [{ label: 'Intro', startSec: 0, endSec: 10, energy: 0.5 }], durationSec: 10 },
+};
const openProject = async (project) => {
listMusicVideoProjects.mockResolvedValue([project]);
@@ -80,3 +88,23 @@ describe('MusicVideo render control (#1760)', () => {
expect(link.closest('a').getAttribute('href')).toContain('preview=video%3Arh-9');
});
});
+
+describe('MusicVideo autonomous shot planner (#1855)', () => {
+ it('disables AI Plan until the track is analyzed', async () => {
+ await openProject(PROJECT_NO_CLIP);
+ const planBtn = await screen.findByRole('button', { name: /AI Plan/i });
+ expect(planBtn).toHaveProperty('disabled', true);
+ });
+
+ it('calls the planner and replaces the project on success', async () => {
+ const plannedProject = { ...PROJECT_ANALYZED, scenes: [{ sceneId: 's1', order: 0, prompt: 'p' }] };
+ planMusicVideoProject.mockResolvedValue({ project: plannedProject, scenesAdded: 1, promptsSeeded: false, promptsSkippedReason: 'no-provider' });
+
+ await openProject(PROJECT_ANALYZED);
+ const planBtn = await screen.findByRole('button', { name: /AI Plan/i });
+ expect(planBtn).toHaveProperty('disabled', false);
+
+ fireEvent.click(planBtn);
+ await waitFor(() => expect(planMusicVideoProject).toHaveBeenCalledWith('mv-3', { seedPrompts: true }));
+ });
+});
diff --git a/client/src/services/apiMusicVideo.js b/client/src/services/apiMusicVideo.js
index a7fe33ae3d..771a4a4fc2 100644
--- a/client/src/services/apiMusicVideo.js
+++ b/client/src/services/apiMusicVideo.js
@@ -22,6 +22,14 @@ export const analyzeMusicVideoProject = (id, options = {}) => request(`/music-vi
method: 'POST', ...options,
});
+// Autonomous shot planner (#1855): propose one scene per analyzed audio
+// section and seed them onto the board. `seedPrompts` (default true) also
+// best-effort asks the active provider for a first-pass framePrompt/prompt
+// per scene. Returns `{ project, scenesAdded, promptsSeeded, promptsSkippedReason }`.
+export const planMusicVideoProject = (id, body = {}, options = {}) => request(`/music-video/${encodeURIComponent(id)}/plan`, {
+ method: 'POST', body: JSON.stringify(body), ...options,
+});
+
// ---- Director scene board ----
export const addMusicVideoScene = (id, scene, options = {}) => request(`/music-video/${encodeURIComponent(id)}/scenes`, {
method: 'POST', body: JSON.stringify(scene), ...options,
diff --git a/server/lib/musicVideoValidation.js b/server/lib/musicVideoValidation.js
index 433e0dd102..0e5d210414 100644
--- a/server/lib/musicVideoValidation.js
+++ b/server/lib/musicVideoValidation.js
@@ -84,6 +84,18 @@ export const musicVideoSceneReorderSchema = z.object({
sceneIds: z.array(z.string().min(1).max(64)).min(1).max(500),
}).strict();
+// Autonomous shot planner (#1855): propose a scene per analyzed audio section.
+// `seedPrompts` (default true) additionally asks the active/given AI provider
+// for a first-pass framePrompt/prompt per scene — best-effort, never fails the
+// plan itself (see services/musicVideo/planner.js). `providerId`/`model` mirror
+// the optional override shape used elsewhere (mediaPromptRefiner, universe
+// builder) so a caller can pin a specific provider instead of the active one.
+export const musicVideoPlanRequestSchema = z.object({
+ seedPrompts: z.boolean().optional(),
+ providerId: z.string().max(64).optional(),
+ model: z.string().max(200).optional(),
+}).strict();
+
// The cached beat/tempo/section map (audioAnalysis.js output). Validated when a
// record round-trips so a hand-edited/legacy project can't carry a malformed
// analysis; the analyzer itself produces this shape.
diff --git a/server/routes/musicVideo.js b/server/routes/musicVideo.js
index bcca1a1a2b..7695599f8d 100644
--- a/server/routes/musicVideo.js
+++ b/server/routes/musicVideo.js
@@ -17,6 +17,7 @@ import {
musicVideoSceneCreateSchema,
musicVideoSceneUpdateSchema,
musicVideoSceneReorderSchema,
+ musicVideoPlanRequestSchema,
} from '../lib/validation.js';
import { PATHS } from '../lib/fileUtils.js';
import { safeUnder } from '../lib/ffmpeg.js';
@@ -34,6 +35,7 @@ import {
} from '../services/musicVideo/projects.js';
import { analyzeAudioFile } from '../services/musicVideo/audioAnalysis.js';
import { renderMusicVideo, attachRenderSseClient, cancelRender } from '../services/musicVideo/render.js';
+import { planProject } from '../services/musicVideo/planner.js';
import { getTrack } from '../services/tracks/index.js';
const router = Router();
@@ -100,6 +102,20 @@ router.post('/:id/analyze', asyncHandler(async (req, res) => {
res.json(updated);
}));
+// Autonomous shot planner (#1855, the secondary "autonomous mode" path):
+// propose one scene per analyzed audio section (energy-aware durations fall
+// out of the cached section boundaries) and seed them onto the director
+// scene board. Director-first — this only seeds editable scenes, same as a
+// hand-added one. `seedPrompts` (default true) additionally best-effort asks
+// the active/given AI provider for a first-pass framePrompt/prompt per scene;
+// a missing provider or parse failure degrades to plain scenes rather than
+// failing the request (see `promptsSeeded`/`promptsSkippedReason` in the body).
+router.post('/:id/plan', asyncHandler(async (req, res) => {
+ const { seedPrompts, providerId, model } = validateRequest(musicVideoPlanRequestSchema, req.body || {});
+ const result = await planProject(req.params.id, { seedPrompts, providerId, model });
+ res.json(result);
+}));
+
// --- Render (#1760, Phase 2) ---
// Assemble the scenes' i2v clips into one MP4 over the track as the master audio
// bed. Kickoff returns { jobId }; progress streams over SSE (mirrors
diff --git a/server/routes/musicVideo.test.js b/server/routes/musicVideo.test.js
index e3378689ef..0c738a783c 100644
--- a/server/routes/musicVideo.test.js
+++ b/server/routes/musicVideo.test.js
@@ -1,6 +1,7 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
import express from 'express';
import { request } from '../lib/testHelper.js';
+import { ServerError } from '../lib/errorHandler.js';
vi.mock('../services/musicVideo/projects.js', () => ({
listProjects: vi.fn(async () => [{ id: 'mv-1', name: 'A' }]),
@@ -31,10 +32,20 @@ vi.mock('../services/musicVideo/render.js', () => ({
cancelRender: vi.fn(() => true),
}));
+vi.mock('../services/musicVideo/planner.js', () => ({
+ planProject: vi.fn(async (id) => ({
+ project: { id, scenes: [{ sceneId: 'mvs-1' }] },
+ scenesAdded: 1,
+ promptsSeeded: false,
+ promptsSkippedReason: 'no-provider',
+ })),
+}));
+
import * as svc from '../services/musicVideo/projects.js';
import { analyzeAudioFile } from '../services/musicVideo/audioAnalysis.js';
import { getTrack } from '../services/tracks/index.js';
import * as renderSvc from '../services/musicVideo/render.js';
+import { planProject } from '../services/musicVideo/planner.js';
import musicVideoRoutes from './musicVideo.js';
describe('musicVideo routes', () => {
@@ -131,6 +142,36 @@ describe('musicVideo routes', () => {
});
});
+ describe('POST /:id/plan', () => {
+ it('plans with default options when no body is sent', async () => {
+ const r = await request(app).post('/api/music-video/mv-1/plan');
+ expect(r.status).toBe(200);
+ expect(planProject).toHaveBeenCalledWith('mv-1', { seedPrompts: undefined, providerId: undefined, model: undefined });
+ expect(r.body.scenesAdded).toBe(1);
+ expect(r.body.promptsSeeded).toBe(false);
+ });
+
+ it('forwards seedPrompts/providerId/model overrides', async () => {
+ const r = await request(app).post('/api/music-video/mv-1/plan')
+ .send({ seedPrompts: false, providerId: 'p1', model: 'gpt-x' });
+ expect(r.status).toBe(200);
+ expect(planProject).toHaveBeenCalledWith('mv-1', { seedPrompts: false, providerId: 'p1', model: 'gpt-x' });
+ });
+
+ it('rejects an unknown body field', async () => {
+ const r = await request(app).post('/api/music-video/mv-1/plan').send({ bogus: true });
+ expect(r.status).toBe(400);
+ expect(planProject).not.toHaveBeenCalled();
+ });
+
+ it('propagates a 422 from the planner (no cached analysis)', async () => {
+ planProject.mockRejectedValueOnce(new ServerError('Project has no analyzed sections to plan from — run Analyze first', { status: 422, code: 'NOT_ANALYZED' }));
+ const r = await request(app).post('/api/music-video/mv-1/plan');
+ expect(r.status).toBe(422);
+ expect(r.body.code).toBe('NOT_ANALYZED');
+ });
+ });
+
describe('scene board', () => {
it('POST /:id/scenes adds a scene', async () => {
const r = await request(app).post('/api/music-video/mv-1/scenes').send({ prompt: 'wide shot' });
diff --git a/server/services/musicVideo/planner.js b/server/services/musicVideo/planner.js
new file mode 100644
index 0000000000..ad0add952c
--- /dev/null
+++ b/server/services/musicVideo/planner.js
@@ -0,0 +1,202 @@
+/**
+ * Music Video — autonomous shot planner (#1855).
+ *
+ * Part of #1760's secondary "autonomous mode" convenience path (the manual
+ * director path shipped through Phase 2). Given a project's cached
+ * `audioAnalysis.sections`, proposes one scene per section and seeds them
+ * onto the director scene board via the same `addProjectScenes` mutator the
+ * manual board uses.
+ *
+ * "Energy-aware durations" falls straight out of the cached analysis with no
+ * extra weighting math needed here: `audioAnalysis.js#segmentSections`
+ * already derives section boundaries from energy-novelty segmentation, so a
+ * loud/eventful stretch of the track is already split into more, shorter
+ * sections and a calm stretch into fewer, longer ones — each proposed scene
+ * simply takes its section's exact span.
+ *
+ * Director-first (#1760's core design constraint): this only SEEDS the
+ * board with ordinary, fully-editable scene records — it never locks or
+ * replaces director control, and the seeded scenes are indistinguishable
+ * from hand-added ones. Optionally (best-effort, mirroring Creative
+ * Director's first-pass asset gen in firstPassGen.js) also asks the
+ * active/given AI provider for a first-pass `framePrompt`/`prompt` per scene
+ * from the project's concept + section context. A missing/disabled provider
+ * or an unparsable response degrades to plain scenes with empty prompts
+ * rather than failing the plan request — the director can always fill in
+ * prompts by hand afterward.
+ */
+
+import { ServerError } from '../../lib/errorHandler.js';
+import { extractJson } from '../../lib/jsonExtract.js';
+import { resolveProviderAndModel, runPromptThroughProvider } from '../../lib/promptRunner.js';
+import { getProject, addProjectScenes } from './projects.js';
+
+const SECTION_LABEL_MAX = 120;
+const SCENE_TEXT_MAX = 2000;
+// A music video plan with more sections than this would blow the LLM prompt
+// budget for marginal value (typical analyses produce single-digit-to-low-
+// dozens of sections) — scenes are still seeded deterministically above the
+// cap, just without the optional first-pass prompt text.
+const MAX_SECTIONS_FOR_PROMPTS = 80;
+
+/**
+ * Keep only sections with a valid forward-time span. Defensive against a
+ * malformed/legacy cached analysis — `musicVideoAudioAnalysisSchema` doesn't
+ * enforce `endSec > startSec` per section. Shared by the scene-input builder
+ * and the LLM prompt builder so their array indices always agree.
+ */
+export function validSections(sections) {
+ return (Array.isArray(sections) ? sections : [])
+ .filter((s) => s && typeof s.startSec === 'number' && typeof s.endSec === 'number' && s.endSec > s.startSec);
+}
+
+/**
+ * Pure: derive one scene-create input per analyzed section, in section
+ * order. `sections` must already be filtered via `validSections` — the
+ * caller owns that so this stays a straight 1:1 map (no index drift between
+ * this and the LLM prompt's section list).
+ */
+export function planScenesFromSections(sections) {
+ return sections.map((s) => {
+ const label = typeof s.label === 'string' ? s.label.slice(0, SECTION_LABEL_MAX) : '';
+ return {
+ label,
+ sectionLabel: label || null,
+ startSec: s.startSec,
+ endSec: s.endSec,
+ beatAligned: true,
+ };
+ });
+}
+
+/** Build the LLM prompt asking for a first-pass framePrompt/prompt per section. */
+export function buildScenePlanPrompt(project, sections) {
+ const concept = project.concept || {};
+ const conceptLine = concept.prompt ? `Concept: ${concept.prompt}` : '';
+ const styleLine = concept.style ? `Visual style: ${concept.style}` : '';
+ const sectionLines = sections.map((s, i) => {
+ const duration = (s.endSec - s.startSec).toFixed(1);
+ const energy = typeof s.energy === 'number' ? s.energy.toFixed(2) : 'unknown';
+ return `${i}. "${s.label || `Section ${i + 1}`}" — ${duration}s, normalized energy ${energy}`;
+ }).join('\n');
+
+ return `You are directing a music video for "${project.name}".
+${conceptLine}
+${styleLine}
+
+The track has been split into these sections (index, label, duration, normalized 0..1 energy — higher energy means a louder/more intense part of the song):
+${sectionLines}
+
+For EACH section above, propose ONE shot for a generative video model:
+- "framePrompt": the opening reference still — subject, setting, lighting, composition. Keep it concrete and visual.
+- "prompt": the motion for that shot — camera move, subject motion, mood — building on the frame. Higher-energy sections should read more kinetic; calmer sections more static/lingering.
+
+Respond with ONLY a JSON array, one object per section, in section-index order, no other text:
+[{ "index": 0, "framePrompt": "...", "prompt": "..." }]`;
+}
+
+/** Parse the LLM's scene-prompt response into a `Map<index, {framePrompt, prompt}>`. */
+function parseScenePlanResponse(text, count) {
+ const { value: parsed } = extractJson(text, { blockType: 'array' });
+ if (!Array.isArray(parsed)) return null;
+ const byIndex = new Map();
+ for (const entry of parsed) {
+ const idx = Number(entry?.index);
+ if (!Number.isInteger(idx) || idx < 0 || idx >= count) continue;
+ const framePrompt = typeof entry?.framePrompt === 'string' ? entry.framePrompt.trim().slice(0, SCENE_TEXT_MAX) : '';
+ const prompt = typeof entry?.prompt === 'string' ? entry.prompt.trim().slice(0, SCENE_TEXT_MAX) : '';
+ if (!framePrompt && !prompt) continue;
+ byIndex.set(idx, { framePrompt, prompt });
+ }
+ return byIndex.size > 0 ? byIndex : null;
+}
+
+/**
+ * Best-effort first-pass prompt proposal. Never throws — returns
+ * `{ seeded: null, reason }` for every failure mode (no provider configured,
+ * provider disabled, LLM call failed, response didn't parse) so the caller
+ * can fall back to plain scenes without the whole plan request failing.
+ */
+async function tryProposeScenePrompts(project, sections, { providerId, model } = {}) {
+ if (sections.length > MAX_SECTIONS_FOR_PROMPTS) {
+ return { seeded: null, reason: 'too-many-sections' };
+ }
+
+ const { provider, selectedModel } = await resolveProviderAndModel({ providerId, model }).catch(() => ({ provider: null, selectedModel: null }));
+ if (!provider) return { seeded: null, reason: 'no-provider' };
+ if (provider.enabled === false) return { seeded: null, reason: 'provider-disabled' };
+
+ let text;
+ try {
+ ({ text } = await runPromptThroughProvider({
+ provider,
+ model: selectedModel,
+ prompt: buildScenePlanPrompt(project, sections),
+ source: 'music-video-plan',
+ }));
+ } catch (err) {
+ console.warn(`⚠️ Music Video plan: scene-prompt LLM call failed for ${project.id}: ${err.message}`);
+ return { seeded: null, reason: 'llm-failed' };
+ }
+
+ const seeded = parseScenePlanResponse(text, sections.length);
+ if (!seeded) {
+ console.warn(`⚠️ Music Video plan: unparsable scene-prompt response for ${project.id}`);
+ return { seeded: null, reason: 'unparsable-response' };
+ }
+ return { seeded, reason: null };
+}
+
+/**
+ * Plan + seed a project's scene board from its cached audio analysis.
+ *
+ * @param {string} id — project id
+ * @param {object} [options]
+ * @param {boolean} [options.seedPrompts=true] — also attempt first-pass
+ * framePrompt/prompt text via the active/given AI provider (best-effort).
+ * @param {string} [options.providerId] — pin a specific provider instead of
+ * the active one.
+ * @param {string} [options.model] — model override for the prompt-seeding call.
+ * @returns {Promise<{ project: object, scenesAdded: number, promptsSeeded: boolean, promptsSkippedReason: string|null }>}
+ */
+export async function planProject(id, { seedPrompts = true, providerId, model } = {}) {
+ const project = await getProject(id);
+ if (!project) throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });
+
+ const sections = validSections(project.audioAnalysis?.sections);
+ if (sections.length === 0) {
+ throw new ServerError(
+ 'Project has no analyzed sections to plan from — run Analyze first',
+ { status: 422, code: 'NOT_ANALYZED' },
+ );
+ }
+
+ const sceneInputs = planScenesFromSections(sections);
+
+ let promptsSeeded = false;
+ let promptsSkippedReason = seedPrompts ? null : 'not-requested';
+ if (seedPrompts) {
+ const { seeded, reason } = await tryProposeScenePrompts(project, sections, { providerId, model });
+ if (seeded) {
+ promptsSeeded = true;
+ for (const [idx, fields] of seeded) {
+ if (!sceneInputs[idx]) continue;
+ if (fields.framePrompt) sceneInputs[idx].framePrompt = fields.framePrompt;
+ if (fields.prompt) sceneInputs[idx].prompt = fields.prompt;
+ }
+ } else {
+ promptsSkippedReason = reason;
+ }
+ }
+
+ const scenes = await addProjectScenes(id, sceneInputs);
+ // Assemble the response in-memory from the pre-mutation `project` + the
+ // scenes `addProjectScenes` just returned, rather than a second
+ // getProject round trip — addScenes' `touch()` only changes `scenes` +
+ // `updatedAt`, so this mirrors exactly what a re-fetch would return
+ // without a second DB transaction / whole-file re-read (the client's
+ // single-scene `addMusicVideoScene` path already composes state this way).
+ const updated = { ...project, scenes: [...(project.scenes || []), ...scenes], updatedAt: new Date().toISOString() };
+ console.log(`🪄 Music Video plan: seeded ${scenes.length} scene${scenes.length === 1 ? '' : 's'} for ${id} (prompts ${promptsSeeded ? 'seeded' : `skipped: ${promptsSkippedReason || 'n/a'}`})`);
+ return { project: updated, scenesAdded: scenes.length, promptsSeeded, promptsSkippedReason };
+}
diff --git a/server/services/musicVideo/planner.test.js b/server/services/musicVideo/planner.test.js
new file mode 100644
index 0000000000..165200bbaf
--- /dev/null
+++ b/server/services/musicVideo/planner.test.js
@@ -0,0 +1,208 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+vi.mock('../../lib/promptRunner.js', () => ({
+ resolveProviderAndModel: vi.fn(),
+ runPromptThroughProvider: vi.fn(),
+}));
+
+vi.mock('./projects.js', () => ({
+ getProject: vi.fn(),
+ addProjectScenes: vi.fn(),
+}));
+
+import { resolveProviderAndModel, runPromptThroughProvider } from '../../lib/promptRunner.js';
+import { getProject, addProjectScenes } from './projects.js';
+import {
+ validSections,
+ planScenesFromSections,
+ buildScenePlanPrompt,
+ planProject,
+} from './planner.js';
+
+const SECTIONS = [
+ { label: 'Intro', startSec: 0, endSec: 10, energy: 0.2 },
+ { label: 'Drop', startSec: 10, endSec: 18, energy: 0.95 },
+ { label: 'Outro', startSec: 18, endSec: 30, energy: 0.4 },
+];
+
+function makeProject(overrides = {}) {
+ return {
+ id: 'mv-1',
+ name: 'Neon Nights',
+ concept: { prompt: 'cyberpunk chase', style: 'neon, rain-slicked streets' },
+ audioAnalysis: { bpm: 120, beats: [], downbeats: [], sections: SECTIONS, durationSec: 30 },
+ scenes: [],
+ ...overrides,
+ };
+}
+
+beforeEach(() => {
+ vi.clearAllMocks();
+});
+
+describe('validSections', () => {
+ it('keeps only sections with a positive forward span', () => {
+ const result = validSections([
+ { label: 'A', startSec: 0, endSec: 5 },
+ { label: 'bad-order', startSec: 5, endSec: 5 },
+ { label: 'bad-reverse', startSec: 8, endSec: 3 },
+ { label: 'missing-times' },
+ null,
+ ]);
+ expect(result).toEqual([{ label: 'A', startSec: 0, endSec: 5 }]);
+ });
+
+ it('returns [] for a non-array input', () => {
+ expect(validSections(null)).toEqual([]);
+ expect(validSections(undefined)).toEqual([]);
+ });
+});
+
+describe('planScenesFromSections', () => {
+ it('builds one beat-aligned scene-create input per section, in order', () => {
+ const inputs = planScenesFromSections(SECTIONS);
+ expect(inputs).toHaveLength(3);
+ expect(inputs[0]).toEqual({
+ label: 'Intro', sectionLabel: 'Intro', startSec: 0, endSec: 10, beatAligned: true,
+ });
+ expect(inputs[1]).toMatchObject({ label: 'Drop', startSec: 10, endSec: 18 });
+ expect(inputs[2]).toMatchObject({ label: 'Outro', startSec: 18, endSec: 30 });
+ });
+
+ it('each scene duration is exactly its section span (energy-aware via segmentation)', () => {
+ const inputs = planScenesFromSections(SECTIONS);
+ for (let i = 0; i < SECTIONS.length; i++) {
+ expect(inputs[i].endSec - inputs[i].startSec).toBe(SECTIONS[i].endSec - SECTIONS[i].startSec);
+ }
+ });
+
+ it('falls back to an empty/null label when a section has no label', () => {
+ const [input] = planScenesFromSections([{ startSec: 0, endSec: 5 }]);
+ expect(input.label).toBe('');
+ expect(input.sectionLabel).toBeNull();
+ });
+});
+
+describe('buildScenePlanPrompt', () => {
+ it('includes the project concept, style, and per-section index/label/duration/energy', () => {
+ const prompt = buildScenePlanPrompt(makeProject(), SECTIONS);
+ expect(prompt).toContain('Neon Nights');
+ expect(prompt).toContain('cyberpunk chase');
+ expect(prompt).toContain('neon, rain-slicked streets');
+ expect(prompt).toContain('0. "Intro" — 10.0s, normalized energy 0.20');
+ expect(prompt).toContain('1. "Drop" — 8.0s, normalized energy 0.95');
+ expect(prompt).toContain('JSON array');
+ });
+});
+
+describe('planProject', () => {
+ it('404s when the project does not exist', async () => {
+ getProject.mockResolvedValue(null);
+ await expect(planProject('mv-x')).rejects.toMatchObject({ status: 404, code: 'NOT_FOUND' });
+ });
+
+ it('422s when the project has no cached analysis', async () => {
+ getProject.mockResolvedValue(makeProject({ audioAnalysis: null }));
+ await expect(planProject('mv-1')).rejects.toMatchObject({ status: 422, code: 'NOT_ANALYZED' });
+ });
+
+ it('422s when every section is malformed', async () => {
+ getProject.mockResolvedValue(makeProject({
+ audioAnalysis: { sections: [{ label: 'bad', startSec: 5, endSec: 1 }] },
+ }));
+ await expect(planProject('mv-1')).rejects.toMatchObject({ status: 422, code: 'NOT_ANALYZED' });
+ });
+
+ it('seeds one scene per section and skips prompts gracefully when no provider is configured', async () => {
+ const project = makeProject();
+ getProject.mockResolvedValueOnce(project).mockResolvedValueOnce({ ...project, scenes: [{ sceneId: 's1' }] });
+ addProjectScenes.mockResolvedValue([{ sceneId: 's1' }, { sceneId: 's2' }, { sceneId: 's3' }]);
+ resolveProviderAndModel.mockResolvedValue({ provider: null, selectedModel: null });
+
+ const result = await planProject('mv-1');
+
+ expect(addProjectScenes).toHaveBeenCalledWith('mv-1', expect.arrayContaining([
+ expect.objectContaining({ label: 'Intro', startSec: 0, endSec: 10 }),
+ ]));
+ expect(addProjectScenes.mock.calls[0][1]).toHaveLength(3);
+ expect(runPromptThroughProvider).not.toHaveBeenCalled();
+ expect(result.scenesAdded).toBe(3);
+ expect(result.promptsSeeded).toBe(false);
+ expect(result.promptsSkippedReason).toBe('no-provider');
+ });
+
+ it('skips the LLM call entirely when seedPrompts is false', async () => {
+ const project = makeProject();
+ getProject.mockResolvedValueOnce(project).mockResolvedValueOnce(project);
+ addProjectScenes.mockResolvedValue([{ sceneId: 's1' }, { sceneId: 's2' }, { sceneId: 's3' }]);
+
+ const result = await planProject('mv-1', { seedPrompts: false });
+
+ expect(resolveProviderAndModel).not.toHaveBeenCalled();
+ expect(result.promptsSeeded).toBe(false);
+ expect(result.promptsSkippedReason).toBe('not-requested');
+ });
+
+ it('merges first-pass framePrompt/prompt into the matching scenes when the LLM call succeeds', async () => {
+ const project = makeProject();
+ getProject.mockResolvedValueOnce(project).mockResolvedValueOnce(project);
+ addProjectScenes.mockResolvedValue([{ sceneId: 's1' }, { sceneId: 's2' }, { sceneId: 's3' }]);
+ resolveProviderAndModel.mockResolvedValue({ provider: { id: 'p1', type: 'api' }, selectedModel: 'gpt' });
+ runPromptThroughProvider.mockResolvedValue({
+ text: JSON.stringify([
+ { index: 0, framePrompt: 'wide establishing shot of a neon alley', prompt: 'slow dolly in' },
+ { index: 1, framePrompt: 'close-up under strobing lights', prompt: 'rapid cuts, handheld shake' },
+ { index: 2, framePrompt: 'empty street at dawn', prompt: 'static, lingering' },
+ ]),
+ });
+
+ const result = await planProject('mv-1');
+
+ const seededInputs = addProjectScenes.mock.calls[0][1];
+ expect(seededInputs[0].framePrompt).toBe('wide establishing shot of a neon alley');
+ expect(seededInputs[0].prompt).toBe('slow dolly in');
+ expect(seededInputs[1].framePrompt).toBe('close-up under strobing lights');
+ expect(result.promptsSeeded).toBe(true);
+ expect(result.promptsSkippedReason).toBeNull();
+ });
+
+ it('degrades to plain scenes when the LLM call throws', async () => {
+ const project = makeProject();
+ getProject.mockResolvedValueOnce(project).mockResolvedValueOnce(project);
+ addProjectScenes.mockResolvedValue([{ sceneId: 's1' }, { sceneId: 's2' }, { sceneId: 's3' }]);
+ resolveProviderAndModel.mockResolvedValue({ provider: { id: 'p1', type: 'api' }, selectedModel: 'gpt' });
+ runPromptThroughProvider.mockRejectedValue(new Error('boom'));
+
+ const result = await planProject('mv-1');
+
+ const seededInputs = addProjectScenes.mock.calls[0][1];
+ expect(seededInputs[0].framePrompt).toBeUndefined();
+ expect(result.promptsSeeded).toBe(false);
+ expect(result.promptsSkippedReason).toBe('llm-failed');
+ });
+
+ it('degrades to plain scenes when the LLM response is unparsable', async () => {
+ const project = makeProject();
+ getProject.mockResolvedValueOnce(project).mockResolvedValueOnce(project);
+ addProjectScenes.mockResolvedValue([{ sceneId: 's1' }, { sceneId: 's2' }, { sceneId: 's3' }]);
+ resolveProviderAndModel.mockResolvedValue({ provider: { id: 'p1', type: 'api' }, selectedModel: 'gpt' });
+ runPromptThroughProvider.mockResolvedValue({ text: 'not json at all' });
+
+ const result = await planProject('mv-1');
+
+ expect(result.promptsSeeded).toBe(false);
+ expect(result.promptsSkippedReason).toBe('unparsable-response');
+ });
+
+ it('skips prompt-seeding when the resolved provider is disabled', async () => {
+ const project = makeProject();
+ getProject.mockResolvedValueOnce(project).mockResolvedValueOnce(project);
+ addProjectScenes.mockResolvedValue([{ sceneId: 's1' }, { sceneId: 's2' }, { sceneId: 's3' }]);
+ resolveProviderAndModel.mockResolvedValue({ provider: { id: 'p1', enabled: false }, selectedModel: 'gpt' });
+
+ const result = await planProject('mv-1');
+
+ expect(runPromptThroughProvider).not.toHaveBeenCalled();
+ expect(result.promptsSkippedReason).toBe('provider-disabled');
+ });
+});
diff --git a/server/services/musicVideo/projects.js b/server/services/musicVideo/projects.js
index 5a29a909f0..dee78b1763 100644
--- a/server/services/musicVideo/projects.js
+++ b/server/services/musicVideo/projects.js
@@ -111,6 +111,13 @@ export async function addProjectScene(id, sceneInput) {
return scene;
}
+/** Bulk-append scenes (the autonomous planner, #1855) — emits one update, not N. */
+export async function addProjectScenes(id, sceneInputs) {
+ const scenes = await (await selectBackend()).addProjectScenes(id, sceneInputs);
+ emitRecordUpdated('musicVideoProject', id);
+ return scenes;
+}
+
export async function updateScene(id, sceneId, patch) {
const result = await (await selectBackend()).updateScene(id, sceneId, patch);
emitRecordUpdated('musicVideoProject', id);
diff --git a/server/services/musicVideo/projects.test.js b/server/services/musicVideo/projects.test.js
index d5dc7b77ba..b6122afefc 100644
--- a/server/services/musicVideo/projects.test.js
+++ b/server/services/musicVideo/projects.test.js
@@ -63,6 +63,21 @@ describe('musicVideo dispatcher — record-event emit (#1770)', () => {
expect(emitRecordDeleted).not.toHaveBeenCalled();
});
+ it('addProjectScenes bulk-appends and emits exactly one updated (not one per scene)', async () => {
+ const p = await projects.createProject({ name: 'A' });
+ emitRecordUpdated.mockClear();
+
+ const scenes = await projects.addProjectScenes(p.id, [{ prompt: 'one' }, { prompt: 'two' }, { prompt: 'three' }]);
+
+ expect(scenes).toHaveLength(3);
+ expect(scenes.map((s) => s.order)).toEqual([0, 1, 2]);
+ expect(emitRecordUpdated).toHaveBeenCalledTimes(1);
+ expect(emitRecordUpdated).toHaveBeenCalledWith('musicVideoProject', p.id);
+
+ const fresh = await projects.getProject(p.id);
+ expect(fresh.scenes).toHaveLength(3);
+ });
+
it('emits deleted on soft-delete (tombstone federates)', async () => {
const p = await projects.createProject({ name: 'A' });
emitRecordDeleted.mockClear();
diff --git a/server/services/musicVideo/projectsDB.js b/server/services/musicVideo/projectsDB.js
index 85ba8a525d..6bc8876d4c 100644
--- a/server/services/musicVideo/projectsDB.js
+++ b/server/services/musicVideo/projectsDB.js
@@ -19,6 +19,7 @@ import {
applyProjectPatch,
setAudioAnalysis,
addScene,
+ addScenes,
applySceneUpdate,
removeScene,
reorderScenes,
@@ -194,6 +195,15 @@ export async function addProjectScene(id, sceneInput) {
return result;
}
+/** Bulk-append scenes (the autonomous planner, #1855) — one locked read/write. */
+export async function addProjectScenes(id, sceneInputs) {
+ const { result } = await withLockedProject(id, (p) => {
+ const { project, scenes } = addScenes(p, sceneInputs);
+ return { project, result: scenes };
+ });
+ return result;
+}
+
export async function updateScene(id, sceneId, patch) {
const { result } = await withLockedProject(id, (p) => {
const { project, updated } = applySceneUpdate(p, sceneId, patch);
diff --git a/server/services/musicVideo/projectsFile.js b/server/services/musicVideo/projectsFile.js
index f36110f424..b08b38446a 100644
--- a/server/services/musicVideo/projectsFile.js
+++ b/server/services/musicVideo/projectsFile.js
@@ -16,6 +16,7 @@ import {
applyProjectPatch,
setAudioAnalysis,
addScene,
+ addScenes,
applySceneUpdate,
removeScene,
reorderScenes,
@@ -157,6 +158,15 @@ export async function addProjectScene(id, sceneInput) {
return scene;
}
+/** Bulk-append scenes (the autonomous planner, #1855) — one load/save round trip. */
+export async function addProjectScenes(id, sceneInputs) {
+ const { all, idx } = await loadAllAndIndex(id);
+ const { project, scenes } = addScenes(all[idx], sceneInputs);
+ all[idx] = project;
+ await saveAll(all);
+ return scenes;
+}
+
export async function updateScene(id, sceneId, patch) {
const { all, idx } = await loadAllAndIndex(id);
const { project, updated } = applySceneUpdate(all[idx], sceneId, patch);
diff --git a/server/services/musicVideo/projectsLogic.js b/server/services/musicVideo/projectsLogic.js
index b0641708d1..ecb1e80cc1 100644
--- a/server/services/musicVideo/projectsLogic.js
+++ b/server/services/musicVideo/projectsLogic.js
@@ -119,14 +119,33 @@ function buildScene(input, { order }) {
/**
* Append a scene to the board. Validates the input, assigns a sceneId and the
- * next order index. Returns `{ project, scene }`.
+ * next order index. Returns `{ project, scene }`. A thin single-item wrapper
+ * over `addScenes` so the validate/build/order logic lives in exactly one
+ * place.
*/
export function addScene(project, sceneInput) {
- const data = parseSceneOrThrow(musicVideoSceneCreateSchema, sceneInput);
- const scenes = project.scenes || [];
- const scene = buildScene(data, { order: scenes.length });
- const next = touch(project, { scenes: [...scenes, scene] });
- return { project: next, scene };
+ const { project: next, scenes } = addScenes(project, [sceneInput]);
+ return { project: next, scene: scenes[0] };
+}
+
+/**
+ * Append several scenes to the board in one pass (the autonomous planner,
+ * #1855) — a single `touch`/persist instead of N sequential addScene calls, so
+ * a 10-section plan is one write (and one peer-sync emit) instead of ten.
+ * Returns `{ project, scenes }` (the newly-created scenes, in input order).
+ */
+export function addScenes(project, sceneInputs) {
+ const list = Array.isArray(sceneInputs) ? sceneInputs : [];
+ const existing = project.scenes || [];
+ const added = [];
+ let order = existing.length;
+ for (const input of list) {
+ const data = parseSceneOrThrow(musicVideoSceneCreateSchema, input);
+ added.push(buildScene(data, { order }));
+ order += 1;
+ }
+ const next = touch(project, { scenes: [...existing, ...added] });
+ return { project: next, scenes: added };
}
/**
diff --git a/server/services/musicVideo/projectsLogic.test.js b/server/services/musicVideo/projectsLogic.test.js
index caba6631bc..aa9c03b6f2 100644
--- a/server/services/musicVideo/projectsLogic.test.js
+++ b/server/services/musicVideo/projectsLogic.test.js
@@ -4,6 +4,7 @@ import {
applyProjectPatch,
setAudioAnalysis,
addScene,
+ addScenes,
applySceneUpdate,
removeScene,
reorderScenes,
@@ -81,6 +82,36 @@ describe('scene board operations', () => {
expect(() => addScene(baseProject(), { startSec: 10, endSec: 5 })).toThrow(/Scene validation failed/);
});
+ it('addScenes bulk-appends in one pass with incrementing order (the autonomous planner, #1855)', () => {
+ const { project, scenes } = addScenes(baseProject(), [
+ { label: 'Intro', startSec: 0, endSec: 10 },
+ { label: 'Drop', startSec: 10, endSec: 18 },
+ ]);
+ expect(scenes).toHaveLength(2);
+ expect(scenes.map((s) => s.order)).toEqual([0, 1]);
+ expect(scenes[0].sceneId).not.toBe(scenes[1].sceneId);
+ expect(project.scenes).toHaveLength(2);
+ });
+
+ it('addScenes continues ordering after existing scenes', () => {
+ const { project: seeded } = addScene(baseProject(), { prompt: 'existing' });
+ const { scenes } = addScenes(seeded, [{ label: 'Next' }]);
+ expect(scenes[0].order).toBe(1);
+ });
+
+ it('addScenes rejects the whole batch if any scene is invalid', () => {
+ expect(() => addScenes(baseProject(), [
+ { label: 'ok', startSec: 0, endSec: 5 },
+ { label: 'bad', startSec: 10, endSec: 5 },
+ ])).toThrow(/Scene validation failed/);
+ });
+
+ it('addScenes treats a non-array input as empty', () => {
+ const { project, scenes } = addScenes(baseProject(), null);
+ expect(scenes).toEqual([]);
+ expect(project.scenes).toEqual([]);
+ });
+
it('updates a scene by id', () => {
const { project, scene } = addScene(baseProject(), { prompt: 'a' });
const { updated } = applySceneUpdate(project, scene.sceneId, { prompt: 'b', referenceImageId: 'img-1' });