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

fix: make reviewed video production editable and recoverable

[._.]/ Adam Eivy37ad9da4c983
diff --git a/client/src/components/creative-director/SegmentsTab.jsx b/client/src/components/creative-director/SegmentsTab.jsx
index f071d4ba66..eae701aa78 100644
--- a/client/src/components/creative-director/SegmentsTab.jsx
+++ b/client/src/components/creative-director/SegmentsTab.jsx
@@ -3,8 +3,9 @@ import { Bot } from 'lucide-react';
import { extractKind } from './ActiveAgentsBanner.jsx';
import ScenePreview from './ScenePreview.jsx';
import { SCENE_STATUS_BADGE } from './sceneStatus.js';
+import VideoShotEditor from './VideoShotEditor.jsx';
-export default function SegmentsTab({ project, activeAgents = [], basePath = '/creative-director' }) {
+export default function SegmentsTab({ project, activeAgents = [], basePath = '/creative-director', onChange }) {
const { sceneId: selectedSceneId } = useParams();
const scenes = project.treatment?.scenes;
if (!scenes?.length) {
@@ -46,7 +47,7 @@ export default function SegmentsTab({ project, activeAgents = [], basePath = '/c
return (
<div>
{selectedSceneId && <Link to={`${basePath}/${project.id}/segments`} className="block mb-3 text-port-accent">View all shots</Link>}
- <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-3">
+ <div className={selectedSceneId ? 'max-w-4xl' : 'grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-3'}>
{sorted.filter(s => !selectedSceneId || s.sceneId === selectedSceneId).map((s) => {
const isInflight = isSceneInflight(s.sceneId);
const decoratedStatus = isInflight && s.status === 'pending' ? 'rendering' : s.status;
@@ -54,6 +55,8 @@ export default function SegmentsTab({ project, activeAgents = [], basePath = '/c
<div key={s.sceneId} className={`bg-port-card border rounded overflow-hidden ${isInflight ? 'border-port-accent/60' : 'border-port-border'}`}>
{s.renderedJobId ? (
<ScenePreview jobId={s.renderedJobId} label={`Scene ${s.order + 1}`} />
+ ) : s.sourceImageFile ? (
+ <img src={`/data/images/${encodeURIComponent(s.sourceImageFile)}`} alt={`Scene ${s.order + 1} reference frame`} className="aspect-video w-full object-contain bg-port-bg" />
) : (
<div className="bg-port-bg aspect-video flex items-center justify-center text-port-text-muted text-xs">
{isInflight ? (
@@ -90,6 +93,7 @@ export default function SegmentsTab({ project, activeAgents = [], basePath = '/c
{s.evaluation.notes}
</div>
)}
+ {selectedSceneId && project.workspace === 'video' && <VideoShotEditor key={`${s.sceneId}:${s.workRevision || 0}`} project={project} scene={s} onChange={onChange} />}
</div>
</div>
);
diff --git a/client/src/components/creative-director/VideoDraftDrawer.jsx b/client/src/components/creative-director/VideoDraftDrawer.jsx
index f6d4aabe98..4b32377da0 100644
--- a/client/src/components/creative-director/VideoDraftDrawer.jsx
+++ b/client/src/components/creative-director/VideoDraftDrawer.jsx
@@ -61,9 +61,9 @@ export default function VideoDraftDrawer({ open, onClose, project, onSaved, cata
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; });
setSaving(false);
- if (saved) { onClose(); onSaved(saved); toast.success('Video draft saved'); }
+ if (saved) { onClose(); onSaved(saved); toast.success(project?.status && project.status !== 'draft' ? 'Production settings saved' : 'Video draft saved'); }
};
- return <Drawer open={open} onClose={onClose} title={project ? 'Edit video draft' : 'New video draft'} subtitle="Saving a draft makes no provider calls" size="lg" tabs={TABS} activeTab={tab} onTabChange={setTab} closeOnEsc={false} closeOnBackdrop={false}>
+ return <Drawer open={open} onClose={onClose} title={project ? !project.status || project.status === 'draft' ? 'Edit video draft' : 'Edit production settings' : 'New video draft'} subtitle="Saving makes no provider calls. Start or resume production when ready." size="lg" tabs={TABS} activeTab={tab} onTabChange={setTab} closeOnEsc={false} closeOnBackdrop={false}>
<fieldset disabled={saving} className="space-y-4">
{tab === 'brief' && <>
{input('name', 'Name', { maxLength: 200 })}
@@ -100,7 +100,7 @@ export default function VideoDraftDrawer({ open, onClose, project, onSaved, cata
<ul className="space-y-2">{(form.sources || []).map(source => <li key={`${source.kind}:${source.id}`} className="flex items-center justify-between gap-2 border border-port-border rounded p-2"><span>{source.kind}: {sourceOptions[source.kind]?.find(s => s.id === source.id)?.name || sourceOptions[source.kind]?.find(s => s.id === source.id)?.title || source.id}</span><button aria-label={`Remove ${source.kind} source ${source.id}`} onClick={() => change('sources', form.sources.filter(s => s !== source))}>Remove</button></li>)}</ul>
<p className="text-sm text-port-text-muted">Attach up to 50 sources from existing creative records. Imported music and voice references remain attached until you remove them.</p>
</>}
- <div className="flex justify-end gap-2 border-t border-port-border pt-4"><button disabled={saving} onClick={onClose} className="px-3 py-2 rounded border border-port-border">Cancel</button><button disabled={saving} onClick={save} className="px-3 py-2 rounded bg-port-accent text-white disabled:opacity-50">{saving ? 'Saving…' : 'Save draft'}</button></div>
+ <div className="flex justify-end gap-2 border-t border-port-border pt-4"><button disabled={saving} onClick={onClose} className="px-3 py-2 rounded border border-port-border">Cancel</button><button disabled={saving} onClick={save} className="px-3 py-2 rounded bg-port-accent text-white disabled:opacity-50">{saving ? 'Saving…' : project?.status && project.status !== 'draft' ? 'Save production settings' : 'Save draft'}</button></div>
</fieldset>
</Drawer>;
}
diff --git a/client/src/components/creative-director/VideoExecutionPanel.jsx b/client/src/components/creative-director/VideoExecutionPanel.jsx
index f09122deea..cef65523c8 100644
--- a/client/src/components/creative-director/VideoExecutionPanel.jsx
+++ b/client/src/components/creative-director/VideoExecutionPanel.jsx
@@ -66,6 +66,8 @@ export default function VideoExecutionPanel({ project, onChange, basePath }) {
<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>)}
{preview.execution?.blocker && <p role="status" className="text-port-warning">{preview.execution.blocker}</p>}
+ {project.videoReview?.waitingFor && <p role="status" className="text-port-warning">Waiting for your approval. <Link className="underline" to={`${basePath}/${project.id}/review`}>Review the current {project.videoReview.waitingFor.stage.replaceAll('-', ' ')} revision</Link> to continue.</p>}
+ {project.treatment?.artifact?.stale && <p role="status" className="text-port-warning">{active ? 'The script is being revised using the saved settings and revision notes.' : 'The saved script needs revision. Resume production to rewrite it using the saved settings and revision notes.'} Rendering waits for the revised script to be approved.</p>}
<div className="flex flex-wrap gap-3 text-sm"><Link className="underline" to="/video/generate?settings=1">Media settings</Link><Link className="underline" to={`${basePath}/${project.id}/overview?models=1`}>Change models</Link><Link className="underline" to="/system-resources/queues">Inspect render queue</Link><Link className="underline" to={`${basePath}/${project.id}/review`}>Review artifacts</Link></div>
{limits && <div className="grid gap-3 sm:grid-cols-2">
{LIMITS.map(([key, label, min, max]) => <div key={key}>
diff --git a/client/src/components/creative-director/VideoReviewPanel.jsx b/client/src/components/creative-director/VideoReviewPanel.jsx
index 2751c1b394..003dfcb957 100644
--- a/client/src/components/creative-director/VideoReviewPanel.jsx
+++ b/client/src/components/creative-director/VideoReviewPanel.jsx
@@ -44,7 +44,7 @@ export default function VideoReviewPanel({ project, onChange }) {
return <section aria-label="Production reviews" className="border-b border-port-border p-4 space-y-3">
<h2 className="font-medium">Production reviews</h2>
- <p className="text-sm text-port-text-muted">Approve the displayed revision to continue. Thumbs up or down saves feedback only.</p>
+ <p className="text-sm text-port-text-muted">Approve the displayed revision to continue. If production is paused, resume it from Overview. Script revision requests pause production; Resume writes a revised script for review. Thumbs up or down saves feedback only.</p>
{error && <div role="alert" className="text-sm text-port-error">{error} <button onClick={() => { setError(''); setReload(value => value + 1); }} className="underline">Refresh reviews</button></div>}
{!review && !error && <p role="status">Loading reviews…</p>}
{review && !review.canReview && <p role="status" className="text-sm text-port-warning">Review on the owning install. For a draft without an owner, create a new local draft from its saved settings.</p>}
diff --git a/client/src/components/creative-director/VideoShotEditor.jsx b/client/src/components/creative-director/VideoShotEditor.jsx
new file mode 100644
index 0000000000..5a72acba6f
--- /dev/null
+++ b/client/src/components/creative-director/VideoShotEditor.jsx
@@ -0,0 +1,38 @@
+import { useState } from 'react';
+import { updateCreativeDirectorScene } from '../../services/apiCreativeDirector.js';
+import GalleryImagePicker from '../imageGen/GalleryImagePicker.jsx';
+import toast from '../ui/Toast';
+
+export default function VideoShotEditor({ project, scene, onChange }) {
+ const [prompt, setPrompt] = useState(scene.prompt);
+ const [sourceImageFile, setSourceImageFile] = useState(scene.sourceImageFile || null);
+ const [continuation, setContinuation] = useState(Boolean(scene.useContinuationFromPrior));
+ const [pickerOpen, setPickerOpen] = useState(false);
+ const [saving, setSaving] = useState(false);
+ const active = ['planning', 'rendering', 'stitching'].includes(project.status);
+ const dirty = prompt !== scene.prompt || sourceImageFile !== (scene.sourceImageFile || null) || continuation !== Boolean(scene.useContinuationFromPrior);
+ const save = async () => {
+ if (saving || active || !dirty || !prompt.trim()) return;
+ setSaving(true);
+ const saved = await updateCreativeDirectorScene(project.id, scene.sceneId, {
+ prompt, sourceImageFile, useContinuationFromPrior: continuation, expectedWorkRevision: scene.workRevision || 0,
+ }, { silent: true }).catch(error => { toast.error(error.message || 'Could not save shot'); return null; });
+ setSaving(false);
+ if (saved) { toast.success('Shot saved. Review the updated production before resuming.'); onChange?.(); }
+ };
+ return <section aria-label="Edit shot" className="space-y-3 border-t border-port-border pt-3">
+ <label htmlFor="video-shot-prompt" className="block text-sm">Render prompt</label>
+ <textarea id="video-shot-prompt" className="w-full rounded border border-port-border bg-port-bg p-2 text-sm" rows={8} maxLength={8000} value={prompt} onChange={event => setPrompt(event.target.value)} disabled={active || saving} />
+ <p className="text-xs text-port-text-muted">Include the action, character appearance, and any native dialogue or sound in this prompt.</p>
+ {sourceImageFile && <img src={`/data/images/${encodeURIComponent(sourceImageFile)}`} alt="Shot reference frame" className="max-h-64 w-full rounded object-contain" />}
+ <div className="flex flex-wrap gap-2">
+ <button className="rounded border border-port-border px-3 py-2 text-sm" disabled={active || saving} onClick={() => setPickerOpen(true)}>{sourceImageFile ? 'Change reference frame' : 'Choose reference frame'}</button>
+ {sourceImageFile && <button className="text-sm underline" disabled={active || saving} onClick={() => setSourceImageFile(null)}>Remove reference frame</button>}
+ </div>
+ <label htmlFor="video-shot-continuation" className="flex items-center gap-2 text-sm"><input id="video-shot-continuation" type="checkbox" checked={continuation} disabled={active || saving || scene.order === 0} onChange={event => setContinuation(event.target.checked)} />Continue from the previous shot's last frame</label>
+ {continuation && <p className="text-xs text-port-text-muted">Continuation uses the previous clip instead of the selected reference frame.</p>}
+ <p className="text-xs text-port-text-muted">{active ? 'Pause production before editing this shot.' : 'Saving pauses production and requires a fresh review. It makes no provider calls.'}</p>
+ <button className="rounded bg-port-accent px-3 py-2 text-white disabled:opacity-40" disabled={active || saving || !dirty || !prompt.trim()} onClick={save}>{saving ? 'Saving…' : 'Save shot'}</button>
+ <GalleryImagePicker open={pickerOpen} onClose={() => setPickerOpen(false)} onSelect={item => { setSourceImageFile(item.filename); setContinuation(false); }} allowUpload />
+ </section>;
+}
diff --git a/client/src/components/creative-director/VideoShotEditor.test.jsx b/client/src/components/creative-director/VideoShotEditor.test.jsx
new file mode 100644
index 0000000000..db2b11f53b
--- /dev/null
+++ b/client/src/components/creative-director/VideoShotEditor.test.jsx
@@ -0,0 +1,26 @@
+import { it, expect, vi } from 'vitest';
+import { render, screen, waitFor } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+vi.mock('../../services/apiCreativeDirector.js', () => ({ updateCreativeDirectorScene: vi.fn() }));
+vi.mock('../imageGen/GalleryImagePicker.jsx', () => ({ default: ({ open, onSelect, onClose }) => open ? <button onClick={() => { onSelect({ filename: 'example-frame.png' }); onClose(); }}>Example reference</button> : null }));
+vi.mock('../ui/Toast', () => ({ default: { success: vi.fn(), error: vi.fn() } }));
+import { updateCreativeDirectorScene } from '../../services/apiCreativeDirector.js';
+import toast from '../ui/Toast';
+import VideoShotEditor from './VideoShotEditor.jsx';
+
+it('keeps unsaved reference edits after a failed save and submits the displayed revision', async () => {
+ const user = userEvent.setup();
+ const onChange = vi.fn();
+ render(<VideoShotEditor project={{ id: 'cd-example', status: 'paused' }} scene={{ sceneId: 'shot-2', order: 1, prompt: 'A garden path', workRevision: 3, useContinuationFromPrior: true }} onChange={onChange} />);
+ await user.click(screen.getByRole('button', { name: 'Choose reference frame' }));
+ await user.click(screen.getByRole('button', { name: 'Example reference' }));
+ expect(screen.getByRole('checkbox')).not.toBeChecked();
+ updateCreativeDirectorScene.mockRejectedValueOnce(new Error('Unavailable')).mockResolvedValueOnce({});
+ await user.click(screen.getByRole('button', { name: 'Save shot' }));
+ await waitFor(() => expect(toast.error).toHaveBeenCalledWith('Unavailable'));
+ expect(onChange).not.toHaveBeenCalled();
+ expect(screen.getByRole('img', { name: 'Shot reference frame' })).toHaveAttribute('src', '/data/images/example-frame.png');
+ await user.click(screen.getByRole('button', { name: 'Save shot' }));
+ await waitFor(() => expect(onChange).toHaveBeenCalledOnce());
+ expect(updateCreativeDirectorScene).toHaveBeenLastCalledWith('cd-example', 'shot-2', { prompt: 'A garden path', sourceImageFile: 'example-frame.png', useContinuationFromPrior: false, expectedWorkRevision: 3 }, { silent: true });
+});
diff --git a/client/src/components/media/MediaCard.jsx b/client/src/components/media/MediaCard.jsx
index fbca603319..c25685fa00 100644
--- a/client/src/components/media/MediaCard.jsx
+++ b/client/src/components/media/MediaCard.jsx
@@ -57,6 +57,7 @@ function MediaCard({
<button
type="button"
onClick={() => handleTileClick(item)}
+ aria-label={prompt || `Select ${isVideo ? 'video' : 'image'}`}
disabled={disabled}
className="block w-full h-full disabled:cursor-not-allowed disabled:opacity-40"
>
diff --git a/client/src/pages/CreativeDirectorDetail.jsx b/client/src/pages/CreativeDirectorDetail.jsx
index d85b7b6f04..cfa3bf2009 100644
--- a/client/src/pages/CreativeDirectorDetail.jsx
+++ b/client/src/pages/CreativeDirectorDetail.jsx
@@ -356,7 +356,7 @@ export default function CreativeDirectorDetail({ basePath = '/creative-director'
)}
{project.workspace !== 'video' && activeTab === 'treatment' && <TreatmentTab project={project} />}
{project.workspace === 'video' && activeTab === 'artifacts' && <VideoArtifactsTab project={project} basePath={basePath} />}
- {activeTab === 'segments' && <SegmentsTab project={project} activeAgents={activeAgents} basePath={basePath} />}
+ {activeTab === 'segments' && <SegmentsTab project={project} activeAgents={activeAgents} basePath={basePath} onChange={fetchProject} />}
{activeTab === 'runs' && <RunsTab project={project} />}
</div>
diff --git a/client/src/services/apiCreativeDirector.js b/client/src/services/apiCreativeDirector.js
index a3d1ca7c6a..f6ac752195 100644
--- a/client/src/services/apiCreativeDirector.js
+++ b/client/src/services/apiCreativeDirector.js
@@ -26,6 +26,11 @@ export const updateCreativeDirectorProject = (id, patch, options = {}) => reques
body: JSON.stringify(patch),
...options,
});
+export const updateCreativeDirectorScene = (id, sceneId, patch, options = {}) => request(`/creative-director/${encodeURIComponent(id)}/scene/${encodeURIComponent(sceneId)}`, {
+ method: 'PATCH',
+ body: JSON.stringify(patch),
+ ...options,
+});
export const deleteCreativeDirectorProject = (id, options = {}) => request(`/creative-director/${encodeURIComponent(id)}`, {
method: 'DELETE',
...options,
diff --git a/scripts/submit-video-artifact.js b/scripts/submit-video-artifact.js
new file mode 100644
index 0000000000..36ecf1d88a
--- /dev/null
+++ b/scripts/submit-video-artifact.js
@@ -0,0 +1,32 @@
+#!/usr/bin/env node
+// Local production-agent handoff. Uses the same validation and persistence as
+// the HTTP routes without exporting an interactive session to a CLI process.
+import { readFile } from 'node:fs/promises';
+import { pathToFileURL } from 'node:url';
+import { creativeDirectorTreatmentSchema, creativeDirectorPlanSchema } from '../server/lib/creativeDirectorValidation.js';
+
+export async function submitVideoArtifact({ projectId, attemptId, kind, input }) {
+ if (!['treatment', 'plan'].includes(kind)) throw new Error('Expected treatment or plan');
+ const [{ getProject, setTreatment, setPlan }, { assertVideoAttemptDispatch }] = await Promise.all([
+ import('../server/services/creativeDirector/local.js'),
+ import('../server/services/creativeDirector/videoExecution.js'),
+ ]);
+ const project = await getProject(projectId);
+ const attempt = project?.videoExecution?.attempts?.find(row => row.id === attemptId);
+ if (project?.workspace !== 'video' || !attempt || attempt.kind !== kind) throw new Error('No matching Video production attempt');
+ await assertVideoAttemptDispatch(projectId, attemptId);
+ const data = (kind === 'treatment' ? creativeDirectorTreatmentSchema : creativeDirectorPlanSchema).parse(input);
+ await (kind === 'treatment' ? setTreatment : setPlan)(projectId, data);
+ return { saved: true, kind };
+}
+
+if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
+ const [projectId, attemptId, kind, filename] = process.argv.slice(2);
+ Promise.resolve().then(async () => {
+ if (!filename) throw new Error('Usage: submit-video-artifact.js PROJECT ATTEMPT treatment|plan JSON_FILE');
+ const input = JSON.parse(await readFile(filename, 'utf8'));
+ const result = await submitVideoArtifact({ projectId, attemptId, kind, input });
+ console.log(JSON.stringify(result));
+ process.exit(0);
+ }).catch(error => { console.error(JSON.stringify({ error: error.message, code: error.code })); process.exit(1); });
+}
diff --git a/scripts/submit-video-artifact.test.js b/scripts/submit-video-artifact.test.js
new file mode 100644
index 0000000000..07e6e11f78
--- /dev/null
+++ b/scripts/submit-video-artifact.test.js
@@ -0,0 +1,25 @@
+import { describe, it, expect, vi } from 'vitest';
+vi.mock('../server/services/creativeDirector/local.js', () => ({ getProject: vi.fn(), setTreatment: vi.fn(), setPlan: vi.fn() }));
+vi.mock('../server/services/creativeDirector/videoExecution.js', () => ({ assertVideoAttemptDispatch: vi.fn() }));
+import { getProject, setTreatment } from '../server/services/creativeDirector/local.js';
+import { assertVideoAttemptDispatch } from '../server/services/creativeDirector/videoExecution.js';
+import { submitVideoArtifact } from './submit-video-artifact.js';
+
+describe('local Video artifact submission', () => {
+ it('validates and persists an authorized treatment, rejecting malformed and retired submissions', async () => {
+ getProject.mockResolvedValue({ workspace: 'video', videoExecution: { attempts: [{ id: 'attempt-1', kind: 'treatment' }] } });
+ const args = { projectId: 'cd-example', attemptId: 'attempt-1', kind: 'treatment', input: {
+ logline: 'A traveler arrives.', synopsis: 'A traveler finds a garden.', script: 'The traveler opens a gate.',
+ scenes: [{ sceneId: 'shot-1', order: 0, intent: 'Arrival', prompt: 'A traveler opens a garden gate.', durationSeconds: 6 }],
+ } };
+ await expect(submitVideoArtifact(args)).resolves.toEqual({ saved: true, kind: 'treatment' });
+ expect(setTreatment).toHaveBeenCalledWith('cd-example', expect.objectContaining({ script: args.input.script }));
+ setTreatment.mockClear();
+ await expect(submitVideoArtifact({ ...args, input: {} })).rejects.toThrow();
+ expect(setTreatment).not.toHaveBeenCalled();
+ assertVideoAttemptDispatch.mockRejectedValueOnce(new Error('Production is paused'));
+ await expect(submitVideoArtifact(args)).rejects.toThrow('Production is paused');
+ await expect(submitVideoArtifact({ ...args, attemptId: 'other-attempt' })).rejects.toThrow('No matching');
+ expect(setTreatment).not.toHaveBeenCalled();
+ });
+});
diff --git a/server/lib/creativeDirectorValidation.js b/server/lib/creativeDirectorValidation.js
index 031d2247c1..4d48c0788c 100644
--- a/server/lib/creativeDirectorValidation.js
+++ b/server/lib/creativeDirectorValidation.js
@@ -342,6 +342,8 @@ export const creativeDirectorTreatmentSchema = z.object({
// Used by the agent when finishing a scene render.
export const creativeDirectorSceneUpdateSchema = z.object({
expectedWorkRevision: z.number().int().min(0).optional(),
+ sourceImageFile: safeBasename.nullable().optional(),
+ useContinuationFromPrior: z.boolean().optional(),
// Full SCENE_STATUSES — the evaluator agent flips a scene back to 'pending'
// (with an updated prompt + bumped retryCount) to request a re-render; see
// creativeDirectorPrompts.js and completionHook.js's advanceAfterSceneSettled.
diff --git a/server/lib/creativeDirectorVideoReview.js b/server/lib/creativeDirectorVideoReview.js
index c9b597c3a6..2a3d89c05a 100644
--- a/server/lib/creativeDirectorVideoReview.js
+++ b/server/lib/creativeDirectorVideoReview.js
@@ -122,6 +122,9 @@ 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) };
}
+ if (input.stage === 'script-shot-plan' && treatment?.artifact) {
+ treatment = { ...treatment, artifact: { ...treatment.artifact, stale: true } };
+ }
return { project: { ...project, treatment, plan, status: 'paused', finalVideoId: null, videoCutHistory: retainVideoCuts(project),
...(index <= 2 ? { videoRoughCut: null } : {}), videoFinalCut: null,
videoWorkRevision: (project.videoWorkRevision || 0) + 1,
diff --git a/server/routes/creativeDirector.js b/server/routes/creativeDirector.js
index 1b705ea81b..a1b8223ad0 100644
--- a/server/routes/creativeDirector.js
+++ b/server/routes/creativeDirector.js
@@ -9,6 +9,7 @@
import { Router } from 'express';
import { asyncHandler, ServerError } from '../lib/errorHandler.js';
+import { resolveGalleryImage } from '../lib/fileUtils.js';
import {
validateRequest,
creativeDirectorProjectCreateSchema,
@@ -171,8 +172,8 @@ router.patch('/:id', asyncHandler(async (req, res) => {
if (draftFields.some((key) => key in data)) {
const project = await getProject(req.params.id);
if (!project) throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });
- if (project.workspace !== 'video' || project.status !== 'draft') {
- throw new ServerError('Production settings can only be edited on a Video draft', { status: 409, code: 'INVALID_STATE' });
+ if (project.workspace !== 'video' || !['draft', 'paused', 'failed'].includes(project.status)) {
+ throw new ServerError('Pause Video production before editing production settings', { status: 409, code: 'INVALID_STATE' });
}
}
const updated = await updateProject(req.params.id, data);
@@ -383,6 +384,9 @@ router.post('/:id/plan/step/:stepId', asyncHandler(async (req, res) => {
router.patch('/:id/scene/:sceneId', asyncHandler(async (req, res) => {
const data = validateRequest(creativeDirectorSceneUpdateSchema, req.body);
const project = await getProject(req.params.id);
+ if (data.sourceImageFile && !resolveGalleryImage(data.sourceImageFile)) {
+ throw new ServerError('The selected reference image is no longer available. Choose another gallery image.', { status: 400, code: 'IMAGE_NOT_FOUND' });
+ }
if (project?.workspace === 'video' && data.expectedWorkRevision === undefined) {
throw new ServerError('Include the displayed shot work revision with this update.', { status: 409, code: 'VIDEO_WORK_STALE' });
}
diff --git a/server/routes/creativeDirector.test.js b/server/routes/creativeDirector.test.js
index 3e2e97532c..5dbe259280 100644
--- a/server/routes/creativeDirector.test.js
+++ b/server/routes/creativeDirector.test.js
@@ -179,6 +179,18 @@ describe('creativeDirector routes', () => {
})).status).toBe(400);
});
+ it('saves paused production settings without starting work and rejects edits while running', async () => {
+ cdService.getProject.mockResolvedValueOnce({ ...draft, id: 'cd-video', status: 'paused' });
+ expect((await request(app).patch('/api/creative-director/cd-video').send({ videoDraft: draft.videoDraft })).status).toBe(200);
+ expect(cdService.updateProject).toHaveBeenCalledTimes(1);
+ expect(hook.startCreativeDirectorProject).not.toHaveBeenCalled();
+ cdService.getProject.mockResolvedValueOnce({ ...draft, id: 'cd-video', status: 'rendering' });
+ const blocked = await request(app).patch('/api/creative-director/cd-video').send({ videoDraft: draft.videoDraft });
+ expect(blocked.status).toBe(409);
+ expect(blocked.body.error).toMatch(/Pause Video production/);
+ expect(cdService.updateProject).toHaveBeenCalledTimes(1);
+ });
+
it('refuses legacy execution entry points before they mutate or enqueue a Video draft', async () => {
cdService.getProject.mockResolvedValue({ ...draft, id: 'cd-video', status: 'draft' });
for (const [action, body] of [
diff --git a/server/services/creativeDirector/agentBridge.js b/server/services/creativeDirector/agentBridge.js
index 3b7f3bc6ea..a928867931 100644
--- a/server/services/creativeDirector/agentBridge.js
+++ b/server/services/creativeDirector/agentBridge.js
@@ -15,6 +15,7 @@
*/
import { randomUUID } from 'crypto';
+import { fileURLToPath } from 'node:url';
import { addTask, reviveBlockedTask, cosEvents } from '../cos.js';
import { buildTreatmentPrompt, buildEvaluatePrompt, buildPlanPrompt } from '../creativeDirectorPrompts.js';
import { getToolSpecs } from '../creative/toolRegistry.js';
@@ -92,7 +93,7 @@ async function buildTaskRecord(project, kind, scene, context) {
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.`;
+ context = `${context}\n\nSaved Video audio contract: ${JSON.stringify(audio)}. Native means the audio generated inside each video clip; there is NO separate dialogue, narration, voice casting, or lip-sync pass. Imported/generated means one assembled soundtrack replacing clip audio, not per-character speech synthesis. Silent means no final audio. Never promise an unconfigured later soundtrack or dialogue pass. Put every intended audible event in its shot prompt when using native audio, and keep any spoken line short enough for that shot. Plan visual storytelling to fit this audio choice. Repeat stable character appearance, wardrobe, and voice descriptions whenever they recur; names alone are not conditioning. Reference images must be existing supplied files, never invented filenames. Shot joins: ${project.videoDraft?.transition || 'cut'}; joins do not overlap or shorten the saved shot timing. Derive act timestamps from the actual summed shot durations. Latest revision requests: ${JSON.stringify(project.videoReview?.revisionRequests || [])}.`;
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 => {
@@ -100,6 +101,10 @@ async function buildTaskRecord(project, kind, scene, context) {
await settleVideoAttempt(project.id, attempt.id, { status: 'failed' });
throw error;
});
+ if (kind === 'treatment' || kind === 'plan') {
+ const submitScript = fileURLToPath(new URL('../../../scripts/submit-video-artifact.js', import.meta.url));
+ context += `\n\nLOCAL VIDEO OUTPUT HANDOFF (replaces the HTTP submission instructions above): Write the specified ${kind} JSON body to a file in your scratch workspace, then run node with these literal arguments: ${JSON.stringify([submitScript, project.id, attempt.id, kind, '<your-json-file>'])}. Use proper shell quoting for each argument. The helper validates the current authorized attempt, production revision, source revision, and artifact schema before persisting. A saved:true result completes the task. No HTTP calls or credentials are needed. Do not search for passwords, tokens, cookies, or sessions. Do not modify application code or project data directly. On a validation error fix the JSON and retry; on a retired attempt stop. All story context is supplied in this prompt.`;
+ }
}
return {
id: taskId,
diff --git a/server/services/creativeDirector/completionHook.js b/server/services/creativeDirector/completionHook.js
index 179c7ccc1c..89881c9090 100644
--- a/server/services/creativeDirector/completionHook.js
+++ b/server/services/creativeDirector/completionHook.js
@@ -283,7 +283,7 @@ export async function advanceAfterSceneSettled(projectId, opts = {}) {
if (project.status === 'paused' || project.status === 'failed') return;
// No treatment yet → enqueue treatment task.
- if (!project.treatment) {
+ if (!project.treatment || (project.workspace === 'video' && project.treatment.artifact?.stale)) {
// Skip if our in-memory dedup set has this project — covers the
// updateProject→enqueueTreatmentTask window between two concurrent
// advance calls. The `planning` status check is intentionally omitted:
@@ -628,7 +628,7 @@ export async function startCreativeDirectorProject(projectId) {
const { videoReviewAllowsDispatch } = await import('./videoReview.js');
if (!await videoReviewAllowsDispatch(projectId, [])) return;
}
- if (project?.directive && (project.workspace !== 'video' || project.treatment)) return advanceAfterPlanStepSettled(projectId);
+ if (project?.directive && (project.workspace !== 'video' || (project.treatment && !project.treatment.artifact?.stale))) return advanceAfterPlanStepSettled(projectId);
return advanceAfterSceneSettled(projectId);
}
diff --git a/server/services/creativeDirector/completionHook.test.js b/server/services/creativeDirector/completionHook.test.js
index dfc8338cf3..f65125c426 100644
--- a/server/services/creativeDirector/completionHook.test.js
+++ b/server/services/creativeDirector/completionHook.test.js
@@ -243,3 +243,16 @@ it('keeps Video drafts inert through both direct starts and background scene adv
expect(mockRunSceneRender).not.toHaveBeenCalled();
expect(mockUpdateProject).not.toHaveBeenCalled();
});
+
+it('resumes an authorized stale Video treatment by rewriting it before rendering', async () => {
+ const review = await import('./videoReview.js');
+ const gate = vi.spyOn(review, 'videoReviewAllowsDispatch').mockResolvedValue(true);
+ const project = { id: 'cd-video', workspace: 'video', status: 'rendering', runs: [],
+ directive: { goal: 'Example' }, treatment: { artifact: { stale: true }, scenes: [{ sceneId: 'one', status: 'pending' }] } };
+ mockGetProject.mockResolvedValue(project);
+ await startCreativeDirectorProject(project.id);
+ expect(mockEnqueueTreatmentTask).toHaveBeenCalledWith(project);
+ expect(mockRunSceneRender).not.toHaveBeenCalled();
+ expect(mockAdvancePlan).not.toHaveBeenCalled();
+ gate.mockRestore();
+});
diff --git a/server/services/creativeDirector/deliverableGate.js b/server/services/creativeDirector/deliverableGate.js
index d6264839bf..9d055d124c 100644
--- a/server/services/creativeDirector/deliverableGate.js
+++ b/server/services/creativeDirector/deliverableGate.js
@@ -59,7 +59,7 @@ export function deliverableMark(project, kind) {
if (kind === 'treatment') {
const scenes = project?.treatment?.scenes;
if (!Array.isArray(scenes)) return null;
- return `treatment:${scenes.length}:${project.treatment.logline || ''}`;
+ return `treatment:${scenes.length}:${project.treatment.logline || ''}${project.workspace === 'video' ? `:${project.treatment.artifact?.revision || 0}` : ''}`;
}
return null;
}
@@ -78,6 +78,10 @@ export function deliverableLanded(project, kind, markBefore) {
const after = deliverableMark(project, kind);
if (after === null) return false;
if (markBefore === undefined) return true;
+ // An in-flight run from an older version recorded no artifact revision.
+ // Adding that suffix on read is not evidence that the run wrote anything.
+ if (kind === 'treatment' && project.workspace === 'video'
+ && markBefore === `treatment:${project.treatment.scenes.length}:${project.treatment.logline || ''}`) return false;
return after !== markBefore;
}
diff --git a/server/services/creativeDirector/deliverableGate.test.js b/server/services/creativeDirector/deliverableGate.test.js
index f91830d7fe..5d6b2449fd 100644
--- a/server/services/creativeDirector/deliverableGate.test.js
+++ b/server/services/creativeDirector/deliverableGate.test.js
@@ -47,6 +47,14 @@ describe('deliverableMark (pure)', () => {
});
describe('deliverableLanded (pure)', () => {
+ it('recognizes a Video script revision even when the logline and shot count stay the same', () => {
+ const project = { workspace: 'video', treatment: { logline: 'An arrival', scenes: [{}], artifact: { revision: 1 } } };
+ const before = deliverableMark(project, 'treatment');
+ expect(deliverableLanded(project, 'treatment', before)).toBe(false);
+ expect(deliverableLanded(project, 'treatment', 'treatment:1:An arrival')).toBe(false);
+ project.treatment.artifact.revision = 2;
+ expect(deliverableLanded(project, 'treatment', before)).toBe(true);
+ });
it('is false when the deliverable is still absent', () => {
expect(deliverableLanded({ plan: null }, 'plan', null)).toBe(false);
});
diff --git a/server/services/creativeDirector/planAdvance.test.js b/server/services/creativeDirector/planAdvance.test.js
index 17b7f005fd..159e685c4d 100644
--- a/server/services/creativeDirector/planAdvance.test.js
+++ b/server/services/creativeDirector/planAdvance.test.js
@@ -286,6 +286,40 @@ const planProject = (steps, over = {}) => ({
});
describe('advanceAfterPlanStepSettled — executor', () => {
+ it.each(['script revision', 'shot edit'])('replans before dispatch after a Video %s retires the executable plan', async (edit) => {
+ const { applyTreatment, applySceneUpdate } = await import('./projectsLogic.js');
+ const { applyVideoReviewAction, videoReviewStages } = await import('../../lib/creativeDirectorVideoReview.js');
+ const review = await import('./videoReview.js');
+ const gate = vi.spyOn(review, 'videoReviewAllowsDispatch').mockResolvedValue(true);
+ try {
+ const oldSteps = [step('old-render', { toolName: 'media_enqueueVideoJob', status: 'done', result: { jobId: 'old-clip' } })];
+ const treatment = { logline: 'A visitor arrives.', synopsis: 'A visitor opens a garden gate.', script: 'The visitor opens the gate.',
+ scenes: [{ sceneId: 'shot-one', order: 0, intent: 'Arrival', prompt: 'A visitor opens a gate.', durationSeconds: 6 }] };
+ let project = applyTreatment(planProject([], { workspace: 'video', targetDurationSeconds: 6, aspectRatio: '16:9',
+ videoOwnerInstanceId: 'example-owner', videoDraft: { sources: [] }, plan: null }), treatment);
+ project.plan = { steps: oldSteps, replanRounds: 0 };
+ if (edit === 'script revision') {
+ const checkpoint = videoReviewStages(project)[0];
+ project = applyVideoReviewAction(project, { stage: checkpoint.stage, revision: checkpoint.revision, action: 'request-revision', note: 'Change the arrival.' }, 'example-owner').project;
+ project = applyTreatment(project, { ...treatment, productionRevision: project.videoWorkRevision, script: 'The visitor waits outside.',
+ scenes: [{ ...treatment.scenes[0], prompt: 'A visitor waits at a gate.' }] });
+ } else {
+ project = applySceneUpdate(project, 'shot-one', { prompt: 'A visitor waits at a gate.', expectedWorkRevision: 0 }).project;
+ }
+ const read = makeStore({ ...project, status: 'rendering' });
+ await advanceAfterPlanStepSettled(project.id);
+ expect(mockEnqueuePlanTask).toHaveBeenCalledTimes(1);
+ expect(mockEnqueuePlanTask).toHaveBeenCalledWith(expect.objectContaining({
+ treatment: expect.objectContaining({ scenes: [expect.objectContaining({ prompt: 'A visitor waits at a gate.' })] }),
+ plan: { history: [expect.objectContaining({ steps: oldSteps })] },
+ }));
+ expect(mockDispatch).not.toHaveBeenCalled();
+ expect(read().status).toBe('planning');
+ } finally {
+ gate.mockRestore();
+ }
+ });
+
it('never plans or dispatches an inert Video production through background advancement', async () => {
makeStore({ ...planProject([step('a', { toolName: 'pipeline_createSeries' })]), workspace: 'video' });
await advanceAfterPlanStepSettled('cd-1');
diff --git a/server/services/creativeDirector/projectsLogic.js b/server/services/creativeDirector/projectsLogic.js
index b8c7090aee..8c39021bfb 100644
--- a/server/services/creativeDirector/projectsLogic.js
+++ b/server/services/creativeDirector/projectsLogic.js
@@ -14,6 +14,7 @@ import { videoSceneInputs, retainVideoCuts } from '../../lib/creativeDirectorVid
import { compileVideoArtifact, validateVideoShot } from '../../lib/creativeDirectorVideoCompiler.js';
import { randomUUID } from 'crypto';
+import { isDeepStrictEqual } from 'node:util';
import { EFFORT_LEVELS } from '../../lib/providerModels.js';
import { ServerError } from '../../lib/errorHandler.js';
import { creativeDirectorVideoDraftSchema } from '../../lib/creativeDirectorValidation.js';
@@ -371,7 +372,7 @@ export function applyProjectPatch(project, patch) {
// empty/model-only stage stubs; the client sends the full object each save.
if ('modelOverrides' in patch) next.modelOverrides = normalizeModelOverrides(patch.modelOverrides);
if (project.workspace === 'video' && project.treatment?.artifact
- && ['videoDraft', 'targetDurationSeconds', 'aspectRatio', 'userStory', 'styleSpec', 'cast', 'startingImageFile', 'modelId', 'renderBackend', 'quality', 'modelOverrides', 'disableAudio'].some((key) => key in patch && JSON.stringify(next[key]) !== JSON.stringify(project[key]))) {
+ && ['videoDraft', 'targetDurationSeconds', 'aspectRatio', 'userStory', 'styleSpec', 'cast', 'startingImageFile', 'modelId', 'renderBackend', 'quality', 'modelOverrides', 'disableAudio'].some((key) => key in patch && !isDeepStrictEqual(next[key], project[key]))) {
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;
@@ -384,6 +385,10 @@ export function applyProjectPatch(project, patch) {
}
+function retireVideoPlan(plan) {
+ return { history: [...(plan.history || []), { steps: structuredClone(plan.steps), updatedAt: plan.updatedAt }] };
+}
+
function priorVideoTreatments(project) {
if (!project.treatment?.artifact) return [];
// Snapshots contain one revision only; nesting prior history grows exponentially.
@@ -427,7 +432,7 @@ export function applyTreatment(project, treatmentInput, sourceRevisions) {
let priorChanged = false;
scenes = scenes.sort((a, b) => a.order - b.order).map(scene => {
const old = previous.get(scene.sceneId);
- const unchanged = old && !project.treatment?.artifact?.stale && JSON.stringify(videoSceneInputs(old)) === JSON.stringify(videoSceneInputs(scene))
+ const unchanged = old && !project.treatment?.artifact?.stale && isDeepStrictEqual(videoSceneInputs(old), videoSceneInputs(scene))
&& !(scene.useContinuationFromPrior && priorChanged);
priorChanged = !unchanged;
return unchanged ? { ...scene, status: old.status, retryCount: old.retryCount, renderedJobId: old.renderedJobId,
@@ -446,6 +451,9 @@ export function applyTreatment(project, treatmentInput, sourceRevisions) {
return {
...project,
treatment,
+ ...(project.workspace === 'video' && project.plan?.steps ? {
+ plan: retireVideoPlan(project.plan),
+ } : {}),
...(project.workspace === 'video' ? { videoCutHistory: retainVideoCuts(project), videoRoughCut: null, videoFinalCut: null, finalVideoId: null } : {}),
status: nextStatus,
updatedAt: new Date().toISOString(),
@@ -492,7 +500,7 @@ export function applyPlan(project, planInput) {
if (project.workspace === 'video') {
for (const step of parsed.data.steps) {
const prior = prevById.get(step.stepId);
- if (!prior || project.treatment?.artifact?.stale || JSON.stringify([prior.toolName, prior.args, prior.dependsOn || []]) !== JSON.stringify([step.toolName, step.args, step.dependsOn || []])) invalidated.add(step.stepId);
+ if (!prior || project.treatment?.artifact?.stale || !isDeepStrictEqual([prior.toolName, prior.args, prior.dependsOn || []], [step.toolName, step.args, step.dependsOn || []])) invalidated.add(step.stepId);
}
let changed = true;
while (changed) {
@@ -533,7 +541,7 @@ export function applyPlan(project, planInput) {
return {
...project,
...(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() },
+ plan: { steps, replanRounds, ...(project.workspace === 'video' ? { submittedProductionRevision: project.videoWorkRevision || 0 } : {}), ...(project.workspace === 'video' && project.plan ? { history: [...(project.plan.history || []), ...(project.plan.steps ? [{ steps: structuredClone(prevSteps), updatedAt: project.plan.updatedAt }] : [])] } : {}), ...(parsed.data.sourceContextRevision ? { sourceContextRevision: parsed.data.sourceContextRevision } : {}), updatedAt: new Date().toISOString() },
status: nextStatus,
updatedAt: new Date().toISOString(),
};
@@ -579,20 +587,31 @@ export function applySceneUpdate(project, sceneId, patch) {
const { expectedWorkRevision, ...changes } = patch;
const previousScene = project.treatment.scenes[sceneIdx];
if (project.workspace === 'video' && expectedWorkRevision !== undefined && expectedWorkRevision !== (previousScene.workRevision || 0)) {
- throw new ServerError('This shot callback belongs to a superseded revision', { status: 409, code: 'VIDEO_WORK_STALE' });
+ throw new ServerError('This shot belongs to a superseded revision. Refresh the project before applying your changes.', { status: 409, code: 'VIDEO_WORK_STALE' });
}
const updated = { ...previousScene, ...changes };
const scenes = project.treatment.scenes.slice();
scenes[sceneIdx] = updated;
const treatment = { ...project.treatment, scenes };
const creativeEdit = project.workspace === 'video' && treatment.artifact
- && ['prompt', 'imageStrength'].some((key) => key in patch && patch[key] !== previousScene[key]);
+ && ['prompt', 'imageStrength', 'sourceImageFile', 'useContinuationFromPrior'].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;
+ updated.retryCount = 0;
+ // A changed last frame also changes every directly continuing shot, up to
+ // the next independent starting frame.
+ const ordered = [...scenes].sort((a, b) => a.order - b.order);
+ for (let index = ordered.findIndex(scene => scene.sceneId === sceneId) + 1; index < ordered.length && ordered[index].useContinuationFromPrior; index += 1) {
+ const descendant = ordered[index];
+ scenes[scenes.findIndex(scene => scene.sceneId === descendant.sceneId)] = {
+ ...descendant, workRevision: (descendant.workRevision || 0) + 1,
+ status: 'pending', renderedJobId: null, evaluation: null, retryCount: 0,
+ };
+ }
// 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);
@@ -600,6 +619,7 @@ export function applySceneUpdate(project, sceneId, patch) {
const next = {
...project,
treatment,
+ ...(creativeEdit && project.plan?.steps ? { plan: retireVideoPlan(project.plan) } : {}),
...(creativeEdit ? { status: 'paused', videoWorkRevision: (project.videoWorkRevision || 0) + 1, videoCutHistory: retainVideoCuts(project), videoRoughCut: null, videoFinalCut: null, finalVideoId: null } : {}),
updatedAt: new Date().toISOString(),
};
diff --git a/server/services/creativeDirector/sceneRunner.backend.test.js b/server/services/creativeDirector/sceneRunner.backend.test.js
index 542ede5786..d035b51102 100644
--- a/server/services/creativeDirector/sceneRunner.backend.test.js
+++ b/server/services/creativeDirector/sceneRunner.backend.test.js
@@ -267,6 +267,26 @@ describe('runSceneRender — Reactor and fal pins', () => {
describe('Video production review boundary', () => {
+ it('renders native audio despite the legacy muted default and pauses on shared runtime setup failure', async () => {
+ const shot = scene({ workRevision: 0, status: 'pending' });
+ const video = project({ workspace: 'video', status: 'rendering', videoOwnerInstanceId: 'example-owner', disableAudio: true,
+ renderBackend: { video: { mode: 'reactor' } },
+ videoExecution: { id: 'example-execution', authorized: true, limits: { maxClips: 3, maxRetries: 1, maxAgentCalls: 10, maxReplans: 1, spendCapUsd: null }, choices: { video: { mode: 'reactor' }, audio: { mode: 'native' }, evaluation: { type: 'agent' } } },
+ videoDraft: { sources: [], audio: { mode: 'native' } },
+ treatment: { artifact: { revision: 1 }, script: 'Example script', scenes: [shot] } });
+ video.videoExecution.inputRevision = videoConfigurationRevision(video);
+ const checkpoint = videoReviewStages(video)[0];
+ video.videoReview = { decisions: { [checkpoint.stage]: { action: 'approve', revision: checkpoint.revision } } };
+ getProject.mockResolvedValue(video);
+ getSettings.mockResolvedValue({ videoGen: { reactor: { apiKey: 'example-test-key' } } });
+ expect(await runSceneRender(video, shot)).toBe('job-1');
+ expect(enqueuedParams()).toMatchObject({ mode: 'reactor', seconds: 8 });
+ expect(enqueuedParams().disableAudio).not.toBe(true);
+ mediaJobEvents.on.mock.calls.find(([event]) => event === 'failed')[1]({ id: 'job-1', error: 'Automatic Reactor runtime preparation failed' });
+ await vi.waitFor(async () => expect((await getProject()).status).toBe('paused'));
+ expect(enqueueJob).toHaveBeenCalledTimes(1);
+ });
+
it('does not enqueue before approval and ignores a superseded render completion', async () => {
const shot = scene({ workRevision: 0, status: 'pending' });
const video = project({ workspace: 'video', status: 'rendering', videoOwnerInstanceId: 'example-owner',
diff --git a/server/services/creativeDirector/sceneRunner.js b/server/services/creativeDirector/sceneRunner.js
index 9441eba4c2..2eb61fc9af 100644
--- a/server/services/creativeDirector/sceneRunner.js
+++ b/server/services/creativeDirector/sceneRunner.js
@@ -270,6 +270,7 @@ export async function runSceneRender(project, scene) {
console.error(`❌ CD scene ${scene.sceneId}: could not queue the render: ${error.message}`);
if (project.workspace === 'video') {
const { pauseVideoExecution } = await import('./videoExecution.js');
+ await updateScene(project.id, scene.sceneId, { expectedWorkRevision: scene.workRevision || 0, status: 'pending' });
await pauseVideoExecution(project.id, error.message);
return null;
}
@@ -495,7 +496,7 @@ async function handleRenderFailed(projectId, sceneId, errorMsg, { retry = true,
const scene = fresh.treatment?.scenes?.find((s) => s.sceneId === sceneId);
if (!scene || (workRevision !== undefined && workRevision !== (scene.workRevision || 0))) return;
const nextRetry = (scene.retryCount || 0) + 1;
- if (fresh.workspace === 'video' && /quota|credit|balance|429|timeout|timed out|interrupted/i.test(errorMsg)) {
+ if (fresh.workspace === 'video' && /quota|credit|balance|429|timeout|timed out|interrupted|runtime (?:preparation|verification) failed|custom Reactor Python runtime/i.test(errorMsg)) {
const { pauseVideoExecution } = await import('./videoExecution.js');
await pauseVideoExecution(projectId, `Render blocked: ${errorMsg}. Review the provider and saved job before Resume.`);
return;
diff --git a/server/services/creativeDirector/sourceRevisionPersistence.test.js b/server/services/creativeDirector/sourceRevisionPersistence.test.js
index 871e1df043..5bb6d0b709 100644
--- a/server/services/creativeDirector/sourceRevisionPersistence.test.js
+++ b/server/services/creativeDirector/sourceRevisionPersistence.test.js
@@ -21,14 +21,36 @@ vi.mock('../../lib/conflictJournal.js', () => ({
}));
vi.mock('../catalogDB/ingredients.js', () => ({ getIngredient: vi.fn() }));
import { getIngredient } from '../catalogDB/ingredients.js';
-import { setTreatment, getProject } from './projectsDB.js';
+import { setTreatment, getProject, updateProject } from './projectsDB.js';
import { getVideoSourceStatus } from './videoSources.js';
describe('Video source revision persistence through the PostgreSQL adapter', () => {
+ it('preserves approved work when a settings save only changes JSON object key order', async () => {
+ state.project = {
+ id: 'cd-settings', workspace: 'video', status: 'paused', videoWorkRevision: 3,
+ renderBackend: { video: { modelId: 'fast-h3', mode: 'reactor' }, image: { mode: 'local' } },
+ treatment: { artifact: { revision: 2 }, scenes: [{ sceneId: 'shot-1', workRevision: 3 }] },
+ videoFinalCut: { videoId: 'approved-cut' }, finalVideoId: 'approved-cut',
+ };
+ const saved = await updateProject(state.project.id, {
+ renderBackend: { image: { mode: 'local' }, video: { mode: 'reactor', modelId: 'fast-h3' } },
+ });
+ expect(saved.treatment.artifact.stale).not.toBe(true);
+ expect(saved.videoWorkRevision).toBe(3);
+ expect(saved.finalVideoId).toBe('approved-cut');
+ const revised = await updateProject(state.project.id, {
+ renderBackend: { image: { mode: 'local' }, video: { mode: 'reactor', modelId: 'quality-h3' } },
+ });
+ expect(revised.treatment.artifact.stale).toBe(true);
+ expect(revised.videoWorkRevision).toBe(4);
+ expect(revised.finalVideoId).toBeNull();
+ });
+
it('awaits source resolution, preserves the captured stamp across reads, and refuses an unavailable source', async () => {
state.project = {
id: 'cd-example', workspace: 'video', status: 'draft', targetDurationSeconds: 60, aspectRatio: '16:9',
videoDraft: { sources: [{ kind: 'catalog', id: 'example-catalog', revision: 'user-label' }] },
+ plan: { steps: [{ stepId: 'old-shot', status: 'succeeded', args: { prompt: 'Previous story' } }] },
};
state.writes = 0;
const source = { id: 'example-catalog', updatedAt: '2026-09-01T00:00:00.000Z', payload: { description: 'Example scene' } };
@@ -40,6 +62,8 @@ describe('Video source revision persistence through the PostgreSQL adapter', ()
};
await setTreatment(state.project.id, treatment);
const saved = await getProject(state.project.id);
+ expect(saved.plan.steps).toBeUndefined();
+ expect(saved.plan.history[0].steps[0]).toMatchObject({ stepId: 'old-shot', status: 'succeeded' });
expect(saved.treatment.artifact.references[0]).toEqual({
kind: 'catalog', id: 'example-catalog', revision: 'user-label', referenceId: 'catalog:example-catalog', sourceRevision: expect.stringMatching(/^[a-f0-9]{32}$/),
});
diff --git a/server/services/creativeDirector/videoExecution.js b/server/services/creativeDirector/videoExecution.js
index 6a463a5d04..e5c4a9cfbb 100644
--- a/server/services/creativeDirector/videoExecution.js
+++ b/server/services/creativeDirector/videoExecution.js
@@ -24,6 +24,9 @@ export function effectiveVideoProject(project) {
const choices = project.videoExecution?.choices;
if (project.workspace !== 'video' || !choices) return project;
return { ...project, renderBackend: { ...project.renderBackend, video: choices.video },
+ // Video audio is selected for assembly. Legacy projects default to muted
+ // clips, but that flag must not override the reviewed Video audio contract.
+ disableAudio: false,
modelId: choices.video.modelId || project.modelId,
modelOverrides: { ...project.modelOverrides, treatment: choices.treatment, plan: choices.plan,
...(choices.evaluation.type === 'api' ? { evaluation: choices.evaluation } : {}) } };
@@ -158,6 +161,7 @@ export async function reconcileVideoExecution(projectId, { restarting = false, r
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');
+ if (!receipt && scene.status === 'rendering' && !scene.renderedJobId) return { ...scene, status: 'pending' };
if (receipt?.status === 'completed' && receipt.jobId && !['accepted', 'evaluating'].includes(scene.status)) return { ...scene, renderedJobId: receipt.jobId, status: 'evaluating' };
if (receipt?.status === 'failed' && ['rendering', 'failed'].includes(scene.status)) return { ...scene, status: 'pending' };
return scene;
diff --git a/server/services/creativeDirector/videoExecution.test.js b/server/services/creativeDirector/videoExecution.test.js
index 87d0913c88..1cfb4d177b 100644
--- a/server/services/creativeDirector/videoExecution.test.js
+++ b/server/services/creativeDirector/videoExecution.test.js
@@ -85,6 +85,16 @@ it('refuses stale choices, unavailable pinned credentials and unenforceable doll
expect(startCreativeDirectorProject).not.toHaveBeenCalled();
});
+it('resumes a shot whose preflight failed before creating a submission receipt', async () => {
+ state.project.status = 'paused';
+ state.project.treatment.scenes[0].status = 'rendering';
+ state.project.treatment.scenes[0].renderedJobId = null;
+ await startVideoExecution('example-video', await startInput());
+ expect(state.project.treatment.scenes[0].status).toBe('pending');
+ expect(startCreativeDirectorProject).toHaveBeenCalledTimes(1);
+ expect(await enqueue()).toMatchObject({ jobId: 'example-job-1' });
+});
+
it('reserves before enqueue, binds one queue ID, enforces retry bounds and pauses dispatch', async () => {
await startVideoExecution('example-video', await startInput({ maxClips: 2, maxRetries: 0 }));
const queued = await enqueue();
diff --git a/server/services/creativeDirector/videoReview.test.js b/server/services/creativeDirector/videoReview.test.js
index da42042b70..f5222ce655 100644
--- a/server/services/creativeDirector/videoReview.test.js
+++ b/server/services/creativeDirector/videoReview.test.js
@@ -29,6 +29,17 @@ beforeEach(() => {
const inputFor = async (stage, action, extra = {}) => ({ stage, action, revision: (await getVideoReview('example-video')).checkpoints.find(row => row.stage === stage).revision, ...extra });
describe('Video review workflow', () => {
+ it('invalidates reference edits and continuing clips while preserving independent accepted shots', async () => {
+ await reviewVideo('example-video', await inputFor('script-shot-plan', 'approve'));
+ mocks.project = applySceneUpdate(mocks.project, 'one', { sourceImageFile: 'example-frame.png', expectedWorkRevision: 0 }).project;
+ expect(mocks.project.status).toBe('paused');
+ expect(mocks.project.treatment.scenes.map(s => s.status)).toEqual(['pending', 'pending', 'accepted']);
+ expect(mocks.project.treatment.scenes.map(s => s.workRevision)).toEqual([1, 1, 0]);
+ expect(mocks.project.treatment.history[0].scenes[0].renderedJobId).toBe('example-render-one');
+ expect(await videoReviewAllowsDispatch('example-video', ['script-shot-plan', 'references'])).toBe(false);
+ expect(() => applySceneUpdate(mocks.project, 'two', { expectedWorkRevision: 0, status: 'accepted' })).toThrow('superseded revision');
+ });
+
it('blocks actual consumption until current approval, resumes once, and keeps feedback separate', async () => {
expect(await videoReviewAllowsDispatch('example-video', ['script-shot-plan', 'references'])).toBe(false);
expect(mocks.project.videoReview.waitingFor.stage).toBe('script-shot-plan');
@@ -64,6 +75,8 @@ describe('Video review workflow', () => {
it('rejects callbacks after a whole-stage revision and resets active work', async () => {
mocks.project.treatment.scenes[0].status = 'rendering';
await reviewVideo('example-video', await inputFor('script-shot-plan', 'request-revision', { note: 'Revise the script' }));
+ expect(mocks.project.treatment.artifact.stale).toBe(true);
+ expect((await getVideoReview('example-video')).checkpoints[0].ready).toBe(false);
expect(mocks.project.treatment.scenes[0]).toMatchObject({ status: 'pending', renderedJobId: null, workRevision: 1 });
expect(() => applySceneUpdate(mocks.project, 'one', { expectedWorkRevision: 0, status: 'accepted' })).toThrow('superseded revision');
expect(mocks.project.treatment.scenes[2].renderedJobId).toBe('example-render-three');