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: revert a changed Music Video input to its approved value (#10241)

Adam Eivyee5d5cf87235
diff --git a/client/src/components/musicVideo/CastAndSetsCheckin.jsx b/client/src/components/musicVideo/CastAndSetsCheckin.jsx
index e9cd50f94e..1d7f075f8f 100644
--- a/client/src/components/musicVideo/CastAndSetsCheckin.jsx
+++ b/client/src/components/musicVideo/CastAndSetsCheckin.jsx
@@ -37,7 +37,7 @@ function statusLine(stage) {
* concept, style, subjects or song changed since (`stale`, from the server's
* readiness) says what changed and offers Keep approved beside Rebuild (#10141).
*/
-export default function CastAndSetsCheckin({ project, stale = null, busy, onOpenSheet, onApprove, onRegenerate, onEditDirection, onResume, onRebuild, onReconfirm, onSkip }) {
+export default function CastAndSetsCheckin({ project, stale = null, busy, onOpenSheet, onApprove, onRegenerate, onEditDirection, onResume, onRebuild, onReconfirm, onRevert, onSkip }) {
const stage = project.castAndSets;
if (!stage) return null;
const working = WORKING.has(stage.status) && !stage.interrupted;
@@ -60,6 +60,16 @@ export default function CastAndSetsCheckin({ project, stale = null, busy, onOpen
{staleText} Keep the sheet approved as it is, or rebuild it from the current inputs.
</p>
)}
+ {staleText && onRevert && stale?.revertible?.length > 0 && (
+ <div className="flex flex-wrap gap-2">
+ {stale.revertible.map((field) => (
+ <button key={field} type="button" disabled={busy} onClick={() => onRevert(field)} title="Put this back to the value you approved"
+ className={`${buttonClass} border border-port-border`}>
+ <RotateCcw size={14} aria-hidden="true" /> Revert {field}
+ </button>
+ ))}
+ </div>
+ )}
<CastAndSetsReferenceProgress stage={stage} />
<div className="flex flex-wrap gap-2">
{sheet && (
diff --git a/client/src/components/musicVideo/CastAndSetsCheckin.test.jsx b/client/src/components/musicVideo/CastAndSetsCheckin.test.jsx
index 9309ac4411..3788960088 100644
--- a/client/src/components/musicVideo/CastAndSetsCheckin.test.jsx
+++ b/client/src/components/musicVideo/CastAndSetsCheckin.test.jsx
@@ -6,7 +6,7 @@ import useMusicVideoCastAndSets from '../../hooks/useMusicVideoCastAndSets';
const { listeners, api, getMediaJob } = vi.hoisted(() => ({
listeners: new Map(),
- api: { getMusicVideoProject: vi.fn(), startMusicVideoCastAndSets: vi.fn(), regenerateMusicVideoCastAndSets: vi.fn(), editMusicVideoCastAndSetsDirection: vi.fn(), resumeMusicVideoCastAndSets: vi.fn(), approveMusicVideoCastAndSets: vi.fn(), reconfirmMusicVideoCastAndSets: vi.fn(), skipMusicVideoCastAndSets: vi.fn() },
+ api: { getMusicVideoProject: vi.fn(), startMusicVideoCastAndSets: vi.fn(), regenerateMusicVideoCastAndSets: vi.fn(), editMusicVideoCastAndSetsDirection: vi.fn(), resumeMusicVideoCastAndSets: vi.fn(), approveMusicVideoCastAndSets: vi.fn(), reconfirmMusicVideoCastAndSets: vi.fn(), revertMusicVideoProductionInput: vi.fn(), skipMusicVideoCastAndSets: vi.fn() },
getMediaJob: vi.fn(),
}));
vi.mock('../../services/socket', () => ({ default: {
@@ -238,6 +238,15 @@ describe('Cast & Sets tab: undo, regenerate and guide import', () => {
expect(api.reconfirmMusicVideoCastAndSets).toHaveBeenCalledWith('example-project', { silent: true });
});
+ it('offers Revert only for changed inputs whose approved value was kept (#10241)', () => {
+ const onRevertApproval = vi.fn();
+ const stale = { approvedAt: '2026-01-01T00:00:00.000Z', changedFields: ['concept', 'song'], revertible: ['concept'] };
+ open(withStatus('approved'), { productionReadiness: { castAndSets: { approved: true, stale } }, onRevertApproval });
+ fireEvent.click(screen.getByRole('button', { name: 'Revert concept' }));
+ expect(onRevertApproval).toHaveBeenCalledWith('castAndSets', 'concept');
+ expect(screen.queryByRole('button', { name: 'Revert song' })).toBeNull();
+ });
+
it('shows no stale note or Keep approved for a current approval', () => {
open(withStatus('approved'), { productionReadiness: { castAndSets: { approved: true, stale: null } } });
expect(screen.queryByRole('button', { name: 'Keep approved' })).toBeNull();
diff --git a/client/src/components/musicVideo/StageChecklist.jsx b/client/src/components/musicVideo/StageChecklist.jsx
index 1e9f5c6e5c..97ab5038e8 100644
--- a/client/src/components/musicVideo/StageChecklist.jsx
+++ b/client/src/components/musicVideo/StageChecklist.jsx
@@ -4,9 +4,10 @@ import { ArrowRight, CheckCircle2, Circle } from 'lucide-react';
* The top of every stage tab: what this stage needs before it counts as done
* (`stageChecklist(…)` items), each open item with what is still missing and,
* where one exists, a button that scrolls to the control that settles it —
- * unless the header's next action already goes there (`headerAnchor`).
+ * unless the header's next action already goes there (`headerAnchor`). A stale
+ * approval lists a Revert button per changed input whose approved value was kept.
*/
-export default function StageChecklist({ items, onAction, headerAnchor = null }) {
+export default function StageChecklist({ items, onAction, onRevert, headerAnchor = null }) {
if (!items?.length) return null;
const done = items.filter((item) => item.done).length;
return (
@@ -32,6 +33,17 @@ export default function StageChecklist({ items, onAction, headerAnchor = null })
{item.details.map((text) => <li key={text} className="break-words">{text}</li>)}
</ul>
)}
+ {!item.done && item.revert && onRevert && (
+ <div className="mt-1 flex flex-wrap gap-1.5">
+ {item.revert.fields.map((field) => (
+ <button key={field} type="button" onClick={() => onRevert(item.revert.stage, field)}
+ title="Put this back to the value you approved"
+ className="min-h-[44px] rounded border border-port-border px-2 py-1 text-xs text-port-accent sm:min-h-0">
+ Revert {field}
+ </button>
+ ))}
+ </div>
+ )}
</div>
{!item.done && item.action && onAction && item.action.anchor !== headerAnchor && (
<button
diff --git a/client/src/components/musicVideo/StageChecklist.test.jsx b/client/src/components/musicVideo/StageChecklist.test.jsx
new file mode 100644
index 0000000000..06a0cea04a
--- /dev/null
+++ b/client/src/components/musicVideo/StageChecklist.test.jsx
@@ -0,0 +1,23 @@
+import { fireEvent, render, screen } from '@testing-library/react';
+import { describe, expect, it, vi } from 'vitest';
+import StageChecklist from './StageChecklist.jsx';
+import { stageChecklist } from '../../lib/musicVideoStages.js';
+
+describe('StageChecklist Revert buttons (#10241)', () => {
+ const project = { id: 'example-project', scenes: [] };
+ const readiness = (revertible) => ({ art: { approved: false, problems: [], stale: { approvedAt: null, changedFields: ['concept', 'cast'], ...(revertible ? { revertible } : {}) } } });
+ const items = (r) => stageChecklist('cast-sets', project, r).filter((i) => i.id === 'approve-art');
+
+ it('reverts a changed input by stage and field, and only those with a kept value', () => {
+ const onRevert = vi.fn();
+ render(<StageChecklist items={items(readiness(['concept']))} onRevert={onRevert} />);
+ fireEvent.click(screen.getByRole('button', { name: 'Revert concept' }));
+ expect(onRevert).toHaveBeenCalledWith('art', 'concept');
+ expect(screen.queryByRole('button', { name: 'Revert cast' })).toBeNull();
+ });
+
+ it('shows no Revert for a legacy approval without kept values', () => {
+ render(<StageChecklist items={items(readiness(null))} onRevert={vi.fn()} />);
+ expect(screen.queryByRole('button', { name: /^Revert/ })).toBeNull();
+ });
+});
diff --git a/client/src/components/musicVideo/stages/CastSetsStage.jsx b/client/src/components/musicVideo/stages/CastSetsStage.jsx
index 609fef3502..acb0f7f48b 100644
--- a/client/src/components/musicVideo/stages/CastSetsStage.jsx
+++ b/client/src/components/musicVideo/stages/CastSetsStage.jsx
@@ -21,6 +21,7 @@ export default function CastSetsStage({ board }) {
onResume={() => castSets.resume()}
onRebuild={() => castSets.start()}
onReconfirm={() => castSets.reconfirm()}
+ onRevert={board.onRevertApproval ? (field) => board.onRevertApproval('castAndSets', field) : undefined}
onSkip={board.skipCastAndSets}
/>
) : (
diff --git a/client/src/hooks/useMusicVideoProductionReview.js b/client/src/hooks/useMusicVideoProductionReview.js
index ad5e5b37b0..ba45d3dacd 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, reviseMusicVideoProductionFromFeedback } from '../services/apiMusicVideo.js';
+ cancelMusicVideoExcerptRender, importMusicVideoProductionPlanning, bindMusicVideoProductionShot, addMusicVideoProductionFeedback, resolveMusicVideoProductionFeedback, reviseMusicVideoProductionFromFeedback, revertMusicVideoProductionInput } from '../services/apiMusicVideo.js';
import useSseJobSlot from './useSseJobSlot.js';
/**
@@ -64,6 +64,7 @@ export default function useMusicVideoProductionReview({ project, replaceProject
feedback: body => call(() => addMusicVideoProductionFeedback(project.id, { ...body, basis: 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 })),
+ revert: (stage, field) => call(() => revertMusicVideoProductionInput(project.id, { stage, field }, { 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/lib/musicVideoStages.js b/client/src/lib/musicVideoStages.js
index 35960a36c6..22b384313b 100644
--- a/client/src/lib/musicVideoStages.js
+++ b/client/src/lib/musicVideoStages.js
@@ -513,6 +513,8 @@ export function stageChecklist(stageId, project, readiness = project?.production
id: `approve-${key}`, label: `${label} approved`, done: approved, stale: !!stale,
detail: approved || !readiness ? null : (stale ? `${stale} Re-approve in the editor below.` : readiness[key]?.problems?.[0] || waitingText),
action: approved ? null : { label: `Review ${label.toLowerCase()}`, anchor: APPROVAL_ANCHORS[key], stage: APPROVAL_STAGES[key] },
+ // Inputs whose approved value the server kept: each gets a Revert button.
+ revert: !approved && stale && readiness[key].stale.revertible?.length ? { stage: key, fields: readiness[key].stale.revertible } : null,
};
};
switch (stageId) {
diff --git a/client/src/pages/MusicVideo.jsx b/client/src/pages/MusicVideo.jsx
index ead7c003bc..4347a7b0fd 100644
--- a/client/src/pages/MusicVideo.jsx
+++ b/client/src/pages/MusicVideo.jsx
@@ -1027,6 +1027,7 @@ export default function MusicVideo() {
runStage,
onSelectStage: setRunStage,
productionReadiness: productionReview.readiness,
+ onRevertApproval: productionReview.revert,
locked: creativeSetupPending || styleReferencesPending || compositionSavePending > 0,
busy: { analyzing, planning, arranging, cloning },
tracks,
@@ -1461,6 +1462,7 @@ export default function MusicVideo() {
<StageChecklist
items={stageChecklist(activeStage, selected, productionReview.readiness, publish)}
onAction={(action) => goToStage(action.stage || activeStage, action.anchor, action.params)}
+ onRevert={productionReview.revert}
headerAnchor={nextAction?.kind === 'goto' ? nextAction.anchor : null}
/>
{APPROVAL_STAGE_BY_TAB[activeStage] && (
diff --git a/client/src/services/apiMusicVideo.js b/client/src/services/apiMusicVideo.js
index 2f3aa48d82..c93308365c 100644
--- a/client/src/services/apiMusicVideo.js
+++ b/client/src/services/apiMusicVideo.js
@@ -485,6 +485,8 @@ 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 });
+// Write one changed input of a stale approval back to its approved value (#10241). `stage` is art | storyboard | proof | castAndSets.
+export const revertMusicVideoProductionInput = (id, body, options = {}) => request(`/music-video/${encodeURIComponent(id)}/production-review/revert`, { 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.
diff --git a/server/lib/musicVideoValidation.js b/server/lib/musicVideoValidation.js
index 69403bf69f..a294d19420 100644
--- a/server/lib/musicVideoValidation.js
+++ b/server/lib/musicVideoValidation.js
@@ -1343,6 +1343,10 @@ export const musicVideoProductionFeedbackSchema = z.object({
export const musicVideoProductionReviseSchema = musicVideoCastAndSetsStartSchema.extend({
stage: z.enum(['art', 'storyboard', 'proof']),
}).strict();
+// The input label a stale approval names (`concept`, `scene 3 prompt`, …) — the server finds its stored value.
+export const musicVideoProductionRevertSchema = z.object({
+ stage: z.enum(['art', 'storyboard', 'proof', 'castAndSets']), field: z.string().trim().min(1).max(100),
+}).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 70dc1b1015..776e21bb50 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, musicVideoProductionReviseSchema } from '../lib/musicVideoValidation.js';
+import { musicVideoProjectListQuerySchema, musicVideoProductionDraftSchema, musicVideoProductionApprovalSchema, musicVideoProductionProofSchema, musicVideoProductionImportSchema, musicVideoProductionFeedbackSchema, musicVideoProductionFeedbackResolutionSchema, musicVideoProductionReviseSchema, musicVideoProductionRevertSchema } from '../lib/musicVideoValidation.js';
import { productionReadiness } from '../services/musicVideo/productionReview.js';
-import { getProductionReview, saveProductionDraft, prepareProductionReview, approveProductionReview, renderProductionProof, requireProductionReviewer, importProductionPlanning, bindProductionShot, addProductionFeedback, closeProductionFeedback, reviseProductionFromFeedback } from '../services/musicVideo/productionReviewService.js';
+import { getProductionReview, saveProductionDraft, prepareProductionReview, approveProductionReview, renderProductionProof, requireProductionReviewer, importProductionPlanning, bindProductionShot, addProductionFeedback, closeProductionFeedback, reviseProductionFromFeedback, revertProductionInput } from '../services/musicVideo/productionReviewService.js';
import { asyncHandler, ServerError } from '../lib/errorHandler.js';
import {
validateRequest,
@@ -608,6 +608,9 @@ router.post('/:id/production-review/feedback/resolve', asyncHandler(async (req,
router.post('/:id/production-review/revise', asyncHandler(async (req, res) => {
res.json(await reviseProductionFromFeedback(req.params.id, validateRequest(musicVideoProductionReviseSchema, req.body ?? {})));
}));
+router.post('/:id/production-review/revert', asyncHandler(async (req, res) => {
+ res.json(await revertProductionInput(req.params.id, validateRequest(musicVideoProductionRevertSchema, 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 a858fb2df7..9459eba559 100644
--- a/server/routes/musicVideoProductionReview.test.js
+++ b/server/routes/musicVideoProductionReview.test.js
@@ -483,3 +483,50 @@ describe('revising from review feedback', () => {
expect(author.calls).toBe(0);
});
});
+
+describe('reverting a changed input to its approved value (#10241)', () => {
+ const revert = body => request(app).post(`${base}/production-review/revert`).send(body);
+
+ it('restores the concept and a scene prompt, making the approvals current again without re-approval', async () => {
+ await store.updateProject(project.id, { concept: { prompt: 'Approved idea' } });
+ expect((await approve('art')).status).toBe(200);
+ expect((await approve('storyboard')).status).toBe(200);
+ const sceneId = (await store.getProject(project.id)).scenes[0].sceneId;
+ await store.updateProject(project.id, { concept: { prompt: 'Drifted idea' } });
+ await store.mutateProjectRecord(project.id, current => ({ project: { ...current,
+ scenes: current.scenes.map(s => ({ ...s, prompt: 'A different prompt' })) } }));
+ const stale = (await read()).body.readiness;
+ expect(stale.art.approved).toBe(false);
+ expect(stale.storyboard.stale).toMatchObject({ changedFields: ['concept', 'scene 1 prompt'], revertible: ['concept', 'scene 1 prompt'] });
+
+ expect((await revert({ stage: 'storyboard', field: 'scene 1 prompt' })).status).toBe(200);
+ const done = await revert({ stage: 'art', field: 'concept' });
+ expect(done.status).toBe(200);
+ expect(done.body.project.concept).toEqual({ prompt: 'Approved idea' });
+ expect(done.body.project.scenes.find(s => s.sceneId === sceneId).prompt).toBe('A paper figure opens a painted doorway.');
+ expect(done.body.readiness.art.approved).toBe(true);
+ expect(done.body.readiness.storyboard.approved).toBe(true);
+ });
+
+ it('refuses with 409 when there is no stored value, nothing changed, or the field is invalid', async () => {
+ expect((await approve('art')).status).toBe(200);
+ expect((await revert({ stage: 'art', field: 'concept' })).body.code).toBe('MUSIC_VIDEO_REVERT_UNAVAILABLE');
+ await store.updateProject(project.id, { concept: { prompt: 'Drifted idea' } });
+ const noSnapshot = await store.mutateProjectRecord(project.id, current => ({ project: { ...current, productionReview: { ...current.productionReview,
+ approvals: { art: { ...current.productionReview.approvals.art, values: undefined } } } } }));
+ expect(noSnapshot.project.productionReview.approvals.art.values).toBeUndefined();
+ const legacy = await revert({ stage: 'art', field: 'concept' });
+ expect(legacy.status).toBe(409);
+ expect(legacy.body.code).toBe('MUSIC_VIDEO_REVERT_UNAVAILABLE');
+ expect((await store.getProject(project.id)).concept).toEqual({ prompt: 'Drifted idea' });
+ expect((await revert({ stage: 'art', field: '' })).status).toBe(400);
+ expect((await revert({ stage: 'takes', field: 'concept' })).status).toBe(400);
+ });
+
+ it('keeps no value for an input over the 8 KB cap', async () => {
+ const big = 'x'.repeat(9000);
+ await store.updateProject(project.id, { concept: { prompt: big } });
+ expect((await approve('art')).status).toBe(200);
+ expect((await store.getProject(project.id)).productionReview.approvals.art.values).not.toHaveProperty('concept');
+ });
+});
diff --git a/server/services/musicVideo/castAndSets.js b/server/services/musicVideo/castAndSets.js
index 2ad62320fe..4fb52264fa 100644
--- a/server/services/musicVideo/castAndSets.js
+++ b/server/services/musicVideo/castAndSets.js
@@ -21,6 +21,7 @@
* artifactId, artifactVersion, notesApplied,
* createdAt, updatedAt, approvedAt,
* approvedInputs, // labeled input hashes the approval rests on (productionReview.js); absent on legacy approvals
+ * approvedValues, // capped approved values of the revertible inputs, keyed like approvedInputs; absent = not revertible
* }
*
* Status: `directing` → `imaging` → `assembling` → `review` → `approved`, or
@@ -128,6 +129,7 @@ export function reviseCastAndSetsOnProject(project, { processId, notesApplied =
notesApplied: notesApplied.map((n) => ({ id: n.id || null, target: n.target || null, text: trimTo(n.text, 2000) })),
approvedAt: null,
approvedInputs: null,
+ approvedValues: null,
}, now);
}
@@ -257,10 +259,10 @@ export function setCastAndSetsStatus(project, status, { reason = null, error = n
* re-stamps `approvedInputs` without re-applying the sheet, so the director's
* later concept/style edits stand. Returns `{ project, stage }`.
*/
-export function reconfirmCastAndSetsOnProject(project, approvedInputs, now = new Date().toISOString()) {
+export function reconfirmCastAndSetsOnProject(project, approvedInputs, approvedValues = null, now = new Date().toISOString()) {
const stage = requireStage(project);
if (stage.status !== 'approved') throw stageError(409, 'CAST_SETS_NOT_APPROVED', `The Cast & Sets check-in is ${stage.status}, not approved`);
- return write(project, { ...stage, approvedInputs, approvedAt: now }, now);
+ return write(project, { ...stage, approvedInputs, approvedValues, approvedAt: now }, now);
}
/** Refuse an approval that has nothing to approve. */
diff --git a/server/services/musicVideo/castAndSetsService.js b/server/services/musicVideo/castAndSetsService.js
index 3f9a6aa987..f43d257335 100644
--- a/server/services/musicVideo/castAndSetsService.js
+++ b/server/services/musicVideo/castAndSetsService.js
@@ -1,5 +1,5 @@
import { musicVideoAllowsMedia, assertMusicVideoMediaSelections } from '../../lib/musicVideoMediaPolicy.js';
-import { castAndSetsApprovalInputs, productionFeedbackContext, seedArtDraft } from './productionReview.js';
+import { castAndSetsApprovalInputs, castAndSetsApprovalValues, productionFeedbackContext, seedArtDraft } from './productionReview.js';
import { withMusicVideoStyle } from './styleReferences.js';
/**
* Music Video — Cast & Sets check-in orchestrator.
@@ -549,7 +549,7 @@ function applyApproval(project, now) {
}
// Record what the approval rests on, so a later concept/style/subject/song
// edit can be named as "changed since" (#10141).
- return setCastAndSetsStatus(next, 'approved', { extra: { approvedInputs: castAndSetsApprovalInputs(next) } }, now);
+ return setCastAndSetsStatus(next, 'approved', { extra: { approvedInputs: castAndSetsApprovalInputs(next), approvedValues: castAndSetsApprovalValues(next) } }, now);
}
// Settle the stage and re-base a production run waiting on it, in ONE write,
@@ -579,7 +579,7 @@ export async function approveCastAndSets(projectId) {
export async function reconfirmCastAndSets(projectId) {
await requireProject(projectId);
const now = new Date().toISOString();
- const out = await mutateProjectRecord(projectId, (current) => reconfirmCastAndSetsOnProject(current, castAndSetsApprovalInputs(current), now));
+ const out = await mutateProjectRecord(projectId, (current) => reconfirmCastAndSetsOnProject(current, castAndSetsApprovalInputs(current), castAndSetsApprovalValues(current), now));
console.log(`✅ Music Video Cast & Sets ${short(projectId)} kept approved on current inputs`);
publish(projectId, out.project);
return { project: out.project, stage: presentCastAndSets(out.stage, PROCESS_ID) };
diff --git a/server/services/musicVideo/productionReview.js b/server/services/musicVideo/productionReview.js
index da87e6749c..9ed54866d6 100644
--- a/server/services/musicVideo/productionReview.js
+++ b/server/services/musicVideo/productionReview.js
@@ -116,13 +116,60 @@ function productionApprovalInputs(project) {
const changedInputs = (before, now) => Object.keys(now).filter(k => before[k] !== now[k])
.concat(Object.keys(before).filter(k => !(k in now)));
-/** `{ approvedAt, changedFields }` when a stage was approved on inputs that have since moved; null otherwise. */
+// Approved VALUES for the small text inputs a director edits by hand, stored
+// beside the hashes so a changed input can be reverted (#10241). Anything over
+// the cap, and anything that is not text (media, takes, the song), keeps only
+// its hash and so is never revertible. Absent from the record = not revertible.
+const MAX_SNAPSHOT_CHARS = 8 * 1024;
+const snapshotValue = v => {
+ const json = JSON.stringify(v);
+ return json !== undefined && json.length <= MAX_SNAPSHOT_CHARS ? JSON.parse(json) : undefined;
+};
+const snapshotAll = entries => Object.fromEntries(Object.entries(entries)
+ .map(([label, v]) => [label, snapshotValue(v)]).filter(([, v]) => v !== undefined));
+const DRAFT_FIELD_LABELS = { cast: 'cast', environments: 'environments', 'visual language': 'visualLanguage',
+ 'motion language': 'motionLanguage', 'implementation plan': 'implementationPlan' };
+const SCENE_PROMPT_LABEL = /^scene \d+ prompt$/;
+const SCENE_PROMPT_KEYS = ['visualIntent', 'prompt', 'framePrompt'];
+
+/** The approved values of a production stage's revertible inputs, keyed by the same labels as its hashes. */
+function productionApprovalValues(project, stage) {
+ const draft = project.productionReview?.draft || {};
+ const entries = { concept: project.concept };
+ for (const [label, key] of Object.entries(DRAFT_FIELD_LABELS)) entries[label] = draft[key];
+ if (stage !== 'art') {
+ for (const [i, s] of (project.scenes || []).entries()) {
+ entries[`scene ${i + 1} prompt`] = { sceneId: s.sceneId, visualIntent: s.visualIntent, prompt: s.prompt, framePrompt: s.framePrompt };
+ }
+ }
+ return snapshotAll(entries);
+}
+
+const CAST_SETS_CONCEPT_STYLE_KEYS = ['style', 'universeStyle', 'moodBoardStyle'];
+const CAST_SETS_SPEC_STYLE_KEYS = ['palette', 'typography', 'cameraRules', 'moodBoardId'];
+const objectConcept = project => project.concept && typeof project.concept === 'object' ? project.concept : {};
+const pick = (obj, keys) => Object.fromEntries(keys.filter(k => obj?.[k] !== undefined).map(k => [k, obj[k]]));
+
+/** The approved values behind a Cast & Sets approval's `concept`, `style` and `subjects` hashes. */
+export function castAndSetsApprovalValues(project) {
+ const { subjects, style, universeStyle, moodBoardStyle, ...concept } = objectConcept(project);
+ return snapshotAll({ concept, subjects: subjects ?? [],
+ style: { ...pick(objectConcept(project), CAST_SETS_CONCEPT_STYLE_KEYS), ...pick(project.visualSpec, CAST_SETS_SPEC_STYLE_KEYS), styleReferences: project.styleReferences ?? null } });
+}
+
+const revertibleOf = (changedFields, values) => changedFields.filter(f => values && f in values);
+const withRevertible = (stale, values) => {
+ const revertible = revertibleOf(stale.changedFields, values);
+ return revertible.length ? { ...stale, revertible } : stale;
+};
+
+/** `{ approvedAt, changedFields, revertible? }` when a stage was approved on inputs that have since moved; null otherwise. */
function staleApproval(project, stage, current, inputs) {
const approval = project.productionReview?.approvals?.[stage];
if (!approval || approval.basis === current) return null;
const before = approval.inputs;
const changedFields = before ? changedInputs(before, inputs[stage]) : [];
- return { approvedAt: approval.approvedAt || null, changedFields: changedFields.length ? changedFields : (before ? ['proof render'] : []) };
+ return withRevertible({ approvedAt: approval.approvedAt || null, changedFields: changedFields.length ? changedFields : (before ? ['proof render'] : []) }, approval.values);
}
/**
@@ -155,7 +202,7 @@ function castAndSetsApproval(project) {
const approved = stage?.status === 'approved';
if (!approved || !stage.approvedInputs) return { approved, stale: null };
const changedFields = changedInputs(stage.approvedInputs, castAndSetsApprovalInputs(project));
- return { approved, stale: changedFields.length ? { approvedAt: stage.approvedAt || null, changedFields } : null };
+ return { approved, stale: changedFields.length ? withRevertible({ approvedAt: stage.approvedAt || null, changedFields }, stage.approvedValues) : null };
}
export function productionReadiness(project) {
@@ -237,6 +284,56 @@ export function productionReadiness(project) {
readyForProduction: proofApproved };
}
+const refuseRevert = (message, code) => new ServerError(message, { status: 409, code });
+
+function restoreScenePrompt(project, value) {
+ if (!project.scenes?.some(s => s.sceneId === value.sceneId)) throw refuseRevert('That scene no longer exists, so its prompt cannot be restored.', 'MUSIC_VIDEO_REVERT_UNAVAILABLE');
+ return { ...project, scenes: project.scenes.map(s => s.sceneId === value.sceneId ? { ...s, ...Object.fromEntries(SCENE_PROMPT_KEYS.map(k => [k, value[k]])) } : s) };
+}
+
+function restoreCastAndSets(project, field, value) {
+ const concept = objectConcept(project);
+ if (field === 'concept') return { ...project, concept: { ...value, ...pick(concept, ['subjects', ...CAST_SETS_CONCEPT_STYLE_KEYS]) } };
+ if (field === 'subjects') return { ...project, concept: { ...concept, subjects: value } };
+ const { styleReferences, ...rest } = value;
+ const nextConcept = { ...concept };
+ for (const k of CAST_SETS_CONCEPT_STYLE_KEYS) delete nextConcept[k];
+ return { ...project, concept: { ...nextConcept, ...pick(rest, CAST_SETS_CONCEPT_STYLE_KEYS) },
+ visualSpec: { ...project.visualSpec, ...pick(rest, CAST_SETS_SPEC_STYLE_KEYS) }, styleReferences };
+}
+
+/**
+ * Write one changed input back to the value an approval was granted on (#10241).
+ * Refuses (409) unless the approval is stale, that input's hash moved, and a
+ * value was recorded for it; a legacy approval or an oversized/media input has none.
+ */
+export function revertApprovedInput(project, { stage, field }) {
+ const unavailable = reason => refuseRevert(reason, 'MUSIC_VIDEO_REVERT_UNAVAILABLE');
+ const cast = stage === 'castAndSets';
+ let record;
+ let now;
+ if (cast) {
+ const approval = project.castAndSets;
+ if (approval?.status !== 'approved') throw unavailable('The Cast & Sets check-in is not approved.');
+ record = { inputs: approval.approvedInputs, values: approval.approvedValues };
+ now = castAndSetsApprovalInputs(project);
+ } else {
+ const readiness = productionReadiness(project);
+ if (readiness[stage].approved) throw unavailable('This approval is current; there is nothing to revert.');
+ record = project.productionReview?.approvals?.[stage];
+ now = readiness.inputs[stage];
+ }
+ if (!record?.inputs || changedInputs(record.inputs, now).includes(field) === false) throw unavailable('That input has not changed since the approval.');
+ const value = record.values?.[field];
+ if (value === undefined) throw unavailable('The approved value of that input was not kept, so it cannot be restored.');
+ if (cast) return restoreCastAndSets(project, field, value);
+ if (field === 'concept') return { ...project, concept: value };
+ if (DRAFT_FIELD_LABELS[field]) return { ...project, productionReview: { ...project.productionReview,
+ draft: { ...project.productionReview?.draft, [DRAFT_FIELD_LABELS[field]]: value } } };
+ if (SCENE_PROMPT_LABEL.test(field)) return restoreScenePrompt(project, value);
+ throw unavailable('That input cannot be reverted.');
+}
+
export function assertProductionApproval(project, stage = 'proof') {
const readiness = productionReadiness(project);
if (!readiness[stage].approved) throw new ServerError(
@@ -263,7 +360,7 @@ export function approveProductionStage(project, { stage, basis, proofReview, app
throw new ServerError('The rendered proof changed. Play and review the new excerpt before approving.', { status: 409, code: 'MUSIC_VIDEO_REVIEW_STALE' });
}
}
- const decision = { stage, basis: expected, inputs: productionApprovalInputs(project)[stage], approvedAt: new Date().toISOString(),
+ const decision = { stage, basis: expected, inputs: productionApprovalInputs(project)[stage], values: productionApprovalValues(project, stage), approvedAt: new Date().toISOString(),
...(approvedBy ? { approvedBy } : {}), ...(reviewer ? { reviewer: structuredClone(reviewer) } : {}),
...(stage === 'proof' ? { proofReview: structuredClone(proofReview) } : {}) };
return { ...project, productionReview: { ...project.productionReview,
diff --git a/server/services/musicVideo/productionReview.stale.test.js b/server/services/musicVideo/productionReview.stale.test.js
index 3254822013..a576022154 100644
--- a/server/services/musicVideo/productionReview.stale.test.js
+++ b/server/services/musicVideo/productionReview.stale.test.js
@@ -1,5 +1,5 @@
import { describe, it, expect } from 'vitest';
-import { castAndSetsApprovalInputs, productionReadiness } from './productionReview.js';
+import { castAndSetsApprovalInputs, castAndSetsApprovalValues, productionReadiness, revertApprovedInput } from './productionReview.js';
const castAndSetsApproval = (project) => productionReadiness(project).castAndSets;
@@ -48,3 +48,23 @@ describe('Cast & Sets approval basis', () => {
expect(castAndSetsApproval(legacy)).toEqual({ approved: true, stale: null });
});
});
+
+describe('reverting a Cast & Sets approval (#10241)', () => {
+ const project = { id: 'p1', concept: { prompt: 'Example concept', style: 'ink', subjects: [{ id: 's1' }] }, visualSpec: { palette: ['#000000'] } };
+ const approved = { ...project, castAndSets: { status: 'approved', approvedInputs: castAndSetsApprovalInputs(project), approvedValues: castAndSetsApprovalValues(project) } };
+
+ it('restores concept, style and subjects independently and clears the stale note', () => {
+ const edited = { ...approved, concept: { prompt: 'Other', style: 'oil', subjects: [] }, visualSpec: { palette: ['#ffffff'] } };
+ expect(productionReadiness(edited).castAndSets.stale.revertible).toEqual(['concept', 'style', 'subjects']);
+ let next = edited;
+ for (const field of ['concept', 'style', 'subjects']) next = revertApprovedInput(next, { stage: 'castAndSets', field });
+ expect(next.concept).toEqual(project.concept);
+ expect(next.visualSpec.palette).toEqual(['#000000']);
+ expect(productionReadiness(next).castAndSets.stale).toBeNull();
+ });
+
+ it('refuses a legacy approval that kept no values', () => {
+ const legacy = { ...approved, concept: { prompt: 'Other' }, castAndSets: { ...approved.castAndSets, approvedValues: undefined } };
+ expect(() => revertApprovedInput(legacy, { stage: 'castAndSets', field: 'concept' })).toThrow(/not kept/);
+ });
+});
diff --git a/server/services/musicVideo/productionReviewService.js b/server/services/musicVideo/productionReviewService.js
index fb81342e12..be09503efc 100644
--- a/server/services/musicVideo/productionReviewService.js
+++ b/server/services/musicVideo/productionReviewService.js
@@ -2,7 +2,7 @@ import { randomUUID } from 'node:crypto';
import { ServerError } from '../../lib/errorHandler.js';
import { getProject, mutateProjectRecord } from './projects.js';
import { musicVideoEvents } from './events.js';
-import { productionReadiness, seedArtDraft, productionReviewBasis, productionAlignmentBasis, documentStoryboardBasis, approveProductionStage, assertProductionApproval, recordProductionFeedback, resolveProductionFeedback } from './productionReview.js';
+import { productionReadiness, seedArtDraft, productionReviewBasis, productionAlignmentBasis, documentStoryboardBasis, approveProductionStage, assertProductionApproval, recordProductionFeedback, resolveProductionFeedback, revertApprovedInput } from './productionReview.js';
const reviewProcessId = randomUUID();
@@ -134,6 +134,13 @@ export async function reverifyProductionAlignment(id, { basis, notes, reviewer }
return changed(project);
}
+/** Restore one changed input to the value its approval was granted on (#10241). */
+export async function revertProductionInput(id, input) {
+ await requireProject(id);
+ const { project } = await mutateProjectRecord(id, current => ({ project: revertApprovedInput(current, input) }));
+ return changed(project);
+}
+
export async function approveProductionReview(id, input) {
const guard = await validateGuideSelection(await requireProject(id), current => current.productionReview?.draft?.guideArtifactId);
const { project } = await mutateProjectRecord(id, current => {