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
feat: one Look references list and uniform model routing for treatment (#10223)
Adam Eivy19e9b0962d23
diff --git a/client/src/components/musicVideo/AutopilotPanel.jsx b/client/src/components/musicVideo/AutopilotPanel.jsxindex c7f628670c..ff65d120cf 100644--- a/client/src/components/musicVideo/AutopilotPanel.jsx+++ b/client/src/components/musicVideo/AutopilotPanel.jsx@@ -37,7 +37,7 @@ const routeLabel = (route) => `${toolLabel.get(`${route.kind}:${route.mode}`) ||const ROUTE_LABELS = [['brief', 'Creative brief'], ['lyrics', 'Lyrics draft'], ['lyricsReview', 'Lyrics review'],- ['plan', 'Shot planning'], ['castAndSets', 'Cast & Sets direction'],+ ['plan', 'Shot planning'], ['castAndSets', 'Cast & Sets direction'], ['treatment', 'Treatment compile'],];const initialPool = (project) => {diff --git a/client/src/components/musicVideo/CastAndSetsCheckin.jsx b/client/src/components/musicVideo/CastAndSetsCheckin.jsxindex 6fc01ed103..37ba9ffb07 100644--- a/client/src/components/musicVideo/CastAndSetsCheckin.jsx+++ b/client/src/components/musicVideo/CastAndSetsCheckin.jsx@@ -1,4 +1,5 @@import { CheckCircle2, Eye, Play, RotateCcw, SkipForward, Users } from 'lucide-react';+import LlmRouteNote from './LlmRouteNote.jsx';import Pill from '../ui/Pill.jsx';import CastAndSetsDirectionEditor from './CastAndSetsDirectionEditor.jsx';import CastAndSetsReferenceProgress from './CastAndSetsReferenceProgress.jsx';@@ -47,6 +48,7 @@ export default function CastAndSetsCheckin({ project, busy, onOpenSheet, onAppro<span className="text-sm font-medium">Cast & Sets check-in</span><Pill size="xs" tone={tone}>{stage.interrupted ? 'interrupted' : stage.status}</Pill>{stage.revision > 1 && <span className="text-[11px] text-port-text-muted">revision {stage.revision}</span>}+ <LlmRouteNote route={project.automation?.routes?.castAndSets} prefix="Direction ran on" /></div><p className={`text-xs ${stage.status === 'review' ? 'text-port-warning' : 'text-port-text-muted'}`} role="status">{statusLine(stage)}</p><CastAndSetsReferenceProgress stage={stage} />diff --git a/client/src/components/musicVideo/CreativeSetupPanel.jsx b/client/src/components/musicVideo/CreativeSetupPanel.jsxindex 903ec0bc99..e0f44db0ca 100644--- a/client/src/components/musicVideo/CreativeSetupPanel.jsx+++ b/client/src/components/musicVideo/CreativeSetupPanel.jsx@@ -3,7 +3,6 @@ import { musicVideoToolPolicyConflict } from '../../../../server/lib/musicVideoMimport { formatCount } from '../../utils/formatters.js';import { Link } from 'react-router';import { listUniverseNames, getUniverse } from '../../services/apiUniverseBuilder.js';-import MoodBoardReferenceStrip from '../moodBoard/MoodBoardReferenceStrip.jsx';import { uuidv4 } from '../../lib/uuid.js';import { pullUniverseCanonReferences } from '../../lib/musicVideoUniverseRefs.js';@@ -60,7 +59,7 @@ export default function CreativeSetupPanel({ project, onSave, onPendingChange })}, [editing, universeId]);const begin = () => {- setDraft({ universeId: project.concept?.universeId || '', subjects: project.concept?.subjects || [], moodBoardId: project.visualSpec?.moodBoardId || '' });+ setDraft({ universeId: project.concept?.universeId || '', subjects: project.concept?.subjects || [] });setSelectedCanon([]);setNewName('');setNewDescription('');@@ -85,14 +84,12 @@ export default function CreativeSetupPanel({ project, onSave, onPendingChange })setSaving(true);setError('');const concept = { subjects: draft.subjects, universeId: draft.universeId || null };- const visualSpec = { moodBoardId: draft.moodBoardId || null };const canon = { characters: [], places: [], objects: [] };for (const item of selectedCanon) {if (draft.subjects.some((s) => s.id === item.subjectId)) canon[fields[item.kind]].push(item.entry);}const pulled = pullUniverseCanonReferences(canon, project.visualSpec?.references || []);- if (pulled.added) visualSpec.references = pulled.next;- return onSave({ concept, visualSpec }).then(() => setEditing(false)).catch((err) => setError(err.message || 'Could not save creative setup')).finally(() => setSaving(false));+ return onSave({ concept, ...(pulled.added ? { visualSpec: { references: pulled.next } } : {}) }).then(() => setEditing(false)).catch((err) => setError(err.message || 'Could not save creative setup')).finally(() => setSaving(false));};return <section className="bg-port-card border border-port-border rounded-lg p-3 space-y-3 min-w-0 break-words" aria-label="Creative setup">@@ -102,7 +99,7 @@ export default function CreativeSetupPanel({ project, onSave, onPendingChange })</div>{!editing ? <p className="text-xs text-port-text-muted">{subjects.length ? subjects.map((s) => `${s.name}${s.role === 'protagonist' ? ' (protagonist)' : s.role === 'band' ? ' (band)' : ''}`).join(' · ') : 'Create the band or protagonist, choose a universe, and select the places and objects that anchor the story.'}</p> : <fieldset disabled={saving} className="space-y-3 min-w-0"><p className="text-xs text-port-text-muted">Save this setup before planning or generating. Canon and style are copied into this project; source records stay independent.</p>- <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">+ <div className="grid grid-cols-1 gap-3"><div><label htmlFor={idFor('universe')} className="text-xs">Universe</label><select id={idFor('universe')} className={inputClass} value={universeId} onChange={(e) => {const nextId = e.target.value;@@ -118,10 +115,6 @@ export default function CreativeSetupPanel({ project, onSave, onPendingChange })</select>{universeId && <Link className="text-xs text-port-accent" target="_blank" to={`/universes/${encodeURIComponent(universeId)}`}>Edit universe canon</Link>}</div>- <div>- <MoodBoardReferenceStrip value={draft.moodBoardId} onChange={(id) => setDraft((d) => ({ ...d, moodBoardId: id || '' }))} newBoardName={project.name} />- <p className="text-xs text-port-text-muted">Copies captions, notes and analyzed styles. Add images in Visual spec to condition frames.</p>- </div></div>{loading && <p className="text-xs">Loading canon…</p>}{universeReady && universe && <div className="grid grid-cols-1 sm:grid-cols-3 gap-2">{kinds.map(([kind, label]) => <div key={kind}>@@ -131,7 +124,7 @@ export default function CreativeSetupPanel({ project, onSave, onPendingChange })if (entry) add(kind, entry.name, entry.physicalDescription || entry.description, entry);}}><option value="">Add from universe…</option>{(universe[fields[kind]] || []).filter((entry) => !subjects.some((s) => s.canonId === entry.id && s.kind === kind)).map((entry) => <option key={entry.id} value={entry.id}>{entry.name}</option>)}</select></div>)}</div>}- <p className="text-xs text-port-text-muted">Up to 24 subjects. Selected canon images are added as look references when space is available; enable “Condition frames” in Visual spec to use their pixels.</p>+ <p className="text-xs text-port-text-muted">Up to 24 subjects. Selected canon images are added as look references when space is available; enable “Condition frames” in Look references to use their pixels.</p><ul className="space-y-2">{subjects.map((subject) => <li key={subject.id} className="border border-port-border rounded p-2 space-y-1"><div className="flex flex-wrap items-center gap-2"><span className="text-sm min-w-0 flex-1 break-words">{subject.name} · {subject.kind}</span>{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></>}diff --git a/client/src/components/musicVideo/CreativeSetupPanel.test.jsx b/client/src/components/musicVideo/CreativeSetupPanel.test.jsxindex 5d9d06f030..30c54ceaa9 100644--- a/client/src/components/musicVideo/CreativeSetupPanel.test.jsx+++ b/client/src/components/musicVideo/CreativeSetupPanel.test.jsx@@ -7,10 +7,6 @@ vi.mock('../../services/apiUniverseBuilder.js', () => ({listUniverseNames: vi.fn(async () => [{ id: 'u1', name: 'Example universe' }, { id: 'u2', name: 'Other universe' }]),getUniverse: vi.fn(),}));-vi.mock('../../services/apiMoodBoard.js', () => ({- listMoodBoards: vi.fn(async () => [{ id: 'b1', name: 'Painted style' }]),- getMoodBoard: vi.fn(async () => ({ name: 'Painted style', description: 'Watercolor', items: [{ type: 'text', text: 'Loose brush strokes' }] })),-}));const project = { id: 'mv1', concept: {}, visualSpec: {} };const open = (onSave = vi.fn(async () => {})) => {render(<MemoryRouter><CreativeSetupPanel project={project} onSave={onSave} onPendingChange={vi.fn()} /></MemoryRouter>);@@ -22,7 +18,7 @@ beforeEach(() => {getUniverse.mockResolvedValue({ id: 'u1', name: 'Example universe', styleNotes: 'Ink silhouettes', characters: [{ id: 'c1', name: 'Example singer', physicalDescription: 'Silver coat' }], places: [], objects: [] });});describe('creative setup', () => {- it('saves image-free canon, an authored prop and mood-board direction together', async () => {+ it('saves image-free canon and an authored prop, leaving the mood board to Look references', async () => {const onSave = open();await screen.findByText('Example universe');fireEvent.change(screen.getByLabelText('Universe'), { target: { value: 'u1' } });@@ -33,17 +29,15 @@ describe('creative setup', () => {fireEvent.change(screen.getByLabelText('Name'), { target: { value: 'Glass guitar' } });fireEvent.change(screen.getByLabelText('Appearance / description'), { target: { value: 'Transparent blue glass' } });fireEvent.click(screen.getByText('Add to production'));- fireEvent.click(screen.getByText('Mood board reference'));- await screen.findByText('Painted style');- fireEvent.change(screen.getByLabelText('Board'), { target: { value: 'b1' } });fireEvent.click(screen.getByText('Save creative setup'));await waitFor(() => expect(onSave).toHaveBeenCalledTimes(1));expect(onSave.mock.calls[0][0]).toMatchObject({concept: { universeId: 'u1', subjects: [{ kind: 'character', name: 'Example singer', role: 'band', description: 'Silver coat', canonId: 'c1' },{ kind: 'object', name: 'Glass guitar', description: 'Transparent blue glass' },- ] }, visualSpec: { moodBoardId: 'b1' },+ ] },});+ expect(onSave.mock.calls[0][0]).not.toHaveProperty('visualSpec');});it('discards an unsaved cast when the director cancels setup', async () => {const onSave = open();diff --git a/client/src/components/musicVideo/LlmRouteNote.jsx b/client/src/components/musicVideo/LlmRouteNote.jsxnew file mode 100644index 0000000000..fea4fe502e--- /dev/null+++ b/client/src/components/musicVideo/LlmRouteNote.jsx@@ -0,0 +1,18 @@+import { llmRouteLabel } from '../../lib/musicVideoAutomation.js';++/**+ * The model a Music Video text stage (AI Plan, Treatment compile, Cast & Sets)+ * last ran on, shown the same way beside each of them (#10223). `route` is the+ * stage's recorded route (`project.automation.routes[stage]`) or any+ * `{ providerId, model, … }`; nothing renders until a stage has run. A pin+ * whose provider no longer resolved says what it was replaced.+ */+export default function LlmRouteNote({ route, prefix = 'Ran on', className = '' }) {+ if (!route?.providerId) return null;+ return (+ <span data-testid="llm-route" className={`text-[11px] text-port-text-muted break-words ${className}`}>+ {prefix} {llmRouteLabel(route)}+ {route.requestedProviderId ? ` — replaced the unavailable ${route.requestedProviderId}` : ''}+ </span>+ );+}diff --git a/client/src/components/musicVideo/LlmRouteNote.test.jsx b/client/src/components/musicVideo/LlmRouteNote.test.jsxnew file mode 100644index 0000000000..a96bbdb17a--- /dev/null+++ b/client/src/components/musicVideo/LlmRouteNote.test.jsx@@ -0,0 +1,12 @@+import { describe, it, expect } from 'vitest';+import { render, screen } from '@testing-library/react';+import LlmRouteNote from './LlmRouteNote.jsx';++describe('LlmRouteNote', () => {+ it('names the model a stage ran on, and what a lost pin was replaced by', () => {+ const { rerender, container } = render(<LlmRouteNote route={null} />);+ expect(container.textContent).toBe('');+ rerender(<LlmRouteNote route={{ providerId: 'example-llm', model: 'big-1', transport: 'api', requestedProviderId: 'gone-llm' }} />);+ expect(screen.getByTestId('llm-route').textContent).toBe('Ran on example-llm · big-1 (API) — replaced the unavailable gone-llm');+ });+});diff --git a/client/src/components/musicVideo/LookReferencesPanel.jsx b/client/src/components/musicVideo/LookReferencesPanel.jsxnew file mode 100644index 0000000000..9b20cd5d56--- /dev/null+++ b/client/src/components/musicVideo/LookReferencesPanel.jsx@@ -0,0 +1,232 @@+import { useEffect, useRef, useState } from 'react';+import { ImagePlus, Trash2, Sparkles, Download } from 'lucide-react';+import useMounted from '../../hooks/useMounted.js';+import { MAX_CONDITIONING_REFERENCES } from '../../hooks/useMusicVideoSceneMedia.js';+import { getMoodBoard } from '../../services/apiMoodBoard.js';+import { getUniverse } from '../../services/apiUniverseBuilder.js';+import { uploadGalleryImage } from '../../services/apiSystem.js';+import { IMAGE_ACCEPT, readFileAsBase64, validateImageFile } from '../../utils/fileUpload.js';+import { moodBoardItemAnalysisSource } from '../../lib/moodBoardItemSrc.js';+import { MUSIC_VIDEO_MAX_REFERENCES, pullUniverseCanonReferences } from '../../lib/musicVideoUniverseRefs.js';+import { uuidv4 } from '../../lib/uuid.js';+import MoodBoardReferenceStrip from '../moodBoard/MoodBoardReferenceStrip.jsx';+import toast from '../ui/Toast';++const ROLES = [+ ['mood', 'Mood'], ['character', 'Character'], ['wardrobe', 'Wardrobe'],+ ['set', 'Set'], ['prop', 'Prop'], ['style', 'Style'],+];+// How the asset is meant to be used (#8980): a look reference, media that+// appears in the final video as-is, or motion-reference scaffolding only.+const USES = [['reference', 'Look reference'], ['final-visible', 'Final visible'], ['motion-reference', 'Motion reference only']];+const MAX_UPLOADS = 8;++const selectCls = 'bg-port-bg border border-port-border rounded px-1 py-0.5 text-[11px] min-h-[44px] sm:min-h-0';+const actionCls = 'flex items-center gap-1 bg-port-border hover:bg-port-border/70 disabled:opacity-50 rounded px-2 py-1 text-xs min-h-[44px] sm:min-h-0';++/**+ * The one list of look references for a Music Video project (#10223), in+ * Creative direction. Everything that tells the generators how the video+ * should look lives here:+ *+ * - the linked mood board (pick one, or import its gallery images as rows);+ * - the canon of the linked universe ("Pull from universe") and gallery picks+ * ("Add reference") — `visualSpec.references`, each with a role, a use and a+ * per-reference "Condition frames" toggle (autosaved through `onSaveSpec`);+ * - project uploads — `styleReferences`, captioned style images that fill a+ * model's spare reference slots after the identities (saved explicitly+ * through `onSave`, and held pending so generation does not start on a+ * half-edited set). Uploads do not invoke an AI provider.+ */+export default function LookReferencesPanel({ project, onSave, onSaveSpec, onAddReference, onPendingChange }) {+ const mounted = useMounted();+ const spec = project.visualSpec || {};+ const references = spec.references || [];+ const [uploads, setUploads] = useState(project.styleReferences || []);+ const [busy, setBusy] = useState(false);+ const [dirty, setDirty] = useState(false);+ const [working, setWorking] = useState(false); // a board import / universe pull is reading+ const idFor = (suffix) => `mv-look-${project.id}-${suffix}`;+ const flagged = references.filter((r) => r.condition).length;+ const full = references.length >= MUSIC_VIDEO_MAX_REFERENCES;++ useEffect(() => {+ onPendingChange?.(dirty || busy);+ return () => onPendingChange?.(false);+ }, [dirty, busy, onPendingChange]);+ useEffect(() => {+ if (!dirty && !busy) setUploads(project.styleReferences || []);+ }, [project.styleReferences, dirty, busy]);++ // An async import must not clobber an edit made while it was reading: read the+ // base list through a ref that tracks every render, not the click-time closure.+ const referencesRef = useRef(references);+ referencesRef.current = references;+ const saveReferences = (next) => onSaveSpec({ references: next });+ const updateRef = (id, patch) => saveReferences(references.map((r) => (r.id === id ? { ...r, ...patch } : r)));++ const readThenAdd = (read, { from, empty, duplicate }) => {+ if (working) return;+ setWorking(true);+ read()+ .then(({ next, added, skipped }) => {+ if (added > 0) {+ saveReferences(next);+ toast.success(`Pulled ${added} reference${added === 1 ? '' : 's'} from ${from}${skipped ? ` (${skipped} skipped)` : ''}`);+ } else toast.error(skipped ? duplicate : empty);+ })+ .catch((err) => toast.error(err?.message || 'Could not read the source'))+ .finally(() => { if (mounted.current) setWorking(false); });+ };+ const pullFromUniverse = () => readThenAdd(+ () => getUniverse(project.concept.universeId, { silent: true }).then((universe) => pullUniverseCanonReferences(universe, referencesRef.current)),+ { from: 'the universe', empty: 'This universe has no canon images to pull yet', duplicate: 'Every canon image is already a reference' },+ );+ const importBoard = () => readThenAdd(async () => {+ const board = await getMoodBoard(spec.moodBoardId, { silent: true });+ const known = new Set(referencesRef.current.map((r) => r.imageId));+ const base = referencesRef.current;+ const fresh = [];+ let skipped = 0;+ for (const item of Array.isArray(board?.items) ? board.items : []) {+ const filename = moodBoardItemAnalysisSource(item)?.filename;+ if (!filename || item.type !== 'image') continue;+ if (known.has(filename) || base.length + fresh.length >= MUSIC_VIDEO_MAX_REFERENCES) { skipped += 1; continue; }+ known.add(filename);+ fresh.push({ id: `mvr-board-${uuidv4()}`, imageId: filename, role: 'mood', label: '', condition: false });+ }+ return { next: [...base, ...fresh], added: fresh.length, skipped };+ }, { from: 'the mood board', empty: 'This mood board has no gallery images to import', duplicate: 'Every mood board image is already a reference' });++ const changeUploads = (next) => { setUploads(next); setDirty(true); };+ const upload = async (files) => {+ if (busy || !files.length) return;+ if (uploads.length + files.length > MAX_UPLOADS) { toast.error('Choose at most eight style uploads'); return; }+ const error = files.map((file) => !IMAGE_ACCEPT.split(',').includes(file.type)+ ? 'Use PNG, JPEG or WebP style images' : validateImageFile(file)).find(Boolean);+ if (error) { toast.error(error); return; }+ setBusy(true);+ let next = [...uploads];+ try {+ for (const file of files) {+ const encoded = await readFileAsBase64(file);+ const { filename } = await uploadGalleryImage(encoded, { silent: true });+ if (!mounted.current) return;+ next = [...next, { imageId: filename, caption: '' }];+ changeUploads(next);+ }+ } catch (err) {+ toast.error(err?.message || 'Style upload failed');+ } finally {+ if (mounted.current) setBusy(false);+ }+ };+ const saveUploads = async () => {+ if (busy) return;+ setBusy(true);+ try {+ await onSave({ styleReferences: uploads });+ if (mounted.current) setDirty(false);+ } catch (err) {+ toast.error(err?.message || 'Style uploads save failed');+ } finally {+ if (mounted.current) setBusy(false);+ }+ };++ return (+ <section aria-label="Look references" className="rounded-lg border border-port-border bg-port-card p-3 space-y-2 min-w-0">+ <div className="flex flex-wrap items-center justify-between gap-2">+ <h3 className="text-sm font-medium">Look references</h3>+ <div className="flex items-center gap-1.5 flex-wrap">+ {spec.moodBoardId && (+ <button type="button" onClick={importBoard} disabled={working || full} className={actionCls}+ title="Add the linked mood board's gallery images as references">+ <Download size={13} /> Import board images+ </button>+ )}+ {project.concept?.universeId && (+ <button type="button" onClick={pullFromUniverse} disabled={working || full} className={actionCls}+ title="Add the linked universe's canon character/place/object images as references">+ <Sparkles size={13} /> {working ? 'Reading…' : 'Pull from universe'}+ </button>+ )}+ <button type="button" onClick={onAddReference} disabled={full} className={actionCls}>+ <ImagePlus size={13} /> Add reference+ </button>+ </div>+ </div>+ <p className="text-xs text-port-text-muted">+ One list for the video’s look: a mood board, gallery images and your own uploads. Identity references take priority; tick “Condition frames” to send an image to every reference-frame render, and models use as many style uploads as their remaining slots allow, or caption text when references are unsupported.+ </p>+ <MoodBoardReferenceStrip value={spec.moodBoardId || ''} onChange={(id) => onSaveSpec({ moodBoardId: id || null })} newBoardName={project.name} />++ {references.length === 0 && uploads.length === 0 && (+ <p className="text-[11px] text-port-text-muted">No look references yet. Import a mood board, add gallery images or upload style images below.</p>+ )}+ <ul className="grid grid-cols-1 sm:grid-cols-2 xl:grid-cols-3 gap-2">+ {references.map((ref) => (+ <li key={ref.id} className="flex gap-2 rounded border border-port-border p-1.5 min-w-0">+ <img src={`/data/images/${encodeURIComponent(ref.imageId)}`} alt="" loading="lazy" className="w-16 h-16 object-cover rounded shrink-0 bg-black" />+ <div className="min-w-0 flex-1 space-y-1">+ <div className="flex gap-1">+ <label htmlFor={idFor(`role-${ref.id}`)} className="sr-only">Reference role</label>+ <select id={idFor(`role-${ref.id}`)} value={ref.role || 'mood'} onChange={(e) => updateRef(ref.id, { role: e.target.value })} className={selectCls}>+ {ROLES.map(([value, label]) => <option key={value} value={value}>{label}</option>)}+ </select>+ <button type="button" onClick={() => saveReferences(references.filter((r) => r.id !== ref.id))}+ aria-label="Remove reference" title="Remove reference"+ className="ml-auto min-h-[32px] min-w-[32px] inline-flex items-center justify-center text-port-error">+ <Trash2 size={12} />+ </button>+ </div>+ <label htmlFor={idFor(`use-${ref.id}`)} className="sr-only">Reference use</label>+ <select id={idFor(`use-${ref.id}`)} value={ref.use || 'reference'} onChange={(e) => updateRef(ref.id, { use: e.target.value })} className={`w-full ${selectCls}`}>+ {USES.map(([value, label]) => <option key={value} value={value}>{label}</option>)}+ </select>+ <label htmlFor={idFor(`label-${ref.id}`)} className="sr-only">Reference label</label>+ <input id={idFor(`label-${ref.id}`)} defaultValue={ref.label || ''} maxLength={120} placeholder="Label (e.g. lead singer)"+ onBlur={(e) => { if (e.target.value !== (ref.label || '')) updateRef(ref.id, { label: e.target.value }); }}+ className={`w-full ${selectCls}`} />+ <label className="flex items-center gap-1 text-[11px] min-h-[44px] sm:min-h-0">+ <input type="checkbox" checked={!!ref.condition}+ disabled={!ref.condition && flagged >= MAX_CONDITIONING_REFERENCES}+ onChange={(e) => updateRef(ref.id, { condition: e.target.checked })} />+ Condition frames+ </label>+ </div>+ </li>+ ))}+ {uploads.map((ref, index) => (+ <li key={ref.imageId} className="flex gap-2 rounded border border-port-border p-1.5 min-w-0">+ <img src={`/data/images/${encodeURIComponent(ref.imageId)}`} alt={`Style upload ${index + 1}`} className="w-16 h-16 object-cover rounded shrink-0 bg-black" />+ <div className="min-w-0 flex-1 space-y-1">+ <span className="block text-[11px] text-port-text-muted">Style upload</span>+ <label htmlFor={idFor(`caption-${index}`)} className="sr-only">Style caption {index + 1}</label>+ <textarea id={idFor(`caption-${index}`)} value={ref.caption || ''} maxLength={500} rows={2}+ placeholder="Palette, lighting, lens, grain"+ onChange={(e) => changeUploads(uploads.map((item, i) => (i === index ? { ...item, caption: e.target.value } : item)))}+ className="block w-full rounded border border-port-border bg-port-bg p-1 text-sm" />+ <button type="button" aria-label={`Remove style upload ${index + 1}`} onClick={() => changeUploads(uploads.filter((_, i) => i !== index))}+ className="min-h-[44px] sm:min-h-0 text-xs text-port-error">Remove</button>+ </div>+ </li>+ ))}+ </ul>+ {flagged > 0 && (+ <p className="text-[11px] text-port-text-muted">+ Conditioning needs an image backend that accepts reference images (local FLUX.2 or Qwen Image 2.1, or a cloud image CLI); others refuse the render and say so. At most {MAX_CONDITIONING_REFERENCES} per frame.+ </p>+ )}+ <fieldset disabled={busy} className="space-y-2">+ <label htmlFor={idFor('upload')} className="block text-xs">Upload style images+ <input id={idFor('upload')} type="file" aria-label="Upload style images" accept={IMAGE_ACCEPT} multiple disabled={uploads.length >= MAX_UPLOADS || busy}+ onChange={(e) => { const files = Array.from(e.target.files || []); e.target.value = ''; upload(files); }}+ className="block w-full text-sm min-h-[44px]" />+ </label>+ <button type="button" disabled={!dirty || busy} onClick={saveUploads} className="min-h-[44px] rounded bg-port-accent px-3 text-sm text-white disabled:opacity-50">{busy ? 'Saving…' : 'Save style uploads'}</button>+ </fieldset>+ {dirty && <p className="text-xs text-port-warning">Save the style uploads before starting generation.</p>}+ </section>+ );+}diff --git a/client/src/components/musicVideo/LookReferencesPanel.test.jsx b/client/src/components/musicVideo/LookReferencesPanel.test.jsxnew file mode 100644index 0000000000..3a180f4641--- /dev/null+++ b/client/src/components/musicVideo/LookReferencesPanel.test.jsx@@ -0,0 +1,81 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';+import { render, screen, fireEvent, waitFor, act } from '@testing-library/react';+import { MemoryRouter } from 'react-router';+import LookReferencesPanel from './LookReferencesPanel.jsx';+import { getMoodBoard } from '../../services/apiMoodBoard.js';++vi.mock('../../services/apiMoodBoard.js', () => ({ getMoodBoard: vi.fn() }));+vi.mock('../../services/api', () => ({+ listMoodBoards: vi.fn(async () => []), getMoodBoard: vi.fn(), createMoodBoard: vi.fn(),+}));+vi.mock('../../services/apiUniverseBuilder.js', () => ({ getUniverse: vi.fn() }));+vi.mock('../../services/apiSystem.js', () => ({ uploadGalleryImage: vi.fn(async () => ({ filename: 'uploaded.png' })) }));+vi.mock('../../utils/fileUpload.js', () => ({ IMAGE_ACCEPT: 'image/png,image/jpeg,image/webp', readFileAsBase64: vi.fn(async () => 'encoded'), validateImageFile: vi.fn(() => null) }));+vi.mock('../ui/Toast', () => ({ default: { error: vi.fn(), success: vi.fn() } }));++const mount = (project, props = {}) => render(+ <MemoryRouter>+ <LookReferencesPanel project={{ id: 'example', ...project }} onSave={vi.fn()} onSaveSpec={vi.fn()} onAddReference={vi.fn()} {...props} />+ </MemoryRouter>,+);++beforeEach(() => vi.clearAllMocks());++describe('look references', () => {+ it('lists spec references and project uploads in one list, with one condition toggle per spec reference', () => {+ const onSaveSpec = vi.fn();+ mount({+ visualSpec: { references: [{ id: 'r1', imageId: 'face.png', role: 'character', label: 'Singer', condition: false }] },+ styleReferences: [{ imageId: 'grain.png', caption: 'Fine grain' }],+ }, { onSaveSpec });+ expect(screen.getAllByRole('region', { name: 'Look references' })).toHaveLength(1);+ expect(screen.getByDisplayValue('Singer')).toBeTruthy();+ expect(screen.getByLabelText('Style caption 1').value).toBe('Fine grain');+ fireEvent.click(screen.getByLabelText('Condition frames'));+ expect(onSaveSpec).toHaveBeenCalledWith({ references: [{ id: 'r1', imageId: 'face.png', role: 'character', label: 'Singer', condition: true }] });+ });++ it('imports the linked mood board gallery images once, skipping text, remote pins and duplicates', async () => {+ getMoodBoard.mockResolvedValue({ id: 'b1', name: 'Example Board', items: [+ { id: 'i1', type: 'image', mediaKey: 'image:pin.png' },+ { id: 'i2', type: 'image', mediaKey: 'image:have.png' },+ { id: 'i3', type: 'image', imageUrl: 'https://example.com/remote.png' },+ { id: 'i4', type: 'text', text: 'Loose brush strokes' },+ ] });+ const onSaveSpec = vi.fn();+ mount({ visualSpec: { moodBoardId: 'b1', references: [{ id: 'r0', imageId: 'have.png', role: 'mood' }] } }, { onSaveSpec });+ fireEvent.click(screen.getByText('Import board images'));+ await waitFor(() => expect(onSaveSpec).toHaveBeenCalledTimes(1));+ const { references } = onSaveSpec.mock.calls[0][0];+ expect(references.map((r) => r.imageId)).toEqual(['have.png', 'pin.png']);+ expect(references[1]).toMatchObject({ role: 'mood', condition: false });+ expect(getMoodBoard).toHaveBeenCalledWith('b1', { silent: true });+ });++ it('uploads, captions and saves style images, holding generation pending through the save', async () => {+ let finish;+ const onSave = vi.fn(() => new Promise((resolve) => { finish = resolve; }));+ const pending = vi.fn();+ mount({}, { onSave, onPendingChange: pending });+ fireEvent.change(screen.getByLabelText('Upload style images'), { target: { files: [new File(['image'], 'style.png', { type: 'image/png' })] } });+ await screen.findByAltText('Style upload 1');+ fireEvent.change(screen.getByLabelText('Style caption 1'), { target: { value: 'Fine silver grain' } });+ fireEvent.click(screen.getByText('Save style uploads'));+ expect(onSave).toHaveBeenCalledWith({ styleReferences: [{ imageId: 'uploaded.png', caption: 'Fine silver grain' }] });+ expect(pending).toHaveBeenLastCalledWith(true);+ await act(async () => finish());+ await waitFor(() => expect(pending).toHaveBeenLastCalledWith(false));+ });++ it('keeps a rejected upload save editable and preserves an unsaved caption across project refreshes', async () => {+ const onSave = vi.fn(async () => { throw new Error('Save failed'); });+ const project = { id: 'example', styleReferences: [{ imageId: 'style.png', caption: 'Warm grain' }] };+ const { rerender } = render(<MemoryRouter><LookReferencesPanel project={project} onSave={onSave} onSaveSpec={vi.fn()} /></MemoryRouter>);+ fireEvent.change(screen.getByLabelText('Style caption 1'), { target: { value: 'My draft' } });+ rerender(<MemoryRouter><LookReferencesPanel project={{ ...project, styleReferences: [{ imageId: 'style.png', caption: 'Remote caption' }] }} onSave={onSave} onSaveSpec={vi.fn()} /></MemoryRouter>);+ expect(screen.getByLabelText('Style caption 1').value).toBe('My draft');+ fireEvent.click(screen.getByText('Save style uploads'));+ await waitFor(() => expect(screen.getByText('Save style uploads').disabled).toBe(false));+ expect(screen.getByText('Save the style uploads before starting generation.')).toBeTruthy();+ });+});diff --git a/client/src/components/musicVideo/ProjectActionGroups.jsx b/client/src/components/musicVideo/ProjectActionGroups.jsxindex c9db105f13..734a219681 100644--- a/client/src/components/musicVideo/ProjectActionGroups.jsx+++ b/client/src/components/musicVideo/ProjectActionGroups.jsx@@ -1,4 +1,5 @@import { useState } from 'react';+import LlmRouteNote from './LlmRouteNote.jsx';import { Film, Music, Activity, Image as ImageIcon, Video, Wand2, X } from 'lucide-react';import { MUSCRIPTOR_MODELS } from '../../lib/muscriptorModels.js';import { isLayeredComposition, sceneRenderReady, sceneVisualLayer } from '../../lib/musicVideoLayers.js';@@ -82,6 +83,7 @@ export function PlanActions({ project, busy, onPlan, onAutoArrange }) {className={buttonCls}><Wand2 size={15} /> {busy.planning ? 'Planning…' : 'AI Plan'}</button>+ <LlmRouteNote route={project.automation?.routes?.plan} />{choosing && !busy.planning && (<div role="group" aria-label="Plan mode" className="flex flex-wrap items-center gap-2 text-sm"><span className="text-gray-400">The board has {sceneCount} shot{sceneCount === 1 ? '' : 's'}.</span>diff --git a/client/src/components/musicVideo/StyleReferencesPanel.jsx b/client/src/components/musicVideo/StyleReferencesPanel.jsxdeleted file mode 100644index 8534b47f7f..0000000000--- a/client/src/components/musicVideo/StyleReferencesPanel.jsx+++ /dev/null@@ -1,129 +0,0 @@-import { useEffect, useMemo, useState } from 'react';-import { Link } from 'react-router';-import { ExternalLink } from 'lucide-react';-import useMounted from '../../hooks/useMounted.js';-import { getMoodBoard } from '../../services/apiMoodBoard.js';-import { moodBoardItemSrc } from '../../lib/moodBoardItemSrc.js';-import { uploadGalleryImage } from '../../services/apiSystem.js';-import { IMAGE_ACCEPT, readFileAsBase64, validateImageFile } from '../../utils/fileUpload.js';-import toast from '../ui/Toast';--const LINKED_THUMBS = 6;--/**- * The mood board linked to the project (`visualSpec.moodBoardId` — the one an- * autonomous run creates or the creative setup picks): its name, a few pinned- * images and a link to the board, so an empty uploader below is not read as- * "no moodboard". Read-only; the board page is where it is edited.- */-function LinkedMoodBoard({ boardId }) {- const [board, setBoard] = useState(null); // null = not loaded (or failed), else the full board- useEffect(() => {- let active = true;- setBoard(null);- getMoodBoard(boardId, { silent: true }).then((data) => { if (active) setBoard(data || null); }, () => {});- return () => { active = false; };- }, [boardId]);- const thumbs = useMemo(() => (Array.isArray(board?.items) ? board.items : [])- .map((item) => ({ id: item.id, src: moodBoardItemSrc(item) })).filter((t) => t.src).slice(0, LINKED_THUMBS), [board]);- return (- <div className="rounded border border-port-border bg-port-bg p-2 space-y-2" data-testid="linked-mood-board">- <div className="flex flex-wrap items-center gap-x-2 gap-y-1 text-xs">- <span className="text-port-text-muted">Linked mood board</span>- <Link to={`/mood-boards/${encodeURIComponent(boardId)}`} className="inline-flex items-center gap-1 text-port-accent hover:underline min-h-[44px] sm:min-h-0">- {board?.name || 'Open mood board'} <ExternalLink size={12} aria-hidden="true" />- </Link>- </div>- {thumbs.length > 0 && (- <ul className="flex flex-wrap gap-1">- {thumbs.map((t, i) => (- <li key={t.id || i}><img src={t.src} alt={`Mood board image ${i + 1}`} loading="lazy" className="h-12 w-12 rounded object-cover" /></li>- ))}- </ul>- )}- </div>- );-}--/** Project-owned moodboard; uploads do not invoke an AI provider. */-export default function StyleReferencesPanel({ project, onSave, onPendingChange }) {- const mounted = useMounted();- const [references, setReferences] = useState(project.styleReferences || []);- const [busy, setBusy] = useState(false);- const [dirty, setDirty] = useState(false);- useEffect(() => {- onPendingChange?.(dirty || busy);- return () => onPendingChange?.(false);- }, [dirty, busy, onPendingChange]);- useEffect(() => {- if (!dirty && !busy) setReferences(project.styleReferences || []);- }, [project.styleReferences, dirty, busy]);- const change = (next) => {- setReferences(next);- setDirty(true);- };- const upload = async (files) => {- if (busy || !files.length) return;- if (references.length + files.length > 8) { toast.error('Choose at most eight moodboard images'); return; }- const error = files.map((file) => !IMAGE_ACCEPT.split(',').includes(file.type)- ? 'Use PNG, JPEG or WebP moodboard images' : validateImageFile(file)).find(Boolean);- if (error) { toast.error(error); return; }- setBusy(true);- let next = [...references];- try {- for (const file of files) {- const encoded = await readFileAsBase64(file);- const { filename } = await uploadGalleryImage(encoded, { silent: true });- if (!mounted.current) return;- next = [...next, { imageId: filename, caption: '' }];- change(next);- }- } catch (err) {- toast.error(err?.message || 'Moodboard upload failed');- } finally {- if (mounted.current) setBusy(false);- }- };- const save = async () => {- if (busy) return;- setBusy(true);- try {- await onSave({ styleReferences: references });- if (mounted.current) setDirty(false);- } catch (err) {- toast.error(err?.message || 'Moodboard save failed');- } finally {- if (mounted.current) setBusy(false);- }- };- return (- <section aria-label="Project moodboard" className="rounded-lg border border-port-border bg-port-card p-3 space-y-2">- <h3 className="text-sm font-medium">Project moodboard</h3>- <p className="text-xs text-port-text-muted">Up to eight style images. Add captions describing palette, lighting, lens and grain. Identity references take priority; models use as many style images as their remaining slots allow, or caption text when references are unsupported.</p>- {project.visualSpec?.moodBoardId && <LinkedMoodBoard boardId={project.visualSpec.moodBoardId} />}- <fieldset disabled={busy} className="space-y-2">- <label htmlFor={`mv-style-upload-${project.id}`} className="block text-xs">Upload style images- <input id={`mv-style-upload-${project.id}`} type="file" aria-label="Upload style images" accept={IMAGE_ACCEPT} multiple disabled={references.length >= 8 || busy}- onChange={(e) => { const files = Array.from(e.target.files || []); e.target.value = ''; upload(files); }}- className="block w-full text-sm min-h-[44px]" />- </label>- <ul className="grid grid-cols-1 sm:grid-cols-2 gap-2">- {references.map((ref, index) => (- <li key={ref.imageId} className="flex gap-2 rounded border border-port-border p-2">- <img src={`/data/images/${encodeURIComponent(ref.imageId)}`} alt={`Style reference ${index + 1}`} className="h-16 w-16 rounded object-cover" />- <label htmlFor={`mv-style-caption-${project.id}-${index}`} className="flex-1 text-xs">Style caption {index + 1}- <textarea id={`mv-style-caption-${project.id}-${index}`} value={ref.caption || ''} maxLength={500} rows={2}- onChange={(e) => change(references.map((item, i) => i === index ? { ...item, caption: e.target.value } : item))}- className="block w-full rounded border border-port-border bg-port-bg p-1 text-sm" />- </label>- <button type="button" aria-label={`Remove style reference ${index + 1}`} onClick={() => change(references.filter((_, i) => i !== index))}- className="min-h-[44px] text-xs text-port-error">Remove</button>- </li>- ))}- </ul>- <button type="button" disabled={!dirty || busy} onClick={save} className="min-h-[44px] rounded bg-port-accent px-3 text-sm text-white disabled:opacity-50">{busy ? 'Saving…' : 'Save moodboard'}</button>- </fieldset>- {dirty && <p className="text-xs text-port-warning">Save the moodboard before starting generation.</p>}- </section>- );-}diff --git a/client/src/components/musicVideo/StyleReferencesPanel.test.jsx b/client/src/components/musicVideo/StyleReferencesPanel.test.jsxdeleted file mode 100644index b5d92c1e79..0000000000--- a/client/src/components/musicVideo/StyleReferencesPanel.test.jsx+++ /dev/null@@ -1,66 +0,0 @@-import { describe, it, expect, vi } from 'vitest';-import { render, screen, fireEvent, waitFor, act } from '@testing-library/react';-import { MemoryRouter } from 'react-router';-import StyleReferencesPanel from './StyleReferencesPanel.jsx';-import { getMoodBoard } from '../../services/apiMoodBoard.js';--vi.mock('../../services/apiMoodBoard.js', () => ({ getMoodBoard: vi.fn() }));--vi.mock('../../services/apiSystem.js', () => ({ uploadGalleryImage: vi.fn(async () => ({ filename: 'uploaded.png' })) }));-vi.mock('../../utils/fileUpload.js', () => ({ IMAGE_ACCEPT: 'image/png,image/jpeg,image/webp', readFileAsBase64: vi.fn(async () => 'encoded'), validateImageFile: vi.fn(() => null) }));-vi.mock('../ui/Toast', () => ({ default: { error: vi.fn() } }));--describe('project moodboard', () => {- it('shows the mood board the project links to (an autonomous run’s board), not just an empty uploader', async () => {- getMoodBoard.mockResolvedValue({ id: 'board-1', name: 'Example Board', items: [{ id: 'i1', type: 'image', imageUrl: '/data/images/pin.png' }] });- render(<MemoryRouter><StyleReferencesPanel project={{ id: 'example', visualSpec: { moodBoardId: 'board-1' } }} onSave={vi.fn()} /></MemoryRouter>);- const link = await screen.findByRole('link', { name: /example board/i });- expect(link.getAttribute('href')).toBe('/mood-boards/board-1');- expect(await screen.findByAltText('Mood board image 1')).toBeTruthy();- expect(getMoodBoard).toHaveBeenCalledWith('board-1', { silent: true });- });-- it('renders no linked-board block without a link, and still links when the board fails to load', async () => {- const { unmount } = render(<MemoryRouter><StyleReferencesPanel project={{ id: 'example' }} onSave={vi.fn()} /></MemoryRouter>);- expect(screen.queryByTestId('linked-mood-board')).toBeNull();- unmount();- getMoodBoard.mockRejectedValue(new Error('gone'));- render(<MemoryRouter><StyleReferencesPanel project={{ id: 'example', visualSpec: { moodBoardId: 'board-2' } }} onSave={vi.fn()} /></MemoryRouter>);- expect(await screen.findByRole('link', { name: /open mood board/i })).toBeTruthy();- });-- it('uploads, captions and saves references, holding generation pending through the save', async () => {- let finish;- const onSave = vi.fn(() => new Promise((resolve) => { finish = resolve; }));- const pending = vi.fn();- render(<StyleReferencesPanel project={{ id: 'example' }} onSave={onSave} onPendingChange={pending} />);- fireEvent.change(screen.getByLabelText('Upload style images'), { target: { files: [new File(['image'], 'style.png', { type: 'image/png' })] } });- await screen.findByAltText('Style reference 1');- fireEvent.change(screen.getByLabelText('Style caption 1'), { target: { value: 'Fine silver grain' } });- fireEvent.click(screen.getByText('Save moodboard'));- expect(onSave).toHaveBeenCalledWith({ styleReferences: [{ imageId: 'uploaded.png', caption: 'Fine silver grain' }] });- expect(pending).toHaveBeenLastCalledWith(true);- await act(async () => finish());- await waitFor(() => expect(pending).toHaveBeenLastCalledWith(false));- });-- it('refreshes clean references from project updates while preserving an unsaved caption', () => {- const { rerender } = render(<StyleReferencesPanel project={{ id: 'example', styleReferences: [] }} onSave={vi.fn()} />);- const updated = { id: 'example', styleReferences: [{ imageId: 'style.png', caption: 'Warm grain' }] };- rerender(<StyleReferencesPanel project={updated} onSave={vi.fn()} />);- expect(screen.getByLabelText('Style caption 1').value).toBe('Warm grain');- fireEvent.change(screen.getByLabelText('Style caption 1'), { target: { value: 'My draft' } });- rerender(<StyleReferencesPanel project={{ ...updated, styleReferences: [{ imageId: 'style.png', caption: 'Remote caption' }] }} onSave={vi.fn()} />);- expect(screen.getByLabelText('Style caption 1').value).toBe('My draft');- });-- it('keeps a rejected save editable and permits removing a saved reference', async () => {- const onSave = vi.fn(async () => { throw new Error('Save failed'); });- render(<StyleReferencesPanel project={{ id: 'example', styleReferences: [{ imageId: 'style.png', caption: 'Warm grain' }] }} onSave={onSave} />);- fireEvent.click(screen.getByLabelText('Remove style reference 1'));- fireEvent.click(screen.getByText('Save moodboard'));- await waitFor(() => expect(screen.getByText('Save moodboard').disabled).toBe(false));- expect(onSave).toHaveBeenCalledWith({ styleReferences: [] });- expect(screen.getByText('Save the moodboard before starting generation.')).toBeTruthy();- });-});diff --git a/client/src/components/musicVideo/TreatmentPanel.jsx b/client/src/components/musicVideo/TreatmentPanel.jsxindex 5a66526bca..3cab52cfb0 100644--- a/client/src/components/musicVideo/TreatmentPanel.jsx+++ b/client/src/components/musicVideo/TreatmentPanel.jsx@@ -1,4 +1,5 @@import { useState } from 'react';+import LlmRouteNote from './LlmRouteNote.jsx';import { Sparkles, Wand2, AlertTriangle, Plus, Trash2 } from 'lucide-react';import useFieldDraft from '../../hooks/useFieldDraft.js';import useProviderModels from '../../hooks/useProviderModels.js';@@ -217,9 +218,9 @@ export default function TreatmentPanel({ project, treatment: api, part = 'all' }</button>{!analyzed && <span className="text-xs text-port-text-muted">Analyze the song first — the arc is built on its sections.</span>}{t?.compiledAt && (- <span className="text-[11px] text-port-text-muted">- Compiled {t.compiledWith?.source === 'ai' ? `with ${t.compiledWith.providerId}${t.compiledWith.model ? ` / ${t.compiledWith.model}` : ''}` : 'deterministically'}- </span>+ t.compiledWith?.source === 'ai'+ ? <LlmRouteNote route={project.automation?.routes?.treatment || t.compiledWith} prefix="Compiled with" />+ : <span className="text-[11px] text-port-text-muted">Compiled deterministically</span>)}</div>diff --git a/client/src/components/musicVideo/VisualSpecPanel.jsx b/client/src/components/musicVideo/VisualSpecPanel.jsxindex b1ca9e9a98..9f82143150 100644--- a/client/src/components/musicVideo/VisualSpecPanel.jsx+++ b/client/src/components/musicVideo/VisualSpecPanel.jsx@@ -1,82 +1,32 @@-import { useRef, useState } from 'react';-import { ImagePlus, Trash2, Plus, Palette, Sparkles } from 'lucide-react';+import { useState } from 'react';+import { Plus, Palette } from 'lucide-react';import useFieldDraft from '../../hooks/useFieldDraft.js';-import { MAX_CONDITIONING_REFERENCES } from '../../hooks/useMusicVideoSceneMedia.js';-import { getUniverse } from '../../services/apiUniverseBuilder.js';-import { pullUniverseCanonReferences } from '../../lib/musicVideoUniverseRefs.js';-import toast from '../ui/Toast';-const ROLES = [- ['mood', 'Mood'], ['character', 'Character'], ['wardrobe', 'Wardrobe'],- ['set', 'Set'], ['prop', 'Prop'], ['style', 'Style'],-];-// How the asset is meant to be used (#8980): a look reference, media that-// appears in the final video as-is, or motion-reference scaffolding only.-const USES = [['reference', 'Look reference'], ['final-visible', 'Final visible'], ['motion-reference', 'Motion reference only']];const MAX_PALETTE = 12;-const MAX_REFERENCES = 24;/**- * The project's reusable visual specification (#8965): moodboard/reference- * images with a role (character, wardrobe, set, …), a palette, typography and- * camera rules. Palette/camera/typography are appended to every generated- * prompt; references ticked "Condition frames" are sent to reference-frame- * renders as real conditioning images, not just prose.+ * The project's reusable visual specification (#8965): a palette, typography+ * and camera rules, appended to every generated prompt. The reference images+ * (with their role, use and "Condition frames" toggle) live in the one Look+ * references list (LookReferencesPanel, #10223).** `onSave(patch)` persists a partial `visualSpec` (the server merges it per- * sub-field); `references` and `palette` are always sent whole. Keyed by the+ * sub-field); `palette` is always sent whole. Keyed by the* project id at the call site, so a draft never carries across projects.*/-export default function VisualSpecPanel({ project, onSave, onAddReference }) {+export default function VisualSpecPanel({ project, onSave }) {const spec = project.visualSpec || {};- const references = spec.references || [];const palette = spec.palette || [];const [color, setColor] = useState('#336699');- const [pulling, setPulling] = useState(false);const typography = useFieldDraft(spec.typography, (v) => onSave({ typography: v }));const cameraRules = useFieldDraft(spec.cameraRules, (v) => onSave({ cameraRules: v }));const idFor = (suffix) => `mv-spec-${project.id}-${suffix}`;- const saveReferences = (next) => onSave({ references: next });- const updateRef = (id, patch) => saveReferences(references.map((r) => (r.id === id ? { ...r, ...patch } : r)));- const flagged = references.filter((r) => r.condition).length;-- // "Pull from universe" (#8978) — reuse the linked universe's canon- // characters/places/objects as references instead of re-picking every one- // by hand through Add reference. Idempotent: images already present are- // skipped, so a second click adds nothing new.- //- // The universe read is async, so an edit/remove/Add-reference the director- // makes WHILE it's in flight must not be clobbered by a stale `references`- // snapshot once it resolves. Read the base list through a ref that tracks- // every render instead of the click-time closure value.- const referencesRef = useRef(references);- referencesRef.current = references;- const universeId = project.concept?.universeId || null;- const handlePullFromUniverse = () => {- if (!universeId || pulling) return;- setPulling(true);- getUniverse(universeId, { silent: true })- .then((universe) => {- const { next, added, skipped } = pullUniverseCanonReferences(universe, referencesRef.current);- if (added > 0) saveReferences(next);- if (added > 0) {- toast.success(`Pulled ${added} reference${added === 1 ? '' : 's'} from the universe${skipped ? ` (${skipped} skipped)` : ''}`);- } else {- toast.error(skipped ? 'Every canon image is already a reference' : 'This universe has no canon images to pull yet');- }- })- .catch((err) => toast.error(err?.message || 'Failed to load the universe'))- .finally(() => setPulling(false));- };-return (<details className="mt-2 rounded border border-port-border bg-port-bg/40 p-2 group"><summary className="cursor-pointer text-xs text-port-text-muted select-none min-h-[44px] sm:min-h-[32px] flex items-center gap-2"><Palette size={13} /><span>Visual spec</span>- <span>· {references.length} reference{references.length === 1 ? '' : 's'}</span>- {flagged > 0 && <span className="text-port-accent">· {flagged} conditioning</span>}{palette.length > 0 && (<span className="flex gap-0.5" aria-hidden="true">{palette.map((c) => <span key={c} className="inline-block w-3 h-3 rounded-sm border border-port-border" style={{ backgroundColor: c }} />)}@@ -84,74 +34,6 @@ export default function VisualSpecPanel({ project, onSave, onAddReference }) {)}</summary><div className="mt-2 space-y-3">- <div className="space-y-1">- <div className="flex items-center justify-between gap-2">- <span className="text-xs text-port-text-muted">References</span>- <div className="flex items-center gap-1.5 flex-wrap">- {universeId && (- <button type="button" onClick={handlePullFromUniverse} disabled={pulling || references.length >= MAX_REFERENCES}- className="flex items-center gap-1 bg-port-border hover:bg-port-border/70 disabled:opacity-50 rounded px-2 py-1 text-xs min-h-[44px] sm:min-h-0"- title="Add this project's linked universe's canon character/place/object images as references">- <Sparkles size={13} /> {pulling ? 'Pulling…' : 'Pull from universe'}- </button>- )}- <button type="button" onClick={onAddReference} disabled={references.length >= MAX_REFERENCES}- className="flex items-center gap-1 bg-port-border hover:bg-port-border/70 disabled:opacity-50 rounded px-2 py-1 text-xs min-h-[44px] sm:min-h-0">- <ImagePlus size={13} /> Add reference- </button>- </div>- </div>- {references.length === 0 && (- <p className="text-[11px] text-port-text-muted">- Add character, wardrobe, set or mood images. Tick “Condition frames” to send one to every reference-frame render.- </p>- )}- <ul className="grid grid-cols-1 sm:grid-cols-2 xl:grid-cols-3 gap-2">- {references.map((ref) => (- <li key={ref.id} className="flex gap-2 rounded border border-port-border p-1.5 min-w-0">- <img src={`/data/images/${encodeURIComponent(ref.imageId)}`} alt="" loading="lazy" className="w-16 h-16 object-cover rounded shrink-0 bg-black" />- <div className="min-w-0 flex-1 space-y-1">- <div className="flex gap-1">- <label htmlFor={idFor(`role-${ref.id}`)} className="sr-only">Reference role</label>- <select id={idFor(`role-${ref.id}`)} value={ref.role || 'mood'}- onChange={(e) => updateRef(ref.id, { role: e.target.value })}- className="bg-port-bg border border-port-border rounded px-1 py-0.5 text-[11px] min-h-[44px] sm:min-h-0">- {ROLES.map(([value, label]) => <option key={value} value={value}>{label}</option>)}- </select>- <button type="button" onClick={() => saveReferences(references.filter((r) => r.id !== ref.id))}- aria-label="Remove reference" title="Remove reference"- className="ml-auto min-h-[32px] min-w-[32px] inline-flex items-center justify-center text-port-error">- <Trash2 size={12} />- </button>- </div>- <label htmlFor={idFor(`use-${ref.id}`)} className="sr-only">Reference use</label>- <select id={idFor(`use-${ref.id}`)} value={ref.use || 'reference'}- onChange={(e) => updateRef(ref.id, { use: e.target.value })}- className="w-full bg-port-bg border border-port-border rounded px-1 py-0.5 text-[11px] min-h-[44px] sm:min-h-0">- {USES.map(([value, label]) => <option key={value} value={value}>{label}</option>)}- </select>- <label htmlFor={idFor(`label-${ref.id}`)} className="sr-only">Reference label</label>- <input id={idFor(`label-${ref.id}`)} defaultValue={ref.label || ''} maxLength={120}- placeholder="Label (e.g. lead singer)"- onBlur={(e) => { if (e.target.value !== (ref.label || '')) updateRef(ref.id, { label: e.target.value }); }}- className="w-full bg-port-bg border border-port-border rounded px-1 py-0.5 text-[11px] min-h-[44px] sm:min-h-0" />- <label className="flex items-center gap-1 text-[11px] min-h-[44px] sm:min-h-0">- <input type="checkbox" checked={!!ref.condition}- disabled={!ref.condition && flagged >= MAX_CONDITIONING_REFERENCES}- onChange={(e) => updateRef(ref.id, { condition: e.target.checked })} />- Condition frames- </label>- </div>- </li>- ))}- </ul>- {flagged > 0 && (- <p className="text-[11px] text-port-text-muted">- Conditioning needs an image backend that accepts reference images (local FLUX.2 or Qwen Image 2.1, or a cloud image CLI); others refuse the render and say so. At most {MAX_CONDITIONING_REFERENCES} per frame.- </p>- )}- </div>-<div className="space-y-1"><span className="text-xs text-port-text-muted">Palette</span><div className="flex flex-wrap items-center gap-1">diff --git a/client/src/components/musicVideo/stages/SetupStage.jsx b/client/src/components/musicVideo/stages/SetupStage.jsxindex 209716af1c..c95366dea1 100644--- a/client/src/components/musicVideo/stages/SetupStage.jsx+++ b/client/src/components/musicVideo/stages/SetupStage.jsx@@ -1,7 +1,7 @@import { useState } from 'react';import AutonomousRunPanel from '../AutonomousRunPanel.jsx';import SongRevisionPanel from '../SongRevisionPanel.jsx';-import StyleReferencesPanel from '../StyleReferencesPanel.jsx';+import LookReferencesPanel from '../LookReferencesPanel.jsx';import AutoSizeTextarea from '../../ui/AutoSizeTextarea';import CreativeSetupPanel from '../CreativeSetupPanel.jsx';import TrackPanel, { AdvancedTrackControls } from '../TrackPanel.jsx';@@ -76,11 +76,11 @@ function AlignWords({ disabled, aligning, status, onAlign }) {}const directionSummary = (project) => {- const refs = (project.styleReferences || []).length;+ const refs = (project.visualSpec?.references || []).length + (project.styleReferences || []).length;return [project.concept?.prompt?.trim() ? 'Concept written' : 'No concept yet',project.concept?.style?.trim() ? 'Style set' : 'No style yet',- refs ? `${formatCount(refs)} style ${refs === 1 ? 'reference' : 'references'}` : 'No style references',+ refs ? `${formatCount(refs)} look ${refs === 1 ? 'reference' : 'references'}` : 'No look references',].join(' · ');};@@ -195,8 +195,9 @@ export default function SetupStage({ board }) {onPendingChange={board.setCreativeSetupPending}onSave={board.saveCreativeSetup}/>- <StyleReferencesPanel key={`moodboard-${project.id}`} project={project}- onSave={board.saveStyleReferences} onPendingChange={board.setStyleReferencesPending} />+ <LookReferencesPanel key={`look-${project.id}`} project={project}+ onSave={board.saveStyleReferences} onSaveSpec={board.saveVisualSpec} onAddReference={board.onAddReference}+ onPendingChange={board.setStyleReferencesPending} /><fieldset disabled={locked} className="min-w-0 space-y-2">{/* Concept & style — global direction for the video */}<div className="grid grid-cols-1 gap-2 sm:grid-cols-2">@@ -231,7 +232,6 @@ export default function SetupStage({ board }) {key={project.id}project={project}onSave={board.saveVisualSpec}- onAddReference={board.onAddReference}/></fieldset></StageSection>diff --git a/server/lib/musicVideoAutomation.js b/server/lib/musicVideoAutomation.jsindex b9e1ebdfae..1b43379f46 100644--- a/server/lib/musicVideoAutomation.js+++ b/server/lib/musicVideoAutomation.js@@ -55,14 +55,16 @@ export const MUSIC_VIDEO_AUTOMATION_BUDGET_MAX_USD = 100000;// The LLM text stages a director may route to their own provider/model/effort// (`automation.llmStages`). An unpinned stage uses the direction pin (`llm`).// `brief` / `lyrics` / `lyricsReview` run inside an autonomous run; `castAndSets`,-// `plan` and `authoring` run for every automation-first project.-export const MUSIC_VIDEO_LLM_STAGES = Object.freeze(['brief', 'lyrics', 'lyricsReview', 'castAndSets', 'plan', 'authoring']);+// `plan` and `authoring` run for every automation-first project; `treatment` is the+// director's Compile with AI on the Treatment brief (#10223).+export const MUSIC_VIDEO_LLM_STAGES = Object.freeze(['brief', 'lyrics', 'lyricsReview', 'castAndSets', 'plan', 'treatment', 'authoring']);export const MUSIC_VIDEO_LLM_STAGE_LABELS = Object.freeze({brief: 'Creative brief',lyrics: 'Lyrics draft',lyricsReview: 'Lyrics review & revise',castAndSets: 'Cast & sets direction',plan: 'Shot plan',+ treatment: 'Treatment compile',authoring: 'Code authoring',});// Stages that record the effective LLM route they last ran on (#9545): every LLM stage.diff --git a/server/routes/musicVideoTreatment.test.js b/server/routes/musicVideoTreatment.test.jsindex b5d454123f..5eddab0994 100644--- a/server/routes/musicVideoTreatment.test.js+++ b/server/routes/musicVideoTreatment.test.js@@ -111,7 +111,7 @@ describe('treatment compile', () => {const res = await compile(project.id, { baseRevision: 1, useAi: false });expect(res.status).toBe(200);expect(runPromptThroughProvider).not.toHaveBeenCalled();- expect(res.body).toMatchObject({ aiUsed: false, aiSkippedReason: 'not-requested' });+ expect(res.body).toMatchObject({ aiUsed: false, aiSkippedReason: 'not-requested', llmRoute: null });const stored = (await reload(project.id)).treatment;expect(stored.revision).toBe(2);@@ -174,7 +174,7 @@ describe('treatment compile', () => {});const res = await compile(project.id, { baseRevision: 1, providerId: 'test-llm', model: 'test-model' });expect(res.status).toBe(200);- expect(res.body).toMatchObject({ aiUsed: true, aiSkippedReason: null });+ expect(res.body).toMatchObject({ aiUsed: true, aiSkippedReason: null, llmRoute: { providerId: 'test-llm', model: 'test-model', transport: 'api', source: 'pinned' } });const prompt = runPromptThroughProvider.mock.calls[0][0];expect(prompt.source).toBe('music-video-treatment');expect(prompt.prompt).toContain('<<<REFERENCE_NOTES');diff --git a/server/services/musicVideo/treatmentService.js b/server/services/musicVideo/treatmentService.jsindex 0661a39370..3b9d7d7d66 100644--- a/server/services/musicVideo/treatmentService.js+++ b/server/services/musicVideo/treatmentService.js@@ -13,7 +13,8 @@*/import { ServerError } from '../../lib/errorHandler.js';-import { resolveProviderAndModel, runPromptThroughProvider } from '../promptRunner.js';+import { runPromptThroughProvider } from '../promptRunner.js';+import { effortArg, recordLlmRoute, resolveMusicVideoLlm } from './llmRoute.js';import { getProject, mutateProjectRecord } from './projects.js';import {applyTreatmentPatch,@@ -43,55 +44,64 @@ export async function updateTreatment(id, patch) {return { project, treatment: project.treatment };}-async function refineWithAi(project, draft, { providerId, model }) {- if (draft.shotDirections.length > MAX_SHOTS_FOR_AI) return { draft, reason: 'too-many-shots', used: null };- const { provider, selectedModel } = await resolveProviderAndModel({ providerId, model }).catch((err) => {+async function refineWithAi(project, draft, { providerId, model, effort }) {+ if (draft.shotDirections.length > MAX_SHOTS_FOR_AI) return { draft, reason: 'too-many-shots', used: null, route: null };+ // Request pin > the brief's treatment pin > its direction LLM > an eligible TUI provider > the active one (llmRoute.js).+ const { provider, selectedModel, route } = await resolveMusicVideoLlm({ providerId, model, effort, automation: project.automation, stage: 'treatment' }).catch((err) => {console.warn(`⚠️ Music Video treatment: provider resolution failed for ${project.id}: ${err.message}`);- return { provider: null, selectedModel: null };+ return { provider: null, selectedModel: null, route: null };});- if (!provider) return { draft, reason: 'no-provider', used: null };- if (provider.enabled === false) return { draft, reason: 'provider-disabled', used: null };+ if (!provider) return { draft, reason: 'no-provider', used: null, route: null };+ if (provider.enabled === false) return { draft, reason: 'provider-disabled', used: null, route };const used = { providerId: provider.id, model: selectedModel || null };let text;try {({ text } = await runPromptThroughProvider({provider,model: selectedModel,+ ...effortArg(route),prompt: buildTreatmentPrompt(project, draft),source: 'music-video-treatment',}));} catch (err) {console.warn(`⚠️ Music Video treatment: LLM call failed for ${project.id}: ${err.message}`);- return { draft, reason: 'llm-failed', used: null };+ return { draft, reason: 'llm-failed', used: null, route };}const parsed = parseTreatmentResponse(text);if (!parsed) {console.warn(`⚠️ Music Video treatment: unusable response for ${project.id}`);- return { draft, reason: 'unparsable-response', used: null };+ return { draft, reason: 'unparsable-response', used: null, route };}- return { draft: mergeAiTreatment(project, draft, parsed), reason: null, used };+ return { draft: mergeAiTreatment(project, draft, parsed), reason: null, used, route };}/*** Compile the treatment from the project's current inputs. Explicit user- * action only. Returns `{ project, treatment, aiUsed, aiSkippedReason }`.+ * action only. Returns `{ project, treatment, aiUsed, aiSkippedReason, llmRoute }`;+ * `llmRoute` is the effective provider/model/effort the AI call ran on (null when+ * AI was not requested or no provider resolved).*/-export async function compileTreatment(id, { baseRevision, useAi = true, providerId, model }) {+export async function compileTreatment(id, { baseRevision, useAi = true, providerId, model, effort }) {const project = await requireProject(id);const basis = treatmentBasis(project);let draft = buildTreatmentDraft(project);let aiSkippedReason = useAi ? null : 'not-requested';let used = null;+ let llmRoute = null;if (useAi) {- ({ draft, reason: aiSkippedReason, used } = await refineWithAi(project, draft, { providerId, model }));+ let route;+ ({ draft, reason: aiSkippedReason, used, route } = await refineWithAi(project, draft, { providerId, model, effort }));+ llmRoute = route || null;}const compiledWith = used ? { source: 'ai', ...used } : { source: 'deterministic', providerId: null, model: null };const { project: updated } = await mutateProjectRecord(id, (current) => ({project: writeCompiledTreatment(current, { baseRevision, draft, basis, compiledWith }),}));+ // The route is shown beside Compile; remember it only when the model actually answered.+ const persisted = (used && await recordLlmRoute(id, 'treatment', llmRoute)) || updated;const log = aiSkippedReason && useAi ? console.warn : console.log;log(`🎬 Music Video treatment: compiled ${draft.shotDirections.length} shot direction${draft.shotDirections.length === 1 ? '' : 's'} for ${id} (${used ? 'ai' : `deterministic${aiSkippedReason ? `: ${aiSkippedReason}` : ''}`})`);- return { project: updated, treatment: updated.treatment, aiUsed: !!used, aiSkippedReason };+ return { project: persisted, treatment: persisted.treatment, aiUsed: !!used, aiSkippedReason, llmRoute };}/** What Apply would change right now (read-only). */