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

Assemble and validate standalone Video final cuts (#6589)

[._.]/7d35f05c5c10
diff --git a/client/src/components/creative-director/VideoArtifactsTab.jsx b/client/src/components/creative-director/VideoArtifactsTab.jsx
index 2ac4d8063c..acb1720cb6 100644
--- a/client/src/components/creative-director/VideoArtifactsTab.jsx
+++ b/client/src/components/creative-director/VideoArtifactsTab.jsx
@@ -32,7 +32,7 @@ export default function VideoArtifactsTab({ project, basePath }) {
return (
<div className="max-w-4xl space-y-4">
<h2 className="text-lg font-medium">Production artifacts</h2>
- <p className="text-sm text-port-text-muted">Saved planning artifacts. Production remains blocked until revision approvals and dispatch controls are available.</p>
+ <p className="text-sm text-port-text-muted">Saved scripts, shot plans, and partial clips. Review current revisions before dependent work proceeds.</p>
{project.treatment?.artifact && <div className="space-y-2">
<label htmlFor="video-artifact-revision" className="block text-sm">View revision</label>
<select id="video-artifact-revision" value={selectedRevision || ''} onChange={event => {
diff --git a/client/src/components/creative-director/VideoCutPanel.jsx b/client/src/components/creative-director/VideoCutPanel.jsx
new file mode 100644
index 0000000000..e1dd473e70
--- /dev/null
+++ b/client/src/components/creative-director/VideoCutPanel.jsx
@@ -0,0 +1,26 @@
+import { Link } from 'react-router';
+import ScenePreview from './ScenePreview.jsx';
+
+export default function VideoCutPanel({ project }) {
+ const trackId = project.musicBed?.trackId || project.videoDraft?.audio?.trackId;
+ const cut = project.videoFinalCut || project.videoRoughCut;
+ const delivered = project.status === 'complete' && project.finalVideoId === cut?.videoId;
+ return <section aria-label="Assembled video" className="space-y-3 rounded border border-port-border p-4">
+ <h3 className="font-medium">{delivered ? 'Final video' : cut ? 'Cut awaiting review' : 'Final assembly'}</h3>
+ {project.failureReason && <p role="alert" className="text-port-warning">{project.failureReason}</p>}
+ {cut?.filename ? <>
+ <ScenePreview jobId={cut.videoId} src={`/data/videos/${encodeURIComponent(cut.filename)}`} label={delivered ? 'Final video preview' : 'Assembled cut preview'} />
+ <p className="text-sm">{cut.durationSeconds?.toFixed(2)} seconds · {cut.audioMode} audio</p>
+ <div className="flex flex-wrap gap-3 text-sm">
+ <a className="underline" href={`/data/videos/${encodeURIComponent(cut.filename)}`} download>Download {delivered ? 'final video' : 'cut'}</a>
+ <Link className="underline" to={`/media/history?preview=${encodeURIComponent(cut.filename)}`}>Open in Media History</Link>
+ </div>
+ </> : <p className="text-sm text-port-text-muted">Completed clips are assembled and checked for playback, duration, and the selected audio contract. Rough and final review precede delivery.</p>}
+ <div className="flex flex-wrap gap-3 text-sm">
+ {project.timelineProjectId && <Link className="underline" to={`/media/timeline/${project.timelineProjectId}`}>Open in Timeline</Link>}
+ {project.collectionId && <Link className="underline" to={`/media/collections/${project.collectionId}`}>Open collection</Link>}
+ {trackId && <Link className="underline" to={`/music/tracks/${encodeURIComponent(trackId)}`}>Open soundtrack</Link>}
+ </div>
+ {project.videoCutHistory?.length > 0 && <details><summary>Previous cuts</summary><ul className="space-y-2">{project.videoCutHistory.map((previous, index) => <li key={`${previous.videoId}-${index}`}><a className="underline" href={`/data/videos/${encodeURIComponent(previous.filename)}`} target="_blank" rel="noreferrer">Cut {index + 1} · {previous.durationSeconds?.toFixed(2)} seconds</a></li>)}</ul></details>}
+ </section>;
+}
diff --git a/client/src/components/creative-director/VideoCutPanel.test.jsx b/client/src/components/creative-director/VideoCutPanel.test.jsx
new file mode 100644
index 0000000000..5f65ea084d
--- /dev/null
+++ b/client/src/components/creative-director/VideoCutPanel.test.jsx
@@ -0,0 +1,19 @@
+import { expect, it } from 'vitest';
+import { fireEvent, render, screen } from '@testing-library/react';
+import { MemoryRouter } from 'react-router';
+import VideoCutPanel from './VideoCutPanel.jsx';
+
+it('plays and downloads the stored Timeline filename and distinguishes a reviewed cut from delivery', () => {
+ const project = { status: 'stitching', collectionId: 'example-collection', timelineProjectId: 'example-timeline', videoRoughCut: { videoId: 'example-job', filename: 'timeline-example-cut.mp4', durationSeconds: 60, audioMode: 'silent' } };
+ const { container, rerender } = render(<MemoryRouter><VideoCutPanel project={project} /></MemoryRouter>);
+ expect(screen.getByText('Cut awaiting review')).toBeInTheDocument();
+ expect(container.querySelector('video')).toHaveAttribute('src', '/data/videos/timeline-example-cut.mp4');
+ expect(screen.getByRole('link', { name: 'Download cut' })).toHaveAttribute('href', '/data/videos/timeline-example-cut.mp4');
+ expect(screen.getByRole('link', { name: 'Open in Media History' })).toHaveAttribute('href', '/media/history?preview=timeline-example-cut.mp4');
+ expect(screen.getByRole('link', { name: 'Open in Timeline' })).toHaveAttribute('href', '/media/timeline/example-timeline');
+ rerender(<MemoryRouter><VideoCutPanel project={{ ...project, status: 'complete', finalVideoId: 'example-job', videoFinalCut: project.videoRoughCut }} /></MemoryRouter>);
+ expect(screen.getByText('Final video')).toBeInTheDocument();
+ expect(screen.getByRole('link', { name: 'Download final video' })).toBeInTheDocument();
+ fireEvent.error(container.querySelector('video'));
+ expect(screen.getByRole('button', { name: /Retry/ })).toBeInTheDocument();
+});
diff --git a/client/src/components/creative-director/VideoDraftDrawer.jsx b/client/src/components/creative-director/VideoDraftDrawer.jsx
index d71be7c038..7d9f6ec60e 100644
--- a/client/src/components/creative-director/VideoDraftDrawer.jsx
+++ b/client/src/components/creative-director/VideoDraftDrawer.jsx
@@ -9,6 +9,7 @@ import { listUniverses } from '../../services/apiUniverseBuilder.js';
import { listPipelineSeries } from '../../services/apiPipeline.js';
import { listCatalogIngredients } from '../../services/apiCatalog.js';
import { listMusicEngines } from '../../services/apiMusic.js';
+import { listTracks } from '../../services/apiTracks.js';
import { listVideoModels } from '../../services/apiImageVideo.js';
const TABS = [{ id: 'brief', label: 'Brief' }, { id: 'production', label: 'Production' }, { id: 'sources', label: 'Sources' }];
@@ -19,6 +20,7 @@ export default function VideoDraftDrawer({ open, onClose, project, onSaved, cata
const [form, setForm] = useState({});
const [models, setModels] = useState([]);
const [engines, setEngines] = useState([]);
+ const [tracks, setTracks] = useState([]);
const [sourceOptions, setSourceOptions] = useState({});
const [sourceKind, setSourceKind] = useState('universe');
const [sourceId, setSourceId] = useState('');
@@ -33,8 +35,9 @@ export default function VideoDraftDrawer({ open, onClose, project, onSaved, cata
videoMode: project?.renderBackend?.video?.mode || 'local', backendModelId: project?.renderBackend?.video?.modelId || '',
aspectRatio: project?.aspectRatio || '16:9', quality: project?.quality || 'standard', modelId: (project?.renderBackend?.video?.mode === 'local' ? project.renderBackend.video.modelId : '') || project?.modelId || '',
min: draft?.durationRange?.min || 30, max: draft?.durationRange?.max || 60,
- reviewPolicy: draft?.reviewPolicy || 'review', audioProvider: draft?.audio?.providerId || '', audioModel: draft?.audio?.model || '',
+ reviewPolicy: draft?.reviewPolicy || 'review', transition: draft?.transition || 'cut', audioMode: draft?.audio?.mode || (project ? 'native' : 'silent'), trackId: draft?.audio?.trackId || '', audioPrompt: draft?.audio?.prompt || '', audioProvider: draft?.audio?.providerId || '', audioModel: draft?.audio?.model || '',
sources: draft?.sources || catalogIngredientIds.map(id => ({ kind: 'catalog', id })) });
+ listTracks({ silent: true }).then(data => setTracks(Array.isArray(data) ? data : data?.tracks || [])).catch(() => {});
listMusicEngines({ silent: true }).then(data => setEngines(data?.engines || [])).catch(() => {});
const rows = data => Array.isArray(data) ? data : data?.items || data?.series || data?.universes || [];
Promise.all([listUniverses({ silent: true }), listPipelineSeries({ silent: true }), listCatalogIngredients({ limit: 100, silent: true })]).then(([u, s, c]) => setSourceOptions({ universe: rows(u), series: rows(s), catalog: rows(c) })).catch(() => toast.error('Unable to load source choices. Close and reopen to retry.'));
@@ -53,7 +56,7 @@ export default function VideoDraftDrawer({ open, onClose, project, onSaved, cata
aspectRatio: form.aspectRatio, quality: form.quality, modelId: form.modelId, targetDurationSeconds: exactTarget,
...(!project ? { workspace: 'video', catalogIngredientIds: sources.filter(s => s.kind === 'catalog').map(s => s.id) } : {}),
renderBackend: { ...project?.renderBackend, video: { ...project?.renderBackend?.video, mode: form.videoMode, modelId: form.videoMode === 'local' ? form.modelId : form.backendModelId || null } },
- videoDraft: { durationRange: { min, max }, sources, audio: { ...(form.audioProvider ? { providerId: form.audioProvider } : {}), ...(form.audioModel ? { model: form.audioModel } : {}) }, reviewPolicy: form.reviewPolicy, checkpoints: project?.videoDraft?.checkpoints || VIDEO_REVIEW_CHECKPOINTS } };
+ videoDraft: { durationRange: { min, max }, sources, transition: form.transition, audio: { mode: form.audioMode, ...(form.trackId ? { trackId: form.trackId } : {}), ...(form.audioPrompt ? { prompt: form.audioPrompt } : {}), ...(form.audioProvider ? { providerId: form.audioProvider } : {}), ...(form.audioModel ? { model: form.audioModel } : {}) }, reviewPolicy: form.reviewPolicy, checkpoints: project?.videoDraft?.checkpoints || VIDEO_REVIEW_CHECKPOINTS } };
setSaving(true);
const saved = await (project ? updateCreativeDirectorProject(project.id, payload, { silent: true }) : createCreativeDirectorProject(payload, { silent: true }))
.catch(err => { toast.error(err.message || 'Unable to save video draft'); return null; });
@@ -77,8 +80,13 @@ export default function VideoDraftDrawer({ open, onClose, project, onSaved, cata
: form.videoMode === 'fal' ? input('backendModelId', 'fal.ai model (optional)', { placeholder: 'Use configured fal.ai default', maxLength: 64 })
: select('backendModelId', 'Media model', [['', form.videoMode === 'reactor' ? 'fast-h3 (backend default)' : 'Backend default'], ...(form.backendModelId ? [[form.backendModelId, `${form.backendModelId} (saved model)`]] : [])])}
<p className="text-sm text-port-text-muted">Backend selections are saved without running providers. Cloud renders may incur charges when production is enabled.</p>
- <h3 className="font-medium">Audio conditioning</h3>
- <div className="grid grid-cols-1 sm:grid-cols-2 gap-3"><label htmlFor="video-draft-audioProvider" className="block text-sm">Audio engine<select id="video-draft-audioProvider" className={fieldClass} value={form.audioProvider || ''} onChange={e => { change('audioProvider', e.target.value); change('audioModel', ''); }}><option value="">Choose before production</option>{engines.map(engine => <option key={engine.id} value={engine.id}>{engine.name || engine.id}</option>)}</select></label>{select('audioModel', 'Audio model', [['', 'Engine default'], ...(engines.find(e => e.id === form.audioProvider)?.models || []).map(m => [m.id, m.name || m.id])])}</div>
+ {select('transition', 'Shot joins', [['cut', 'Straight cuts'], ['fade', 'Fade through black (no overlap)']])}
+ <h3 className="font-medium">Soundtrack</h3>
+ {select('audioMode', 'Audio contract', [['silent', 'Silent (remove audio)'], ['native', 'Native audio from every clip'], ['imported', 'Existing Music track'], ['generated', 'Generate one soundtrack bed']])}
+ {form.audioMode === 'imported' && select('trackId', 'Soundtrack track', [['', 'Choose a track'], ...tracks.filter(track => track.audioFilename).map(track => [track.id, track.title || track.id])])}
+ {form.audioMode === 'generated' && input('audioPrompt', 'Soundtrack description', { maxLength: 1000 })}
+ <p className="text-sm text-port-text-muted">Native audio requires audio in every clip; it does not guarantee dialogue or lip sync. Soundtracks replace clip audio and repeat to fill the cut. Generated audio uses one bounded job unless you authorize a retry.</p>
+ {form.audioMode === 'generated' && <div className="grid grid-cols-1 sm:grid-cols-2 gap-3"><label htmlFor="video-draft-audioProvider" className="block text-sm">Audio engine<select id="video-draft-audioProvider" className={fieldClass} value={form.audioProvider || ''} onChange={e => { change('audioProvider', e.target.value); change('audioModel', ''); }}><option value="">Choose before production</option>{engines.map(engine => <option key={engine.id} value={engine.id}>{engine.name || engine.id}</option>)}</select></label>{select('audioModel', 'Audio model', [['', 'Engine default'], ...(engines.find(e => e.id === form.audioProvider)?.models || []).map(m => [m.id, m.name || m.id])])}</div>}
{select('reviewPolicy', 'Review policy', [['review', 'Review at checkpoints'], ['autonomous', 'Autonomous after production is enabled']])}
<p className="text-sm text-port-text-muted">Checkpoints: script and shot plan, references, rough cut, final cut. Start authorizes the displayed provider choices and limits. Creative changes require a fresh review.</p>
</>}
diff --git a/client/src/components/creative-director/VideoDraftDrawer.test.jsx b/client/src/components/creative-director/VideoDraftDrawer.test.jsx
index 3857b3ca2d..21f0fd8779 100644
--- a/client/src/components/creative-director/VideoDraftDrawer.test.jsx
+++ b/client/src/components/creative-director/VideoDraftDrawer.test.jsx
@@ -1,3 +1,4 @@
+vi.mock('../../services/apiTracks.js', () => ({ listTracks: vi.fn(async () => []) }));
vi.mock('../../services/apiMusic.js', () => ({ listMusicEngines: vi.fn(() => Promise.resolve({ engines: [] })) }));
vi.mock('../../services/apiUniverseBuilder.js', () => ({ listUniverses: vi.fn(() => Promise.resolve([])) }));
vi.mock('../../services/apiPipeline.js', () => ({ listPipelineSeries: vi.fn(() => Promise.resolve([])) }));
diff --git a/client/src/components/creative-director/VideoExecutionPanel.jsx b/client/src/components/creative-director/VideoExecutionPanel.jsx
index e14ece6687..53fad2218a 100644
--- a/client/src/components/creative-director/VideoExecutionPanel.jsx
+++ b/client/src/components/creative-director/VideoExecutionPanel.jsx
@@ -3,6 +3,7 @@ import { Link } from 'react-router';
import { getCreativeDirectorVideoExecution, startCreativeDirectorVideoExecution } from '../../services/apiCreativeDirector.js';
const LIMITS = [
+ ['maxAudioJobs', 'Maximum soundtrack jobs', 0, 4],
['maxClips', 'Maximum clip submissions', 1, 200],
['maxRetries', 'Retries per shot or step', 0, 3],
['maxReplans', 'Replans', 0, 5],
@@ -60,7 +61,7 @@ export default function VideoExecutionPanel({ project, onChange, basePath }) {
{preview && <>
<dl className="grid gap-2 text-sm sm:grid-cols-2">
{['treatment', 'plan', 'evaluation', 'video'].map(key => <div key={key}><dt className="capitalize text-port-text-muted">{key}</dt><dd className="break-words">{choiceText(preview.choices?.[key])}</dd></div>)}
- <div><dt className="text-port-text-muted">Audio</dt><dd>{preview.choices?.audio?.providerId ? choiceText(preview.choices.audio) : 'Attached music or native clip audio'}</dd></div>
+ <div><dt className="text-port-text-muted">Audio</dt><dd>{preview.choices?.audio?.providerId ? choiceText(preview.choices.audio) : preview.choices?.audio?.mode || 'Native clip audio'}</dd></div>
</dl>
<p className="text-xs text-port-text-muted">{preview.costNotice}</p>
{preview.blockers.map(blocker => <p key={blocker} role="alert" className="text-port-warning">{blocker}</p>)}
@@ -73,7 +74,7 @@ export default function VideoExecutionPanel({ project, onChange, basePath }) {
</div>)}
<div><label className="block text-sm" htmlFor="video-dollar-cap">Dollar cap (optional)</label><input id="video-dollar-cap" type="number" min="0.01" max="10000" step="0.01" placeholder="Unknown cost; use clip limits" value={limits.spendCapUsd ?? ''} disabled={active || pending} onChange={event => setLimits(previous => ({ ...previous, spendCapUsd: event.target.value }))} className="w-full rounded border border-port-border bg-port-bg p-2" /></div>
</div>}
- <p className="text-xs text-port-text-muted">Used: {(preview.execution?.attempts || []).filter(attempt => attempt.kind === 'clip').length} clip submissions · {(preview.execution?.attempts || []).filter(attempt => attempt.kind !== 'clip').length} agent calls. Limits include previous attempts.</p>
+ <p className="text-xs text-port-text-muted">Used: {(preview.execution?.attempts || []).filter(attempt => attempt.kind === 'clip').length} clip submissions · {(preview.execution?.attempts || []).filter(attempt => !['clip', 'audio'].includes(attempt.kind)).length} agent calls · {(preview.execution?.attempts || []).filter(attempt => attempt.kind === 'audio').length} soundtrack jobs. Limits include previous attempts.</p>
{uncertain.map(attempt => <div key={attempt.id} className="text-sm">
<label htmlFor={`retry-${attempt.id}`} className="flex gap-2 items-start"><input id={`retry-${attempt.id}`} type="checkbox" checked={retryAttemptIds.includes(attempt.id)} onChange={event => setRetryAttemptIds(previous => event.target.checked ? [...previous, attempt.id] : previous.filter(id => id !== attempt.id))} />Authorize another attempt for {attempt.sceneId || attempt.stepId || attempt.kind}. The earlier submission is uncertain and retrying may charge again{attempt.jobId ? ` (job ${attempt.jobId})` : ''}.</label>
</div>)}
diff --git a/client/src/components/creative-director/VideoExecutionPanel.test.jsx b/client/src/components/creative-director/VideoExecutionPanel.test.jsx
index 8ffaa8a0cc..0a6a6eca8d 100644
--- a/client/src/components/creative-director/VideoExecutionPanel.test.jsx
+++ b/client/src/components/creative-director/VideoExecutionPanel.test.jsx
@@ -5,7 +5,7 @@ import { MemoryRouter } from 'react-router';
vi.mock('../../services/apiCreativeDirector.js', () => ({ getCreativeDirectorVideoExecution: vi.fn(), startCreativeDirectorVideoExecution: vi.fn() }));
import { getCreativeDirectorVideoExecution, startCreativeDirectorVideoExecution } from '../../services/apiCreativeDirector.js';
import VideoExecutionPanel from './VideoExecutionPanel.jsx';
-const preview = { canStart: true, blockers: [], configurationRevision: 'a'.repeat(32), choices: { video: { mode: 'reactor', modelDescription: 'fast-h3' }, treatment: { providerId: 'example-agent', model: 'example-model' }, audio: {} }, costNotice: 'Provider prices are unknown.', limits: { maxClips: 60, maxRetries: 1, maxReplans: 2, maxAgentCalls: 100, spendCapUsd: null }, execution: null };
+const preview = { canStart: true, blockers: [], configurationRevision: 'a'.repeat(32), choices: { video: { mode: 'reactor', modelDescription: 'fast-h3' }, treatment: { providerId: 'example-agent', model: 'example-model' }, audio: {} }, costNotice: 'Provider prices are unknown.', limits: { maxAudioJobs: 1, maxClips: 60, maxRetries: 1, maxReplans: 2, maxAgentCalls: 100, spendCapUsd: null }, execution: null };
beforeEach(() => {
vi.resetAllMocks();
getCreativeDirectorVideoExecution.mockResolvedValue(preview);
diff --git a/client/src/components/creative-director/VideoReviewPanel.jsx b/client/src/components/creative-director/VideoReviewPanel.jsx
index 99f476f114..2751c1b394 100644
--- a/client/src/components/creative-director/VideoReviewPanel.jsx
+++ b/client/src/components/creative-director/VideoReviewPanel.jsx
@@ -61,7 +61,7 @@ export default function VideoReviewPanel({ project, onChange }) {
{checkpoint.ready && <>
<p className="text-xs text-port-text-muted">Artifact revision {review.artifacts?.revision ?? 'unknown'} · <span title={checkpoint.revision}>{checkpoint.revision.slice(0, 12)}</span></p>
{checkpoint.stage === 'script-shot-plan' && <p className="text-sm whitespace-pre-wrap">{typeof review.artifacts?.script === 'string' ? review.artifacts.script : JSON.stringify(review.artifacts?.script)}</p>}
- {artifact?.videoId && <ScenePreview jobId={artifact.videoId} label={`${checkpoint.label} preview`} />}
+ {artifact?.videoId && <ScenePreview jobId={artifact.videoId} src={artifact.filename ? `/data/videos/${encodeURIComponent(artifact.filename)}` : null} label={`${checkpoint.label} preview`} />}
<details><summary className="cursor-pointer text-xs">View full saved artifact</summary><pre className="max-h-80 overflow-auto whitespace-pre-wrap break-words text-xs">{JSON.stringify(artifact, null, 2)}</pre></details>
</>}
{checkpoint.stale && <p className="text-xs text-port-warning">Previous approval is stale.</p>}
diff --git a/client/src/pages/CreativeDirectorDetail.jsx b/client/src/pages/CreativeDirectorDetail.jsx
index 668da88de3..d85b7b6f04 100644
--- a/client/src/pages/CreativeDirectorDetail.jsx
+++ b/client/src/pages/CreativeDirectorDetail.jsx
@@ -14,6 +14,7 @@ import {
stopCreativeDirectorProject,
resumeCreativeDirectorProject,
} from '../services/apiCreativeDirector.js';
+import VideoCutPanel from '../components/creative-director/VideoCutPanel.jsx';
import VideoExecutionPanel from '../components/creative-director/VideoExecutionPanel.jsx';
import VideoReviewPanel from '../components/creative-director/VideoReviewPanel.jsx';
import VideoDraftDrawer from '../components/creative-director/VideoDraftDrawer.jsx';
@@ -336,6 +337,7 @@ export default function CreativeDirectorDetail({ basePath = '/creative-director'
<p className="text-sm">Exact target: {project.targetDurationSeconds} seconds (requested: {project.videoDraft?.durationRange?.min}–{project.videoDraft?.durationRange?.max} seconds) · {project.aspectRatio} · {project.quality}</p>
<p className="text-sm">Review: {project.videoDraft?.reviewPolicy || 'review'} · Checkpoints: {(project.videoDraft?.checkpoints || []).join(', ')}</p>
{['draft', 'paused', 'failed'].includes(project.status) && <button onClick={() => setEditingDraft(true)} className="px-3 py-2 rounded bg-port-accent text-white">{project.status === 'draft' ? 'Edit draft' : 'Edit production settings'}</button>}
+ <VideoCutPanel project={project} />
<VideoExecutionPanel key={project.id} project={project} onChange={fetchProject} basePath={basePath} />
<VideoDraftDrawer open={editingDraft} onClose={() => setEditingDraft(false)} project={project} onSaved={saved => setProject(prev => ({ ...prev, ...saved }))} />
</section>}
diff --git a/docs/STORAGE.md b/docs/STORAGE.md
index 15bf54fc44..50a116f81e 100644
--- a/docs/STORAGE.md
+++ b/docs/STORAGE.md
@@ -343,3 +343,15 @@ submissions require explicit retry consent because they may already have charged
Completed jobs can be reused after reconciliation. Project sync v9 gates the
execution semantics; existing records need no rewrite and remain unauthorized
until the owner explicitly starts them.
+
+Validated `videoRoughCut` / `videoFinalCut` references and `videoCutHistory` remain
+in the Creative Director project JSONB. Timeline records and video-history entries
+use their existing stores; rendered files remain under `data/videos/`, thumbnails
+under `data/video-thumbnails/`, and standalone soundtrack assets under `data/music/`.
+Existing backup classification covers those assets. Generated soundtracks create
+ordinary Music Track records; no synthetic Series or source issue is created.
+The machine-local execution receipt also carries audio jobs and the current
+Timeline render ID, so restart can reconcile output without new provider work.
+Project sync v10 gates cut validation and explicit audio semantics. Older Video
+audio settings default to native clip audio when read; new drafts explicitly
+select a contract. No new store, seed or data-rewriting migration is required.
diff --git a/docs/features/creative-director-video.md b/docs/features/creative-director-video.md
new file mode 100644
index 0000000000..2079f1ef3d
--- /dev/null
+++ b/docs/features/creative-director-video.md
@@ -0,0 +1,97 @@
+# Standalone Video production in Creative Director
+
+Commission a standalone video from **Creative Director → New video draft**.
+Create → Video remains the existing creative-commission video browser. Existing
+Video Gen, remix/continue and Creative Director links continue to work. No Series
+is required. Saving or opening a draft makes no generation calls.
+
+## Workflow
+
+1. Enter the brief, duration range, aspect, quality and optional creative sources.
+ The displayed exact target is retained within that range. Sources are read
+ into the local planning context; deleted or changed sources block stale work.
+2. Choose the media backend and cognitive models. Treatment and production-plan
+ stages require a configured agent harness; evaluation can use a configured
+ vision model. Stage provider/model/effort choices survive reload. Explicit
+ Video backends do not fall back to a different provider. Reactor readiness
+ does not depend on local model hardware.
+3. Select an audio contract: silent, native audio in every clip, an existing
+ Music track, or one generated soundtrack bed. Generated audio names a local
+ engine, model and prompt. An unavailable engine blocks Start. A short bed
+ repeats through Timeline to cover the cut, within its 20-track lane limit;
+ choose a longer track if it would require more repetitions. Soundtracks
+ replace clip audio. Native audio does not promise dialogue or lip sync.
+4. Review the resolved choices and explicit clip, audio-job, agent-call, retry
+ and replan limits, then select **Start production**. Counts include previous
+ attempts. Provider prices and balances can be unknown; an optional dollar
+ cap blocks calls without enforceable pricing rather than claiming a budget
+ guarantee. No Reactor balance endpoint is assumed.
+5. The treatment becomes a revisioned script and timed shot artifact. Review
+ mode gates script/shot plan, references, rough cut and final cut at the saved
+ checkpoints. Autonomous mode skips human decisions after artifacts exist.
+ Thumbs and notes are optional feedback; they do not approve or dispatch work.
+6. Accepted shots (or completed bounded video-plan steps) enter the existing
+ Timeline renderer. The output includes all required clips, trims excess at
+ the exact target, and supports straight cuts or fades through black. These
+ fades do not overlap shots or shorten the timeline. Clips too short for
+ their planned timing block assembly; missing shots cannot silently disappear.
+7. The rough cut is playable before approval. Final review uses the same
+ validated cut unless a revision changes it. Delivery requires an existing
+ playable file, verified video stream, the chosen audio contract, and duration
+ within both the saved range and one output frame of the exact target.
+ Missing ffprobe, unreadable media, incorrect timing or missing requested
+ audio cannot produce a completed project.
+8. Play or download the final video, open Media History, the project collection,
+ or its reusable Timeline. Soundtrack placements remain in that Timeline;
+ generated beds also become standalone Music Tracks. Previous cuts and partial
+ clips stay accessible after revisions.
+
+## Pause, review and recovery
+
+Pause and Stop revoke authorization before canceling owned agents, render jobs
+and Timeline assembly where supported. A provider may already have accepted or
+charged for work that cannot be confirmed canceled. Such submissions remain
+uncertain and require queue reconciliation or explicit retry consent.
+
+Restart reads receipts and completed outputs without starting new provider work.
+Resume reconciles stored job/task IDs first, reuses completed assets and applies
+the reviewed limits. Settings can be edited while a Video project is draft,
+paused or failed; creative edits invalidate dependent review revisions.
+Approving an obsolete revision is rejected, and late callbacks cannot overwrite
+newer work. An assembly failure keeps partial media and provides a visible reason
+with links to repair settings, review artifacts, inspect queues or open Timeline.
+
+Execution authority belongs to the creating install. Synced replicas cannot
+start a second production. See [Storage](../STORAGE.md) for JSONB, file assets,
+backup and cross-version gates. Legacy generalized Creative Director projects
+retain their prior behavior.
+
+## Verification without provider charges
+
+`server/services/creativeDirector/videoAssembly.test.js` creates synthetic
+multi-shot Reactor-like results, then exercises the real Timeline/ffmpeg boundary,
+including trimming, audio preservation, distinct cut approvals and validation
+failures. It makes no AI-provider calls. Tests require local ffmpeg/ffprobe and
+skip that real media exercise when they are unavailable. Other execution tests
+use fake queues, task providers and audio generation. DB-backed tests run only
+against `portos_test` through the documented test command.
+
+## Optional real-render smoke test
+
+Run this only when deliberately choosing to spend provider credits; it is never
+part of boot or CI. Configure the intended backend credentials and eligible
+cognitive stages. Create a fresh standalone Video draft for a 60–180 second
+animated woodland short, select Reactor, set silent audio (or explicitly choose
+a soundtrack), and keep review mode enabled. Verify the exact target and resolved
+providers before Start; set a clip bound sufficient for that target plus only
+the retries you intend to fund. Leave the dollar cap unset only if accepting
+unknown cost with the displayed call bounds.
+
+Approve the current script and references, inspect one rendered shot and queue
+receipt, then pause. Confirm no new job is submitted while paused. Resume, approve
+the actual rough and final cuts, and play/download the delivered file. Confirm its
+duration, requested audio, separate assembled media ID, collection entry and
+Timeline placements. Optionally restart while paused and verify it remains paused.
+An uncertain submission requires inspecting the provider/queue and explicit retry
+consent; do not rerun blindly. Delete or archive only this smoke project's assets
+when finished.
diff --git a/server/lib/README.md b/server/lib/README.md
index cb63db1dbc..ad9401abc5 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -606,4 +606,4 @@ pm` default, `NPM_CONFIG_PREFIX`, nvm/Volta) installed `codex` successfully and
| `cosFederationPolicy.js` | `isMachineLocalCosTask` excludes private assessments and explicitly machine-local tasks and agent archives from federation. |
-| `creativeDirectorVideoReview.js` | Video checkpoint fingerprints, owner-only review actions, feedback, and targeted revision invalidation. |
+| `creativeDirectorVideoReview.js` | `retainVideoCuts` preserves rendered cut references on invalidation. Video checkpoint fingerprints, owner-only review actions, feedback, and targeted revision invalidation. |
diff --git a/server/lib/creativeDirectorValidation.js b/server/lib/creativeDirectorValidation.js
index 68d21f61fa..56d29ff007 100644
--- a/server/lib/creativeDirectorValidation.js
+++ b/server/lib/creativeDirectorValidation.js
@@ -128,6 +128,7 @@ export const creativeDirectorVideoLimitsSchema = z.object({
maxClips: z.number().int().min(1).max(200).default(60),
maxRetries: z.number().int().min(0).max(3).default(1),
maxReplans: z.number().int().min(0).max(5).default(2),
+ maxAudioJobs: z.number().int().min(0).max(4).default(1),
maxAgentCalls: z.number().int().min(1).max(500).default(100),
spendCapUsd: z.number().positive().max(10000).nullable().default(null),
}).strict();
@@ -148,7 +149,11 @@ export const creativeDirectorVideoDraftSchema = z.object({
id: z.string().trim().min(1).max(120),
revision: z.string().max(120).optional(),
}).strict()).max(50).default([]),
+ transition: z.enum(['cut', 'fade']).default('cut'),
audio: z.object({
+ mode: z.enum(['silent', 'native', 'imported', 'generated']).default('native'),
+ trackId: z.string().max(120).optional(),
+ prompt: z.string().trim().max(1000).optional(),
providerId: z.string().max(120).optional(),
model: z.string().max(200).optional(),
}).strict().default({}),
diff --git a/server/lib/creativeDirectorVideoReview.js b/server/lib/creativeDirectorVideoReview.js
index b7d7169e9b..c9b597c3a6 100644
--- a/server/lib/creativeDirectorVideoReview.js
+++ b/server/lib/creativeDirectorVideoReview.js
@@ -57,6 +57,15 @@ export function videoReviewStages(project) {
});
}
+/** Preserve rendered cuts when an edit invalidates their approvals. */
+export function retainVideoCuts(project) {
+ const cuts = [...(project.videoCutHistory || [])];
+ for (const cut of [project.videoRoughCut, project.videoFinalCut]) {
+ if (cut?.videoId && !cuts.some(row => row.videoId === cut.videoId)) cuts.push(cut);
+ }
+ return cuts;
+}
+
/** One atomic owner action; feedback never changes authorization or artifact readiness. */
export function applyVideoReviewAction(project, input, instanceId, now = new Date().toISOString()) {
assertVideoOwner(project, instanceId);
@@ -113,7 +122,7 @@ export function applyVideoReviewAction(project, input, instanceId, now = new Dat
plan = { ...plan, history: [...(plan.history || []), { steps: structuredClone(plan.steps), updatedAt: plan.updatedAt }],
steps: plan.steps.map(step => affected.has(step.stepId) ? { ...step, status: 'pending', result: null, workRevision: (step.workRevision || 0) + 1 } : step) };
}
- return { project: { ...project, treatment, plan, status: 'paused', finalVideoId: null,
+ return { project: { ...project, treatment, plan, status: 'paused', finalVideoId: null, videoCutHistory: retainVideoCuts(project),
...(index <= 2 ? { videoRoughCut: null } : {}), videoFinalCut: null,
videoWorkRevision: (project.videoWorkRevision || 0) + 1,
videoReview: { ...review, decisions, waitingFor: null,
diff --git a/server/lib/schemaVersions.js b/server/lib/schemaVersions.js
index 29edc03bb5..8fc1e9ef74 100644
--- a/server/lib/schemaVersions.js
+++ b/server/lib/schemaVersions.js
@@ -455,7 +455,8 @@ export const PORTOS_SCHEMA_VERSIONS = Object.freeze({
// v7: Planning binds to resolved source revisions; older writers skip that guard.
// v8: Revision-bound approvals and machine-local execution authority.
// v9: Bounded owner execution receipts and fail-closed restart reconciliation.
- creativeDirectorProjects: 9,
+ // v10: Validated assembled cuts, retained cut history, and explicit standalone audio.
+ creativeDirectorProjects: 10,
// v1 = Mood boards (PostgreSQL `mood_boards`) federated via the per-record
// peer-sync push pipeline (record kind `moodBoard`, sync category `moodBoards`,
// #1564). Same posture as `creativeDirectorProjects` above: a brand-NEW synced
diff --git a/server/services/creativeDirector/agentBridge.js b/server/services/creativeDirector/agentBridge.js
index 8681fb715c..3b7f3bc6ea 100644
--- a/server/services/creativeDirector/agentBridge.js
+++ b/server/services/creativeDirector/agentBridge.js
@@ -91,6 +91,8 @@ async function buildTaskRecord(project, kind, scene, context) {
let attempt;
if (project.workspace === 'video') {
const { reserveVideoAttempt, assertVideoAttemptDispatch } = await import('./videoExecution.js');
+ const audio = project.videoExecution?.choices?.audio || project.videoDraft?.audio || { mode: 'native' };
+ context = `${context}\n\nSaved Video audio contract: ${JSON.stringify(audio)}. Soundtracks are assembled separately; do not enqueue audio or assume the video renderer supplies dialogue or lip sync. Plan visual storytelling to fit this audio choice. Shot joins: ${project.videoDraft?.transition || 'cut'}; joins do not overlap or shorten the saved shot timing.`;
attempt = await reserveVideoAttempt(project.id, { kind, expectedProductionRevision: project.videoWorkRevision || 0, key: `${kind}:${scene?.sceneId || 'project'}`, ...(scene ? { sceneId: scene.sceneId, workRevision: scene.workRevision || 0 } : {}) });
if (!attempt) return null;
await assertVideoAttemptDispatch(project.id, attempt.id).catch(async error => {
diff --git a/server/services/creativeDirector/agentBridge.test.js b/server/services/creativeDirector/agentBridge.test.js
index 5c551b6db3..ccc3b0e6a0 100644
--- a/server/services/creativeDirector/agentBridge.test.js
+++ b/server/services/creativeDirector/agentBridge.test.js
@@ -49,11 +49,12 @@ describe('Video planning source context', () => {
{ type: 'function', function: { name: 'media_enqueueVideoJob', description: 'Video', parameters: {} } },
{ type: 'function', function: { name: 'pipeline_runSeriesAutopilot', description: 'Batch', parameters: {} } },
]);
- const video = { ...project, workspace: 'video', videoDraft: { sources: [] } };
+ const video = { ...project, workspace: 'video', videoDraft: { sources: [], audio: { mode: 'silent' } } };
await enqueuePlanTask(video);
expect(mocks.buildPlanPrompt.mock.calls[0][1].toolSpecs).toEqual([
expect.objectContaining({ function: expect.objectContaining({ name: 'media_enqueueVideoJob', description: expect.stringContaining('exactly one clip') }) }),
]);
+ expect(mocks.addTask.mock.calls[0][0].metadata.context).toContain('Saved Video audio contract: {"mode":"silent"}');
mocks.addTask.mockRejectedValueOnce(new Error('store unavailable'));
await expect(enqueueTreatmentTask(video)).rejects.toThrow('store unavailable');
expect(settleVideoAttempt).toHaveBeenLastCalledWith('cd-1', 'example-attempt', { status: 'failed' });
diff --git a/server/services/creativeDirector/projectsLogic.js b/server/services/creativeDirector/projectsLogic.js
index 61b8b19121..7bde9aabc2 100644
--- a/server/services/creativeDirector/projectsLogic.js
+++ b/server/services/creativeDirector/projectsLogic.js
@@ -10,7 +10,7 @@
* read/write to the caller.
*/
-import { videoSceneInputs } from '../../lib/creativeDirectorVideoReview.js';
+import { videoSceneInputs, retainVideoCuts } from '../../lib/creativeDirectorVideoReview.js';
import { randomUUID } from 'crypto';
import { EFFORT_LEVELS } from '../../lib/providerModels.js';
import { ServerError } from '../../lib/errorHandler.js';
@@ -368,6 +368,7 @@ export function applyProjectPatch(project, patch) {
next.treatment = { ...project.treatment, artifact: { ...project.treatment.artifact, stale: true },
scenes: project.treatment.scenes.map(scene => ({ ...scene, workRevision: (scene.workRevision || 0) + 1 })) };
next.videoWorkRevision = (project.videoWorkRevision || 0) + 1;
+ next.videoCutHistory = retainVideoCuts(project);
next.videoRoughCut = null;
next.videoFinalCut = null;
next.finalVideoId = null;
@@ -509,7 +510,7 @@ export function applyTreatment(project, treatmentInput, sourceRevisions) {
return {
...project,
treatment,
- ...(project.workspace === 'video' ? { videoRoughCut: null, videoFinalCut: null, finalVideoId: null } : {}),
+ ...(project.workspace === 'video' ? { videoCutHistory: retainVideoCuts(project), videoRoughCut: null, videoFinalCut: null, finalVideoId: null } : {}),
status: nextStatus,
updatedAt: new Date().toISOString(),
};
@@ -595,7 +596,7 @@ export function applyPlan(project, planInput) {
: 'rendering';
return {
...project,
- ...(project.workspace === 'video' ? { videoWorkRevision: (project.videoWorkRevision || 0) + 1, videoRoughCut: null, videoFinalCut: null, finalVideoId: null } : {}),
+ ...(project.workspace === 'video' ? { videoCutHistory: retainVideoCuts(project), videoWorkRevision: (project.videoWorkRevision || 0) + 1, videoRoughCut: null, videoFinalCut: null, finalVideoId: null } : {}),
plan: { steps, replanRounds, ...(project.workspace === 'video' ? { submittedProductionRevision: project.videoWorkRevision || 0 } : {}), ...(project.workspace === 'video' && project.plan ? { history: [...(project.plan.history || []), { steps: structuredClone(prevSteps), updatedAt: project.plan.updatedAt }] } : {}), ...(parsed.data.sourceContextRevision ? { sourceContextRevision: parsed.data.sourceContextRevision } : {}), updatedAt: new Date().toISOString() },
status: nextStatus,
updatedAt: new Date().toISOString(),
@@ -648,10 +649,14 @@ export function applySceneUpdate(project, sceneId, patch) {
const scenes = project.treatment.scenes.slice();
scenes[sceneIdx] = updated;
const treatment = { ...project.treatment, scenes };
- if (project.workspace === 'video' && treatment.artifact
- && ['prompt', 'imageStrength'].some((key) => key in patch && patch[key] !== project.treatment.scenes[sceneIdx][key])) {
+ const creativeEdit = project.workspace === 'video' && treatment.artifact
+ && ['prompt', 'imageStrength'].some((key) => key in patch && patch[key] !== previousScene[key]);
+ if (creativeEdit) {
validateVideoShot(project, updated, sceneId === [...scenes].sort((a, b) => a.order - b.order)[0].sceneId);
updated.workRevision = (previousScene.workRevision || 0) + 1;
+ updated.status = 'pending';
+ updated.renderedJobId = null;
+ updated.evaluation = null;
// A shot edit changes the reviewed content, but cannot refresh stale source context.
treatment.artifact = { ...treatment.artifact, revision: treatment.artifact.revision + 1 };
treatment.history = priorVideoTreatments(project);
@@ -659,6 +664,7 @@ export function applySceneUpdate(project, sceneId, patch) {
const next = {
...project,
treatment,
+ ...(creativeEdit ? { status: 'paused', videoWorkRevision: (project.videoWorkRevision || 0) + 1, videoCutHistory: retainVideoCuts(project), videoRoughCut: null, videoFinalCut: null, finalVideoId: null } : {}),
updatedAt: new Date().toISOString(),
};
return { project: next, updated };
diff --git a/server/services/creativeDirector/stitchRunner.js b/server/services/creativeDirector/stitchRunner.js
index 73975112ea..27bf564d6d 100644
--- a/server/services/creativeDirector/stitchRunner.js
+++ b/server/services/creativeDirector/stitchRunner.js
@@ -39,8 +39,8 @@ export async function runStitch(projectId) {
return;
}
if (project.workspace === 'video') {
- const { videoReviewAllowsDispatch } = await import('./videoReview.js');
- if (!await videoReviewAllowsDispatch(projectId, ['script-shot-plan', 'references'])) return;
+ const { runVideoAssembly } = await import('./videoAssembly.js');
+ return runVideoAssembly(projectId);
}
const clips = buildTimelineClips(project);
if (!clips.length) {
diff --git a/server/services/creativeDirector/stopProject.js b/server/services/creativeDirector/stopProject.js
index d0bda63225..ee17206392 100644
--- a/server/services/creativeDirector/stopProject.js
+++ b/server/services/creativeDirector/stopProject.js
@@ -176,6 +176,10 @@ export async function stopProject(projectId, { reason = 'Stopped', project: prer
const { pauseVideoExecution } = await import('./videoExecution.js');
// If the durable stop fails, do not pretend subsequent teardown is safe.
await pauseVideoExecution(projectId, reason, { invalidate: true });
+ if (project.videoExecution?.assembly?.jobId) {
+ const { cancelRender } = await import('../videoTimeline/local.js');
+ cancelRender(project.videoExecution.assembly.jobId);
+ }
} else await updateProject(projectId, { status: 'paused', failureReason: reason })
.catch((e) => console.error(`❌ CD stop ${projectId}: park failed: ${e.message}`));
@@ -213,7 +217,7 @@ export async function stopProject(projectId, { reason = 'Stopped', project: prer
if (project.workspace === 'video') {
const { mutateVideoProject } = await import('./local.js');
await mutateVideoProject(projectId, current => ({ project: { ...current, videoExecution: { ...current.videoExecution,
- attempts: (current.videoExecution?.attempts || []).map(attempt => attempt.kind !== 'clip' && ['running', 'submitting'].includes(attempt.status) ? { ...attempt, status: 'failed' } : attempt),
+ attempts: (current.videoExecution?.attempts || []).map(attempt => !['clip', 'audio'].includes(attempt.kind) && ['running', 'submitting'].includes(attempt.status) ? { ...attempt, status: 'failed' } : attempt),
} }, result: true }));
}
console.log(`🛑 CD project ${projectId} stopped: ${reason} (${retired.runs} run(s), ${retired.tasks} task(s), ${retired.agents} agent(s), ${jobs} job(s))`);
diff --git a/server/services/creativeDirector/videoAssembly.js b/server/services/creativeDirector/videoAssembly.js
new file mode 100644
index 0000000000..b4c775271f
--- /dev/null
+++ b/server/services/creativeDirector/videoAssembly.js
@@ -0,0 +1,162 @@
+/** Video final-cut contract on the existing Timeline renderer and media history. */
+import { join } from 'path';
+import { PATHS, sleep } from '../../lib/fileUtils.js';
+import { safeUnder, verifyVideoPlayable, probeVideoDuration, probeVideoStreamInfo, hasAudioStream } from '../../lib/ffmpeg.js';
+import { canonicalSnapshotChecksum } from '../../lib/snapshotChecksum.js';
+import { ServerError } from '../../lib/errorHandler.js';
+
+const inFlight = new Set();
+const fail = message => new ServerError(message, { status: 409, code: 'VIDEO_ASSEMBLY_BLOCKED' });
+
+/** Check actual files, not render status or metadata claims. */
+export async function validateVideoCut(project, entry) {
+ if (!entry?.filename || !safeUnder(PATHS.videos, entry.filename)) throw fail('The assembled video file is missing. Open Timeline and render the cut again.');
+ const path = join(PATHS.videos, entry.filename);
+ const playable = await verifyVideoPlayable(path);
+ if (!playable.ok) throw fail(`The assembled video is not playable: ${playable.reason}. Open Timeline to repair it.`);
+ const [durationSeconds, stream, audio] = await Promise.all([probeVideoDuration(path), probeVideoStreamInfo(path), hasAudioStream(path)]);
+ if (!(durationSeconds > 0 && stream.fps > 0 && stream.width > 0 && stream.height > 0)) throw fail('The final video stream could not be verified. Install working ffmpeg and ffprobe before retrying assembly.');
+ const range = project.videoDraft.durationRange;
+ const tolerance = 1 / stream.fps + 1e-6;
+ if (durationSeconds < range.min - tolerance || durationSeconds > range.max + tolerance) throw fail(`The assembled duration (${durationSeconds.toFixed(2)} seconds) is outside the requested ${range.min}–${range.max} seconds. Revise shot timing or the requested range.`);
+ if (Math.abs(durationSeconds - project.targetDurationSeconds) > tolerance) throw fail('The assembled cut does not match the saved exact duration target. Revise the shot timing before resuming.');
+ const audioMode = project.videoExecution.choices.audio.mode || 'native';
+ if (audioMode === 'silent' ? audio : !audio) throw fail(audioMode === 'silent' ? 'The silent cut still contains an audio stream.' : 'The final cut is missing its requested audio stream. Choose a soundtrack or a renderer that supplies native audio.');
+ return { videoId: entry.id, filename: entry.filename, durationSeconds, fps: stream.fps, audioMode };
+}
+
+async function prepareClips(project, history) {
+ const requested = project.directive && project.plan?.steps?.length
+ ? project.plan.steps.map(step => {
+ if (step.status !== 'done' || step.toolName !== 'media_enqueueVideoJob' || !step.result?.jobId) throw fail('Every planned clip must finish before assembly. Review the failed or incomplete steps.');
+ return { clipId: step.result.jobId, outSec: step.args?.params?.durationSeconds };
+ })
+ : [...(project.treatment?.scenes || [])].sort((a, b) => a.order - b.order).map(scene => {
+ if (scene.status !== 'accepted' || !scene.renderedJobId) throw fail('Every shot must be accepted before assembly. Partial clips remain available in Artifacts.');
+ return { clipId: scene.renderedJobId, outSec: scene.durationSeconds };
+ });
+ if (!requested.length) throw fail('No completed clips are available to assemble.');
+ const segments = [];
+ let remaining = project.targetDurationSeconds;
+ for (const clip of requested) {
+ const entry = history.find(row => row.id === clip.clipId);
+ if (!entry?.filename || !safeUnder(PATHS.videos, entry.filename)) throw fail(`A required clip (${clip.clipId}) is missing from Media History.`);
+ const path = join(PATHS.videos, entry.filename);
+ const playable = await verifyVideoPlayable(path);
+ if (!playable.ok) throw fail(`A required clip is not playable: ${playable.reason}. Revise or render that shot again.`);
+ const [duration, stream, audio] = await Promise.all([probeVideoDuration(path), probeVideoStreamInfo(path), hasAudioStream(path)]);
+ if (!(duration > 0 && stream.fps > 0)) throw fail('A source clip duration could not be verified. Check ffprobe and the source file.');
+ if (project.videoExecution.choices.audio.mode === 'native' && !audio) throw fail('A source clip has no native audio. Select silent or a soundtrack before resuming.');
+ if (!(clip.outSec > 0) || clip.outSec > duration + 1 / stream.fps + 1e-6) throw fail('A rendered clip is shorter than its planned shot. Revise the timing or render the shot again.');
+ if (remaining <= 0) throw fail('The planned shots exceed the exact target before the last shot. Revise their timing so every shot fits the final cut.');
+ const outSec = Math.min(clip.outSec, duration, remaining);
+ const fadeSec = project.videoDraft.transition === 'fade' ? Math.min(0.25, outSec / 2) : 0;
+ segments.push({ type: 'clip', clipId: clip.clipId, inSec: 0, outSec, fadeInSec: fadeSec, fadeOutSec: fadeSec });
+ remaining -= outSec;
+ }
+ if (!segments.length) throw fail('The requested cut has no playable duration.');
+ return segments;
+}
+
+export async function runVideoAssembly(projectId) {
+ if (inFlight.has(projectId)) return;
+ inFlight.add(projectId);
+ const { getProject, mutateVideoProject } = await import('./local.js');
+ const { videoReviewAllowsDispatch } = await import('./videoReview.js');
+ const { videoConfigurationRevision } = await import('./videoExecution.js');
+ let project;
+ const matches = current => current?.videoExecution?.authorized && ['rendering', 'stitching'].includes(current.status)
+ && (current.videoWorkRevision || 0) === (project?.videoWorkRevision || 0)
+ && current.videoExecution.inputRevision === videoConfigurationRevision(current);
+ const isCurrent = async () => matches(await getProject(projectId));
+ const save = patch => mutateVideoProject(projectId, current => matches(current)
+ ? { project: { ...current, ...patch, updatedAt: new Date().toISOString() }, result: true }
+ : { project: current, result: false, skipPersist: true });
+ try {
+ if (!await videoReviewAllowsDispatch(projectId, ['script-shot-plan', 'references'])) return;
+ project = await getProject(projectId);
+ if (!matches(project)) return;
+ const timeline = await import('../videoTimeline/local.js');
+ const { loadHistory } = await import('../videoGen/local.js');
+ const { prepareVideoSoundtrack } = await import('./videoAudio.js');
+ const { muxStripAudio, resolveMusicTrackPath } = await import('../pipeline/audioMux.js');
+ const history = await loadHistory();
+ const segments = await prepareClips(project, history);
+ const contentRevision = canonicalSnapshotChecksum({ segments, audio: project.videoExecution.choices.audio,
+ input: project.videoExecution.inputRevision, revision: project.videoWorkRevision || 0 });
+ let entry = project.videoRoughCut?.contentRevision === contentRevision
+ ? history.find(row => row.id === project.videoRoughCut.videoId) : null;
+ if (!entry) {
+ await save({ status: 'stitching', failureReason: null });
+ const soundtrack = await prepareVideoSoundtrack(project, isCurrent);
+ if (!await isCurrent()) return;
+ if (['imported', 'generated'].includes(project.videoExecution.choices.audio.mode) && !soundtrack) return;
+ let timelineProject = project.timelineProjectId ? await timeline.getProject(project.timelineProjectId).catch(() => null) : null;
+ if (!timelineProject) timelineProject = await timeline.createProject(`${project.name} — Final Cut`);
+ if (!await isCurrent()) return;
+ await save({ timelineProjectId: timelineProject.id });
+ // Replace all lanes deliberately: reused timelines must not retain unrelated overlays or beds.
+ const tracks = [];
+ const audioMode = project.videoExecution.choices.audio.mode;
+ if (soundtrack) {
+ const audioPath = await resolveMusicTrackPath(soundtrack.filename);
+ const duration = audioPath && await probeVideoDuration(audioPath);
+ if (!(duration > 0) || !await hasAudioStream(audioPath)) throw fail('The soundtrack is not playable. Repair it in Music before resuming.');
+ const total = segments.reduce((sum, clip) => sum + clip.outSec - clip.inSec, 0);
+ const { MAX_AUDIO_TRACKS } = await import('../videoTimeline/segments.js');
+ if (Math.ceil(total / duration) > MAX_AUDIO_TRACKS) throw fail('The soundtrack is too short for this cut. Choose a longer track before resuming.');
+ for (let startSec = 0; startSec < total; startSec += duration) tracks.push({ assetKind: 'music', assetFile: soundtrack.filename, startSec, offsetSec: 0, durationSec: Math.min(duration, total - startSec), volume: 1 });
+ }
+ await timeline.updateProject(timelineProject.id, { segments, overlays: [], audio: { clipVolume: audioMode === 'native' ? 1 : 0, tracks } });
+ const prior = project.videoExecution.assembly;
+ let jobId = prior?.contentRevision === contentRevision ? prior.jobId : null;
+ entry = jobId ? history.find(row => row.id === jobId) : null;
+ if (!entry && !['running', 'pending'].includes(timeline.getRenderJobStatus(jobId)?.status)) {
+ if (!await isCurrent()) return;
+ ({ jobId } = await timeline.renderProject(timelineProject.id));
+ await mutateVideoProject(projectId, current => matches(current)
+ ? { project: { ...current, videoExecution: { ...current.videoExecution, assembly: { jobId, contentRevision, timelineProjectId: timelineProject.id } } }, result: true }
+ : { project: current, result: false, skipPersist: true });
+ }
+ const deadline = Date.now() + 30 * 60 * 1000;
+ while (!entry && Date.now() < deadline) {
+ if (!await isCurrent()) { timeline.cancelRender(jobId); return; }
+ const status = timeline.getRenderJobStatus(jobId);
+ if (['error', 'canceled'].includes(status?.status)) throw fail(`Timeline assembly ${status.status}: ${status.error || 'Open Timeline to inspect the cut.'}`);
+ entry = (await loadHistory()).find(row => row.id === jobId);
+ if (!entry) await sleep(1000);
+ }
+ if (!entry) { timeline.cancelRender(jobId); throw fail('Timeline assembly timed out. Partial clips remain available; inspect Timeline and Resume.'); }
+ if (!await isCurrent()) return;
+ const path = safeUnder(PATHS.videos, entry.filename) ? join(PATHS.videos, entry.filename) : null;
+ if (!path) throw fail('Timeline returned an invalid output path.');
+ const mode = project.videoExecution.choices.audio.mode;
+ const muxed = mode === 'silent' ? await muxStripAudio(path) : { ok: true };
+ if (!muxed.ok) throw fail(`Could not apply the selected audio: ${muxed.reason}. Repair the soundtrack before resuming.`);
+ }
+ if (!await isCurrent()) return;
+ const artifact = { ...await validateVideoCut(project, entry), contentRevision };
+ if (!(await save({ videoRoughCut: artifact })).result) return;
+ if (!await videoReviewAllowsDispatch(projectId, ['rough-cut'])) return;
+ if (!(await save({ videoFinalCut: artifact })).result) return;
+ if (!await videoReviewAllowsDispatch(projectId, ['final-cut'])) return;
+ // Revalidate at delivery, including a resume after the file was reviewed or removed.
+ await validateVideoCut(project, entry);
+ if (project.collectionId) {
+ const { addItem } = await import('../mediaCollections.js');
+ await addItem(project.collectionId, { kind: 'video', ref: entry.id });
+ }
+ await save({ finalVideoId: entry.id, status: 'complete', failureReason: null });
+ } catch (error) {
+ if (project) {
+ const { retainVideoCuts } = await import('../../lib/creativeDirectorVideoReview.js');
+ await mutateVideoProject(projectId, current => matches(current)
+ ? { project: { ...current, status: 'paused', failureReason: `${error.message} Review Artifacts, Timeline, or production settings, then Resume.`,
+ videoCutHistory: retainVideoCuts(current), videoRoughCut: null, videoFinalCut: null, finalVideoId: null,
+ videoExecution: { ...current.videoExecution, assembly: null }, updatedAt: new Date().toISOString() }, result: true }
+ : { project: current, result: false, skipPersist: true });
+ }
+ } finally {
+ inFlight.delete(projectId);
+ }
+}
diff --git a/server/services/creativeDirector/videoAssembly.test.js b/server/services/creativeDirector/videoAssembly.test.js
new file mode 100644
index 0000000000..2f06988a9c
--- /dev/null
+++ b/server/services/creativeDirector/videoAssembly.test.js
@@ -0,0 +1,125 @@
+import { afterAll, beforeAll, beforeEach, expect, it, vi } from 'vitest';
+import { execFile } from 'node:child_process';
+import { promisify } from 'node:util';
+import { mkdir, rm, writeFile } from 'node:fs/promises';
+import { join } from 'node:path';
+const state = vi.hoisted(() => ({ root: null, project: null, history: [], collection: [], tracks: [] }));
+vi.mock('../../lib/fileUtils.js', async importOriginal => {
+ const original = await importOriginal();
+ const { mkdtemp } = await import('node:fs/promises');
+ const { tmpdir } = await import('node:os');
+ const { join } = await import('node:path');
+ state.root = await mkdtemp(join(tmpdir(), 'video-assembly-test-'));
+ return { ...original, PATHS: { ...original.PATHS, data: state.root, videos: join(state.root, 'videos'), music: join(state.root, 'music'), videoThumbnails: join(state.root, 'thumbnails') }, sleep: () => new Promise(resolve => setTimeout(resolve, 20)) };
+});
+vi.mock('./local.js', () => ({
+ getProject: async () => structuredClone(state.project),
+ mutateVideoProject: async (_id, mutate) => { const outcome = mutate(structuredClone(state.project)); if (!outcome.skipPersist) state.project = outcome.project; return outcome; },
+}));
+vi.mock('../videoGen/local.js', () => ({ loadHistory: async () => state.history, mutateVideoHistory: async mutate => { state.history = mutate(state.history); return state.history; } }));
+vi.mock('../instances.js', () => ({ getInstanceId: async () => 'example-owner' }));
+vi.mock('./videoSources.js', () => ({ assertVideoSourcesAvailable: async () => {} }));
+vi.mock('../mediaCollections.js', () => ({ addItem: async (_id, item) => { state.collection.push(item); } }));
+vi.mock('../tracks/index.js', () => ({ getTrack: async id => state.tracks.find(track => track.id === id) }));
+// Keep library lookup inside this test's music directory while exercising the real mux.
+vi.mock('../pipeline/musicLibrary.js', () => ({ statMusicTrack: async filename => ({ filename }) }));
+import { findFfmpeg, findFfprobe, hasAudioStream } from '../../lib/ffmpeg.js';
+import { videoConfigurationRevision } from './videoExecution.js';
+import { videoReviewStages, applyVideoReviewAction } from '../../lib/creativeDirectorVideoReview.js';
+import { runVideoAssembly, validateVideoCut } from './videoAssembly.js';
+const exec = promisify(execFile);
+let ffmpeg;
+beforeAll(async () => {
+ ffmpeg = await findFfmpeg();
+ if (!ffmpeg || !await findFfprobe()) { ffmpeg = null; return; }
+ await Promise.all(['videos', 'music', 'thumbnails'].map(dir => mkdir(join(state.root, dir), { recursive: true })));
+ for (const [index, color] of ['red', 'blue'].entries()) await exec(ffmpeg, ['-y', '-f', 'lavfi', '-i', `color=c=${color}:s=64x64:r=24:d=3`, '-c:v', 'libx264', '-pix_fmt', 'yuv420p', '-an', join(state.root, 'videos', `reactor-${index}.mp4`)]);
+ await exec(ffmpeg, ['-y', '-f', 'lavfi', '-i', 'sine=frequency=440:duration=2', join(state.root, 'music', 'example-bed.wav')]);
+}, 30000);
+afterAll(async () => { await rm(state.root, { recursive: true, force: true }); });
+beforeEach(() => {
+ state.collection = [];
+ state.tracks = [{ id: 'example-track', audioFilename: 'example-bed.wav' }];
+ state.history = [0, 1].map(i => ({ id: `00000000-0000-4000-8000-00000000000${i}`, filename: `reactor-${i}.mp4`, width: 64, height: 64, fps: 24, numFrames: 72, modelId: 'reactor' }));
+ state.project = { id: 'example-video', name: 'Example short', workspace: 'video', videoOwnerInstanceId: 'example-owner', status: 'rendering', targetDurationSeconds: 5,
+ collectionId: 'example-collection', videoDraft: { durationRange: { min: 5, max: 6 }, audio: { mode: 'silent' }, transition: 'fade', sources: [], reviewPolicy: 'autonomous' },
+ treatment: { script: 'A color study.', artifact: { revision: 1 }, scenes: [0, 1].map(i => ({ sceneId: `shot-${i}`, order: i, status: 'accepted', renderedJobId: `00000000-0000-4000-8000-00000000000${i}`, durationSeconds: 3 })) },
+ videoExecution: { authorized: true, choices: { audio: { mode: 'silent' } }, attempts: [] } };
+ state.project.videoExecution.inputRevision = videoConfigurationRevision(state.project);
+});
+const requireFfmpeg = context => { if (!ffmpeg) context.skip(); };
+
+it('assembles a one-minute standalone cut from fake Reactor clips through real Timeline and links reusable outputs', async context => {
+ requireFfmpeg(context);
+ state.project.targetDurationSeconds = 60;
+ state.project.videoDraft.durationRange = { min: 60, max: 180 };
+ state.project.treatment.scenes = Array.from({ length: 20 }, (_, order) => ({ ...state.project.treatment.scenes[order % 2], sceneId: `shot-${order}`, order }));
+ state.project.videoExecution.inputRevision = videoConfigurationRevision(state.project);
+ await runVideoAssembly('example-video');
+ expect(state.project.failureReason).toBeNull();
+ expect(state.project.status).toBe('complete');
+ expect(state.project.finalVideoId).not.toBe('00000000-0000-4000-8000-000000000001');
+ expect(state.project.videoFinalCut).toMatchObject({ audioMode: 'silent', durationSeconds: 60 });
+ const { getProject } = await import('../videoTimeline/local.js');
+ const timeline = await getProject(state.project.timelineProjectId);
+ expect(timeline.segments).toHaveLength(20);
+ expect(timeline.segments.reduce((sum, segment) => sum + segment.outSec - segment.inSec, 0)).toBe(60);
+ expect(timeline.segments[0].fadeOutSec).toBe(0.25);
+ expect(await hasAudioStream(join(state.root, 'videos', state.project.videoFinalCut.filename))).toBe(false);
+ expect(state.collection).toEqual([{ kind: 'video', ref: state.project.finalVideoId }]);
+}, 30000);
+
+it('holds real rough/final artifacts for distinct approvals and reuses the rendered file on each continuation', async context => {
+ requireFfmpeg(context);
+ state.project.videoDraft.reviewPolicy = 'review';
+ state.project.videoExecution.inputRevision = videoConfigurationRevision(state.project);
+ const approve = stage => {
+ const row = videoReviewStages(state.project).find(item => item.stage === stage);
+ state.project = applyVideoReviewAction(state.project, { action: 'approve', stage, revision: row.revision }, 'example-owner').project;
+ };
+ approve('script-shot-plan');
+ await runVideoAssembly('example-video');
+ expect(state.project.status).toBe('stitching');
+ expect(state.project.videoRoughCut.videoId).toBeTruthy();
+ expect(state.project.videoFinalCut).toBeUndefined();
+ const rendered = state.history.length;
+ approve('rough-cut');
+ await runVideoAssembly('example-video');
+ expect(state.project.videoFinalCut.videoId).toBe(state.project.videoRoughCut.videoId);
+ expect(state.project.finalVideoId).toBeUndefined();
+ approve('final-cut');
+ await runVideoAssembly('example-video');
+ expect(state.project.status).toBe('complete');
+ expect(state.history.length).toBe(rendered);
+}, 30000);
+
+it('assembles directive clips and repeats an imported standalone soundtrack in the reusable Timeline', async context => {
+ requireFfmpeg(context);
+ state.project.directive = { goal: 'Example cut' };
+ state.project.plan = { steps: [0, 1].map(i => ({ stepId: `clip-${i}`, toolName: 'media_enqueueVideoJob', status: 'done', args: { params: { durationSeconds: 3 } }, result: { jobId: `00000000-0000-4000-8000-00000000000${i}` } })) };
+ state.project.videoDraft.audio = { mode: 'imported', trackId: 'example-track' };
+ state.project.videoExecution.choices.audio = { ...state.project.videoDraft.audio, filename: 'example-bed.wav' };
+ state.project.videoExecution.inputRevision = videoConfigurationRevision(state.project);
+ await runVideoAssembly('example-video');
+ expect(state.project.failureReason).toBeNull();
+ expect(state.project.status).toBe('complete');
+ const { getProject } = await import('../videoTimeline/local.js');
+ const timeline = await getProject(state.project.timelineProjectId);
+ expect(timeline.segments.map(segment => segment.outSec)).toEqual([3, 2]);
+ expect(timeline.audio.tracks.map(track => track.durationSec)).toEqual([2, 2, 1]);
+ expect(timeline.audio.clipVolume).toBe(0);
+ expect(await hasAudioStream(join(state.root, 'videos', state.project.videoFinalCut.filename))).toBe(true);
+}, 30000);
+
+it('rejects missing, corrupt, out-of-range and missing-audio finals even when history claims completion', async context => {
+ requireFfmpeg(context);
+ const entry = state.history[0];
+ await expect(validateVideoCut(state.project, { ...entry, filename: 'missing.mp4' })).rejects.toThrow(/not playable/);
+ await writeFile(join(state.root, 'videos', 'corrupt.mp4'), 'not video');
+ await expect(validateVideoCut(state.project, { ...entry, filename: 'corrupt.mp4' })).rejects.toThrow(/not playable/);
+ await expect(validateVideoCut(state.project, entry)).rejects.toThrow(/outside the requested/);
+ state.project.targetDurationSeconds = 3;
+ state.project.videoDraft.durationRange = { min: 3, max: 3 };
+ state.project.videoExecution.choices.audio.mode = 'native';
+ await expect(validateVideoCut(state.project, entry)).rejects.toThrow(/missing its requested audio/);
+});
diff --git a/server/services/creativeDirector/videoAudio.js b/server/services/creativeDirector/videoAudio.js
new file mode 100644
index 0000000000..d0682bc656
--- /dev/null
+++ b/server/services/creativeDirector/videoAudio.js
@@ -0,0 +1,86 @@
+/** Standalone soundtrack selection over the existing music library and audio queue. */
+import { canonicalSnapshotChecksum } from '../../lib/snapshotChecksum.js';
+import { ServerError } from '../../lib/errorHandler.js';
+import { sleep } from '../../lib/fileUtils.js';
+
+const blocked = message => new ServerError(message, { status: 409, code: 'VIDEO_AUDIO_BLOCKED' });
+
+export async function resolveVideoAudioChoice(project) {
+ const audio = project.videoDraft?.audio || {};
+ const mode = audio.mode || 'native';
+ if (mode === 'silent' || mode === 'native') return { mode };
+ if (mode === 'imported') {
+ const { getTrack } = await import('../tracks/index.js');
+ const { resolveMusicTrackPath } = await import('../pipeline/audioMux.js');
+ const track = audio.trackId ? await getTrack(audio.trackId) : null;
+ if (!track?.audioFilename || !await resolveMusicTrackPath(track.audioFilename)) throw blocked('Choose an existing soundtrack in Music before Start.');
+ return { mode, trackId: track.id, filename: track.audioFilename };
+ }
+ const { ENGINES, isEngineHealthy } = await import('../pipeline/musicGen.js');
+ const { hasConfiguredMediaRoute } = await import('../federatedMedia/defaultRouting.js');
+ if (await hasConfiguredMediaRoute('audio')) throw blocked('Disable the standing audio route before using the selected local soundtrack engine.');
+ const engine = ENGINES[audio.providerId];
+ if (!engine || !await isEngineHealthy(engine.id)) throw blocked('The selected audio engine is unavailable. Configure it in Music or change the audio choice.');
+ const model = audio.model || engine.defaultModelId;
+ if (!engine.models.some(entry => entry.id === model)) throw blocked('Select an available model for the chosen audio engine.');
+ if (!audio.prompt?.trim()) throw blocked('Describe the generated soundtrack before Start.');
+ return { mode, providerId: engine.id, model, prompt: audio.prompt,
+ durationSec: Math.min(engine.maxDurationSec, Math.max(engine.minDurationSec, project.targetDurationSeconds)) };
+}
+
+/** One bounded soundtrack job. A short bed loops at assembly; it never expands into a batch. */
+export async function prepareVideoSoundtrack(project, isCurrent) {
+ const audio = { mode: 'native', ...project.videoExecution.choices.audio };
+ if (audio.mode === 'silent' || audio.mode === 'native') return null;
+ const { resolveMusicTrackPath } = await import('../pipeline/audioMux.js');
+ if (audio.mode === 'imported') {
+ const current = await resolveVideoAudioChoice(project);
+ if (current.filename !== audio.filename) throw blocked('The selected soundtrack changed. Review the new choices and Resume.');
+ return { filename: audio.filename, trackId: audio.trackId };
+ }
+ const audioRevision = canonicalSnapshotChecksum(audio);
+ if (project.musicBed?.audioRevision === audioRevision && await resolveMusicTrackPath(project.musicBed.filename)) return project.musicBed;
+ const { reserveVideoAttempt, assertVideoAttemptDispatch, settleVideoAttempt } = await import('./videoExecution.js');
+ const { getJob, enqueueJob } = await import('../mediaJobQueue/index.js');
+ const { getProject, mutateVideoProject } = await import('./local.js');
+ const key = `audio:${audioRevision}`;
+ let attempt = [...(project.videoExecution.attempts || [])].reverse().find(row => row.key === key && ['submitting', 'queued', 'running', 'completed', 'uncertain'].includes(row.status));
+ if (attempt?.status === 'uncertain' || (attempt?.status === 'submitting' && !attempt.jobId)) throw blocked('The previous soundtrack submission is uncertain. Reconcile it or authorize retry before Resume.');
+ if (!attempt) {
+ attempt = await reserveVideoAttempt(project.id, { kind: 'audio', key, expectedProductionRevision: project.videoWorkRevision || 0 });
+ if (!attempt) return null;
+ await assertVideoAttemptDispatch(project.id, attempt.id);
+ // Persist before enqueue; the queue worker checks this receipt again.
+ const { jobId } = enqueueJob({ kind: 'audio', owner: `creative-director:${project.id}`,
+ params: { engine: audio.providerId, modelId: audio.model, prompt: audio.prompt, durationSec: audio.durationSec,
+ videoProduction: { projectId: project.id, attemptId: attempt.id, executionId: attempt.executionId } } });
+ await settleVideoAttempt(project.id, attempt.id, { status: 'queued', jobId });
+ attempt = { ...attempt, jobId };
+ }
+ const deadline = Date.now() + 30 * 60 * 1000;
+ while (Date.now() < deadline) {
+ if (!await isCurrent()) return null;
+ const job = getJob(attempt.jobId);
+ if (!job || ['failed', 'canceled'].includes(job.status)) throw blocked('Soundtrack generation failed or its receipt is missing. Inspect the queue, then Resume within the saved limits.');
+ if (job.status === 'completed') {
+ const filename = job.result?.filename;
+ if (!filename || !await resolveMusicTrackPath(filename)) throw blocked('The generated soundtrack file is missing. Inspect the audio job before retrying.');
+ const { listTracks, createTrack } = await import('../tracks/index.js');
+ const track = (await listTracks()).find(row => row.audioFilename === filename)
+ || await createTrack({ title: `${project.name} — Soundtrack`, audioFilename: filename, engine: audio.providerId, modelId: audio.model, durationSec: job.result.durationSec });
+ const bed = { filename, trackId: track.id, jobId: job.id, audioRevision };
+ await mutateVideoProject(project.id, current => isCurrentSnapshot(current, project) ? { project: { ...current, musicBed: bed }, result: true } : { project: current, result: false, skipPersist: true });
+ return bed;
+ }
+ await sleep(1000);
+ }
+ // Keep the job receipt live; a timeout never implies it is safe to resubmit.
+ const current = await getProject(project.id);
+ if (isCurrentSnapshot(current, project)) throw blocked('Soundtrack generation is still running. Inspect the queue before Resume.');
+ return null;
+}
+
+function isCurrentSnapshot(current, project) {
+ return current?.videoExecution?.authorized && ['rendering', 'stitching'].includes(current.status)
+ && (current.videoWorkRevision || 0) === (project.videoWorkRevision || 0);
+}
diff --git a/server/services/creativeDirector/videoExecution.js b/server/services/creativeDirector/videoExecution.js
index da8fd8e53c..57550c617e 100644
--- a/server/services/creativeDirector/videoExecution.js
+++ b/server/services/creativeDirector/videoExecution.js
@@ -6,6 +6,7 @@ import { creativeDirectorVideoLimitsSchema } from '../../lib/creativeDirectorVal
import { assertVideoOwner } from '../../lib/creativeDirectorVideoReview.js';
const ACTIVE = new Set(['planning', 'rendering', 'stitching']);
+const isMediaAttempt = attempt => ['clip', 'audio'].includes(attempt.kind);
const LIVE_ATTEMPTS = new Set(['submitting', 'queued', 'running', 'uncertain']);
const now = () => new Date().toISOString();
@@ -71,7 +72,9 @@ async function resolveChoices(project) {
const explicitEval = project.modelOverrides?.evaluation?.providerId || settings.creativeDirector?.evaluation?.providerId;
if (explicitEval && vision?.provider.id !== explicitEval) throw new ServerError('The selected evaluation provider is unavailable. Change Models or Settings before Start.', { status: 409, code: 'VIDEO_AGENT_UNAVAILABLE' });
const evaluation = vision ? { type: 'api', providerId: vision.provider.id, model: vision.model || vision.provider.defaultModel || null } : await agentChoice('evaluate');
- return { video, treatment, plan, evaluation, audio: project.videoDraft?.audio || {}, costEstimateUsd: null };
+ const { resolveVideoAudioChoice } = await import('./videoAudio.js');
+ const audio = await resolveVideoAudioChoice(project);
+ return { video, treatment, plan, evaluation, audio, costEstimateUsd: null };
}
export async function getVideoExecutionPreview(projectId) {
@@ -90,7 +93,7 @@ export async function getVideoExecutionPreview(projectId) {
return { canStart: canStart && blockers.length === 0, blockers, choices,
inputRevision: videoConfigurationRevision(project),
configurationRevision: canonicalSnapshotChecksum({ input: videoConfigurationRevision(project), choices }),
- limits: project.videoExecution?.limits || creativeDirectorVideoLimitsSchema.parse({}),
+ limits: creativeDirectorVideoLimitsSchema.parse(project.videoExecution?.limits || {}),
execution: project.videoExecution || null,
costNotice: 'Provider prices and balances are unknown. Clip and agent-call limits are enforced; a dollar cap blocks calls whose price cannot be bounded.' };
}
@@ -118,7 +121,7 @@ export async function reconcileVideoExecution(projectId, { restarting = false, r
const snapshot = await getProject(projectId);
const tasks = new Map();
if (!restarting) {
- const liveAgents = (snapshot?.videoExecution?.attempts || []).filter(attempt => attempt.kind !== 'clip' && LIVE_ATTEMPTS.has(attempt.status) && attempt.taskId);
+ const liveAgents = (snapshot?.videoExecution?.attempts || []).filter(attempt => !isMediaAttempt(attempt) && LIVE_ATTEMPTS.has(attempt.status) && attempt.taskId);
if (liveAgents.length) {
const { getTaskById } = await import('../cos.js');
for (const attempt of liveAgents) tasks.set(attempt.taskId, await getTaskById(attempt.taskId));
@@ -127,7 +130,7 @@ export async function reconcileVideoExecution(projectId, { restarting = false, r
return ownedMutation(projectId, project => {
const attempts = (project.videoExecution?.attempts || []).map(attempt => {
if (!LIVE_ATTEMPTS.has(attempt.status)) return attempt;
- if (attempt.kind !== 'clip') return restarting || (attempt.taskId && (!tasks.get(attempt.taskId) || ['blocked', 'completed', 'failed'].includes(tasks.get(attempt.taskId).status))) ? { ...attempt, status: 'failed' } : attempt;
+ if (!isMediaAttempt(attempt)) return restarting || (attempt.taskId && (!tasks.get(attempt.taskId) || ['blocked', 'completed', 'failed'].includes(tasks.get(attempt.taskId).status))) ? { ...attempt, status: 'failed' } : attempt;
const job = jobs.find(job => job.id === attempt.jobId || job.params?.videoProduction?.attemptId === attempt.id);
if (job?.status === 'completed') return { ...attempt, jobId: job.id, status: 'completed' };
if (job?.status === 'queued' || job?.status === 'running') return { ...attempt, jobId: job.id, status: job.status };
@@ -136,7 +139,7 @@ export async function reconcileVideoExecution(projectId, { restarting = false, r
if (uncertain && !retryAttemptIds.includes(attempt.id)) return { ...attempt, jobId: job?.id || attempt.jobId, status: 'uncertain' };
return { ...attempt, status: 'failed', explicitlyRetriedAt: retryAttemptIds.includes(attempt.id) ? now() : undefined };
});
- const retiredTaskIds = new Set(attempts.filter(attempt => attempt.kind !== 'clip' && attempt.status === 'failed').map(attempt => attempt.taskId).filter(Boolean));
+ const retiredTaskIds = new Set(attempts.filter(attempt => !isMediaAttempt(attempt) && attempt.status === 'failed').map(attempt => attempt.taskId).filter(Boolean));
const runs = (project.runs || []).map(run => retiredTaskIds.has(run.taskId) && run.status === 'running' ? { ...run, status: 'failed', failureReason: 'Provider task ended before resume' } : run);
const scenes = project.treatment?.scenes?.map(scene => {
const receipt = [...attempts].reverse().find(attempt => attempt.sceneId === scene.sceneId && attempt.workRevision === (scene.workRevision || 0) && attempt.kind === 'clip');
@@ -197,10 +200,12 @@ export async function reserveVideoAttempt(projectId, details) {
if (attempts.some(attempt => LIVE_ATTEMPTS.has(attempt.status) && attempt.key === details.key)) return { project, result: null, skipPersist: true };
const limits = execution.limits;
const isClip = details.kind === 'clip';
+ const isAudio = details.kind === 'audio';
const sameKey = attempts.filter(attempt => attempt.key === details.key);
if (isClip && attempts.filter(attempt => attempt.kind === 'clip').length >= limits.maxClips) blocker = 'The clip limit is exhausted. Review limits before Resume.';
if (isClip && sameKey.length > limits.maxRetries) blocker = 'The retry limit for this shot is exhausted. Review limits before Resume.';
- if (!isClip && attempts.filter(attempt => attempt.kind !== 'clip').length >= limits.maxAgentCalls) blocker = 'The agent-call limit is exhausted. Review limits before Resume.';
+ if (!isClip && !isAudio && attempts.filter(attempt => !isMediaAttempt(attempt)).length >= limits.maxAgentCalls) blocker = 'The agent-call limit is exhausted. Review limits before Resume.';
+ if (isAudio && (attempts.filter(attempt => attempt.kind === 'audio').length >= (limits.maxAudioJobs ?? 1) || sameKey.length > limits.maxRetries)) blocker = 'The audio job limit is exhausted. Review limits before Resume.';
if (details.kind === 'plan' && attempts.filter(attempt => attempt.kind === 'plan').length > limits.maxReplans) blocker = 'The replan limit is exhausted. Review limits before Resume.';
if (limits.spendCapUsd !== null) blocker = 'The next call has unknown cost and cannot fit an enforceable dollar cap.';
if (blocker) return { project: { ...project, status: 'paused', failureReason: blocker, videoExecution: { ...execution, blocker }, updatedAt: now() }, result: null };
@@ -232,6 +237,10 @@ export async function assertVideoAttemptDispatch(projectId, attemptId, { jobId }
const { getSettings } = await import('../settings.js');
const { resolveVideoBackendPin } = await import('../videoGen/backendPin.js');
resolveVideoBackendPin(effective, await getSettings());
+ if (attempt.kind === 'audio') {
+ const { resolveVideoAudioChoice } = await import('./videoAudio.js');
+ await resolveVideoAudioChoice({ ...project, videoDraft: { ...project.videoDraft, audio: execution.choices.audio } });
+ }
const { hasConfiguredMediaRoute } = await import('../federatedMedia/defaultRouting.js');
if (await hasConfiguredMediaRoute('video')) throw new ServerError('The standing video route changed the reviewed backend. Review Settings and Resume.', { status: 409, code: 'VIDEO_ROUTE_CHANGED' });
{
diff --git a/server/services/creativeDirector/videoExecution.test.js b/server/services/creativeDirector/videoExecution.test.js
index 9e69706949..41f9af5bc5 100644
--- a/server/services/creativeDirector/videoExecution.test.js
+++ b/server/services/creativeDirector/videoExecution.test.js
@@ -1,5 +1,5 @@
import { beforeEach, expect, it, vi } from 'vitest';
-const state = vi.hoisted(() => ({ project: null, jobs: [], settings: null }));
+const state = vi.hoisted(() => ({ project: null, jobs: [], settings: null, tracks: [] }));
vi.mock('./local.js', () => ({
getProject: vi.fn(async () => structuredClone(state.project)),
mutateVideoProject: vi.fn(async (_id, mutate) => {
@@ -16,7 +16,12 @@ vi.mock('../agentProviderResolution.js', () => ({ resolveAgentProviderAndModel:
vi.mock('./sceneEvaluator.js', () => ({ resolveVisionEvalTarget: vi.fn(async () => null) }));
vi.mock('../videoGen/reactor.js', () => ({ REACTOR_MODEL_ID: 'fast-h3' }));
vi.mock('../videoGen/modelSelection.js', () => ({ resolveVideoModelSelection: vi.fn() }));
-vi.mock('../mediaJobQueue/index.js', () => ({ listJobs: vi.fn(() => state.jobs) }));
+vi.mock('../mediaJobQueue/index.js', () => ({ listJobs: vi.fn(() => state.jobs), getJob: vi.fn(id => state.jobs.find(job => job.id === id)),
+ enqueueJob: vi.fn(job => { const jobId = `example-audio-${state.jobs.length}`; state.jobs.push({ ...job, id: jobId, status: 'completed', result: { filename: 'example-bed.wav', durationSec: 10 } }); return { jobId }; }),
+}));
+vi.mock('../pipeline/musicGen.js', () => ({ ENGINES: { 'example-audio': { id: 'example-audio', models: [{ id: 'example-model' }], defaultModelId: 'example-model', minDurationSec: 1, maxDurationSec: 30 } }, isEngineHealthy: vi.fn(async () => true) }));
+vi.mock('../pipeline/audioMux.js', () => ({ resolveMusicTrackPath: vi.fn(async filename => filename ? `/fake/music/${filename}` : null) }));
+vi.mock('../tracks/index.js', () => ({ listTracks: async () => state.tracks, createTrack: async input => { const track = { id: 'example-track', ...input }; state.tracks.push(track); return track; } }));
vi.mock('../federatedMedia/defaultRouting.js', () => ({
hasConfiguredMediaRoute: vi.fn(async () => false),
enqueueUnattendedMediaJob: vi.fn(async job => {
@@ -35,6 +40,7 @@ import { getVideoExecutionPreview, startVideoExecution, enqueueVideoProductionJo
beforeEach(() => {
vi.clearAllMocks();
state.jobs = [];
+ state.tracks = [];
state.settings = { videoGen: { reactor: { apiKey: 'example-key' } } };
state.project = { id: 'example-video', workspace: 'video', videoOwnerInstanceId: 'example-owner',
status: 'draft', userStory: 'An invented woodland journey.', videoDraft: { sources: [], audio: {} },
@@ -133,3 +139,22 @@ it('checks the duration the backend actually consumes and rejects batch expansio
expect(state.project.videoExecution.attempts).toHaveLength(0);
expect(enqueueUnattendedMediaJob).not.toHaveBeenCalled();
});
+
+it('generates one explicitly selected soundtrack, retains its Track, and reuses it within audio job limits', async () => {
+ const { prepareVideoSoundtrack } = await import('./videoAudio.js');
+ const { enqueueJob } = await import('../mediaJobQueue/index.js');
+ state.project.videoDraft.audio = { mode: 'generated', providerId: 'example-audio', model: 'example-model', prompt: 'A quiet invented melody.' };
+ await startVideoExecution('example-video', await startInput({ maxAudioJobs: 1 }));
+ const bed = await prepareVideoSoundtrack(state.project, async () => true);
+ expect(bed).toMatchObject({ filename: 'example-bed.wav', trackId: 'example-track' });
+ expect(enqueueJob).toHaveBeenCalledWith(expect.objectContaining({ kind: 'audio', owner: 'creative-director:example-video', params: expect.objectContaining({ engine: 'example-audio', modelId: 'example-model', durationSec: 10, videoProduction: expect.objectContaining({ projectId: 'example-video' }) }) }));
+ expect(state.project.videoExecution.attempts.filter(attempt => attempt.kind === 'audio')).toHaveLength(1);
+ await prepareVideoSoundtrack(state.project, async () => true);
+ expect(enqueueJob).toHaveBeenCalledTimes(1);
+ state.project.videoDraft.audio.prompt = 'A different melody.';
+ state.project.status = 'paused';
+ await startVideoExecution('example-video', await startInput({ maxAudioJobs: 1 }));
+ expect(await prepareVideoSoundtrack(state.project, async () => true)).toBeNull();
+ expect(state.project.videoExecution.blocker).toMatch(/audio job limit/);
+ expect(enqueueJob).toHaveBeenCalledTimes(1);
+});