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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
Bound Video production execution and reconcile saved submissions (#6588)
[._.]/8ce46e630cb6
diff --git a/client/src/components/creative-director/VideoDraftDrawer.jsx b/client/src/components/creative-director/VideoDraftDrawer.jsxindex b7a7146882..d71be7c038 100644--- a/client/src/components/creative-director/VideoDraftDrawer.jsx+++ b/client/src/components/creative-director/VideoDraftDrawer.jsx@@ -80,7 +80,7 @@ export default function VideoDraftDrawer({ open, onClose, project, onSaved, cata<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('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. Production is unavailable until revision approval and dispatch controls are implemented.</p>+ <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></>}{tab === 'sources' && <>{sourceKind === 'catalog' && <div className="flex items-end gap-2"><label htmlFor="video-source-search" className="flex-1">Search catalog<input id="video-source-search" className={fieldClass} value={sourceQuery} onChange={e => setSourceQuery(e.target.value)} /></label><button onClick={() => { setSourceId(''); listCatalogIngredients({ q: sourceQuery, limit: 100, silent: true }).then(data => setSourceOptions(prev => ({ ...prev, catalog: Array.isArray(data) ? data : data?.items || [] }))).catch(() => toast.error('Unable to search catalog')); }} className="px-3 py-2 rounded border border-port-border">Search</button></div>}diff --git a/client/src/components/creative-director/VideoExecutionPanel.jsx b/client/src/components/creative-director/VideoExecutionPanel.jsxnew file mode 100644index 0000000000..e14ece6687--- /dev/null+++ b/client/src/components/creative-director/VideoExecutionPanel.jsx@@ -0,0 +1,84 @@+import { useEffect, useRef, useState } from 'react';+import { Link } from 'react-router';+import { getCreativeDirectorVideoExecution, startCreativeDirectorVideoExecution } from '../../services/apiCreativeDirector.js';++const LIMITS = [+ ['maxClips', 'Maximum clip submissions', 1, 200],+ ['maxRetries', 'Retries per shot or step', 0, 3],+ ['maxReplans', 'Replans', 0, 5],+ ['maxAgentCalls', 'Maximum agent calls', 1, 500],+];+const choiceText = choice => choice ? `${choice.providerId || choice.mode} · ${choice.modelDescription || choice.model || choice.modelId || 'provider default'}${choice.effort ? ` · ${choice.effort}` : ''}` : 'Not available';++export default function VideoExecutionPanel({ project, onChange, basePath }) {+ const [preview, setPreview] = useState(null);+ const [limits, setLimits] = useState(null);+ const [retryAttemptIds, setRetryAttemptIds] = useState([]);+ const [error, setError] = useState('');+ const [pending, setPending] = useState(false);+ const [reload, setReload] = useState(0);+ const submitting = useRef(false);+ useEffect(() => {+ let active = true;+ getCreativeDirectorVideoExecution(project.id, { silent: true }).then(result => {+ if (!active) return;+ setPreview(result);+ setLimits(previous => previous || result.limits);+ }).catch(err => { if (active) setError(err.message || 'Could not load production choices'); });+ return () => { active = false; };+ }, [project.id, project.updatedAt, reload]);+ const active = ['planning', 'rendering', 'stitching'].includes(project.status);+ const uncertain = (preview?.execution?.attempts || []).filter(attempt => attempt.status === 'uncertain');+ const valid = limits && LIMITS.every(([key, , min, max]) => limits[key] !== '' && Number.isInteger(Number(limits[key])) && Number(limits[key]) >= min && Number(limits[key]) <= max)+ && (limits.spendCapUsd === null || limits.spendCapUsd === '' || Number(limits.spendCapUsd) > 0);+ const start = async () => {+ if (submitting.current || !valid) return;+ submitting.current = true;+ setPending(true);+ setError('');+ try {+ await startCreativeDirectorVideoExecution(project.id, {+ configurationRevision: preview.configurationRevision,+ limits: { ...Object.fromEntries(LIMITS.map(([key]) => [key, Number(limits[key])])), spendCapUsd: limits.spendCapUsd === '' || limits.spendCapUsd === null ? null : Number(limits.spendCapUsd) },+ retryAttemptIds,+ }, { silent: true });+ setRetryAttemptIds([]);+ onChange?.();+ setReload(value => value + 1);+ } catch (err) {+ setError(err.message || 'Could not start production');+ setReload(value => value + 1);+ } finally {+ submitting.current = false;+ setPending(false);+ }+ };+ return <section aria-label="Video execution" className="rounded border border-port-border p-4 space-y-3">+ <h3 className="font-medium">Production choices and limits</h3>+ {!preview && !error && <p role="status">Loading production choices…</p>}+ {error && <p role="alert" className="text-port-error">{error}</p>}+ {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>+ </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>)}+ {preview.execution?.blocker && <p role="status" className="text-port-warning">{preview.execution.blocker}</p>}+ <div className="flex flex-wrap gap-3 text-sm"><Link className="underline" to="/settings">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}>+ <label className="block text-sm" htmlFor={`video-limit-${key}`}>{label}</label>+ <input id={`video-limit-${key}`} type="number" min={min} max={max} step="1" value={limits[key]} disabled={active || pending} onChange={event => setLimits(previous => ({ ...previous, [key]: event.target.value }))} className="w-full rounded border border-port-border bg-port-bg p-2" />+ </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>+ {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>)}+ <button onClick={start} disabled={active || pending || !preview.canStart || !valid || uncertain.some(attempt => !retryAttemptIds.includes(attempt.id))} className="rounded bg-port-accent px-3 py-2 text-white disabled:opacity-40">{pending ? 'Starting…' : project.status === 'draft' ? 'Start production' : 'Resume production'}</button>+ </>}+ <button className="text-sm underline" onClick={() => setReload(value => value + 1)} disabled={pending}>Refresh choices</button>+ </section>;+}diff --git a/client/src/components/creative-director/VideoExecutionPanel.test.jsx b/client/src/components/creative-director/VideoExecutionPanel.test.jsxnew file mode 100644index 0000000000..8ffaa8a0cc--- /dev/null+++ b/client/src/components/creative-director/VideoExecutionPanel.test.jsx@@ -0,0 +1,45 @@+import { beforeEach, expect, it, vi } from 'vitest';+import { render, screen, waitFor } from '@testing-library/react';+import userEvent from '@testing-library/user-event';+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 };+beforeEach(() => {+ vi.resetAllMocks();+ getCreativeDirectorVideoExecution.mockResolvedValue(preview);+ startCreativeDirectorVideoExecution.mockResolvedValue({});+});+const show = status => render(<MemoryRouter><VideoExecutionPanel project={{ id: 'example-video', status }} basePath="/video/productions" /></MemoryRouter>);+it('shows reviewed choices and submits explicit limits with the displayed configuration revision', async () => {+ const user = userEvent.setup();+ show('draft');+ expect(await screen.findByText('reactor · fast-h3')).toBeInTheDocument();+ expect(startCreativeDirectorVideoExecution).not.toHaveBeenCalled();+ await user.clear(screen.getByLabelText('Maximum clip submissions'));+ expect(screen.getByRole('button', { name: 'Start production' })).toBeDisabled();+ await user.type(screen.getByLabelText('Maximum clip submissions'), '8');+ await user.click(screen.getByRole('button', { name: 'Start production' }));+ expect(startCreativeDirectorVideoExecution).toHaveBeenCalledWith('example-video', { configurationRevision: preview.configurationRevision, limits: { ...preview.limits, maxClips: 8 }, retryAttemptIds: [] }, { silent: true });+});+it('requires explicit acknowledgement of uncertain submissions before Resume', async () => {+ const user = userEvent.setup();+ const attemptId = '00000000-0000-4000-8000-000000000001';+ getCreativeDirectorVideoExecution.mockResolvedValue({ ...preview, execution: { attempts: [{ id: attemptId, kind: 'clip', sceneId: 'opening', status: 'uncertain' }] } });+ show('paused');+ const resume = await screen.findByRole('button', { name: 'Resume production' });+ expect(resume).toBeDisabled();+ await user.click(screen.getByRole('checkbox', { name: /retrying may charge again/ }));+ await user.click(resume);+ expect(startCreativeDirectorVideoExecution).toHaveBeenCalledWith('example-video', expect.objectContaining({ retryAttemptIds: [attemptId] }), { silent: true });+});++it('keeps the Start rejection visible after refreshing provider choices', async () => {+ const user = userEvent.setup();+ startCreativeDirectorVideoExecution.mockRejectedValue(new Error('The dollar cap cannot bound this provider'));+ show('draft');+ await user.click(await screen.findByRole('button', { name: 'Start production' }));+ await waitFor(() => expect(getCreativeDirectorVideoExecution).toHaveBeenCalledTimes(2));+ expect(screen.getByRole('alert')).toHaveTextContent('The dollar cap cannot bound this provider');+});diff --git a/client/src/pages/CreativeDirectorDetail.jsx b/client/src/pages/CreativeDirectorDetail.jsxindex 4a9ded7bae..668da88de3 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 VideoExecutionPanel from '../components/creative-director/VideoExecutionPanel.jsx';import VideoReviewPanel from '../components/creative-director/VideoReviewPanel.jsx';import VideoDraftDrawer from '../components/creative-director/VideoDraftDrawer.jsx';import OverviewTab from '../components/creative-director/OverviewTab.jsx';@@ -329,12 +330,13 @@ export default function CreativeDirectorDetail({ basePath = '/creative-director'<ActiveAgentsBanner agents={activeAgents} />{project.workspace === 'video' && activeTab === 'overview' && <section className="space-y-4">- <h2 className="text-lg font-medium">Video draft</h2>- <p className="text-port-text-muted">Stage: {project.status}. Production is blocked until revision approvals and dispatch controls are available. Next: refine your brief, source references, and model selections.</p>+ <h2 className="text-lg font-medium">Video production</h2>+ <p className="text-port-text-muted">Stage: {project.status}. Start authorizes the saved choices within your limits. Enabled review checkpoints pause for your approval.</p><p className="whitespace-pre-wrap">{project.userStory || 'Add a brief to describe this video.'}</p><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>- <button onClick={() => setEditingDraft(true)} className="px-3 py-2 rounded bg-port-accent text-white">Edit draft</button>+ {['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>}+ <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>}{project.workspace !== 'video' && activeTab === 'overview' && (diff --git a/client/src/pages/CreativeDirectorDetail.test.jsx b/client/src/pages/CreativeDirectorDetail.test.jsxindex fcaa67bc52..d91149bcda 100644--- a/client/src/pages/CreativeDirectorDetail.test.jsx+++ b/client/src/pages/CreativeDirectorDetail.test.jsx@@ -5,6 +5,8 @@ import { MemoryRouter, Route, Routes, useLocation } from 'react-router';vi.mock('../services/apiCreativeDirector.js', () => ({getCreativeDirectorProject: vi.fn(),+ getCreativeDirectorVideoExecution: vi.fn(async () => ({ canStart: false, blockers: ['Configure a provider'], choices: null, limits: { maxClips: 60, maxRetries: 1, maxReplans: 2, maxAgentCalls: 100, spendCapUsd: null }, execution: null })),+ startCreativeDirectorVideoExecution: vi.fn(),getCreativeDirectorSources: vi.fn(async () => ({ draft: [], artifact: [] })),deleteCreativeDirectorProject: vi.fn(),startCreativeDirectorProject: vi.fn(),diff --git a/client/src/services/apiCreativeDirector.js b/client/src/services/apiCreativeDirector.jsindex bcefe4bcb0..a3d1ca7c6a 100644--- a/client/src/services/apiCreativeDirector.js+++ b/client/src/services/apiCreativeDirector.js@@ -109,3 +109,8 @@ export const getCreativeDirectorVideoReview = (id, options = {}) => request(`/crexport const submitCreativeDirectorVideoReview = (id, input, options = {}) => request(`/creative-director/${encodeURIComponent(id)}/review`, {method: 'POST', body: JSON.stringify(input), ...options,});++export const getCreativeDirectorVideoExecution = (id, options = {}) => request(`/creative-director/${encodeURIComponent(id)}/execution`, options);+export const startCreativeDirectorVideoExecution = (id, input, options = {}) => request(`/creative-director/${encodeURIComponent(id)}/start`, {+ method: 'POST', body: JSON.stringify(input), ...options,+});diff --git a/docs/STORAGE.md b/docs/STORAGE.mdindex d22db6c4b9..15bf54fc44 100644--- a/docs/STORAGE.md+++ b/docs/STORAGE.md@@ -331,3 +331,15 @@ never ride the wire. Owner records reject remote overwrites, and receivers neveracquire local execution authorization from sync. Pre-owner Video drafts remain inertand can be recreated locally from their settings. Legacy generalized projects retaintheir prior sync/execution behavior. Project sync v8 gates these semantics.++Video execution authorization and attempt receipts persist in the same project+JSONB as `videoExecution`: frozen provider/model identifiers, reviewed configuration+revision, limits, and queued job/task IDs. These are machine-local and excluded+from sync. No credentials or separate store are introduced. Clip submissions,+agent calls, retries and replans consume explicit limits; unknown provider prices+prevent promising a dollar cap. Pause revokes dispatch before canceling owned work.+Restart reconciles receipts without replaying provider submissions; uncertain+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.diff --git a/server/lib/creativeDirectorValidation.js b/server/lib/creativeDirectorValidation.jsindex 67ecec75a4..68d21f61fa 100644--- a/server/lib/creativeDirectorValidation.js+++ b/server/lib/creativeDirectorValidation.js@@ -124,6 +124,19 @@ export const creativeDirectorRenderBackendSchema = z.object({video: creativeDirectorRenderPinSchema.optional(),}).strict();+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),+ maxAgentCalls: z.number().int().min(1).max(500).default(100),+ spendCapUsd: z.number().positive().max(10000).nullable().default(null),+}).strict();+export const creativeDirectorVideoStartSchema = z.object({+ configurationRevision: z.string().regex(/^[a-f0-9]{32}$/),+ limits: creativeDirectorVideoLimitsSchema,+ retryAttemptIds: z.array(z.string().uuid()).max(200).default([]),+}).strict();+// Additive workspace metadata. Absence keeps pre-Video execution semantics.export const creativeDirectorVideoDraftSchema = z.object({durationRange: z.object({diff --git a/server/lib/schemaVersions.js b/server/lib/schemaVersions.jsindex 9b7071c3c0..29edc03bb5 100644--- a/server/lib/schemaVersions.js+++ b/server/lib/schemaVersions.js@@ -454,7 +454,8 @@ export const PORTOS_SCHEMA_VERSIONS = Object.freeze({// v6: Preserve Video treatment history; older writers discard prior snapshots.// v7: Planning binds to resolved source revisions; older writers skip that guard.// v8: Revision-bound approvals and machine-local execution authority.- creativeDirectorProjects: 8,+ // v9: Bounded owner execution receipts and fail-closed restart reconciliation.+ creativeDirectorProjects: 9,// 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 synceddiff --git a/server/routes/creativeDirector.js b/server/routes/creativeDirector.jsindex b78c62b47d..1b705ea81b 100644--- a/server/routes/creativeDirector.js+++ b/server/routes/creativeDirector.js@@ -15,6 +15,7 @@ import {creativeDirectorProjectUpdateSchema,creativeDirectorTreatmentSchema,creativeDirectorVideoReviewActionSchema,+ creativeDirectorVideoStartSchema,creativeDirectorPlanSchema,creativeDirectorPlanStepActionSchema,creativeDirectorDirectiveSchema,@@ -404,10 +405,19 @@ router.patch('/:id/scene/:sceneId', asyncHandler(async (req, res) => {// the orchestrator can retry them, and the project status flips back to// planning/rendering. This matches the PR's "you can resume from the UI"// promise — without it, a single failed scene would leave Start a no-op.+router.get('/:id/execution', asyncHandler(async (req, res) => {+ const { getVideoExecutionPreview } = await import('../services/creativeDirector/videoExecution.js');+ res.json(await getVideoExecutionPreview(req.params.id));+}));+router.post('/:id/start', asyncHandler(async (req, res) => {const project = await getProject(req.params.id);if (!project) throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });- assertVideoDispatchAvailable(project);+ if (project.workspace === 'video') {+ const input = validateRequest(creativeDirectorVideoStartSchema, req.body);+ const { startVideoExecution } = await import('../services/creativeDirector/videoExecution.js');+ return res.json(await startVideoExecution(project.id, input));+ }if (project.status === 'failed') {// Reset every failed scene back to pending so the orchestrator picks// them up. Without this, a single failed scene would leave Start a no-op.@@ -436,6 +446,11 @@ router.post('/:id/start', asyncHandler(async (req, res) => {// work. The currently running render (if any) keeps going to completion —// canceling that is a separate gesture (POST /api/media-jobs/:id/cancel).router.post('/:id/pause', asyncHandler(async (req, res) => {+ const project = await getProject(req.params.id);+ if (project?.workspace === 'video') {+ await stopProject(project.id, { reason: 'Paused by the user.' });+ return res.json(await getProject(project.id));+ }const updated = await updateProject(req.params.id, { status: 'paused' });res.json(updated);}));@@ -453,7 +468,11 @@ router.post('/smoke-test', asyncHandler(async (_req, res) => {router.post('/:id/resume', asyncHandler(async (req, res) => {const project = await getProject(req.params.id);if (!project) throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });- assertVideoDispatchAvailable(project);+ if (project.workspace === 'video') {+ const input = validateRequest(creativeDirectorVideoStartSchema, req.body);+ const { startVideoExecution } = await import('../services/creativeDirector/videoExecution.js');+ return res.json(await startVideoExecution(project.id, input));+ }if (project.status !== 'paused') {throw new ServerError('Project is not paused', { status: 400, code: 'INVALID_STATE' });}diff --git a/server/routes/creativeDirector.test.js b/server/routes/creativeDirector.test.jsindex 39a4bf2973..3e2e97532c 100644--- a/server/routes/creativeDirector.test.js+++ b/server/routes/creativeDirector.test.js@@ -77,6 +77,8 @@ import * as creativeTools from '../services/creative/toolRegistry.js';import { CREATIVE_DIRECTOR_IDS_BATCH_MAX } from '../lib/creativeDirectorValidation.js';vi.mock('../services/creativeDirector/videoReview.js', () => ({ reviewVideo: vi.fn(async () => ({ checkpoints: [], feedback: [] })), getVideoReview: vi.fn(async () => ({ checkpoints: [], canReview: true })) }));import { reviewVideo } from '../services/creativeDirector/videoReview.js';+vi.mock('../services/creativeDirector/videoExecution.js', () => ({ getVideoExecutionPreview: vi.fn(async () => ({ canStart: true })), startVideoExecution: vi.fn(async () => ({ status: 'planning' })) }));+const { getVideoExecutionPreview, startVideoExecution } = await import('../services/creativeDirector/videoExecution.js');import creativeDirectorRoutes from './creativeDirector.js';describe('creativeDirector routes', () => {@@ -89,6 +91,19 @@ describe('creativeDirector routes', () => {vi.clearAllMocks();});+ it('previews choices, validates explicit Start limits, and cancels owned work on Video Pause', async () => {+ cdService.getProject.mockResolvedValue({ id: 'cd-video', workspace: 'video', status: 'draft' });+ expect((await request(app).get('/api/creative-director/cd-video/execution')).body.canStart).toBe(true);+ expect(getVideoExecutionPreview).toHaveBeenCalledWith('cd-video');+ const input = { configurationRevision: 'a'.repeat(32), limits: { maxClips: 2 } };+ expect((await request(app).post('/api/creative-director/cd-video/start').send({ ...input, limits: { maxClips: 0 } })).status).toBe(400);+ expect(startVideoExecution).not.toHaveBeenCalled();+ expect((await request(app).post('/api/creative-director/cd-video/start').send(input)).status).toBe(200);+ expect(startVideoExecution).toHaveBeenCalledWith('cd-video', expect.objectContaining({ configurationRevision: input.configurationRevision, limits: expect.objectContaining({ maxClips: 2 }) }));+ await request(app).post('/api/creative-director/cd-video/pause').send({});+ expect(stop.stopProject).toHaveBeenCalledWith('cd-video', { reason: 'Paused by the user.' });+ });+it('validates review revisions and feedback before the owner mutation', async () => {const invalid = await request(app).post('/api/creative-director/cd-video/review').send({ action: 'feedback', stage: 'script-shot-plan', revision: 'a'.repeat(32) });expect(invalid.status).toBe(400);@@ -172,7 +187,7 @@ describe('creativeDirector routes', () => {['auto-cast', { compose: true, generateFirstPass: true }],['plan/step/example', { action: 'retry' }],]) {- expect((await request(app).post('/api/creative-director/cd-video/' + action).send(body)).status).toBe(409);+ expect((await request(app).post('/api/creative-director/cd-video/' + action).send(body)).status).toBe(['start', 'resume'].includes(action) ? 400 : 409);}expect(cdService.updateProject).not.toHaveBeenCalled();expect(autoCast.applyAutoCastToProject).not.toHaveBeenCalled();diff --git a/server/services/agentProviderResolution.js b/server/services/agentProviderResolution.jsindex 499828b3dd..b3ce2afb2c 100644--- a/server/services/agentProviderResolution.js+++ b/server/services/agentProviderResolution.js@@ -36,6 +36,18 @@ import { publicReviewPostureForTask, resolvePublicReviewProvider } from './publi* >}*/export async function resolveAgentProviderAndModel(task) {+ if (task?.metadata?.videoProduction) {+ const { assertVideoAttemptDispatch } = await import('./creativeDirector/videoExecution.js');+ const marker = task.metadata.videoProduction;+ const project = await assertVideoAttemptDispatch(marker.projectId, marker.attemptId).catch(() => null);+ if (!project) return { ok: false, permanent: true, error: 'Video production is paused or changed. Review and Resume from the project.' };+ const choice = project.videoExecution.choices[marker.kind === 'evaluate' ? 'evaluation' : marker.kind];+ const provider = choice?.providerId ? await getProviderById(choice.providerId) : null;+ if (!provider || provider.enabled === false || provider.type === 'api' || !await isProviderAvailable(provider.id)) {+ return { ok: false, permanent: true, error: 'The reviewed Video agent provider is unavailable. Change Models or Settings and Resume.' };+ }+ return { ok: true, provider, selectedModel: choice.model, modelSelection: { model: choice.model, tier: 'user-specified', reason: 'Reviewed Video production choice' } };+ }if (isPrivateSecurityTask(task)) {const { privateSecurityEndpoint } = await import('../lib/privateSecuritySandbox.js');Object.assign(task.metadata, PRIVATE_SECURITY_DELIVERY);diff --git a/server/services/creative/tools/media.js b/server/services/creative/tools/media.jsindex d33b999038..b41dbfd1c2 100644--- a/server/services/creative/tools/media.js+++ b/server/services/creative/tools/media.js@@ -143,9 +143,8 @@ export function reconcileVideoParamsWithModel(params, project, models = getVideo* `creativeDirectorMusicBed` already on the params (a caller that set its own* destination) wins and is left as-is.*/-async function configureMusicJob(params, ctx) {+async function configureMusicJob(params, ctx, project) {if (!ctx?.projectId) return params;- const project = await loadOwningProject(ctx);if ((ctx.targetAbility === 'music' || ctx.targetAbility === 'music-video') && !project) {throw new Error('commission-project-unavailable');}@@ -308,12 +307,19 @@ const mediaTool = (kind, label) => ({},execute: async (args, ctx) => {let params = args.params || {};+ const owningProject = await loadOwningProject(ctx);+ let owningVideo = owningProject;+ if (owningVideo?.workspace === 'video') {+ if (kind !== 'video' || !ctx.videoStepId) throw new Error('Video production requires a bounded video plan step.');+ const { effectiveVideoProject } = await import('../../creativeDirector/videoExecution.js');+ owningVideo = effectiveVideoProject(owningVideo);+ } else owningVideo = null;if (kind === 'audio') {- params = await configureMusicJob(params, ctx);+ params = await configureMusicJob(params, ctx, owningProject);} else {// Image + video both consult the owning project: video for its locked// geometry preset, both for a pinned render backend (#3135).- const project = await loadOwningProject(ctx);+ const project = owningVideo || owningProject;if (ctx.targetAbility && !project) throw new Error('commission-project-unavailable');if (kind === 'video') params = enforceVideoRenderPreset(params, project);if (kind === 'image') params = enforceImageRenderPreset(params, project);@@ -344,6 +350,12 @@ const mediaTool = (kind, label) => ({// planner renders but not its scene renders). It resolves LAST, after the// project/install pin ladder above: a configured remote provider overrides// those local backend choices, and an unrouted job is unaffected.+ if (owningVideo) {+ const { enqueueVideoProductionJob } = await import('../../creativeDirector/videoExecution.js');+ const queued = await enqueueVideoProductionJob(owningVideo, { kind, params, stepId: ctx.videoStepId });+ if (!queued) throw new Error('Video production is paused or its execution limit is exhausted.');+ return queued;+ }return enqueueUnattendedMediaJob({ kind, params, owner: resolveOwner(args, ctx) });},});diff --git a/server/services/creativeDirector/agentBridge.js b/server/services/creativeDirector/agentBridge.jsindex c3af297343..8681fb715c 100644--- a/server/services/creativeDirector/agentBridge.js+++ b/server/services/creativeDirector/agentBridge.js@@ -44,7 +44,11 @@ import { DELIVERABLE_KINDS, deliverableMark } from './deliverableGate.js';// Only adds a pin when one is set, preserving the system-default behavior for// existing installations. A commission lookup failure falls through rather than// stalling the dispatch.-async function getStageAssignment(kind, project) {+export async function getStageAssignment(kind, project) {+ if (project.workspace === 'video' && project.videoExecution?.choices) {+ const choice = project.videoExecution.choices[kind === 'evaluate' ? 'evaluation' : kind];+ return { provider: choice.providerId, providerId: choice.providerId, model: choice.model, ...(choice.effort ? { effort: choice.effort } : {}) };+ }// Scene evaluation is a direct vision API call (apiProviderTypes) resolved// separately, NOT a CoS agent pin — injecting its api-type provider into the// agent task metadata would trip the harness-boundary guard. Never pin it@@ -84,6 +88,17 @@ async function buildTaskRecord(project, kind, scene, context) {const taskId = `cd-${project.id}-${kind}-${Date.now().toString(36)}`;const runId = randomUUID();const assignment = await getStageAssignment(kind, project);+ let attempt;+ if (project.workspace === 'video') {+ const { reserveVideoAttempt, assertVideoAttemptDispatch } = await import('./videoExecution.js');+ 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 => {+ const { settleVideoAttempt } = await import('./videoExecution.js');+ await settleVideoAttempt(project.id, attempt.id, { status: 'failed' });+ throw error;+ });+ }return {id: taskId,runId,@@ -94,7 +109,7 @@ async function buildTaskRecord(project, kind, scene, context) {priorityValue: 2,description: buildDescription(project, kind, scene),metadata: {- ...(project.workspace === 'video' ? { machineLocal: true } : {}),+ ...(project.workspace === 'video' ? { machineLocal: true, videoProduction: { projectId: project.id, attemptId: attempt.id, kind } } : {}),creativeDirector: {projectId: project.id,...(project.workspace === 'video' ? { productionRevision: project.videoWorkRevision || 0 } : {}),@@ -141,7 +156,26 @@ function buildDescription(project, kind, scene) {return `Creative Director — ${kind} for "${project.name}" ${tag}`;}-async function persistAndEmit({ id, runId, record }, project, kind, sceneId) {+async function persistAndEmit(built, project, kind, sceneId) {+ const marker = built.record.metadata.videoProduction;+ try {+ const result = await persistAndEmitTask(built, project, kind, sceneId);+ if (marker && result?.metadata?.videoProduction?.attemptId !== marker.attemptId) {+ const { settleVideoAttempt } = await import('./videoExecution.js');+ await settleVideoAttempt(project.id, marker.attemptId, { status: 'failed', duplicateTaskId: result?.id });+ }+ return result;+ } catch (error) {+ if (marker) {+ const { settleVideoAttempt, pauseVideoExecution } = await import('./videoExecution.js');+ await settleVideoAttempt(project.id, marker.attemptId, { status: 'failed' });+ await pauseVideoExecution(project.id, `Agent enqueue stopped: ${error.message}. Review and Resume.`);+ }+ throw error;+ }+}++async function persistAndEmitTask({ id, runId, record }, project, kind, sceneId) {// Persist FIRST and resolve the effective task before recording the run or// emitting `task:ready`. CD descriptions are deterministic per project+kind,// so addTask's dedup (which also matches blocked tasks, #2614) can return an@@ -193,6 +227,10 @@ async function persistAndEmit({ id, runId, record }, project, kind, sceneId) {status: 'running',...(DELIVERABLE_KINDS.has(kind) ? { deliverableMark: deliverableMark(project, kind) } : {}),}).catch((err) => console.log(`⚠️ CD recordRun(running) failed: ${err.message}`));+ if (project.workspace === 'video') {+ const { settleVideoAttempt } = await import('./videoExecution.js');+ await settleVideoAttempt(project.id, record.metadata.videoProduction.attemptId, { status: 'running', taskId: effective.id });+ }cosEvents.emit('task:ready', effective);console.log(`📤 CD task enqueued: ${effective.id} (${kind}${sceneId ? ` for ${sceneId}` : ''} on ${project.id})`);return effective;@@ -201,9 +239,13 @@ async function persistAndEmit({ id, runId, record }, project, kind, sceneId) {export async function enqueueTreatmentTask(project) {const { prepareVideoPlanningProject } = await import('./videoSources.js');project = await prepareVideoPlanningProject(project);+ if (project.workspace === 'video') {+ const { effectiveVideoProject } = await import('./videoExecution.js');+ project = effectiveVideoProject(project);+ }const context = await buildTreatmentPrompt(project);const built = await buildTaskRecord(project, 'treatment', null, context);- return persistAndEmit(built, project, 'treatment', null);+ return built ? persistAndEmit(built, project, 'treatment', null) : null;}// CDO Phase 2 (#2184) — the planner. Mirrors enqueueTreatmentTask: an internal@@ -215,15 +257,19 @@ export async function enqueueTreatmentTask(project) {export async function enqueuePlanTask(project) {const { prepareVideoPlanningProject } = await import('./videoSources.js');project = await prepareVideoPlanningProject(project);+ if (project.workspace === 'video') {+ const { effectiveVideoProject } = await import('./videoExecution.js');+ project = effectiveVideoProject(project);+ }const targetAbility = project?.directive?.constraints?.targetAbility || null;- const context = await buildPlanPrompt(project, { toolSpecs: getToolSpecs({ targetAbility }) });+ const context = await buildPlanPrompt(project, { toolSpecs: getToolSpecs({ targetAbility }).filter(tool => project.workspace !== 'video' || tool.function?.name === 'media_enqueueVideoJob').map(tool => project.workspace === 'video' ? { ...tool, function: { ...tool.function, description: `${tool.function.description} Each step renders exactly one clip; set params.durationSeconds between 1 and 10. Match the saved timed shot plan. Do not batch or chain clips.` } } : tool) });const built = await buildTaskRecord(project, 'plan', null, context);- return persistAndEmit(built, project, 'plan', null);+ return built ? persistAndEmit(built, project, 'plan', null) : null;}export async function enqueueEvaluateTask(project, scene) {if (!scene) throw new Error('enqueueEvaluateTask: scene is required');const context = await buildEvaluatePrompt(project, scene);const built = await buildTaskRecord(project, 'evaluate', scene, context);- return persistAndEmit(built, project, 'evaluate', scene.sceneId);+ return built ? persistAndEmit(built, project, 'evaluate', scene.sceneId) : null;}diff --git a/server/services/creativeDirector/agentBridge.test.js b/server/services/creativeDirector/agentBridge.test.jsindex 0ea8b4f394..5c551b6db3 100644--- a/server/services/creativeDirector/agentBridge.test.js+++ b/server/services/creativeDirector/agentBridge.test.js@@ -14,6 +14,7 @@ const mocks = vi.hoisted(() => ({commissionStagePin: vi.fn(),}));+vi.mock('./videoExecution.js', () => ({ effectiveVideoProject: project => project, reserveVideoAttempt: vi.fn(async () => ({ id: 'example-attempt' })), assertVideoAttemptDispatch: vi.fn(async () => ({})), settleVideoAttempt: vi.fn(async () => {}), pauseVideoExecution: vi.fn(async () => {}) }));vi.mock('../cos.js', () => ({addTask: mocks.addTask,reviveBlockedTask: mocks.reviveBlockedTask,@@ -28,6 +29,7 @@ vi.mock('../creative/toolRegistry.js', () => ({ getToolSpecs: mocks.getToolSpecsvi.mock('../settings.js', () => ({ getSettings: mocks.getSettings }));vi.mock('./local.js', () => ({ recordRun: mocks.recordRun, updateProject: mocks.updateProject }));vi.mock('../universeBuilder/crud.js', () => ({ getUniverse: vi.fn() }));+import { settleVideoAttempt } from './videoExecution.js';import { getUniverse } from '../universeBuilder/crud.js';vi.mock('../pipeline/series.js', () => ({ getSeries: vi.fn() }));vi.mock('../tracks/index.js', () => ({ getTrack: vi.fn() }));@@ -42,6 +44,21 @@ const { enqueueTreatmentTask, enqueuePlanTask, enqueueEvaluateTask } = await impconst project = { id: 'cd-1', name: 'Test project', treatment: { scenes: [] } };describe('Video planning source context', () => {+ it('keeps the bounded video tool specification and retires a failed enqueue reservation', async () => {+ mocks.getToolSpecs.mockReturnValue([+ { 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: [] } };+ 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') }) }),+ ]);+ mocks.addTask.mockRejectedValueOnce(new Error('store unavailable'));+ await expect(enqueueTreatmentTask(video)).rejects.toThrow('store unavailable');+ expect(settleVideoAttempt).toHaveBeenLastCalledWith('cd-1', 'example-attempt', { status: 'failed' });+ });+it('includes a series linked canon and selected audio context without voice bindings or audio paths', async () => {const updatedAt = '2026-09-01T00:00:00Z';getSeries.mockResolvedValue({ updatedAt, title: 'Example series', logline: 'A traveler returns', arc: { summary: 'A reunion' }, universeId: 'example-universe' });diff --git a/server/services/creativeDirector/completionHook.js b/server/services/creativeDirector/completionHook.jsindex f8ad38dc24..179c7ccc1c 100644--- a/server/services/creativeDirector/completionHook.js+++ b/server/services/creativeDirector/completionHook.js@@ -45,6 +45,11 @@ import {} from './deliverableGate.js';export async function handleCreativeDirectorCompletion(task, agentId, success) {+ const videoAttempt = task?.metadata?.videoProduction;+ if (videoAttempt) {+ const { settleVideoAttempt } = await import('./videoExecution.js');+ await settleVideoAttempt(videoAttempt.projectId, videoAttempt.attemptId, { status: success ? 'completed' : 'failed' });+ }const meta = task?.metadata?.creativeDirector;if (!meta?.projectId) return;const project = await getProject(meta.projectId).catch(() => null);@@ -623,7 +628,7 @@ export async function startCreativeDirectorProject(projectId) {const { videoReviewAllowsDispatch } = await import('./videoReview.js');if (!await videoReviewAllowsDispatch(projectId, [])) return;}- if (project?.directive) return advanceAfterPlanStepSettled(projectId);+ if (project?.directive && (project.workspace !== 'video' || project.treatment)) return advanceAfterPlanStepSettled(projectId);return advanceAfterSceneSettled(projectId);}diff --git a/server/services/creativeDirector/local.test.js b/server/services/creativeDirector/local.test.jsindex 33e500522f..808c1d5227 100644--- a/server/services/creativeDirector/local.test.js+++ b/server/services/creativeDirector/local.test.js@@ -85,7 +85,7 @@ describe('setTreatment — first-pass scene frames (#1867/#1938)', () => {mockReadJSONFile.mockResolvedValue([project]);getIngredient.mockResolvedValue(null);const treatment = { ...VALID_TREATMENT, script: 'A cat finds a hat.', scenes: Array.from({ length: 12 }, (_, order) => ({ ...VALID_TREATMENT.scenes[0], sceneId: `scene-${order}`, order, durationSeconds: 10 })) };- const plan = { steps: [{ stepId: 'lookup', toolName: 'catalog_searchIngredients', args: { query: 'Example' } }] };+ const plan = { steps: [{ stepId: 'render', toolName: 'media_enqueueVideoJob', args: { params: { prompt: 'Example forest', durationSeconds: 10 } } }] };await expect(setTreatment(project.id, treatment)).rejects.toMatchObject({ code: 'VIDEO_SOURCE_MISSING', status: 409 });await expect(setPlan(project.id, plan)).rejects.toMatchObject({ code: 'VIDEO_SOURCE_MISSING', status: 409 });getIngredient.mockRejectedValueOnce(new Error('Store unavailable'));diff --git a/server/services/creativeDirector/planAdvance.js b/server/services/creativeDirector/planAdvance.jsindex 28d80dbeb1..1045830e7d 100644--- a/server/services/creativeDirector/planAdvance.js+++ b/server/services/creativeDirector/planAdvance.js@@ -424,6 +424,7 @@ async function runPlanStep(project, step) {const targetAbility = project.directive?.constraints?.targetAbility;const dispatch = await dispatchCreativeTool(resolvedStep.toolName, resolvedStep.args, {projectId,+ ...(project.workspace === 'video' ? { videoStepId: step.stepId } : {}),...(targetAbility ? { targetAbility } : {}),}).catch((err) => ({ ok: false, threw: true, error: err.message }));@@ -491,9 +492,12 @@ async function settlePlanStepDispatch(projectId, step, runId, dispatch) {// times, then the project pauses with residuals for human review.async function handlePlanStepFailure(projectId, step) {const project = await getProject(projectId).catch(() => null);+ if (project?.workspace === 'video' && (project.videoExecution?.attempts || []).some(attempt => attempt.status === 'uncertain')) {+ return pausePlanWithResidual(projectId, 'A Video submission is uncertain. Reconcile its job before retrying.');+ }if (!project || project.status === 'paused' || project.status === 'failed') return;const rounds = project.plan?.replanRounds || 0;- if (rounds < MAX_REPLAN_ROUNDS && !inflightPlanner.has(projectId)) {+ if (rounds < (project.workspace === 'video' ? project.videoExecution?.limits?.maxReplans ?? 0 : MAX_REPLAN_ROUNDS) && !inflightPlanner.has(projectId)) {// MAX_REPLAN_ROUNDS alone cannot bound this path: `replanRounds` is bumped by// applyPlan, so a planner that never PATCHes leaves it at the same value and// this branch would re-fire forever (#4146). The empty-run gate is whatdiff --git a/server/services/creativeDirector/projectsLogic.js b/server/services/creativeDirector/projectsLogic.jsindex 23dccc1cf3..61b8b19121 100644--- a/server/services/creativeDirector/projectsLogic.js+++ b/server/services/creativeDirector/projectsLogic.js@@ -347,8 +347,8 @@ export function applyProjectPatch(project, patch) {if (patch.status && !PROJECT_STATUSES.includes(patch.status)) {throw new ServerError(`Invalid status: ${patch.status}`, { status: 400, code: 'VALIDATION_ERROR' });}- if ('videoDraft' in patch && (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 ('videoDraft' in patch && (project.workspace !== 'video' || !['draft', 'paused', 'failed'].includes(project.status))) {+ throw new ServerError('Pause Video production before editing production settings', { status: 409, code: 'INVALID_STATE' });}if ('workspace' in patch && patch.workspace !== project.workspace) {throw new ServerError('The project workspace cannot be changed', { status: 409, code: 'INVALID_STATE' });@@ -375,7 +375,7 @@ export function applyProjectPatch(project, patch) {return next;}-function validateVideoShot(project, scene, isFirst) {+export function validateVideoShot(project, scene, isFirst) {const backend = project.renderBackend?.video?.mode;const unsupported = [];if (isFirst && scene.useContinuationFromPrior) unsupported.push('continuation without a prior shot');@@ -536,6 +536,19 @@ export function applyPlan(project, planInput) {{ status: 400, code: 'VALIDATION_ERROR' },);}+ if (project.workspace === 'video' && parsed.data.steps.some(step => step.toolName !== 'media_enqueueVideoJob')) {+ throw new ServerError('Video production plans support bounded media_enqueueVideoJob steps. Use the saved reference and audio choices for other media.', { status: 400, code: 'VIDEO_PLAN_TOOL_UNSUPPORTED' });+ }+ if (project.workspace === 'video') {+ for (const step of parsed.data.steps) {+ const params = step.args?.params || {};+ if (!Number.isFinite(params.durationSeconds) || params.durationSeconds < 1 || params.durationSeconds > 10+ || Number(params.chunks || 1) !== 1 || Number(params.batchSize || 1) !== 1) {+ throw new ServerError('Each Video plan step must render one clip with durationSeconds between 1 and 10.', { status: 400, code: 'VIDEO_PLAN_CLIP_BOUNDS' });+ }+ validateVideoShot(project, { sceneId: step.stepId, prompt: String(params.prompt || ''), durationSeconds: params.durationSeconds }, false);+ }+ }const prevSteps = Array.isArray(project.plan?.steps) ? project.plan.steps : [];const prevById = new Map(prevSteps.map((s) => [s.stepId, s]));const invalidated = new Set();diff --git a/server/services/creativeDirector/recovery.js b/server/services/creativeDirector/recovery.jsindex 0cdbeea321..7ce0289ce4 100644--- a/server/services/creativeDirector/recovery.js+++ b/server/services/creativeDirector/recovery.js@@ -79,6 +79,13 @@ export async function recoverInFlightProjects() {let resumed = 0;const completedAt = new Date().toISOString();for (const project of needsCleanup) {+ if (project.workspace === 'video') {+ if (project.videoReplica || !project.videoOwnerInstanceId) continue;+ const { reconcileVideoExecution } = await import('./videoExecution.js');+ await retireRuns(project.id, { runs: inflightRuns(project), reason: 'Video production paused after restart', taskMetadata: { interruptedByRestart: 'true' } });+ await reconcileVideoExecution(project.id, { restarting: true });+ continue;+ }// CDO Phase 2 (#2184): a directive-driven project's plan steps stuck in// `running` lost their in-memory dispatch/job listener when the process// died — reset them to `pending` so the advance loop re-dispatches. (Theirdiff --git a/server/services/creativeDirector/sceneEvaluator.js b/server/services/creativeDirector/sceneEvaluator.jsindex 2a1df0e8c4..462016484b 100644--- a/server/services/creativeDirector/sceneEvaluator.js+++ b/server/services/creativeDirector/sceneEvaluator.js@@ -110,6 +110,13 @@ export function parseVisionVerdict(text) {* when nothing suitable is configured (caller falls back to the agent).*/export async function resolveVisionEvalTarget(project) {+ if (project?.workspace === 'video' && project.videoExecution?.choices) {+ const choice = project.videoExecution.choices.evaluation;+ if (choice.type !== 'api') return null;+ const provider = await getProviderById(choice.providerId);+ if (!provider || provider.type !== 'api' || provider.enabled === false) throw new Error('The reviewed evaluation provider is unavailable. Change Models or Settings and Resume.');+ return { provider, model: choice.model };+ }// An API provider is usable only if it exists and is enabled — vision runs// through the api-only chat path, so a CLI/TUI provider can't serve it.const usableApiProvider = async (id) => {@@ -210,6 +217,7 @@ export async function evaluateSceneWithVision(project, scene) {source: 'cd-scene-evaluate',screenshots: frames,timeout: VISION_EVAL_TIMEOUT_MS,+ ...(project.workspace === 'video' ? { allowFallback: false } : {}),});// Guard against a silent fallback to a non-API provider (which would drop the@@ -302,7 +310,7 @@ export async function applySceneVerdict(project, scene, verdict, llm = null, runreturn advance();}- if (retryCount < CD_MAX_SCENE_RETRIES) {+ if (retryCount < (project.workspace === 'video' ? project.videoExecution?.limits?.maxRetries ?? 0 : CD_MAX_SCENE_RETRIES)) {const patch = { status: 'pending', retryCount: retryCount + 1, evaluation };if (verdict.refinedPrompt && verdict.refinedPrompt.trim()) patch.prompt = verdict.refinedPrompt.trim();if (verdict.imageStrength !== undefined) patch.imageStrength = verdict.imageStrength;@@ -340,6 +348,29 @@ export async function dispatchSceneEvaluation(project, scene) {}inflightSceneEval.add(lockKey);try {+ if (project.workspace === 'video') {+ const { videoReviewAllowsDispatch } = await import('./videoReview.js');+ if (!await videoReviewAllowsDispatch(project.id, [])) return null;+ const { getProject } = await import('./local.js');+ const { effectiveVideoProject, reserveVideoAttempt, settleVideoAttempt, assertVideoAttemptDispatch, pauseVideoExecution } = await import('./videoExecution.js');+ project = effectiveVideoProject(await getProject(project.id));+ const currentScene = project.treatment?.scenes?.find(value => value.sceneId === scene.sceneId);+ if (!currentScene || (currentScene.workRevision || 0) !== (scene.workRevision || 0)) return null;+ if (project.videoExecution.choices.evaluation.type === 'agent') return enqueueEvaluateTask(project, currentScene);+ const attempt = await reserveVideoAttempt(project.id, { kind: 'evaluation', expectedProductionRevision: project.videoWorkRevision || 0, key: `evaluation:${scene.sceneId}`, sceneId: scene.sceneId, workRevision: scene.workRevision || 0 });+ if (!attempt) return null;+ try {+ await assertVideoAttemptDispatch(project.id, attempt.id);+ const result = await evaluateSceneWithVision(project, currentScene);+ if (!result.ok) throw new Error(result.reason || 'The reviewed vision evaluator is unavailable.');+ await settleVideoAttempt(project.id, attempt.id, { status: 'completed' });+ return await applySceneVerdict(project, currentScene, result.verdict, result.llm, result.runId);+ } catch (error) {+ await settleVideoAttempt(project.id, attempt.id, { status: 'failed' });+ if (error.code !== 'VIDEO_WORK_STALE') await pauseVideoExecution(project.id, `Evaluation stopped: ${error.message}. Review Models and Resume.`);+ return null;+ }+ }return await runSceneEvaluation(project, scene);} finally {inflightSceneEval.delete(lockKey);diff --git a/server/services/creativeDirector/sceneRunner.backend.test.js b/server/services/creativeDirector/sceneRunner.backend.test.jsindex f9357173bf..234ae99171 100644--- a/server/services/creativeDirector/sceneRunner.backend.test.js+++ b/server/services/creativeDirector/sceneRunner.backend.test.js@@ -16,6 +16,7 @@ import { describe, it, expect, beforeEach, vi } from 'vitest';vi.mock('../mediaJobQueue/index.js', () => ({enqueueJob: vi.fn(() => ({ jobId: 'job-1' })),+ getJob: vi.fn(() => null),mediaJobEvents: { on: vi.fn(), off: vi.fn() },}));vi.mock('../instances.js', () => ({ getInstanceId: vi.fn(async () => 'example-owner') }));@@ -32,7 +33,7 @@ vi.mock('../settings.js', () => ({}));vi.mock('./local.js', () => ({updateScene: vi.fn(async () => {}),- mutateVideoProject: vi.fn(async (_id, mutate) => mutate(await getProject())),+ mutateVideoProject: vi.fn(async (_id, mutate) => { const result = await mutate(await getProject()); if (!result.skipPersist) getProject.mockResolvedValue(result.project); return result; }),updateProject: vi.fn(async () => {}),getProject: vi.fn(async () => null),}));@@ -51,6 +52,7 @@ vi.mock('../../lib/fileUtils.js', async (importOriginal) => ({import { runSceneRender } from './sceneRunner.js';import { dispatchSceneEvaluation } from './sceneEvaluator.js';+import { videoConfigurationRevision } from './videoExecution.js';import { videoReviewStages } from '../../lib/creativeDirectorVideoReview.js';import { enqueueJob, mediaJobEvents } from '../mediaJobQueue/index.js';import { getSettings } from '../settings.js';@@ -244,16 +246,18 @@ describe('runSceneRender — Reactor and fal pins', () => {describe('Video production review boundary', () => {it('does not enqueue before approval and ignores a superseded render completion', async () => {- const shot = scene({ workRevision: 0 });+ const shot = scene({ workRevision: 0, status: 'pending' });const video = project({ workspace: 'video', status: 'rendering', videoOwnerInstanceId: 'example-owner',- videoExecution: { authorized: true }, videoDraft: { sources: [] },+ videoExecution: { id: 'example-execution', authorized: true, limits: { maxClips: 3, maxRetries: 1, maxAgentCalls: 10, maxReplans: 1, spendCapUsd: null }, choices: { video: { mode: 'local' }, evaluation: { type: 'agent' } } }, videoDraft: { sources: [] },treatment: { artifact: { revision: 1 }, script: 'Example script', scenes: [shot] } });+ video.videoExecution.inputRevision = videoConfigurationRevision(video);getProject.mockResolvedValue(video);getSettings.mockResolvedValue(LOCAL_READY);expect(await runSceneRender(video, shot)).toBeNull();expect(enqueueJob).not.toHaveBeenCalled();const checkpoint = videoReviewStages(video)[0];video.videoReview = { decisions: { [checkpoint.stage]: { action: 'approve', revision: checkpoint.revision } } };+ getProject.mockResolvedValue(video);expect(await runSceneRender(video, shot)).toBe('job-1');const completed = mediaJobEvents.on.mock.calls.find(([event]) => event === 'completed')[1];getProject.mockResolvedValue({ ...video, treatment: { ...video.treatment, scenes: [{ ...shot, workRevision: 1 }] } });diff --git a/server/services/creativeDirector/sceneRunner.js b/server/services/creativeDirector/sceneRunner.jsindex 28e8774936..3f8c0919e8 100644--- a/server/services/creativeDirector/sceneRunner.js+++ b/server/services/creativeDirector/sceneRunner.js@@ -67,6 +67,10 @@ export async function runSceneRender(project, scene) {if (project.workspace === 'video') {const { videoReviewAllowsDispatch } = await import('./videoReview.js');if (!await videoReviewAllowsDispatch(project.id, ['script-shot-plan', 'references'])) return null;+ const { effectiveVideoProject } = await import('./videoExecution.js');+ project = effectiveVideoProject(await getProject(project.id));+ scene = project.treatment?.scenes?.find(value => value.sceneId === scene.sceneId);+ if (!scene || scene.status !== 'pending') return null;}console.log(`🎞️ CD scene render starting: ${project.id} / ${scene.sceneId} (order ${scene.order}, attempt ${(scene.retryCount || 0) + 1}/${CD_MAX_SCENE_RETRIES + 1})`);@@ -240,11 +244,27 @@ export async function runSceneRender(project, scene) {// throw here leaves the scene stuck in 'rendering' forever with nothing to// advance the project. Settle it through the normal failure path instead.let jobId;+ let videoAttemptId;try {const params = videoBackendJobParams(settings, videoPin, sceneParams, { durationSeconds: scene.durationSeconds });- ({ jobId } = await enqueueUnattendedMediaJob({ kind: 'video', params, owner }));+ if (project.workspace === 'video') {+ const { enqueueVideoProductionJob } = await import('./videoExecution.js');+ const queued = await enqueueVideoProductionJob(project, { params, sceneId: scene.sceneId, workRevision: scene.workRevision || 0 });+ if (!queued) {+ await updateScene(project.id, scene.sceneId, { expectedWorkRevision: scene.workRevision || 0, status: 'pending' });+ return null;+ }+ jobId = queued.jobId;+ videoAttemptId = queued.attemptId;+ await updateScene(project.id, scene.sceneId, { expectedWorkRevision: scene.workRevision || 0, renderedJobId: jobId });+ } else ({ jobId } = await enqueueUnattendedMediaJob({ kind: 'video', params, owner }));} catch (error) {console.error(`❌ CD scene ${scene.sceneId}: could not queue the render: ${error.message}`);+ if (project.workspace === 'video') {+ const { pauseVideoExecution } = await import('./videoExecution.js');+ await pauseVideoExecution(project.id, error.message);+ return null;+ }await handleRenderFailed(project.id, scene.sceneId, error.message || 'could not queue the render', {workRevision: project.workspace === 'video' ? scene.workRevision || 0 : undefined,retry: error.code !== 'VIDEO_BACKEND_INPUT_UNSUPPORTED' && error.code !== 'VIDEO_BACKEND_UNSUPPORTED',@@ -258,27 +278,34 @@ export async function runSceneRender(project, scene) {// cancelJob handlers — we MUST listen for all three or a user-initiated// cancel via the Render Queue UI would leave the scene stuck in// `rendering` forever and leak listeners.+ const settleReceipt = (status) => videoAttemptId+ ? import('./videoExecution.js').then(({ settleVideoAttempt }) => settleVideoAttempt(project.id, videoAttemptId, { status }))+ : Promise.resolve();+ let settled = false;const onCompleted = (job) => {- if (job.id !== jobId) return;+ if (settled || job.id !== jobId) return;+ settled = true;cleanup();- handleRenderCompleted(project.id, scene.sceneId, jobId, { continuationFellBack, workRevision: project.workspace === 'video' ? scene.workRevision || 0 : undefined })+ settleReceipt('completed').then(() => handleRenderCompleted(project.id, scene.sceneId, jobId, { continuationFellBack, workRevision: project.workspace === 'video' ? scene.workRevision || 0 : undefined })).catch(error => console.error(`❌ CD render completion failed: ${error.message}`));};const onFailed = (job) => {- if (job.id !== jobId) return;+ if (settled || job.id !== jobId) return;+ settled = true;cleanup();- handleRenderFailed(project.id, scene.sceneId, job.error || 'render failed', { workRevision: project.workspace === 'video' ? scene.workRevision || 0 : undefined })+ settleReceipt(/timeout|timed out|interrupted/i.test(job.error || '') ? 'uncertain' : 'failed').then(() => handleRenderFailed(project.id, scene.sceneId, job.error || 'render failed', { workRevision: project.workspace === 'video' ? scene.workRevision || 0 : undefined })).catch(error => console.error(`❌ CD render failure handling failed: ${error.message}`));};const onCanceled = (job) => {- if (job.id !== jobId) return;+ if (settled || job.id !== jobId) return;+ settled = true;cleanup();// Treat user-initiated cancel as a terminal stop for this scene — do// NOT route through handleRenderFailed (which would retry up to// CD_MAX_SCENE_RETRIES); the user explicitly stopped this. Mark the scene// failed and let the completionHook flag the project so the user can// resume from the UI.- handleRenderCanceled(project.id, scene.sceneId, project.workspace === 'video' ? scene.workRevision || 0 : undefined)+ settleReceipt(job.params?.videoProduction?.submissionUncertain ? 'uncertain' : 'canceled').then(() => handleRenderCanceled(project.id, scene.sceneId, project.workspace === 'video' ? scene.workRevision || 0 : undefined)).catch(error => console.error(`❌ CD render cancellation handling failed: ${error.message}`));};function cleanup() {@@ -289,6 +316,13 @@ export async function runSceneRender(project, scene) {mediaJobEvents.on('completed', onCompleted);mediaJobEvents.on('failed', onFailed);mediaJobEvents.on('canceled', onCanceled);+ if (project.workspace === 'video') {+ const { getJob } = await import('../mediaJobQueue/index.js');+ const settled = getJob(jobId);+ if (settled?.status === 'completed') onCompleted(settled);+ if (settled?.status === 'failed') onFailed(settled);+ if (settled?.status === 'canceled') onCanceled(settled);+ }return jobId;}@@ -453,7 +487,12 @@ 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 (retry && nextRetry <= CD_MAX_SCENE_RETRIES) {+ if (fresh.workspace === 'video' && /quota|credit|balance|429|timeout|timed out|interrupted/i.test(errorMsg)) {+ const { pauseVideoExecution } = await import('./videoExecution.js');+ await pauseVideoExecution(projectId, `Render blocked: ${errorMsg}. Review the provider and saved job before Resume.`);+ return;+ }+ if (retry && nextRetry <= (fresh.workspace === 'video' ? fresh.videoExecution?.limits?.maxRetries ?? 0 : CD_MAX_SCENE_RETRIES)) {console.log(`🔁 CD scene ${sceneId} render failed (${errorMsg}) — retry ${nextRetry}/${CD_MAX_SCENE_RETRIES}`);await updateScene(projectId, sceneId, { ...(workRevision === undefined ? {} : { expectedWorkRevision: workRevision }), status: 'pending', retryCount: nextRetry });const updated = { ...scene, retryCount: nextRetry };diff --git a/server/services/creativeDirector/stopProject.js b/server/services/creativeDirector/stopProject.jsindex f27075f373..d0bda63225 100644--- a/server/services/creativeDirector/stopProject.js+++ b/server/services/creativeDirector/stopProject.js@@ -167,12 +167,16 @@ export async function stopProject(projectId, { reason = 'Stopped', project: prer// query per project just to rediscover what it already holds.const project = preread || await getProject(projectId).catch(() => null);if (!project) return { projectId, stopped: false, skipped: 'missing', runs: 0, tasks: 0, agents: 0, jobs: 0 };- if (PROJECT_TERMINAL_STATUSES.has(project.status)) {+ if (PROJECT_TERMINAL_STATUSES.has(project.status) && (project.workspace !== 'video' || project.status === 'complete')) {return { projectId, stopped: false, skipped: 'terminal', runs: 0, tasks: 0, agents: 0, jobs: 0 };}// 1. Park first — a settle event racing us must find `paused` and bail.- await updateProject(projectId, { status: 'paused', failureReason: reason })+ if (project.workspace === 'video') {+ const { pauseVideoExecution } = await import('./videoExecution.js');+ // If the durable stop fails, do not pretend subsequent teardown is safe.+ await pauseVideoExecution(projectId, reason, { invalidate: true });+ } else await updateProject(projectId, { status: 'paused', failureReason: reason }).catch((e) => console.error(`❌ CD stop ${projectId}: park failed: ${e.message}`));const retired = await retireRuns(projectId, { runs: inflightRuns(project), reason });@@ -192,8 +196,8 @@ export async function stopProject(projectId, { reason = 'Stopped', project: prer}for (const scene of (project.treatment?.scenes || [])) {if (scene.status !== 'rendering' && scene.status !== 'evaluating') continue;- if (scene.renderedJobId) continue;- await updateScene(projectId, scene.sceneId, { status: 'pending' })+ if (scene.renderedJobId && (project.workspace !== 'video' || scene.status === 'evaluating')) continue;+ await updateScene(projectId, scene.sceneId, { status: 'pending', ...(project.workspace === 'video' ? { renderedJobId: null } : {}) }).catch((e) => console.log(`⚠️ CD stop ${projectId}: reset scene ${scene.sceneId} failed: ${e.message}`));}@@ -206,6 +210,12 @@ 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),+ } }, result: true }));+ }console.log(`🛑 CD project ${projectId} stopped: ${reason} (${retired.runs} run(s), ${retired.tasks} task(s), ${retired.agents} agent(s), ${jobs} job(s))`);return { projectId, stopped: true, ...retired, jobs };}diff --git a/server/services/creativeDirector/stopProject.test.js b/server/services/creativeDirector/stopProject.test.jsindex a12e6e5cab..618b0d6118 100644--- a/server/services/creativeDirector/stopProject.test.js+++ b/server/services/creativeDirector/stopProject.test.js@@ -7,12 +7,15 @@ const updateSceneMock = vi.fn(async () => ({}));const updatePlanStepMock = vi.fn(async () => ({}));vi.mock('./local.js', () => ({getProject: (...a) => getProjectMock(...a),+ mutateVideoProject: async (_id, mutate) => { const result = mutate(await getProjectMock(_id)); getProjectMock.mockResolvedValue(result.project); return result; },updateProject: (...a) => updateProjectMock(...a),updateRun: (...a) => updateRunMock(...a),updateScene: (...a) => updateSceneMock(...a),updatePlanStep: (...a) => updatePlanStepMock(...a),}));+vi.mock('../instances.js', () => ({ getInstanceId: async () => 'example-owner' }));+const getActiveAgentsMock = vi.fn(() => []);const killAgentMock = vi.fn(async () => ({ success: true }));vi.mock('../agentManagement.js', () => ({@@ -235,3 +238,22 @@ describe('stopProject', () => {expect(updateRunMock).toHaveBeenCalledWith('cd-1', 'r1', expect.objectContaining({ status: 'failed' }));});});++it('revokes Video authorization before canceling jobs and retains completed clips', async () => {+ getProjectMock.mockResolvedValue(project({ workspace: 'video', videoOwnerInstanceId: 'example-owner', videoWorkRevision: 2,+ videoExecution: { authorized: true, attempts: [{ id: 'agent-attempt', kind: 'treatment', status: 'running' }] },+ treatment: { scenes: [{ sceneId: 'pending-shot', status: 'rendering', renderedJobId: 'pending-job', workRevision: 3 }, { sceneId: 'done-shot', status: 'evaluating', renderedJobId: 'done-job', workRevision: 1 }] },+ }));+ listJobsMock.mockReturnValue([{ id: 'pending-job', status: 'running', owner: 'cd:cd-1:pending-shot' }, { id: 'unrelated-job', status: 'running', owner: 'other' }]);+ cancelJobMock.mockImplementationOnce(async () => {+ const saved = await getProjectMock('cd-1');+ expect(saved.status).toBe('paused');+ expect(saved.videoExecution.authorized).toBe(false);+ expect(saved.videoWorkRevision).toBe(3);+ expect(saved.treatment.scenes[0].workRevision).toBe(4);+ });+ await stopProject('cd-1');+ expect(cancelJobMock).toHaveBeenCalledExactlyOnceWith('pending-job');+ expect(updateSceneMock).toHaveBeenCalledExactlyOnceWith('cd-1', 'pending-shot', { status: 'pending', renderedJobId: null });+ expect((await getProjectMock('cd-1')).videoExecution.attempts[0].status).toBe('failed');+});diff --git a/server/services/creativeDirector/videoExecution.js b/server/services/creativeDirector/videoExecution.jsnew file mode 100644index 0000000000..da8fd8e53c--- /dev/null+++ b/server/services/creativeDirector/videoExecution.js@@ -0,0 +1,280 @@+/** Explicit Video authorization and bounded receipts on the existing project store. */+import { randomUUID } from 'crypto';+import { canonicalSnapshotChecksum } from '../../lib/snapshotChecksum.js';+import { ServerError } from '../../lib/errorHandler.js';+import { creativeDirectorVideoLimitsSchema } from '../../lib/creativeDirectorValidation.js';+import { assertVideoOwner } from '../../lib/creativeDirectorVideoReview.js';++const ACTIVE = new Set(['planning', 'rendering', 'stitching']);+const LIVE_ATTEMPTS = new Set(['submitting', 'queued', 'running', 'uncertain']);+const now = () => new Date().toISOString();++export function videoConfigurationRevision(project) {+ return canonicalSnapshotChecksum(Object.fromEntries(['userStory', 'styleSpec', 'cast', 'targetDurationSeconds',+ 'aspectRatio', 'quality', 'modelId', 'renderBackend', 'modelOverrides', 'videoDraft', 'startingImageFile',+ 'disableAudio', 'autoAcceptScenes', 'directive'].map(key => [key, project[key] ?? null])));+}++/** Frozen choices contain identifiers only; credentials always stay in Settings. */+export function effectiveVideoProject(project) {+ const choices = project.videoExecution?.choices;+ if (project.workspace !== 'video' || !choices) return project;+ return { ...project, renderBackend: { ...project.renderBackend, video: choices.video },+ modelId: choices.video.modelId || project.modelId,+ modelOverrides: { ...project.modelOverrides, treatment: choices.treatment, plan: choices.plan,+ ...(choices.evaluation.type === 'api' ? { evaluation: choices.evaluation } : {}) } };+}++async function resolveChoices(project) {+ project = { ...project, videoExecution: null };+ const { getSettings } = await import('../settings.js');+ const { resolveVideoBackendPin } = await import('../videoGen/backendPin.js');+ const { getStageAssignment } = await import('./agentBridge.js');+ const { resolveAgentProviderAndModel } = await import('../agentProviderResolution.js');+ const { resolveVisionEvalTarget } = await import('./sceneEvaluator.js');+ const settings = await getSettings();+ const pin = resolveVideoBackendPin(project, settings);+ const { hasConfiguredMediaRoute } = await import('../federatedMedia/defaultRouting.js');+ if (await hasConfiguredMediaRoute('video')) throw new ServerError('A standing video route would change the reviewed backend. Disable it in Settings before Start.', { status: 409, code: 'VIDEO_ROUTE_CHANGED' });+ const video = { mode: pin.mode, modelId: pin.modelId || (pin.mode === 'local' ? project.modelId : null) || null };+ if (pin.mode === 'reactor') {+ const { REACTOR_MODEL_ID } = await import('../videoGen/reactor.js');+ video.modelDescription = REACTOR_MODEL_ID;+ }+ if (pin.mode === 'fal' && !pin.modelId) {+ const { FAL_DEFAULT_TEXT_MODEL, FAL_DEFAULT_IMAGE_MODEL } = await import('../videoGen/fal.js');+ video.modelDescription = `${FAL_DEFAULT_TEXT_MODEL} (text) / ${FAL_DEFAULT_IMAGE_MODEL} (image)`;+ }+ if (pin.mode === 'local') {+ const { hasConfiguredMediaRoute } = await import('../federatedMedia/defaultRouting.js');+ // A strict local choice must not silently become a different peer/backend.+ if (await hasConfiguredMediaRoute('video')) throw new ServerError('This install routes video to a peer. Disable the standing video route or use a production backend that is configured locally before Start.', { status: 409, code: 'VIDEO_ROUTE_CHANGED' });+ if (!settings.imageGen?.local?.pythonPath) throw new ServerError('Configure the local video runtime in Settings, or select a cloud backend.', { status: 409, code: 'VIDEO_BACKEND_UNAVAILABLE' });+ const { resolveVideoModelSelection } = await import('../videoGen/modelSelection.js');+ const { isHardwareCompatible, hardwareUnavailableReason } = await import('../../lib/systemCapabilities.js');+ const selected = await resolveVideoModelSelection(video.modelId || undefined);+ if (!selected.model) throw new ServerError('Select an installed local video model in Settings.', { status: 409, code: 'VIDEO_BACKEND_UNAVAILABLE' });+ if (!isHardwareCompatible(selected.model.hardwareCompatibility)) throw new ServerError(hardwareUnavailableReason('Selected video model', selected.model.hardwareCompatibility), { status: 409, code: 'MODEL_HARDWARE_UNAVAILABLE' });+ video.modelId = selected.modelId;+ }+ const agentChoice = async kind => {+ const assignment = await getStageAssignment(kind, project);+ const resolved = await resolveAgentProviderAndModel({ description: 'Video production planning', metadata: assignment });+ if (!resolved.ok || (assignment.providerId && assignment.providerId !== resolved.provider?.id)) {+ throw new ServerError(resolved.error || `The selected ${kind} provider is unavailable. Change Models or Settings before Start.`, { status: 409, code: 'VIDEO_AGENT_UNAVAILABLE' });+ }+ return { type: 'agent', providerId: resolved.provider.id, model: resolved.selectedModel, ...(assignment.effort ? { effort: assignment.effort } : {}) };+ };+ const treatment = await agentChoice('treatment');+ const plan = await agentChoice('plan');+ const vision = await resolveVisionEvalTarget(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 };+}++export async function getVideoExecutionPreview(projectId) {+ const { getProject } = await import('./local.js');+ const { getInstanceId } = await import('../instances.js');+ const project = await getProject(projectId);+ if (!project) throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });+ const owner = await getInstanceId();+ const canStart = project.workspace === 'video' && !project.videoReplica && project.videoOwnerInstanceId === owner;+ const blockers = [];+ if (!canStart) blockers.push('Start is available only on the owning install.');+ if (!project.userStory?.trim()) blockers.push('Add a production brief before Start.');+ const choices = canStart ? await resolveChoices(project).catch(error => { blockers.push(error.message); return null; }) : null;+ const { assertVideoSourcesAvailable } = await import('./videoSources.js');+ if (canStart) await assertVideoSourcesAvailable(project).catch(error => blockers.push(error.message));+ return { canStart: canStart && blockers.length === 0, blockers, choices,+ inputRevision: videoConfigurationRevision(project),+ configurationRevision: canonicalSnapshotChecksum({ input: videoConfigurationRevision(project), choices }),+ limits: project.videoExecution?.limits || creativeDirectorVideoLimitsSchema.parse({}),+ 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.' };+}++async function ownedMutation(projectId, mutate) {+ const { mutateVideoProject } = await import('./local.js');+ const { getInstanceId } = await import('../instances.js');+ const owner = await getInstanceId();+ return mutateVideoProject(projectId, project => { assertVideoOwner(project, owner); return mutate(project); });+}++export async function pauseVideoExecution(projectId, reason, { invalidate = false } = {}) {+ return ownedMutation(projectId, project => ({ project: { ...project, status: 'paused', failureReason: reason || null,+ ...(invalidate ? { videoWorkRevision: (project.videoWorkRevision || 0) + 1,+ treatment: project.treatment ? { ...project.treatment, scenes: project.treatment.scenes.map(scene => ({ ...scene, workRevision: (scene.workRevision || 0) + 1 })) } : project.treatment } : {}),+ videoExecution: { ...project.videoExecution, ...(invalidate ? { authorized: false } : {}), blocker: reason || null }, updatedAt: now(),+ }, result: true }));+}++/** Reload queue receipts before deciding whether an explicit resume may submit. No provider call. */+export async function reconcileVideoExecution(projectId, { restarting = false, retryAttemptIds = [] } = {}) {+ const { listJobs } = await import('../mediaJobQueue/index.js');+ const jobs = listJobs();+ const { getProject } = await import('./local.js');+ 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);+ if (liveAgents.length) {+ const { getTaskById } = await import('../cos.js');+ for (const attempt of liveAgents) tasks.set(attempt.taskId, await getTaskById(attempt.taskId));+ }+ }+ 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;+ 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 };+ const uncertain = !job || job.params?.videoProduction?.submissionUncertain === true+ || (job.params?.videoProduction?.submissionUncertain !== false && /interrupted|restart|timeout|timed out/i.test(job.error || ''));+ 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 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?.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;+ });+ const steps = project.plan?.steps?.map(step => {+ const receipt = [...attempts].reverse().find(attempt => attempt.stepId === step.stepId && attempt.productionRevision === (project.videoWorkRevision || 0));+ if (receipt?.status === 'completed' && receipt.jobId) return { ...step, status: 'done', result: { jobId: receipt.jobId } };+ if (receipt?.status === 'failed' && ['running', 'failed', 'blocked'].includes(step.status)) return { ...step, status: 'pending' };+ return step;+ });+ const blocked = attempts.some(attempt => attempt.status === 'uncertain');+ return { project: { ...project, runs, ...(steps ? { plan: { ...project.plan, steps } } : {}), ...(scenes ? { treatment: { ...project.treatment, scenes } } : {}),+ ...(restarting || blocked ? { status: 'paused' } : {}),+ videoExecution: { ...project.videoExecution, attempts,+ ...(restarting ? { authorized: false } : {}),+ blocker: blocked ? 'A previous submission is uncertain. Reconcile its job or explicitly authorize retry; it may charge again.' : restarting ? 'Restart paused production. Review the saved jobs and Resume to continue.' : null,+ }, updatedAt: now() }, result: { uncertain: blocked, live: attempts.some(attempt => ['queued', 'running', 'submitting'].includes(attempt.status)) } };+ });+}++export async function startVideoExecution(projectId, input) {+ const preview = await getVideoExecutionPreview(projectId);+ if (preview.configurationRevision !== input.configurationRevision) throw new ServerError('Production choices changed. Refresh before Start.', { status: 409, code: 'VIDEO_START_STALE' });+ if (!preview.canStart) throw new ServerError(preview.blockers.join(' '), { status: 409, code: 'VIDEO_START_BLOCKED' });+ const limits = creativeDirectorVideoLimitsSchema.parse(input.limits);+ if (limits.spendCapUsd !== null && preview.choices.costEstimateUsd === null) throw new ServerError('This provider has no enforceable dollar estimate. Remove the dollar cap to use clip/call bounds, or choose a provider with bounded pricing.', { status: 409, code: 'VIDEO_COST_UNKNOWN' });+ const reconciled = await reconcileVideoExecution(projectId, { retryAttemptIds: input.retryAttemptIds });+ if (reconciled.result.uncertain) throw new ServerError(reconciled.project.videoExecution.blocker, { status: 409, code: 'VIDEO_SUBMISSION_UNCERTAIN' });+ const { project, result } = await ownedMutation(projectId, current => {+ if (current.videoExecution?.authorized && ACTIVE.has(current.status)) return { project: current, result: false, skipPersist: true };+ if (videoConfigurationRevision(current) !== preview.inputRevision) throw new ServerError('Production changed during Start. Refresh and try again.', { status: 409, code: 'VIDEO_START_STALE' });+ const execution = current.videoExecution || {};+ return { project: { ...current, status: current.treatment ? 'rendering' : 'planning', failureReason: null,+ videoExecution: { ...execution, id: execution.id || randomUUID(), authorized: true, authorizedAt: now(),+ inputRevision: videoConfigurationRevision(current), configurationRevision: input.configurationRevision,+ choices: preview.choices, limits, attempts: execution.attempts || [], blocker: null }, updatedAt: now(),+ }, result: true };+ });+ if (result) {+ const { startCreativeDirectorProject } = await import('./completionHook.js');+ startCreativeDirectorProject(projectId).catch(error => pauseVideoExecution(projectId, error.message).catch(() => {}));+ }+ return project;+}++export async function reserveVideoAttempt(projectId, details) {+ const { result } = await ownedMutation(projectId, project => {+ const execution = project.videoExecution;+ if (!execution?.authorized || !ACTIVE.has(project.status)) return { project, result: null, skipPersist: true };+ if (details.expectedProductionRevision !== undefined && details.expectedProductionRevision !== (project.videoWorkRevision || 0)) return { project, result: null, skipPersist: true };+ if (details.sceneId && details.workRevision !== undefined && details.workRevision !== (project.treatment?.scenes?.find(scene => scene.sceneId === details.sceneId)?.workRevision || 0)) return { project, result: null, skipPersist: true };+ const attempts = execution.attempts || [];+ let blocker = null;+ if (execution.inputRevision !== videoConfigurationRevision(project)) blocker = 'Production settings changed. Review the new choices and Resume.';+ 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 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 (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 };+ const attempt = { ...details, id: randomUUID(), executionId: execution.id, productionRevision: project.videoWorkRevision || 0, status: 'submitting', at: now() };+ return { project: { ...project, videoExecution: { ...execution, attempts: [...attempts, attempt] }, updatedAt: now() }, result: attempt };+ });+ return result;+}++export async function settleVideoAttempt(projectId, attemptId, patch) {+ return ownedMutation(projectId, project => ({ project: { ...project,+ videoExecution: { ...project.videoExecution, attempts: (project.videoExecution?.attempts || []).map(attempt => attempt.id === attemptId ? { ...attempt, ...patch, status: (patch.status === 'queued' && ['running', 'completed', 'failed', 'canceled'].includes(attempt.status)) || (attempt.status === 'completed' && patch.status !== 'completed') ? attempt.status : patch.status || attempt.status } : attempt) }, updatedAt: now(),+ }, result: true }));+}++/** Checked at the worker boundary, after the queue wait and immediately before provider work. */+export async function assertVideoAttemptDispatch(projectId, attemptId, { jobId } = {}) {+ const { getProject } = await import('./local.js');+ const { getInstanceId } = await import('../instances.js');+ const project = await getProject(projectId);+ assertVideoOwner(project, await getInstanceId());+ const execution = project.videoExecution;+ const attempt = execution?.attempts?.find(value => value.id === attemptId);+ if (!execution?.authorized || !ACTIVE.has(project.status) || !attempt || !LIVE_ATTEMPTS.has(attempt.status)+ || execution.inputRevision !== videoConfigurationRevision(project) || attempt.productionRevision !== (project.videoWorkRevision || 0)) throw new ServerError('Video production is paused or changed. Review and Resume before dispatch.', { status: 409, code: 'VIDEO_DISPATCH_BLOCKED' });+ const { assertVideoSourcesAvailable } = await import('./videoSources.js');+ await assertVideoSourcesAvailable(project);+ const effective = effectiveVideoProject(project);+ const { getSettings } = await import('../settings.js');+ const { resolveVideoBackendPin } = await import('../videoGen/backendPin.js');+ resolveVideoBackendPin(effective, await getSettings());+ 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' });+ {+ await ownedMutation(projectId, current => {+ const receipt = current.videoExecution?.attempts?.find(value => value.id === attemptId);+ if (!current.videoExecution?.authorized || !ACTIVE.has(current.status) || !receipt || !LIVE_ATTEMPTS.has(receipt.status)+ || (jobId && receipt.jobId && receipt.jobId !== jobId) || receipt.productionRevision !== (current.videoWorkRevision || 0)+ || current.videoExecution.inputRevision !== videoConfigurationRevision(current)+ || (receipt.sceneId && receipt.workRevision !== undefined && receipt.workRevision !== (current.treatment?.scenes?.find(scene => scene.sceneId === receipt.sceneId)?.workRevision || 0))) {+ throw new ServerError('This queue job has no current Video authorization. Resume through the production.', { status: 409, code: 'VIDEO_DISPATCH_BLOCKED' });+ }+ if (!jobId) return { project: current, result: true, skipPersist: true };+ return { project: { ...current, videoExecution: { ...current.videoExecution, attempts: current.videoExecution.attempts.map(value => value.id === attemptId ? { ...value, jobId, status: 'running' } : value) } }, result: true };+ });+ }+ return effective;+}++export async function enqueueVideoProductionJob(project, { kind = 'video', params, sceneId, stepId, workRevision }) {+ if (kind !== 'video') throw new ServerError('Video plans currently render bounded video clips. Use attached references and the saved audio choice for other media.', { status: 409, code: 'VIDEO_PLAN_TOOL_UNSUPPORTED' });+ const seconds = Number(params.mode === 'reactor' ? params.seconds+ : ['fal', 'grok'].includes(params.mode) ? params.duration+ : params.numFrames / params.fps);+ if (!Number.isFinite(seconds) || seconds < 1 || seconds > 10.1 || Number(params.chunks || 1) !== 1 || Number(params.batchSize || 1) !== 1) {+ throw new ServerError('A Video submission must contain one clip of at most 10 seconds.', { status: 409, code: 'VIDEO_PLAN_CLIP_BOUNDS' });+ }+ const { validateVideoShot } = await import('./projectsLogic.js');+ validateVideoShot(project, { sceneId: sceneId || stepId, prompt: String(params.prompt || ''), durationSeconds: seconds }, false);+ const { hasConfiguredMediaRoute, enqueueUnattendedMediaJob } = await import('../federatedMedia/defaultRouting.js');+ if (await hasConfiguredMediaRoute(kind)) throw new ServerError('A standing peer route would change the reviewed video backend. Change Settings before Resume.', { status: 409, code: 'VIDEO_ROUTE_CHANGED' });+ const attempt = await reserveVideoAttempt(project.id, { kind: 'clip', key: sceneId ? `scene:${sceneId}` : `step:${stepId}`, sceneId, stepId, workRevision, expectedProductionRevision: project.videoWorkRevision || 0 });+ if (!attempt) return null;+ const marker = { projectId: project.id, attemptId: attempt.id, executionId: attempt.executionId };+ try {+ await assertVideoAttemptDispatch(project.id, attempt.id);+ const result = await enqueueUnattendedMediaJob({ kind, params: { ...params, videoProduction: marker },+ owner: sceneId ? `cd:${project.id}:${sceneId}` : `creative-director:${project.id}` });+ await settleVideoAttempt(project.id, attempt.id, { status: 'queued', jobId: result.jobId });+ return { ...result, attemptId: attempt.id };+ } catch (error) {+ const uncertain = error.code !== 'VIDEO_DISPATCH_BLOCKED';+ await settleVideoAttempt(project.id, attempt.id, { status: uncertain ? 'uncertain' : 'failed' });+ await pauseVideoExecution(project.id, uncertain ? 'Submission could not be confirmed. Reconcile the queue or explicitly authorize retry; it may charge again.' : error.message);+ throw new ServerError(error.message, { status: 409, code: uncertain ? 'VIDEO_SUBMISSION_UNCERTAIN' : error.code });+ }+}diff --git a/server/services/creativeDirector/videoExecution.test.js b/server/services/creativeDirector/videoExecution.test.jsnew file mode 100644index 0000000000..9e69706949--- /dev/null+++ b/server/services/creativeDirector/videoExecution.test.js@@ -0,0 +1,135 @@+import { beforeEach, expect, it, vi } from 'vitest';+const state = vi.hoisted(() => ({ project: null, jobs: [], settings: null }));+vi.mock('./local.js', () => ({+ getProject: vi.fn(async () => structuredClone(state.project)),+ mutateVideoProject: vi.fn(async (_id, mutate) => {+ const output = await mutate(structuredClone(state.project));+ if (!output.skipPersist) state.project = output.project;+ return output;+ }),+}));+vi.mock('../instances.js', () => ({ getInstanceId: vi.fn(async () => 'example-owner') }));+vi.mock('../settings.js', () => ({ getSettings: vi.fn(async () => state.settings) }));+vi.mock('./videoSources.js', () => ({ assertVideoSourcesAvailable: vi.fn(async () => {}) }));+vi.mock('./agentBridge.js', () => ({ getStageAssignment: vi.fn(async () => ({ providerId: 'example-agent', provider: 'example-agent', model: 'example-model' })) }));+vi.mock('../agentProviderResolution.js', () => ({ resolveAgentProviderAndModel: vi.fn(async () => ({ ok: true, provider: { id: 'example-agent' }, selectedModel: 'example-model' })) }));+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('../federatedMedia/defaultRouting.js', () => ({+ hasConfiguredMediaRoute: vi.fn(async () => false),+ enqueueUnattendedMediaJob: vi.fn(async job => {+ const id = `example-job-${state.jobs.length + 1}`;+ state.jobs.push({ ...job, id, status: 'queued' });+ return { jobId: id };+ }),+}));+vi.mock('./completionHook.js', () => ({ startCreativeDirectorProject: vi.fn(async () => {}) }));+const { startCreativeDirectorProject } = await import('./completionHook.js');+const { enqueueUnattendedMediaJob, hasConfiguredMediaRoute } = await import('../federatedMedia/defaultRouting.js');+const { resolveVideoModelSelection } = await import('../videoGen/modelSelection.js');+import { getVideoExecutionPreview, startVideoExecution, enqueueVideoProductionJob, pauseVideoExecution,+ reconcileVideoExecution, reserveVideoAttempt, settleVideoAttempt, assertVideoAttemptDispatch, videoConfigurationRevision } from './videoExecution.js';++beforeEach(() => {+ vi.clearAllMocks();+ state.jobs = [];+ 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: {} },+ renderBackend: { video: { mode: 'reactor' } }, aspectRatio: '16:9', targetDurationSeconds: 10,+ treatment: { scenes: [{ sceneId: 'opening', order: 0, status: 'pending', workRevision: 0 }] } };+ hasConfiguredMediaRoute.mockResolvedValue(false);+});+const startInput = async (limits = {}, extra = {}) => ({ configurationRevision: (await getVideoExecutionPreview('example-video')).configurationRevision, limits, ...extra });+const enqueue = () => enqueueVideoProductionJob(state.project, { params: { mode: 'reactor', prompt: 'Example landscape', seconds: 10 }, sceneId: 'opening', workRevision: state.project.treatment.scenes[0].workRevision });++it('previews cloud choices without local hardware or paid calls and makes Start idempotent', async () => {+ const preview = await getVideoExecutionPreview('example-video');+ expect(preview).toMatchObject({ canStart: true, choices: { video: { mode: 'reactor', modelDescription: 'fast-h3' }, costEstimateUsd: null } });+ expect(resolveVideoModelSelection).not.toHaveBeenCalled();+ expect(enqueueUnattendedMediaJob).not.toHaveBeenCalled();+ expect(startCreativeDirectorProject).not.toHaveBeenCalled();+ const input = await startInput({ maxClips: 2, maxRetries: 0 });+ await startVideoExecution('example-video', input);+ await startVideoExecution('example-video', input);+ expect(startCreativeDirectorProject).toHaveBeenCalledTimes(1);+ expect(state.project.videoExecution).toMatchObject({ authorized: true, limits: { maxClips: 2, maxRetries: 0 }, inputRevision: videoConfigurationRevision(state.project) });+});++it('refuses stale choices, unavailable pinned credentials and unenforceable dollar caps', async () => {+ const input = await startInput();+ state.project.userStory = 'A changed brief.';+ await expect(startVideoExecution('example-video', input)).rejects.toMatchObject({ code: 'VIDEO_START_STALE' });+ await expect(startVideoExecution('example-video', await startInput({ spendCapUsd: 5 }))).rejects.toMatchObject({ code: 'VIDEO_COST_UNKNOWN' });+ state.settings = {};+ vi.stubEnv('REACTOR_API_KEY', '');+ expect(await getVideoExecutionPreview('example-video')).toMatchObject({ canStart: false, choices: null });+ vi.unstubAllEnvs();+ expect(startCreativeDirectorProject).not.toHaveBeenCalled();+});++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();+ expect(state.project.videoExecution.attempts[0]).toMatchObject({ id: queued.attemptId, jobId: queued.jobId, status: 'queued' });+ expect(await enqueue()).toBeNull();+ await assertVideoAttemptDispatch('example-video', queued.attemptId, { jobId: queued.jobId });+ await expect(assertVideoAttemptDispatch('example-video', queued.attemptId, { jobId: 'another-job' })).rejects.toMatchObject({ code: 'VIDEO_DISPATCH_BLOCKED' });+ await pauseVideoExecution('example-video', 'Paused');+ await expect(assertVideoAttemptDispatch('example-video', queued.attemptId, { jobId: queued.jobId })).rejects.toMatchObject({ code: 'VIDEO_DISPATCH_BLOCKED' });+ expect(await enqueue()).toBeNull();+ state.jobs[0].status = 'failed';+ state.jobs[0].error = 'Render failed';+ await startVideoExecution('example-video', await startInput({ maxClips: 2, maxRetries: 0 }));+ expect(await enqueue()).toBeNull();+ expect(state.project.videoExecution.blocker).toMatch(/retry limit/);+ expect(enqueueUnattendedMediaJob).toHaveBeenCalledTimes(1);+});++it('keeps uncertain submissions inert until the user explicitly acknowledges a possible duplicate charge', async () => {+ await startVideoExecution('example-video', await startInput());+ enqueueUnattendedMediaJob.mockRejectedValueOnce(new Error('connection lost after submit'));+ await expect(enqueue()).rejects.toMatchObject({ code: 'VIDEO_SUBMISSION_UNCERTAIN' });+ const attempt = state.project.videoExecution.attempts[0];+ expect(attempt.status).toBe('uncertain');+ expect(state.project.status).toBe('paused');+ await expect(startVideoExecution('example-video', await startInput())).rejects.toMatchObject({ code: 'VIDEO_SUBMISSION_UNCERTAIN' });+ expect(enqueueUnattendedMediaJob).toHaveBeenCalledTimes(1);+ await startVideoExecution('example-video', await startInput({}, { retryAttemptIds: [attempt.id] }));+ expect(state.project.videoExecution.attempts[0].status).toBe('failed');+ expect(startCreativeDirectorProject).toHaveBeenCalledTimes(2);+});++it('reconciles completed clips without a rerender and requires Resume after restart', async () => {+ await startVideoExecution('example-video', await startInput());+ const queued = await enqueue();+ state.project.treatment.scenes[0].status = 'rendering';+ state.jobs[0].status = 'completed';+ await reconcileVideoExecution('example-video', { restarting: true });+ expect(state.project).toMatchObject({ status: 'paused', videoExecution: { authorized: false }, treatment: { scenes: [{ status: 'evaluating', renderedJobId: queued.jobId }] } });+ expect(enqueueUnattendedMediaJob).toHaveBeenCalledTimes(1);+ expect(startCreativeDirectorProject).toHaveBeenCalledTimes(1);+});++it('bounds planner calls and refuses stale or replica dispatch', async () => {+ await startVideoExecution('example-video', await startInput({ maxReplans: 0 }));+ const first = await reserveVideoAttempt('example-video', { kind: 'plan', key: 'plan:project' });+ await settleVideoAttempt('example-video', first.id, { status: 'failed' });+ expect(await reserveVideoAttempt('example-video', { kind: 'plan', key: 'plan:project' })).toBeNull();+ expect(state.project.videoExecution.blocker).toMatch(/replan limit/);+ state.project.videoReplica = true;+ await expect(startVideoExecution('example-video', await startInput())).rejects.toMatchObject({ code: 'VIDEO_START_BLOCKED' });+});+++it('checks the duration the backend actually consumes and rejects batch expansion', async () => {+ await startVideoExecution('example-video', await startInput());+ await expect(enqueueVideoProductionJob(state.project, { sceneId: 'opening', workRevision: 0,+ params: { mode: 'fal', durationSeconds: 5, duration: 60, prompt: 'Example' } })).rejects.toMatchObject({ code: 'VIDEO_PLAN_CLIP_BOUNDS' });+ await expect(enqueueVideoProductionJob(state.project, { sceneId: 'opening', workRevision: 0,+ params: { mode: 'text', durationSeconds: 5, numFrames: 1440, fps: 24, prompt: 'Example' } })).rejects.toMatchObject({ code: 'VIDEO_PLAN_CLIP_BOUNDS' });+ expect(state.project.videoExecution.attempts).toHaveLength(0);+ expect(enqueueUnattendedMediaJob).not.toHaveBeenCalled();+});diff --git a/server/services/creativeDirector/videoReview.test.js b/server/services/creativeDirector/videoReview.test.jsindex f58f70b0ac..da42042b70 100644--- a/server/services/creativeDirector/videoReview.test.js+++ b/server/services/creativeDirector/videoReview.test.js@@ -71,12 +71,12 @@ describe('Video review workflow', () => {it('reuses only unchanged successful plan work and invalidates changed dependencies', () => {const steps = [- { stepId: 'a', toolName: 'video_generate', args: { prompt: 'Old' }, dependsOn: [] },- { stepId: 'b', toolName: 'video_generate', args: { prompt: 'Next' }, dependsOn: ['a'] },- { stepId: 'c', toolName: 'video_generate', args: { prompt: 'Independent' }, dependsOn: [] },+ { stepId: 'a', toolName: 'media_enqueueVideoJob', args: { params: { prompt: 'Old', durationSeconds: 5 } }, dependsOn: [] },+ { stepId: 'b', toolName: 'media_enqueueVideoJob', args: { params: { prompt: 'Next', durationSeconds: 5 } }, dependsOn: ['a'] },+ { stepId: 'c', toolName: 'media_enqueueVideoJob', args: { params: { prompt: 'Independent', durationSeconds: 5 } }, dependsOn: [] },];mocks.project.plan = { steps: steps.map(step => ({ ...step, status: 'done', result: { jobId: step.stepId } })) };- const revised = applyPlan(mocks.project, { steps: steps.map(step => step.stepId === 'a' ? { ...step, args: { prompt: 'Changed' }, status: 'done', result: { jobId: 'forged' } } : step) });+ const revised = applyPlan(mocks.project, { steps: steps.map(step => step.stepId === 'a' ? { ...step, args: { params: { prompt: 'Changed', durationSeconds: 5 } }, status: 'done', result: { jobId: 'forged' } } : step) });expect(revised.plan.steps.map(step => step.status)).toEqual(['pending', 'pending', 'done']);expect(revised.plan.steps[0].result).toBeNull();expect(revised.plan.steps[2].result).toEqual({ jobId: 'c' });diff --git a/server/services/mediaJobQueue/index.js b/server/services/mediaJobQueue/index.jsindex bf34ab5c62..40e2a20536 100644--- a/server/services/mediaJobQueue/index.js+++ b/server/services/mediaJobQueue/index.js@@ -494,6 +494,14 @@ export async function initMediaJobQueue() {const videoReap = await reapAndCleanDetachedDirs(join(PATHS.videos, '.detached')).catch(() => ({ reaped: 0 }));if (videoReap.reaped) console.log(`🧹 reaped ${videoReap.reaped} surviving render(s) on boot`);for (const j of persistedJobs) {+ // Explicit Video Start grants one process lifetime. Restored jobs wait for+ // project reconciliation; replaying an unknown paid submit could charge twice.+ if (j.params?.videoProduction && ['queued', 'running'].includes(j.status)) {+ archive.push({ ...j, status: 'failed', error: 'Video production paused after restart', completedAt: new Date().toISOString(),+ params: { ...restoredParams(j), videoProduction: { ...j.params.videoProduction, submissionUncertain: j.status === 'running' } } });+ restartedFailedIds.push(j.id);+ continue;+ }if (j.status === 'running') {// A remote provider job survives this process: its local queue id is// also the stable Idempotency-Key. Re-enqueue the same record and let@@ -961,6 +969,12 @@ async function runJob(job) {// (how far it got) — consumers gate the progress UI on status === 'running',// so the residual values are not displayed for terminal jobs.job.completedAt = new Date().toISOString();+ if (job.params?.videoProduction) {+ const { settleVideoAttempt } = await import('../creativeDirector/videoExecution.js');+ const tag = job.params.videoProduction;+ await settleVideoAttempt(tag.projectId, tag.attemptId, { jobId: job.id, status: job.params.videoProduction.submissionUncertain || (state === 'failed' && /timeout|timed out|interrupted/i.test(job.error || '')) ? 'uncertain' : state })+ .catch(error => console.error(`❌ Video receipt could not settle: ${error.message}`));+ }// Wake the lane finalizer without polling. Some providers emit their// terminal event just before their kickoff promise resolves; the promise// retains that signal until runJob reaches the await below.@@ -1144,6 +1158,10 @@ async function runJob(job) {try {const mod = await getGenModuleForJob(job);+ if (job.params?.videoProduction) {+ const { assertVideoAttemptDispatch } = await import('../creativeDirector/videoExecution.js');+ await assertVideoAttemptDispatch(job.params.videoProduction.projectId, job.params.videoProduction.attemptId, { jobId: job.id });+ }if (!mod) throw new Error(`Unknown job kind: ${job.kind}`);// A cancel that arrived while this job was still queued lives on the// persisted marker, not on any in-memory adapter state. Re-stamp it for@@ -1330,6 +1348,10 @@ export async function cancelJob(jobId) {// cancelRequested flips the dispatcher's `failed` handler into the// `canceled` branch instead of marking it failed.runningJob.cancelRequested = true;+ if (runningJob.params?.videoProduction && ['reactor', 'fal', 'grok'].includes(runningJob.params.mode)) {+ runningJob.params.videoProduction = { ...runningJob.params.videoProduction, submissionUncertain: true };+ await persist();+ }if (isRemoteMediaJob(runningJob)) {// Remote cancellation can outlive this process when the peer is down.// Persist the intent before signaling the adapter so boot reconciliationdiff --git a/server/services/mediaJobQueue/index.test.js b/server/services/mediaJobQueue/index.test.jsindex ad193b2b26..0842f6f4f8 100644--- a/server/services/mediaJobQueue/index.test.js+++ b/server/services/mediaJobQueue/index.test.js@@ -732,6 +732,19 @@ describe('mediaJobQueue', () => {await waitFor(() => mediaJobQueue.getJob(job.jobId).status === 'completed');});+ it('holds restored Video production submissions before any worker can spend', async () => {+ const jobs = ['queued', 'running'].map((status, index) => ({ id: `00000000-0000-4000-8000-00000000000${index + 1}`,+ kind: 'video', status, queuedAt: '2026-04-30T10:00:00.000Z',+ params: { videoProduction: { projectId: 'example-video', attemptId: `example-attempt-${index}` } } }));+ writeFileSync(join(tempDataDir, 'media-jobs.json'), JSON.stringify({ jobs }));+ await importFresh();+ await mediaJobQueue.initMediaJobQueue();+ expect(mediaJobQueue.getJob(jobs[0].id)).toMatchObject({ status: 'failed', params: { videoProduction: { submissionUncertain: false } } });+ expect(mediaJobQueue.getJob(jobs[1].id)).toMatchObject({ status: 'failed', params: { videoProduction: { submissionUncertain: true } } });+ expect(stubs.generateVideo).not.toHaveBeenCalled();+ expect(stubs.generateVideoRemote).not.toHaveBeenCalled();+ });+it('boot recovery: persisted "running" jobs are reclassified as failed', async () => {const interruptedId = '00000000-0000-4000-8000-000000000001';const persisted = {diff --git a/server/services/videoGen/backendPin.js b/server/services/videoGen/backendPin.jsindex 608b0d7a45..6ecab442f7 100644--- a/server/services/videoGen/backendPin.js+++ b/server/services/videoGen/backendPin.js@@ -32,7 +32,7 @@ import { nearestGrokDuration } from '../../lib/grokVideoClip.js';import { nearestReactorAspect } from '../../lib/reactorVideoClip.js';import { ServerError } from '../../lib/errorHandler.js';import { renderTargetDefaults } from '../imageGen/cloudProviderConfig.js';-import { VIDEO_GEN_MODE, VIDEO_GEN_MODES, resolveVideoMode, hasVideoPin } from './modes.js';+import { VIDEO_GEN_MODE, VIDEO_GEN_MODES, resolveVideoMode, hasVideoPin, isVideoModeUsable } from './modes.js';/*** Resolve the video backend for a CD project through the pin ladder: the@@ -61,7 +61,11 @@ export function resolveVideoBackendPin(project, settings, { target = RENDER_TARG// it), but a hand-made or peer-synced project can carry the sentinel.const mode = normalizeRenderPinValue(raw?.mode);const targetDefaults = renderTargetDefaults(settings, target);- const resolvedMode = resolveVideoMode(mode, settings, { target });+ const strictMode = mode || normalizeRenderPinValue(targetDefaults.videoMode) || normalizeRenderPinValue(settings?.videoGen?.mode) || VIDEO_GEN_MODE.LOCAL;+ if (project?.workspace === 'video' && (!VIDEO_GEN_MODES.includes(strictMode) || !isVideoModeUsable(settings, strictMode))) {+ throw new ServerError(`The selected ${strictMode} video backend is unavailable. Enable it and configure its credentials in Settings, or change the production backend.`, { status: 409, code: 'VIDEO_BACKEND_UNAVAILABLE' });+ }+ const resolvedMode = project?.workspace === 'video' ? strictMode : resolveVideoMode(mode, settings, { target });// The target videoModel and project.modelId are local catalog choices. fal// accepts an endpoint model only from its own explicit project pin; Reactor// and Grok choose their models in the renderer. A lapsed fal pin must not