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
Save music video cast, sets and props to the catalog, with an importer for existing videos (#11922)
[._.]/99271b39c526
diff --git a/client/src/App.jsx b/client/src/App.jsxindex 57f14e26cb..d788c1dc41 100644--- a/client/src/App.jsx+++ b/client/src/App.jsx@@ -72,6 +72,7 @@ const RoundsGuide = lazyWithReload(() => import('./pages/RoundsGuide'));const CatalogIngest = lazyWithReload(() => import('./pages/CatalogIngest'));const CatalogIngredient = lazyWithReload(() => import('./pages/CatalogIngredient'));const CreativeLibrary = lazyWithReload(() => import('./pages/CreativeLibrary'));+const CreativeCastImport = lazyWithReload(() => import('./pages/CreativeCastImport'));const VideoTimeline = lazyWithReload(() => import('./pages/VideoTimeline'));const VideoTimelineEditor = lazyWithReload(() => import('./pages/VideoTimelineEditor'));const CreativeDirector = lazyWithReload(() => import('./pages/CreativeDirector'));@@ -608,6 +609,7 @@ export default function App() {<Route path="catalog/ingest" element={<CatalogIngest />} /><Route path="catalog/:type/:id" element={<CatalogIngredient />} /><Route path="casting" element={<CreativeLibrary key="casting" libraryId="casting" />} />+ <Route path="casting/import" element={<CreativeCastImport />} /><Route path="casting/:id" element={<CatalogIngredient />} /><Route path="environments" element={<CreativeLibrary key="environments" libraryId="environments" />} /><Route path="environments/:id" element={<CatalogIngredient />} />diff --git a/client/src/components/musicVideo/CreativeSetupPanel.jsx b/client/src/components/musicVideo/CreativeSetupPanel.jsxindex 57f62c2b86..6d89c815b7 100644--- a/client/src/components/musicVideo/CreativeSetupPanel.jsx+++ b/client/src/components/musicVideo/CreativeSetupPanel.jsx@@ -7,6 +7,7 @@ import { uuidv4 } from '../../lib/uuid.js';import { pullUniverseCanonReferences } from '../../lib/musicVideoUniverseRefs.js';import CharacterStylePicker from './CharacterStylePicker.jsx';import IngredientPicker from '../IngredientPicker.jsx';+import { ingredientPath } from '../../lib/creativeLibraries.js';const inputClass = 'w-full min-w-0 bg-port-bg border border-port-border rounded px-2 py-1.5 text-sm';const kinds = [['character', 'Cast'], ['place', 'Places'], ['object', 'Objects']];@@ -165,6 +166,9 @@ export default function CreativeSetupPanel({ project, onSave, onPendingChange }){subject.kind === 'character' && <><label htmlFor={idFor(subject.id)} className="sr-only">Role for {subject.name}</label><select id={idFor(subject.id)} className="bg-port-bg border border-port-border rounded text-xs" value={subject.role || 'supporting'} onChange={(e) => setDraft((d) => ({ ...d, subjects: d.subjects.map((s) => s.id === subject.id ? { ...s, role: e.target.value } : s) }))}><option value="protagonist">Protagonist</option><option value="band">Band</option><option value="supporting">Supporting</option></select></>}<button type="button" aria-label={`Remove ${subject.name}`} className="ml-auto text-xs text-port-error min-h-[44px]" onClick={() => setDraft((d) => ({ ...d, subjects: d.subjects.filter((s) => s.id !== subject.id) }))}>Remove</button></div>+ {subject.ingredientId+ ? <Link className="text-xs text-port-accent" target="_blank" to={ingredientPath({ id: subject.ingredientId, type: subject.kind })}>Open in catalog</Link>+ : <div className="flex items-center gap-2 min-h-[32px]"><input id={idFor(`local-${subject.id}`)} type="checkbox" checked={!!subject.localOnly} onChange={(e) => setDraft((d) => ({ ...d, subjects: d.subjects.map((s) => (s.id === subject.id ? { ...s, localOnly: e.target.checked || undefined } : s)) }))} /><label htmlFor={idFor(`local-${subject.id}`)} className="text-xs text-port-text-muted">Keep in this video only</label></div>}<label htmlFor={idFor(`description-${subject.id}`)} className="sr-only">Description for {subject.name}</label><textarea id={idFor(`description-${subject.id}`)} rows={2} maxLength={1000} className={inputClass} value={subject.description || ''} onChange={(e) => setDraft((d) => ({ ...d, subjects: d.subjects.map((s) => s.id === subject.id ? { ...s, description: e.target.value } : s) }))} /></li>)}</ul>diff --git a/client/src/components/musicVideo/CreativeSetupPanel.test.jsx b/client/src/components/musicVideo/CreativeSetupPanel.test.jsxindex 5f853d5f35..ce1fd56f20 100644--- a/client/src/components/musicVideo/CreativeSetupPanel.test.jsx+++ b/client/src/components/musicVideo/CreativeSetupPanel.test.jsx@@ -74,6 +74,21 @@ describe('creative setup', () => {expect(saved.visualSpec.references).toEqual([expect.objectContaining({ imageId: 'diner.png', role: 'set', label: 'Night diner', condition: false })]);});+ it('links a catalog subject to its record and lets the director keep a new one in this video only', async () => {+ const onSave = vi.fn(async () => {});+ const cast = { ...project, concept: { subjects: [+ { id: 'mvc-1', kind: 'character', name: 'Example singer', ingredientId: 'cat-chr-1' },+ { id: 'mvc-2', kind: 'object', name: 'Glass guitar' },+ ] } };+ render(<MemoryRouter><CreativeSetupPanel project={cast} onSave={onSave} onPendingChange={vi.fn()} /></MemoryRouter>);+ fireEvent.click(screen.getByText('Edit'));+ expect(screen.getByRole('link', { name: 'Open in catalog' })).toHaveAttribute('href', '/casting/cat-chr-1');+ fireEvent.click(screen.getByLabelText('Keep in this video only'));+ fireEvent.click(screen.getByText('Save creative setup'));+ await waitFor(() => expect(onSave).toHaveBeenCalledTimes(1));+ expect(onSave.mock.calls[0][0].concept.subjects[1]).toEqual(expect.objectContaining({ id: 'mvc-2', localOnly: true }));+ });+it('discards an unsaved cast when the director cancels setup', async () => {const onSave = open();fireEvent.change(screen.getByLabelText('Name'), { target: { value: 'Unsaved singer' } });diff --git a/client/src/pages/CreativeCastImport.jsx b/client/src/pages/CreativeCastImport.jsxnew file mode 100644index 0000000000..f854d6334a--- /dev/null+++ b/client/src/pages/CreativeCastImport.jsx@@ -0,0 +1,159 @@+/**+ * CreativeCastImport — Casting › Import from music videos.+ *+ * Lists every music video's cast, sets and props that are not in the catalog+ * yet, each with the server's proposal (link to the universe or synced record+ * it matches, or create a new one). The director reviews, changes any choice,+ * and imports. "Keep in this video only" is remembered on the video so it is+ * not offered again.+ */++import { useCallback, useEffect, useMemo, useState } from 'react';+import { Link } from 'react-router';+import { ArrowLeft, Import, Loader2, Sparkles } from 'lucide-react';+import PageHeader from '../components/PageHeader';+import MediaImage from '../components/MediaImage';+import toast from '../components/ui/Toast';+import { previewMusicVideoCastImport, commitMusicVideoCastImport } from '../services/apiCatalog';+import { libraryForType } from '../lib/creativeLibraries';+import { formatCount } from '../utils/formatters';++const decisionKey = (projectId, subjectId) => `${projectId}\n${subjectId}`;+// Under the server's per-request cap, so a large library imports in parts.+const IMPORT_CHUNK = 500;++async function commitInChunks(selections) {+ const totals = { created: 0, linked: 0, kept: 0 };+ for (let i = 0; i < selections.length; i += IMPORT_CHUNK) {+ const result = await commitMusicVideoCastImport(selections.slice(i, i + IMPORT_CHUNK), { silent: true });+ totals.created += result.created;+ totals.linked += result.linked;+ totals.kept += result.kept;+ }+ return totals;+}++function ImportRow({ project, item, action, onChange }) {+ const id = `cast-import-${project.projectId}-${item.subjectId}`;+ const kindLabel = libraryForType(item.kind)?.singular || item.kind;+ return (+ <li className="flex items-center gap-3 py-2 min-w-0">+ <div className="w-12 h-16 shrink-0 rounded bg-port-bg border border-port-border overflow-hidden flex items-center justify-center">+ {item.imageId+ ? <MediaImage src={`/data/images/${item.imageId}`} alt={item.name} className="w-full h-full object-cover" loading="lazy" />+ : <Sparkles size={16} className="text-gray-600" aria-hidden="true" />}+ </div>+ <div className="min-w-0 flex-1">+ <div className="text-sm text-white truncate">{item.name}</div>+ <div className="text-[11px] text-gray-500 capitalize">{kindLabel}</div>+ </div>+ <label htmlFor={id} className="sr-only">What to do with {item.name}</label>+ <select+ id={id}+ value={action}+ onChange={(e) => onChange(e.target.value)}+ className="max-w-[11rem] sm:max-w-xs bg-port-bg border border-port-border rounded px-2 py-1.5 text-sm text-white"+ >+ {item.action === 'link' && <option value="link">Use {item.ingredientName}</option>}+ <option value="create">Add as new</option>+ <option value="local">Keep in this video only</option>+ </select>+ </li>+ );+}++export default function CreativeCastImport() {+ const [projects, setProjects] = useState(null);+ const [decisions, setDecisions] = useState({});+ const [importing, setImporting] = useState(false);++ const load = useCallback(async (signal) => {+ const data = await previewMusicVideoCastImport({ signal, silent: true }).catch((err) => {+ if (err?.name !== 'AbortError') toast.error(err?.message || 'Could not load music video cast');+ return null;+ });+ if (signal?.aborted) return;+ setProjects(Array.isArray(data?.projects) ? data.projects : []);+ setDecisions({});+ }, []);++ useEffect(() => {+ const controller = new AbortController();+ load(controller.signal);+ return () => controller.abort();+ }, [load]);++ const actionFor = (project, item) => decisions[decisionKey(project.projectId, item.subjectId)] || item.action;+ const selections = useMemo(() => (projects || []).flatMap((project) => project.items.map((item) => {+ const action = decisions[decisionKey(project.projectId, item.subjectId)] || item.action;+ return { projectId: project.projectId, subjectId: item.subjectId, action, ...(action === 'link' ? { ingredientId: item.ingredientId } : {}) };+ })), [projects, decisions]);+ const toCatalog = selections.filter((s) => s.action !== 'local').length;++ const handleImport = async () => {+ setImporting(true);+ const result = await commitInChunks(selections)+ .catch((err) => { toast.error(err?.message || 'Import failed'); return null; });+ setImporting(false);+ if (!result) return;+ toast.success(`Imported: ${formatCount(result.created)} new, ${formatCount(result.linked)} linked, ${formatCount(result.kept)} kept in their videos`);+ load();+ };++ return (+ // /casting/* is a full-width route, so the page owns its scroll.+ <div className="h-full overflow-y-auto p-3 sm:p-4 flex flex-col gap-3 min-w-0">+ <PageHeader+ icon={Import}+ title="Import from music videos"+ actions={(+ <Link to="/casting" className="inline-flex items-center gap-1.5 px-3 py-2 min-h-[40px] rounded-lg border border-port-border bg-port-card hover:bg-port-bg text-gray-300 hover:text-white text-sm">+ <ArrowLeft size={16} aria-hidden="true" /> Casting+ </Link>+ )}+ />+ {projects === null ? (+ <div className="flex items-center gap-2 text-sm text-gray-400"><Loader2 size={14} className="animate-spin" aria-hidden="true" /> Reading music videos…</div>+ ) : projects.length === 0 ? (+ <div className="bg-port-card border border-port-border rounded-lg p-8 text-center text-sm text-gray-400">+ Every music video's cast, sets and props are already in the catalog.+ </div>+ ) : (+ <>+ <div className="flex flex-wrap items-center justify-between gap-2 bg-port-card border border-port-border rounded-lg p-3">+ <p className="text-sm text-gray-300">+ {formatCount(selections.length)} from {formatCount(projects.length)} {projects.length === 1 ? 'video' : 'videos'}. Matches to a universe record are linked, not copied.+ </p>+ <button+ type="button"+ onClick={handleImport}+ disabled={importing}+ className="inline-flex items-center gap-2 px-4 py-2 min-h-[40px] rounded-lg bg-port-accent text-white text-sm font-medium disabled:opacity-50"+ >+ {importing && <Loader2 size={14} className="animate-spin" aria-hidden="true" />}+ Import {formatCount(toCatalog)}+ </button>+ </div>+ {projects.map((project) => (+ <section key={project.projectId} aria-label={project.name} className="bg-port-card border border-port-border rounded-lg px-3 py-2 min-w-0">+ <h2 className="text-sm font-medium text-white pt-1">+ <Link to={`/music-video/${encodeURIComponent(project.projectId)}`} className="hover:text-port-accent">{project.name}</Link>+ </h2>+ <ul className="divide-y divide-port-border">+ {project.items.map((item) => (+ <ImportRow+ key={item.subjectId}+ project={project}+ item={item}+ action={actionFor(project, item)}+ onChange={(action) => setDecisions((d) => ({ ...d, [decisionKey(project.projectId, item.subjectId)]: action }))}+ />+ ))}+ </ul>+ </section>+ ))}+ </>+ )}+ </div>+ );+}diff --git a/client/src/pages/CreativeCastImport.test.jsx b/client/src/pages/CreativeCastImport.test.jsxnew file mode 100644index 0000000000..deb5330d2f--- /dev/null+++ b/client/src/pages/CreativeCastImport.test.jsx@@ -0,0 +1,62 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';+import { render, screen, fireEvent, waitFor } from '@testing-library/react';+import { MemoryRouter } from 'react-router';++vi.mock('../services/apiCatalog', () => ({+ previewMusicVideoCastImport: vi.fn(),+ commitMusicVideoCastImport: vi.fn(),+}));+vi.mock('../components/ui/Toast', () => ({ default: { success: vi.fn(), error: vi.fn() } }));+vi.mock('../components/MediaImage', () => ({+ default: ({ src, alt, ...rest }) => <img src={src} alt={alt} {...rest} />,+}));++import CreativeCastImport from './CreativeCastImport';+import { previewMusicVideoCastImport, commitMusicVideoCastImport } from '../services/apiCatalog';+import toast from '../components/ui/Toast';++const PREVIEW = { projects: [{ projectId: 'mv-1', name: 'Example Video', items: [+ { subjectId: 'cs-protagonist', kind: 'character', name: 'Ada', imageId: 'ada.png', action: 'create', ingredientId: 'cat-chr-mv-1' },+ { subjectId: 'mvc-2', kind: 'character', name: 'Cal', imageId: null, action: 'link', ingredientId: 'cat-chr-cal', ingredientName: 'Cal' },+ { subjectId: 'cs-set-diner', kind: 'place', name: 'Night diner', imageId: 'diner.png', action: 'create', ingredientId: 'cat-plc-mv-2' },+] }] };++const renderPage = () => render(<MemoryRouter><CreativeCastImport /></MemoryRouter>);++describe('CreativeCastImport', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ it('shows each video\'s proposals and imports the reviewed choices', async () => {+ previewMusicVideoCastImport.mockResolvedValueOnce(PREVIEW).mockResolvedValueOnce({ projects: [] });+ commitMusicVideoCastImport.mockResolvedValue({ projects: 1, created: 1, linked: 1, kept: 1 });+ renderPage();++ expect(await screen.findByRole('link', { name: 'Example Video' })).toHaveAttribute('href', '/music-video/mv-1');+ expect(screen.getByRole('img', { name: 'Ada' })).toHaveAttribute('src', '/data/images/ada.png');+ expect(screen.getByLabelText('What to do with Cal')).toHaveValue('link');+ fireEvent.change(screen.getByLabelText('What to do with Night diner'), { target: { value: 'local' } });+ fireEvent.click(screen.getByRole('button', { name: 'Import 2' }));++ await waitFor(() => expect(commitMusicVideoCastImport).toHaveBeenCalledWith([+ { projectId: 'mv-1', subjectId: 'cs-protagonist', action: 'create' },+ { projectId: 'mv-1', subjectId: 'mvc-2', action: 'link', ingredientId: 'cat-chr-cal' },+ { projectId: 'mv-1', subjectId: 'cs-set-diner', action: 'local' },+ ], { silent: true }));+ expect(toast.success).toHaveBeenCalledWith('Imported: 1 new, 1 linked, 1 kept in their videos');+ expect(await screen.findByText(/already in the catalog/)).toBeInTheDocument();+ });++ it('imports a large library in parts and totals the results', async () => {+ const items = Array.from({ length: 501 }, (_, i) => ({ subjectId: `mvc-${i}`, kind: 'object', name: `Prop ${i}`, imageId: null, action: 'create', ingredientId: `cat-obj-${i}` }));+ previewMusicVideoCastImport.mockResolvedValueOnce({ projects: [{ projectId: 'mv-1', name: 'Example Video', items }] }).mockResolvedValueOnce({ projects: [] });+ commitMusicVideoCastImport.mockImplementation(async (rows) => ({ projects: 1, created: rows.length, linked: 0, kept: 0 }));+ renderPage();++ fireEvent.click(await screen.findByRole('button', { name: 'Import 501' }));++ await waitFor(() => expect(toast.success).toHaveBeenCalledWith('Imported: 501 new, 0 linked, 0 kept in their videos'));+ expect(commitMusicVideoCastImport.mock.calls.map(([rows]) => rows.length)).toEqual([500, 1]);+ });+});diff --git a/client/src/pages/CreativeLibrary.jsx b/client/src/pages/CreativeLibrary.jsxindex 4cc7b84ffc..eeb010c4c3 100644--- a/client/src/pages/CreativeLibrary.jsx+++ b/client/src/pages/CreativeLibrary.jsx@@ -9,7 +9,7 @@import { useCallback, useEffect, useMemo, useState } from 'react';import { Link, useNavigate } from 'react-router';-import { Drama, Mountain, Package, Plus, Search, Loader2, Sparkles, Library } from 'lucide-react';+import { Drama, Mountain, Package, Plus, Search, Loader2, Sparkles, Library, Import } from 'lucide-react';import PageHeader from '../components/PageHeader';import MediaImage from '../components/MediaImage';import InfiniteScrollFooter from '../components/ui/InfiniteScrollFooter';@@ -121,6 +121,14 @@ export default function CreativeLibrary({ libraryId }) {)}actions={(<div className="flex items-center gap-2">+ <Link+ to="/casting/import"+ aria-label="Import from music videos"+ title="Import from music videos"+ className="inline-flex items-center gap-1.5 px-3 py-2 min-h-[40px] rounded-lg border border-port-border bg-port-card hover:bg-port-bg text-gray-300 hover:text-white text-sm"+ >+ <Import size={16} aria-hidden="true" /> <span className="hidden sm:inline">From videos</span>+ </Link><Linkto={`/catalog?type=${encodeURIComponent(library.type)}`}className="inline-flex items-center gap-1.5 px-3 py-2 min-h-[40px] rounded-lg border border-port-border bg-port-card hover:bg-port-bg text-gray-300 hover:text-white text-sm"diff --git a/client/src/services/apiCatalog.js b/client/src/services/apiCatalog.jsindex 6ed8e364f3..35fb32e8dd 100644--- a/client/src/services/apiCatalog.js+++ b/client/src/services/apiCatalog.js@@ -198,3 +198,8 @@ export const bulkImportCatalogIngredients = (body, options) =>export const rerunCatalogMigration = ({ force, ...options } = {}) =>request('/catalog/migration/rerun', { method: 'POST', body: JSON.stringify({ force }), ...options });++// Casting › Import from music videos: the dry run, then the reviewed decisions.+export const previewMusicVideoCastImport = (options) => request('/catalog/import/music-videos', options);+export const commitMusicVideoCastImport = (selections, options) =>+ request('/catalog/import/music-videos', { method: 'POST', body: JSON.stringify({ selections }), ...options });diff --git a/server/lib/catalogValidation.js b/server/lib/catalogValidation.jsindex 85b2a98ad3..6d4acab5c6 100644--- a/server/lib/catalogValidation.js+++ b/server/lib/catalogValidation.js@@ -514,6 +514,17 @@ export const catalogEmbeddingsBackfillSchema = z.object({includeStale: z.boolean().optional(),}).strict();+// Music video cast import commit (Casting › Import from music videos): one+// reviewed decision per subject. `local` keeps the subject in its video only.+export const catalogMusicVideoImportSchema = z.object({+ selections: z.array(z.object({+ projectId: z.string().min(1).max(128),+ subjectId: z.string().min(1).max(64),+ action: z.enum(['create', 'link', 'local']),+ ingredientId: z.string().min(1).max(128).optional(),+ }).strict().refine((s) => s.action !== 'link' || s.ingredientId, { message: 'link needs an ingredientId' })).min(1).max(2000),+}).strict();+// /migration/rerun — pass `force: true` to ignore the marker file.export const catalogMigrationRerunSchema = z.object({force: z.boolean().optional(),diff --git a/server/lib/musicVideoValidation.js b/server/lib/musicVideoValidation.jsindex 47d2490761..cce6cbaa8e 100644--- a/server/lib/musicVideoValidation.js+++ b/server/lib/musicVideoValidation.js@@ -124,6 +124,8 @@ export const musicVideoConceptSchema = z.object({// The catalog record this subject was cast from (Casting / Environments /// Objects). The project keeps its own name and description snapshot.ingredientId: z.string().max(128).optional(),+ // Kept in this video only: never offered for saving to the catalog.+ localOnly: z.boolean().optional(),}).strict()).max(24).optional(),}).strict();diff --git a/server/lib/navManifest.js b/server/lib/navManifest.jsindex fb2d8e4a23..b397d2ef32 100644--- a/server/lib/navManifest.js+++ b/server/lib/navManifest.js@@ -45,6 +45,8 @@ const RAW_NAV_COMMANDS = [{ id: 'nav.catalog.ingest', path: '/catalog/ingest', label: 'Catalog Ingest', section: 'Create', aliases: ['catalog-ingest', 'ingest', 'paste-scrap', 'extract-ingredients'], keywords: ['paste', 'snippet', 'scene', 'idea', 'extract', 'scrap', 'import-catalog'] },{ 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.create.casting', path: '/casting', label: 'Casting', section: 'Create', aliases: ['casting', 'cast', 'characters', 'actors', 'casting-sheets', 'cast-list'], keywords: ['character', 'casting sheet', 'turnaround', 'wardrobe', 'looks', 'performer', 'actor', 'reference'] },+ // ⌘K / voice only — no sidebar row: reached from the Casting, Environments and Objects headers.+ { id: 'nav.create.casting-import', path: '/casting/import', label: 'Import Cast from Music Videos', section: 'Create', aliases: ['import-cast', 'cast-import', 'import-sets', 'backfill-cast'], keywords: ['music video', 'casting sheet', 'set plate', 'catalog', 'backfill', 'import'] },{ id: 'nav.create.environments', path: '/environments', label: 'Environments', section: 'Create', aliases: ['environments', 'environment', 'sets', 'locations', 'places', 'set-list'], keywords: ['place', 'set', 'location', 'clean plate', 'background', 'scene setting', 'reference'] },{ id: 'nav.create.objects', path: '/objects', label: 'Objects', section: 'Create', aliases: ['objects', 'props', 'prop-list', 'items'], keywords: ['object', 'prop', 'artifact', 'talisman', 'macguffin', 'reference'] },{ id: 'nav.media', path: '/media', label: 'Media Gen', section: 'Create', aliases: ['media', 'media-gen', 'mediagen', 'generate'], keywords: ['image', 'video', 'render', 'art', 'movie'] },diff --git a/server/routes/catalog.js b/server/routes/catalog.jsindex f8b1531165..4fc72f826b 100644--- a/server/routes/catalog.js+++ b/server/routes/catalog.js@@ -30,6 +30,7 @@ import {catalogPruneRequestSchema,catalogEmbeddingsBackfillSchema,catalogMigrationRerunSchema,+ catalogMusicVideoImportSchema,catalogBulkImportSchema,catalogBulkEntrySchema,catalogExportQuerySchema,@@ -52,6 +53,7 @@ import { extractIngredientsForScrap } from '../services/catalogExtraction.js';import { ingestFromUrl, ingestFromFile, ingestFromVoice, ingestFromBrain } from '../services/catalogIngestSources.js';import { readImageGenerationMetadata, uploadIngredientMediaFile, recordIngredientVoiceMemo } from '../services/catalogMedia.js';import { migrateBibleToCatalog } from '../scripts/migrateBibleToCatalog.js';+import { previewCatalogCastImport, commitCatalogCastImport } from '../services/musicVideo/catalogCast.js';import { PORTOS_SCHEMA_VERSIONS } from '../lib/schemaVersions.js';const router = Router();@@ -867,6 +869,18 @@ router.post('/migration/rerun', asyncHandler(async (req, res) => {res.json(result);}));+// Music video cast import: every video's cast, sets and props not yet in the+// catalog, each with a proposed create/link (dry run), then the reviewed+// decisions applied. Deterministic ids make a repeated commit a no-op.+router.get('/import/music-videos', asyncHandler(async (req, res) => {+ res.json({ projects: await previewCatalogCastImport() });+}));++router.post('/import/music-videos', asyncHandler(async (req, res) => {+ const { selections } = validateRequest(catalogMusicVideoImportSchema, req.body || {});+ res.json(await commitCatalogCastImport(selections));+}));+// --- User-defined ingredient types --------------------------------------// User types live in PostgreSQL (`catalog_user_types`, #1001 — formerly the// settings.json `catalogUserTypes` slice) and merge into the active typediff --git a/server/services/musicVideo/castAndSetsPlan.js b/server/services/musicVideo/castAndSetsPlan.jsindex 970458bad6..8f1c9bae51 100644--- a/server/services/musicVideo/castAndSetsPlan.js+++ b/server/services/musicVideo/castAndSetsPlan.js@@ -399,6 +399,14 @@ export function castAndSetsSubjects(project, stage) {description: trimTo([set.description, set.lighting && `Light: ${set.lighting}`].filter(Boolean).join(' '), 1000),});}- const fresh = ours.filter((s) => s.name && !taken.has(`${s.kind}:${s.name.toLowerCase()}`));+ // A re-approval keeps each subject's catalog link and keep-local choice.+ const previous = new Map((project?.concept?.subjects || []).map((s) => [s.id, s]));+ const fresh = ours+ .filter((s) => s.name && !taken.has(`${s.kind}:${s.name.toLowerCase()}`))+ .map((s) => {+ const prior = previous.get(s.id);+ if (prior?.kind !== s.kind) return s;+ return { ...s, ...(prior.ingredientId ? { ingredientId: prior.ingredientId } : {}), ...(prior.localOnly ? { localOnly: true } : {}) };+ });return [...authored, ...fresh].slice(0, MAX_SUBJECTS);}diff --git a/server/services/musicVideo/castAndSetsService.js b/server/services/musicVideo/castAndSetsService.jsindex b57f800ecf..41117a67b4 100644--- a/server/services/musicVideo/castAndSetsService.js+++ b/server/services/musicVideo/castAndSetsService.js@@ -546,6 +546,15 @@ async function assemble(projectId) {// ---- approval ------------------------------------------------------------------------+// Save the approved check-in's new cast and sets to the catalog (Casting /+// Environments), then show the stamped subjects. The approval already landed.+function queueCheckinCastToCatalog(projectId) {+ import('./catalogCast.js')+ .then(({ saveCheckinCastToCatalog }) => saveCheckinCastToCatalog(projectId))+ .then((result) => { if (result?.project) publish(projectId, result.project); })+ .catch((err) => console.error(`❌ Music Video Cast & Sets ${short(projectId)}: saving cast to the catalog failed: ${err.message}`));+}+/*** Apply an approved check-in to the project (references, subjects), approve* its artifact, and re-base a production run that was waiting on it.@@ -589,6 +598,7 @@ export async function approveCastAndSets(projectId) {});console.log(`✅ Music Video Cast & Sets ${short(projectId)} approved (r${out.stage.revision})`);publish(projectId, out.project);+ queueCheckinCastToCatalog(projectId);return { project: out.project, stage: presentCastAndSets(out.stage, PROCESS_ID) };}diff --git a/server/services/musicVideo/catalogCast.js b/server/services/musicVideo/catalogCast.jsnew file mode 100644index 0000000000..319593e6af--- /dev/null+++ b/server/services/musicVideo/catalogCast.js@@ -0,0 +1,212 @@+// Saves a music video's cast, sets and props to the catalog so Casting,+// Environments and Objects hold them for reuse. Two callers share it: approving+// Cast & Sets saves the check-in's new cast automatically, and the importer+// (dry run, review, commit) backfills videos made before the catalog link.+//+// A subject is saved by stamping `ingredientId` on it; catalogLinks.js then+// keeps the music-video ref in step. `localOnly` marks a subject the director+// keeps in this video only, so neither caller offers it again.+//+// Catalog ids are deterministic per (project, subject), like the universe canon+// promotion, so two machines saving the same synced video converge on one row.++import { createHash } from 'crypto';+import { isFileBackend } from '../../lib/pgFileFacade.js';+import { trimTo } from '../../lib/textUtils.js';+import { CAST_SETS_SUBJECT_PREFIX } from './castAndSetsPlan.js';++const TYPE_PREFIX = { character: 'chr', place: 'plc', object: 'obj' };+const PRIMARY_KEY = { character: 'physicalDescription', place: 'description', object: 'description' };+const UNIVERSE_FIELD = { character: 'characters', place: 'places', object: 'objects' };+const REFERENCE_ROLE = { character: 'character', place: 'set', object: 'prop' };++function musicVideoCastIngredientId(projectId, subject) {+ const seed = `music-video:${projectId}:${subject.kind}:${subject.id}`;+ return `cat-${TYPE_PREFIX[subject.kind]}-mv-${createHash('sha256').update(seed).digest('hex').slice(0, 32)}`;+}++// The Cast & Sets image behind each check-in subject: the protagonist's+// character sheet, a supporting cast sheet, or a set plate.+function checkinImages(project) {+ const stage = project?.castAndSets;+ if (stage?.status !== 'approved') return new Map();+ const images = stage.images || {};+ const done = (key) => (images[key]?.status === 'done' && images[key].imageId) || null;+ const out = new Map([[`${CAST_SETS_SUBJECT_PREFIX}protagonist`, done('character')]]);+ for (const c of stage.direction?.cast || []) out.set(`${CAST_SETS_SUBJECT_PREFIX}cast-${c.id}`.slice(0, 64), done(`cast:${c.id}`));+ for (const set of stage.direction?.sets || []) out.set(`${CAST_SETS_SUBJECT_PREFIX}set-${set.id}`.slice(0, 64), done(`set:${set.id}`));+ return out;+}++// A director-cast subject's image: the look reference pulled for it by name.+function referenceImage(project, subject) {+ const ref = (project?.visualSpec?.references || [])+ .find((r) => r.imageId && r.role === REFERENCE_ROLE[subject.kind] && String(r.label || '').trim().toLowerCase() === subject.name.trim().toLowerCase());+ return ref?.imageId || null;+}++/**+ * The subjects of a project not yet in the catalog, with the image that shows+ * each. `checkinOnly` limits it to the ones Cast & Sets created.+ */+function catalogCastCandidates(project, { checkinOnly = false } = {}) {+ if (!project || project.deleted) return [];+ const sheets = checkinImages(project);+ return (project.concept?.subjects || [])+ .filter((s) => s?.id && s.name && TYPE_PREFIX[s.kind] && !s.ingredientId && !s.localOnly)+ .filter((s) => !checkinOnly || s.id.startsWith(CAST_SETS_SUBJECT_PREFIX))+ .map((s) => ({+ subjectId: s.id,+ kind: s.kind,+ name: s.name,+ description: s.description || '',+ canonId: s.canonId || null,+ imageId: sheets.get(s.id) || referenceImage(project, s),+ }));+}++/**+ * Decide each candidate: link to the universe entry it was cast from, link to+ * a same-named record of the video's universe, link to the row a synced machine+ * already saved, or create. Reads only.+ */+async function planCatalogCast(project, candidates, deps) {+ const { catalogDB, getUniverse } = deps;+ const universeId = project.concept?.universeId || null;+ const universe = universeId ? await getUniverse(universeId).catch(() => null) : null;+ const universeRows = universeId ? await catalogDB.listIngredientsForRef('universe', universeId) : [];+ const plan = [];+ for (const candidate of candidates) {+ const canon = candidate.canonId && universe+ ? (universe[UNIVERSE_FIELD[candidate.kind]] || []).find((e) => e.id === candidate.canonId && e.ingredientId)+ : null;+ const named = universeRows.find(({ ingredient }) => ingredient.type === candidate.kind+ && ingredient.name.trim().toLowerCase() === candidate.name.trim().toLowerCase())?.ingredient;+ const ownId = musicVideoCastIngredientId(project.id, { id: candidate.subjectId, kind: candidate.kind });+ const target = canon ? { id: canon.ingredientId, name: canon.name } : named || await catalogDB.getIngredient(ownId);+ plan.push(target+ ? { ...candidate, action: 'link', ingredientId: target.id, ingredientName: target.name }+ : { ...candidate, action: 'create', ingredientId: ownId });+ }+ return plan;+}++// Creates the record and attaches its image. False when a row already sits at+// the id but was deleted: the director removed it, so it is not brought back.+async function createRecord(project, item, catalogDB) {+ const payload = item.description ? { [PRIMARY_KEY[item.kind]]: trimTo(item.description, 4000) } : {};+ const tags = project.name ? [trimTo(project.name, 60)] : [];+ const created = await catalogDB.createIngredient({ id: item.ingredientId, type: item.kind, name: item.name, payload, tags })+ .then(() => true)+ .catch(async (err) => {+ if (err?.code !== '23505') throw err;+ // A synced machine saved the same subject first: same deterministic id.+ return Boolean(await catalogDB.getIngredient(item.ingredientId));+ });+ if (created && item.imageId) {+ await catalogDB.attachMedia(item.ingredientId, item.imageId, 'reference', { caption: `From ${trimTo(project.name || 'a music video', 100)}` });+ }+ return created;+}++/**+ * Apply decisions to one project. `create` makes the catalog record (with its+ * image), `link` reuses one, and `local` keeps the subject in this video only.+ * Stamps the subjects in one write and returns the saved project.+ */+async function commitCatalogCast(projectId, decisions, deps) {+ const { catalogDB, getProject, mutateProjectRecord, queueProjectCatalogLinkSync } = deps;+ const project = await getProject(projectId);+ if (!project || project.deleted || !decisions.length) return { project, created: 0, linked: 0, kept: 0 };+ const images = new Map(catalogCastCandidates(project).map((c) => [c.subjectId, c.imageId]));+ const stamps = new Map();+ const stats = { created: 0, linked: 0, kept: 0 };+ for (const d of decisions) {+ const subject = (project.concept?.subjects || []).find((s) => s.id === d.subjectId);+ if (!subject || subject.ingredientId) continue;+ if (d.action === 'local') {+ stamps.set(subject.id, { localOnly: true });+ stats.kept++;+ } else if (d.action === 'create') {+ const item = { kind: subject.kind, name: subject.name, description: subject.description || '', imageId: images.get(subject.id) || null, ingredientId: musicVideoCastIngredientId(projectId, subject) };+ if (await createRecord(project, item, catalogDB)) {+ stamps.set(subject.id, { ingredientId: item.ingredientId });+ stats.created++;+ } else {+ stamps.set(subject.id, { localOnly: true });+ stats.kept++;+ }+ } else if (d.action === 'link' && d.ingredientId) {+ const target = await catalogDB.getIngredient(d.ingredientId);+ if (!target || target.type !== subject.kind) continue;+ stamps.set(subject.id, { ingredientId: target.id });+ stats.linked++;+ }+ }+ if (!stamps.size) return { project, ...stats };+ const { project: saved } = await mutateProjectRecord(projectId, (current) => ({+ project: {+ ...current,+ concept: {+ ...(current.concept || {}),+ subjects: (current.concept?.subjects || []).map((s) => (stamps.has(s.id) && !s.ingredientId ? { ...s, ...stamps.get(s.id) } : s)),+ },+ },+ }));+ queueProjectCatalogLinkSync(projectId);+ return { project: saved, ...stats };+}++async function defaultDeps() {+ const [catalogDB, projects, { getUniverse }, { queueProjectCatalogLinkSync }] = await Promise.all([+ import('../catalogDB.js'),+ import('./projects.js'),+ import('../universeBuilder.js'),+ import('./catalogLinks.js'),+ ]);+ return { catalogDB, getUniverse, getProject: projects.getProject, listProjects: projects.listProjects, mutateProjectRecord: projects.mutateProjectRecord, queueProjectCatalogLinkSync };+}++/**+ * After Cast & Sets is approved: save the check-in's new cast, sets and their+ * sheets to the catalog, reusing universe records where they match. No+ * provider calls; Postgres backend only.+ */+export async function saveCheckinCastToCatalog(projectId, deps = null) {+ if (isFileBackend()) return null;+ const d = deps || await defaultDeps();+ const project = await d.getProject(projectId);+ const candidates = catalogCastCandidates(project, { checkinOnly: true });+ if (!candidates.length) return null;+ const plan = await planCatalogCast(project, candidates, d);+ return commitCatalogCast(projectId, plan.map(({ subjectId, action, ingredientId }) => ({ subjectId, action, ingredientId })), d);+}++/** The importer's dry run: every live video's uncatalogued subjects, decided. */+export async function previewCatalogCastImport(deps = null) {+ const d = deps || await defaultDeps();+ const out = [];+ for (const project of await d.listProjects()) {+ const candidates = catalogCastCandidates(project);+ if (!candidates.length) continue;+ out.push({ projectId: project.id, name: project.name || 'Untitled', items: await planCatalogCast(project, candidates, d) });+ }+ return out;+}++/** The importer's commit: the reviewed decisions, grouped by project. */+export async function commitCatalogCastImport(selections, deps = null) {+ const d = deps || await defaultDeps();+ const byProject = new Map();+ for (const s of selections) byProject.set(s.projectId, [...(byProject.get(s.projectId) || []), s]);+ const totals = { projects: 0, created: 0, linked: 0, kept: 0 };+ for (const [projectId, decisions] of byProject) {+ const result = await commitCatalogCast(projectId, decisions, d);+ if (result.created + result.linked + result.kept) totals.projects++;+ totals.created += result.created;+ totals.linked += result.linked;+ totals.kept += result.kept;+ }+ console.log(`🎭 Music video cast import: ${totals.created} created, ${totals.linked} linked, ${totals.kept} kept in their videos (${totals.projects} videos)`);+ return totals;+}diff --git a/server/services/musicVideo/catalogCast.test.js b/server/services/musicVideo/catalogCast.test.jsnew file mode 100644index 0000000000..4df2222670--- /dev/null+++ b/server/services/musicVideo/catalogCast.test.js@@ -0,0 +1,186 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';++vi.mock('../../lib/pgFileFacade.js', () => ({ isFileBackend: () => false }));++import { createHash } from 'crypto';++const { saveCheckinCastToCatalog, previewCatalogCastImport, commitCatalogCastImport } = await import('./catalogCast.js');++// The deterministic catalog id two synced machines both derive for a subject.+const PREFIX = { character: 'chr', place: 'plc', object: 'obj' };+const musicVideoCastIngredientId = (projectId, { id, kind }) =>+ `cat-${PREFIX[kind]}-mv-${createHash('sha256').update(`music-video:${projectId}:${kind}:${id}`).digest('hex').slice(0, 32)}`;++// In-memory catalog + project store behind the injected deps.+function makeDeps({ projects, universes = {}, rows = [], universeLinks = {} }) {+ const ingredients = new Map(rows.map((r) => [r.id, { deleted: false, ...r }]));+ const media = [];+ const catalogDB = {+ getIngredient: vi.fn(async (id) => { const r = ingredients.get(id); return r && !r.deleted ? r : null; }),+ createIngredient: vi.fn(async (input) => {+ if (ingredients.has(input.id)) throw Object.assign(new Error('duplicate key'), { code: '23505' });+ ingredients.set(input.id, { ...input, deleted: false });+ return input;+ }),+ attachMedia: vi.fn(async (id, key, kind, opts) => { media.push({ id, key, kind, caption: opts?.caption }); }),+ listIngredientsForRef: vi.fn(async (kind, refId) => (universeLinks[refId] || []).map((id) => ({ ingredient: ingredients.get(id), role: 'cast' }))),+ };+ const deps = {+ catalogDB,+ getUniverse: vi.fn(async (id) => { if (!universes[id]) throw Object.assign(new Error('Universe not found'), { code: 'NOT_FOUND' }); return universes[id]; }),+ getProject: vi.fn(async (id) => projects.find((p) => p.id === id) || null),+ listProjects: vi.fn(async () => projects.filter((p) => !p.deleted)),+ mutateProjectRecord: vi.fn(async (id, transform) => {+ const i = projects.findIndex((p) => p.id === id);+ const { project } = transform(projects[i]);+ projects[i] = project;+ return { project };+ }),+ queueProjectCatalogLinkSync: vi.fn(),+ };+ return { deps, ingredients, media };+}++const approvedStage = {+ status: 'approved',+ direction: { protagonist: { name: 'Ada' }, cast: [{ id: 'bo', name: 'Bo' }], sets: [{ id: 'diner', name: 'Night diner' }] },+ images: {+ character: { status: 'done', imageId: 'ada-sheet.png' },+ 'cast:bo': { status: 'failed', imageId: null },+ 'set:diner': { status: 'done', imageId: 'diner-plate.png' },+ },+};++const videoProject = () => ({+ id: 'mv-1',+ name: 'Example Video',+ castAndSets: approvedStage,+ visualSpec: { references: [{ id: 'r1', imageId: 'guitar.png', role: 'prop', label: 'Glass guitar' }] },+ concept: {+ universeId: 'u-1',+ subjects: [+ { id: 'cs-protagonist', kind: 'character', name: 'Ada', description: 'Red scarf' },+ { id: 'cs-cast-bo', kind: 'character', name: 'Bo' },+ { id: 'cs-set-diner', kind: 'place', name: 'Night diner', description: 'Chrome booths' },+ { id: 'mvc-1', kind: 'object', name: 'Glass guitar' },+ { id: 'mvc-2', kind: 'character', name: 'Cal', canonId: 'c-cal' },+ { id: 'mvc-3', kind: 'place', name: 'Linked', ingredientId: 'cat-plc-9' },+ { id: 'mvc-4', kind: 'object', name: 'Private', localOnly: true },+ ],+ },+});++describe('which subjects are offered', () => {+ it('offers uncatalogued subjects with their sheet, plate or pulled reference image, and saves only check-in ones on approval', async () => {+ const projects = [videoProject()];+ const { deps } = makeDeps({ projects });+ const [preview] = await previewCatalogCastImport(deps);+ expect(preview.items.map((i) => [i.subjectId, i.imageId])).toEqual([+ ['cs-protagonist', 'ada-sheet.png'],+ ['cs-cast-bo', null],+ ['cs-set-diner', 'diner-plate.png'],+ ['mvc-1', 'guitar.png'],+ ['mvc-2', null],+ ]);+ await saveCheckinCastToCatalog('mv-1', deps);+ expect(projects[0].concept.subjects.filter((s) => s.ingredientId && s.id !== 'mvc-3').map((s) => s.id)).toEqual(['cs-protagonist', 'cs-cast-bo', 'cs-set-diner']);+ });+});++describe('saving approved Cast & Sets cast', () => {+ let projects;+ beforeEach(() => { projects = [videoProject()]; });++ it('creates check-in cast and sets with their images, reusing a same-named universe record', async () => {+ const { deps, ingredients, media } = makeDeps({+ projects,+ universes: { 'u-1': { id: 'u-1', characters: [] } },+ rows: [{ id: 'cat-chr-bo', type: 'character', name: 'bo' }],+ universeLinks: { 'u-1': ['cat-chr-bo'] },+ });++ const result = await saveCheckinCastToCatalog('mv-1', deps);++ expect(result).toMatchObject({ created: 2, linked: 1, kept: 0 });+ const leadId = musicVideoCastIngredientId('mv-1', { id: 'cs-protagonist', kind: 'character' });+ expect(leadId).toMatch(/^cat-chr-mv-[0-9a-f]{32}$/);+ expect(ingredients.get(leadId)).toMatchObject({ type: 'character', name: 'Ada', payload: { physicalDescription: 'Red scarf' }, tags: ['Example Video'] });+ expect(media).toEqual([+ { id: leadId, key: 'ada-sheet.png', kind: 'reference', caption: 'From Example Video' },+ expect.objectContaining({ key: 'diner-plate.png', kind: 'reference' }),+ ]);+ const subjects = projects[0].concept.subjects;+ expect(subjects.find((s) => s.id === 'cs-protagonist').ingredientId).toBe(leadId);+ expect(subjects.find((s) => s.id === 'cs-cast-bo').ingredientId).toBe('cat-chr-bo');+ expect(subjects.find((s) => s.id === 'mvc-1').ingredientId).toBeUndefined();+ expect(deps.queueProjectCatalogLinkSync).toHaveBeenCalledWith('mv-1');+ });++ it('links to the row a synced machine already saved, and leaves a subject whose record was deleted in the video', async () => {+ const leadId = musicVideoCastIngredientId('mv-1', { id: 'cs-protagonist', kind: 'character' });+ const dinerId = musicVideoCastIngredientId('mv-1', { id: 'cs-set-diner', kind: 'place' });+ const { deps } = makeDeps({+ projects,+ rows: [{ id: leadId, type: 'character', name: 'Ada' }, { id: dinerId, type: 'place', name: 'Night diner', deleted: true }],+ });++ const result = await saveCheckinCastToCatalog('mv-1', deps);++ expect(result).toMatchObject({ created: 1, linked: 1, kept: 1 });+ const subjects = projects[0].concept.subjects;+ expect(subjects.find((s) => s.id === 'cs-protagonist').ingredientId).toBe(leadId);+ expect(subjects.find((s) => s.id === 'cs-set-diner')).toMatchObject({ localOnly: true });+ expect(subjects.find((s) => s.id === 'cs-set-diner').ingredientId).toBeUndefined();+ });+});++describe('music video cast import', () => {+ it('previews every video with a proposal, then applies the reviewed decisions', async () => {+ const projects = [videoProject(), { id: 'mv-2', name: 'Done', concept: { subjects: [{ id: 'a', kind: 'place', name: 'X', ingredientId: 'cat-plc-1' }] } }];+ const { deps, ingredients } = makeDeps({+ projects,+ universes: { 'u-1': { id: 'u-1', characters: [{ id: 'c-cal', name: 'Cal', ingredientId: 'cat-chr-cal' }] } },+ rows: [{ id: 'cat-chr-cal', type: 'character', name: 'Cal' }],+ });++ const preview = await previewCatalogCastImport(deps);+ expect(preview).toHaveLength(1);+ expect(preview[0]).toMatchObject({ projectId: 'mv-1', name: 'Example Video' });+ expect(preview[0].items.find((i) => i.subjectId === 'mvc-2')).toMatchObject({ action: 'link', ingredientId: 'cat-chr-cal', ingredientName: 'Cal' });+ expect(preview[0].items.find((i) => i.subjectId === 'mvc-1')).toMatchObject({ action: 'create' });++ const totals = await commitCatalogCastImport([+ { projectId: 'mv-1', subjectId: 'mvc-2', action: 'link', ingredientId: 'cat-chr-cal' },+ { projectId: 'mv-1', subjectId: 'mvc-1', action: 'create' },+ { projectId: 'mv-1', subjectId: 'cs-cast-bo', action: 'local' },+ { projectId: 'mv-1', subjectId: 'cs-set-diner', action: 'link', ingredientId: 'cat-chr-cal' },+ ], deps);++ expect(totals).toEqual({ projects: 1, created: 1, linked: 1, kept: 1 });+ const subjects = projects[0].concept.subjects;+ expect(subjects.find((s) => s.id === 'mvc-2').ingredientId).toBe('cat-chr-cal');+ expect(ingredients.get(subjects.find((s) => s.id === 'mvc-1').ingredientId)).toMatchObject({ type: 'object', name: 'Glass guitar' });+ expect(subjects.find((s) => s.id === 'cs-cast-bo').localOnly).toBe(true);+ // A link to a record of another type is refused.+ expect(subjects.find((s) => s.id === 'cs-set-diner').ingredientId).toBeUndefined();++ // Committing again changes nothing.+ expect(await commitCatalogCastImport([{ projectId: 'mv-1', subjectId: 'mvc-1', action: 'create' }], deps)).toEqual({ projects: 0, created: 0, linked: 0, kept: 0 });+ });+});++describe('re-approving Cast & Sets', () => {+ it('keeps each regenerated subject\'s catalog link and keep-local choice', async () => {+ const { castAndSetsSubjects } = await import('./castAndSetsPlan.js');+ const project = { concept: { subjects: [+ { id: 'cs-protagonist', kind: 'character', name: 'Ada', ingredientId: 'cat-chr-ada' },+ { id: 'cs-set-diner', kind: 'place', name: 'Night diner', localOnly: true },+ ] } };+ const stage = { direction: { protagonist: { name: 'Ada', face: 'Freckles' }, sets: [{ id: 'diner', name: 'Night diner' }, { id: 'roof', name: 'Rooftop' }] } };+ expect(castAndSetsSubjects(project, stage)).toEqual([+ expect.objectContaining({ id: 'cs-protagonist', description: 'Freckles', ingredientId: 'cat-chr-ada' }),+ expect.objectContaining({ id: 'cs-set-diner', localOnly: true }),+ expect.not.objectContaining({ ingredientId: expect.anything() }),+ ]);+ });+});diff --git a/server/services/musicVideo/productionReview.js b/server/services/musicVideo/productionReview.jsindex bbb5fde787..fd3a29edfa 100644--- a/server/services/musicVideo/productionReview.js+++ b/server/services/musicVideo/productionReview.js@@ -399,10 +399,21 @@ function setClipLocks(project, scenes, { locked, reviewer, approvedBy }) {const storyboardApprovalCurrent = (approval, basis) => !!approval&& (approval.basis === basis.storyboard || (!!basis.storyboardShots && approval.shotsBasis === basis.storyboardShots));+// A subject's catalog link and keep-local choice are bookkeeping saved after an+// approval (catalogCast.js), never a change to who or what was approved.+const CATALOG_SUBJECT_KEYS = ['ingredientId', 'localOnly'];+const withoutCatalogFields = subjects => (subjects || []).map(s => (s && typeof s === 'object' ? Object.fromEntries(Object.entries(s).filter(([k]) => !CATALOG_SUBJECT_KEYS.includes(k))) : s));+const approvalConcept = concept => (concept?.subjects ? { ...concept, subjects: withoutCatalogFields(concept.subjects) } : concept);+// Restoring approved subjects keeps the catalog fields saved since.+const keepCatalogFields = (subjects, current) => {+ const byId = new Map((current || []).map(s => [s?.id, s]));+ return (subjects || []).map(s => ({ ...s, ...Object.fromEntries(CATALOG_SUBJECT_KEYS.filter(k => byId.get(s?.id)?.[k] !== undefined).map(k => [k, byId.get(s.id)[k]])) }));+};+export function productionReviewBasis(project) {const draft = project.productionReview?.draft || {};const art = hash({ projectId: project.id, mediaMode: project.mediaMode, authoringRenderer: project.composition?.authoringRenderer, mode: project.composition?.mode, policy: project.productionPolicy,- concept: project.concept, visualSpec: project.visualSpec, styleReferences: project.styleReferences,+ concept: approvalConcept(project.concept), visualSpec: project.visualSpec, styleReferences: project.styleReferences,direction: project.castAndSets?.direction,cast: draft.cast, environments: draft.environments, visualLanguage: draft.visualLanguage,motionLanguage: draft.motionLanguage, implementationPlan: draft.implementationPlan, guide: artifactBasis(artifact(project, draft.guideArtifactId)) });@@ -435,7 +446,7 @@ const h = v => hash(v ?? null);function productionApprovalInputs(project) {const draft = project.productionReview?.draft || {};const art = {- concept: h(project.concept), 'visual spec': h(project.visualSpec), 'style references': h(project.styleReferences),+ concept: h(approvalConcept(project.concept)), 'visual spec': h(project.visualSpec), 'style references': h(project.styleReferences),'media mode': h([project.mediaMode, project.composition?.authoringRenderer, project.composition?.mode, project.productionPolicy]),'art direction': h(project.castAndSets?.direction), cast: h(draft.cast), environments: h(draft.environments),'visual language': h(draft.visualLanguage), 'motion language': h(draft.motionLanguage),@@ -534,7 +545,7 @@ export function castAndSetsApprovalInputs(project) {concept: h(concept),style: h([style || '', universeStyle || '', moodBoardStyle || '', spec.palette || [], spec.typography || '',spec.cameraRules || '', spec.moodBoardId || null, project.styleReferences ?? null]),- subjects: h([subjects || [], (spec.references || []).map(r => r?.imageId || null)]),+ subjects: h([withoutCatalogFields(subjects), (spec.references || []).map(r => r?.imageId || null)]),song: h([project.trackId || null, project.uploadedAudioFilename || null]),};}@@ -772,7 +783,7 @@ function restoreScenePrompt(project, value) {function restoreCastAndSets(project, field, value) {const concept = objectConcept(project);if (field === 'concept') return { ...project, concept: { ...value, ...pick(concept, ['subjects', ...CAST_SETS_CONCEPT_STYLE_KEYS]) } };- if (field === 'subjects') return { ...project, concept: { ...concept, subjects: value } };+ if (field === 'subjects') return { ...project, concept: { ...concept, subjects: keepCatalogFields(value, concept.subjects) } };const { styleReferences, ...rest } = value;const nextConcept = { ...concept };for (const k of CAST_SETS_CONCEPT_STYLE_KEYS) delete nextConcept[k];@@ -805,7 +816,7 @@ export function revertApprovedInput(project, { stage, field }) {const value = record.values?.[field];if (value === undefined) throw unavailable('The approved value of that input was not kept, so it cannot be restored.');if (cast) return restoreCastAndSets(project, field, value);- if (field === 'concept') return { ...project, concept: value };+ if (field === 'concept') return { ...project, concept: value?.subjects ? { ...value, subjects: keepCatalogFields(value.subjects, project.concept?.subjects) } : value };if (DRAFT_FIELD_LABELS[field]) return { ...project, productionReview: { ...project.productionReview,draft: { ...project.productionReview?.draft, [DRAFT_FIELD_LABELS[field]]: value } } };if (SCENE_PROMPT_LABEL.test(field)) return restoreScenePrompt(project, value);diff --git a/server/services/musicVideo/productionReview.stale.test.js b/server/services/musicVideo/productionReview.stale.test.jsindex a7dc83bbc7..2d53c9a1a2 100644--- a/server/services/musicVideo/productionReview.stale.test.js+++ b/server/services/musicVideo/productionReview.stale.test.js@@ -49,6 +49,23 @@ describe('Cast & Sets approval basis', () => {});});+describe('saving cast to the catalog after approval', () => {+ const project = { id: 'p1', concept: { prompt: 'Example concept', subjects: [{ id: 'cs-protagonist', kind: 'character', name: 'Ada' }, { id: 's2', kind: 'place', name: 'Diner' }] },+ visualSpec: {}, scenes: [], productionReview: { draft: {} } };+ const stamp = (p) => ({ ...p, concept: { ...p.concept, subjects: [{ ...p.concept.subjects[0], ingredientId: 'cat-chr-1' }, { ...p.concept.subjects[1], localOnly: true }] } });++ it('leaves the Cast & Sets and art approvals current, and a subject revert keeps the catalog link', () => {+ const approved = approvedArt({ ...project, castAndSets: { status: 'approved', approvedAt: '2026-01-01T00:00:00.000Z', approvedInputs: castAndSetsApprovalInputs(project), approvedValues: castAndSetsApprovalValues(project) } });+ const stamped = stamp(approved);+ expect(castAndSetsApproval(stamped).stale).toBeNull();+ expect(productionReadiness(stamped).art.stale).toBeNull();++ const renamed = { ...stamped, concept: { ...stamped.concept, subjects: [{ ...stamped.concept.subjects[0], name: 'Ada Lane' }, stamped.concept.subjects[1]] } };+ const reverted = revertApprovedInput(renamed, { stage: 'castAndSets', field: 'subjects' });+ expect(reverted.concept.subjects).toEqual(stamp(project).concept.subjects);+ });+});+describe('reverting a Cast & Sets approval (#10241)', () => {const project = { id: 'p1', concept: { prompt: 'Example concept', style: 'ink', subjects: [{ id: 's1' }] }, visualSpec: { palette: ['#000000'] } };const approved = { ...project, castAndSets: { status: 'approved', approvedInputs: castAndSetsApprovalInputs(project), approvedValues: castAndSetsApprovalValues(project) } };