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 only a music-video draft's flagged sections, resumable with no paid resubmission (#8987)

[._.]/ Adam Eivyde69ae501bee
diff --git a/client/src/components/musicVideo/ExcerptPanel.jsx b/client/src/components/musicVideo/ExcerptPanel.jsx
index ca939d4f06..d80ac96088 100644
--- a/client/src/components/musicVideo/ExcerptPanel.jsx
+++ b/client/src/components/musicVideo/ExcerptPanel.jsx
@@ -1,5 +1,6 @@
import { useRef, useState } from 'react';
-import { Film, Flag, CheckCircle2, Trash2, X, Clapperboard } from 'lucide-react';
+import { Film, Flag, CheckCircle2, Trash2, X, Clapperboard, RotateCcw } from 'lucide-react';
+import RevisionPanel, { currentRevision } from './RevisionPanel.jsx';
const VERDICT_STYLES = {
flagged: 'bg-port-error/20 text-port-error',
@@ -59,7 +60,7 @@ function NoteRow({ excerptId, note, busy, onEdit, onDelete, onSeek }) {
);
}
-function ExcerptCard({ excerpt, deleting, noteBusy, onDelete, onCancel, onAddNote, onEditNote, onDeleteNote }) {
+function ExcerptCard({ excerpt, deleting, noteBusy, onDelete, onCancel, onAddNote, onEditNote, onDeleteNote, canRevise, onRevise }) {
const videoRef = useRef(null);
const [draft, setDraft] = useState('');
const seek = (t) => { if (videoRef.current) { videoRef.current.currentTime = t; videoRef.current.play?.().catch(() => {}); } };
@@ -77,6 +78,12 @@ function ExcerptCard({ excerpt, deleting, noteBusy, onDelete, onCancel, onAddNot
<div className="flex flex-wrap items-center justify-between gap-2 text-xs">
<span className="font-medium">{fmt(excerpt.startSec)} – {fmt(excerpt.endSec)} <span className="text-port-text-muted">({STATUS_LABELS[excerpt.status] || excerpt.status})</span></span>
<div className="flex items-center gap-2">
+ {/* #8987: regenerate ONLY the sections holding a flagged note; the rest stay as approved. */}
+ {excerpt.status === 'complete' && excerpt.sections?.length > 0 && excerpt.notes?.some((n) => n.verdict === 'flagged') && (
+ <button type="button" disabled={!canRevise} onClick={() => onRevise(excerpt.id)}
+ title="Reject the flagged sections and regenerate only those"
+ className="text-port-accent flex items-center gap-1 disabled:opacity-50 min-h-[44px] sm:min-h-0"><RotateCcw size={12} /> Revise flagged</button>
+ )}
{excerpt.status === 'rendering'
? <button type="button" onClick={() => onCancel(excerpt.id)} className="text-port-error flex items-center gap-1 min-h-[44px] sm:min-h-0"><X size={12} /> Cancel</button>
: <button type="button" disabled={deleting} onClick={() => onDelete(excerpt.id)} className="text-port-error flex items-center gap-1 disabled:opacity-50 min-h-[44px] sm:min-h-0"><Trash2 size={12} /> Delete</button>}
@@ -126,7 +133,10 @@ function ExcerptCard({ excerpt, deleting, noteBusy, onDelete, onCancel, onAddNot
* start) — a frame check alone can't prove motion/audio sync, so the video
* plays alongside the sheet rather than replacing it.
*/
-export default function ExcerptPanel({ project, rendering, progress, excerpts, ...actions }) {
+export default function ExcerptPanel({ project, rendering, progress, excerpts, revision = null, ...actions }) {
+ const activeRevision = currentRevision(project);
+ const canRevise = !!revision && !revision.busy && !rendering
+ && !(activeRevision && (activeRevision.status === 'open' || activeRevision.status === 'rendering'));
const durationSec = project?.audioAnalysis?.durationSec ?? null;
const [startSec, setStartSec] = useState(0);
const [endSec, setEndSec] = useState(durationSec ? Math.min(15, durationSec) : 15);
@@ -163,12 +173,18 @@ export default function ExcerptPanel({ project, rendering, progress, excerpts, .
<p className="text-xs text-port-text-muted mt-1">Rendering excerpt — {Math.round(progress)}%</p>
</div>
)}
+ {revision && (
+ <RevisionPanel project={project} busy={revision.busy || rendering}
+ genScenes={revision.genScenes} genVideoScenes={revision.genVideoScenes}
+ onResume={revision.resume} onCancel={revision.cancel} />
+ )}
{excerpts.length > 0 && (
<ul className="space-y-2">
{[...excerpts].reverse().map((excerpt) => (
<ExcerptCard key={excerpt.id} excerpt={excerpt} deleting={actions.deletingId === excerpt.id} noteBusy={actions.noteBusyId}
onDelete={actions.deleteExcerpt} onCancel={actions.cancelExcerpt}
- onAddNote={actions.addNote} onEditNote={actions.editNote} onDeleteNote={actions.deleteNote} />
+ onAddNote={actions.addNote} onEditNote={actions.editNote} onDeleteNote={actions.deleteNote}
+ canRevise={canRevise} onRevise={revision?.revise} />
))}
</ul>
)}
diff --git a/client/src/components/musicVideo/RevisionPanel.jsx b/client/src/components/musicVideo/RevisionPanel.jsx
new file mode 100644
index 0000000000..67c7128564
--- /dev/null
+++ b/client/src/components/musicVideo/RevisionPanel.jsx
@@ -0,0 +1,77 @@
+import { RotateCcw, Play, X } from 'lucide-react';
+
+const STATUS_LABELS = { open: 'Open', rendering: 'Rendering revised draft…', complete: 'Complete', canceled: 'Cancelled' };
+const SLOT = { image: 'referenceImageId', video: 'videoHistoryId' };
+
+// The latest revision worth showing: the active one, else the most recent.
+export const currentRevision = (project) => {
+ const revisions = Array.isArray(project?.revisions) ? project.revisions : [];
+ return revisions.find((r) => r.status === 'open' || r.status === 'rendering') || revisions[revisions.length - 1] || null;
+};
+
+// A rejected section's live state, from the board's own record + spinners
+// (the server re-derives the authoritative state on every resume).
+function sectionState(section, scene, spinning) {
+ if (section.verdict !== 'rejected') return { label: 'Kept', tone: 'text-port-success' };
+ if (!scene) return { label: 'Scene removed', tone: 'text-port-text-muted' };
+ if (scene[SLOT[section.kind]]) return { label: 'New take ready', tone: 'text-port-success' };
+ if (spinning) return { label: 'Generating…', tone: 'text-port-warning' };
+ return { label: 'Needs a new take', tone: 'text-port-error' };
+}
+
+/**
+ * Selective section revision (#8987): the revision opened from a reviewed
+ * draft — which sections were rejected (regenerated) and which were kept
+ * untouched — with Resume (continue from the checkpoint: generate what still
+ * lacks a take, else re-render the draft) and Cancel.
+ */
+export default function RevisionPanel({ project, busy, genScenes = {}, genVideoScenes = {}, onResume, onCancel }) {
+ const revision = currentRevision(project);
+ if (!revision) return null;
+ const scenes = [...(project.scenes || [])].sort((a, b) => (a.order ?? 0) - (b.order ?? 0));
+ const byId = new Map(scenes.map((s, i) => [s.sceneId, { scene: s, number: i + 1 }]));
+ const active = revision.status === 'open' || revision.status === 'rendering';
+ const sections = Array.isArray(revision.sections) ? revision.sections : [];
+ const rejected = sections.filter((s) => s.verdict === 'rejected');
+ const readyCount = rejected.filter((s) => byId.get(s.sceneId)?.scene?.[SLOT[s.kind]]).length;
+
+ return (
+ <div className="rounded border border-port-border p-2 space-y-2 text-xs" aria-label="Section revision">
+ <div className="flex flex-wrap items-center justify-between gap-2">
+ <span className="font-medium flex items-center gap-1">
+ <RotateCcw size={12} /> Revision {STATUS_LABELS[revision.status] ? `— ${STATUS_LABELS[revision.status]}` : ''}
+ {active && <span className="text-port-text-muted">({readyCount}/{rejected.length} revised sections ready)</span>}
+ </span>
+ {active && (
+ <div className="flex items-center gap-2">
+ {revision.status === 'open' && (
+ <button type="button" disabled={busy} onClick={() => onResume(revision.id)}
+ className="flex items-center gap-1 text-port-accent disabled:opacity-50 min-h-[44px] sm:min-h-0">
+ <Play size={12} /> {readyCount === rejected.length ? 'Render revised draft' : 'Resume'}
+ </button>
+ )}
+ <button type="button" disabled={busy} onClick={() => onCancel(revision.id)}
+ className="flex items-center gap-1 text-port-error disabled:opacity-50 min-h-[44px] sm:min-h-0">
+ <X size={12} /> Cancel revision
+ </button>
+ </div>
+ )}
+ </div>
+ {revision.error && active && <p role="alert" className="text-port-error">{revision.error}</p>}
+ <ul className="space-y-1">
+ {sections.map((section) => {
+ const entry = byId.get(section.sceneId);
+ const spinning = section.kind === 'image' ? genScenes[section.sceneId] : genVideoScenes[section.sceneId];
+ const state = sectionState(section, entry?.scene, spinning);
+ return (
+ <li key={section.sceneId} className="flex flex-wrap items-center gap-2">
+ <span className="min-w-0 flex-1">{entry ? `Scene ${entry.number}` : section.sceneId} <span className="text-port-text-muted">({section.layer})</span></span>
+ <span className={`px-1.5 py-0.5 rounded text-[10px] uppercase ${section.verdict === 'rejected' ? 'bg-port-error/20 text-port-error' : 'bg-port-success/20 text-port-success'}`}>{section.verdict}</span>
+ <span className={state.tone}>{state.label}</span>
+ </li>
+ );
+ })}
+ </ul>
+ </div>
+ );
+}
diff --git a/client/src/hooks/README.md b/client/src/hooks/README.md
index b14291b1c3..9896f2b7ef 100644
--- a/client/src/hooks/README.md
+++ b/client/src/hooks/README.md
@@ -42,7 +42,7 @@ grep -i "what you want to do" client/src/hooks/README.md
|---|---|---|
| `useQuotaUpdates` | Reconcile quota cards on scrape completion, reconnect and tab show; the caller owns the entry read. | Usage, Subscriptions and Quota Burn quota cards. |
| `useSseProgress` | Generic JSON-frame EventSource subscriber. | New SSE progress stream — start here, build on top. |
-| `useSseJobSlot` | Generic single-slot SSE job: captured target from preparation through completion, terminal-frame handling (`complete`/`error`/`canceled`), and `sse.closed`-without-terminal-frame recovery in one place. Returns `{ active, pending, jobId, percent, stage, context, start, cancel }`; reserves synchronously, exposes context during kickoff and ignores unmounted responses. Optional `readPercent` adapts other progress scales. Pass `startRequest`/`eventsUrl`/`cancelRequest` + per-feature toast copy. | Any "kick off a job → stream SSE → settle on terminal frame" hook. The reference-audio/YouTube/video-download/MIDI/music-video-render hooks all wrap this — don't re-roll the terminal-frame + lost-connection dance. |
+| `useSseJobSlot` | Generic single-slot SSE job: captured target from preparation through completion, terminal-frame handling (`complete`/`error`/`canceled`), and `sse.closed`-without-terminal-frame recovery in one place. Returns `{ active, pending, jobId, percent, stage, context, start, attach, cancel }` (`attach(jobId, context)` adopts a job another request already started into the idle slot); reserves synchronously, exposes context during kickoff and ignores unmounted responses. Optional `readPercent` adapts other progress scales. Pass `startRequest`/`eventsUrl`/`cancelRequest` + per-feature toast copy. | Any "kick off a job → stream SSE → settle on terminal frame" hook. The reference-audio/YouTube/video-download/MIDI/music-video-render hooks all wrap this — don't re-roll the terminal-frame + lost-connection dance. |
| `useInstallStream` | BYO-runtime install-log stream lifecycle: `stage`/`log`/`complete`/`error` frame dispatch, capped + optionally-debounced log accumulation, "connection lost" handling, ref-stashed `onComplete`, auto-scroll. `method: 'GET'` uses EventSource; `method: 'POST'` reads one fetch stream for a non-idempotent install. | A streamed install/setup modal that shows live SSE log lines (FLUX.2, video runtimes, OpenCode). Don't re-roll the teardown/onComplete-ref dance. |
| `useModelDownloadStatus` | Image/video model cache-status + SSE pre-download. `useDownloadableAssets(descriptors, options)` shares readiness and independent integrity dismissals across asset roles. `start(id)` commands a pull; `startWhenIdle(id)` requests one — it waits for the cache verdict, skips an already-resident repo, and queues behind whatever owns the single EventSource lane (`queuedModelId` while it waits, falsy id to retract). | Surfacing "Available" vs "Download" badge inline in the gen form; `startWhenIdle` for a picker where choosing an option IS the request for its weights. |
| `useAgyModels` | Live `agy models` probe (the AGENT models `--model` accepts) with `models`/`error`/`loading`/`refresh`; opt-in via an `enabled` flag so it never spawns for a disabled backend. | Any Agy model picker — the Settings default or the per-render override. Don't hardcode a model list: agy exits non-zero on an id outside this catalog. |
@@ -248,7 +248,8 @@ grep -i "what you want to do" client/src/hooks/README.md
| `useMusicVideoYoutubeImport` | The Music Video page's two independent `useYoutubeTrackImport` slots (create form + detail-view track row) plus their URL drafts, the detail slot's captured target project, and the URL-nav backstop that bounces a deep link / Back / ⌘K jump away from an in-flight import back to its project. Returns `{ createUrl, setCreateUrl, editUrl, setEditUrl, createJob, editJob, startCreate, startEdit, switchBlockedMessage }`. | The Music Video page. Reuse `switchBlockedMessage` for any additional guard (delete, list picker) so every surface says the same thing. |
| `useMusicVideoMidiJob` | `useMidiTranscription` bound to the music-video API surface, plus the MuScriptor model-size picker state (read fresh at each kickoff). Returns the slot (`active`/`stage`/`stageLabel`/`context`/`start(projectId)`/`cancel`/`installGate`/`gatedGate`) plus `{ model, setModel }`; `onTranscribed(projectId, midiTranscription)` fires on a non-discarded terminal frame. | The Music Video MIDI button + model select. |
| `useMusicVideoRenderJob` | The final-render job (#1760 Phase 2): kickoff (409 → attach to the existing job), SSE progress, terminal-frame handling and non-terminal stream-close recovery. Thin `useSseJobSlot` adapter with 0–1 progress conversion; returns `{ active, pending, context, job, progress, start(projectId), cancel }`; `onRendered(projectId, result)` / `onFailed(projectId)` key on the projectId captured at kickoff. | The Music Video "Render final" control. |
-| `useMusicVideoExcerpts` | Draft excerpt render + timecoded review notes (#8986): a `useSseJobSlot` render job over a chosen `[startSec, endSec)` window (any terminal frame reloads the project, since the persisted excerpt shape lives server-side) plus add/edit/delete review-note calls that apply the fresh whole project from each response. Returns `{ rendering, progress, deletingId, noteBusyId, startExcerpt(startSec, endSec), cancelExcerpt, deleteExcerpt(excerptId), addNote(excerptId, {atSec, note, verdict?}), editNote(excerptId, noteId, patch), deleteNote(excerptId, noteId) }`. | The Music Video excerpt panel. |
+| `useMusicVideoRevisions` | Selective section revision (#8987): open a revision from a reviewed draft excerpt (its flagged sections' takes are rejected, the rest kept), resume it from the server checkpoint — generating ONLY the sections the server reports as `needsGeneration` through the board's scene lanes, or adopting the draft re-render via `attachRender` once every revised section has a take — and cancel it. Returns `{ busy, revise(excerptId, sceneIds?), resume(revisionId), cancel(revisionId) }`. | The Music Video excerpt panel. |
+| `useMusicVideoExcerpts` | Draft excerpt render + timecoded review notes (#8986): a `useSseJobSlot` render job over a chosen `[startSec, endSec)` window (any terminal frame reloads the project, since the persisted excerpt shape lives server-side) plus add/edit/delete review-note calls that apply the fresh whole project from each response. Returns `{ rendering, progress, deletingId, noteBusyId, startExcerpt(startSec, endSec), cancelExcerpt(excerptId), attachRender(jobId, projectId), deleteExcerpt(excerptId), addNote(excerptId, {atSec, note, verdict?}), editNote(excerptId, noteId, patch), deleteNote(excerptId, noteId) }`. | The Music Video excerpt panel. |
| `useMusicVideoModelSettings` | A project's saved render pins — video backend (local/Grok/fal.ai)/model/generation-mode/audio-reactive LoRA + the image-side frame pin — with the Video Gen catalog they read from. Optimistic-local + silent PATCH, rollback + toast on failure; `saving` gates the dependent generate buttons. Returns `{ models, modelsLoading, defaultModel, falEnabled, saving, settings, effectiveModelId, activeModel, audioReactiveModels, audioReactiveLoras, detectedAudioReactiveLora, audioReactiveReady, audioReactiveSelected, videoBlockedReason, change, changeFramePin }`. `videoBlockedReason` is the single "why can't I generate" string (an unavailable audio-reactive setup, or a fal.ai pin with no configured API key) shared by the disabled buttons, their tooltips, and the blocked-call toast. | The Music Video renderer selects and anything building a scene-clip job payload from them. |
| `useMusicVideoSceneMedia` | Both per-scene generation lanes (reference frame + scene clip) over `useSceneRenderLifecycle`, the frame/shot prompt builders (concept-style + visual-spec direction suffix), visual-spec reference-image conditioning with explicit unsupported-backend feedback (#8965), and the batch "generate the missing ones" actions. Returns `{ genScenes, genVideoScenes, conditioning, buildFramePrompt, buildShotPrompt, generateFrame, generateSceneVideo, continueSceneVideo, generateMissingFrames, generateMissingVideos }`. | The Music Video scene board — don't re-wire the two lanes or re-derive the i2v/a2v/extend payloads. |
| `useMusicVideoTakes` | Scene-take review + external-asset handoff for the Music Video board (#8965): serialized select / reject / note / gallery-import take mutations folded back as scene patches, the handoff manifest download, and the handoff import (gallery upload per file, then scene association by file tag with provider provenance). Returns `{ busy, selectTake, reviewTake, importTake, exportHandoff, importHandoffFiles }`. | The Music Video board's take strips, contact sheet and handoff row — don't re-sequence take mutations per call site. |
diff --git a/client/src/hooks/index.js b/client/src/hooks/index.js
index fc3a4329af..3adf19176e 100644
--- a/client/src/hooks/index.js
+++ b/client/src/hooks/index.js
@@ -64,6 +64,7 @@ export { default as useMusicVideoManualTempo } from './useMusicVideoManualTempo.
export { default as useMusicVideoMidiJob } from './useMusicVideoMidiJob.js';
export { default as useMusicVideoModelSettings } from './useMusicVideoModelSettings.js';
export { default as useMusicVideoRenderJob } from './useMusicVideoRenderJob.js';
+export { default as useMusicVideoRevisions } from './useMusicVideoRevisions.js';
export { default as useMusicVideoSceneMedia } from './useMusicVideoSceneMedia.js';
export { default as useMusicVideoTakes } from './useMusicVideoTakes.js';
export { default as useMusicVideoTreatment } from './useMusicVideoTreatment.js';
diff --git a/client/src/hooks/useMusicVideoExcerpts.js b/client/src/hooks/useMusicVideoExcerpts.js
index c28a7f5444..fed4392b50 100644
--- a/client/src/hooks/useMusicVideoExcerpts.js
+++ b/client/src/hooks/useMusicVideoExcerpts.js
@@ -62,6 +62,13 @@ export default function useMusicVideoExcerpts({ project, replaceProject } = {})
});
const startExcerpt = (startSec, endSec) => job.start({ startSec, endSec }, projectId);
+ // #8987: a selective revision's resume starts its draft re-render server-side;
+ // adopt that job so it shows the same progress and reloads on its finish.
+ const attachRender = (jobId, id = projectId) => job.attach(jobId, id);
+ // An excerpt's id IS its render job id, so any rendering excerpt — including
+ // one started before a reload, or by a revision — can be cancelled by id.
+ const cancelExcerpt = (excerptId) => cancelMusicVideoExcerptRender(excerptId, { silent: true })
+ .catch((err) => toast.error(err?.message || 'Failed to cancel the excerpt render'));
const deleteExcerpt = (excerptId) => {
setDeletingId(excerptId);
@@ -101,7 +108,8 @@ export default function useMusicVideoExcerpts({ project, replaceProject } = {})
deletingId,
noteBusyId,
startExcerpt,
- cancelExcerpt: job.cancel,
+ cancelExcerpt,
+ attachRender,
deleteExcerpt,
addNote,
editNote,
diff --git a/client/src/hooks/useMusicVideoRevisions.js b/client/src/hooks/useMusicVideoRevisions.js
new file mode 100644
index 0000000000..1f0151c8db
--- /dev/null
+++ b/client/src/hooks/useMusicVideoRevisions.js
@@ -0,0 +1,95 @@
+import { useState } from 'react';
+import toast from '../components/ui/Toast';
+import {
+ startMusicVideoRevision,
+ resumeMusicVideoRevision,
+ cancelMusicVideoRevision,
+} from '../services/apiMusicVideo.js';
+
+const plural = (n, word) => `${n} ${word}${n === 1 ? '' : 's'}`;
+
+/**
+ * Selective section revision (#8987): reject a reviewed draft excerpt's
+ * flagged sections, regenerate ONLY those, and re-render the draft window —
+ * resumable from the server's persisted checkpoint and cancelable.
+ *
+ * The server decides what may be generated: `resume` answers with the rejected
+ * sections that still hold no take and have no job in flight
+ * (`needsGeneration`), and this hook submits exactly those through the board's
+ * normal scene lanes (`sceneMedia.generateSceneVideo` / `generateFrame`),
+ * skipping any the board already has spinning. A section holding a take is
+ * never in that list, so resuming after a failed or interrupted render
+ * re-renders without paying for any generation again. Once every rejected
+ * section holds a take, `resume` starts the draft re-render server-side and
+ * its job is adopted into the excerpt job slot (`attachRender`) for progress.
+ *
+ * `revise(excerptId, sceneIds?)` opens a revision and immediately resumes it.
+ *
+ * `replaceProject(project)` swaps the local record whole; `sceneMedia` is the
+ * `useMusicVideoSceneMedia` result; `attachRender(jobId, projectId)` is
+ * `useMusicVideoExcerpts().attachRender`.
+ */
+export default function useMusicVideoRevisions({ project, replaceProject, sceneMedia, attachRender } = {}) {
+ const projectId = project?.id || null;
+ const [busy, setBusy] = useState(false);
+
+ const run = (request) => {
+ setBusy(true);
+ return request()
+ .catch((err) => { toast.error(err?.message || 'Revision request failed'); return null; })
+ .finally(() => setBusy(false));
+ };
+
+ const generateSections = (next, refs) => {
+ const scenes = new Map((next.scenes || []).map((s) => [s.sceneId, s]));
+ let submitted = 0;
+ for (const { sceneId, kind } of refs) {
+ const scene = scenes.get(sceneId);
+ if (!scene) continue;
+ if (kind === 'image') {
+ if (sceneMedia?.genScenes?.[sceneId]) continue;
+ sceneMedia?.generateFrame(scene);
+ } else {
+ if (sceneMedia?.genVideoScenes?.[sceneId]) continue;
+ sceneMedia?.generateSceneVideo(scene);
+ }
+ submitted += 1;
+ }
+ return submitted;
+ };
+
+ const resume = (revisionId) => run(() => resumeMusicVideoRevision(projectId, revisionId, { silent: true })
+ .then((res) => {
+ replaceProject(res.project);
+ if (res.render?.jobId) {
+ attachRender?.(res.render.jobId, res.project.id);
+ toast.info('Every revised section has a new take — rendering the revised draft');
+ return res;
+ }
+ const submitted = generateSections(res.project, res.needsGeneration || []);
+ const waiting = (res.generating || []).length;
+ const parts = [
+ submitted ? `generating ${plural(submitted, 'section')}` : '',
+ waiting ? `${plural(waiting, 'section')} still in progress` : '',
+ ].filter(Boolean);
+ toast.info(`${parts.join('; ') || 'Waiting on the revised sections'} — resume again once their takes land`);
+ return res;
+ }));
+
+ const startRevision = (excerptId, sceneIds) => run(() => startMusicVideoRevision(projectId, excerptId, sceneIds ? { sceneIds } : {}, { silent: true })
+ .then((res) => {
+ replaceProject(res.project);
+ if (res.skippedSceneIds?.length) toast.info(`Skipped ${plural(res.skippedSceneIds.length, 'title card')} — edit card text instead`);
+ return res;
+ }));
+
+ // The one-click path from a review: open the revision, then resume it at
+ // once, which generates the rejected sections (an explicit director action).
+ const revise = (excerptId, sceneIds) => startRevision(excerptId, sceneIds)
+ .then((res) => (res?.revision ? resume(res.revision.id) : null));
+
+ const cancel = (revisionId) => run(() => cancelMusicVideoRevision(projectId, revisionId, { silent: true })
+ .then((res) => { replaceProject(res.project); return res; }));
+
+ return { busy, revise, resume, cancel };
+}
diff --git a/client/src/hooks/useSseJobSlot.js b/client/src/hooks/useSseJobSlot.js
index f369570d4e..4c73e67e34 100644
--- a/client/src/hooks/useSseJobSlot.js
+++ b/client/src/hooks/useSseJobSlot.js
@@ -25,6 +25,11 @@ const defaultReadPercent = (frame) => frame.percent;
* - `onErrorFrame(frame, context)` → return true to suppress the error toast.
* - `onKickoffError(err, startArg)` → return true to suppress the kickoff toast.
* - `onKickoffSuccess(jobId, startArg)` — fires when the kickoff resolves.
+ *
+ * `attach(jobId, context)` adopts a job some OTHER request already started
+ * (e.g. a workflow step whose response carried the jobId) into the idle slot,
+ * so it gets the same progress, terminal and cancel handling. Returns false
+ * when the slot is busy.
*/
export default function useSseJobSlot({
startRequest,
@@ -120,6 +125,15 @@ export default function useSseJobSlot({
});
};
+ const attach = (jobId, context) => {
+ if (!jobId || !mounted.current || slotRef.current) return false;
+ const slot = { jobId, context: context ?? null };
+ slotRef.current = slot;
+ setJob(slot);
+ setProgress({ percent: 0, stage: null });
+ return true;
+ };
+
const cancel = () => {
if (!mounted.current || !job?.jobId) return;
cancelRequest(job.jobId, { silent: true }).catch(() => {});
@@ -133,6 +147,7 @@ export default function useSseJobSlot({
stage: progress.stage,
context: job?.context ?? null,
start,
+ attach,
cancel,
};
}
diff --git a/client/src/pages/MusicVideo.jsx b/client/src/pages/MusicVideo.jsx
index 990ce749ce..d6ce0fcbc6 100644
--- a/client/src/pages/MusicVideo.jsx
+++ b/client/src/pages/MusicVideo.jsx
@@ -23,6 +23,7 @@ import useMusicVideoYoutubeImport from '../hooks/useMusicVideoYoutubeImport.js';
import useMusicVideoMidiJob from '../hooks/useMusicVideoMidiJob.js';
import useMusicVideoRenderJob from '../hooks/useMusicVideoRenderJob.js';
import useMusicVideoExcerpts from '../hooks/useMusicVideoExcerpts.js';
+import useMusicVideoRevisions from '../hooks/useMusicVideoRevisions.js';
import useMusicVideoModelSettings from '../hooks/useMusicVideoModelSettings.js';
import useMusicVideoManualTempo from '../hooks/useMusicVideoManualTempo.js';
import useMusicVideoSceneMedia from '../hooks/useMusicVideoSceneMedia.js';
@@ -129,6 +130,9 @@ export default function MusicVideo() {
applyScenePatch: patchScene,
});
const takes = useMusicVideoTakes({ project: selected, applyScenePatch: patchScene });
+ // Selective section revision (#8987): regenerate only a draft's flagged
+ // sections, resumable from the server's checkpoint.
+ const revisions = useMusicVideoRevisions({ project: selected, replaceProject, sceneMedia, attachRender: excerpts.attachRender });
// Pre-production treatment (#8980): brief, compiled arc, shot direction,
// proof checklist and the non-destructive Apply review.
const treatment = useMusicVideoTreatment({ project: selected, onProjectPatch: patchProject, replaceProject });
@@ -700,6 +704,7 @@ export default function MusicVideo() {
addNote={excerpts.addNote}
editNote={excerpts.editNote}
deleteNote={excerpts.deleteNote}
+ revision={{ ...revisions, genScenes: sceneMedia.genScenes, genVideoScenes: sceneMedia.genVideoScenes }}
/>
<LyricsPanel
project={selected}
diff --git a/client/src/pages/MusicVideo.test.jsx b/client/src/pages/MusicVideo.test.jsx
index 151e4d01a4..a7a41a6d55 100644
--- a/client/src/pages/MusicVideo.test.jsx
+++ b/client/src/pages/MusicVideo.test.jsx
@@ -77,6 +77,9 @@ vi.mock('../services/apiMusicVideo.js', () => ({
addMusicVideoExcerptNote: vi.fn(),
updateMusicVideoExcerptNote: vi.fn(),
deleteMusicVideoExcerptNote: vi.fn(),
+ startMusicVideoRevision: vi.fn(),
+ resumeMusicVideoRevision: vi.fn(),
+ cancelMusicVideoRevision: vi.fn(),
}));
vi.mock('../services/apiUniverseBuilder.js', () => ({ getUniverse: vi.fn() }));
vi.mock('../lib/downloadBlob.js', () => ({ downloadBlob: vi.fn() }));
@@ -160,6 +163,7 @@ import {
addMusicVideoSceneTake, getMusicVideoHandoffBundle,
renderMusicVideoExcerpt, deleteMusicVideoExcerpt, addMusicVideoExcerptNote,
updateMusicVideoExcerptNote, deleteMusicVideoExcerptNote, getMusicVideoProject,
+ startMusicVideoRevision, resumeMusicVideoRevision, cancelMusicVideoRevision,
} from '../services/apiMusicVideo.js';
import { generateImage, uploadGalleryImage } from '../services/apiSystem.js';
import { importTrackFromYoutube, trackImportEventsUrl, listTracks } from '../services/apiTracks.js';
@@ -457,6 +461,75 @@ describe('MusicVideo draft excerpt render (#8986)', () => {
});
});
+describe('MusicVideo selective section revision (#8987)', () => {
+ // A reviewed draft: s1 approved, s2 flagged (song time 10 + 7 = 17s).
+ const REVIEWED = {
+ ...PROJECT_WITH_CLIP,
+ scenes: [
+ { sceneId: 's1', order: 0, prompt: 'a', referenceImageId: 'img1', videoHistoryId: 'h1' },
+ { sceneId: 's2', order: 1, prompt: 'b', referenceImageId: 'img2', videoHistoryId: 'h2' },
+ ],
+ excerpts: [{
+ id: 'mve-1', startSec: 10, endSec: 20, status: 'complete', filename: 'excerpt-1.mp4', contactSheetFilename: null, error: null,
+ sections: [{ sceneId: 's1', layer: 'footage', startSec: 10, endSec: 15 }, { sceneId: 's2', layer: 'footage', startSec: 15, endSec: 20 }],
+ notes: [{ id: 'mvn-1', atSec: 7, note: 'the jump cut stutters', verdict: 'flagged' }],
+ }],
+ };
+ const revisionOf = (status = 'open') => ({
+ id: 'mvr-1', excerptId: 'mve-1', startSec: 10, endSec: 20, status, renderExcerptId: null, renderAttempts: 0, error: null,
+ sections: [
+ { sceneId: 's1', layer: 'footage', kind: 'video', verdict: 'approved', rejectedAssetId: null, keptAssetId: 'h1', noteIds: [] },
+ { sceneId: 's2', layer: 'footage', kind: 'video', verdict: 'rejected', rejectedAssetId: 'h2', keptAssetId: null, noteIds: ['mvn-1'] },
+ ],
+ });
+ const withRevision = (s2Clip, status) => ({
+ ...REVIEWED,
+ scenes: [REVIEWED.scenes[0], { ...REVIEWED.scenes[1], videoHistoryId: s2Clip }],
+ revisions: [revisionOf(status)],
+ });
+
+ it('revising a flagged draft generates only the rejected section', async () => {
+ const opened = withRevision(null);
+ startMusicVideoRevision.mockResolvedValue({ project: opened, revision: opened.revisions[0], skippedSceneIds: [] });
+ resumeMusicVideoRevision.mockResolvedValue({ project: opened, revision: opened.revisions[0], needsGeneration: [{ sceneId: 's2', kind: 'video' }], generating: [], render: null });
+ generateVideo.mockResolvedValue({ jobId: 'video-job-s2' });
+ await openProject(REVIEWED);
+
+ fireEvent.click(await findEnabledByRole('button', { name: /Revise flagged/i }));
+ await waitFor(() => expect(resumeMusicVideoRevision).toHaveBeenCalledWith('mv-1', 'mvr-1', { silent: true }));
+ expect(startMusicVideoRevision).toHaveBeenCalledWith('mv-1', 'mve-1', {}, { silent: true });
+ await waitFor(() => expect(generateVideo).toHaveBeenCalledTimes(1));
+ expect(JSON.parse(generateVideo.mock.calls[0][0].musicVideo)).toEqual({ projectId: 'mv-1', sceneId: 's2' });
+ const panel = screen.getByLabelText('Section revision');
+ expect(within(panel).getByText('Kept')).toBeInTheDocument();
+ });
+
+ it('resuming once every revised section has a take re-renders the draft without any paid generation', async () => {
+ const ready = withRevision('h2-new');
+ resumeMusicVideoRevision.mockResolvedValue({
+ project: { ...ready, revisions: [{ ...ready.revisions[0], status: 'rendering', renderExcerptId: 'mve-2' }] },
+ revision: { ...ready.revisions[0], status: 'rendering' }, needsGeneration: [], generating: [], render: { jobId: 'mve-2', excerptId: 'mve-2' },
+ });
+ await openProject(ready);
+
+ fireEvent.click(await findEnabledByRole('button', { name: /Render revised draft/i }));
+ await waitFor(() => expect(resumeMusicVideoRevision).toHaveBeenCalledWith('mv-1', 'mvr-1', { silent: true }));
+ await screen.findByText(/Rendering excerpt/);
+ expect(generateVideo).not.toHaveBeenCalled();
+ expect(generateImage).not.toHaveBeenCalled();
+ });
+
+ it('cancels an open revision', async () => {
+ const open = withRevision(null);
+ cancelMusicVideoRevision.mockResolvedValue({ project: { ...open, revisions: [{ ...open.revisions[0], status: 'canceled' }] }, revision: { ...open.revisions[0], status: 'canceled' } });
+ await openProject(open);
+ fireEvent.click(await findEnabledByRole('button', { name: /Cancel revision/i }));
+ await waitFor(() => expect(cancelMusicVideoRevision).toHaveBeenCalledWith('mv-1', 'mvr-1', { silent: true }));
+ await screen.findByText(/Revision — Cancelled/);
+ expect(generateVideo).not.toHaveBeenCalled();
+ });
+});
+
describe('MusicVideo project video renderer', () => {
it('lets the server resolve this install default when a synced project has no backend pin', async () => {
generateVideo.mockResolvedValue({ jobId: 'video-job-default' });
diff --git a/client/src/services/apiMusicVideo.js b/client/src/services/apiMusicVideo.js
index cfb639fe4d..fc63796dfb 100644
--- a/client/src/services/apiMusicVideo.js
+++ b/client/src/services/apiMusicVideo.js
@@ -156,6 +156,19 @@ export const deleteMusicVideoExcerptNote = (id, excerptId, noteId, options = {})
method: 'DELETE', ...options,
});
+// ---- Selective section revision (#8987) ----
+// Reject a reviewed draft's flagged sections and regenerate only those.
+// Start body: { sceneIds? } → { project, revision, skippedSceneIds }.
+export const startMusicVideoRevision = (id, excerptId, body = {}, options = {}) =>
+ request(`/music-video/${encodeURIComponent(id)}/excerpt/${encodeURIComponent(excerptId)}/revisions`, {
+ method: 'POST', body: JSON.stringify(body), ...options,
+ });
+// → { project, revision, needsGeneration, generating, render: { jobId, excerptId } | null }.
+export const resumeMusicVideoRevision = (id, revisionId, options = {}) =>
+ request(`/music-video/${encodeURIComponent(id)}/revisions/${encodeURIComponent(revisionId)}/resume`, { method: 'POST', ...options });
+export const cancelMusicVideoRevision = (id, revisionId, options = {}) =>
+ request(`/music-video/${encodeURIComponent(id)}/revisions/${encodeURIComponent(revisionId)}/cancel`, { method: 'POST', ...options });
+
// ---- Pre-production treatment (#8980) ----
// A structured brief, a compiled whole-song arc, per-shot direction keyed to the
// board's scene ids and a proof checklist. Every write names the treatment
diff --git a/server/lib/musicVideoValidation.js b/server/lib/musicVideoValidation.js
index 853f04c94c..765263ed4b 100644
--- a/server/lib/musicVideoValidation.js
+++ b/server/lib/musicVideoValidation.js
@@ -374,6 +374,14 @@ export const musicVideoExcerptNoteUpdateSchema = z.object({
verdict: z.enum(MUSIC_VIDEO_EXCERPT_NOTE_VERDICTS).nullable().optional(),
}).strict().refine((r) => r.atSec !== undefined || r.note !== undefined || r.verdict !== undefined, { message: 'atSec, note or verdict is required' });
+// ---- Selective section revision (#8987) -------------------------------------
+// Reject the flagged sections of a reviewed draft excerpt and regenerate only
+// those. `sceneIds` names the sections explicitly; omitted, every section
+// holding a `flagged` note is revised. See services/musicVideo/revision.js.
+export const musicVideoRevisionStartSchema = z.object({
+ sceneIds: z.array(z.string().min(1).max(200)).min(1).max(500).optional(),
+}).strict();
+
export const musicVideoProjectCreateSchema = z.object({
name: z.string().min(1).max(200),
mode: z.enum(MUSIC_VIDEO_MODES).optional(),
diff --git a/server/routes/musicVideo.js b/server/routes/musicVideo.js
index dec3ffeab4..84c572b4fe 100644
--- a/server/routes/musicVideo.js
+++ b/server/routes/musicVideo.js
@@ -32,6 +32,7 @@ import {
musicVideoExcerptRequestSchema,
musicVideoExcerptNoteSchema,
musicVideoExcerptNoteUpdateSchema,
+ musicVideoRevisionStartSchema,
isPaginationRequested,
paginateArray,
} from '../lib/validation.js';
@@ -68,6 +69,7 @@ import { analyzeAudioFile, analyzeAudioFileManual, buildManualAnalysisFromCached
import { renderMusicVideo, attachRenderSseClient, cancelRender } from '../services/musicVideo/render.js';
import { startExcerptRender, attachExcerptRenderSseClient, cancelExcerptRender } from '../services/musicVideo/excerptRender.js';
import { deleteExcerpt, addReviewNote, editReviewNote, deleteReviewNote } from '../services/musicVideo/excerptService.js';
+import { startRevision, resumeRevision, cancelRevision } from '../services/musicVideo/revisionService.js';
import { planProject } from '../services/musicVideo/planner.js';
import { parseLyricCues } from '../services/musicVideo/timedText.js';
import {
@@ -371,6 +373,26 @@ router.delete('/:id/excerpt/:excerptId/notes/:noteId', asyncHandler(async (req,
res.json(await deleteReviewNote(req.params.id, req.params.excerptId, req.params.noteId));
}));
+// --- Selective section revision (#8987) ---
+// Reject the flagged sections of a reviewed draft (their selected takes clear)
+// while every other section keeps its selection. Resume continues from the
+// persisted checkpoint: sections still without a take come back as
+// `needsGeneration` for the board to generate; once all hold one, the draft
+// window re-renders. A section holding a take is never asked to generate again,
+// so a render retry never re-submits paid generation.
+router.post('/:id/excerpt/:excerptId/revisions', asyncHandler(async (req, res) => {
+ const input = validateRequest(musicVideoRevisionStartSchema, req.body || {});
+ res.status(201).json(await startRevision(req.params.id, req.params.excerptId, input));
+}));
+
+router.post('/:id/revisions/:revisionId/resume', asyncHandler(async (req, res) => {
+ res.json(await resumeRevision(req.params.id, req.params.revisionId));
+}));
+
+router.post('/:id/revisions/:revisionId/cancel', asyncHandler(async (req, res) => {
+ res.json(await cancelRevision(req.params.id, req.params.revisionId));
+}));
+
// --- Director scene board ---
router.post('/:id/scenes', asyncHandler(async (req, res) => {
diff --git a/server/routes/musicVideoRevision.test.js b/server/routes/musicVideoRevision.test.js
new file mode 100644
index 0000000000..e0170f690b
--- /dev/null
+++ b/server/routes/musicVideoRevision.test.js
@@ -0,0 +1,267 @@
+/**
+ * Music Video selective section revision (#8987), through the real router,
+ * revisionService.js, excerptRender.js and the real file-backed project store.
+ * Only the process boundaries are doubled: the ffmpeg child (a fake emitter
+ * the test finishes), the render prep that needs a real ffmpeg + song, and the
+ * media-job queue — whose `enqueueJob` is the PAID generation sink, asserted
+ * never to be reached, and whose `listJobs` feeds the in-flight check.
+ */
+
+import { describe, it, expect, vi, beforeEach, afterAll } from 'vitest';
+import express from 'express';
+import { existsSync, mkdirSync, rmSync, writeFileSync } from 'fs';
+import { join } from 'path';
+import { request } from '../lib/testHelper.js';
+import { errorMiddleware } from '../lib/errorHandler.js';
+import { makePathsProxy, lazyTempDataRoot, cleanupTempDataRoots } from '../lib/mockPathsDataRoot.js';
+
+const ROOT = () => lazyTempDataRoot('mv-revision-route-test-');
+vi.mock('../lib/paths.js', async (importOriginal) => makePathsProxy(await importOriginal(), { dataRoot: ROOT }));
+
+const h = vi.hoisted(() => {
+ const procs = [];
+ const makeEmitter = () => {
+ const listeners = {};
+ return {
+ on(ev, fn) { (listeners[ev] ||= []).push(fn); return this; },
+ emit(ev, ...args) { for (const fn of listeners[ev] || []) fn(...args); },
+ };
+ };
+ const spawn = (_cmd, args) => {
+ const p = makeEmitter();
+ p.args = args;
+ p.stderr = makeEmitter();
+ p.kill = () => {};
+ procs.push(p);
+ return p;
+ };
+ return { procs, spawn, jobs: [], enqueueJob: vi.fn() };
+});
+
+vi.mock('../lib/childProcess.js', async (importOriginal) => ({ ...(await importOriginal()), spawn: h.spawn }));
+vi.mock('../lib/sseUtils.js', () => ({ broadcastSse: vi.fn(), attachSseClient: vi.fn(() => true), closeJobAfterDelay: vi.fn() }));
+vi.mock('../lib/killWithEscalation.js', () => ({ killWithEscalation: vi.fn((proc) => proc.emit('close', null, 'SIGTERM')) }));
+vi.mock('../services/htmlComposition/encode.js', () => ({ encodeFileContactSheetAtTimes: vi.fn(async () => {}) }));
+vi.mock('../services/mediaJobQueue/index.js', () => ({
+ listJobs: vi.fn(({ kind } = {}) => h.jobs.filter((j) => !kind || j.kind === kind)),
+ enqueueJob: h.enqueueJob,
+}));
+// Three 10s sections: footage s1, footage s2, still s3 (a composed render).
+const CLIPS = [
+ { sceneId: 's1', videoPath: '/v/a.mp4', width: 640, height: 360, fps: 24, inSec: 0, outSec: 10, duration: 10, sourceSec: 10, loop: true },
+ { sceneId: 's2', videoPath: '/v/b.mp4', width: 640, height: 360, fps: 24, inSec: 0, outSec: 10, duration: 10, sourceSec: 10, loop: true },
+ { sceneId: 's3', layer: 'still', imagePath: '/i/c.png', move: 'hold', inSec: 0, outSec: 10, duration: 10, sourceSec: 10 },
+];
+vi.mock('../services/musicVideo/render.js', async (importOriginal) => ({
+ ...(await importOriginal()),
+ planMusicVideoRender: vi.fn(async () => ({ ffmpeg: 'ffmpeg', audioPath: '/a/song.wav', composed: true, clips: CLIPS, audioDurationSec: 30 })),
+}));
+
+const { default: musicVideoRoutes } = await import('./musicVideo.js');
+const projects = await import('../services/musicVideo/projects.js');
+const { recoverStuckMusicVideoExcerpts } = await import('../services/musicVideo/excerptRender.js');
+
+const app = express();
+app.use(express.json());
+app.use('/api/music-video', musicVideoRoutes);
+app.use(errorMiddleware);
+
+const base = (id) => `/api/music-video/${id}`;
+const tick = () => new Promise((r) => setTimeout(r, 0));
+const lastProc = () => h.procs[h.procs.length - 1];
+const settle = async () => { for (let i = 0; i < 5; i += 1) await tick(); };
+
+beforeEach(() => {
+ rmSync(join(ROOT(), 'music-video-projects.json'), { force: true });
+ h.procs.length = 0;
+ h.jobs.length = 0;
+ vi.clearAllMocks();
+});
+afterAll(cleanupTempDataRoots);
+
+const scene = (sceneId, order, media) => ({ sceneId, order, prompt: `shot ${sceneId}`, takes: [], ...media });
+
+// A reviewed draft of [5, 25): s1 [5,10), s2 [10,20), s3 [20,25). One flagged
+// note lands in s2 (excerpt time 8 → song time 13), one approval in s1.
+async function reviewedProject(noteOverrides = []) {
+ const project = await projects.createProject({ name: 'Example Video' });
+ return projects.updateProject(project.id, {
+ scenes: [
+ scene('s1', 0, { referenceImageId: 'f1.png', videoHistoryId: 'clip-1' }),
+ scene('s2', 1, { referenceImageId: 'f2.png', videoHistoryId: 'clip-2' }),
+ scene('s3', 2, { referenceImageId: 'still-3.png', visualLayer: 'still' }),
+ ],
+ excerpts: [{
+ id: 'mve-draft', startSec: 5, endSec: 25, status: 'complete', jobId: null,
+ filename: 'music-video-excerpt-draft.mp4', contactSheetFilename: null, partialFilename: null, error: null,
+ sections: [
+ { sceneId: 's1', layer: 'footage', startSec: 5, endSec: 10 },
+ { sceneId: 's2', layer: 'footage', startSec: 10, endSec: 20 },
+ { sceneId: 's3', layer: 'still', startSec: 20, endSec: 25 },
+ ],
+ notes: [
+ { id: 'mvn-bad', atSec: 8, note: 'the camera jitters', verdict: 'flagged' },
+ { id: 'mvn-good', atSec: 1, note: 'great open', verdict: 'approved' },
+ ...noteOverrides,
+ ],
+ createdAt: '2026-01-01T00:00:00.000Z', updatedAt: '2026-01-01T00:00:00.000Z',
+ }],
+ });
+}
+
+// What the scene-video completion hook does when a regenerated clip lands.
+const landNewTake = (projectId, sceneId, assetId) =>
+ projects.appendSceneTakes(projectId, sceneId, [{ kind: 'video', assetId, source: 'generated', provider: 'portos', jobId: `job-${assetId}` }]);
+
+describe('selective section revision (#8987)', () => {
+ it('rejects only the flagged section and leaves every approved section untouched', async () => {
+ const project = await reviewedProject();
+ const r = await request(app).post(`${base(project.id)}/excerpt/mve-draft/revisions`).send({});
+ expect(r.status).toBe(201);
+ const { revision } = r.body;
+ expect(revision.sections.map((s) => [s.sceneId, s.verdict])).toEqual([['s1', 'approved'], ['s2', 'rejected'], ['s3', 'approved']]);
+ expect(revision.sections[1]).toMatchObject({ kind: 'video', rejectedAssetId: 'clip-2', noteIds: ['mvn-bad'] });
+
+ const reloaded = await projects.getProject(project.id);
+ const [s1, s2, s3] = reloaded.scenes;
+ expect(s2.videoHistoryId).toBeNull(); // the rejected clip no longer fills the slot
+ expect(s2.referenceImageId).toBe('f2.png'); // its reference frame is kept for the regeneration
+ expect(s2.takes.find((t) => t.assetId === 'clip-2').status).toBe('rejected');
+ // Approved sections: byte-identical to before the revision.
+ expect(s1).toEqual(project.scenes[0]);
+ expect(s3).toEqual(project.scenes[2]);
+ });
+
+ it('resumes to generate only the rejected section, never a section already holding a take', async () => {
+ const project = await reviewedProject();
+ const { body: { revision } } = await request(app).post(`${base(project.id)}/excerpt/mve-draft/revisions`).send({});
+
+ const first = await request(app).post(`${base(project.id)}/revisions/${revision.id}/resume`);
+ expect(first.status).toBe(200);
+ expect(first.body.needsGeneration).toEqual([{ sceneId: 's2', kind: 'video' }]);
+ expect(first.body.render).toBeNull();
+
+ // The board submitted s2's clip; while that job is live a second resume
+ // (a double click, or a resume after a restart) asks for nothing new.
+ h.jobs.push({ id: 'job-live', kind: 'video', status: 'running', queuedAt: new Date().toISOString(), params: { musicVideo: { projectId: project.id, sceneId: 's2' } } });
+ const again = await request(app).post(`${base(project.id)}/revisions/${revision.id}/resume`);
+ expect(again.body.needsGeneration).toEqual([]);
+ expect(again.body.generating).toEqual([{ sceneId: 's2', kind: 'video' }]);
+ expect(h.procs).toHaveLength(0); // nothing renders until every rejected section has a take
+ expect(h.enqueueJob).not.toHaveBeenCalled();
+ });
+
+ it('retries a failed render without re-submitting any generation, then completes', async () => {
+ const project = await reviewedProject();
+ const { body: { revision } } = await request(app).post(`${base(project.id)}/excerpt/mve-draft/revisions`).send({});
+ await landNewTake(project.id, 's2', 'clip-2b');
+
+ const renderStart = await request(app).post(`${base(project.id)}/revisions/${revision.id}/resume`);
+ expect(renderStart.status).toBe(200);
+ expect(renderStart.body.needsGeneration).toEqual([]);
+ expect(renderStart.body.render.excerptId).toMatch(/^mve-/);
+ expect(renderStart.body.revision.status).toBe('rendering');
+ // The draft re-renders the same window through the same clips.
+ const firstRender = renderStart.body.render.excerptId;
+ const proc = lastProc();
+ proc.emit('spawn');
+ proc.emit('close', 1, null); // ffmpeg fails
+ await settle();
+
+ let reloaded = await projects.getProject(project.id);
+ expect(reloaded.revisions[0]).toMatchObject({ status: 'open', renderAttempts: 1 });
+ expect(reloaded.excerpts.find((e) => e.id === firstRender)).toMatchObject({ status: 'error', partialFilename: null });
+
+ // Retry: s2 already holds its new take, so the retry renders straight away.
+ const retry = await request(app).post(`${base(project.id)}/revisions/${revision.id}/resume`);
+ expect(retry.body.needsGeneration).toEqual([]);
+ expect(retry.body.generating).toEqual([]);
+ expect(h.procs).toHaveLength(2);
+ lastProc().emit('spawn');
+ lastProc().emit('close', 0, null);
+ await settle();
+
+ reloaded = await projects.getProject(project.id);
+ expect(reloaded.revisions[0]).toMatchObject({ status: 'complete', renderAttempts: 2 });
+ expect(reloaded.scenes[1].videoHistoryId).toBe('clip-2b');
+ expect(reloaded.scenes[0].videoHistoryId).toBe('clip-1'); // approved section still untouched
+ expect(h.enqueueJob).not.toHaveBeenCalled(); // zero paid (re)submissions across the retry
+ });
+
+ it('after a restart mid-draft, deletes the partial output and resumes from the checkpoint', async () => {
+ const project = await reviewedProject();
+ const { body: { revision } } = await request(app).post(`${base(project.id)}/excerpt/mve-draft/revisions`).send({});
+ await landNewTake(project.id, 's2', 'clip-2b');
+ // The record exactly as a process killed mid-encode left it: the draft
+ // re-render still 'rendering' with its partial file on disk, the revision
+ // 'rendering' — and (being a fresh process) no live job for either.
+ const partial = 'music-video-excerpt-crashed.mp4';
+ mkdirSync(join(ROOT(), 'videos'), { recursive: true });
+ writeFileSync(join(ROOT(), 'videos', partial), 'half-an-mp4');
+ await projects.mutateProjectRecord(project.id, (current) => ({
+ project: {
+ ...current,
+ excerpts: [...current.excerpts, { id: 'mve-crashed', startSec: 5, endSec: 25, status: 'rendering', jobId: 'mve-crashed', filename: null, contactSheetFilename: null, partialFilename: partial, sections: null, error: null, notes: [] }],
+ revisions: current.revisions.map((r) => ({ ...r, status: 'rendering', renderExcerptId: 'mve-crashed', renderAttempts: 1 })),
+ },
+ }));
+
+ await recoverStuckMusicVideoExcerpts();
+
+ expect(existsSync(join(ROOT(), 'videos', partial))).toBe(false);
+ let reloaded = await projects.getProject(project.id);
+ expect(reloaded.excerpts.find((e) => e.id === 'mve-crashed')).toMatchObject({ status: 'error', partialFilename: null });
+ expect(reloaded.revisions[0]).toMatchObject({ status: 'open', error: expect.stringMatching(/restart/) });
+
+ const resumed = await request(app).post(`${base(project.id)}/revisions/${revision.id}/resume`);
+ expect(resumed.body.needsGeneration).toEqual([]);
+ expect(resumed.body.render).toBeTruthy();
+ reloaded = await projects.getProject(project.id);
+ expect(reloaded.revisions[0]).toMatchObject({ status: 'rendering', renderAttempts: 2 });
+ expect(h.enqueueJob).not.toHaveBeenCalled();
+ lastProc().emit('spawn');
+ lastProc().emit('close', 0, null);
+ await settle();
+ });
+
+ it('cancels a rendering revision, stopping its draft render and removing the partial output', async () => {
+ const project = await reviewedProject();
+ const { body: { revision } } = await request(app).post(`${base(project.id)}/excerpt/mve-draft/revisions`).send({});
+ await landNewTake(project.id, 's2', 'clip-2b');
+ const { body: { render } } = await request(app).post(`${base(project.id)}/revisions/${revision.id}/resume`);
+ lastProc().emit('spawn');
+
+ const canceled = await request(app).post(`${base(project.id)}/revisions/${revision.id}/cancel`);
+ expect(canceled.status).toBe(200);
+ expect(canceled.body.revision.status).toBe('canceled');
+ await settle();
+
+ const reloaded = await projects.getProject(project.id);
+ expect(reloaded.revisions[0].status).toBe('canceled'); // the render's own cancel doesn't reopen it
+ expect(reloaded.excerpts.find((e) => e.id === render.excerptId)).toMatchObject({ status: 'canceled', partialFilename: null });
+ const resume = await request(app).post(`${base(project.id)}/revisions/${revision.id}/resume`);
+ expect(resume.status).toBe(409);
+ });
+
+ it('refuses a second open revision, a section outside the draft, and a draft without a section map', async () => {
+ const project = await reviewedProject();
+ const first = await request(app).post(`${base(project.id)}/excerpt/mve-draft/revisions`).send({ sceneIds: ['s1'] });
+ expect(first.status).toBe(201);
+ const second = await request(app).post(`${base(project.id)}/excerpt/mve-draft/revisions`).send({});
+ expect(second.status).toBe(409);
+ expect(second.body.code).toBe('REVISION_IN_PROGRESS');
+
+ const outside = await request(app).post(`${base(project.id)}/revisions/${first.body.revision.id}/cancel`);
+ expect(outside.status).toBe(200);
+ const notInDraft = await request(app).post(`${base(project.id)}/excerpt/mve-draft/revisions`).send({ sceneIds: ['s9'] });
+ expect(notInDraft.status).toBe(422);
+
+ const legacy = await projects.createProject({ name: 'Legacy' });
+ await projects.updateProject(legacy.id, {
+ excerpts: [{ id: 'mve-old', startSec: 0, endSec: 5, status: 'complete', notes: [{ id: 'n', atSec: 1, note: 'x', verdict: 'flagged' }] }],
+ });
+ const noMap = await request(app).post(`${base(legacy.id)}/excerpt/mve-old/revisions`).send({});
+ expect(noMap.status).toBe(422);
+ expect(noMap.body.code).toBe('EXCERPT_SECTIONS_UNKNOWN');
+ });
+});
diff --git a/server/services/musicVideo/excerpt.js b/server/services/musicVideo/excerpt.js
index c40b514576..082c1c6677 100644
--- a/server/services/musicVideo/excerpt.js
+++ b/server/services/musicVideo/excerpt.js
@@ -53,7 +53,7 @@ function findExcerpt(project, excerptId) {
* project; the render job fills in `filename`/`contactSheetFilename` (or
* `error`) once the encode finishes.
*/
-export function startExcerptOnProject(project, { startSec, endSec }, now = new Date().toISOString()) {
+export function startExcerptOnProject(project, { startSec, endSec, sections = null, partialFilename = null }, now = new Date().toISOString()) {
if (!(startSec >= 0) || !(endSec > startSec) || endSec > MAX_EXCERPT_SEC) {
throw excerptError(422, 'INVALID_EXCERPT_RANGE', 'endSec must be greater than startSec, and both within range');
}
@@ -66,6 +66,13 @@ export function startExcerptOnProject(project, { startSec, endSec }, now = new D
jobId: id,
filename: null,
contactSheetFilename: null,
+ // #8987: the output file an in-flight encode is writing, so boot recovery
+ // can delete a partial file a restart left behind (cleared on every
+ // terminal patch).
+ partialFilename,
+ // #8987: the sections the draft cuts, in ABSOLUTE song time — what a
+ // flagged note maps onto when the director asks for a selective revision.
+ sections: Array.isArray(sections) ? sections : null,
error: null,
notes: [],
createdAt: now,
diff --git a/server/services/musicVideo/excerptRender.js b/server/services/musicVideo/excerptRender.js
index fd5e0fa0e5..a62bc67548 100644
--- a/server/services/musicVideo/excerptRender.js
+++ b/server/services/musicVideo/excerptRender.js
@@ -26,12 +26,14 @@ import { safeChildProcessOptions } from '../../lib/processEnv.js';
import { broadcastSse, attachSseClient as attachSse, closeJobAfterDelay } from '../../lib/sseUtils.js';
import { attachFfmpegRenderGuard } from '../../lib/ffmpegRenderGuard.js';
import { killWithEscalation } from '../../lib/killWithEscalation.js';
+import { safeUnder } from '../../lib/ffmpeg.js';
import { encodeFileContactSheetAtTimes } from '../htmlComposition/encode.js';
import { getProject, listProjects, mutateProjectRecord } from './projects.js';
import { planMusicVideoRender, buildMusicVideoFfmpegArgs, excerptBoundaryTimes } from './render.js';
import { renderableCues, sectionCardCues } from './composition.js';
import { renderTypographyOverlays, removeCompositionScratch } from './compositionRender.js';
import { startExcerptOnProject, applyExcerptPatch } from './excerpt.js';
+import { markRevisionRendering, settleRevisionRender } from './revision.js';
const jobs = new Map();
const projectExcerptRenders = new Map();
@@ -57,8 +59,21 @@ export function cancelExcerptRender(jobId) {
return true;
}
-/** Kick off a draft excerpt render. Returns `{ jobId, excerptId }`. */
-export async function startExcerptRender(projectId, { startSec, endSec }) {
+const round3 = (n) => Math.round(n * 1000) / 1000;
+const sheetFilenameFor = (filename) => `${filename.replace(/\.mp4$/, '')}-sheet.png`;
+// A filename read back off a (possibly peer-synced) record is only ever
+// resolved inside its own media directory.
+const unlinkUnder = (root, filename) => {
+ const path = safeUnder(root, filename);
+ return path ? unlink(path).catch(() => {}) : Promise.resolve();
+};
+
+/**
+ * Kick off a draft excerpt render. Returns `{ jobId, excerptId }`.
+ * `revisionId` (#8987) links the render to an open selective revision in the
+ * same write that creates the excerpt, so its finish settles that revision.
+ */
+export async function startExcerptRender(projectId, { startSec, endSec }, { revisionId = null } = {}) {
const project = await getProject(projectId);
if (!project) throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });
@@ -87,15 +102,25 @@ export async function startExcerptRender(projectId, { startSec, endSec }) {
);
}
const endClamped = Math.min(endSec, probe.totalDuration);
+ const filename = `music-video-excerpt-${projectId.slice(0, 8)}-${Date.now()}.mp4`;
+ const outputPath = join(PATHS.videos, filename);
+ // #8987: the sections this draft cuts, in absolute song time and clipped to
+ // the window — a flagged review note maps onto one of these when the
+ // director asks for a selective revision.
+ const sections = probe.sections
+ .filter((s) => s.startSec < endClamped && s.endSec > startSec)
+ .map((s) => ({ sceneId: s.sceneId, layer: s.layer, startSec: round3(Math.max(s.startSec, startSec)), endSec: round3(Math.min(s.endSec, endClamped)) }));
// Persist the new `status: 'rendering'` excerpt against the FRESHEST
// record (not the `project` snapshot planning read above), so a
- // concurrent note/edit on another excerpt can't be clobbered.
- const { excerpt } = await mutateProjectRecord(projectId, (current) => startExcerptOnProject(current, { startSec, endSec: endClamped }));
+ // concurrent note/edit on another excerpt can't be clobbered. The output
+ // filename is recorded now so a restart mid-encode can delete the partial.
+ const { excerpt } = await mutateProjectRecord(projectId, (current) => {
+ const started = startExcerptOnProject(current, { startSec, endSec: endClamped, sections, partialFilename: filename });
+ return revisionId ? { ...started, project: markRevisionRendering(started.project, revisionId, started.excerpt.id) } : started;
+ });
const excerptId = excerpt.id;
const jobId = excerptId;
- const filename = `music-video-excerpt-${projectId.slice(0, 8)}-${Date.now()}.mp4`;
- const outputPath = join(PATHS.videos, filename);
// Only the cue/card windows overlapping the window are worth capturing —
// typography outside it never survives the final trim.
@@ -123,7 +148,9 @@ export async function startExcerptRender(projectId, { startSec, endSec }) {
// catching up (boot recovery clears a truly stuck one).
const finalize = async (patch) => {
projectExcerptRenders.delete(projectId);
- const persisted = await mutateProjectRecord(projectId, (current) => ({ project: applyExcerptPatch(current, excerptId, patch) }))
+ const persisted = await mutateProjectRecord(projectId, (current) => ({
+ project: settleRevisionRender(applyExcerptPatch(current, excerptId, { ...patch, partialFilename: null }), excerptId, patch),
+ }))
.then(() => true, (err) => {
console.error(`❌ Music-video excerpt render [${jobId.slice(4, 12)}] project ${projectId.slice(0, 8)} status→${patch.status} write failed: ${err.message}`);
return false;
@@ -140,7 +167,7 @@ export async function startExcerptRender(projectId, { startSec, endSec }) {
const buildContactSheet = async () => {
try {
const times = excerptBoundaryTimes(probe.sections, cues, startSec, endClamped, { fps: probe.fps });
- const sheetFilename = `${filename.replace(/\.mp4$/, '')}-sheet.png`;
+ const sheetFilename = sheetFilenameFor(filename);
await encodeFileContactSheetAtTimes(outputPath, join(PATHS.videoThumbnails, sheetFilename), times, { width: probe.canonW, height: probe.canonH, fps: probe.fps });
return sheetFilename;
} catch (err) {
@@ -278,22 +305,35 @@ export async function startExcerptRender(projectId, { startSec, endSec }) {
// render survives a restart — the job map is memory-only. Demote any excerpt
// left `status: 'rendering'` with no live job to `error` so it isn't shown as
// perpetually in-flight (and its slot doesn't 409 every later excerpt render
-// on that project).
+// on that project). #8987: delete the partial video/contact sheet the
+// interrupted encode was writing, and return a selective revision that was
+// rendering that draft to `open` — resumable from its checkpoint, re-rendering
+// without generating anything its sections already hold.
export async function recoverStuckMusicVideoExcerpts() {
const projects = await listProjects();
let recovered = 0;
for (const project of projects) {
const stuck = (project.excerpts || []).filter((e) => e.status === 'rendering' && !projectExcerptRenders.has(project.id));
if (stuck.length === 0) continue;
- await mutateProjectRecord(project.id, (current) => {
+ const ok = await mutateProjectRecord(project.id, (current) => {
let next = current;
for (const excerpt of stuck) {
- next = { ...next, excerpts: (next.excerpts || []).map((e) => (e.id === excerpt.id ? { ...e, status: 'error', error: 'Interrupted by a server restart', jobId: null } : e)) };
+ next = { ...next, excerpts: (next.excerpts || []).map((e) => (e.id === excerpt.id ? { ...e, status: 'error', error: 'Interrupted by a server restart', jobId: null, partialFilename: null } : e)) };
+ next = settleRevisionRender(next, excerpt.id, { status: 'error', error: 'The draft render was interrupted by a server restart' });
}
return { project: next };
- }).then(() => { recovered += stuck.length; }, (err) => {
+ }).then(() => { recovered += stuck.length; return true; }, (err) => {
console.error(`❌ Music Video excerpt recovery: project ${project.id.slice(0, 8)} write failed: ${err.message}`);
+ return false;
});
+ // Only once the record no longer points at them, so a failed write can't
+ // leave a record naming a file that is gone.
+ if (!ok) continue;
+ for (const { partialFilename } of stuck) {
+ if (typeof partialFilename !== 'string' || !partialFilename) continue;
+ await unlinkUnder(PATHS.videos, partialFilename);
+ await unlinkUnder(PATHS.videoThumbnails, sheetFilenameFor(partialFilename));
+ }
}
if (recovered > 0) console.log(`🎬 Music Video excerpt boot recovery: demoted ${recovered} stuck excerpt render(s)`);
}
diff --git a/server/services/musicVideo/projectsLogic.js b/server/services/musicVideo/projectsLogic.js
index 77a17514a1..11a84aeba9 100644
--- a/server/services/musicVideo/projectsLogic.js
+++ b/server/services/musicVideo/projectsLogic.js
@@ -201,6 +201,16 @@ export function cloneProjectRecord(source, {
sourceScenesFingerprint: scenesFingerprint(source.scenes || []),
cloneScenesFingerprint: scenesFingerprint(scenes),
}) : null,
+ // #8987 — a draft's section map follows the scenes to their new ids, so a
+ // clone can still revise from the review notes it carried over (#8986).
+ ...(Array.isArray(source.excerpts) ? {
+ excerpts: source.excerpts.map((excerpt) => (Array.isArray(excerpt?.sections)
+ ? { ...excerpt, sections: excerpt.sections.map((s) => ({ ...s, sceneId: sceneIdMap.get(s.sceneId) ?? s.sceneId })) }
+ : excerpt)),
+ } : {}),
+ // A revision is in-progress work against the SOURCE's takes; the clone
+ // starts with none (its carried-over notes can open a fresh one).
+ revisions: [],
renderHistoryId: null,
deleted: false,
deletedAt: null,
diff --git a/server/services/musicVideo/revision.js b/server/services/musicVideo/revision.js
new file mode 100644
index 0000000000..d972366229
--- /dev/null
+++ b/server/services/musicVideo/revision.js
@@ -0,0 +1,263 @@
+/**
+ * Music Video — selective section revision (#8987, part of #8966): pure record
+ * transforms.
+ *
+ * A director reviews a draft excerpt (#8986), flags the moments that don't
+ * work, and asks for a revision. The revision is a persisted CHECKPOINT on the
+ * project (`project.revisions[]`) that:
+ *
+ * - maps the excerpt's flagged notes onto the sections the draft actually
+ * rendered (`excerpt.sections`, absolute song time) and REJECTS the selected
+ * take of each flagged section — the slot clears, so that section, and only
+ * that section, reads as "needs a take" again (takes.js semantics);
+ * - leaves every other section in the window APPROVED and untouched, with its
+ * selection snapshotted (`keptAssetId`) so the record shows what was kept;
+ * - is resumed by `resumeRevision` (revisionService.js), which re-derives each
+ * rejected section's state from the record plus the media-job queue EVERY
+ * time rather than trusting a stored "submitted" flag. A section whose slot
+ * holds a take is `ready` and is never asked to generate again, whatever
+ * happened to the render — so a rendering retry, a restart, or a second
+ * click can never re-submit paid generation for it.
+ *
+ * Title cards are code-rendered (no paid generation, #8985), so a flagged card
+ * is reported as skipped rather than revised — its fix is an edit, not a take.
+ *
+ * Peer sync: `revisions` (like `excerpts`) is an additive field on the
+ * whole-record LWW project body. An older peer stores it verbatim and has no
+ * route that acts on it, so no `musicVideoProjects` schema bump is needed.
+ */
+
+import { randomUUID } from 'crypto';
+import { ServerError } from '../../lib/errorHandler.js';
+import { isNonBlankStr } from '../../lib/textUtils.js';
+import { ensureSceneTakes, reviewSceneTake, TAKE_SLOT } from './takes.js';
+import { projectExcerpts } from './excerpt.js';
+
+export const REVISION_STATUSES = Object.freeze(['open', 'rendering', 'complete', 'canceled']);
+// A project row carries its recent revisions; the oldest SETTLED ones are
+// dropped past this so a long review loop can't grow one record without bound.
+export const MAX_PROJECT_REVISIONS = 20;
+
+const revisionError = (status, code, message, context) =>
+ new ServerError(message, { status, code, ...(context ? { context } : {}) });
+
+/** The revision array on a project, tolerating a legacy record with none. */
+export const projectRevisions = (project) => (Array.isArray(project?.revisions) ? project.revisions : []);
+
+const isActive = (revision) => revision.status === 'open' || revision.status === 'rendering';
+
+function findRevision(project, revisionId) {
+ const revision = projectRevisions(project).find((r) => r.id === revisionId);
+ if (!revision) throw revisionError(404, 'NOT_FOUND', 'Revision not found');
+ return revision;
+}
+
+function replaceRevision(project, revision) {
+ return { ...project, revisions: projectRevisions(project).map((r) => (r.id === revision.id ? revision : r)) };
+}
+
+function pruneRevisions(revisions) {
+ const next = revisions.slice();
+ for (let i = 0; i < next.length && next.length > MAX_PROJECT_REVISIONS;) {
+ if (isActive(next[i])) i += 1;
+ else next.splice(i, 1);
+ }
+ return next;
+}
+
+// The section a song-time instant falls in. Sections are half-open, except the
+// window's last one also owns its end instant (a note dropped on the final frame).
+function sectionAt(sections, t) {
+ const last = sections[sections.length - 1];
+ return sections.find((s) => t >= s.startSec - 1e-6 && t < s.endSec - 1e-6)
+ || (last && Math.abs(t - last.endSec) <= 1e-6 ? last : null);
+}
+
+/**
+ * Open a revision from one reviewed excerpt. `sceneIds` (optional) names the
+ * sections to reject explicitly; otherwise every section holding a `flagged`
+ * note is rejected. Returns `{ project, revision, skippedSceneIds }`.
+ */
+export function startRevisionOnProject(project, excerptId, { sceneIds } = {}, now = new Date().toISOString()) {
+ const active = projectRevisions(project).find(isActive);
+ if (active) {
+ throw revisionError(409, 'REVISION_IN_PROGRESS', 'Finish or cancel the open revision before starting another', { revisionId: active.id });
+ }
+ const excerpt = projectExcerpts(project).find((e) => e.id === excerptId);
+ if (!excerpt) throw revisionError(404, 'NOT_FOUND', 'Excerpt not found');
+ if (excerpt.status !== 'complete') throw revisionError(409, 'EXCERPT_NOT_READY', 'Only a finished draft excerpt can be revised');
+ const sections = Array.isArray(excerpt.sections) ? excerpt.sections.filter((s) => isNonBlankStr(s?.sceneId)) : null;
+ if (!sections?.length) {
+ throw revisionError(422, 'EXCERPT_SECTIONS_UNKNOWN', 'This draft predates section tracking — render the excerpt again to revise it');
+ }
+ const inWindow = new Set(sections.map((s) => s.sceneId));
+
+ // Notes are timecoded on the excerpt's OWN timeline; sections are in song time.
+ const noteIdsByScene = new Map();
+ for (const note of excerpt.notes || []) {
+ if (note.verdict !== 'flagged') continue;
+ const section = sectionAt(sections, excerpt.startSec + note.atSec);
+ if (!section) continue;
+ noteIdsByScene.set(section.sceneId, [...(noteIdsByScene.get(section.sceneId) || []), note.id]);
+ }
+ let rejectIds;
+ if (Array.isArray(sceneIds)) {
+ const outside = sceneIds.filter((id) => !inWindow.has(id));
+ if (outside.length) throw revisionError(422, 'SCENE_NOT_IN_EXCERPT', 'Every revised section must be part of this draft excerpt', { sceneIds: outside });
+ rejectIds = new Set(sceneIds);
+ } else {
+ rejectIds = new Set(noteIdsByScene.keys());
+ }
+
+ const scenesById = new Map((project.scenes || []).map((s) => [s.sceneId, s]));
+ const skippedSceneIds = [];
+ let next = project;
+ const revisionSections = [];
+ const seen = new Set();
+ for (const section of sections) {
+ if (seen.has(section.sceneId)) continue; // a scene appears once however it was cut
+ seen.add(section.sceneId);
+ const scene = scenesById.get(section.sceneId);
+ if (!scene) continue; // deleted since the draft — nothing left to keep or revise
+ const rejected = rejectIds.has(section.sceneId);
+ if (section.layer === 'card') {
+ if (rejected) skippedSceneIds.push(section.sceneId);
+ continue;
+ }
+ const kind = section.layer === 'still' ? 'image' : 'video';
+ const assetId = isNonBlankStr(scene[TAKE_SLOT[kind]]) ? scene[TAKE_SLOT[kind]] : null;
+ if (rejected && assetId) {
+ // Materialize a legacy selection as a take first, so the take id the
+ // review below resolves is the one persisted (ensureSceneTakes mints
+ // fresh ids on every call for a selection that has no take yet).
+ const idx = next.scenes.findIndex((s) => s.sceneId === section.sceneId);
+ const withTakes = { ...next.scenes[idx], takes: ensureSceneTakes(next.scenes[idx], now) };
+ const scenes = next.scenes.slice();
+ scenes[idx] = withTakes;
+ next = { ...next, scenes };
+ const take = withTakes.takes.find((t) => t.kind === kind && t.assetId === assetId);
+ next = reviewSceneTake(next, section.sceneId, take.takeId, { status: 'rejected' }).project;
+ }
+ revisionSections.push({
+ sceneId: section.sceneId,
+ layer: section.layer,
+ kind,
+ verdict: rejected ? 'rejected' : 'approved',
+ rejectedAssetId: rejected ? assetId : null,
+ keptAssetId: rejected ? null : assetId,
+ noteIds: noteIdsByScene.get(section.sceneId) || [],
+ });
+ }
+ if (!revisionSections.some((s) => s.verdict === 'rejected')) {
+ throw revisionError(422, 'NOTHING_TO_REVISE', skippedSceneIds.length
+ ? 'The flagged sections are title cards — edit their text instead; there is no footage to regenerate'
+ : 'Flag a moment in this draft (or pick a section) before revising it', skippedSceneIds.length ? { skippedSceneIds } : undefined);
+ }
+
+ const revision = {
+ id: `mvr-${randomUUID()}`,
+ excerptId,
+ startSec: excerpt.startSec,
+ endSec: excerpt.endSec,
+ status: 'open',
+ sections: revisionSections,
+ renderExcerptId: null,
+ renderAttempts: 0,
+ error: null,
+ createdAt: now,
+ updatedAt: now,
+ };
+ return {
+ project: { ...next, revisions: pruneRevisions([...projectRevisions(next), revision]), updatedAt: now },
+ revision,
+ skippedSceneIds,
+ };
+}
+
+const tagMatches = (job, projectId, sceneId) =>
+ job?.params?.musicVideo?.projectId === projectId && job.params.musicVideo.sceneId === sceneId;
+
+/**
+ * Pure: each section of a revision with its current `state`:
+ * - `kept` — approved; its selection is untouched;
+ * - `removed` — the scene was deleted since;
+ * - `ready` — the slot holds a take (a new one landed, or the
+ * director selected one) — never generated again;
+ * - `generating` — a generation job for the scene is queued/running, or
+ * finished but its take hasn't attached yet;
+ * - `needs-generation` — nothing selected and nothing in flight.
+ * `jobs` is the media-job queue's list (queued, running and recent archive).
+ */
+export function revisionSectionStates(project, revision, jobs = []) {
+ const scenesById = new Map((project.scenes || []).map((s) => [s.sceneId, s]));
+ return (revision.sections || []).map((section) => {
+ if (section.verdict !== 'rejected') return { ...section, state: 'kept' };
+ const scene = scenesById.get(section.sceneId);
+ if (!scene) return { ...section, state: 'removed' };
+ if (isNonBlankStr(scene[TAKE_SLOT[section.kind]])) return { ...section, state: 'ready' };
+ const takes = Array.isArray(scene.takes) ? scene.takes : [];
+ const pending = jobs.some((job) => job?.kind === section.kind && tagMatches(job, project.id, section.sceneId) && (
+ job.status === 'queued' || job.status === 'running'
+ // Completed after the revision opened, but its take isn't on the scene
+ // yet: the attach hook is still writing it. Asking again would pay twice.
+ || (job.status === 'completed' && typeof job.queuedAt === 'string' && job.queuedAt >= revision.createdAt
+ && !takes.some((t) => t.jobId === job.id))
+ ));
+ return { ...section, state: pending ? 'generating' : 'needs-generation' };
+ });
+}
+
+/** Find a revision that can still be resumed (open, or rendering). Throws 404/409. */
+export function resumableRevision(project, revisionId) {
+ const revision = findRevision(project, revisionId);
+ if (!isActive(revision)) {
+ throw revisionError(409, 'REVISION_CLOSED', `This revision is already ${revision.status}`);
+ }
+ return revision;
+}
+
+/**
+ * Link a draft re-render to an open revision (same write as the excerpt's
+ * creation, so a fast finish can always find the revision it settles).
+ */
+export function markRevisionRendering(project, revisionId, renderExcerptId, now = new Date().toISOString()) {
+ const revision = resumableRevision(project, revisionId);
+ if (revision.status === 'rendering') {
+ const current = projectExcerpts(project).find((e) => e.id === revision.renderExcerptId);
+ if (current?.status === 'rendering') {
+ throw revisionError(409, 'REVISION_RENDERING', 'This revision is already rendering its draft', { excerptId: current.id });
+ }
+ }
+ return replaceRevision(project, {
+ ...revision,
+ status: 'rendering',
+ renderExcerptId,
+ renderAttempts: (revision.renderAttempts || 0) + 1,
+ error: null,
+ updatedAt: now,
+ });
+}
+
+/**
+ * Settle every revision whose draft re-render just ended. `complete` closes the
+ * revision; an error or a cancel returns it to `open` (resumable — the next
+ * resume re-renders without generating anything). A canceled revision stays so.
+ */
+export function settleRevisionRender(project, excerptId, { status, error = null }, now = new Date().toISOString()) {
+ let changed = false;
+ const revisions = projectRevisions(project).map((revision) => {
+ if (revision.renderExcerptId !== excerptId || revision.status !== 'rendering') return revision;
+ changed = true;
+ return status === 'complete'
+ ? { ...revision, status: 'complete', error: null, updatedAt: now }
+ : { ...revision, status: 'open', error: error || 'The draft render was cancelled', updatedAt: now };
+ });
+ return changed ? { ...project, revisions } : project;
+}
+
+/** Cancel a revision. Its rejected takes stay rejected — the director can re-select one. */
+export function cancelRevisionOnProject(project, revisionId, now = new Date().toISOString()) {
+ const revision = resumableRevision(project, revisionId);
+ const next = { ...revision, status: 'canceled', updatedAt: now };
+ return { project: replaceRevision(project, next), revision: next, renderExcerptId: revision.status === 'rendering' ? revision.renderExcerptId : null };
+}
diff --git a/server/services/musicVideo/revisionService.js b/server/services/musicVideo/revisionService.js
new file mode 100644
index 0000000000..d5fb74e8f9
--- /dev/null
+++ b/server/services/musicVideo/revisionService.js
@@ -0,0 +1,73 @@
+/**
+ * Music Video — selective section revision I/O (#8987) over the pure
+ * transforms in `revision.js`.
+ *
+ * The lifecycle is a resumable checkpoint, driven by explicit director actions
+ * (never by boot — no paid generation is ever queued on its own):
+ *
+ * start → reject the flagged sections' selected takes, keep the rest;
+ * resume → re-derive every rejected section's state from the record and the
+ * media-job queue. Sections still without a take are returned as
+ * `needsGeneration` (the director's board generates exactly those,
+ * through the normal scene lanes); once every one holds a take, the
+ * draft window is re-rendered. A section that holds a take is never
+ * in `needsGeneration`, so retrying a failed/cancelled/interrupted
+ * render generates nothing;
+ * cancel → close the revision and stop its draft render if one is running.
+ *
+ * Every record write goes through `mutateProjectRecord`, so each transform runs
+ * against the freshest record under the backend's write serialization.
+ */
+
+import { ServerError } from '../../lib/errorHandler.js';
+import { getProject, mutateProjectRecord } from './projects.js';
+import { cancelExcerptRender, startExcerptRender } from './excerptRender.js';
+import {
+ cancelRevisionOnProject,
+ projectRevisions,
+ resumableRevision,
+ revisionSectionStates,
+ startRevisionOnProject,
+} from './revision.js';
+
+const sceneRef = ({ sceneId, kind }) => ({ sceneId, kind });
+
+/** Open a revision from a reviewed excerpt. Returns `{ project, revision, skippedSceneIds }`. */
+export async function startRevision(projectId, excerptId, input = {}) {
+ return mutateProjectRecord(projectId, (current) => startRevisionOnProject(current, excerptId, input));
+}
+
+/**
+ * Continue a revision from its checkpoint. Returns
+ * `{ project, revision, needsGeneration, generating, render }` — `render` is the
+ * draft re-render's `{ jobId, excerptId }` when every rejected section already
+ * holds a take, otherwise null.
+ */
+export async function resumeRevision(projectId, revisionId) {
+ const project = await getProject(projectId);
+ if (!project) throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });
+ const revision = resumableRevision(project, revisionId);
+ // Deferred: the queue module's closure is large and only this path needs it.
+ const { listJobs } = await import('../mediaJobQueue/index.js');
+ const jobs = [...listJobs({ kind: 'video' }), ...listJobs({ kind: 'image' })];
+ const sections = revisionSectionStates(project, revision, jobs);
+ const needsGeneration = sections.filter((s) => s.state === 'needs-generation').map(sceneRef);
+ const generating = sections.filter((s) => s.state === 'generating').map(sceneRef);
+ if (needsGeneration.length || generating.length) {
+ return { project, revision: { ...revision, sections }, needsGeneration, generating, render: null };
+ }
+ // Every rejected section holds a take: re-render the draft window. The
+ // excerpt render links itself to the revision in its creation write (and
+ // refuses one that closed or is already rendering meanwhile).
+ const render = await startExcerptRender(projectId, { startSec: revision.startSec, endSec: revision.endSec }, { revisionId });
+ const fresh = await getProject(projectId);
+ const current = projectRevisions(fresh).find((r) => r.id === revisionId) || revision;
+ return { project: fresh, revision: { ...current, sections: revisionSectionStates(fresh, current, jobs) }, needsGeneration: [], generating: [], render };
+}
+
+/** Cancel a revision; a draft render it started is cancelled too. Returns `{ project, revision }`. */
+export async function cancelRevision(projectId, revisionId) {
+ const { project, revision, renderExcerptId } = await mutateProjectRecord(projectId, (current) => cancelRevisionOnProject(current, revisionId));
+ if (renderExcerptId) cancelExcerptRender(renderExcerptId);
+ return { project, revision };
+}