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: revise music-video stages from open "Request changes" feedback (#10165)

Adam Eivycabdef24b44f
diff --git a/client/src/components/musicVideo/ProductionReviewPanel.jsx b/client/src/components/musicVideo/ProductionReviewPanel.jsx
index 849326ca31..b9bbf2c0f6 100644
--- a/client/src/components/musicVideo/ProductionReviewPanel.jsx
+++ b/client/src/components/musicVideo/ProductionReviewPanel.jsx
@@ -23,6 +23,8 @@ export default function ProductionReviewPanel({ project, review, onOpenArtifact,
const [feedback, setFeedback] = useState({ stage: 'art', target: '', text: '', decision: 'request-changes' });
const [resolutions, setResolutions] = useState({});
const [importError, setImportError] = useState(null);
+ const [revisionNotice, setRevisionNotice] = useState(null);
+ const [savedRequestStage, setSavedRequestStage] = useState(null);
const [playbackReview, setPlaybackReview] = useState({ ...EMPTY_PLAYBACK, identity: null });
const [startSec, setStartSec] = useState(project.productionReview?.proof?.startSec || 0);
const [endSec, setEndSec] = useState(project.productionReview?.proof?.endSec || Math.min(20, project.audioAnalysis?.durationSec || 20));
@@ -81,6 +83,33 @@ export default function ProductionReviewPanel({ project, review, onOpenArtifact,
if (target) { target.open = true; target.focus({ preventScroll: true }); }
};
const nextStage = ['art', 'storyboard', 'proof'].find(stage => !ready?.[stage].approved) || 'proof';
+ const openRequests = stage => (project.productionReview?.feedback || []).filter(f => f.stage === stage && f.decision === 'request-changes' && !f.resolvedAt);
+ // Mirrors the server's revise routing so an unsupported stage explains itself instead of failing on click.
+ const revisionScope = stage => {
+ if (stage === 'art') return project.castAndSets?.direction
+ ? { action: 'Regenerates the Cast & Sets direction and sheet with these requests. Review the new sheet before approving.' }
+ : { unavailable: 'This art direction has no Cast & Sets direction to regenerate. Edit the guide, then resolve each request.' };
+ if (stage === 'storyboard') {
+ if (documentShots) return { unavailable: 'Document shots come from the authored source. Revise it, reimport its shot manifest, then resolve each request.' };
+ return project.scenes?.length
+ ? { action: 'Re-plans the shots these requests name (every shot when a request names none) in place, keeping their takes and selected media.' }
+ : { unavailable: 'Plan timed Board shots before revising them from feedback.' };
+ }
+ const mode = project.composition?.mode;
+ if (mode === 'code') return { action: 'Regenerates the code composition with these requests. Render a new proof afterwards.' };
+ if (mode === 'document') return ['generated', 'template', undefined].includes(project.composition?.document?.source?.kind)
+ ? { action: 'Authors a revised composition candidate with these requests. Accept it in Compose, then render a new proof.' }
+ : { unavailable: 'This composition was imported from its own source. Revise that source and reimport it, then resolve each request.' };
+ return { unavailable: 'This proof is assembled from Board footage. Revise the affected storyboard shots or takes, then render a new proof.' };
+ };
+ const revise = async stage => {
+ const result = await review.revise(stage);
+ if (!result) return;
+ const count = result.revision?.sceneIds?.length;
+ setRevisionNotice({ stage, text: stage === 'art' ? 'Cast & Sets is regenerating with these requests. Review the new sheet, then resolve each request.'
+ : stage === 'storyboard' ? `Revised ${count} shot${count === 1 ? '' : 's'}. Review them, then resolve each request.`
+ : 'A revised composition is ready. Render and review a new proof, then resolve each request.' });
+ };
const proofContent = <>
<p className="text-xs text-port-text-muted break-words">Project v{project.version || 1} · proof revision {ready?.basis.proof?.slice(0, 12) || 'Loading…'} · {excerpt ? `Excerpt ${excerpt.id}` : 'No registered proof'}</p>
{!excerpt && <div className="rounded border border-port-border p-3 space-y-2" aria-label="Proof approval prerequisites">
@@ -186,6 +215,15 @@ export default function ProductionReviewPanel({ project, review, onOpenArtifact,
const fold = input?.closest('details'); if (fold) fold.open = true;
input?.scrollIntoView({ block: 'center' }); input?.focus({ preventScroll: true });
}}>Request changes</button>
+ {openRequests(key).length > 0 && <div role="group" aria-label={`${label} change requests`} className="mt-2 space-y-2 rounded border border-port-warning p-2">
+ <p className="text-sm">Approval stays blocked until these are resolved. Revise from feedback, or edit and resolve manually.</p>
+ <ul className="list-disc pl-5 text-sm">{openRequests(key).map(item => <li key={item.id} className="break-words"><strong>{item.target}</strong>: {item.text}</li>)}</ul>
+ {revisionScope(key).unavailable ? <p className="text-xs text-port-text-muted">{revisionScope(key).unavailable}</p> : <>
+ <button type="button" className={buttonClass} disabled={blocked} aria-describedby={fieldId(`${key}-revision-help`)} onClick={() => revise(key)}>Revise from feedback</button>
+ <p id={fieldId(`${key}-revision-help`)} className="text-xs text-port-text-muted">{revisionScope(key).action}</p>
+ </>}
+ {revisionNotice?.stage === key && <p role="status" className="text-sm">{revisionNotice.text}</p>}
+ </div>}
</details></li>)}
</ol>
<p className="text-xs text-port-text-muted">Your signed-in session can approve each reviewed stage. Authenticated agents can also review and approve. Proof approval requires recorded visual and audio evidence; publishing remains manual.</p>
@@ -202,8 +240,14 @@ export default function ProductionReviewPanel({ project, review, onOpenArtifact,
<option value="request-changes">Request changes — blocks affected approvals</option><option value="comment">Comment</option><option value="structure-accepted">Accept structure only — art remains unapproved</option>
</select></label>
<button type="button" className={buttonClass} disabled={blocked || !feedback.target.trim() || !feedback.text.trim()} onClick={async () => {
- if (await review.feedback(feedback)) setFeedback({ ...feedback, text: '' });
+ if (await review.feedback(feedback)) {
+ setFeedback({ ...feedback, text: '' });
+ setSavedRequestStage(feedback.decision === 'request-changes' ? feedback.stage : null);
+ }
}}>Save revision feedback</button>
+ {savedRequestStage && openRequests(savedRequestStage).length > 0 && <p role="status" className="text-sm">
+ Approval stays blocked until these are resolved. <a href={`#mv-review-${savedRequestStage}`} onClick={openReviewSection} className="text-port-accent underline">Revise from feedback</a>, or edit and resolve manually.
+ </p>}
<ul className="mt-3 space-y-3">{(project.productionReview?.feedback || []).map(item => <li key={item.id} className="rounded border border-port-border p-2">
<p className="text-sm"><strong>{item.target}</strong> · {item.decision} · {item.resolvedAt ? 'Resolved' : 'Open'}</p>
<p className="text-sm whitespace-pre-wrap">{item.text}</p>
diff --git a/client/src/components/musicVideo/ProductionReviewPanel.test.jsx b/client/src/components/musicVideo/ProductionReviewPanel.test.jsx
index 0371fd6dc7..7f32592dff 100644
--- a/client/src/components/musicVideo/ProductionReviewPanel.test.jsx
+++ b/client/src/components/musicVideo/ProductionReviewPanel.test.jsx
@@ -191,6 +191,28 @@ describe('Production proof playback evidence', () => {
expect(screen.getByLabelText('Requested change').closest('details').open).toBe(true);
});
+ it('offers a stage revision for open change requests and explains the blocked approval', async () => {
+ const review = { ...reviewFixture(), revise: vi.fn(async () => ({ revision: { stage: 'storyboard', sceneIds: ['scene-a', 'scene-b'] } })) };
+ review.readiness.storyboard = { approved: false, problems: ['Resolve storyboard feedback for shot: Chorus: Land the leap on the downbeat'] };
+ const withRequests = { ...project, scenes: [{ sceneId: 'scene-a', label: 'Chorus', startSec: 0, endSec: 10 }],
+ productionReview: { ...project.productionReview, feedback: [
+ { id: 'fb-open', stage: 'storyboard', target: 'shot: Chorus', text: 'Land the leap on the downbeat', decision: 'request-changes', basis: 'board' },
+ { id: 'fb-done', stage: 'storyboard', target: 'shot: Intro', text: 'Already handled', decision: 'request-changes', basis: 'board', resolvedAt: '2026-01-01T00:00:00.000Z' },
+ { id: 'fb-proof', stage: 'proof', target: 'frame: 0:04', text: 'Prop lands late', decision: 'request-changes', basis: 'same-creative-basis' },
+ ] } };
+ render(<ProductionReviewPanel project={withRequests} review={review} onOpenArtifact={vi.fn()} />);
+ const requests = screen.getByRole('group', { name: 'Lyric-timed storyboard change requests' });
+ expect(requests.textContent).toContain('Approval stays blocked until these are resolved. Revise from feedback, or edit and resolve manually.');
+ expect(requests.textContent).toContain('Land the leap on the downbeat');
+ expect(requests.textContent).not.toContain('Already handled');
+ fireEvent.click(within(requests).getByRole('button', { name: 'Revise from feedback' }));
+ expect(review.revise).toHaveBeenCalledWith('storyboard');
+ await waitFor(() => expect(requests.textContent).toContain('Revised 2 shots. Review them, then resolve each request.'));
+ // A document-mode proof with no imported source can be re-authored as a generated candidate.
+ const proofRequests = screen.getByRole('group', { name: 'Animated proof change requests' });
+ expect(within(proofRequests).getByRole('button', { name: 'Revise from feedback' })).toBeTruthy();
+ });
+
it('keeps the hash-selected art context open when readiness arrives', () => {
window.location.hash = '#mv-review-art';
const review = reviewFixture();
diff --git a/client/src/hooks/useMusicVideoProductionReview.js b/client/src/hooks/useMusicVideoProductionReview.js
index 82cfc9a14c..a88c59bbca 100644
--- a/client/src/hooks/useMusicVideoProductionReview.js
+++ b/client/src/hooks/useMusicVideoProductionReview.js
@@ -1,7 +1,7 @@
import { useEffect, useRef, useState } from 'react';
import { reverifyMusicVideoAlignment, importMusicVideoDocumentShots, getMusicVideoProductionReview, saveMusicVideoProductionDraft, prepareMusicVideoProductionReview,
approveMusicVideoProductionReview, renderMusicVideoProductionProof, musicVideoExcerptRenderEventsUrl,
- cancelMusicVideoExcerptRender, importMusicVideoProductionPlanning, bindMusicVideoProductionShot, addMusicVideoProductionFeedback, resolveMusicVideoProductionFeedback } from '../services/apiMusicVideo.js';
+ cancelMusicVideoExcerptRender, importMusicVideoProductionPlanning, bindMusicVideoProductionShot, addMusicVideoProductionFeedback, resolveMusicVideoProductionFeedback, reviseMusicVideoProductionFromFeedback } from '../services/apiMusicVideo.js';
import useSseJobSlot from './useSseJobSlot.js';
/** Server-authoritative approvals; changing any project input hides stale readiness immediately. */
@@ -52,6 +52,7 @@ export default function useMusicVideoProductionReview({ project, replaceProject
return { readiness: state?.owner === project ? state.readiness : null, busy, error, proof: { ...proof, occupied: proof.active, active: proof.active && proof.context === project?.id },
feedback: body => call(() => addMusicVideoProductionFeedback(project.id, { ...body, basis: state?.readiness.basis[body.stage] }, { silent: true })),
resolveFeedback: (feedbackId, resolution) => call(() => resolveMusicVideoProductionFeedback(project.id, { feedbackId, resolution }, { silent: true })),
+ revise: stage => call(() => reviseMusicVideoProductionFromFeedback(project.id, { stage }, { silent: true })),
importDocumentShots: body => call(() => importMusicVideoDocumentShots(project.id, body, { silent: true })),
importPlanning: source => call(() => importMusicVideoProductionPlanning(project.id, source, { silent: true })),
bindShot: shotId => call(() => bindMusicVideoProductionShot(project.id, shotId, { silent: true })),
diff --git a/client/src/services/apiMusicVideo.js b/client/src/services/apiMusicVideo.js
index c47db132f3..8169caacb4 100644
--- a/client/src/services/apiMusicVideo.js
+++ b/client/src/services/apiMusicVideo.js
@@ -459,6 +459,7 @@ export const importMusicVideoProductionPlanning = (id, source, options = {}) =>
export const bindMusicVideoProductionShot = (id, shotId, options = {}) => request(`/music-video/${encodeURIComponent(id)}/production-review/shots/${encodeURIComponent(shotId)}/bind`, { method: 'POST', ...options });
export const addMusicVideoProductionFeedback = (id, body, options = {}) => request(`/music-video/${encodeURIComponent(id)}/production-review/feedback`, { method: 'POST', body: JSON.stringify(body), ...options });
+export const reviseMusicVideoProductionFromFeedback = (id, body, options = {}) => request(`/music-video/${encodeURIComponent(id)}/production-review/revise`, { method: 'POST', body: JSON.stringify(body), ...options });
export const resolveMusicVideoProductionFeedback = (id, body, options = {}) => request(`/music-video/${encodeURIComponent(id)}/production-review/feedback/resolve`, { method: 'POST', body: JSON.stringify(body), ...options });
// Drafting is free; generation and candidate selection are separate explicit actions.
export const saveMusicVideoSongRevision = (id, fields, options = {}) => request(`/music-video/${encodeURIComponent(id)}/song-revision`, { method: 'POST', body: JSON.stringify(fields), ...options });
diff --git a/server/lib/musicVideoValidation.js b/server/lib/musicVideoValidation.js
index f3a2653a20..b317e31571 100644
--- a/server/lib/musicVideoValidation.js
+++ b/server/lib/musicVideoValidation.js
@@ -1302,6 +1302,9 @@ export const musicVideoProductionFeedbackSchema = z.object({
target: z.string().trim().min(1).max(300), text: z.string().trim().min(1).max(8000),
decision: z.enum(['comment', 'structure-accepted', 'request-changes']),
}).strict();
+export const musicVideoProductionReviseSchema = musicVideoCastAndSetsStartSchema.extend({
+ stage: z.enum(['art', 'storyboard', 'proof']),
+}).strict();
export const musicVideoProductionFeedbackResolutionSchema = z.object({
feedbackId: z.string().min(1).max(128), resolution: z.string().trim().min(1).max(8000), password: z.string().max(1024).optional(),
}).strict();
diff --git a/server/routes/musicVideo.js b/server/routes/musicVideo.js
index a55f0ba17e..92833c5436 100644
--- a/server/routes/musicVideo.js
+++ b/server/routes/musicVideo.js
@@ -11,9 +11,9 @@
import { existsSync } from 'fs';
import { unlink } from 'fs/promises';
import { Router } from 'express';
-import { musicVideoProjectListQuerySchema, musicVideoProductionDraftSchema, musicVideoProductionApprovalSchema, musicVideoProductionProofSchema, musicVideoProductionImportSchema, musicVideoProductionFeedbackSchema, musicVideoProductionFeedbackResolutionSchema } from '../lib/musicVideoValidation.js';
+import { musicVideoProjectListQuerySchema, musicVideoProductionDraftSchema, musicVideoProductionApprovalSchema, musicVideoProductionProofSchema, musicVideoProductionImportSchema, musicVideoProductionFeedbackSchema, musicVideoProductionFeedbackResolutionSchema, musicVideoProductionReviseSchema } from '../lib/musicVideoValidation.js';
import { productionReadiness } from '../services/musicVideo/productionReview.js';
-import { getProductionReview, saveProductionDraft, prepareProductionReview, approveProductionReview, renderProductionProof, requireProductionReviewer, importProductionPlanning, bindProductionShot, addProductionFeedback, closeProductionFeedback } from '../services/musicVideo/productionReviewService.js';
+import { getProductionReview, saveProductionDraft, prepareProductionReview, approveProductionReview, renderProductionProof, requireProductionReviewer, importProductionPlanning, bindProductionShot, addProductionFeedback, closeProductionFeedback, reviseProductionFromFeedback } from '../services/musicVideo/productionReviewService.js';
import { asyncHandler, ServerError } from '../lib/errorHandler.js';
import {
validateRequest,
@@ -557,6 +557,10 @@ router.post('/:id/production-review/feedback/resolve', asyncHandler(async (req,
const reviewer = await requireProductionReviewer(req);
res.json(await closeProductionFeedback(req.params.id, { feedbackId: input.feedbackId, resolution: input.resolution, reviewer }));
}));
+// An explicit click: the only provider call is the stage's own revision.
+router.post('/:id/production-review/revise', asyncHandler(async (req, res) => {
+ res.json(await reviseProductionFromFeedback(req.params.id, validateRequest(musicVideoProductionReviseSchema, req.body ?? {})));
+}));
router.get('/:id/production-review', asyncHandler(async (req, res) => {
res.json(await getProductionReview(req.params.id));
}));
diff --git a/server/routes/musicVideoProductionReview.test.js b/server/routes/musicVideoProductionReview.test.js
index 23d2aa0ce3..a858fb2df7 100644
--- a/server/routes/musicVideoProductionReview.test.js
+++ b/server/routes/musicVideoProductionReview.test.js
@@ -4,13 +4,14 @@ import { request } from '../lib/testHelper.js';
import { errorMiddleware } from '../lib/errorHandler.js';
import { makePathsProxy, lazyTempDataRoot, cleanupTempDataRoots } from '../lib/mockPathsDataRoot.js';
-const author = vi.hoisted(() => ({ sections: [], calls: 0 }));
+const author = vi.hoisted(() => ({ sections: [], calls: 0, prompts: [] }));
vi.mock('../services/promptRunner.js', () => ({
assertProvider: () => {},
resolveProviderAndModel: async () => ({ provider: { id: 'fixture-author', type: 'api', enabled: true }, selectedModel: 'fixture-model' }),
- runPromptThroughProvider: async ({ beforeExecute }) => {
+ runPromptThroughProvider: async ({ beforeExecute, prompt }) => {
await beforeExecute?.({ provider: { id: 'fixture-author', type: 'api' }, model: 'fixture-model' });
author.calls += 1;
+ author.prompts.push(prompt);
return { text: JSON.stringify({ sections: author.sections }) };
},
}));
@@ -22,7 +23,8 @@ const ROOT = () => lazyTempDataRoot('mv-production-review-');
vi.mock('../lib/paths.js', async original => makePathsProxy(await original(), { dataRoot: ROOT }));
vi.mock('../services/settings.js', () => ({ getSettings: vi.fn(async () => ({})) }));
const planner = vi.hoisted(() => vi.fn());
-vi.mock('../services/musicVideo/planner.js', () => ({ planProject: planner }));
+const shotReviser = vi.hoisted(() => vi.fn());
+vi.mock('../services/musicVideo/planner.js', () => ({ planProject: planner, proposeShotRevisions: shotReviser }));
const auth = vi.hoisted(() => ({ enabled: true, authenticated: true }));
vi.mock('../services/auth.js', () => ({ isAuthEnabled: async () => auth.enabled, verifyPassword: async password => password === 'synthetic-operator-password',
verifyRequestSessionIdentity: async req => auth.authenticated && req.headers.authorization !== 'Bearer expired'
@@ -59,7 +61,7 @@ async function approve(stage, extra = {}) {
beforeEach(async () => {
auth.enabled = true; auth.authenticated = true;
- author.calls = 0; author.sections = [];
+ author.calls = 0; author.sections = []; author.prompts = [];
project = await store.createProject({ name: 'Example animation', uploadedAudioFilename: 'synthetic-song.wav', composition: { mode: 'code' } });
base = `/api/music-video/${project.id}`;
await store.setProjectAnalysis(project.id, { durationSec: 20, bpm: 120, beats: [0, 1], downbeats: [0], sections: [{ startSec: 0, endSec: 20, label: 'Chorus' }] });
@@ -418,3 +420,66 @@ describe('document-bound storyboard revision', () => {
expect((await request(app).post(`${base}/render`).send({})).status).toBe(409);
});
});
+
+describe('revising from review feedback', () => {
+ const revise = stage => request(app).post(`${base}/production-review/revise`).send({ stage });
+ const requestChanges = async (stage, target, text, decision = 'request-changes') => {
+ const status = await read();
+ return request(app).post(`${base}/production-review/feedback`).send({ stage, target, text, decision, basis: status.body.readiness.basis[stage] });
+ };
+
+ it('re-plans the named storyboard shots in place on a new basis and keeps the request open', async () => {
+ expect((await revise('storyboard')).body.code).toBe('MUSIC_VIDEO_NO_FEEDBACK');
+ expect((await requestChanges('storyboard', 'shot: Chorus', 'Open the doorway on the downbeat, not before')).status).toBe(200);
+ const before = await read();
+ const [scene] = before.body.project.scenes;
+ shotReviser.mockImplementationOnce(async (_project, requests) => {
+ expect(requests.map(r => r.text)).toEqual(['Open the doorway on the downbeat, not before']);
+ return new Map([[scene.sceneId, { framePrompt: 'Figure waits at the closed doorway', prompt: 'Doorway swings open on the first downbeat' }]]);
+ });
+
+ const revised = await revise('storyboard');
+
+ expect(revised.status).toBe(200);
+ expect(revised.body.revision).toMatchObject({ stage: 'storyboard', sceneIds: [scene.sceneId] });
+ const after = revised.body.project;
+ expect(after.scenes[0]).toMatchObject({ sceneId: scene.sceneId, prompt: 'Doorway swings open on the first downbeat', framePrompt: 'Figure waits at the closed doorway' });
+ expect(after.productionReview.draft.storyboard[0]).toMatchObject({ action: 'Doorway swings open on the first downbeat',
+ staging: 'Figure waits at the closed doorway', camera: 'Dolly through doorway', transition: 'Match doorway to next frame' });
+ expect(revised.body.readiness.basis.storyboard).not.toBe(before.body.readiness.basis.storyboard);
+ expect(after.productionReview.feedback[0].resolvedAt).toBeUndefined();
+ expect(revised.body.readiness.storyboard.problems).toContain('Resolve storyboard feedback for shot: Chorus: Open the doorway on the downbeat, not before');
+ });
+
+ it('authors a revised document candidate with storyboard and proof feedback in its prompt', async () => {
+ await store.updateProject(project.id, { mediaMode: 'code-only', composition: { mode: 'document', authoringRenderer: 'canvas' },
+ productionPolicy: { strategy: 'code-first', maxGeneratedVideoPercent: 0 } });
+ expect((await approve('art')).status).toBe(200);
+ expect((await request(app).post(`${base}/production-review/prepare`).send({})).status).toBe(200);
+ expect((await approve('storyboard')).status).toBe(200);
+ expect((await requestChanges('storyboard', 'shot: Chorus', 'Keep the doorway silhouette readable', 'comment')).status).toBe(200);
+ expect((await requestChanges('proof', 'frame: 0:04', 'The prop lands a beat late')).status).toBe(200);
+ const { buildCodeTimeline } = await import('../services/musicVideo/codeTimeline.js');
+ author.sections = buildCodeTimeline(await store.getProject(project.id)).sections.map(section => ({ id: section.id,
+ source: "function render(ctx, env) { ctx.fillStyle = '#203040'; ctx.fillRect(0, 0, env.width, env.height); }" }));
+
+ const revised = await revise('proof');
+
+ expect(revised.status).toBe(200);
+ expect(author.calls).toBe(1);
+ expect(author.prompts[0]).toContain('UNRESOLVED REVIEW FEEDBACK');
+ expect(author.prompts[0]).toContain('proof / frame: 0:04 / request-changes: The prop lands a beat late');
+ expect(author.prompts[0]).toContain('storyboard / shot: Chorus / comment: Keep the doorway silhouette readable');
+ expect(revised.body.project.composition.documentDraft.source.kind).toBe('generated');
+ expect(revised.body.project.productionReview.feedback.every(item => !item.resolvedAt)).toBe(true);
+ });
+
+ it('explains instead of revising a footage-assembled proof', async () => {
+ await store.updateProject(project.id, { composition: { mode: 'composed' } });
+ expect((await requestChanges('proof', 'frame: 0:04', 'The prop lands a beat late')).status).toBe(200);
+ const refused = await revise('proof');
+ expect(refused.status).toBe(409);
+ expect(refused.body.code).toBe('MUSIC_VIDEO_REVISION_UNSUPPORTED');
+ expect(author.calls).toBe(0);
+ });
+});
diff --git a/server/services/musicVideo/planner.js b/server/services/musicVideo/planner.js
index 9bc29b81be..efec57a3ce 100644
--- a/server/services/musicVideo/planner.js
+++ b/server/services/musicVideo/planner.js
@@ -44,6 +44,7 @@ import { runPromptThroughProvider } from '../promptRunner.js';
import { effortArg, recordLlmRoute, resolveMusicVideoLlm } from './llmRoute.js';
import { directShots, planShots, resolveClipCapacitySec, validSections } from './shotPlan.js';
import { getProject, addProjectScenes, mutateProjectRecord } from './projects.js';
+import { productionFeedbackContext } from './productionReview.js';
const SCENE_LABEL_MAX = 120;
const SCENE_TEXT_MAX = 2000;
@@ -163,8 +164,11 @@ export function buildScenePlanPrompt(project, shots) {
if (times) parts.push(`${kind} (seconds): ${times}`);
}
if (s.shotMode === 'performance') parts.push(PERFORMANCE_FRAME);
+ if (s.current?.framePrompt) parts.push(`current frame: ${quote(s.current.framePrompt, PROMPT_GUIDANCE_MAX)}`);
+ if (s.current?.prompt) parts.push(`current motion: ${quote(s.current.prompt, PROMPT_GUIDANCE_MAX)}`);
return parts.join('; ');
}).join('\n');
+ const revising = shots.some((s) => s.current);
return `You are directing a music video for "${project.name}".
${conceptLine}
@@ -174,6 +178,7 @@ ${musicVideoDirectionContext(direction)}
${briefLines}
${guidanceLine}
${motionPlan}
+${productionFeedbackContext(project)}
The song has been cut into these shots (index; musical section and the shot's position inside it; duration; normalized 0..1 section energy — higher is louder/more intense; the lyric lines sung during the shot, or "instrumental"; optional director intent${hasDelivery ? '; optional delivery directions from the lyric sheet' : ''}):
${shotLines}
@@ -184,7 +189,7 @@ For EACH shot above, propose a timed composition for its assigned medium (code-a
- Shots in the same section are one edited sequence: keep subject and setting continuous, but vary framing (wide / medium / close), angle, or action from shot to shot so consecutive shots cut rather than repeat.
- The OPENING HOOK shot must grab attention immediately.
- In each motion prompt, name absolute start/end times and the supplied musical anchors for subject action, prop transformation, camera framing/movement and any permitted graphic typography. Follow the saved energy target; this proposal still needs human review. Repeated choruses must develop the action, scale or staging instead of replaying the same pose. Include anticipation, payoff and recovery; motivated holds and long takes are valid. Do not replace choreography with continuous camera drift, geometry presence, subtitles alone or an arbitrary fast-cut quota.
-- If an energy target or required audio timing is absent, identify it as a director decision to review rather than inventing analysis or claiming the plan is approved.
+${revising ? '- These shots already exist. Revise each one\'s current frame and motion to address the unresolved review feedback, keeping what the feedback does not ask to change.\n' : ''}- If an energy target or required audio timing is absent, identify it as a director decision to review rather than inventing analysis or claiming the plan is approved.
${hasLyrics ? '- Let the lyric lines inform the imagery and emotion of their shot (interpret, do not illustrate word-for-word). Never render the lyrics as on-screen text in footage; assigned card layers use their explicit card text.\n' : ''}${hasDelivery ? '- Follow the delivery directions: spoken or whispered lines play as intimate close-ups; shouts land as hard-hitting cuts or impacts; a silence or stop is a held, frozen or cut-to-black beat.\n' : ''}- Keep the assigned layer and shot mode: performance uses source-audio lip-sync and a frontal medium close-up with the mouth visible; cutaways show narrative action without lip-sync; cards are graphic beats.\n- Honor any director intent given for a shot. Instrumental shots carry no singing or lip-sync.
Respond with ONLY a JSON array, one object per shot, in shot-index order (replace every <…> with real content; do NOT output the literal angle-bracket text), no other text:
@@ -315,15 +320,7 @@ export async function planProject(id, { seedPrompts = true, providerId, model, e
// One shot list drives both the seeded scenes and the prompt, so prompt
// indices agree 1:1 with `sceneInputs`.
- const { shots: tiledShots, pacing } = planShots(sections, {
- downbeats: project.audioAnalysis?.downbeats,
- beats: project.audioAnalysis?.beats,
- lyricCues: project.lyricCues,
- phrases: project.phrases,
- pacing: project.pacing,
- clipCapacitySec: resolveClipCapacitySec(project.videoSettings),
- });
- const shots = directShots(tiledShots, project);
+ const { shots, pacing } = directedShotPlan(project, sections);
const sceneInputs = sceneInputsFromShots(shots);
let promptsSeeded = false;
@@ -366,6 +363,75 @@ export async function planProject(id, { seedPrompts = true, providerId, model, e
return { project: updated, scenesAdded: scenes.length, promptsSeeded, promptsSkippedReason, pacing, llmRoute };
}
+/** The directed shot list for a project's analyzed sections. Deterministic for a given analysis. */
+function directedShotPlan(project, sections) {
+ const { shots, pacing } = planShots(sections, {
+ downbeats: project.audioAnalysis?.downbeats,
+ beats: project.audioAnalysis?.beats,
+ lyricCues: project.lyricCues,
+ phrases: project.phrases,
+ pacing: project.pacing,
+ clipCapacitySec: resolveClipCapacitySec(project.videoSettings),
+ });
+ return { shots: directShots(shots, project), pacing };
+}
+
+const sameSpan = (a, b) => Number.isFinite(a) && Number.isFinite(b) && Math.abs(a - b) < 0.01;
+const TIMECODE = /(\d{1,2}):(\d{2}(?:\.\d+)?)|(\d+(?:\.\d+)?)s\b/g;
+
+/**
+ * Board scenes a review note addresses: its target names the shot label,
+ * section or scene id, or a time inside the shot. A note that names no shot
+ * addresses every shot, so general feedback is never dropped.
+ */
+function feedbackSceneIds(scenes, feedback) {
+ const ids = new Set();
+ for (const item of feedback) {
+ const target = String(item.target || '').toLowerCase();
+ const times = [...target.matchAll(TIMECODE)].map((m) => (m[3] != null ? Number(m[3]) : Number(m[1]) * 60 + Number(m[2])));
+ const named = scenes.filter((scene) => [scene.sceneId, scene.label, scene.sectionLabel]
+ .some((name) => typeof name === 'string' && name.trim().length >= 3 && target.includes(name.trim().toLowerCase()))
+ || times.some((t) => t >= scene.startSec && t < scene.endSec));
+ if (!named.length) return scenes.map((scene) => scene.sceneId);
+ for (const scene of named) ids.add(scene.sceneId);
+ }
+ return scenes.filter((scene) => ids.has(scene.sceneId)).map((scene) => scene.sceneId);
+}
+
+/**
+ * Propose revised frame/motion prompts for the Board shots that unresolved
+ * review feedback names, without re-tiling the board. Each shot keeps its
+ * span, takes and selected media; the caller persists the returned fields.
+ * A shot whose span still matches the deterministic plan keeps its assigned
+ * set, look and layer direction. Throws when no usable proposal comes back.
+ * @returns {Promise<Map<string, { framePrompt?: string, prompt?: string }>>} revised fields by sceneId
+ */
+export async function proposeShotRevisions(project, feedback, { providerId, model, effort } = {}) {
+ const scenes = (project.scenes || []).filter((scene) => Number.isFinite(scene.startSec) && scene.endSec > scene.startSec);
+ if (!scenes.length) throw new ServerError('Plan timed Board shots before revising them from feedback', { status: 409, code: 'NO_SCENES' });
+ const targets = new Set(feedbackSceneIds(scenes, feedback));
+ const sections = validSections(project.audioAnalysis?.sections);
+ const planned = sections.length ? directedShotPlan(project, sections).shots : [];
+ const shots = scenes.filter((scene) => targets.has(scene.sceneId)).map((scene, index) => {
+ const match = planned.find((shot) => sameSpan(shot.startSec, scene.startSec) && sameSpan(shot.endSec, scene.endSec)
+ && (shot.visualLayer || null) === (scene.visualLayer || null));
+ const base = match || { sectionLabel: scene.sectionLabel || scene.label, sectionIndex: scene.sectionIndex ?? index,
+ shotIndex: 0, shotCount: 1, startSec: scene.startSec, endSec: scene.endSec };
+ return { ...base, lyricText: scene.lyricText ?? base.lyricText, visualIntent: scene.visualIntent ?? base.visualIntent,
+ sceneId: scene.sceneId, current: { framePrompt: scene.framePrompt, prompt: scene.prompt } };
+ });
+ const { seeded, reason } = await tryProposeScenePrompts(project, shots, { providerId, model, effort });
+ if (!seeded) throw new ServerError(`No revised shots came back (${reason}). Edit the shots by hand or retry.`, { status: 422, code: 'SHOT_REVISION_FAILED' });
+ const updates = new Map();
+ for (const [index, fields] of seeded) {
+ const shot = shots[index];
+ updates.set(shot.sceneId, shot.visualLayer ? directedPrompts(shot, fields) : {
+ ...(fields.framePrompt ? { framePrompt: fields.framePrompt } : {}), ...(fields.prompt ? { prompt: fields.prompt } : {}),
+ });
+ }
+ return updates;
+}
+
async function persistPlan(id, sceneInputs, { hasCards, replace }) {
if (!hasCards && !replace) return addProjectScenes(id, sceneInputs);
const { addScenes, replaceScenes } = await import('./projectsLogic.js');
diff --git a/server/services/musicVideo/planner.test.js b/server/services/musicVideo/planner.test.js
index 5481ede61b..5c734d3dc6 100644
--- a/server/services/musicVideo/planner.test.js
+++ b/server/services/musicVideo/planner.test.js
@@ -17,6 +17,7 @@ import {
validSections,
buildScenePlanPrompt,
planProject,
+ proposeShotRevisions,
} from './planner.js';
import { planShots } from './shotPlan.js';
@@ -698,3 +699,53 @@ describe('directed planner', () => {
expect(inputs.every((s) => s.shotMode === undefined && s.visualLayer === undefined && s.framePrompt === undefined)).toBe(true);
});
});
+
+describe('review feedback in shot planning', () => {
+ const feedback = (target, text, extra = {}) => ({ id: `fb-${target}`, stage: 'storyboard', target, text, decision: 'request-changes', basis: 'b', ...extra });
+
+ it('carries unresolved review feedback into the plan prompt and drops resolved feedback', () => {
+ const project = makeProject({ productionReview: { feedback: [
+ feedback('shot: Drop', 'Let the figure leap on the drop instead of walking'),
+ feedback('shot: Intro', 'Already handled', { resolvedAt: '2026-01-01T00:00:00.000Z' }),
+ ] } });
+ const { shots } = planShots(SECTIONS, { beats: BEATS, downbeats: DOWNBEATS });
+ const prompt = buildScenePlanPrompt(project, shots);
+ expect(prompt).toContain('UNRESOLVED REVIEW FEEDBACK');
+ expect(prompt).toContain('storyboard / shot: Drop / request-changes: Let the figure leap on the drop instead of walking');
+ expect(prompt).not.toContain('Already handled');
+ });
+
+ it('revises only the named shots in place, showing the model their current prompts', async () => {
+ const scenes = [
+ { sceneId: 'scene-intro', label: 'Intro', startSec: 0, endSec: 10, framePrompt: 'quiet alley', prompt: 'slow push' },
+ { sceneId: 'scene-drop', label: 'Drop', startSec: 10, endSec: 18, framePrompt: 'crowded rooftop', prompt: 'figure walks' },
+ { sceneId: 'scene-outro', label: 'Outro', startSec: 18, endSec: 30, framePrompt: 'dawn street', prompt: 'static' },
+ ];
+ const requests = [feedback('frame: 12.5s', 'Let the figure leap on the drop')];
+ const project = makeProject({ scenes, productionReview: { feedback: requests } });
+ resolveProviderAndModel.mockResolvedValue({ provider: { id: 'p1', type: 'api' }, selectedModel: 'gpt' });
+ runPromptThroughProvider.mockResolvedValue({ text: JSON.stringify([{ index: 0, framePrompt: 'rooftop at the peak', prompt: 'figure leaps on the downbeat' }]) });
+
+ const updates = await proposeShotRevisions(project, requests);
+
+ const prompt = runPromptThroughProvider.mock.calls[0][0].prompt;
+ expect(prompt).toContain('current frame: crowded rooftop; current motion: figure walks');
+ expect(prompt).not.toContain('quiet alley');
+ expect(prompt).toContain('Let the figure leap on the drop');
+ expect([...updates]).toEqual([['scene-drop', { framePrompt: 'rooftop at the peak', prompt: 'figure leaps on the downbeat' }]]);
+ });
+
+ it('treats a request that names no shot as addressing every shot, and fails loudly when nothing usable returns', async () => {
+ const scenes = [
+ { sceneId: 'scene-a', label: 'Intro', startSec: 0, endSec: 10 },
+ { sceneId: 'scene-b', label: 'Drop', startSec: 10, endSec: 18 },
+ ];
+ const requests = [feedback('overall pacing', 'Everything feels too slow')];
+ resolveProviderAndModel.mockResolvedValue({ provider: { id: 'p1', type: 'api' }, selectedModel: 'gpt' });
+ runPromptThroughProvider.mockResolvedValue({ text: 'no json here' });
+ await expect(proposeShotRevisions(makeProject({ scenes }), requests)).rejects.toMatchObject({ status: 422, code: 'SHOT_REVISION_FAILED' });
+ const prompt = runPromptThroughProvider.mock.calls[0][0].prompt;
+ expect(prompt).toContain('"Intro"');
+ expect(prompt).toContain('"Drop"');
+ });
+});
diff --git a/server/services/musicVideo/productionReviewService.js b/server/services/musicVideo/productionReviewService.js
index da230c55be..57af85859f 100644
--- a/server/services/musicVideo/productionReviewService.js
+++ b/server/services/musicVideo/productionReviewService.js
@@ -297,3 +297,57 @@ export async function closeProductionFeedback(id, input) {
const { project } = await mutateProjectRecord(id, current => ({ project: resolveProductionFeedback(current, input) }));
return changed(project);
}
+
+const openChangeRequests = (project, stage) => (project.productionReview?.feedback || [])
+ .filter(f => f.stage === stage && f.decision === 'request-changes' && !f.resolvedAt);
+
+/**
+ * One explicit click acts on a stage's open change requests: art regenerates
+ * the Cast & Sets direction, the storyboard re-plans the shots the notes name
+ * in place, and the proof re-authors its code or generated composition. The
+ * result lands on a new basis; the requests stay open until a reviewer
+ * resolves them, so approval remains blocked until then.
+ */
+export async function reviseProductionFromFeedback(id, { stage, ...route }) {
+ const project = await requireProject(id);
+ const requests = openChangeRequests(project, stage);
+ if (!requests.length) throw new ServerError('There are no open change requests for this stage.', { status: 409, code: 'MUSIC_VIDEO_NO_FEEDBACK' });
+ const refuse = message => new ServerError(message, { status: 409, code: 'MUSIC_VIDEO_REVISION_UNSUPPORTED' });
+ if (stage === 'art') {
+ if (!project.castAndSets?.direction) throw refuse('This art direction has no Cast & Sets direction to regenerate. Edit the guide, then resolve each request.');
+ const { regenerateCastAndSets } = await import('./castAndSetsService.js');
+ const { project: next } = await regenerateCastAndSets(id, { notes: [], ...route });
+ return { ...changed(next), revision: { stage } };
+ }
+ if (stage === 'storyboard') {
+ if (project.productionReview?.draft?.storyboardSource === 'document') throw refuse('Document shots come from the authored source. Revise it, reimport its shot manifest, then resolve each request.');
+ const { proposeShotRevisions } = await import('./planner.js');
+ const basis = productionReviewBasis(project).storyboard;
+ const updates = await proposeShotRevisions(project, requests, route);
+ const { project: next } = await mutateProjectRecord(id, current => {
+ if (productionReviewBasis(current).storyboard !== basis) throw new ServerError('The storyboard changed while it was being revised. Review it and try again.', { status: 409, code: 'MUSIC_VIDEO_REVIEW_STALE' });
+ const scenes = current.scenes.map(scene => updates.has(scene.sceneId) ? { ...scene, ...updates.get(scene.sceneId) } : scene);
+ const draft = current.productionReview?.draft;
+ const storyboard = draft?.storyboard?.map(shot => {
+ const fields = updates.get(shot.sceneId);
+ return fields ? { ...shot, ...(fields.prompt ? { action: fields.prompt } : {}), ...(fields.framePrompt ? { staging: fields.framePrompt } : {}) } : shot;
+ });
+ return { project: { ...current, scenes, updatedAt: new Date().toISOString(),
+ ...(storyboard ? { productionReview: { ...current.productionReview, draft: { ...draft, storyboard } } } : {}) } };
+ });
+ return { ...changed(next), revision: { stage, sceneIds: [...updates.keys()] } };
+ }
+ const mode = project.composition?.mode;
+ if (mode === 'code') {
+ const { generateMusicVideoCode } = await import('./codeGeneration.js');
+ await generateMusicVideoCode(id, route);
+ } else if (mode === 'document') {
+ const kind = project.composition?.document?.source?.kind;
+ if (kind && !['generated', 'template'].includes(kind)) throw refuse('This composition was imported from its own source. Revise that source and reimport it, then resolve each request.');
+ const { generateMixedMediaDocument } = await import('./documentGeneration.js');
+ await generateMixedMediaDocument(id, route);
+ } else {
+ throw refuse('This proof is assembled from Board footage. Revise the affected storyboard shots or takes, then render a new proof.');
+ }
+ return { ...changed(await requireProject(id)), revision: { stage } };
+}