Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

feat: add the Video workspace and inert production drafts (#6546)

[._.]/ Adam Eivy007009b9527f
diff --git a/client/src/App.jsx b/client/src/App.jsx
index 6a1ce4adbc..5efa2929cc 100644
--- a/client/src/App.jsx
+++ b/client/src/App.jsx
@@ -146,8 +146,8 @@ const PageLoader = () => (
// /image-gen?settings=1 chain depends on ?settings=1 reaching the new path, and
// legacy universe bookmarks may carry a hash (e.g. `#canon`) we must not drop.
function RedirectWithSearch({ to }) {
- const { search, hash } = useLocation();
- return <Navigate to={`${to}${search}${hash}`} replace />;
+ const { search, hash, state } = useLocation();
+ return <Navigate to={`${to}${search}${hash}`} state={state} replace />;
}
// Canon page was folded into Universe Builder; redirect the old sub-route to
@@ -204,8 +204,8 @@ const ANNOTATE_PREFIX = /^\/annotate/;
// drop them; building the relative target from useLocation keeps deep-link
// state intact (the relative pathname still resolves the :id segment).
function CreativeDirectorOverviewRedirect() {
- const { search, hash } = useLocation();
- return <Navigate to={`overview${search}${hash}`} replace />;
+ const { search, hash, state } = useLocation();
+ return <Navigate to={`overview${search}${hash}`} state={state} replace />;
}
// Force full reload on HMR — partial hot-replacement of the route tree
@@ -423,7 +423,7 @@ export default function App() {
<Route path="media" element={<MediaGen />}>
<Route index element={<Navigate to="/media/image" replace />} />
<Route path="image" element={<ImageGen />} />
- <Route path="video" element={<VideoGen />} />
+ <Route path="video" element={<RedirectWithSearch to="/video/generate" />} />
<Route path="history" element={<MediaHistory />} />
<Route path="annotate" element={<MediaAnnotate />} />
<Route path="annotate/:mediaKey" element={<MediaAnnotate />} />
@@ -435,6 +435,7 @@ export default function App() {
/media/creative-director bookmarks + in-app deep-links working. */}
<Route path="creative-director" element={<RedirectWithSearch to="/creative-director" />} />
<Route path="creative-director/:id" element={<PrefixRedirect from={MEDIA_CREATIVE_DIRECTOR_PREFIX} to="/creative-director" />} />
+ <Route path="creative-director/:id/:tab/:sceneId" element={<PrefixRedirect from={MEDIA_CREATIVE_DIRECTOR_PREFIX} to="/creative-director" />} />
<Route path="creative-director/:id/:tab" element={<PrefixRedirect from={MEDIA_CREATIVE_DIRECTOR_PREFIX} to="/creative-director" />} />
{/* Music Video moved to the top-level /music-video route (Create
sidebar link). These redirects keep legacy /media/music-video
@@ -479,8 +480,14 @@ export default function App() {
carrying any query string + hash (relative Navigate preserves the
:id in the path) so a deep-link like /creative-director/abc?x#y
lands on /creative-director/abc/overview?x#y intact. */}
+ <Route path="video" element={<CreativeDirector basePath="/video" workspace="video" />} />
+ <Route path="video/generate" element={<VideoGen />} />
+ <Route path="video/:id" element={<CreativeDirectorOverviewRedirect />} />
+ <Route path="video/:id/:tab/:sceneId" element={<CreativeDirectorDetail basePath="/video" />} />
+ <Route path="video/:id/:tab" element={<CreativeDirectorDetail basePath="/video" />} />
<Route path="creative-director" element={<CreativeDirector />} />
<Route path="creative-director/:id" element={<CreativeDirectorOverviewRedirect />} />
+ <Route path="creative-director/:id/:tab/:sceneId" element={<CreativeDirectorDetail />} />
<Route path="creative-director/:id/:tab" element={<CreativeDirectorDetail />} />
{/* Music Video — a top-level Create page (moved out of the Media Gen
tabs). The project id is the URL, per the ID-based deep-linking
@@ -502,7 +509,7 @@ export default function App() {
<Route path="game" element={<Game />} />
<Route path="game/:id" element={<Game />} />
<Route path="image-gen" element={<RedirectWithSearch to="/media/image" />} />
- <Route path="video-gen" element={<RedirectWithSearch to="/media/video" />} />
+ <Route path="video-gen" element={<RedirectWithSearch to="/video/generate" />} />
<Route path="media-history" element={<RedirectWithSearch to="/media/history" />} />
<Route path="media-models" element={<RedirectWithSearch to="/models/media" />} />
<Route path="wiki" element={<RedirectWithSearch to="/wiki/overview" />} />
diff --git a/client/src/App.videoRoutes.test.jsx b/client/src/App.videoRoutes.test.jsx
new file mode 100644
index 0000000000..c54e54839f
--- /dev/null
+++ b/client/src/App.videoRoutes.test.jsx
@@ -0,0 +1,15 @@
+import { it, expect, vi } from 'vitest';
+import { render, screen } from '@testing-library/react';
+import { MemoryRouter, Outlet, useLocation } from 'react-router';
+vi.mock('./components/Layout', () => ({ default: () => <Outlet /> }));
+vi.mock('./pages/Dashboard', () => ({ default: () => null }));
+vi.mock('./hooks/useCatalogTypes.jsx', () => ({ CatalogTypesProvider: ({ children }) => children }));
+vi.mock('./services/api', () => ({ getSettings: vi.fn(() => Promise.resolve({ timezone: 'UTC' })), updateSettings: vi.fn(), getSelfInstance: vi.fn(() => Promise.resolve({})), PORTOS_APP_ID: 'portos' }));
+vi.mock('./pages/MediaGen', () => ({ default: () => <Outlet /> }));
+vi.mock('./pages/VideoGen', () => ({ default: () => { const location = useLocation(); return <pre data-testid="clip-location">{JSON.stringify({ pathname: location.pathname, search: location.search, hash: location.hash, state: location.state })}</pre>; } }));
+import App from './App.jsx';
+it.each(['/media/video', '/video-gen'])('preserves clip handoff state through %s', async path => {
+ const state = { remix: { ingredientIds: ['example-ingredient'] } };
+ render(<MemoryRouter initialEntries={[{ pathname: path, search: '?settings=1', hash: '#clip', state }]}><App /></MemoryRouter>);
+ expect(JSON.parse((await screen.findByTestId('clip-location')).textContent)).toEqual({ pathname: '/video/generate', search: '?settings=1', hash: '#clip', state });
+});
diff --git a/client/src/components/Layout.jsx b/client/src/components/Layout.jsx
index c8beb6e786..3ce0e43c34 100644
--- a/client/src/components/Layout.jsx
+++ b/client/src/components/Layout.jsx
@@ -229,6 +229,7 @@ export const NAV_PRESENTATION = {
'/catalog': { icon: Sparkles },
'/creative-commission': { icon: CalendarClock },
'/creative-director': { icon: Clapperboard },
+ '/video': { icon: Clapperboard },
'/pipeline/editorial-checks': { icon: ListChecks },
'/fableloom': { icon: Waypoints },
'/game': { icon: Gamepad2 },
@@ -586,6 +587,7 @@ const FULL_WIDTH_PATH_PREFIXES = [
// so they need the bare full-width main — same as when they lived
// under the /media tabs.
'/creative-director',
+ '/video',
'/brain',
'/digital-twin',
'/feature-agents',
diff --git a/client/src/components/creative-director/SegmentsTab.jsx b/client/src/components/creative-director/SegmentsTab.jsx
index 4dc5f49b8c..f071d4ba66 100644
--- a/client/src/components/creative-director/SegmentsTab.jsx
+++ b/client/src/components/creative-director/SegmentsTab.jsx
@@ -1,10 +1,11 @@
-import { Link } from 'react-router';
+import { Link, useParams } from 'react-router';
import { Bot } from 'lucide-react';
import { extractKind } from './ActiveAgentsBanner.jsx';
import ScenePreview from './ScenePreview.jsx';
import { SCENE_STATUS_BADGE } from './sceneStatus.js';
-export default function SegmentsTab({ project, activeAgents = [] }) {
+export default function SegmentsTab({ project, activeAgents = [], basePath = '/creative-director' }) {
+ const { sceneId: selectedSceneId } = useParams();
const scenes = project.treatment?.scenes;
if (!scenes?.length) {
return <div className="text-port-text-muted text-sm">No scenes yet — the treatment hasn't been generated.</div>;
@@ -41,9 +42,12 @@ export default function SegmentsTab({ project, activeAgents = [] }) {
return [];
};
+ if (selectedSceneId && !sorted.some(s => s.sceneId === selectedSceneId)) return <div>Shot not found. <Link to={`${basePath}/${project.id}/segments`}>View all shots</Link></div>;
return (
+ <div>
+ {selectedSceneId && <Link to={`${basePath}/${project.id}/segments`} className="block mb-3 text-port-accent">View all shots</Link>}
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-3">
- {sorted.map((s) => {
+ {sorted.filter(s => !selectedSceneId || s.sceneId === selectedSceneId).map((s) => {
const isInflight = isSceneInflight(s.sceneId);
const decoratedStatus = isInflight && s.status === 'pending' ? 'rendering' : s.status;
return (
@@ -61,7 +65,7 @@ export default function SegmentsTab({ project, activeAgents = [] }) {
)}
<div className="p-2 space-y-1">
<div className="flex items-center justify-between gap-2">
- <div className="text-sm font-medium">Scene {s.order + 1}</div>
+ <Link className="text-sm font-medium hover:underline" to={`${basePath}/${project.id}/segments/${encodeURIComponent(s.sceneId)}`}>Scene {s.order + 1}</Link>
<span className={`text-xs px-2 py-0.5 rounded ${SCENE_STATUS_BADGE[decoratedStatus] || ''}`}>{decoratedStatus}</span>
</div>
<div className="text-xs text-port-text-muted truncate" title={s.intent}>{s.intent}</div>
@@ -91,5 +95,6 @@ export default function SegmentsTab({ project, activeAgents = [] }) {
);
})}
</div>
+ </div>
);
}
diff --git a/client/src/components/creative-director/SegmentsTab.test.jsx b/client/src/components/creative-director/SegmentsTab.test.jsx
new file mode 100644
index 0000000000..19838a74d4
--- /dev/null
+++ b/client/src/components/creative-director/SegmentsTab.test.jsx
@@ -0,0 +1,12 @@
+import { it, expect } from 'vitest';
+import { render, screen } from '@testing-library/react';
+import { MemoryRouter, Route, Routes } from 'react-router';
+import SegmentsTab from './SegmentsTab.jsx';
+it('restores the selected shot from its URL without changing the project ID', () => {
+ const project = { id: 'existing-project', treatment: { scenes: [{ sceneId: 'shot-a', order: 0, intent: 'Opening', status: 'pending' }, { sceneId: 'shot-b', order: 1, intent: 'Closing', status: 'pending' }] } };
+ render(<MemoryRouter initialEntries={['/video/existing-project/segments/shot-b']}><Routes><Route path="/video/:id/:tab/:sceneId" element={<SegmentsTab project={project} basePath="/video" />} /></Routes></MemoryRouter>);
+ expect(screen.getByText('Closing')).toBeTruthy();
+ expect(screen.queryByText('Opening')).toBeNull();
+ expect(screen.getByRole('link', { name: 'View all shots' })).toHaveAttribute('href', '/video/existing-project/segments');
+ expect(screen.getByRole('link', { name: 'Scene 2' })).toHaveAttribute('href', '/video/existing-project/segments/shot-b');
+});
diff --git a/client/src/components/creative-director/VideoDraftDrawer.jsx b/client/src/components/creative-director/VideoDraftDrawer.jsx
new file mode 100644
index 0000000000..37c0795750
--- /dev/null
+++ b/client/src/components/creative-director/VideoDraftDrawer.jsx
@@ -0,0 +1,89 @@
+import { VIDEO_REVIEW_CHECKPOINTS } from '../../../../server/lib/creativeDirectorPresets.js';
+import { useEffect, useState } from 'react';
+import Drawer from '../Drawer.jsx';
+import useDrawerTab from '../../hooks/useDrawerTab.js';
+import toast from '../ui/Toast';
+import { createCreativeDirectorProject, updateCreativeDirectorProject } from '../../services/apiCreativeDirector.js';
+import { listUniverses } from '../../services/apiUniverseBuilder.js';
+import { listPipelineSeries } from '../../services/apiPipeline.js';
+import { listCatalogIngredients } from '../../services/apiCatalog.js';
+import { listMusicEngines } from '../../services/apiMusic.js';
+import { listVideoModels } from '../../services/apiImageVideo.js';
+
+const TABS = [{ id: 'brief', label: 'Brief' }, { id: 'production', label: 'Production' }, { id: 'sources', label: 'Sources' }];
+const fieldClass = 'w-full mt-1 bg-port-bg border border-port-border rounded px-2 py-2 text-sm';
+
+export default function VideoDraftDrawer({ open, onClose, project, onSaved, catalogIngredientIds = [] }) {
+ const [tab, setTab] = useDrawerTab('videoDraftTab', 'brief', TABS.map(t => t.id));
+ const [form, setForm] = useState({});
+ const [models, setModels] = useState([]);
+ const [engines, setEngines] = useState([]);
+ const [sourceOptions, setSourceOptions] = useState({});
+ const [sourceKind, setSourceKind] = useState('universe');
+ const [sourceId, setSourceId] = useState('');
+ const [sourceQuery, setSourceQuery] = useState('');
+ const [saving, setSaving] = useState(false);
+ useEffect(() => {
+ if (!open) return;
+ setSourceId('');
+ setSourceQuery('');
+ const draft = project?.videoDraft;
+ setForm({ name: project?.name || '', userStory: project?.userStory || '', styleSpec: project?.styleSpec || '',
+ aspectRatio: project?.aspectRatio || '16:9', quality: project?.quality || 'standard', modelId: project?.modelId || '',
+ min: draft?.durationRange?.min || 30, max: draft?.durationRange?.max || 60,
+ reviewPolicy: draft?.reviewPolicy || 'review', audioProvider: draft?.audio?.providerId || '', audioModel: draft?.audio?.model || '',
+ sources: draft?.sources || catalogIngredientIds.map(id => ({ kind: 'catalog', id })) });
+ listMusicEngines({ silent: true }).then(data => setEngines(data?.engines || [])).catch(() => {});
+ const rows = data => Array.isArray(data) ? data : data?.items || data?.series || data?.universes || [];
+ Promise.all([listUniverses({ silent: true }), listPipelineSeries({ silent: true }), listCatalogIngredients({ limit: 100, silent: true })]).then(([u, s, c]) => setSourceOptions({ universe: rows(u), series: rows(s), catalog: rows(c) })).catch(() => toast.error('Unable to load source choices. Close and reopen to retry.'));
+ listVideoModels({ silent: true }).then(m => setModels(m || [])).catch(() => {});
+ }, [open, project?.id]);
+ const change = (key, value) => setForm(prev => ({ ...prev, [key]: value }));
+ const input = (key, label, options = {}) => <label htmlFor={`video-draft-${key}`} className="block text-sm">{label}<input id={`video-draft-${key}`} className={fieldClass} value={form[key] ?? ''} onChange={e => change(key, e.target.value)} {...options} /></label>;
+ const select = (key, label, choices) => <label htmlFor={`video-draft-${key}`} className="block text-sm">{label}<select id={`video-draft-${key}`} className={fieldClass} value={form[key] || ''} onChange={e => change(key, e.target.value)}>{choices.map(([value, text]) => <option key={value} value={value}>{text}</option>)}</select></label>;
+ const save = async () => {
+ if (!form.name?.trim()) { setTab('brief'); toast.error('Name is required'); return; }
+ const min = Number(form.min), max = Number(form.max);
+ if (!Number.isInteger(min) || !Number.isInteger(max) || min < 5 || max > 600 || min > max) { setTab('brief'); toast.error('Choose a duration range between 5 and 600 seconds, minimum first'); return; }
+ const sources = form.sources || [];
+ const payload = { name: form.name.trim(), userStory: form.userStory, styleSpec: form.styleSpec,
+ aspectRatio: form.aspectRatio, quality: form.quality, modelId: form.modelId, targetDurationSeconds: max,
+ ...(!project ? { workspace: 'video', catalogIngredientIds: sources.filter(s => s.kind === 'catalog').map(s => s.id) } : {}),
+ videoDraft: { durationRange: { min, max }, sources, audio: { ...(form.audioProvider ? { providerId: form.audioProvider } : {}), ...(form.audioModel ? { model: form.audioModel } : {}) }, reviewPolicy: form.reviewPolicy, checkpoints: project?.videoDraft?.checkpoints || VIDEO_REVIEW_CHECKPOINTS } };
+ setSaving(true);
+ const saved = await (project ? updateCreativeDirectorProject(project.id, payload, { silent: true }) : createCreativeDirectorProject(payload, { silent: true }))
+ .catch(err => { toast.error(err.message || 'Unable to save video draft'); return null; });
+ setSaving(false);
+ if (saved) { onClose(); onSaved(saved); toast.success('Video draft saved'); }
+ };
+ return <Drawer open={open} onClose={onClose} title={project ? 'Edit video draft' : 'New video draft'} subtitle="Saving a draft makes no provider calls" size="lg" tabs={TABS} activeTab={tab} onTabChange={setTab} closeOnEsc={false} closeOnBackdrop={false}>
+ <fieldset disabled={saving} className="space-y-4">
+ {tab === 'brief' && <>
+ {input('name', 'Name', { maxLength: 200 })}
+ <label htmlFor="video-draft-userStory" className="block text-sm">Brief<textarea id="video-draft-userStory" value={form.userStory || ''} onChange={e => change('userStory', e.target.value)} className={fieldClass} rows={4} maxLength={10000} /></label>
+ <label htmlFor="video-draft-styleSpec" className="block text-sm">Style<textarea id="video-draft-styleSpec" value={form.styleSpec || ''} onChange={e => change('styleSpec', e.target.value)} className={fieldClass} rows={3} maxLength={5000} /></label>
+ <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">{input('min', 'Minimum duration (seconds)', { type: 'number', min: 5, max: 600 })}{input('max', 'Maximum duration (seconds)', { type: 'number', min: 5, max: 600 })}</div>
+ </>}
+ {tab === 'production' && <>
+ <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">{select('aspectRatio', 'Aspect ratio', ['16:9', '9:16', '1:1'].map(x => [x, x]))}{select('quality', 'Quality', ['draft', 'standard', 'high'].map(x => [x, x]))}</div>
+ <h3 className="font-medium">Cognitive models</h3><p className="text-sm text-port-text-muted">Inherit Creative Director defaults. After saving, use Models to select providers and models separately for treatment, production planning, and evaluation.</p>
+ {select('modelId', 'Media model', [['', 'Choose before production'], ...models.map(m => [m.id, m.name || m.id])])}
+ <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>
+ </>}
+ {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>}
+ <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
+ <label htmlFor="video-source-kind">Source collection<select id="video-source-kind" className={fieldClass} value={sourceKind} onChange={e => { setSourceKind(e.target.value); setSourceId(''); }}><option value="universe">Universes</option><option value="series">Series</option><option value="catalog">Catalog</option></select></label>
+ <label htmlFor="video-source-record">Source<select id="video-source-record" className={fieldClass} value={sourceId} onChange={e => setSourceId(e.target.value)}><option value="">Choose a source</option>{(sourceOptions[sourceKind] || []).map(source => <option key={source.id} value={source.id}>{source.name || source.title || source.id}</option>)}</select></label>
+ </div>
+ <button disabled={!sourceId || (form.sources || []).length >= 50} onClick={() => { if (!(form.sources || []).some(s => s.kind === sourceKind && s.id === sourceId)) change('sources', [...(form.sources || []), { kind: sourceKind, id: sourceId }]); setSourceId(''); }} className="px-3 py-2 rounded border border-port-border disabled:opacity-50">Add source</button>
+ <ul className="space-y-2">{(form.sources || []).map(source => <li key={`${source.kind}:${source.id}`} className="flex items-center justify-between gap-2 border border-port-border rounded p-2"><span>{source.kind}: {sourceOptions[source.kind]?.find(s => s.id === source.id)?.name || sourceOptions[source.kind]?.find(s => s.id === source.id)?.title || source.id}</span><button aria-label={`Remove ${source.kind} source ${source.id}`} onClick={() => change('sources', form.sources.filter(s => s !== source))}>Remove</button></li>)}</ul>
+ <p className="text-sm text-port-text-muted">Attach up to 50 sources from existing creative records. Imported music and voice references remain attached until you remove them.</p>
+ </>}
+ <div className="flex justify-end gap-2 border-t border-port-border pt-4"><button disabled={saving} onClick={onClose} className="px-3 py-2 rounded border border-port-border">Cancel</button><button disabled={saving} onClick={save} className="px-3 py-2 rounded bg-port-accent text-white disabled:opacity-50">{saving ? 'Saving…' : 'Save draft'}</button></div>
+ </fieldset>
+ </Drawer>;
+}
diff --git a/client/src/components/creative-director/VideoDraftDrawer.test.jsx b/client/src/components/creative-director/VideoDraftDrawer.test.jsx
new file mode 100644
index 0000000000..e068a02cbb
--- /dev/null
+++ b/client/src/components/creative-director/VideoDraftDrawer.test.jsx
@@ -0,0 +1,27 @@
+vi.mock('../../services/apiMusic.js', () => ({ listMusicEngines: vi.fn(() => Promise.resolve({ engines: [] })) }));
+vi.mock('../../services/apiUniverseBuilder.js', () => ({ listUniverses: vi.fn(() => Promise.resolve([])) }));
+vi.mock('../../services/apiPipeline.js', () => ({ listPipelineSeries: vi.fn(() => Promise.resolve([])) }));
+vi.mock('../../services/apiCatalog.js', () => ({ listCatalogIngredients: vi.fn(() => Promise.resolve([])) }));
+import { it, expect, 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', () => ({ createCreativeDirectorProject: vi.fn(), updateCreativeDirectorProject: vi.fn() }));
+vi.mock('../../services/apiImageVideo.js', () => ({ listVideoModels: vi.fn(() => Promise.resolve([])) }));
+vi.mock('../ui/Toast', () => ({ default: { success: vi.fn(), error: vi.fn() } }));
+import { createCreativeDirectorProject, updateCreativeDirectorProject } from '../../services/apiCreativeDirector.js';
+import VideoDraftDrawer from './VideoDraftDrawer.jsx';
+it('edits the same draft without changing workspace or losing source revisions', async () => {
+ const user = userEvent.setup();
+ const project = { id: 'draft-1', workspace: 'video', name: 'Example', videoDraft: { sources: [{ kind: 'catalog', id: 'example', revision: 'r1' }], durationRange: { min: 20, max: 40 }, reviewPolicy: 'review', checkpoints: ['rough-cut'] } };
+ updateCreativeDirectorProject.mockResolvedValue(project);
+ const saved = vi.fn();
+ render(<MemoryRouter><VideoDraftDrawer open project={project} onClose={vi.fn()} onSaved={saved} /></MemoryRouter>);
+ await user.clear(screen.getByLabelText('Name'));
+ await user.type(screen.getByLabelText('Name'), 'Revised');
+ await user.click(screen.getByRole('button', { name: 'Save draft' }));
+ await waitFor(() => expect(saved).toHaveBeenCalledWith(project));
+ expect(updateCreativeDirectorProject).toHaveBeenCalledWith('draft-1', expect.objectContaining({ name: 'Revised', videoDraft: expect.objectContaining({ sources: project.videoDraft.sources, checkpoints: ['rough-cut'] }) }), { silent: true });
+ expect(updateCreativeDirectorProject.mock.calls[0][1]).not.toHaveProperty('workspace');
+ expect(createCreativeDirectorProject).not.toHaveBeenCalled();
+});
diff --git a/client/src/pages/CreativeDirector.jsx b/client/src/pages/CreativeDirector.jsx
index d1b8fd555c..4042406372 100644
--- a/client/src/pages/CreativeDirector.jsx
+++ b/client/src/pages/CreativeDirector.jsx
@@ -22,6 +22,7 @@ import PageSkeleton from '../components/ui/PageSkeleton';
import Drawer from '../components/Drawer';
import DirectiveComposer from '../components/creative-director/DirectiveComposer.jsx';
import CreativeDirectorModelsDrawer from '../components/creative-director/CreativeDirectorModelsDrawer.jsx';
+import VideoDraftDrawer from '../components/creative-director/VideoDraftDrawer.jsx';
import ProjectPreview from '../components/creative-director/ProjectPreview.jsx';
const ASPECT_RATIOS = ['16:9', '9:16', '1:1'];
@@ -39,13 +40,20 @@ const STATUS_COLORS = {
const EMPTY_DIRECTIVE = { goal: '', deliverables: [], constraints: { universeId: null, seriesId: null, budgetCap: null } };
-export default function CreativeDirector() {
+export default function CreativeDirector({ basePath = '/creative-director', workspace } = {}) {
+ const isVideo = workspace === 'video';
const location = useLocation();
const navigate = useNavigate();
const [searchParams, setSearchParams] = useSearchParams();
const [projects, setProjects] = useState([]);
const [loading, setLoading] = useState(true);
- const [showForm, setShowForm] = useState(false);
+ const [legacyFormOpen, setLegacyFormOpen] = useState(false);
+ const showForm = isVideo ? searchParams.get('new') === 'video' : legacyFormOpen;
+ const setShowForm = value => {
+ const open = typeof value === 'function' ? value(showForm) : value;
+ if (!isVideo) { setLegacyFormOpen(open); return; }
+ setSearchParams(prev => { const next = new URLSearchParams(prev); if (open) next.set('new', 'video'); else next.delete('new'); return next; }, { replace: true });
+ };
const [models, setModels] = useState([]);
// Directive composer (CDO Phase 4, #2186) — deep-linkable drawer (`?new=directive`)
// that creates a studio production project seeded with a directive. State is
@@ -115,7 +123,9 @@ export default function CreativeDirector() {
.then((res) => setRemixIngredients(Array.isArray(res) ? res : (Array.isArray(res?.items) ? res.items : [])))
.catch(() => {});
// Clear the handoff state so a refresh doesn't re-seed (ids already captured).
- navigate('.', { replace: true, state: {} });
+ const nextSearch = new URLSearchParams(location.search);
+ if (isVideo) nextSearch.set('new', 'video');
+ navigate({ pathname: location.pathname, search: nextSearch.toString(), hash: location.hash }, { replace: true, state: {} });
}, []);
// Drop any pending remix handoff so abandoned ingredient ids can't leak into
@@ -152,7 +162,7 @@ export default function CreativeDirector() {
// so the user sees the cast immediately; otherwise stay on the list.
if (remixIds.length) {
clearRemix();
- navigate(`/creative-director/${created.id}/overview`);
+ navigate(`${basePath}/${created.id}/overview`);
}
} catch (err) {
toast.error(err.message || 'Failed to create project');
@@ -205,7 +215,7 @@ export default function CreativeDirector() {
setProjects((prev) => [created, ...prev]);
toast.success(`Created directive "${created.name}"`);
closeDirective();
- navigate(`/creative-director/${created.id}/plan`);
+ navigate(`${basePath}/${created.id}/plan`);
};
// Optimistic-update the row in place rather than refetching the whole list
@@ -280,18 +290,18 @@ export default function CreativeDirector() {
<div className="flex flex-col h-full">
<PageHeader
icon={Film}
- title="Creative Director"
- subtitle="Long-form video projects driven by an autonomous CoS agent"
+ title={isVideo ? 'Video' : 'Creative Director'}
+ subtitle={isVideo ? 'Draft standalone shorts, then review each production stage' : 'Long-form video projects driven by an autonomous CoS agent'}
actions={
<>
- <button
+ {!isVideo && <button
onClick={openDirective}
className="flex items-center gap-2 bg-port-card border border-port-border hover:bg-port-card/60 text-port-text px-3 py-2 rounded text-sm"
title="Compose a directive — the Creative Director plans and executes it across the creative suite"
>
<Wand2 className="w-4 h-4" />
New directive
- </button>
+ </button>}
<button
onClick={() => setModelsOpen(true)}
className="flex items-center gap-2 bg-port-card border border-port-border hover:bg-port-card/60 text-port-text px-3 py-2 rounded text-sm"
@@ -300,7 +310,7 @@ export default function CreativeDirector() {
<SlidersHorizontal className="w-4 h-4" />
Model defaults
</button>
- <OverflowMenu
+ {!isVideo && <OverflowMenu
label="More Creative Director actions"
triggerRef={smokeMenuTriggerRef}
items={[
@@ -312,13 +322,14 @@ export default function CreativeDirector() {
onSelect: () => setConfirmingSmokeTest(true),
},
]}
- />
+ />}
+ {isVideo && <Link to="/video/generate" className="px-3 py-2 rounded border border-port-border text-sm">Generate clip</Link>}
<button
onClick={() => { setShowForm((s) => !s); clearRemix(); }}
className="flex items-center gap-2 bg-port-accent hover:bg-port-accent/80 text-white px-3 py-2 rounded text-sm"
>
<Plus className="w-4 h-4" />
- New project
+ {isVideo ? 'New video draft' : 'New project'}
</button>
</>
}
@@ -342,7 +353,7 @@ export default function CreativeDirector() {
/>
)}
- {showForm && (
+ {showForm && !isVideo && (
<form onSubmit={handleCreate} className="shrink-0 p-6 border-b border-port-border bg-port-card/40 space-y-3">
{remixIngredients.length > 0 && (
<div className="rounded border border-port-accent/40 bg-port-accent/10 px-3 py-2">
@@ -478,9 +489,9 @@ export default function CreativeDirector() {
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-3">
{projects.map((p) => (
<div key={p.id} className="bg-port-card border border-port-border rounded p-3 flex flex-col gap-2">
- <ProjectPreview project={p} to={`/creative-director/${p.id}/overview`} />
+ <ProjectPreview project={p} to={`${basePath}/${p.id}/overview`} />
<div className="flex items-start justify-between gap-2">
- <Link to={`/creative-director/${p.id}/overview`} className="flex-1 min-w-0">
+ <Link to={`${basePath}/${p.id}/overview`} className="flex-1 min-w-0">
<div className="font-medium truncate">{p.name}</div>
<div className="text-xs text-port-text-muted truncate">{p.id}</div>
</Link>
@@ -493,6 +504,7 @@ export default function CreativeDirector() {
{p.treatment?.scenes?.length ? `${p.treatment.scenes.filter((s) => s.status === 'accepted').length}/${p.treatment.scenes.length} scenes accepted` : 'No treatment yet'}
</div>
<div className="flex gap-1 mt-1">
+ {p.workspace === 'video' && <span className="text-xs text-port-text-muted">Draft · next: edit brief · production not enabled</span>}
{/* Pause is meaningful only when the agent could be in flight.
`draft` has nothing running yet, and the terminal states are
obviously inert — match the detail page's gating. */}
@@ -501,7 +513,7 @@ export default function CreativeDirector() {
<Pause className="w-3 h-3" /> Pause
</button>
)}
- {(p.status === 'paused' || p.status === 'draft' || p.status === 'failed') && (
+ {p.workspace !== 'video' && (p.status === 'paused' || p.status === 'draft' || p.status === 'failed') && (
<button onClick={() => handleStart(p.id)} className="flex items-center gap-1 px-2 py-1 bg-port-accent/30 text-port-accent rounded text-xs">
<Play className="w-3 h-3" /> Start
</button>
@@ -555,6 +567,7 @@ export default function CreativeDirector() {
</div>
</Drawer>
+ {isVideo && <VideoDraftDrawer open={showForm} onClose={() => { setShowForm(false); clearRemix(); }} catalogIngredientIds={remixIds} onSaved={created => { setProjects(prev => [created, ...prev]); navigate(`${basePath}/${created.id}/overview`); }} />}
<CreativeDirectorModelsDrawer
scope="global"
open={modelsOpen}
diff --git a/client/src/pages/CreativeDirector.test.jsx b/client/src/pages/CreativeDirector.test.jsx
index c73f6cfd84..25ef0f06e7 100644
--- a/client/src/pages/CreativeDirector.test.jsx
+++ b/client/src/pages/CreativeDirector.test.jsx
@@ -1,3 +1,4 @@
+vi.mock('../services/apiMusic.js', () => ({ listMusicEngines: vi.fn(() => Promise.resolve({ engines: [] })) }));
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { render, screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
@@ -5,13 +6,14 @@ import { MemoryRouter } from 'react-router';
vi.mock('../services/apiCreativeDirector.js', () => ({
listCreativeDirectorProjects: vi.fn(() => Promise.resolve([])),
+ updateCreativeDirectorProject: vi.fn(() => Promise.resolve({})),
createCreativeDirectorProject: vi.fn(() => Promise.resolve({})),
createSmokeTestCreativeDirectorProject: vi.fn(() => Promise.resolve({ id: 'smoke-1', name: 'CD smoke test (colored ball)', status: 'planning' })),
deleteCreativeDirectorProject: vi.fn(() => Promise.resolve({})),
startCreativeDirectorProject: vi.fn(() => Promise.resolve({})),
pauseCreativeDirectorProject: vi.fn(() => Promise.resolve({})),
}));
-vi.mock('../services/apiCatalog.js', () => ({ listCatalogIngredientsByIds: vi.fn(() => Promise.resolve([])) }));
+vi.mock('../services/apiCatalog.js', () => ({ listCatalogIngredients: vi.fn(() => Promise.resolve([])), listCatalogIngredientsByIds: vi.fn(() => Promise.resolve([])) }));
vi.mock('../services/apiImageVideo.js', () => ({ listVideoModels: vi.fn(() => Promise.resolve([{ id: 'model-a', name: 'Model A' }])) }));
vi.mock('../services/apiUniverseBuilder.js', () => ({ listUniverses: vi.fn(() => Promise.resolve([])) }));
vi.mock('../services/apiPipeline.js', () => ({ listPipelineSeries: vi.fn(() => Promise.resolve([])) }));
@@ -130,3 +132,37 @@ describe('CreativeDirector header action hierarchy (#3287)', () => {
await waitFor(() => expect(screen.getByRole('menuitem', { name: ITEM_LABEL }).disabled).toBe(false));
});
});
+
+
+describe('Video workspace draft creation', () => {
+ it('saves an inert draft and links existing project IDs within Video', async () => {
+ const user = userEvent.setup();
+ vi.clearAllMocks();
+ cdApi.listCreativeDirectorProjects.mockResolvedValue([{ id: 'existing-project', name: 'Existing project', status: 'draft', workspace: 'video' }]);
+ cdApi.createCreativeDirectorProject.mockResolvedValue({ id: 'new-draft', name: 'Example short', workspace: 'video', status: 'draft' });
+ render(<MemoryRouter initialEntries={['/video']}><CreativeDirector basePath="/video" workspace="video" /></MemoryRouter>);
+ await user.click(await screen.findByRole('button', { name: 'New video draft' }));
+ expect(screen.getByRole('link', { name: 'Open Existing project' })).toHaveAttribute('href', '/video/existing-project/overview');
+ expect(screen.queryByRole('button', { name: 'Start' })).toBeNull();
+ await user.type(screen.getByLabelText('Name'), 'Example short');
+ await user.type(screen.getByRole('textbox', { name: 'Brief' }), 'A traveler returns home.');
+ await user.click(screen.getByRole('button', { name: 'Save draft' }));
+ await waitFor(() => expect(cdApi.createCreativeDirectorProject).toHaveBeenCalledWith(expect.objectContaining({
+ workspace: 'video', name: 'Example short', userStory: 'A traveler returns home.',
+ videoDraft: expect.objectContaining({ durationRange: { min: 30, max: 60 }, reviewPolicy: 'review', checkpoints: ['script-shot-plan', 'references', 'rough-cut', 'final-cut'] }),
+ }), { silent: true }));
+ expect(cdApi.startCreativeDirectorProject).not.toHaveBeenCalled();
+ });
+});
+
+it('keeps a Video remix draft open and forwards source IDs once on save', async () => {
+ vi.clearAllMocks();
+ cdApi.listCreativeDirectorProjects.mockResolvedValue([]);
+ cdApi.createCreativeDirectorProject.mockResolvedValue({ id: 'remix-draft', name: 'Example remix', workspace: 'video', status: 'draft' });
+ const user = userEvent.setup();
+ render(<MemoryRouter initialEntries={[{ pathname: '/video', search: '?view=all', hash: '#drafts', state: { remix: { ingredientIds: ['source-example'] } } }]}><CreativeDirector basePath="/video" workspace="video" /></MemoryRouter>);
+ await user.type(await screen.findByRole('textbox', { name: 'Name' }), 'Example remix');
+ await user.click(screen.getByRole('button', { name: 'Save draft' }));
+ await waitFor(() => expect(cdApi.createCreativeDirectorProject).toHaveBeenCalledTimes(1));
+ expect(cdApi.createCreativeDirectorProject).toHaveBeenCalledWith(expect.objectContaining({ catalogIngredientIds: ['source-example'], videoDraft: expect.objectContaining({ sources: [{ kind: 'catalog', id: 'source-example' }] }) }), { silent: true });
+});
diff --git a/client/src/pages/CreativeDirectorDetail.jsx b/client/src/pages/CreativeDirectorDetail.jsx
index e2f9cda5d9..44563437fb 100644
--- a/client/src/pages/CreativeDirectorDetail.jsx
+++ b/client/src/pages/CreativeDirectorDetail.jsx
@@ -1,6 +1,7 @@
import { useEffect, useState, useCallback, useRef } from 'react';
import { useParams, useNavigate, useSearchParams, Link } from 'react-router';
import { ArrowLeft, Play, Pause, RefreshCw, SlidersHorizontal, Square, Trash2 } from 'lucide-react';
+import TabPills from '../components/ui/TabPills.jsx';
import PageSkeleton from '../components/ui/PageSkeleton';
import toast from '../components/ui/Toast';
import ConfirmButtonPair from '../components/ui/ConfirmButtonPair';
@@ -13,6 +14,7 @@ import {
stopCreativeDirectorProject,
resumeCreativeDirectorProject,
} from '../services/apiCreativeDirector.js';
+import VideoDraftDrawer from '../components/creative-director/VideoDraftDrawer.jsx';
import OverviewTab from '../components/creative-director/OverviewTab.jsx';
import TreatmentTab from '../components/creative-director/TreatmentTab.jsx';
import SegmentsTab from '../components/creative-director/SegmentsTab.jsx';
@@ -27,6 +29,8 @@ import useMediaJobProgress from '../hooks/useMediaJobProgress';
const TERMINAL_PROJECT_STATUSES = new Set(['complete', 'failed', 'paused', 'draft']);
+const VIDEO_DRAFT_TABS = [{ id: 'overview', label: 'Overview' }, { id: 'segments', label: 'Shots' }, { id: 'runs', label: 'Runs' }];
+
const TABS = [
{ id: 'overview', label: 'Overview' },
{ id: 'plan', label: 'Plan' },
@@ -35,11 +39,15 @@ const TABS = [
{ id: 'runs', label: 'Runs' },
];
-export default function CreativeDirectorDetail() {
+export default function CreativeDirectorDetail({ basePath = '/creative-director' } = {}) {
const { id } = useParams();
const navigate = useNavigate();
const [searchParams, setSearchParams] = useSearchParams();
- const activeTab = useValidTab(TABS, 'overview');
+ const editingDraft = searchParams.get('draft') === '1';
+ const setEditingDraft = open => setSearchParams(prev => { const next = new URLSearchParams(prev); if (open) next.set('draft', '1'); else next.delete('draft'); return next; }, { replace: true });
+ const [project, setProject] = useState(null);
+ const tabs = project?.workspace === 'video' ? VIDEO_DRAFT_TABS : TABS;
+ const activeTab = useValidTab(tabs, 'overview');
// Deep-linkable open state for the per-project AI models drawer (URL is the
// source of truth for what's open, per the project convention).
const modelsOpen = searchParams.get('models') === '1';
@@ -51,7 +59,6 @@ export default function CreativeDirectorDetail() {
return params;
}, { replace: !next });
}, [setSearchParams]);
- const [project, setProject] = useState(null);
const [loading, setLoading] = useState(true);
const [activeAgents, setActiveAgents] = useState([]);
// Extends polling past the terminal-status gate below for a bounded window
@@ -203,7 +210,7 @@ export default function CreativeDirectorDetail() {
try {
await deleteCreativeDirectorProject(id, { silent: true });
toast.success('Creative Director project deleted');
- navigate('/creative-director');
+ navigate(basePath);
} catch (err) {
toast.error(err.message || 'Failed to delete project');
setDeleting(false);
@@ -231,14 +238,14 @@ export default function CreativeDirectorDetail() {
}
if (!project) return <div className="p-6 text-port-error">Project not found.</div>;
- const goTo = (tabId) => navigate(`/creative-director/${id}/${tabId}`);
+ const goTo = (tabId) => navigate(`${basePath}/${id}/${tabId}`);
return (
<div className="flex flex-col h-full">
<div className="shrink-0 px-6 pt-6 pb-3 border-b border-port-border">
<div className="flex items-center justify-between gap-3">
<div className="flex items-center gap-3 min-w-0">
- <Link to="/creative-director" className="text-port-text-muted hover:text-port-text"><ArrowLeft className="w-4 h-4" /></Link>
+ <Link to={basePath} className="text-port-text-muted hover:text-port-text"><ArrowLeft className="w-4 h-4" /></Link>
<div className="min-w-0">
<h1 className="line-clamp-2 break-words text-xl font-semibold" title={project.name}>{project.name}</h1>
<div className="text-xs text-port-text-muted truncate">
@@ -253,12 +260,12 @@ export default function CreativeDirectorDetail() {
<button onClick={() => setModelsOpen(true)} title="AI provider + model for this project's treatment, plan, and scene evaluation" className="flex items-center gap-1 px-2 py-1 bg-port-card border border-port-border rounded text-xs">
<SlidersHorizontal className="w-3 h-3" /> Models
</button>
- {(project.status === 'draft' || project.status === 'failed') && (
+ {project.workspace !== 'video' && (project.status === 'draft' || project.status === 'failed') && (
<button onClick={() => handleAction('start')} className="flex items-center gap-1 px-2 py-1 bg-port-accent/30 text-port-accent rounded text-xs">
<Play className="w-3 h-3" /> Start
</button>
)}
- {project.status === 'paused' && (
+ {project.workspace !== 'video' && project.status === 'paused' && (
<button onClick={() => handleAction('resume')} className="flex items-center gap-1 px-2 py-1 bg-port-accent/30 text-port-accent rounded text-xs">
<Play className="w-3 h-3" /> Resume
</button>
@@ -312,36 +319,35 @@ export default function CreativeDirectorDetail() {
)}
</div>
</div>
- <div className="flex gap-1 mt-3">
- {TABS.map((t) => (
- <button
- key={t.id}
- onClick={() => goTo(t.id)}
- className={`px-3 py-1.5 text-sm rounded ${activeTab === t.id ? 'bg-port-accent/30 text-port-accent' : 'text-port-text-muted hover:text-port-text'}`}
- >
- {t.label}
- </button>
- ))}
- </div>
+ <TabPills tabs={tabs} activeTab={activeTab} onChange={goTo} mobileDropdown ariaLabel="Video project sections" className="mt-3" />
</div>
<div className="flex-1 overflow-auto p-6">
<ActiveAgentsBanner agents={activeAgents} />
- {activeTab === 'overview' && (
+ {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>
+ <p className="whitespace-pre-wrap">{project.userStory || 'Add a brief to describe this video.'}</p>
+ <p className="text-sm">Target: {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>
+ <VideoDraftDrawer open={editingDraft} onClose={() => setEditingDraft(false)} project={project} onSaved={saved => setProject(prev => ({ ...prev, ...saved }))} />
+ </section>}
+ {project.workspace !== 'video' && activeTab === 'overview' && (
<OverviewTab
project={project}
onProjectUpdate={(updates) => setProject((p) => p ? { ...p, ...updates } : p)}
onAsyncWorkQueued={extendPollingForAsyncWork}
/>
)}
- {activeTab === 'plan' && (
+ {project.workspace !== 'video' && activeTab === 'plan' && (
<PlanTab
project={project}
onProjectUpdate={(updated) => setProject((p) => (p ? { ...p, ...updated } : updated))}
/>
)}
- {activeTab === 'treatment' && <TreatmentTab project={project} />}
- {activeTab === 'segments' && <SegmentsTab project={project} activeAgents={activeAgents} />}
+ {project.workspace !== 'video' && activeTab === 'treatment' && <TreatmentTab project={project} />}
+ {activeTab === 'segments' && <SegmentsTab project={project} activeAgents={activeAgents} basePath={basePath} />}
{activeTab === 'runs' && <RunsTab project={project} />}
</div>
diff --git a/client/src/pages/MediaGen.jsx b/client/src/pages/MediaGen.jsx
index ad4eeff1e8..48be42ba8c 100644
--- a/client/src/pages/MediaGen.jsx
+++ b/client/src/pages/MediaGen.jsx
@@ -38,7 +38,7 @@ export default function MediaGen() {
<TabPills
tabs={TABS}
activeTab={activeTab}
- onChange={(id) => navigate(`/media/${id}`)}
+ onChange={(id) => navigate(id === 'video' ? '/video/generate' : `/media/${id}`)}
ariaLabel="Media Gen sections"
mobileDropdown
mobileSelectId="media-gen-section-select"
diff --git a/docs/STORAGE.md b/docs/STORAGE.md
index 88e9130db0..334fffc954 100644
--- a/docs/STORAGE.md
+++ b/docs/STORAGE.md
@@ -259,3 +259,22 @@ successful API fetch and subsequent syncs can omit it. Downgrades to versions be
this store require re-entering keys through the older settings UI or environment.
Other credentials (provider connections, account-specific logins, and auth) retain
their existing dedicated stores and management flows.
+
+### Video workspace drafts
+
+Video reuses `creative_director_projects` and its existing project IDs, collection
+links, PostgreSQL JSONB record, and test-only file adapter. New records opt in
+with `workspace: 'video'`; missing workspace means the existing Creative Director
+behavior. The additive `videoDraft` stores a bounded duration range, source IDs
+and optional revisions, audio choices, review policy, and four review checkpoints.
+Brief/style/quality and cognitive/media pins use the existing project fields.
+No new table, file store, seed, or record-rewriting migration is needed: legacy
+records must retain their prior behavior. Both adapters share record construction
+and patch validation. Draft creation and save perform no provider work.
+
+Schema category `creativeDirectorProjects` advances to v4 because an older peer
+would ignore the Video dispatch barrier. Video production stays unavailable at
+both HTTP start/resume and background advancement until revision-specific approval
+support ships. Selecting autonomous policy only saves intent; it cannot authorize
+dispatch while that barrier is present. Source references do not copy or mutate
+the referenced creative-suite records.
diff --git a/server/lib/README.md b/server/lib/README.md
index bf5467650c..70e6a6991f 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -79,7 +79,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `cosValidation.js` | Chief-of-Staff task/job/loop/learning schemas, the Code-Review settings slice, and the task-metadata sanitizer. The Review-Loop reviewer vocabulary lives in `reviewerConfig.js` (#5702) and is re-exported flat from here. |
| `creativeBriefLimits.js` | `COMMISSION_NAME_MAX` / `COMMISSION_INTENT_MAX` / `COMMISSION_STYLE_SPEC_MAX` / `COMMISSION_BRIEF_TAG_MAX` and `CREATIVE_DIRECTOR_GOAL_MAX` — the creative brief caps `creativeCommissionValidation.js` and `creativeDirectorValidation.js` enforce and the browser forms use as a silent input `maxLength`. A pure leaf (the schemas pull `zod`) so `client/src/components/creative-commission/commissionForm.js` and `client/src/lib/creativeDirectorPlan.js` re-export one definition instead of copying the numbers. |
| `creativeCommissionValidation.js` | Creative Commission (Autonomous Creation Engine) create/update + brief/schedule/generation schemas. The brief field caps it enforces come from `creativeBriefLimits.js`. |
-| `creativeDirectorValidation.js` | Creative Director project/treatment/scene + Create-Suite importer schemas. The directive `goal` cap it enforces comes from `creativeBriefLimits.js`. |
+| `creativeDirectorValidation.js` | Creative Director project/treatment/scene, inert Video draft preferences, and Create-Suite importer schemas. The directive `goal` cap it enforces comes from `creativeBriefLimits.js`. |
| `digitalTwinValidation.js` | Digital twin document/category schemas. |
| `eidoverseValidation.js` | Eidoverse world-projection schemas — the `EIDOVERSE_PROJECTION_SOURCE_KEYS` allowlist, the V1/V2 projection recipe union (includes/assets/terrain/scale/districts/environment, with the `..`-escape guard on every asset path), and the world augment/say/config-patch route bodies (incl. the 8KB augment-argument cap). Split out of `validation.js` (#5698), which re-exports it. |
| `fableLoomValidation.js` | FableLoom branching-narrative route schemas (loom/episode/node/transition CRUD, weave/branch/review, play turns). |
diff --git a/server/lib/creativeDirectorPresets.js b/server/lib/creativeDirectorPresets.js
index 5b374e7a8a..edf4c9ce84 100644
--- a/server/lib/creativeDirectorPresets.js
+++ b/server/lib/creativeDirectorPresets.js
@@ -126,3 +126,7 @@ export function presetToRenderParams({ aspectRatio, quality, durationSeconds })
numFrames,
};
}
+
+// Shared by the Video draft form and wire defaults; saved policy is inert until
+// revision-specific dispatch support is available.
+export const VIDEO_REVIEW_CHECKPOINTS = Object.freeze(['script-shot-plan', 'references', 'rough-cut', 'final-cut']);
diff --git a/server/lib/creativeDirectorValidation.js b/server/lib/creativeDirectorValidation.js
index 25b3e2ee6f..2658fd8abd 100644
--- a/server/lib/creativeDirectorValidation.js
+++ b/server/lib/creativeDirectorValidation.js
@@ -1,6 +1,6 @@
import { z } from 'zod';
import { EFFORT_LEVELS } from './providerModels.js';
-import { ASPECT_RATIOS, QUALITIES, PROJECT_STATUSES, SCENE_STATUSES, PLAN_STEP_STATUSES } from './creativeDirectorPresets.js';
+import { ASPECT_RATIOS, QUALITIES, PROJECT_STATUSES, SCENE_STATUSES, PLAN_STEP_STATUSES, VIDEO_REVIEW_CHECKPOINTS } from './creativeDirectorPresets.js';
import { ARC_SHAPE_IDS, ARC_ROLES } from './storyArc.js';
import { BIBLE_LIMITS } from './storyBible.js';
import { emptyToUndefined } from './zodCompat.js';
@@ -124,11 +124,33 @@ export const creativeDirectorRenderBackendSchema = z.object({
video: creativeDirectorRenderPinSchema.optional(),
}).strict();
+// Additive workspace metadata. Absence keeps pre-Video execution semantics.
+export const creativeDirectorVideoDraftSchema = z.object({
+ durationRange: z.object({
+ min: z.number().int().min(5).max(600),
+ max: z.number().int().min(5).max(600),
+ }).strict().refine(({ min, max }) => min <= max, 'Minimum duration must not exceed maximum'),
+ sources: z.array(z.object({
+ kind: z.enum(['universe', 'series', 'catalog', 'music', 'voice']),
+ id: z.string().trim().min(1).max(120),
+ revision: z.string().max(120).optional(),
+ }).strict()).max(50).default([]),
+ audio: z.object({
+ providerId: z.string().max(120).optional(),
+ model: z.string().max(200).optional(),
+ }).strict().default({}),
+ reviewPolicy: z.enum(['review', 'autonomous']).default('review'),
+ checkpoints: z.array(z.enum(VIDEO_REVIEW_CHECKPOINTS))
+ .max(VIDEO_REVIEW_CHECKPOINTS.length).default([...VIDEO_REVIEW_CHECKPOINTS]),
+}).strict();
+
export const creativeDirectorProjectCreateSchema = z.object({
+ workspace: z.literal('video').optional(),
+ videoDraft: creativeDirectorVideoDraftSchema.optional(),
name: z.string().min(1).max(200),
aspectRatio: creativeDirectorAspectRatioSchema,
quality: creativeDirectorQualitySchema,
- modelId: z.string().min(1).max(64),
+ modelId: z.string().max(64),
targetDurationSeconds: z.number().int().min(5).max(600),
styleSpec: z.string().max(5000).default(''),
startingImageFile: safeBasename.nullable().optional(),
@@ -161,6 +183,10 @@ export const creativeDirectorProjectCreateSchema = z.object({
// Optional per-project image/video RENDER-backend pin (#3135). Absent → each
// enqueued media job resolves the install-wide default.
renderBackend: creativeDirectorRenderBackendSchema.nullable().optional(),
+}).refine((v) => v.workspace === 'video' || v.modelId.length > 0, {
+ message: 'Model is required', path: ['modelId'],
+}).refine((v) => !v.videoDraft || v.workspace === 'video', {
+ message: 'Video draft requires the Video workspace', path: ['videoDraft'],
});
// Autonomous auto-cast (#1810). `types` narrows the catalog search to a set of
@@ -209,6 +235,12 @@ export const creativeDirectorAutoCastApplySchema = z.object({
// point a CD project at an unrelated user timeline project, which the
// next stitch would silently overwrite via updateTimelineProject.
export const creativeDirectorProjectUpdateSchema = z.object({
+ videoDraft: creativeDirectorVideoDraftSchema.optional(),
+ aspectRatio: creativeDirectorAspectRatioSchema.optional(),
+ quality: creativeDirectorQualitySchema.optional(),
+ modelId: z.string().max(64).optional(),
+ targetDurationSeconds: z.number().int().min(5).max(600).optional(),
+ renderBackend: creativeDirectorRenderBackendSchema.nullable().optional(),
name: z.string().min(1).max(200).optional(),
styleSpec: z.string().max(5000).optional(),
userStory: z.string().max(10000).nullable().optional(),
diff --git a/server/lib/navManifest.js b/server/lib/navManifest.js
index 95524bef55..125a3a847d 100644
--- a/server/lib/navManifest.js
+++ b/server/lib/navManifest.js
@@ -45,12 +45,13 @@ const RAW_NAV_COMMANDS = [
{ id: 'nav.catalog.settings', path: '/catalog?settings=1', label: 'Catalog Types', section: 'Create', previousPaths: ['/settings/catalog'], aliases: ['catalog settings', 'catalog-settings', 'settings-catalog', 'catalog-types'], keywords: ['catalog', 'types', 'labels', 'character', 'place', 'object', 'taxonomy'] },
{ id: 'nav.media', path: '/media', label: 'Media Gen', section: 'Create', aliases: ['media', 'media-gen', 'mediagen', 'generate'], keywords: ['image', 'video', 'render', 'art', 'movie'] },
{ id: 'nav.media.image', path: '/media/image', label: 'Image', section: 'Create', tabGroup: 'media', tabId: 'image', previousPaths: ['/image-gen'], aliases: ['image-gen', 'imagegen', 'generate-image', 'sd', 'stable-diffusion'], keywords: ['stable diffusion', 'render', 'art', 'picture', 'photo', 'draw', 'flux', 'mflux'] },
- { id: 'nav.media.video', path: '/media/video', label: 'Video', section: 'Create', tabGroup: 'media', tabId: 'video', previousPaths: ['/video-gen'], aliases: ['video-gen', 'videogen', 'generate-video', 'ltx'], keywords: ['video', 'animate', 'movie', 'clip', 'ltx', 'episode composer', 'continuous video', 'multi-scene'] },
+ { id: 'nav.media.video', path: '/video/generate', label: 'Generate Video', tabLabel: 'Video', section: 'Create', tabGroup: 'media', tabId: 'video', previousPaths: ['/video-gen', '/media/video'], aliases: ['video-gen', 'videogen', 'generate-video', 'ltx'], keywords: ['video', 'animate', 'movie', 'clip', 'ltx', 'episode composer', 'continuous video', 'multi-scene'] },
{ id: 'nav.media.threejs', path: '/media/threejs', label: 'Three.js Models', section: 'Create', tabGroup: 'media', tabId: 'threejs', tabLabel: 'Three.js', aliases: ['threejs', 'three-js', '3d-models', 'image-to-3d', 'img2threejs'], keywords: ['procedural', '3d', 'mesh', 'model', 'gallery', 'webgl', 'preview'] },
{ id: 'nav.media.annotate', path: '/media/annotate', label: 'Annotate', section: 'Create', tabGroup: 'media', tabId: 'annotate', previousPaths: ['/annotate', '/annotate/:mediaKey'], aliases: ['annotate', 'media-annotate', 'sketch', 'draw-over', 'markup'], keywords: ['annotation', 'sketch', 'draw', 'markup', 'scribble', 'label', 'canvas', 'overlay', 'stroke'] },
{ id: 'nav.media.timeline', path: '/media/timeline', label: 'Timeline', section: 'Create', tabGroup: 'media', tabId: 'timeline', aliases: ['timeline', 'video-timeline', 'editor'], keywords: ['edit', 'trim', 'composite', 'stitch', 'cut', 'compose'] },
{ id: 'nav.media.history', path: '/media/history', label: 'Media History', section: 'Create', tabGroup: 'media', tabId: 'history', tabLabel: 'History', previousPaths: ['/media-history'], aliases: ['media-history', 'video-history'], keywords: ['videos', 'gallery', 'stitch'] },
{ id: 'nav.media.collections', path: '/media/collections', label: 'Collections', section: 'Create', tabGroup: 'media', tabId: 'collections', aliases: ['collections', 'media-collections', 'stacks', 'projects'], keywords: ['bucket', 'group', 'project', 'album', 'organize'] },
+ { id: 'nav.create.video', path: '/video', label: 'Video', section: 'Create', aliases: ['video', 'create-video', 'video-workspace'], keywords: ['shorts', 'brief', 'script', 'production', 'review'] },
{ id: 'nav.create.creative-director', path: '/creative-director', label: 'Creative Director', section: 'Create', previousPaths: ['/media/creative-director', '/media/creative-director/:id', '/media/creative-director/:id/:tab'], aliases: ['creative-director', 'creative', 'director', 'producer', 'orchestrator', 'long-form', 'episode'], keywords: ['story', 'episode', 'narrative', 'agent', 'auto-video', 'long-form', 'directive', 'production plan', 'plan board', 'orchestrator', 'studio', 'producer'] },
{ id: 'nav.create.creative-commission', path: '/creative-commission', label: 'Creative Commissions', section: 'Create', aliases: ['creative-commission', 'commissions', 'commission', 'creation-engine', 'autonomous-creation', 'standing-brief', 'recurring-brief'], keywords: ['schedule', 'recurring', 'nightly', 'brief', 'autonomous', 'creation engine', 'cron', 'feedback', 'taste', 'standing commission', 'auto-generate'] },
{ id: 'nav.create.fableloom', path: '/fableloom', label: 'FableLoom', section: 'Create', aliases: ['fableloom', 'fable-loom', 'loom', 'branching-narrative', 'interactive-story', 'branching-story'], keywords: ['branching', 'interactive', 'narrative', 'intent', 'endings', 'reader', 'scene', 'node', 'graph', 'nonlinear', 'play', 'story graph'] },
diff --git a/server/lib/schemaVersions.js b/server/lib/schemaVersions.js
index 4e7f1760bb..ebbeca1f7d 100644
--- a/server/lib/schemaVersions.js
+++ b/server/lib/schemaVersions.js
@@ -445,7 +445,10 @@ export const PORTOS_SCHEMA_VERSIONS = Object.freeze({
// transfer (per-category 409) until it upgrades, so it never mis-executes a
// syntax it can't resolve. No record rewrite needed — reference-free projects
// are unchanged; the bump only gates cross-version CD-project sync.
- creativeDirectorProjects: 3,
+ // v4: Video drafts must stay inert. Older peers ignore workspace and could
+ // start them through the legacy planner; reject transfers until they upgrade.
+ // Existing records remain unchanged and need no data rewrite.
+ creativeDirectorProjects: 4,
// v1 = Mood boards (PostgreSQL `mood_boards`) federated via the per-record
// peer-sync push pipeline (record kind `moodBoard`, sync category `moodBoards`,
// #1564). Same posture as `creativeDirectorProjects` above: a brand-NEW synced
diff --git a/server/routes/creativeDirector.js b/server/routes/creativeDirector.js
index 684f080b29..38e2e6652a 100644
--- a/server/routes/creativeDirector.js
+++ b/server/routes/creativeDirector.js
@@ -45,6 +45,14 @@ import { stopProject } from '../services/creativeDirector/stopProject.js';
const router = Router();
+function assertVideoDispatchAvailable(project) {
+ if (project?.workspace === 'video') {
+ throw new ServerError('Video production is waiting for revision-specific approval support. Save the brief and model choices; Start will be available when dispatch gates are installed.', {
+ status: 409, code: 'VIDEO_DISPATCH_UNAVAILABLE',
+ });
+ }
+}
+
// Backward-compatible by default: returns the full projects array. When a client
// passes `limit`/`offset`, the response becomes the bounded
// `{ items, total, limit, offset }` envelope every paginated PortOS list shares.
@@ -138,6 +146,14 @@ router.post('/auto-cast/suggest', asyncHandler(async (req, res) => {
router.patch('/:id', asyncHandler(async (req, res) => {
const data = validateRequest(creativeDirectorProjectUpdateSchema, req.body);
+ const draftFields = ['videoDraft', 'aspectRatio', 'quality', 'modelId', 'targetDurationSeconds', 'renderBackend'];
+ if (draftFields.some((key) => key in data)) {
+ const project = await getProject(req.params.id);
+ if (!project) throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });
+ if (project.workspace !== 'video' || project.status !== 'draft') {
+ throw new ServerError('Production settings can only be edited on a Video draft', { status: 409, code: 'INVALID_STATE' });
+ }
+ }
const updated = await updateProject(req.params.id, data);
res.json(updated);
}));
@@ -177,6 +193,7 @@ router.delete('/:id', asyncHandler(async (req, res) => {
// treatment as they land. The response carries `composing` so the UI can tell
// the user the director took over.
router.post('/:id/auto-cast', asyncHandler(async (req, res) => {
+ assertVideoDispatchAvailable(await getProject(req.params.id));
const { brief, types, limit, compose, generateFirstPass, generateFirstPassMusicBed } = validateRequest(creativeDirectorAutoCastApplySchema, req.body);
// Scene reference frames (#1867) depend on a treatment existing, which may
// land well after THIS request — either because `compose` kicks it off
@@ -282,6 +299,7 @@ router.post('/:id/directive', asyncHandler(async (req, res) => {
const directive = validateRequest(creativeDirectorDirectiveSchema, req.body);
const project = await getProject(req.params.id);
if (!project) throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });
+ assertVideoDispatchAvailable(project);
const parked = project.status === 'paused' || project.status === 'failed';
const updated = await updateProject(req.params.id, {
directive,
@@ -302,6 +320,7 @@ router.post('/:id/directive', asyncHandler(async (req, res) => {
router.post('/:id/replan', 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.directive) throw new ServerError('Project has no directive to re-plan', { status: 400, code: 'NO_DIRECTIVE' });
const updated = await updateProject(req.params.id, { plan: null, status: 'planning', failureReason: null });
const { advanceAfterPlanStepSettled } = await import('../services/creativeDirector/planAdvance.js');
@@ -321,6 +340,7 @@ router.post('/:id/plan/step/:stepId', asyncHandler(async (req, res) => {
const { action } = validateRequest(creativeDirectorPlanStepActionSchema, req.body);
const project = await getProject(req.params.id);
if (!project) throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });
+ assertVideoDispatchAvailable(project);
const step = (project.plan?.steps || []).find((s) => s.stepId === req.params.stepId);
if (!step) throw new ServerError('Plan step not found', { status: 404, code: 'NOT_FOUND' });
const patch = action === 'skip'
@@ -363,6 +383,7 @@ router.patch('/:id/scene/:sceneId', asyncHandler(async (req, res) => {
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.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.
@@ -408,6 +429,7 @@ 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.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.js
index 1d9d97b314..fe185ea207 100644
--- a/server/routes/creativeDirector.test.js
+++ b/server/routes/creativeDirector.test.js
@@ -79,6 +79,51 @@ describe('creativeDirector routes', () => {
vi.clearAllMocks();
});
+ describe('Video drafts', () => {
+ const draft = {
+ name: 'Example short', workspace: 'video', modelId: '',
+ aspectRatio: '16:9', quality: 'draft', targetDurationSeconds: 60,
+ videoDraft: { durationRange: { min: 60, max: 180 } },
+ };
+
+ it('creates and saves a brief without starting provider work, and rejects malformed ranges', async () => {
+ cdService.createProject.mockResolvedValueOnce({ ...draft, id: 'cd-video', status: 'draft' });
+ expect((await request(app).post('/api/creative-director').send(draft)).status).toBe(201);
+ expect(cdService.createProject).toHaveBeenCalledWith(expect.objectContaining({
+ videoDraft: expect.objectContaining({ reviewPolicy: 'review', checkpoints: ['script-shot-plan', 'references', 'rough-cut', 'final-cut'] }),
+ }));
+ cdService.getProject.mockResolvedValueOnce({ ...draft, id: 'cd-video', status: 'draft' });
+ expect((await request(app).patch('/api/creative-director/cd-video').send({
+ userStory: 'A quiet journey', videoDraft: draft.videoDraft,
+ })).status).toBe(200);
+ expect(hook.startCreativeDirectorProject).not.toHaveBeenCalled();
+ expect(firstPass.enqueueFirstPassPortraits).not.toHaveBeenCalled();
+ expect(firstPassMusicBed.enqueueFirstPassMusicBed).not.toHaveBeenCalled();
+ expect((await request(app).post('/api/creative-director').send({
+ ...draft, videoDraft: { durationRange: { min: 180, max: 60 } },
+ })).status).toBe(400);
+ expect((await request(app).post('/api/creative-director').send({
+ ...draft, workspace: undefined, videoDraft: undefined,
+ })).status).toBe(400);
+ });
+
+ it('refuses legacy execution entry points before they mutate or enqueue a Video draft', async () => {
+ cdService.getProject.mockResolvedValue({ ...draft, id: 'cd-video', status: 'draft' });
+ for (const [action, body] of [
+ ['start', {}], ['resume', {}], ['replan', {}],
+ ['directive', { goal: 'Example goal' }],
+ ['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(cdService.updateProject).not.toHaveBeenCalled();
+ expect(autoCast.applyAutoCastToProject).not.toHaveBeenCalled();
+ expect(hook.startCreativeDirectorProject).not.toHaveBeenCalled();
+ cdService.getProject.mockReset();
+ });
+ });
+
describe('stop', () => {
it('POST /:id/stop tears down the in-flight work and reports the counts', async () => {
cdService.getProject.mockResolvedValueOnce({ id: 'cd-1', status: 'planning' });
diff --git a/server/services/creativeDirector/completionHook.js b/server/services/creativeDirector/completionHook.js
index 9485db8f83..4802d5b14d 100644
--- a/server/services/creativeDirector/completionHook.js
+++ b/server/services/creativeDirector/completionHook.js
@@ -264,7 +264,7 @@ export async function advanceAfterSceneSettled(projectId, opts = {}) {
// fresh defer on a stale/stalled duplicate seed job (which would loop).
const skipSeedDeferSceneId = opts.skipSeedDeferSceneId || null;
const project = await getProject(projectId);
- if (!project) return;
+ if (!project || project.workspace === 'video') return;
if (project.status === 'paused' || project.status === 'failed') return;
// No treatment yet → enqueue treatment task.
@@ -609,6 +609,7 @@ export async function advanceAfterSceneSettled(projectId, opts = {}) {
*/
export async function startCreativeDirectorProject(projectId) {
const project = await getProject(projectId).catch(() => null);
+ if (project?.workspace === 'video') return;
if (project?.directive) return advanceAfterPlanStepSettled(projectId);
return advanceAfterSceneSettled(projectId);
}
diff --git a/server/services/creativeDirector/completionHook.test.js b/server/services/creativeDirector/completionHook.test.js
index 5462e4d0b2..35da29e8c0 100644
--- a/server/services/creativeDirector/completionHook.test.js
+++ b/server/services/creativeDirector/completionHook.test.js
@@ -219,3 +219,13 @@ describe('advanceAfterSceneSettled — bounded treatment gate', () => {
expect(mockEnqueueTreatmentTask).toHaveBeenCalledTimes(1);
});
});
+
+it('keeps Video drafts inert through both direct starts and background scene advancement', async () => {
+ mockGetProject.mockResolvedValue({ id: 'cd-video', workspace: 'video', status: 'planning', runs: [], directive: { goal: 'Example' } });
+ await startCreativeDirectorProject('cd-video');
+ await advanceAfterSceneSettled('cd-video');
+ expect(mockAdvancePlan).not.toHaveBeenCalled();
+ expect(mockEnqueueTreatmentTask).not.toHaveBeenCalled();
+ expect(mockRunSceneRender).not.toHaveBeenCalled();
+ expect(mockUpdateProject).not.toHaveBeenCalled();
+});
diff --git a/server/services/creativeDirector/local.js b/server/services/creativeDirector/local.js
index 73fcc9b081..1bcec68ae0 100644
--- a/server/services/creativeDirector/local.js
+++ b/server/services/creativeDirector/local.js
@@ -143,7 +143,7 @@ export async function setTreatment(id, treatmentInput) {
// than in one route handler (#1938) so every setTreatment path (the agent
// `/:id/treatment` PATCH, episodeVideo, liveDirector) honors the opt-in
// instead of the flag silently no-op'ing for treatments that land another way.
- if (next?.generateFirstPass) {
+ if (next?.generateFirstPass && next.workspace !== 'video') {
enqueueFirstPassSceneFrames(next)
.catch((e) => console.log(`⚠️ CD first-pass scene frames failed: ${e.message}`));
}
diff --git a/server/services/creativeDirector/planAdvance.js b/server/services/creativeDirector/planAdvance.js
index 850203c1ab..f1c5b142a2 100644
--- a/server/services/creativeDirector/planAdvance.js
+++ b/server/services/creativeDirector/planAdvance.js
@@ -312,7 +312,7 @@ async function enqueuePlannerOnce(project) {
*/
export async function advanceAfterPlanStepSettled(projectId) {
const project = await getProject(projectId).catch(() => null);
- if (!project) return;
+ if (!project || project.workspace === 'video') return;
if (project.status === 'paused' || project.status === 'failed') return;
// Legacy video project — the scene loop owns it; never plan-advance it.
if (!project.directive) return;
diff --git a/server/services/creativeDirector/planAdvance.test.js b/server/services/creativeDirector/planAdvance.test.js
index 4904d12af5..17b7f005fd 100644
--- a/server/services/creativeDirector/planAdvance.test.js
+++ b/server/services/creativeDirector/planAdvance.test.js
@@ -286,6 +286,14 @@ const planProject = (steps, over = {}) => ({
});
describe('advanceAfterPlanStepSettled — executor', () => {
+ it('never plans or dispatches an inert Video production through background advancement', async () => {
+ makeStore({ ...planProject([step('a', { toolName: 'pipeline_createSeries' })]), workspace: 'video' });
+ await advanceAfterPlanStepSettled('cd-1');
+ expect(mockDispatch).not.toHaveBeenCalled();
+ expect(mockEnqueuePlanTask).not.toHaveBeenCalled();
+ expect(mockUpdateProject).not.toHaveBeenCalled();
+ });
+
it('is a no-op for a legacy project (no directive)', async () => {
makeStore({ id: 'cd-1', status: 'rendering', directive: null, plan: null, runs: [] });
await advanceAfterPlanStepSettled('cd-1');
diff --git a/server/services/creativeDirector/projectsDB.test.js b/server/services/creativeDirector/projectsDB.test.js
index e809986133..e4a0ba05be 100644
--- a/server/services/creativeDirector/projectsDB.test.js
+++ b/server/services/creativeDirector/projectsDB.test.js
@@ -73,6 +73,25 @@ describe.skipIf(!runDb)('projectsDB round-trip', () => {
await close();
});
+ it('persists Video draft preferences and prevents removing the workspace barrier', async () => {
+ const p = await db.createProject({
+ name: 'Example short', workspace: 'video', modelId: '', aspectRatio: '16:9',
+ quality: 'draft', targetDurationSeconds: 60,
+ });
+ created.push(p.id);
+ expect(p.videoDraft.checkpoints).toEqual(['script-shot-plan', 'references', 'rough-cut', 'final-cut']);
+ const videoDraft = {
+ ...p.videoDraft, durationRange: { min: 60, max: 180 },
+ sources: [{ kind: 'universe', id: 'example-universe', revision: 'r1' }],
+ audio: { providerId: 'example-audio', model: 'example-model' },
+ };
+ await db.updateProject(p.id, { userStory: 'Example brief', videoDraft });
+ expect(await db.getProject(p.id)).toMatchObject({
+ id: p.id, workspace: 'video', status: 'draft', userStory: 'Example brief', videoDraft,
+ });
+ await expect(db.updateProject(p.id, { workspace: undefined })).rejects.toThrow('workspace cannot be changed');
+ });
+
it('round-trips and clears cognitive effort through create and patch', async () => {
const pin = { providerId: 'example-agent', model: 'example-model', effort: 'high' };
const p = await db.createProject({ ...CREATE_INPUT, modelOverrides: { plan: pin } });
diff --git a/server/services/creativeDirector/projectsFile.test.js b/server/services/creativeDirector/projectsFile.test.js
index 5ad9672584..46e69d6290 100644
--- a/server/services/creativeDirector/projectsFile.test.js
+++ b/server/services/creativeDirector/projectsFile.test.js
@@ -67,6 +67,24 @@ const project = (id, extra = {}) => ({
const journalEntries = () => cj.conflictJournalStore().loadAll();
describe('projectsFile federation merge', () => {
+ it('persists Video draft preferences and prevents removing the workspace barrier', async () => {
+ const p = await file.createProject({
+ name: 'Example short', workspace: 'video', modelId: '', aspectRatio: '16:9',
+ quality: 'draft', targetDurationSeconds: 60,
+ });
+ expect(p.videoDraft.checkpoints).toEqual(['script-shot-plan', 'references', 'rough-cut', 'final-cut']);
+ const videoDraft = {
+ ...p.videoDraft, durationRange: { min: 60, max: 180 },
+ sources: [{ kind: 'universe', id: 'example-universe', revision: 'r1' }],
+ audio: { providerId: 'example-audio', model: 'example-model' },
+ };
+ await file.updateProject(p.id, { userStory: 'Example brief', videoDraft });
+ expect(await file.getProject(p.id)).toMatchObject({
+ id: p.id, workspace: 'video', status: 'draft', userStory: 'Example brief', videoDraft,
+ });
+ await expect(file.updateProject(p.id, { workspace: undefined })).rejects.toThrow('workspace cannot be changed');
+ });
+
it('round-trips and clears cognitive effort through create and patch', async () => {
const pin = { providerId: 'example-agent', model: 'example-model', effort: 'high' };
const p = await file.createProject({ name: 'Example', modelId: 'example', aspectRatio: '1:1', quality: 'draft', targetDurationSeconds: 9, modelOverrides: { plan: pin } });
diff --git a/server/services/creativeDirector/projectsLogic.js b/server/services/creativeDirector/projectsLogic.js
index 18bd0e96d6..fbdcbb31fe 100644
--- a/server/services/creativeDirector/projectsLogic.js
+++ b/server/services/creativeDirector/projectsLogic.js
@@ -13,6 +13,7 @@
import { randomUUID } from 'crypto';
import { EFFORT_LEVELS } from '../../lib/providerModels.js';
import { ServerError } from '../../lib/errorHandler.js';
+import { creativeDirectorVideoDraftSchema } from '../../lib/creativeDirectorValidation.js';
import { creativeDirectorTreatmentSchema, creativeDirectorPlanSchema } from '../../lib/validation.js';
import { PROJECT_STATUSES, PLAN_STEP_TERMINAL_SUCCESS } from '../../lib/creativeDirectorPresets.js';
import { compareNewerWins } from '../../lib/lwwTimestamp.js';
@@ -184,6 +185,12 @@ export function buildProjectRecord(input, { id, now, collectionId }) {
return {
id,
name,
+ ...(input.workspace === 'video' ? {
+ workspace: 'video',
+ videoDraft: creativeDirectorVideoDraftSchema.parse(input.videoDraft || {
+ durationRange: { min: targetDurationSeconds, max: targetDurationSeconds },
+ }),
+ } : {}),
status: 'draft',
createdAt: now,
updatedAt: now,
@@ -328,7 +335,15 @@ 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 ('workspace' in patch && patch.workspace !== project.workspace) {
+ throw new ServerError('The project workspace cannot be changed', { status: 409, code: 'INVALID_STATE' });
+ }
const next = { ...project, ...patch, updatedAt: new Date().toISOString() };
+ if ('videoDraft' in patch) next.videoDraft = creativeDirectorVideoDraftSchema.parse(patch.videoDraft);
+ if ('renderBackend' in patch) next.renderBackend = normalizeRenderBackend(patch.renderBackend);
// Normalize the whole override object on write so stored records never carry
// empty/model-only stage stubs; the client sends the full object each save.
if ('modelOverrides' in patch) next.modelOverrides = normalizeModelOverrides(patch.modelOverrides);