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: repair failed performance suffixes while preserving accepted footage (#9348)

[._.]/ Adam Eivy1e1deff9f566
diff --git a/client/src/components/musicVideo/PerformanceEvidence.jsx b/client/src/components/musicVideo/PerformanceEvidence.jsx
index a1d7e756ed..567269838d 100644
--- a/client/src/components/musicVideo/PerformanceEvidence.jsx
+++ b/client/src/components/musicVideo/PerformanceEvidence.jsx
@@ -1,10 +1,10 @@
import { useEffect, useRef, useState } from 'react';
-import { formatTimecode } from '../../utils/formatters.js';
+import { formatTimecode, formatUsd } from '../../utils/formatters.js';
/** One transport: muted output picture against the take's recorded source.
* Word windows are clip-relative; temporal evidence is excerpt-relative.
*/
-export default function PerformanceEvidence({ clipSrc, instruction, temporal = null, excerptStartSec = 0 }) {
+export default function PerformanceEvidence({ clipSrc, instruction, temporal = null, excerptStartSec = 0, repair = null, onRepair, repairBusy = false }) {
const video = useRef(null);
const audio = useRef(null);
const [sourceMuted, setSourceMuted] = useState(false);
@@ -64,6 +64,14 @@ export default function PerformanceEvidence({ clipSrc, instruction, temporal = n
</div>
<p className="text-port-text-muted">Temporal lip-sync: {temporal?.lipSync || 'unverified'}{temporal?.analyzer ? ` · ${temporal.analyzer.id} ${temporal.analyzer.version}` : ' · review needed'}</p>
{temporal && <p className="text-port-text-muted">Measured evidence: {temporal.status}</p>}
+ {repair && <div className="rounded border border-port-border p-2 space-y-1" aria-label="Suffix repair">
+ {repair.ok && onRepair ? <>
+ <p>Keep accepted prefix through {formatTimecode(repair.boundarySec)}. Continue only {formatTimecode(repair.boundarySec)}–{formatTimecode(repair.endSec)} (song time).</p>
+ <p>Next spend: {formatUsd(repair.costUsd)} · one generation · accepted boundary frame</p>
+ <button type="button" disabled={repairBusy} onClick={onRepair}
+ className="rounded border border-port-border px-2 py-1 min-h-[44px] sm:min-h-0 disabled:opacity-50">{repairBusy ? 'Repairing…' : 'Repair from here'}</button>
+ </> : <p className="text-port-warning">{repair.ok ? 'Review needed: update the authored composition edit points before continuing' : repair.message}</p>}
+ </div>}
<ul className="space-y-1" aria-label="Temporal evidence spans">
{spans.map((span, i) => (
<li key={i}>
diff --git a/client/src/components/musicVideo/PerformanceEvidence.test.jsx b/client/src/components/musicVideo/PerformanceEvidence.test.jsx
index 6b365a01dd..55685ddb35 100644
--- a/client/src/components/musicVideo/PerformanceEvidence.test.jsx
+++ b/client/src/components/musicVideo/PerformanceEvidence.test.jsx
@@ -45,3 +45,20 @@ describe('PerformanceEvidence', () => {
expect(screen.getByText(/Recorded source unavailable/)).toBeTruthy();
});
});
+
+// This interaction verifies the spend/boundary shown before the explicit
+// submission, and that inconclusive evidence cannot expose a repair action.
+it('shows the accepted boundary and next spend, disables duplicate clicks, and requires a conclusive repair plan', () => {
+ const onRepair = vi.fn();
+ const repair = { ok: true, boundarySec: 14, endSec: 24, costUsd: 1.6 };
+ const view = render(<PerformanceEvidence clipSrc="/example.mp4" instruction={instruction} repair={repair} onRepair={onRepair} />);
+ expect(screen.getByText(/Continue only 0:14.00–0:24.00/)).toBeTruthy();
+ expect(screen.getByText(/Next spend: \$1.60/)).toBeTruthy();
+ fireEvent.click(screen.getByRole('button', { name: 'Repair from here' }));
+ expect(onRepair).toHaveBeenCalledTimes(1);
+ view.rerender(<PerformanceEvidence instruction={instruction} repair={repair} onRepair={onRepair} repairBusy />);
+ expect(screen.getByRole('button', { name: 'Repairing…' }).disabled).toBe(true);
+ view.rerender(<PerformanceEvidence instruction={instruction} repair={{ ok: false, message: 'Review needed: evidence is inconclusive' }} onRepair={onRepair} />);
+ expect(screen.queryByRole('button', { name: 'Repair from here' })).toBeNull();
+ expect(screen.getByText(/evidence is inconclusive/)).toBeTruthy();
+});
diff --git a/client/src/components/musicVideo/RevisionPanel.jsx b/client/src/components/musicVideo/RevisionPanel.jsx
index 67c7128564..bcf075d5bf 100644
--- a/client/src/components/musicVideo/RevisionPanel.jsx
+++ b/client/src/components/musicVideo/RevisionPanel.jsx
@@ -11,11 +11,12 @@ export const currentRevision = (project) => {
// 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) {
+function sectionState(section, scene, spinning, repair) {
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' };
+ if (repair?.submitted) return { label: 'Reserved repair — review if interrupted', tone: 'text-port-warning' };
return { label: 'Needs a new take', tone: 'text-port-error' };
}
@@ -62,7 +63,7 @@ export default function RevisionPanel({ project, busy, genScenes = {}, genVideoS
{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);
+ const state = sectionState(section, entry?.scene, spinning, revision.repair);
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>
diff --git a/client/src/components/musicVideo/SceneCard.jsx b/client/src/components/musicVideo/SceneCard.jsx
index 73a29b1c60..869eb826e7 100644
--- a/client/src/components/musicVideo/SceneCard.jsx
+++ b/client/src/components/musicVideo/SceneCard.jsx
@@ -5,6 +5,7 @@ import { Trash2, Activity, ArrowUp, ArrowDown, ChevronRight, Image as ImageIcon,
import { formatDurationSec, formatUsd } from '../../utils/formatters.js';
import { useVideoFileSrc } from '../../hooks/useVideoFileSrc.js';
import PerformanceEvidence from './PerformanceEvidence.jsx';
+import { planPerformanceRepair } from '../../lib/musicVideoShotTiming.js';
import SceneTakeStrip from './SceneTakeStrip.jsx';
import { MUSIC_VIDEO_VISUAL_LAYERS, sceneHasAuthoredSpan } from '../../lib/musicVideoLayers.js';
@@ -69,7 +70,7 @@ export default function SceneCard({
onMove, onDelete, onEditLocal, onSave,
onGenerateFrame, onGenerateVideo, onContinueVideo,
onOpenPreview, onSelectTake, onReviewTake, onImportTake, onImportClipTake, takeBusy = false, layered = false,
- lipSyncBackend = '', songDurationSec = null, onSplit, falVideoSettings = null, onSeek, performanceReview = null,
+ lipSyncBackend = '', songDurationSec = null, onSplit, falVideoSettings = null, onSeek, performanceReview = null, onRepairPerformance, repairBusy = false,
}) {
// Pause the inline clip before opening the lightbox so the user can't hear
// two desynced copies — MediaLightbox autoplays unmuted, and the thumb's
@@ -120,6 +121,8 @@ export default function SceneCard({
const splitLimit = layer === 'footage' ? shotSplitLimit(scene, lipSyncBackend) : null;
const canSplit = splitLimit != null && timedSpan != null && timedSpan > splitLimit + 1e-6;
const instruction = scene.takes?.find((take) => take.kind === 'video' && take.assetId === scene.videoHistoryId)?.shotInstruction;
+ const repairPlan = planPerformanceRepair({ scene, temporal: performanceReview?.shot,
+ excerptStartSec: performanceReview?.excerptStartSec, backend: lipSyncBackend, videoSettings: falVideoSettings || {} });
const shotModeId = `mv-shot-mode-${scene.sceneId}`;
return (
<details className="group min-w-0 rounded-lg border border-port-border bg-port-card">
@@ -368,7 +371,11 @@ export default function SceneCard({
<div className="flex items-center gap-2 flex-wrap">
{scene.videoHistoryId && performance && (
<PerformanceEvidence key={scene.videoHistoryId} clipSrc={clipSrc} instruction={instruction}
- temporal={performanceReview?.shot} excerptStartSec={performanceReview?.excerptStartSec || 0} />
+ temporal={performanceReview?.shot} excerptStartSec={performanceReview?.excerptStartSec || 0}
+ repair={repairPlan} repairBusy={repairBusy || settingsSaving || generatingVideo || takeBusy}
+ onRepair={onRepairPerformance ? () => onRepairPerformance(scene.sceneId, {
+ excerptId: performanceReview.excerptId, sourceAssetId: repairPlan.sourceAssetId, boundarySec: repairPlan.boundarySec,
+ }) : null} />
)}
{scene.videoHistoryId && !performance && (
<div className="relative w-40 shrink-0">
diff --git a/client/src/components/musicVideo/stages/BoardStage.jsx b/client/src/components/musicVideo/stages/BoardStage.jsx
index 0d7d37badd..da18a771e1 100644
--- a/client/src/components/musicVideo/stages/BoardStage.jsx
+++ b/client/src/components/musicVideo/stages/BoardStage.jsx
@@ -22,6 +22,7 @@ export default function BoardStage({ board }) {
if (!performanceReviews.has(key)) performanceReviews.set(key, {
shot: { ...shot, status: temporal.status, lipSync: attempt.review.checks?.lipSync, analyzer: temporal.analyzer },
excerptStartSec: attempt.review.evidence.excerptStartSec,
+ excerptId: attempt.excerptId,
});
}
}
@@ -63,6 +64,8 @@ export default function BoardStage({ board }) {
onMove={board.moveScene}
onDelete={board.onDeleteScene}
onSplit={board.onSplitScene}
+ onRepairPerformance={['code', 'document'].includes(project.composition?.mode) ? null : board.onRepairPerformance}
+ repairBusy={board.repairBusy || videoSettings.saving}
onEditLocal={board.editSceneLocal}
onSave={board.saveScene}
onGenerateFrame={sceneMedia.generateFrame}
diff --git a/client/src/hooks/useMusicVideoRevisions.js b/client/src/hooks/useMusicVideoRevisions.js
index 397c4ae128..7ac2751987 100644
--- a/client/src/hooks/useMusicVideoRevisions.js
+++ b/client/src/hooks/useMusicVideoRevisions.js
@@ -3,6 +3,7 @@ import toast from '../components/ui/Toast';
import {
startMusicVideoDependencyRepair,
startMusicVideoRevision,
+ repairMusicVideoPerformance,
resumeMusicVideoRevision,
cancelMusicVideoRevision,
releaseMusicVideoRevisionSection,
@@ -86,6 +87,10 @@ export default function useMusicVideoRevisions({ project, replaceProject, sceneM
toast.info('Every revised section has a new take — rendering the revised draft');
return res;
}
+ if (res.revision?.sections?.some((section) => section.state === 'review-needed')) {
+ toast.info('Repair needs review — its reserved generation has no usable take; it will not submit again');
+ return res;
+ }
const submitted = await generateSections(res.project, res.needsGeneration || [], revisionId);
const waiting = (res.generating || []).length;
const parts = [
@@ -108,6 +113,10 @@ export default function useMusicVideoRevisions({ project, replaceProject, sceneM
const revise = (excerptId, sceneIds) => startRevision(excerptId, sceneIds)
.then((res) => (res?.revision ? resume(res.revision.id) : null));
+ const repairPerformance = (sceneId, input) => run(() => repairMusicVideoPerformance(projectId, sceneId, input, { silent: true })
+ .then((res) => { replaceProject(res.project); return res; }))
+ .then((res) => res?.revision ? resume(res.revision.id) : null);
+
const cancel = (revisionId) => run(() => cancelMusicVideoRevision(projectId, revisionId, { silent: true })
.then((res) => {
replaceProject(res.project);
@@ -123,5 +132,5 @@ export default function useMusicVideoRevisions({ project, replaceProject, sceneM
// Also used by an opt-in auto-review run (#8988), which hands its revised
// sections to the open board over the `music-video:auto-review` event.
- return { busy, repair, revise, resume, cancel, submitSections: generateSections };
+ return { busy, repair, repairPerformance, revise, resume, cancel, submitSections: generateSections };
}
diff --git a/client/src/lib/README.md b/client/src/lib/README.md
index 8e6ac9f4c1..05ec29d44e 100644
--- a/client/src/lib/README.md
+++ b/client/src/lib/README.md
@@ -63,7 +63,7 @@ grep -i "what you want to do" client/src/lib/README.md
| `musicVideoMotion.js` | Re-export of `server/lib/musicVideoMotion.js` (`MOTION_CONTINUITY_CLAUSE`) for board motion prompts. |
| `musicVideoLayers.js` | Music-video per-scene visual layers (#8985), re-exported from `server/lib/musicVideoLayers.js`: `MUSIC_VIDEO_VISUAL_LAYERS`, `MUSIC_VIDEO_STILL_MOVES`, `sceneVisualLayer(scene, { layered })`, `sceneHasAuthoredSpan`, `sceneRenderReady(scene, { layered })`. Used by `components/musicVideo/SceneCard.jsx`, `ProjectActionGroups.jsx` and `hooks/useMusicVideoSceneMedia.js`. |
| `musicVideoTakes.js` | Music-video scene takes view helpers (#8965): `sceneTakeList(scene, kind)` lists a scene's image/video takes with an un-materialized pre-takes selection appended as a read-only `legacy` take; `takePreviewKey`, `takeThumbUrl`, `takeProvenance`; `TAKE_SLOT` maps a take kind to its selection field. Used by `components/musicVideo/SceneTakeStrip.jsx` and `pages/MusicVideo.jsx`. |
-| `musicVideoShotTiming.js` | Re-export of `server/lib/musicVideoShotTiming.js` (#8977) — shot modes, the verified source-audio lip-sync capability table, `performanceBlockedReason`, `planPerformanceWindow`, `grokCoverage`, `approximateMotionCues`, `shotSplitLimit` (when a scene offers a lyric-boundary split), `falSceneTake` (a fal take's model, length, resolution and estimated cost). Used by `hooks/useMusicVideoSceneMedia.js` and `components/musicVideo/SceneCard.jsx`. |
+| `musicVideoShotTiming.js` | Re-export of `server/lib/musicVideoShotTiming.js` (#8977) — shot modes, the verified source-audio lip-sync capability table, `performanceBlockedReason`, `planPerformanceRepair` (measured accepted-prefix boundary, suffix interval and next spend), `planPerformanceWindow`, `grokCoverage`, `approximateMotionCues`, `shotSplitLimit` (when a scene offers a lyric-boundary split), `falSceneTake` (a fal take's model, length, resolution and estimated cost). Used by `hooks/useMusicVideoSceneMedia.js` and `components/musicVideo/SceneCard.jsx`. |
| `musicVideoStages.js` | Music Video page stage model: `MUSIC_VIDEO_STAGES` (setup → cast-sets → board → produce → compose → review), `resolveStageParam(value)` for the `:stage` route param, `deriveStages(project)` (per-stage `done`/`active`/`blocked`/`todo` + `current`, the first incomplete stage; a live production run pins Produce), `deriveNextAction(project, ctx)` (the one primary action the sticky header offers — approve Cast & Sets, stop/resume production, render final, …), `projectSpend(project)` (paid generation used vs. cap) and `currentProductionRun`. Used by `components/musicVideo/MusicVideoLayout.jsx` and `pages/MusicVideo.jsx`. |
| `musicVideoUniverseRefs.js` | `pullUniverseCanonReferences(universe, existingReferences)` (#8978) maps a linked universe's characters/places/objects to visual-spec references (character/set/prop roles), skipping images already present and capping at `MUSIC_VIDEO_MAX_REFERENCES` (24, mirrors the server schema). Returns `{ next, added, skipped }`; the caller persists `next` via the ordinary visualSpec PATCH. Used by `components/musicVideo/VisualSpecPanel.jsx`. (The style snapshots are derived server-side, #9105.) |
| `musicVideoAutomation.js` | Music Video automation brief, client half: re-exports the server tool catalog (`MUSIC_VIDEO_AUTOMATION_TOOLS` / `_TOOL_IDS`), `DEFAULT_AUTOMATION_TOOLS` (the unmetered tools), and the form mapping `automationDraftFrom(automation)` / `automationFromDraft(draft)` (empty budget = no cap). Used by the create drawer and `AutopilotPanel`. |
diff --git a/client/src/lib/musicVideoShotTiming.js b/client/src/lib/musicVideoShotTiming.js
index 171add9f78..d68934c1dd 100644
--- a/client/src/lib/musicVideoShotTiming.js
+++ b/client/src/lib/musicVideoShotTiming.js
@@ -17,5 +17,6 @@ export {
performanceBlockedReason,
performanceCapability,
planPerformanceWindow,
+ planPerformanceRepair,
shotSplitLimit,
} from '../../../server/lib/musicVideoShotTiming.js';
diff --git a/client/src/pages/MusicVideo.jsx b/client/src/pages/MusicVideo.jsx
index e6097aaeea..0a908549e0 100644
--- a/client/src/pages/MusicVideo.jsx
+++ b/client/src/pages/MusicVideo.jsx
@@ -830,6 +830,8 @@ export default function MusicVideo() {
onAddScene: handleAddScene,
onDeleteScene: handleDeleteScene,
onSplitScene: handleSplitScene,
+ onRepairPerformance: revisions.repairPerformance,
+ repairBusy: revisions.busy,
onRenderStyle: (mode) => {
const composition = compositionDraft(selected, { mode });
editProjectLocal({ composition });
diff --git a/client/src/services/apiMusicVideo.js b/client/src/services/apiMusicVideo.js
index 61fa9b0c0a..7069fdff9f 100644
--- a/client/src/services/apiMusicVideo.js
+++ b/client/src/services/apiMusicVideo.js
@@ -401,3 +401,8 @@ export const getMusicVideoDependencyImpact = (id, options = {}) =>
request(`/music-video/${encodeURIComponent(id)}/dependency-impact`, options);
export const startMusicVideoDependencyRepair = (id, basis, options = {}) =>
request(`/music-video/${encodeURIComponent(id)}/dependency-repairs`, { method: 'POST', body: JSON.stringify({ basis }), ...options });
+
+export const repairMusicVideoPerformance = (id, sceneId, input, options = {}) =>
+ request(`/music-video/${encodeURIComponent(id)}/scenes/${encodeURIComponent(sceneId)}/performance-repair`, {
+ method: 'POST', body: JSON.stringify(input), ...options,
+ });
diff --git a/docs/features/music-video-temporal-evidence.md b/docs/features/music-video-temporal-evidence.md
index f8f89938fb..a14e2e09a2 100644
--- a/docs/features/music-video-temporal-evidence.md
+++ b/docs/features/music-video-temporal-evidence.md
@@ -71,3 +71,26 @@ Analyzer identity/version, shot/source provenance, measured offsets/confidence
and spans persist in existing auto-review records. Excerpts snapshot performance
provenance when rendering begins, so later board edits cannot relabel evidence.
The project sync schema is version-gated; older takes need no data migration.
+
+## Repair a measured performance suffix
+
+After stopping or finishing a review/production run, the Board evidence inspector
+can offer **Repair from here** for the latest measured take. It shows the song-time
+boundary, remaining audio interval and estimated next spend before submitting.
+The boundary must lie in a real word gap inside an accepted prefix; every remaining
+span must have a measured offset above 0.12 seconds. Incomplete evidence, missing
+word timings, changed audio, unsupported providers and suffixes outside the
+provider's limits stay review-needed. There is no backward audio padding and no
+whole-take fallback. Authored code/document compositions and timed action contracts
+need their own edit review before this continuation route is available.
+
+Repair keeps the original clip as an accepted-prefix scene with explicit edit
+points, captures its last accepted frame, and creates a contiguous suffix scene.
+The checkpoint retains the original take, source interval, boundary, reference
+frame time and generated continuation provenance. Resume submits only that suffix
+through the normal revision/media queue. Its durable reservation permits one paid
+generation; duplicate clicks, cancellation and ambiguous restarts cannot submit it
+again. A synchronous enqueue failure with no durable job refunds the reservation.
+Once the suffix take lands, Resume renders the revised draft using both original
+prefix footage and the continuation. Retrying the draft render generates no video.
+Existing active run budgets cannot be bypassed by opening a manual repair.
diff --git a/server/lib/README.md b/server/lib/README.md
index 71edc18275..f662aa8094 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -303,7 +303,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `grok.js` | xAI Grok Build (`grok`) provider helpers — id/endpoint constants (`GROK_API_ID`/`GROK_CLI_ID`/`GROK_TUI_ID`/`GROK_API_ENDPOINT`), `isGrokCommand`/`isGrokCliProvider`/`isGrokTuiProvider` predicates, `ensureGrokHeadlessArgs`/`ensureGrokTuiArgs` argv builders (grok reads its prompt from `--prompt-file /dev/stdin`, not raw stdin; model selection uses the `GROK_CONFIGURED_DEFAULT` sentinel in `providerModels.js` so PortOS omits `--model` like Antigravity), and `prepareGrokPromptFile` (Windows temp-file delivery fallback). |
| `falVideoModels.js` | Curated fal.ai VIDEO model catalog — `FAL_VIDEO_MODELS` (Hailuo-02 standard t2v/i2v default, MiniMax H3 Max/Max Turbo i2v, H3 reference-to-video, H3 lip-sync, Seedance 2.5 t2v/i2v/reference, Kling v3 Pro i2v, Veo 3.1 Fast i2v) with per-model duration rules (enum/range/audio), resolutions, aspect ratios, optional inputs and list prices verified on `FAL_VIDEO_PRICING_VERIFIED_AT`; `getFalVideoModel()`, `coerceFalVideoSeconds()` (round UP to a covering length), `resolveFalVideoResolution()`, `buildFalVideoRequest()` (the exact queue body per model; null for an uncurated id, which keeps the legacy body), `estimateFalVideoCostUsd()` (null = unknown), `describeFalVideoRate()`. Dependency-free; the client re-exports it. |
| `grokVideoClip.js` | Clip lengths grok's `image_to_video` actually delivers — `GROK_VIDEO_DURATIONS` (`[6, 10]`, measured in #3022: a 2s/3s request returns the same 6.04s clip), `GROK_VIDEO_DEFAULT_DURATION`, `resolveGrokDuration()` (validate an already-grok-shaped request, else default), and `nearestGrokDuration()` (round a length authored against another backend's continuous contract UP to the shortest clip that covers it — for translating a CD/commission `targetDurationSeconds`). Dependency-free so `validation.js` / `routes/videoGen.js` can derive their schemas from the same list the services gate on. |
-| `musicVideoShotTiming.js` | Music Video shot modes (#8977): `MUSIC_VIDEO_SHOT_MODES` (`cutaway`/`performance`), `isPerformanceScene`, `selectedPerformanceInstruction(scene)` (the selected take's shot instruction, performance scenes only), `SOURCE_AUDIO_LIPSYNC` (verified source-audio lip-sync lanes — only fal.ai MiniMax H3 lip-sync, 5–30s per take, default 1080P), `falSceneTake()` (the fal model/length/resolution a scene take requests and its estimated cost — shared by the board, the submit path and the autopilot spend cap) + `falTakeRequestFields(take)` (that take as `/api/video-gen` fields), `performanceCapability(backend)`, `performanceBlockedReason(backend)` (Grok is cutaway-only), `planPerformanceWindow()` (provider-bounded audio window + clip-relative edit in/out points; refuses over-long shots instead of relying on provider truncation), `clipRelativeCues()`, `grokCoverage(spanSec)` (covering 6/10s request, flags spans needing a split), `approximateMotionCues()`, `shotSplitLimit(scene, backend)` (per-take limit: lip-sync window or Grok's longest clip), `planShotSplit()` (contiguous pieces cut at lyric pauses → line/phrase boundaries → beats; one extra piece at most to avoid cutting a sung line). Dependency-free; the client re-exports it. |
+| `musicVideoShotTiming.js` | Music Video shot modes (#8977): `MUSIC_VIDEO_SHOT_MODES` (`cutaway`/`performance`), `isPerformanceScene`, `selectedPerformanceInstruction(scene)` (the selected take's shot instruction, performance scenes only), `SOURCE_AUDIO_LIPSYNC` (verified source-audio lip-sync lanes — only fal.ai MiniMax H3 lip-sync, 5–30s per take, default 1080P), `falSceneTake()` (the fal model/length/resolution a scene take requests and its estimated cost — shared by the board, the submit path and the autopilot spend cap) + `falTakeRequestFields(take)` (that take as `/api/video-gen` fields), `performanceCapability(backend)`, `performanceBlockedReason(backend)` (Grok is cutaway-only), `planPerformanceWindow()` (provider-bounded audio window + clip-relative edit in/out points; refuses over-long shots instead of relying on provider truncation), `planPerformanceRepair()` (complete measured suffix evidence, safe word-gap boundary, source/clip timebases and next spend), `clipRelativeCues()`, `grokCoverage(spanSec)` (covering 6/10s request, flags spans needing a split), `approximateMotionCues()`, `shotSplitLimit(scene, backend)` (per-take limit: lip-sync window or Grok's longest clip), `planShotSplit()` (contiguous pieces cut at lyric pauses → line/phrase boundaries → beats; one extra piece at most to avoid cutting a sung line). Dependency-free; the client re-exports it. |
| `reactorStartingFrame.js` | Fits a reactor.inc `starting_frame` to the fast-h3 session canvas before it is uploaded. `readImageSize(path)` → `{width,height}` or `null` (never a guessed dimension), and `prepareReactorStartingFrame(sourceImagePath, requestedAspect, outputPath)` → `{ aspect, canvas, framePath, fittedPath }`: an absent `requestedAspect` DERIVES the canvas from the frame's own shape (`nearestReactorAspect`), then centre cover-crops the frame to that canvas's exact pixel size so reactor's own "fitted to the session canvas" step is a no-op. `fittedPath` is the temp file the caller deletes; `null` means the original was uploaded unchanged. A frame sharp cannot decode (or a resize that fails) passes through untouched on the default canvas rather than failing a render PortOS merely could not measure — reactor decodes more containers than sharp does. |
| `reactorVideoClip.js` | The reactor.inc `fast-h3` clip contract, dependency-free so the route schema, the FableLoom prompt compiler and the VideoGen picker all read one copy — `REACTOR_MAX_PROMPT_LENGTH` (800; the API rejects a longer prompt rather than truncating it), `REACTOR_MIN_CLIP_SECONDS` / `REACTOR_MAX_CLIP_SECONDS` (5.167–14.375, i.e. 124–345 frames at the `REACTOR_CLIP_FPS` 24 it delivers), `REACTOR_MAX_CLIP_ID_LENGTH`, and the picker list `REACTOR_CLIP_LENGTHS` + `REACTOR_DEFAULT_CLIP_LENGTH` + `reactorClipLengthLabel()` (the two exact endpoints plus every whole second between them, since the accepted range is continuous but starts and ends off a round number). Also the CANVAS contract `set_canvas` accepts: `REACTOR_CANVASES` (`16:9` 1344×768, `4:3` 1024×768, `1:1` 768×768, `9:16` 768×1344 — every one a 768px short edge, so the aspect string is the whole choice), `REACTOR_ASPECTS`, `REACTOR_DEFAULT_ASPECT`, `reactorCanvas(aspect)` and `nearestReactorAspect(width, height)` (closest canvas in log-ratio space; anything unmeasurable answers the default rather than deriving one). Mirrored to `client/src/lib/reactorVideoClip.js`, parity pinned by `reactorVideoClip.test.js`. |
| `kimi.js` | Moonshot AI Kimi Code (`kimi`) provider helpers — id constants (`KIMI_CLI_ID`/`KIMI_TUI_ID`), `isKimiCommand`/`isKimiCliProvider`/`isKimiTuiProvider` predicates, `ensureKimiHeadlessArgs` (model flag only — non-interactive mode is implicit in `--prompt`, and kimi has no `--print`/`--afk` and refuses approval flags alongside `--prompt`) / `ensureKimiTuiArgs` (`--yolo`) argv builders (model selection uses the `KIMI_CONFIGURED_DEFAULT` sentinel in `providerModels.js` so PortOS omits `--model` like Grok/Antigravity), and `prepareKimiPrompt` (delivers the prompt as the `--prompt <value>` argv, not stdin). |
diff --git a/server/lib/musicVideoShotTiming.js b/server/lib/musicVideoShotTiming.js
index 2f1f7693ea..5d2d7b9768 100644
--- a/server/lib/musicVideoShotTiming.js
+++ b/server/lib/musicVideoShotTiming.js
@@ -437,3 +437,56 @@ export const falTakeRequestFields = (take) => (take.performance
...(take.seconds != null ? { falDuration: take.seconds } : {}),
...(take.resolution ? { falResolution: take.resolution } : {}),
});
+
+/** A repair needs measured complete coverage and a genuine pause between words.
+ * Returned times distinguish song, excerpt and provider-clip timebases.
+ * No padding: accepted audio must never be sent for generation again.
+ */
+export function planPerformanceRepair({ scene, temporal, excerptStartSec, backend, videoSettings = {} }) {
+ const no = (message) => ({ ok: false, message });
+ const instruction = selectedPerformanceInstruction(scene);
+ const capability = performanceCapability(backend);
+ if (!capability) return no(performanceBlockedReason(backend));
+ if (!instruction || instruction.songInterval?.startSec !== scene.startSec || instruction.songInterval?.endSec !== scene.endSec) return no('Review needed: the selected take no longer matches this shot');
+ if (scene.direction?.actionContract || scene.performanceRepair) return no('Review needed: edit the shot contract or review the existing continuation before repairing again');
+ if (temporal?.status !== 'verified' || !temporal.analyzer || temporal.takeId !== scene.videoHistoryId || !Number.isFinite(excerptStartSec)) return no('Review needed: complete measured temporal evidence is required');
+ const spans = Array.isArray(temporal.spans) ? temporal.spans : [];
+ if (!spans.length || spans.length > 256) return no('Review needed: temporal coverage is missing or unbounded');
+ let cursor = scene.startSec;
+ let failedAt = null;
+ for (const span of spans) {
+ const start = span.startSec + excerptStartSec;
+ const end = span.endSec + excerptStartSec;
+ if (span.status !== 'verified' || !Number.isFinite(span.offsetSec) || !Number.isFinite(span.confidence) || !(span.confidence >= 0.8 && span.confidence <= 1)
+ || !Number.isFinite(end) || end <= start || Math.abs(start - cursor) > 0.001 || end > scene.endSec + 0.001) return no('Review needed: temporal coverage is incomplete or inconclusive');
+ const failed = Math.abs(span.offsetSec) > 0.12;
+ if (failed && failedAt === null) failedAt = start;
+ if (!failed && failedAt !== null) return no('Review needed: the failure is not confined to a suffix');
+ cursor = end;
+ }
+ if (Math.abs(cursor - scene.endSec) > 0.001 || failedAt === null || failedAt <= scene.startSec) return no('Review needed: no accepted prefix and failed suffix were measured');
+ const windowStart = instruction.audioWindow?.startSec;
+ if (!Number.isFinite(windowStart) || Math.abs(windowStart + instruction.edit.inSec - scene.startSec) > 0.001
+ || Math.abs(windowStart + instruction.edit.outSec - scene.endSec) > 0.001) return no('Review needed: the source audio timebase is missing');
+ const cues = (instruction.cues || []).filter((cue) => cue.endSec + windowStart > scene.startSec && cue.startSec + windowStart < scene.endSec);
+ if (!cues.length || cues.some((cue) => !cue.words?.length)) return no('Review needed: word timings are required to choose a safe boundary');
+ const words = cues.flatMap((cue) => cue.words).slice().sort((a, b) => a.startSec - b.startSec);
+ if (words.some((word) => !Number.isFinite(word.startSec) || !Number.isFinite(word.endSec) || word.endSec <= word.startSec)) return no('Review needed: word timings are invalid');
+ let boundarySec = null;
+ for (let i = 1; i < words.length; i += 1) {
+ const left = words[i - 1].endSec + windowStart;
+ const right = words[i].startSec + windowStart;
+ const boundary = round6((left + right) / 2);
+ // A gap is not safe if another overlapping word crosses it.
+ if (right - left < 0.02 || words.some((word) => word.startSec + windowStart < boundary && word.endSec + windowStart > boundary)) continue;
+ const suffixSec = scene.endSec - boundary;
+ if (boundary - scene.startSec >= 0.4 && boundary <= failedAt && suffixSec >= capability.minAudioSec + PERFORMANCE_WINDOW_MARGIN_SEC
+ && suffixSec <= capability.maxAudioSec - PERFORMANCE_WINDOW_MARGIN_SEC) boundarySec = boundary;
+ }
+ if (boundarySec === null) return no('Review needed: no word gap leaves a supported suffix window; choose another reviewed shot boundary');
+ const suffix = { ...scene, startSec: boundarySec };
+ const take = falSceneTake({ scene: suffix, videoSettings, songDurationSec: instruction.audio?.songDurationSec });
+ return { ok: true, boundarySec, endSec: scene.endSec, suffixSec: round6(scene.endSec - boundarySec),
+ referenceClipSec: round6(instruction.edit.inSec + boundarySec - scene.startSec),
+ costUsd: take?.costUsd ?? null, sourceAssetId: scene.videoHistoryId };
+}
diff --git a/server/lib/musicVideoShotTiming.test.js b/server/lib/musicVideoShotTiming.test.js
index 63e15165a4..57e2f4f3e5 100644
--- a/server/lib/musicVideoShotTiming.test.js
+++ b/server/lib/musicVideoShotTiming.test.js
@@ -84,3 +84,37 @@ describe('shotSplitLimit', () => {
expect(shotSplitLimit({ shotMode: 'cutaway', visualLayer: 'still' }, 'grok')).toBeNull();
});
});
+
+// Each failure variant is a distinct admission regression: evidence, word
+// gap, provider minimum, or timebase mismatch must never resubmit a prefix.
+describe('accepted-prefix repair planning', () => {
+ const scene = { shotMode: 'performance', sceneId: 'example', videoHistoryId: 'clip', startSec: 10, endSec: 24,
+ takes: [{ kind: 'video', assetId: 'clip', shotInstruction: { shotMode: 'performance',
+ songInterval: { startSec: 10, endSec: 24 }, audio: { songDurationSec: 30 }, audioWindow: { startSec: 8 },
+ edit: { inSec: 2, outSec: 16 }, cues: [{ startSec: 2, endSec: 16, words: [
+ { startSec: 2, endSec: 5.8 }, { startSec: 6.2, endSec: 16 },
+ ] }] } }] };
+ const temporal = { status: 'verified', takeId: 'clip', analyzer: { id: 'synthetic' }, spans: [
+ { startSec: 2, endSec: 6, status: 'verified', offsetSec: 0.01, confidence: 0.95 },
+ { startSec: 6, endSec: 16, status: 'verified', offsetSec: 0.3, confidence: 0.95 },
+ ] };
+ it('maps excerpt evidence and clip-relative words to the exact source suffix and reference frame', async () => {
+ const { planPerformanceRepair } = await import('./musicVideoShotTiming.js');
+ expect(planPerformanceRepair({ scene, temporal, excerptStartSec: 8, backend: 'fal' }))
+ .toMatchObject({ ok: true, boundarySec: 14, endSec: 24, suffixSec: 10, referenceClipSec: 6, costUsd: 1.6 });
+ });
+ it('rejects inconclusive/partial evidence, unsafe word gaps, short suffixes and unsupported routes', async () => {
+ const { planPerformanceRepair } = await import('./musicVideoShotTiming.js');
+ const plan = (overrides = {}) => planPerformanceRepair({ scene, temporal, excerptStartSec: 8, backend: 'fal', ...overrides });
+ expect(plan({ temporal: { ...temporal, status: 'unverified' } }).ok).toBe(false);
+ expect(plan({ temporal: { ...temporal, spans: [{ ...temporal.spans[0], confidence: null }, temporal.spans[1]] } }).ok).toBe(false);
+ expect(plan({ excerptStartSec: 8.1 }).ok).toBe(false);
+ expect(plan({ backend: 'grok' }).ok).toBe(false);
+ const unsafe = structuredClone(scene);
+ unsafe.takes[0].shotInstruction.cues[0].words[0].endSec = 6.3;
+ expect(plan({ scene: unsafe }).ok).toBe(false);
+ const short = structuredClone(scene);
+ short.takes[0].shotInstruction.cues[0].words = [{ startSec: 2, endSec: 12 }, { startSec: 12.2, endSec: 16 }];
+ expect(plan({ scene: short }).ok).toBe(false);
+ });
+});
diff --git a/server/lib/musicVideoValidation.js b/server/lib/musicVideoValidation.js
index bdc46aed02..efcb047d8c 100644
--- a/server/lib/musicVideoValidation.js
+++ b/server/lib/musicVideoValidation.js
@@ -1007,3 +1007,9 @@ export const musicVideoAudioAnalysisSchema = z.object({
endSec: z.number().min(0),
}).nullable().optional(),
}).strict();
+
+export const musicVideoPerformanceRepairSchema = z.object({
+ excerptId: z.string().min(1).max(200),
+ sourceAssetId: z.string().min(1).max(200),
+ boundarySec: z.number().finite().min(0).max(36000),
+}).strict();
diff --git a/server/routes/musicVideo.js b/server/routes/musicVideo.js
index b397eb3598..0278d70dfe 100644
--- a/server/routes/musicVideo.js
+++ b/server/routes/musicVideo.js
@@ -48,6 +48,7 @@ import {
musicVideoExcerptNoteUpdateSchema,
musicVideoDependencyRepairSchema,
musicVideoRevisionStartSchema,
+ musicVideoPerformanceRepairSchema,
musicVideoRevisionReleaseSchema,
musicVideoAutoReviewStartSchema,
musicVideoAutoReviewResumeSchema,
@@ -731,6 +732,12 @@ router.delete('/:id/excerpt/:excerptId/notes/:noteId', asyncHandler(async (req,
res.json(await deleteReviewNote(req.params.id, req.params.excerptId, req.params.noteId));
}));
+router.post('/:id/scenes/:sceneId/performance-repair', asyncHandler(async (req, res) => {
+ const input = validateRequest(musicVideoPerformanceRepairSchema, req.body || {});
+ const { startPerformanceRepair } = await import('../services/musicVideo/performanceRepair.js');
+ res.status(201).json(await startPerformanceRepair(req.params.id, req.params.sceneId, input));
+}));
+
// --- 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
diff --git a/server/routes/musicVideoRevision.test.js b/server/routes/musicVideoRevision.test.js
index 94cf1df6a5..f03b26ad43 100644
--- a/server/routes/musicVideoRevision.test.js
+++ b/server/routes/musicVideoRevision.test.js
@@ -39,6 +39,11 @@ const h = vi.hoisted(() => {
});
vi.mock('../lib/childProcess.js', async (importOriginal) => ({ ...(await importOriginal()), spawn: h.spawn }));
+vi.mock('../services/musicVideo/performanceShot.js', () => ({ assertCurrentPerformanceTakes: vi.fn(async () => {}) }));
+vi.mock('../services/videoGen/local.js', () => ({ loadHistory: vi.fn(async () => []), getHistoryItem: vi.fn(async () => ({ filename: 'accepted.mp4', fps: 24 })) }));
+vi.mock('../lib/ffmpeg.js', async (original) => ({ ...(await original()), findFfmpeg: vi.fn(async () => 'ffmpeg'),
+ runFfmpegProcess: vi.fn(async ({ args }) => { writeFileSync(args.at(-1), 'synthetic-boundary-frame'); return { ok: true }; }),
+}));
vi.mock('../lib/sseUtils.js', () => ({ broadcastSse: vi.fn(), attachSseClient: vi.fn(() => true), closeJobAfterDelay: vi.fn() }));
// The draft render stamps this install's id on its in-flight mark (#9010).
vi.mock('../services/instanceIdentity.js', () => ({ ensureInstanceId: vi.fn(async () => 'inst-test') }));
@@ -57,13 +62,14 @@ const CLIPS = [
];
vi.mock('../services/musicVideo/render.js', async (importOriginal) => ({
...(await importOriginal()),
+ resolveMasterAudioPath: vi.fn(async () => '/example/song.wav'),
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 { assertRevisionOpen } = await import('../services/musicVideo/revisionService.js');
+const { assertRevisionOpen, assertPerformanceRepairDispatch } = await import('../services/musicVideo/revisionService.js');
const app = express();
app.use(express.json());
@@ -395,3 +401,78 @@ describe('selective section revision (#8987)', () => {
expect(noMap.body.code).toBe('EXCERPT_SECTIONS_UNKNOWN');
});
});
+
+// This regression uniquely pins accepted-prefix persistence and a durable paid
+// submission reservation through the real HTTP revision boundary and store.
+async function performanceProject() {
+ const created = await projects.createProject({ name: 'Example Performance' });
+ const instruction = { shotMode: 'performance', songInterval: { startSec: 10, endSec: 24 },
+ audio: { songDurationSec: 30 }, audioWindow: { startSec: 10, endSec: 24, durationSec: 14 },
+ edit: { inSec: 0, outSec: 14, targetSec: 14 },
+ cues: [{ startSec: 0, endSec: 14, words: [{ text: 'one', startSec: 0, endSec: 3.8 }, { text: 'two', startSec: 4.2, endSec: 14 }] }] };
+ mkdirSync(join(ROOT(), 'videos'), { recursive: true });
+ writeFileSync(join(ROOT(), 'videos', 'accepted.mp4'), 'synthetic-source');
+ return projects.updateProject(created.id, {
+ videoSettings: { backend: 'fal' },
+ scenes: [{ sceneId: 'performance', order: 0, shotMode: 'performance', startSec: 10, endSec: 24,
+ referenceImageId: 'frame.png', videoHistoryId: 'accepted', takes: [{ takeId: 'take-original', kind: 'video', assetId: 'accepted', shotInstruction: instruction }] }],
+ excerpts: [{ id: 'mve-performance', startSec: 8, endSec: 24, status: 'complete',
+ sections: [{ sceneId: 'performance', layer: 'footage', startSec: 10, endSec: 24, performance: { takeId: 'accepted' } }], notes: [] }],
+ autoReviews: [{ id: 'review-example', status: 'needs-human', attempts: [{ excerptId: 'mve-performance', review: {
+ evidence: { excerptStartSec: 8, temporal: { status: 'verified', analyzer: { id: 'synthetic', version: '1' },
+ shots: [{ sceneId: 'performance', takeId: 'accepted', spans: [
+ { startSec: 2, endSec: 6, status: 'verified', offsetSec: 0.01, confidence: 0.95 },
+ { startSec: 6, endSec: 16, status: 'verified', offsetSec: 0.3, confidence: 0.95 },
+ ] }] } } } }] }],
+ });
+}
+const repairInput = { excerptId: 'mve-performance', sourceAssetId: 'accepted', boundarySec: 14 };
+describe('accepted-prefix performance repair (#9348)', () => {
+ it('persists only a suffix revision, preserves draft provenance, and never pays twice after a restart or cancellation', async () => {
+ const project = await performanceProject();
+ const path = `${base(project.id)}/scenes/performance/performance-repair`;
+ const [a, b] = await Promise.all([request(app).post(path).send(repairInput), request(app).post(path).send(repairInput)]);
+ expect([a.status, b.status].sort()).toEqual([201, 409]);
+ const repaired = (a.status === 201 ? a : b).body;
+ const [prefix, suffix] = repaired.project.scenes;
+ expect(prefix).toMatchObject({ videoHistoryId: 'accepted', startSec: 10, endSec: 14 });
+ expect(prefix.takes[0].shotInstruction.edit).toEqual({ inSec: 0, outSec: 4, targetSec: 4 });
+ expect(repaired.project.excerpts).toEqual(project.excerpts);
+ expect(repaired.revision.repair).toMatchObject({ originalTake: project.scenes[0].takes[0], generations: 0, maxGenerations: 1 });
+ const revisionId = repaired.revision.id;
+ const resumed = await request(app).post(`${base(project.id)}/revisions/${revisionId}/resume`);
+ expect(resumed.body.needsGeneration).toEqual([{ sceneId: suffix.sceneId, kind: 'video' }]);
+ const guard = () => assertRevisionOpen(project.id, revisionId, { sceneId: suffix.sceneId, kind: 'video' });
+ const results = await Promise.allSettled([guard(), guard()]);
+ expect(results.map((r) => r.status).sort()).toEqual(['fulfilled', 'rejected']);
+ expect(results.find((r) => r.status === 'rejected').reason.code).toBe('PERFORMANCE_REPAIR_SPEND_LIMIT');
+ // As on a restart, the queue knows no job, but the durable reservation
+ // survives. Even lease expiry must not create another paid request.
+ await projects.mutateProjectRecord(project.id, (current) => ({ project: { ...current,
+ revisions: current.revisions.map((r) => ({ ...r, sections: r.sections.map((section) => ({ ...section, claimedAt: null })) })),
+ } }));
+ const restart = await request(app).post(`${base(project.id)}/revisions/${revisionId}/resume`);
+ expect(restart.body.needsGeneration).toEqual([]);
+ expect(restart.body.render).toBeNull();
+ expect(restart.body.revision.sections.find((s) => s.sceneId === suffix.sceneId).state).toBe('review-needed');
+ await request(app).post(`${base(project.id)}/revisions/${revisionId}/cancel`);
+ await expect(guard()).rejects.toMatchObject({ code: 'REVISION_CLOSED' });
+ await expect(assertPerformanceRepairDispatch({ projectId: project.id, revisionId, sceneId: suffix.sceneId })).rejects.toMatchObject({ code: 'REVISION_CLOSED' });
+ expect(h.enqueueJob).not.toHaveBeenCalled();
+ });
+
+ it('refuses inconclusive evidence, stale boundaries, and attempts to bypass an existing run budget without changing the scene', async () => {
+ const project = await performanceProject();
+ const path = `${base(project.id)}/scenes/performance/performance-repair`;
+ const stale = await request(app).post(path).send({ ...repairInput, boundarySec: 14.1 });
+ expect(stale.status).toBe(409);
+ await projects.mutateProjectRecord(project.id, (current) => ({ project: { ...current, autoReviews: current.autoReviews.map((r) => ({ ...r, status: 'limit-reached' })) } }));
+ expect((await request(app).post(path).send(repairInput)).status).toBe(409);
+ await projects.mutateProjectRecord(project.id, (current) => ({ project: { ...current, autoReviews: current.autoReviews.map((r) => ({ ...r, status: 'needs-human', attempts: r.attempts.map((a) => ({ ...a,
+ review: { ...a.review, evidence: { ...a.review.evidence, temporal: { ...a.review.evidence.temporal, status: 'unverified' } } },
+ })) })) } }));
+ expect((await request(app).post(path).send(repairInput)).status).toBe(409);
+ expect((await projects.getProject(project.id)).scenes).toEqual(project.scenes);
+ expect(h.enqueueJob).not.toHaveBeenCalled();
+ });
+});
diff --git a/server/services/mediaJobQueue/index.js b/server/services/mediaJobQueue/index.js
index e04d05f243..a3839634d1 100644
--- a/server/services/mediaJobQueue/index.js
+++ b/server/services/mediaJobQueue/index.js
@@ -1257,6 +1257,10 @@ async function runJobLifecycle(job, markDispatched) {
const { assertVideoAttemptDispatch } = await import('../creativeDirector/videoExecution.js');
await assertVideoAttemptDispatch(job.params.videoProduction.projectId, job.params.videoProduction.attemptId, { jobId: job.id });
}
+ if (job.params?.shotInstruction?.repair && job.params?.musicVideo) {
+ const { assertPerformanceRepairDispatch } = await import('../musicVideo/revisionService.js');
+ await assertPerformanceRepairDispatch(job.params.musicVideo);
+ }
if (!mod) throw new Error(`Unknown job kind: ${job.kind}`);
// A cancel that arrived while this job was still queued lives on the
// persisted marker, not on any in-memory adapter state. Re-stamp it for
diff --git a/server/services/mediaJobQueue/index.test.js b/server/services/mediaJobQueue/index.test.js
index 9f51ddadd6..43557becb3 100644
--- a/server/services/mediaJobQueue/index.test.js
+++ b/server/services/mediaJobQueue/index.test.js
@@ -85,6 +85,8 @@ const stubs = {
cancelComposition: vi.fn(),
};
+vi.mock('../musicVideo/revisionService.js', () => ({ assertPerformanceRepairDispatch: vi.fn().mockResolvedValue(undefined) }));
+
vi.mock('../creativeDirector/videoExecution.js', () => ({
assertVideoAttemptDispatch: vi.fn().mockResolvedValue(undefined),
settleVideoAttempt: vi.fn().mockResolvedValue(undefined),
@@ -794,6 +796,17 @@ describe('mediaJobQueue', () => {
await waitFor(() => mediaJobQueue.getJob(job.jobId).status === 'completed');
});
+ it('refuses a canceled suffix repair at provider dispatch without paying again', async () => {
+ const { assertPerformanceRepairDispatch } = await import('../musicVideo/revisionService.js');
+ assertPerformanceRepairDispatch.mockRejectedValueOnce(new Error('This repair revision is canceled'));
+ const job = await mediaJobQueue.enqueueJob({ kind: 'video', params: {
+ prompt: 'Example continuation', musicVideo: { projectId: 'example-project', sceneId: 'example-suffix', revisionId: 'example-revision' },
+ shotInstruction: { repair: { role: 'continuation' } },
+ } });
+ await waitFor(() => mediaJobQueue.getJob(job.jobId).status === 'failed');
+ expect(stubs.generateVideo).not.toHaveBeenCalled();
+ });
+
it('cancels during dispatch validation without invoking the provider and cleans staged uploads', async () => {
const { assertVideoAttemptDispatch } = await import('../creativeDirector/videoExecution.js');
let releaseDispatch;
diff --git a/server/services/musicVideo/performanceRepair.js b/server/services/musicVideo/performanceRepair.js
new file mode 100644
index 0000000000..f2b19ef517
--- /dev/null
+++ b/server/services/musicVideo/performanceRepair.js
@@ -0,0 +1,109 @@
+/** Explicit, one-generation suffix repair over the existing revision workflow.
+ * The accepted picture stays in its original file; two authored scene edit
+ * points compose it with the continuation without baking or replacing it.
+ */
+import { randomUUID } from 'crypto';
+import { existsSync } from 'fs';
+import { unlink } from 'fs/promises';
+import { join } from 'path';
+import { ServerError } from '../../lib/errorHandler.js';
+import { ensureDir, PATHS } from '../../lib/fileUtils.js';
+import { findFfmpeg, probeVideoStreamInfo, runFfmpegProcess, safeUnder } from '../../lib/ffmpeg.js';
+import { canonicalSnapshotChecksum } from '../../lib/snapshotChecksum.js';
+import { planPerformanceRepair } from '../../lib/musicVideoShotTiming.js';
+import { getProject, mutateProjectRecord } from './projects.js';
+import { startRevisionOnProject } from './revision.js';
+
+const refuse = (message, code = 'PERFORMANCE_REPAIR_REVIEW_NEEDED') => new ServerError(message, { status: 409, code });
+const basis = (project) => canonicalSnapshotChecksum({ trackId: project.trackId, uploadedAudioFilename: project.uploadedAudioFilename, performanceConditioningSource: project.performanceConditioningSource, vocalStemFilename: project.vocalStemFilename, scenes: project.scenes, videoSettings: project.videoSettings,
+ lyricCues: project.lyricCues, composition: project.composition, autoReviews: project.autoReviews, productionRuns: project.productionRuns, revisions: project.revisions });
+
+function repairContext(project, sceneId, input) {
+ const scene = project?.scenes?.find((s) => s.sceneId === sceneId);
+ if (!scene) throw new ServerError('Scene not found', { status: 404, code: 'NOT_FOUND' });
+ if (['code', 'document'].includes(project.composition?.mode)) throw refuse('Review needed: update the authored composition document to preserve its edit points');
+ if ((project.productionRuns || []).some((run) => ['running', 'stopped', 'limit-reached', 'blocked'].includes(run.status))
+ || (project.autoReviews || []).some((run) => ['running', 'stopped', 'limit-reached'].includes(run.status))) {
+ throw refuse('Finish or cancel the existing budgeted run before requesting a manual repair');
+ }
+ const attempts = (project.autoReviews || []).flatMap((run) => run.attempts || []).slice().reverse();
+ const attempt = attempts.find((a) => a.review?.evidence?.temporal?.shots?.some((shot) => shot.sceneId === sceneId && shot.takeId === scene.videoHistoryId));
+ if (attempt?.excerptId !== input.excerptId) throw refuse('Review the latest temporal evidence before choosing a repair boundary', 'PERFORMANCE_REPAIR_STALE');
+ const evidence = attempt?.review?.evidence;
+ const temporal = evidence?.temporal;
+ const shot = temporal?.shots?.find((s) => s.sceneId === sceneId && s.takeId === scene.videoHistoryId);
+ const plan = planPerformanceRepair({ scene, temporal: shot ? { ...shot, status: temporal.status, analyzer: temporal.analyzer } : null,
+ excerptStartSec: evidence?.excerptStartSec, backend: project.videoSettings?.backend, videoSettings: project.videoSettings });
+ if (!plan.ok) throw refuse(plan.message);
+ if (input.sourceAssetId !== plan.sourceAssetId || input.boundarySec !== plan.boundarySec) throw refuse('The repair boundary changed — review the latest evidence', 'PERFORMANCE_REPAIR_STALE');
+ const excerpt = project.excerpts?.find((e) => e.id === input.excerptId);
+ if (!excerpt || excerpt.status !== 'complete') throw refuse('The reviewed draft is unavailable');
+ const section = excerpt.sections?.find((s) => s.sceneId === sceneId);
+ if (!section || section.startSec !== scene.startSec || section.endSec !== scene.endSec
+ || section.performance?.takeId !== scene.videoHistoryId) throw refuse('The draft does not contain this complete selected performance shot');
+ return { scene, plan, excerpt };
+}
+
+/** Pure checkpoint transform, run under the persisted project's write lock. */
+export function startPerformanceRepairOnProject(project, sceneId, input, referenceImageId, referenceFrameSec = null) {
+ const { scene, plan, excerpt } = repairContext(project, sceneId, input);
+ const originalTake = scene.takes.find((t) => t.kind === 'video' && t.assetId === scene.videoHistoryId);
+ const suffixSceneId = `mvs-${randomUUID()}`;
+ const provenance = { version: 1, sourceSceneId: sceneId, sourceAssetId: scene.videoHistoryId,
+ sourceTakeId: originalTake.takeId, referenceFrameSec: referenceFrameSec ?? Math.max(originalTake.shotInstruction.edit.inSec, plan.referenceClipSec - 1 / 24), excerptId: excerpt.id, boundarySec: plan.boundarySec, referenceClipSec: plan.referenceClipSec,
+ sourceInterval: { startSec: scene.startSec, endSec: scene.endSec } };
+ const prefixInstruction = structuredClone(originalTake.shotInstruction);
+ prefixInstruction.songInterval.endSec = plan.boundarySec;
+ prefixInstruction.edit.outSec = plan.referenceClipSec;
+ prefixInstruction.edit.targetSec = plan.boundarySec - scene.startSec;
+ prefixInstruction.repair = { ...provenance, role: 'accepted-prefix' };
+ // The original immutable take is captured on the revision. The prefix uses a
+ // derived take with the same source bytes and its shorter composition edit.
+ const prefix = { ...scene, endSec: plan.boundarySec, beatAligned: false, loop: false,
+ takes: scene.takes.map((t) => t === originalTake ? { ...t, takeId: `mvt-${randomUUID()}`, source: 'accepted-prefix', shotInstruction: prefixInstruction } : t) };
+ const suffix = { ...scene, sceneId: suffixSceneId, startSec: plan.boundarySec, beatAligned: false, loop: false,
+ referenceImageId, videoHistoryId: null, takes: [], performanceRepair: provenance };
+ const scenes = project.scenes.flatMap((s) => s.sceneId === sceneId ? [prefix, suffix] : [s]).map((s, order) => ({ ...s, order }));
+ const sections = excerpt.sections.flatMap((s) => s.sceneId === sceneId ? [
+ { ...s, endSec: plan.boundarySec }, { ...s, sceneId: suffixSceneId, startSec: plan.boundarySec, performance: null },
+ ] : [s]);
+ const next = { ...project, scenes, excerpts: project.excerpts.map((e) => e.id === excerpt.id ? { ...e, sections } : e) };
+ const started = startRevisionOnProject(next, excerpt.id, { sceneIds: [suffixSceneId] });
+ const repair = { ...provenance, suffixSceneId, originalTake: structuredClone(originalTake),
+ maxGenerations: 1, generations: 0, costUsd: plan.costUsd, submitted: false };
+ const revision = { ...started.revision, repair };
+ return { ...started, revision, project: { ...started.project, excerpts: project.excerpts,
+ scenes: started.project.scenes.map((s) => s.sceneId === suffixSceneId ? { ...s, performanceRepair: { ...provenance, revisionId: revision.id } } : s),
+ revisions: started.project.revisions.map((r) => r.id === revision.id ? revision : r) } };
+}
+
+/** Prepare only a local boundary frame, then atomically open the checkpoint.
+ * No provider call occurs here. Generation uses the ordinary revision resume.
+ */
+export async function startPerformanceRepair(projectId, sceneId, input) {
+ const project = await getProject(projectId);
+ const { scene, plan } = repairContext(project, sceneId, input);
+ const { assertCurrentPerformanceTakes } = await import('./performanceShot.js');
+ const { resolveMasterAudioPath } = await import('./render.js');
+ await assertCurrentPerformanceTakes(project, await resolveMasterAudioPath(project));
+ const { getHistoryItem } = await import('../videoGen/local.js');
+ const entry = await getHistoryItem(scene.videoHistoryId);
+ const path = entry?.filename ? safeUnder(PATHS.videos, entry.filename) : null;
+ const ffmpeg = await findFfmpeg();
+ if (!path || !existsSync(path) || !ffmpeg) throw refuse('Review needed: the accepted clip or frame extractor is unavailable');
+ await ensureDir(PATHS.images);
+ const filename = `mv-repair-${randomUUID()}.png`;
+ const output = join(PATHS.images, filename);
+ const fps = entry.fps || (await probeVideoStreamInfo(path)).fps;
+ if (!Number.isFinite(fps) || fps <= 0) throw refuse('Review needed: the accepted clip has no verified frame rate');
+ const referenceFrameSec = Math.max(scene.takes.find((take) => take.assetId === scene.videoHistoryId)?.shotInstruction?.edit?.inSec || 0, plan.referenceClipSec - 1 / fps);
+ const result = await runFfmpegProcess({ bin: ffmpeg, signal: AbortSignal.timeout(30_000), args: ['-v', 'error', '-i', path, '-ss', String(referenceFrameSec), '-frames:v', '1', '-y', output] });
+ if (!result.ok || !existsSync(output)) {
+ await unlink(output).catch(() => {});
+ throw refuse('Review needed: the accepted boundary frame could not be extracted');
+ }
+ return mutateProjectRecord(projectId, (current) => {
+ if (basis(current) !== basis(project)) throw refuse('The project changed during frame preparation — review it again', 'PERFORMANCE_REPAIR_STALE');
+ return startPerformanceRepairOnProject(current, sceneId, input, filename, referenceFrameSec);
+ }).catch(async (error) => { await unlink(output).catch(() => {}); throw error; });
+}
diff --git a/server/services/musicVideo/performanceShot.js b/server/services/musicVideo/performanceShot.js
index 3cef6f9012..f67aedda1d 100644
--- a/server/services/musicVideo/performanceShot.js
+++ b/server/services/musicVideo/performanceShot.js
@@ -242,6 +242,12 @@ export async function preparePerformanceShot({ musicVideo, backend, sourceImageP
// before and the completion hook refuses to attach it to a deleted scene.
assertShotActionContract(scene);
if (!isPerformanceScene(scene)) return null;
+ if (scene.performanceRepair) {
+ const { assertRevisionOpenForGeneration } = await import('./revision.js');
+ if (musicVideo.revisionId !== scene.performanceRepair.revisionId) throw refuse('A continuation must use its reserved repair revision', 'PERFORMANCE_REPAIR_REVISION_REQUIRED', 409);
+ assertRevisionOpenForGeneration(project, musicVideo.revisionId, { sceneId: scene.sceneId, kind: 'video' });
+ if (!sourceImagePath || basename(sourceImagePath) !== scene.referenceImageId) throw refuse('Use the accepted boundary frame for this continuation', 'PERFORMANCE_REPAIR_STALE', 409);
+ }
const capability = performanceCapability(backend);
if (!capability) throw refuse(performanceBlockedReason(backend), 'MUSIC_VIDEO_PERFORMANCE_UNSUPPORTED');
@@ -255,10 +261,14 @@ export async function preparePerformanceShot({ musicVideo, backend, sourceImageP
// submission (the common case) never needs.
const { resolveMasterAudioPath } = await import('./render.js');
const masterPath = await resolveMasterAudioPath(project);
+ if (scene.performanceRepair) await assertCurrentPerformanceTakes(project, masterPath);
const songDurationSec = await probeVideoDuration(masterPath);
if (songDurationSec == null) throw refuse('Could not read the song duration for this performance shot', 'MUSIC_VIDEO_AUDIO_UNREADABLE');
const plan = planPerformanceWindow({ startSec: scene.startSec, endSec: scene.endSec, songDurationSec, capability });
if (!plan.ok) throw refuse(plan.message, plan.code);
+ if (scene.performanceRepair && (plan.windowStartSec !== scene.startSec || plan.windowEndSec !== scene.endSec)) {
+ throw refuse('Review needed: this provider cannot continue only the remaining audio interval', 'PERFORMANCE_REPAIR_REVIEW_NEEDED', 409);
+ }
const offered = getFalVideoModel(capability.modelId)?.resolution?.options || capability.resolutions || [];
const pick = (value) => (typeof value === 'string' ? offered.find((o) => o.toLowerCase() === value.trim().toLowerCase()) : null);
const takeResolution = pick(resolution) || pick(project.videoSettings?.falLipSyncResolution) || capability.defaultResolution;
@@ -303,6 +313,7 @@ export async function preparePerformanceShot({ musicVideo, backend, sourceImageP
const transcription = capability.transcription === true && project.videoSettings?.falLipSyncTranscription !== false;
const shotInstruction = {
version: SHOT_INSTRUCTION_VERSION,
+ ...(scene.performanceRepair ? { repair: { ...scene.performanceRepair, role: 'continuation' } } : {}),
shotMode: 'performance',
createdAt: new Date().toISOString(),
speaker: scene.performanceSpeaker || null,
diff --git a/server/services/musicVideo/performanceShot.test.js b/server/services/musicVideo/performanceShot.test.js
index 47d1c0c56d..5b1b26fea6 100644
--- a/server/services/musicVideo/performanceShot.test.js
+++ b/server/services/musicVideo/performanceShot.test.js
@@ -347,3 +347,90 @@ describe.skipIf(!ffmpeg)('music-video performance shot through the fal lip-sync
expect(fetchMock).not.toHaveBeenCalled();
});
});
+
+// Real sample slicing and ffmpeg render: this uniquely catches regeneration of
+// accepted audio or movement/replacement of the original prefix picture.
+describe.skipIf(!ffmpeg)('accepted-prefix continuation render (#9348)', () => {
+ it('submits only the remaining source interval and renders the original accepted frames', async () => {
+ const original = project({ startSec: 10, endSec: 24, videoHistoryId: 'accepted', referenceImageId: 'frame.png', beatAligned: true });
+ getProject.mockResolvedValue(original);
+ const full = await preparePerformanceShot({ musicVideo: { projectId: 'mv-1', sceneId: 'mvs-1' }, backend: 'fal', sourceImagePath: join(PATHS.images, 'frame.png'), mode: 'image' });
+ const instruction = { ...full.shotInstruction, cues: [{ startSec: 0, endSec: 14, words: [
+ { text: 'one', startSec: 0, endSec: 3.8 }, { text: 'two', startSec: 4.2, endSec: 14 },
+ ] }] };
+ original.scenes[0].takes = [{ takeId: 'accepted-take', kind: 'video', assetId: 'accepted', shotInstruction: instruction }];
+ original.videoSettings = { backend: 'fal' };
+ original.excerpts = [{ id: 'draft', status: 'complete', startSec: 8, endSec: 24, notes: [], sections: [
+ { sceneId: 'mvs-1', startSec: 10, endSec: 24, layer: 'footage', performance: { takeId: 'accepted' } },
+ ] }];
+ original.autoReviews = [{ status: 'needs-human', attempts: [{ excerptId: 'draft', review: { evidence: { excerptStartSec: 8, temporal: {
+ status: 'verified', analyzer: { id: 'synthetic' }, shots: [{ sceneId: 'mvs-1', takeId: 'accepted', spans: [
+ { startSec: 2, endSec: 6, status: 'verified', offsetSec: 0.01, confidence: 0.9 },
+ { startSec: 6, endSec: 16, status: 'verified', offsetSec: 0.3, confidence: 0.9 },
+ ] }],
+ } } } }] }];
+ const { startPerformanceRepairOnProject } = await import('./performanceRepair.js');
+ const repair = startPerformanceRepairOnProject(original, 'mvs-1', { excerptId: 'draft', sourceAssetId: 'accepted', boundarySec: 14 }, 'boundary.png');
+ const [prefix, suffix] = repair.project.scenes;
+ getProject.mockResolvedValue(repair.project);
+ const prepared = await preparePerformanceShot({ musicVideo: { projectId: 'mv-1', sceneId: suffix.sceneId, revisionId: repair.revision.id },
+ backend: 'fal', sourceImagePath: join(PATHS.images, 'boundary.png'), mode: 'image' });
+ expect(prepared.shotInstruction.audioWindow).toEqual({ startSec: 14, endSec: 24, durationSec: 10 });
+ expect(prepared.shotInstruction.edit).toEqual({ inSec: 0, outSec: 10, targetSec: 10 });
+ expect(prepared.shotInstruction.repair).toMatchObject({ sourceAssetId: 'accepted', sourceTakeId: 'accepted-take', role: 'continuation' });
+ const sliced = pcm(await readFile(prepared.audioFilePath));
+ expect(sliced.length / 2).toBe(10 * RATE);
+ expect(sliced.readInt16LE((20 - 14) * RATE * 2)).toBe(30000);
+ // A source edit to a short interval cannot make preparation pad backwards
+ // across the accepted prefix or choose a different source frame.
+ await expect(preparePerformanceShot({ musicVideo: { projectId: 'mv-1', sceneId: suffix.sceneId }, backend: 'fal', sourceImagePath: join(PATHS.images, 'boundary.png') }))
+ .rejects.toMatchObject({ code: 'PERFORMANCE_REPAIR_REVISION_REQUIRED' });
+
+ const acceptedPath = join(PATHS.videos, 'accepted.mp4');
+ const suffixPath = join(PATHS.videos, 'suffix.mp4');
+ await mkdir(PATHS.videos, { recursive: true });
+ execFileSync(ffmpeg, ['-v', 'error', '-f', 'lavfi', '-i', 'testsrc2=s=64x64:r=24:d=14', '-c:v', 'libx264', '-pix_fmt', 'yuv420p', '-y', acceptedPath]);
+ execFileSync(ffmpeg, ['-v', 'error', '-f', 'lavfi', '-i', 'color=blue:s=64x64:r=24:d=10', '-c:v', 'libx264', '-pix_fmt', 'yuv420p', '-y', suffixPath]);
+ await mkdir(PATHS.images, { recursive: true });
+ execFileSync(ffmpeg, ['-v', 'error', '-i', acceptedPath, '-ss', String(repair.revision.repair.referenceFrameSec), '-frames:v', '1', '-y', join(PATHS.images, 'boundary.png')]);
+ const delivered = await readFile(suffixPath);
+ const posts = [];
+ vi.stubGlobal('fetch', vi.fn(async (url, options) => {
+ if (options?.method === 'POST') { posts.push(JSON.parse(options.body)); return jsonResponse({ request_id: 'suffix-request', status_url: 'https://queue.fal.run/suffix-s', response_url: 'https://queue.fal.run/suffix-r' }); }
+ if (url === 'https://queue.fal.run/suffix-s') return jsonResponse({ status: 'COMPLETED' });
+ if (url === 'https://queue.fal.run/suffix-r') return jsonResponse({ video: { url: 'https://cdn.example.com/suffix.mp4' } });
+ if (url === 'https://cdn.example.com/suffix.mp4') return { ok: true, status: 200, arrayBuffer: async () => Uint8Array.from(delivered).buffer };
+ throw new Error('Unexpected synthetic provider request');
+ }));
+ const generated = await fal.generateVideo({ apiKey: 'test-key', modelId: prepared.modelId, resolution: prepared.resolution,
+ sourceImagePath: join(PATHS.images, 'boundary.png'), audioFilePath: prepared.audioFilePath,
+ lipSync: { enableTranscription: prepared.enableTranscription }, shotInstruction: prepared.shotInstruction });
+ expect(await waitForTerminal(generated.jobId)).toMatchObject({ type: 'completed' });
+ expect(posts).toHaveLength(1);
+ expect(Buffer.from(posts[0].audio_url.replace(/^data:audio\/wav;base64,/, ''), 'base64')).toEqual(await readFile(prepared.audioFilePath));
+ const { mutateVideoHistory } = await import('../videoGen/history.js');
+ await mutateVideoHistory((items) => [{ id: 'accepted', filename: 'accepted.mp4', numFrames: 336, fps: 24, width: 64, height: 64 }, ...items]);
+ const landed = appendSceneTakes(repair.project, suffix.sceneId, [{ kind: 'video', assetId: generated.jobId, shotInstruction: prepared.shotInstruction }]).project;
+ const clips = beatSnapClips(await resolveSceneClips(landed), [], { scenes: landed.scenes });
+ expect(clips[0]).toMatchObject({ videoPath: acceptedPath, inSec: 0, outSec: 4, duration: 4, loop: false });
+ expect(clips[1]).toMatchObject({ inSec: 0, outSec: 10, duration: 10 });
+ expect(await findStalePerformanceTakes(landed, join(PATHS.music, 'song.wav'))).toEqual([]);
+ const encode = (selected, filename) => {
+ const { args } = buildMusicVideoFfmpegArgs(selected, join(PATHS.music, 'song.wav'), filename);
+ execFileSync(ffmpeg, ['-v', 'error', ...args.filter((a, i) => a !== '-progress' && args[i - 1] !== '-progress')]);
+ };
+ const baseline = join(PATHS.videos, 'prefix-baseline.mp4');
+ const output = join(PATHS.videos, 'repaired.mp4');
+ encode([clips[0]], baseline);
+ encode(clips, output);
+ const pixels = (path) => execFileSync(ffmpeg, ['-v', 'error', '-i', path, '-t', '4', '-f', 'rawvideo', '-pix_fmt', 'rgb24', '-'], { maxBuffer: 4 * 1024 * 1024 });
+ // H.264 quantization depends on following frames; compare the unchanged
+ // source selection and allow only normal codec rounding in rendered pixels.
+ const before = pixels(baseline), after = pixels(output);
+ expect(after.length).toBe(before.length);
+ let error = 0;
+ for (let i = 0; i < before.length; i++) error += Math.abs(before[i] - after[i]);
+ expect(error / before.length).toBeLessThan(2);
+ expect(prefix.videoHistoryId).toBe('accepted');
+ }, 60_000);
+});
diff --git a/server/services/musicVideo/render.js b/server/services/musicVideo/render.js
index 2cc23ecfdf..49589fa813 100644
--- a/server/services/musicVideo/render.js
+++ b/server/services/musicVideo/render.js
@@ -314,7 +314,8 @@ export function beatSnapClips(clips, beats, { toleranceSec = 0.12, minClipSec =
// supply an on-beat cut. Beat alignment describes the cut, not ownership
// of its timing. Section provenance is cleared when the audio changes.
const planned = Number.isInteger(scene?.sectionIndex) && scene.sectionIndex >= 0;
- if ((scene?.beatAligned || planned) && sceneHasAuthoredSpan(scene)) {
+ // A measured word-gap repair owns its edit boundary independently of beats.
+ if ((scene?.beatAligned || planned || selectedPerformanceInstruction(scene)?.repair) && sceneHasAuthoredSpan(scene)) {
// inSec stays 0 here deliberately: this only ever trims how much of the
// clip plays, never which frames — there is no in-point/out-point
// distinction. A legacy planned scene commonly spans much longer than
diff --git a/server/services/musicVideo/revision.js b/server/services/musicVideo/revision.js
index 24525a880c..788ca3171a 100644
--- a/server/services/musicVideo/revision.js
+++ b/server/services/musicVideo/revision.js
@@ -259,7 +259,7 @@ export function revisionSectionStates(project, revision, jobs = [], nowMs = Date
&& within(job.completedAt, TAKE_ATTACH_GRACE_MS, nowMs) && !takes.some((t) => t.jobId === job.id))
));
const claimed = within(section.claimedAt, GENERATION_CLAIM_LEASE_MS, nowMs);
- return { ...section, state: pending || claimed ? 'generating' : 'needs-generation' };
+ return { ...section, state: pending || claimed ? 'generating' : revision.repair?.submitted ? 'review-needed' : 'needs-generation' };
});
}
@@ -381,6 +381,15 @@ export function assertRevisionOpenForGeneration(project, revisionId, { sceneId =
throw revisionError(409, 'DEPENDENCY_REPAIR_CHANGED', 'This generation does not match the previewed repair inputs');
}
}
+ if (revision.repair) {
+ const scene = project.scenes?.find((s) => s.sceneId === sceneId);
+ const prefix = project.scenes?.find((s) => s.sceneId === revision.repair.sourceSceneId);
+ if (kind !== 'video' || sceneId !== revision.repair.suffixSceneId || scene?.performanceRepair?.revisionId !== revisionId
+ || prefix?.videoHistoryId !== revision.repair.sourceAssetId || prefix?.endSec !== revision.repair.boundarySec
+ || scene?.startSec !== revision.repair.boundarySec || scene?.endSec !== revision.repair.sourceInterval.endSec) {
+ throw revisionError(409, 'PERFORMANCE_REPAIR_STALE', 'This generation no longer matches the accepted prefix and repair interval');
+ }
+ }
if (revision.mediumBasis || codeFirst(project)) {
if (!revision.mediumBasis || revision.mediumBasis !== mediumBasis(project)) {
throw revisionError(409, 'REVISION_MEDIUM_PLAN_CHANGED', 'The medium plan or allowance changed since this revision opened');
diff --git a/server/services/musicVideo/revisionService.js b/server/services/musicVideo/revisionService.js
index 8c89a13ba0..2daea47537 100644
--- a/server/services/musicVideo/revisionService.js
+++ b/server/services/musicVideo/revisionService.js
@@ -59,9 +59,16 @@ export async function startRevision(projectId, excerptId, input = {}) {
export async function assertRevisionOpen(projectId, revisionId, { sceneId = null, kind = null } = {}) {
if (!revisionId) return;
const project = await getProject(projectId);
- assertRevisionOpenForGeneration(project, revisionId, { sceneId, kind });
- const revision = projectRevisions(project).find((entry) => entry.id === revisionId);
- if (!project || (!runOwningRevision(project, revisionId) && revision?.type !== 'dependencies')) return;
+ const checked = assertRevisionOpenForGeneration(project, revisionId, { sceneId, kind });
+ if (checked?.repair) {
+ return mutateProjectRecord(projectId, (current) => {
+ const revision = assertRevisionOpenForGeneration(current, revisionId, { sceneId, kind });
+ if (revision.repair.submitted) throw new ServerError('This repair already reserved its one generation — review or cancel it', { status: 409, code: 'PERFORMANCE_REPAIR_SPEND_LIMIT' });
+ const next = { ...revision, repair: { ...revision.repair, submitted: true, generations: 1 } };
+ return { project: { ...current, revisions: current.revisions.map((r) => r.id === revisionId ? next : r) } };
+ }).then(() => undefined);
+ }
+ if (!project || (!runOwningRevision(project, revisionId) && checked?.type !== 'dependencies')) return;
const { listJobs } = await import('../mediaJobQueue/index.js');
const jobs = [...listJobs({ kind: 'video' }), ...listJobs({ kind: 'image' })];
await mutateProjectRecord(projectId, (current) => {
@@ -112,7 +119,7 @@ export async function resumeRevision(projectId, revisionId) {
// Derive + claim under the record's write serialization, so two overlapping
// resumes can never both hand the same section out for (paid) generation.
const claim = await mutateProjectRecord(projectId, (current) => claimRevisionGeneration(current, revisionId, jobs));
- if (claim.needsGeneration.length || claim.generating.length) return { ...claim, render: null };
+ if (claim.needsGeneration.length || claim.generating.length || claim.revision.sections.some((s) => s.state === 'review-needed')) return { ...claim, 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).
@@ -179,3 +186,26 @@ export async function startDependencyRepair(projectId, input) {
return startDependencyRepairOnProject(current, impact, input);
});
}
+
+/** Refund only a synchronous enqueue failure with no durable job. A restart
+ * leaves an ambiguous reservation spent until the director reviews it.
+ */
+export async function releasePerformanceRepairSubmission(projectId, revisionId) {
+ const { listJobs } = await import('../mediaJobQueue/index.js');
+ return mutateProjectRecord(projectId, (current) => {
+ const revision = projectRevisions(current).find((r) => r.id === revisionId);
+ const jobs = listJobs({ kind: 'video' });
+ if (!revision?.repair || jobs.some((job) => job.params?.musicVideo?.projectId === projectId && job.params?.musicVideo?.revisionId === revisionId)) return { project: current };
+ const next = { ...revision, repair: { ...revision.repair, submitted: false, generations: 0 } };
+ return { project: { ...current, revisions: current.revisions.map((r) => r.id === revisionId ? next : r) } };
+ });
+}
+
+/** Queue dispatch re-check: cancellation after reservation must not start a
+ * provider. This validates without charging the reservation a second time.
+ */
+export async function assertPerformanceRepairDispatch(tag) {
+ const project = await getProject(tag.projectId);
+ const revision = assertRevisionOpenForGeneration(project, tag.revisionId, { sceneId: tag.sceneId, kind: 'video' });
+ if (!revision?.repair?.submitted) throw new ServerError('The repair has no open generation reservation', { status: 409, code: 'PERFORMANCE_REPAIR_STALE' });
+}
diff --git a/server/services/videoGen/submitJob.js b/server/services/videoGen/submitJob.js
index acf6eb9c3b..afc2d6bba0 100644
--- a/server/services/videoGen/submitJob.js
+++ b/server/services/videoGen/submitJob.js
@@ -194,22 +194,17 @@ const submitValidatedVideoGenJob = async (body, uploads) => {
shotInstruction: performance.shotInstruction,
} : null;
+ let repairReserved = false;
const enqueue = (params) => withStagedRollback(
async () => {
+ if (repairReserved) {
+ const { releasePerformanceRepairSubmission } = await import('../musicVideo/revisionService.js');
+ await releasePerformanceRepairSubmission(body.musicVideo.projectId, body.musicVideo.revisionId);
+ }
if (performance) await unlink(performance.audioFilePath).catch(() => {});
await cleanupStaged();
},
async () => {
- // Selective section revision (#9011): checked as the LAST step before the
- // actual queue write (staging, FableLoom compilation and the performance-
- // shot audio slice above can all take real time), so a revision closed
- // mid-submission is caught as close to the cancel/kickoff race as this
- // request can get. A no-op when the tag carries no revisionId; deferred
- // import since only this rare path needs the revision service's closure.
- if (body.musicVideo?.revisionId) {
- const { assertRevisionOpen } = await import('../musicVideo/revisionService.js');
- await assertRevisionOpen(body.musicVideo.projectId, body.musicVideo.revisionId, { sceneId: body.musicVideo.sceneId, kind: 'video' });
- }
if (body.musicVideo?.productionRunId) {
const { assertProductionSubmission } = await import('../musicVideo/productionService.js');
await assertProductionSubmission(body.musicVideo.projectId, body.musicVideo.productionRunId,
@@ -223,11 +218,11 @@ const submitValidatedVideoGenJob = async (body, uploads) => {
const scene = project?.scenes?.find((entry) => entry.sceneId === body.musicVideo.sceneId);
assertShotActionContract(scene);
params.prompt = withShotActionPrompt(params.prompt, project, scene, { offsetSec: performance?.shotInstruction?.edit?.inSec || 0 });
+ const interval = performance?.shotInstruction?.songInterval;
+ if (interval && (interval.startSec !== scene?.startSec || interval.endSec !== scene?.endSec)) {
+ throw new ServerError('The shot timing changed while its performance audio was prepared — submit again', { status: 409, code: 'MUSIC_VIDEO_SHOT_TIMING_CHANGED' });
+ }
if (scene?.direction?.actionContract != null) {
- const interval = performance?.shotInstruction?.songInterval;
- if (interval && (interval.startSec !== scene.startSec || interval.endSec !== scene.endSec)) {
- throw new ServerError('The shot timing changed while its performance audio was prepared — submit again', { status: 409, code: 'MUSIC_VIDEO_SHOT_TIMING_CHANGED' });
- }
const requestedSec = performance?.shotInstruction?.audioWindow?.durationSec ?? params.duration
?? (Number.isFinite(params.numFrames) ? (params.numFrames - 1) / (params.fps || 24) : null);
const offsetSec = performance?.shotInstruction?.edit?.inSec || 0;
@@ -244,6 +239,17 @@ const submitValidatedVideoGenJob = async (body, uploads) => {
const { basename } = await import('path');
if (scene) params.musicVideoDependencies = captureTakeDependencies(scene, prepared.sourceImagePath ? basename(prepared.sourceImagePath) : null);
}
+ // Selective section revision (#9011): checked as the LAST step before the
+ // actual queue write (staging, FableLoom compilation and the performance-
+ // shot audio slice above can all take real time), so a revision closed
+ // mid-submission is caught as close to the cancel/kickoff race as this
+ // request can get. A no-op when the tag carries no revisionId; deferred
+ // import since only this rare path needs the revision service's closure.
+ if (body.musicVideo?.revisionId) {
+ const { assertRevisionOpen } = await import('../musicVideo/revisionService.js');
+ await assertRevisionOpen(body.musicVideo.projectId, body.musicVideo.revisionId, { sceneId: body.musicVideo.sceneId, kind: 'video' });
+ repairReserved = Boolean(performance?.shotInstruction?.repair);
+ }
return enqueueJob({ kind: 'video', params });
},
);