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: require an explicit Replace/Add choice when AI Plan runs on a board with shots (#10144)

Adam Eivyc1ef23bae2c7
diff --git a/client/src/components/musicVideo/ProjectActionGroups.jsx b/client/src/components/musicVideo/ProjectActionGroups.jsx
index a43121eba4..e38f701262 100644
--- a/client/src/components/musicVideo/ProjectActionGroups.jsx
+++ b/client/src/components/musicVideo/ProjectActionGroups.jsx
@@ -1,3 +1,4 @@
+import { useState } from 'react';
import { Film, Music, Activity, Image as ImageIcon, Video, Wand2 } from 'lucide-react';
import { MUSCRIPTOR_MODELS } from '../../lib/muscriptorModels.js';
import { isLayeredComposition, sceneRenderReady, sceneVisualLayer } from '../../lib/musicVideoLayers.js';
@@ -60,13 +61,31 @@ export function AudioActions({ project, midi, midiBound, busy, onAnalyze }) {
/** Plan the shots against the analyzed song and spread them by energy. */
export function PlanActions({ project, busy, onPlan, onAutoArrange }) {
const sceneCount = (project.scenes || []).length;
+ // A board that already has shots needs an explicit choice before planning:
+ // planning blindly would stack a second full-song plan on top of it.
+ const [choosing, setChoosing] = useState(false);
+ const choose = (mode) => { setChoosing(false); onPlan(mode); };
return (
<div className={groupCls}>
- <button onClick={onPlan} disabled={busy.planning || !project.audioAnalysis}
+ <button onClick={() => (sceneCount > 0 ? setChoosing(true) : onPlan())} disabled={busy.planning || !project.audioAnalysis}
title={!project.audioAnalysis ? 'Analyze the track first' : 'AI-plan bounded shots per song section, cut on timed lyrics, phrases and beats'}
className={buttonCls}>
<Wand2 size={15} /> {busy.planning ? 'Planning…' : 'AI Plan'}
</button>
+ {choosing && !busy.planning && (
+ <div role="group" aria-label="Plan mode" className="flex flex-wrap items-center gap-2 text-sm">
+ <span className="text-gray-400">The board has {sceneCount} shot{sceneCount === 1 ? '' : 's'}.</span>
+ <button onClick={() => choose('replace')} className={buttonCls}
+ title="Swap the board for a new plan; takes and clips are kept on shots whose time span is reused">
+ Replace {sceneCount} shot{sceneCount === 1 ? '' : 's'}
+ </button>
+ <button onClick={() => choose('append')} className={buttonCls}
+ title="Add the planned shots after the existing ones (can overlap them)">
+ Add to board
+ </button>
+ <button onClick={() => setChoosing(false)} className={buttonCls}>Cancel</button>
+ </div>
+ )}
<button onClick={onAutoArrange}
disabled={busy.arranging || !project.audioAnalysis || sceneCount === 0}
title={!project.audioAnalysis
diff --git a/client/src/pages/MusicVideo.jsx b/client/src/pages/MusicVideo.jsx
index 83fdd5dd69..712509db8c 100644
--- a/client/src/pages/MusicVideo.jsx
+++ b/client/src/pages/MusicVideo.jsx
@@ -434,10 +434,10 @@ export default function MusicVideo() {
// Director-first — seeded shots are ordinary, fully-editable board entries.
// `target` lets the autopilot kickoff plan the freshly analyzed record
// before `selected` re-renders with it.
- const handlePlan = (target = selected) => {
+ const handlePlan = (target = selected, mode) => {
if (!target?.audioAnalysis) return Promise.resolve();
setPlanning(true);
- return planMusicVideoProject(target.id, { seedPrompts: true }, { silent: true })
+ return planMusicVideoProject(target.id, { seedPrompts: true, ...(mode ? { mode } : {}) }, { silent: true })
.then(({ project, scenesAdded, promptsSeeded, promptsSkippedReason }) => {
replaceProject(project);
const suffix = promptsSeeded
@@ -939,7 +939,7 @@ export default function MusicVideo() {
setPickerTarget,
onAddReference: () => setPickerTarget({ type: 'reference' }),
onAnalyze: () => handleAnalyze(),
- onPlan: () => handlePlan(),
+ onPlan: (mode) => handlePlan(selected, mode),
onAutoArrange: handleAutoArrange,
onKickoff: handleKickoff,
onChangeTrack: handleChangeTrack,
diff --git a/client/src/pages/MusicVideo.test.jsx b/client/src/pages/MusicVideo.test.jsx
index 64a99bdc84..4b16c1bff4 100644
--- a/client/src/pages/MusicVideo.test.jsx
+++ b/client/src/pages/MusicVideo.test.jsx
@@ -1274,7 +1274,7 @@ describe('MusicVideo autonomous shot planner (#1855)', () => {
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, 'board');
+ await openProject({ ...PROJECT_ANALYZED, scenes: [] }, 'board');
const planBtn = await screen.findByRole('button', { name: /AI Plan/i });
expect(planBtn).toHaveProperty('disabled', false);
@@ -1283,6 +1283,26 @@ describe('MusicVideo autonomous shot planner (#1855)', () => {
});
});
+describe('MusicVideo AI Plan on a board that already has scenes (#10144)', () => {
+ const withScenes = { ...PROJECT_ANALYZED, scenes: [{ sceneId: 's1', order: 0, prompt: 'p' }, { sceneId: 's2', order: 1, prompt: 'q' }] };
+
+ it('sends no plan request until the director chooses Replace or Add', async () => {
+ planMusicVideoProject.mockClear();
+ planMusicVideoProject.mockResolvedValue({ project: withScenes, scenesAdded: 1, promptsSeeded: false });
+ await openProject(withScenes, 'board');
+ fireEvent.click(await screen.findByRole('button', { name: /AI Plan/i }));
+ expect(await screen.findByRole('button', { name: /Replace 2 shots/ })).toBeTruthy();
+ expect(planMusicVideoProject).not.toHaveBeenCalled();
+
+ fireEvent.click(screen.getByRole('button', { name: 'Cancel' }));
+ expect(planMusicVideoProject).not.toHaveBeenCalled();
+
+ fireEvent.click(screen.getByRole('button', { name: /AI Plan/i }));
+ fireEvent.click(await screen.findByRole('button', { name: /Replace 2 shots/ }));
+ await waitFor(() => expect(planMusicVideoProject).toHaveBeenCalledWith(withScenes.id, { seedPrompts: true, mode: 'replace' }, { silent: true }));
+ });
+});
+
describe('MusicVideo autonomous mode setup experience', () => {
it('renders autonomous run at top of setup, hides lyrics fork callout when no lyrics exist, and reflects progress in next action', async () => {
const autoProject = {
diff --git a/server/lib/musicVideoValidation.js b/server/lib/musicVideoValidation.js
index 5b5a808a98..acb2e18f54 100644
--- a/server/lib/musicVideoValidation.js
+++ b/server/lib/musicVideoValidation.js
@@ -1186,6 +1186,8 @@ export const musicVideoPlanRequestSchema = z.object({
providerId: z.string().max(64).optional(),
model: z.string().max(200).optional(),
effort: z.enum(EFFORT_LEVELS).optional(),
+ // Required once the board has scenes (409 PLAN_MODE_REQUIRED otherwise).
+ mode: z.enum(['replace', 'append']).optional(),
}).strict();
// Manual-tempo fallback (see services/musicVideo/audioAnalysis.js for why bpm
diff --git a/server/routes/musicVideo.js b/server/routes/musicVideo.js
index 9143660ffa..849eab9e0b 100644
--- a/server/routes/musicVideo.js
+++ b/server/routes/musicVideo.js
@@ -360,8 +360,8 @@ router.post('/:id/analyze/manual', asyncHandler(async (req, res) => {
// 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, effort } = validateRequest(musicVideoPlanRequestSchema, req.body || {});
- const result = await planProject(req.params.id, { seedPrompts, providerId, model, effort });
+ const { seedPrompts, providerId, model, effort, mode } = validateRequest(musicVideoPlanRequestSchema, req.body || {});
+ const result = await planProject(req.params.id, { seedPrompts, providerId, model, effort, mode: mode ?? 'require' });
res.json(result);
}));
diff --git a/server/routes/musicVideo.test.js b/server/routes/musicVideo.test.js
index ba47c02fb9..193dfbb0bd 100644
--- a/server/routes/musicVideo.test.js
+++ b/server/routes/musicVideo.test.js
@@ -583,7 +583,7 @@ describe('musicVideo routes', () => {
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(planProject).toHaveBeenCalledWith('mv-1', { seedPrompts: undefined, providerId: undefined, model: undefined, mode: 'require' });
expect(r.body.scenesAdded).toBe(1);
expect(r.body.promptsSeeded).toBe(false);
});
@@ -592,7 +592,26 @@ describe('musicVideo routes', () => {
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' });
+ expect(planProject).toHaveBeenCalledWith('mv-1', { seedPrompts: false, providerId: 'p1', model: 'gpt-x', mode: 'require' });
+ });
+
+ it.each(['replace', 'append'])('forwards an explicit %s mode', async (mode) => {
+ const r = await request(app).post('/api/music-video/mv-1/plan').send({ mode });
+ expect(r.status).toBe(200);
+ expect(planProject).toHaveBeenCalledWith('mv-1', expect.objectContaining({ mode }));
+ });
+
+ it('surfaces the 409 PLAN_MODE_REQUIRED the planner raises for a non-empty board', async () => {
+ const { ServerError } = await import('../lib/errorHandler.js');
+ planProject.mockRejectedValueOnce(new ServerError('choose', { status: 409, code: 'PLAN_MODE_REQUIRED' }));
+ const r = await request(app).post('/api/music-video/mv-1/plan');
+ expect(r.status).toBe(409);
+ expect(r.body.code).toBe('PLAN_MODE_REQUIRED');
+ });
+
+ it('rejects an unknown mode', async () => {
+ const r = await request(app).post('/api/music-video/mv-1/plan').send({ mode: 'merge' });
+ expect(r.status).toBe(400);
});
it('rejects an unknown body field', async () => {
diff --git a/server/services/musicVideo/planner.js b/server/services/musicVideo/planner.js
index 86f1dcf94d..9bc29b81be 100644
--- a/server/services/musicVideo/planner.js
+++ b/server/services/musicVideo/planner.js
@@ -283,6 +283,10 @@ async function tryProposeScenePrompts(project, shots, { providerId, model, effor
* @param {string} [options.model] — model override for the prompt-seeding call.
* @param {string} [options.effort] — reasoning-effort override for an
* effort-capable CLI/TUI provider (clamped by the runner).
+ * @param {'replace'|'append'|'require'} [options.mode='append'] — what to do when the
+ * board already has scenes: `replace` swaps the board (keeping work on scenes
+ * whose time span is reused), `append` adds to it, `require` refuses with a
+ * 409 `PLAN_MODE_REQUIRED` so a caller must choose (the HTTP route).
* @param {string} [options.directive] — a production run's directive (#9066),
* added to the director guidance the first-pass prompts are written under.
* @returns {Promise<{ project: object, scenesAdded: number, promptsSeeded: boolean, promptsSkippedReason: string|null, pacing: object, llmRoute: object|null }>}
@@ -290,9 +294,16 @@ async function tryProposeScenePrompts(project, shots, { providerId, model, effor
* used (null when none was made); a project with an automation brief also
* keeps it under `automation.routes.plan`.
*/
-export async function planProject(id, { seedPrompts = true, providerId, model, effort, directive } = {}) {
+export async function planProject(id, { seedPrompts = true, providerId, model, effort, directive, mode = 'append' } = {}) {
const project = await getProject(id);
if (!project) throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });
+ const existingCount = (project.scenes || []).length;
+ if (mode === 'require' && existingCount > 0) {
+ throw new ServerError(
+ `The board already has ${existingCount} shot${existingCount === 1 ? '' : 's'} — choose to replace them or add to the board`,
+ { status: 409, code: 'PLAN_MODE_REQUIRED', context: { sceneCount: existingCount } },
+ );
+ }
const sections = validSections(project.audioAnalysis?.sections);
if (sections.length === 0) {
@@ -348,22 +359,21 @@ export async function planProject(id, { seedPrompts = true, providerId, model, e
const hasCards = sceneInputs.some((s) => s.visualLayer === 'card');
// Persist card scenes and the mode that renders them in the same transaction.
// Read the current composition under the lock so concurrent edits survive.
- const { project: persisted, scenes } = hasCards
- ? await persistCardPlan(id, sceneInputs)
- : await addProjectScenes(id, sceneInputs);
+ const { project: persisted, scenes } = await persistPlan(id, sceneInputs, { hasCards, replace: mode === 'replace' });
// Only a project with an automation brief keeps the route it planned on.
const updated = (persisted.automation && await recordLlmRoute(id, 'plan', llmRoute)) || persisted;
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, pacing, llmRoute };
}
-async function persistCardPlan(id, sceneInputs) {
- const { addScenes } = await import('./projectsLogic.js');
+async function persistPlan(id, sceneInputs, { hasCards, replace }) {
+ if (!hasCards && !replace) return addProjectScenes(id, sceneInputs);
+ const { addScenes, replaceScenes } = await import('./projectsLogic.js');
const { normalizeComposition } = await import('./composition.js');
return mutateProjectRecord(id, (current) => {
- const outcome = addScenes(current, sceneInputs);
+ const outcome = (replace ? replaceScenes : addScenes)(current, sceneInputs);
// An authored whole-song code/document renderer remains the operator's choice.
- if (!current.composition?.mode || current.composition.mode === 'concat') {
+ if (hasCards && (!current.composition?.mode || current.composition.mode === 'concat')) {
outcome.project.composition = normalizeComposition({ ...current.composition, mode: 'composed' });
}
return outcome;
diff --git a/server/services/musicVideo/planner.test.js b/server/services/musicVideo/planner.test.js
index 70091b2574..5481ede61b 100644
--- a/server/services/musicVideo/planner.test.js
+++ b/server/services/musicVideo/planner.test.js
@@ -332,6 +332,38 @@ describe('planProject', () => {
expect(result.promptsSkippedReason).toBe('no-provider');
});
+ it('409s PLAN_MODE_REQUIRED before any LLM or write when the board has scenes and the caller must choose', async () => {
+ getProject.mockResolvedValue(makeProject({ scenes: [{ sceneId: 'old-1' }, { sceneId: 'old-2' }] }));
+ await expect(planProject('mv-1', { mode: 'require' })).rejects.toMatchObject({ status: 409, code: 'PLAN_MODE_REQUIRED' });
+ expect(addProjectScenes).not.toHaveBeenCalled();
+ expect(mutateProjectRecord).not.toHaveBeenCalled();
+ expect(runPromptThroughProvider).not.toHaveBeenCalled();
+ });
+
+ it('plans normally under mode "require" when the board is empty', async () => {
+ getProject.mockResolvedValue(makeProject({ scenes: [] }));
+ addProjectScenes.mockResolvedValue(freshProjectResult());
+ await planProject('mv-1', { mode: 'require', seedPrompts: false });
+ expect(addProjectScenes).toHaveBeenCalledTimes(1);
+ });
+
+ it('replace swaps the board through the record mutation, keeping work on scenes with a reused span', async () => {
+ const old = [{ sceneId: 'old-1', startSec: 0, endSec: 2, videoHistoryId: 'v1', referenceImageId: 'r1', takes: [{ takeId: 't' }] }, { sceneId: 'old-2', startSec: 99, endSec: 100 }];
+ getProject.mockResolvedValue(makeProject({ scenes: old }));
+ let outcome;
+ mutateProjectRecord.mockImplementation(async (_id, transform) => { outcome = transform(makeProject({ scenes: old })); return outcome; });
+
+ const result = await planProject('mv-1', { mode: 'replace', seedPrompts: false });
+
+ expect(addProjectScenes).not.toHaveBeenCalled();
+ const scenes = outcome.project.scenes;
+ expect(scenes.some((sc) => sc.sceneId === 'old-2')).toBe(false);
+ const kept = scenes.find((sc) => sc.sceneId === 'old-1');
+ if (kept) expect(kept).toMatchObject({ videoHistoryId: 'v1', referenceImageId: 'r1', takes: [{ takeId: 't' }] });
+ expect(scenes.map((sc) => sc.order)).toEqual(scenes.map((_, i) => i));
+ expect(result.scenesAdded).toBe(scenes.length);
+ });
+
it('skips the LLM call entirely when seedPrompts is false', async () => {
getProject.mockResolvedValue(makeProject());
addProjectScenes.mockResolvedValue(freshProjectResult());
diff --git a/server/services/musicVideo/projectsLogic.js b/server/services/musicVideo/projectsLogic.js
index ca9829f738..d7f3b61edd 100644
--- a/server/services/musicVideo/projectsLogic.js
+++ b/server/services/musicVideo/projectsLogic.js
@@ -521,6 +521,36 @@ export function addScenes(project, sceneInputs) {
return { project: next, scenes: added };
}
+/**
+ * Replace the whole board with freshly planned scenes (AI Plan "Replace").
+ * A new shot whose time span matches an old scene (within 10 ms) inherits that
+ * scene's id, direction, reference frame, selected clip and takes, so the
+ * generated work and treatment direction keyed to the id survive the re-plan.
+ * Returns `{ project, scenes, replaced }` (`replaced` = the old scene count).
+ */
+export function replaceScenes(project, sceneInputs) {
+ const list = Array.isArray(sceneInputs) ? sceneInputs : [];
+ const existing = project.scenes || [];
+ const claimed = new Set();
+ const sameSpan = (a, b) => typeof a === 'number' && typeof b === 'number' && Math.abs(a - b) < 0.01;
+ const scenes = list.map((input, order) => {
+ const fresh = buildScene(parseSceneOrThrow(musicVideoSceneCreateSchema, input), { order });
+ const prior = existing.find((old) => !claimed.has(old.sceneId)
+ && sameSpan(old.startSec, fresh.startSec) && sameSpan(old.endSec, fresh.endSec));
+ if (!prior) return fresh;
+ claimed.add(prior.sceneId);
+ return {
+ ...fresh,
+ sceneId: prior.sceneId,
+ referenceImageId: prior.referenceImageId ?? null,
+ videoHistoryId: prior.videoHistoryId ?? null,
+ takes: prior.takes || [],
+ ...(prior.direction ? { direction: prior.direction } : {}),
+ };
+ });
+ return { project: touch(project, { scenes }), scenes, replaced: existing.length };
+}
+
/**
* Apply a patch to a single scene. Returns `{ project, updated }`. Throws if the
* scene id is unknown.