Skip to content

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

feat: condition music video images with a project moodboard (#9293)

[._.]/ Adam Eivyf22c047c6a36
diff --git a/client/src/components/musicVideo/StyleReferencesPanel.jsx b/client/src/components/musicVideo/StyleReferencesPanel.jsx
new file mode 100644
index 0000000000..c2e3b6a046
--- /dev/null
+++ b/client/src/components/musicVideo/StyleReferencesPanel.jsx
@@ -0,0 +1,87 @@
+import { useEffect, useState } from 'react';
+import useMounted from '../../hooks/useMounted.js';
+import { uploadGalleryImage } from '../../services/apiSystem.js';
+import { IMAGE_ACCEPT, readFileAsBase64, validateImageFile } from '../../utils/fileUpload.js';
+import toast from '../ui/Toast';
+
+/** 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>
+ <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.jsx
new file mode 100644
index 0000000000..307d74b828
--- /dev/null
+++ b/client/src/components/musicVideo/StyleReferencesPanel.test.jsx
@@ -0,0 +1,44 @@
+import { describe, it, expect, vi } from 'vitest';
+import { render, screen, fireEvent, waitFor, act } from '@testing-library/react';
+import StyleReferencesPanel from './StyleReferencesPanel.jsx';
+
+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('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/stages/SetupStage.jsx b/client/src/components/musicVideo/stages/SetupStage.jsx
index c180861c0f..2b72d3656c 100644
--- a/client/src/components/musicVideo/stages/SetupStage.jsx
+++ b/client/src/components/musicVideo/stages/SetupStage.jsx
@@ -1,3 +1,4 @@
+import StyleReferencesPanel from '../StyleReferencesPanel.jsx';
import AutoSizeTextarea from '../../ui/AutoSizeTextarea';
import CreativeSetupPanel from '../CreativeSetupPanel.jsx';
import TrackPanel from '../TrackPanel.jsx';
@@ -25,6 +26,8 @@ export default function SetupStage({ board }) {
onPendingChange={board.setCreativeSetupPending}
onSave={board.saveCreativeSetup}
/>
+ <StyleReferencesPanel key={`moodboard-${project.id}`} project={project}
+ onSave={board.saveStyleReferences} onPendingChange={board.setStyleReferencesPending} />
<fieldset disabled={locked} className="min-w-0">
<div id="mv-track" className="space-y-2 rounded-lg border border-port-border bg-port-card p-3">
<TrackPanel
diff --git a/client/src/pages/MusicVideo.jsx b/client/src/pages/MusicVideo.jsx
index 3305139ca5..71e4cd12f0 100644
--- a/client/src/pages/MusicVideo.jsx
+++ b/client/src/pages/MusicVideo.jsx
@@ -119,6 +119,8 @@ export default function MusicVideo() {
const [analyzing, setAnalyzing] = useState(false);
const [arranging, setArranging] = useState(false);
const [creativeSetupPending, setCreativeSetupPending] = useState(false);
+ const [styleReferencesPending, setStyleReferencesPending] = useState(false);
+ useEffect(() => { setStyleReferencesPending(false); }, [selectedId]);
const [planning, setPlanning] = useState(false);
const [cloning, setCloning] = useState(false);
const [importingLyrics, setImportingLyrics] = useState(false);
@@ -362,7 +364,7 @@ export default function MusicVideo() {
// separate the vocal, align the words, then plan every shot against the
// brief (the planner reads automation.guidance). Each step only runs when
// its result is missing; lyric/vocal/alignment failures still plan.
- const autopilotBlockedReason = creativeSetupPending
+ const autopilotBlockedReason = (creativeSetupPending || styleReferencesPending)
? 'Save or cancel the creative setup before starting autopilot.'
: autopilotBlocker(selected);
const kickoff = useMusicVideoKickoff({
@@ -760,7 +762,7 @@ export default function MusicVideo() {
// use, so a panel moving between tabs never changes a signature here.
const board = selected ? {
project: selected,
- locked: creativeSetupPending,
+ locked: creativeSetupPending || styleReferencesPending,
busy: { analyzing, planning, arranging, cloning },
tracks,
trackName,
@@ -802,6 +804,10 @@ export default function MusicVideo() {
patchProject(project.id, { concept: project.concept, visualSpec: project.visualSpec });
}),
setCreativeSetupPending,
+ setStyleReferencesPending,
+ saveStyleReferences: (patch) => updateMusicVideoProject(selected.id, patch, { silent: true }).then((project) => {
+ patchProject(project.id, { styleReferences: project.styleReferences });
+ }),
setPickerTarget,
onAddReference: () => setPickerTarget({ type: 'reference' }),
onAnalyze: () => handleAnalyze(),
diff --git a/server/lib/README.md b/server/lib/README.md
index b5501dca1b..431b020a3d 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -800,4 +800,4 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `musicVideoAspect.js` | `musicVideoAspect(project)` (treatment brief aspect, default 16:9), `MUSIC_VIDEO_FRAME_GEN_SIZES` and `musicVideoFrameGenSize(project)`: the size every Music Video reference frame is requested at, so a backend never picks portrait for a 16:9 video. `musicVideoAtAspect(project, aspect)` re-frames the project for one render (a vertical social cut) without touching the record. Shared by `productionDispatch.js`, `documentRender.js` and the client board. |
| `musicVideoMotion.js` | `MOTION_CONTINUITY_CLAUSE`: the clause every Music Video motion (i2v) prompt ends with, pinning the reference frame's lighting, time of day and palette. Shared by `handoff.js` and the client board. |
-| `musicVideoConditioning.js` | `musicVideoConditioningReferences(project, scene)` selects the approved character sheet and scene's mapped set plate, with capped project-wide fallback; shared by board and production. |
+| `musicVideoConditioning.js` | `musicVideoStyleImages`, `musicVideoStylePrompt`, `musicVideoStyleBasis`, and `musicVideoStyleReferenceCapacity` supply bounded moodboard conditioning and text fallback; `musicVideoConditioningReferences(project, scene)` selects the approved character sheet and scene's mapped set plate, with capped project-wide fallback; shared by board and production. |
diff --git a/server/lib/musicVideoConditioning.js b/server/lib/musicVideoConditioning.js
index 1161269624..d0371dccb5 100644
--- a/server/lib/musicVideoConditioning.js
+++ b/server/lib/musicVideoConditioning.js
@@ -1,3 +1,6 @@
+import { isEditCapableMode, maxInputImages } from './imageGenCapabilities.js';
+import { RUNNER_FAMILIES } from './runners.js';
+
/** Browser-safe reference selection shared by the board and production lanes. */
export const MUSIC_VIDEO_MAX_CONDITIONING_REFERENCES = 4;
@@ -16,3 +19,34 @@ export function musicVideoConditioningReferences(project, scene) {
return references.filter((ref) => ref?.condition && ref.imageId)
.slice(0, MUSIC_VIDEO_MAX_CONDITIONING_REFERENCES);
}
+
+/** Style images fill spare slots after identities; never displace a character or set. */
+export function musicVideoStyleReferenceCapacity(mode, localModel) {
+ if (!isEditCapableMode(mode)) return 0;
+ if (mode === 'local') {
+ if (localModel?.pipelineClass === 'QwenImage21Pipeline') return 10;
+ return localModel?.runner === RUNNER_FAMILIES.FLUX2 ? 4 : 0;
+ }
+ return Math.min(4, maxInputImages(mode) ?? 4);
+}
+
+export const musicVideoStyleBasis = (project) => JSON.stringify(project?.styleReferences || []);
+
+export function musicVideoStylePrompt(project, referenceCount = 0) {
+ const refs = project?.styleReferences || [];
+ if (!refs.length) return '';
+ const treatment = project?.treatment;
+ const look = treatment?.styleReferencesBasis === musicVideoStyleBasis(project) && treatment?.styleLook
+ ? treatment.styleLook : refs.map((r) => r.caption?.trim()).filter(Boolean).join('; ').slice(0, 1000);
+ return `${referenceCount ? `The last ${referenceCount} reference images supply style, after the identity references. ` : ''}Moodboard style only (palette, lighting, lens language and grain; never copy its subjects, locations or poses)${look ? `: ${look}` : ''}`;
+}
+
+export function musicVideoStyleImages(project, identityImages, capacity) {
+ const seen = new Set(identityImages);
+ const available = Math.max(0, capacity - identityImages.length);
+ return (project?.styleReferences || []).filter((ref) => {
+ if (!ref?.imageId || seen.has(ref.imageId)) return false;
+ seen.add(ref.imageId);
+ return true;
+ }).slice(0, available).map((r) => r.imageId);
+}
diff --git a/server/lib/musicVideoValidation.js b/server/lib/musicVideoValidation.js
index 7211adec86..80b929d475 100644
--- a/server/lib/musicVideoValidation.js
+++ b/server/lib/musicVideoValidation.js
@@ -176,6 +176,11 @@ export const musicVideoVisualReferenceSchema = z.object({
use: z.enum(MUSIC_VIDEO_REFERENCE_USES).optional(),
}).strict();
+export const musicVideoStyleReferencesSchema = z.array(z.object({
+ imageId: galleryImageName,
+ caption: z.string().trim().max(500).optional(),
+}).strict()).max(8);
+
// The project's reusable visual specification. A patch merges per sub-field
// (like `concept`), and `references` / `palette` replace their list whole.
export const musicVideoVisualSpecSchema = z.object({
@@ -755,6 +760,7 @@ export const musicVideoProjectCreateSchema = z.object({
uploadedAudioFilename: z.string().max(256).nullable().optional(),
concept: musicVideoConceptSchema.nullable().optional(),
visualSpec: musicVideoVisualSpecSchema.optional(),
+ styleReferences: musicVideoStyleReferencesSchema.optional(),
videoSettings: musicVideoVideoSettingsSchema.optional(),
automation: musicVideoAutomationSchema.nullable().optional(),
lyricCues: lyricCueList.optional(),
@@ -773,6 +779,7 @@ export const musicVideoProjectUpdateSchema = z.object({
uploadedAudioFilename: z.string().max(256).nullable().optional(),
concept: musicVideoConceptSchema.nullable().optional(),
visualSpec: musicVideoVisualSpecSchema.optional(),
+ styleReferences: musicVideoStyleReferencesSchema.optional(),
videoSettings: musicVideoVideoSettingsSchema.optional(),
automation: musicVideoAutomationSchema.nullable().optional(),
renderHistoryId: z.string().max(64).nullable().optional(),
diff --git a/server/routes/musicVideo.test.js b/server/routes/musicVideo.test.js
index ef2b12f251..e0c5468492 100644
--- a/server/routes/musicVideo.test.js
+++ b/server/routes/musicVideo.test.js
@@ -732,3 +732,16 @@ describe('musicVideo routes', () => {
});
});
});
+
+it('validates a project moodboard as up to eight bounded gallery images', async () => {
+ const app = express();
+ app.use(express.json());
+ app.use('/api/music-video', musicVideoRoutes);
+ const styleReferences = Array.from({ length: 8 }, (_, i) => ({ imageId: `style-${i}.png`, caption: 'silver grain' }));
+ const saved = await request(app).patch('/api/music-video/mv-1').send({ styleReferences });
+ expect(saved.status).toBe(200);
+ expect(saved.body.styleReferences).toEqual(styleReferences);
+ for (const refs of [[...styleReferences, styleReferences[0]], [{ imageId: '../escape.png' }], [{ imageId: 'style.png', caption: 'a'.repeat(501) }]]) {
+ expect((await request(app).patch('/api/music-video/mv-1').send({ styleReferences: refs })).status).toBe(400);
+ }
+});
diff --git a/server/routes/musicVideoTreatment.test.js b/server/routes/musicVideoTreatment.test.js
index 3be580b8ef..2f3567598e 100644
--- a/server/routes/musicVideoTreatment.test.js
+++ b/server/routes/musicVideoTreatment.test.js
@@ -504,3 +504,19 @@ describe('treatment proofs, clone and motion references', () => {
expect(body.treatment.capabilityGaps.map((g) => g.id)).toContain('rotoscope');
});
});
+
+it('persists a treatment look once and invalidates its application when the moodboard changes', async () => {
+ const project = await plannedProject();
+ await projects.updateProject(project.id, { styleReferences: [{ imageId: 'look.png', caption: 'teal night, fine grain' }] });
+ runPromptThroughProvider.mockResolvedValueOnce({ text: JSON.stringify({
+ beats: [{ sectionIndex: 0, objective: 'Reveal the harbor' }], styleLook: 'Teal night with fine grain.',
+ }) });
+ const result = await compile(project.id, { baseRevision: 0 });
+ expect(result.status).toBe(200);
+ expect(result.body.treatment.styleLook).toBe('Teal night with fine grain.');
+ expect((await reload(project.id)).treatment.styleLook).toBe('Teal night with fine grain.');
+ expect(runPromptThroughProvider.mock.calls.at(-1)[0].prompt).toContain('teal night, fine grain');
+ await projects.updateProject(project.id, { styleReferences: [{ imageId: 'new.png', caption: 'warm daylight' }] });
+ const preview = await request(app).get(`${base(project.id)}/treatment/apply-preview`);
+ expect(preview.body.stale.some((entry) => entry.input === 'visualSpec')).toBe(true);
+});
diff --git a/server/services/imageGen/prepareParams.js b/server/services/imageGen/prepareParams.js
index 7622e62e12..cc42a73208 100644
--- a/server/services/imageGen/prepareParams.js
+++ b/server/services/imageGen/prepareParams.js
@@ -28,6 +28,7 @@
*/
import { randomUUID } from 'crypto';
+import { musicVideoStyleImages, musicVideoStylePrompt, musicVideoStyleReferenceCapacity } from '../../lib/musicVideoConditioning.js';
import { join } from 'node:path';
import { ServerError } from '../../lib/errorHandler.js';
import { PATHS, ensureDir, resolveGalleryImage, copyFileGuarded, unlinkGuarded } from '../../lib/fileUtils.js';
@@ -131,7 +132,9 @@ export async function prepareGenerateParams({ data, files, referenceImageFields
const initUpload = files?.initImage;
const referenceImagePaths = [];
const referenceImageStrengths = [];
- const namedReferenceFiles = Array.isArray(data.referenceImageFiles) ? data.referenceImageFiles : [];
+ const namedReferenceFiles = Array.isArray(data.referenceImageFiles) ? [...data.referenceImageFiles] : [];
+ let musicVideoProject = null;
+ let musicVideoProjectLoaded = false;
// Pair strengths by PACK position (post-filter), not slot position — the
// client renumbers populated slots into `referenceImage1..N` and sends a
@@ -195,6 +198,7 @@ export async function prepareGenerateParams({ data, files, referenceImageFields
const source = data.mode ? null : RECORD_PIN_SOURCES.find((s) => data[s.tag]?.[s.idKey]);
if (source) {
const record = await source.load(data[source.tag][source.idKey]).catch(() => null);
+ if (source.tag === 'musicVideo') { musicVideoProject = record; musicVideoProjectLoaded = true; }
const pin = recordRenderPin(record || {});
const resolved = resolveRenderTargetConfig(settings, source.target, {
model: data.cloudModel || null,
@@ -219,10 +223,19 @@ export async function prepareGenerateParams({ data, files, referenceImageFields
// request or named by an earlier one) plus every reference slot. Every gate
// below keys off these two, rather than respelling "carries input images"
// per gate and having to keep the spellings in sync.
+ const localModel = mode === IMAGE_GEN_MODE.LOCAL ? selectLocalImageModelFromSettings(settings, data.modelId, getImageModels(), localModelCandidates) : null;
+ if (data.musicVideo?.sceneId) {
+ if (!musicVideoProjectLoaded) musicVideoProject = await getMusicVideoProject(data.musicVideo.projectId).catch(() => null);
+ const reservedSlots = referenceUploads.length + (initUpload || data.initImageFile ? 1 : 0);
+ const capacity = Math.max(0, musicVideoStyleReferenceCapacity(mode, localModel) - reservedSlots);
+ const styles = musicVideoStyleImages(musicVideoProject, namedReferenceFiles, capacity);
+ // Named inputs precede uploads. Keep the latter's packed strength positions intact.
+ if (!referenceUploads.length) namedReferenceFiles.push(...styles);
+ const look = musicVideoStylePrompt(musicVideoProject, referenceUploads.length ? 0 : styles.length);
+ if (look) data.prompt = [data.prompt, look].filter(Boolean).join('. ');
+ }
const referenceImageCount = namedReferenceFiles.length + referenceUploads.length;
const inputImageCount = (initUpload || data.initImageFile ? 1 : 0) + referenceImageCount;
-
- const localModel = mode === IMAGE_GEN_MODE.LOCAL ? selectLocalImageModelFromSettings(settings, data.modelId, getImageModels(), localModelCandidates) : null;
// Freeze the selected preference before capability checks. Explicit ids stay
// untouched so the existing unknown/hardware rejection still applies.
if (!data.modelId && localModel?.id) data.modelId = localModel.id;
diff --git a/server/services/imageGen/prepareParams.test.js b/server/services/imageGen/prepareParams.test.js
index e027635e92..4fb45241dc 100644
--- a/server/services/imageGen/prepareParams.test.js
+++ b/server/services/imageGen/prepareParams.test.js
@@ -168,8 +168,8 @@ describe('music-video render-target resolution (#3231 Phase 4)', () => {
const { data, mode } = await run({ prompt: 'p', mode: 'local', musicVideo: { projectId: 'mv-1', sceneId: 's1' } });
expect(mode).toBe('local');
expect(data.cloudModel).toBeUndefined();
- // Explicit mode wins outright, so the project store isn't even consulted.
- expect(getProject).not.toHaveBeenCalled();
+ // The project is read for style references, but its renderer pin cannot override the explicit mode.
+ expect(getProject).toHaveBeenCalledOnce();
});
it('falls through to the install default with no pins, and a missing project is harmless', async () => {
@@ -274,3 +274,12 @@ describe('universe render-target resolution', () => {
expect(data.cloudModelIsShippedDefault).toBe(false);
});
});
+
+it('uses moodboard caption text on a backend without image-reference support', async () => {
+ getSettings.mockResolvedValue({ imageGen: { mode: 'external' } });
+ getProject.mockResolvedValue({ styleReferences: [{ imageId: 'style.png', caption: 'fine silver grain' }] });
+ const { data, mode } = await run({ prompt: 'a lighthouse', musicVideo: { projectId: 'mv-1', sceneId: 's1' } });
+ expect(mode).toBe('external');
+ expect(data.prompt).toContain('fine silver grain');
+ expect(data.referenceImagePaths).toBeUndefined();
+});
diff --git a/server/services/musicVideo/castAndSetsService.js b/server/services/musicVideo/castAndSetsService.js
index be8d4cd908..1d912a2e4a 100644
--- a/server/services/musicVideo/castAndSetsService.js
+++ b/server/services/musicVideo/castAndSetsService.js
@@ -1,3 +1,4 @@
+import { withMusicVideoStyle } from './styleReferences.js';
/**
* Music Video — Cast & Sets check-in orchestrator.
*
@@ -262,7 +263,9 @@ async function enqueueImage(project, stage, key) {
} : {}),
},
};
- const params = await deps.imageParams(await deps.getSettings(), stage.route, common);
+ const settings = await deps.getSettings();
+ const baseParams = await deps.imageParams(settings, stage.route, common);
+ const params = await withMusicVideoStyle(project, baseParams, stage.route.mode, stage.route.model, settings);
return deps.enqueue({ kind: 'image', params, owner: `music-video-cast-sets:${project.id}` });
}
diff --git a/server/services/musicVideo/castAndSetsService.test.js b/server/services/musicVideo/castAndSetsService.test.js
index 3ff1b90b48..f8626d2943 100644
--- a/server/services/musicVideo/castAndSetsService.test.js
+++ b/server/services/musicVideo/castAndSetsService.test.js
@@ -325,3 +325,13 @@ describe('Cast & Sets check-in', () => {
expect(skipped.body.stage.status).toBe('skipped');
});
});
+
+it('uses project moodboard style images for Cast & Sets without a linked board', async () => {
+ const project = await seed({ visualSpec: null, styleReferences: [{ imageId: 'style.png', caption: 'silver grain' }] });
+ await service.startCastAndSets(project.id);
+ await runTo(project.id, 'review');
+ expect(jobs[0].params.referenceImagePaths.some((p) => p.endsWith('style.png'))).toBe(true);
+ expect(jobs[0].params.prompt).toContain('silver grain');
+ const dependent = jobs.find((j) => j.params.referenceImagePaths?.length > 1);
+ expect(dependent.params.referenceImagePaths.at(-1)).toMatch(/style.png$/);
+});
diff --git a/server/services/musicVideo/production.js b/server/services/musicVideo/production.js
index 525dab6022..18935de015 100644
--- a/server/services/musicVideo/production.js
+++ b/server/services/musicVideo/production.js
@@ -112,6 +112,7 @@ function productionBasisRevision(project) {
return canonicalSnapshotChecksum({
concept: pick(project?.concept),
visualSpec: pick(project?.visualSpec),
+ ...(project?.styleReferences?.length ? { styleReferences: project.styleReferences } : {}),
brief: pick(project?.treatment?.brief),
automation: pick(project?.automation),
audio: {
diff --git a/server/services/musicVideo/productionDispatch.js b/server/services/musicVideo/productionDispatch.js
index 39ef7224cf..8c9e5325b2 100644
--- a/server/services/musicVideo/productionDispatch.js
+++ b/server/services/musicVideo/productionDispatch.js
@@ -20,6 +20,7 @@
* passes the revision's enqueue-time guard first, exactly as the routes do.
*/
+import { withMusicVideoStyle } from './styleReferences.js';
import { ServerError } from '../../lib/errorHandler.js';
import { resolveGalleryImage } from '../../lib/pathSafety.js';
import { RENDER_TARGET } from '../../lib/renderTargets.js';
@@ -66,9 +67,10 @@ async function dispatchFrame({ project, scene, route, tag, settings }) {
...(referenceImagePaths.length ? { referenceImagePaths, referenceImageStrengths: referenceImagePaths.map(() => 1) } : {}),
musicVideo: tag,
};
- const params = resolved.cloud
+ const baseParams = resolved.cloud
? { ...resolved.cloud.jobParams, ...common }
: { pythonPath: settings.imageGen?.local?.pythonPath || null, modelId: route.model, ...common };
+ const params = await withMusicVideoStyle(project, baseParams, route.mode, route.model, settings);
await guardRevision(tag, 'image');
const { jobId } = await enqueueJob({ kind: 'image', params, owner: `music-video-production:${tag.productionRunId}` });
return { jobId };
diff --git a/server/services/musicVideo/productionDispatch.test.js b/server/services/musicVideo/productionDispatch.test.js
index 5454de8cf3..f81aa73c33 100644
--- a/server/services/musicVideo/productionDispatch.test.js
+++ b/server/services/musicVideo/productionDispatch.test.js
@@ -63,6 +63,16 @@ describe('production scene dispatch (#9066)', () => {
}
});
+ it('appends capped style images after identities and carries a text look', async () => {
+ await dispatchProductionStep({ stepKind: 'frame', project: { ...project,
+ styleReferences: Array.from({ length: 8 }, (_, i) => ({ imageId: `style-${i}.png`, caption: 'teal shadows, fine grain' })),
+ }, scene, route: { kind: 'image', mode: 'codex', model: null }, tag, settings });
+ const params = enqueueJob.mock.calls[0][0].params;
+ expect(params.referenceImagePaths.map((p) => basename(p))).toEqual(['ref-example.png', 'style-0.png', 'style-1.png', 'style-2.png']);
+ expect(params.prompt).toContain('teal shadows, fine grain');
+ expect(params.referenceImageStrengths).toEqual([1, 1, 1, 1]);
+ });
+
it('refuses a disabled backend instead of rendering on another one', async () => {
await expect(dispatchProductionStep({ stepKind: 'frame', project, scene, route: { kind: 'image', mode: 'grok', model: null }, tag, settings }))
.rejects.toThrow(/disabled/);
diff --git a/server/services/musicVideo/projectsLogic.js b/server/services/musicVideo/projectsLogic.js
index 7797f0ef79..1349b0faff 100644
--- a/server/services/musicVideo/projectsLogic.js
+++ b/server/services/musicVideo/projectsLogic.js
@@ -117,6 +117,7 @@ export function buildProjectRecord(input, { id, now }) {
// #8965 — the reusable visual specification (moodboard/reference assets,
// palette, typography, camera rules). Null until the director sets one.
visualSpec: input.visualSpec ? normalizeVisualSpec(input.visualSpec) : null,
+ ...(input.styleReferences ? { styleReferences: input.styleReferences } : {}),
videoSettings: {
backend: videoSettings.backend ?? 'local',
modelId: videoSettings.modelId ?? null,
diff --git a/server/services/musicVideo/projectsLogic.test.js b/server/services/musicVideo/projectsLogic.test.js
index 666b38ca91..eb9bd60431 100644
--- a/server/services/musicVideo/projectsLogic.test.js
+++ b/server/services/musicVideo/projectsLogic.test.js
@@ -742,3 +742,12 @@ describe('composition document (render style `document`)', () => {
expect(next.composition.document).toEqual(pointer);
});
});
+
+it('preserves optional project moodboard uploads through create, patch and clone', () => {
+ const styleReferences = [{ imageId: 'style.png', caption: 'silver grain' }];
+ const project = buildProjectRecord({ name: 'Example', styleReferences }, { id: 'mv-example', now: '2026-01-01' });
+ expect(project.styleReferences).toEqual(styleReferences);
+ expect(applyProjectPatch(project, { name: 'Updated' }).styleReferences).toEqual(styleReferences);
+ expect(cloneProjectRecord(project, { id: 'mv-clone', now: '2026-01-02' }).styleReferences).toEqual(styleReferences);
+ expect(applyProjectPatch(project, { styleReferences: [] }).styleReferences).toEqual([]);
+});
diff --git a/server/services/musicVideo/styleReferences.js b/server/services/musicVideo/styleReferences.js
new file mode 100644
index 0000000000..a1466bc3d7
--- /dev/null
+++ b/server/services/musicVideo/styleReferences.js
@@ -0,0 +1,27 @@
+import { basename } from 'node:path';
+import { resolveGalleryImage } from '../../lib/pathSafety.js';
+import { musicVideoStyleImages, musicVideoStylePrompt, musicVideoStyleReferenceCapacity } from '../../lib/musicVideoConditioning.js';
+
+/** Resolve style capacity on the actual route, preserving every explicit identity input. */
+export async function withMusicVideoStyle(project, params, mode, model, settings) {
+ if (!project?.styleReferences?.length) return params;
+ let localModel = null;
+ if (mode === 'local') {
+ const [{ selectLocalImageModelFromSettings }, { getImageModels }] = await Promise.all([
+ import('../imageGen/prepareParams.js'), import('../../lib/mediaModels.js'),
+ ]);
+ localModel = selectLocalImageModelFromSettings(settings, model, getImageModels());
+ }
+ const identities = params.referenceImagePaths || [];
+ const capacity = musicVideoStyleReferenceCapacity(mode, localModel);
+ const styles = musicVideoStyleImages(project, identities.map((p) => basename(p)), capacity)
+ .map((id) => resolveGalleryImage(id, { mustExist: false })).filter((p) => p && !identities.includes(p));
+ return {
+ ...params,
+ prompt: [params.prompt, musicVideoStylePrompt(project, styles.length)].filter(Boolean).join('. '),
+ ...(styles.length ? {
+ referenceImagePaths: [...identities, ...styles],
+ referenceImageStrengths: [...(params.referenceImageStrengths || identities.map(() => 1)), ...styles.map(() => 1)],
+ } : {}),
+ };
+}
diff --git a/server/services/musicVideo/treatment.js b/server/services/musicVideo/treatment.js
index e355dbeb32..aff3054762 100644
--- a/server/services/musicVideo/treatment.js
+++ b/server/services/musicVideo/treatment.js
@@ -262,6 +262,7 @@ function normalizeTreatment(input, now = new Date().toISOString()) {
revision: Number.isInteger(input.revision) && input.revision > 0 ? input.revision : 1,
brief: normalizeBrief(input.brief, null, now),
arc: normalizeArc(input.arc),
+ ...(typeof input.styleLook === 'string' ? { styleLook: input.styleLook.slice(0, 1000), styleReferencesBasis: input.styleReferencesBasis } : {}),
shotDirections: normalizeShotDirections(input.shotDirections),
proofs: normalizeProofs(input.proofs),
capabilityGaps: normalizeGaps(input.capabilityGaps),
@@ -321,7 +322,7 @@ export function treatmentBasis(project) {
visualSpec: fingerprint([project?.concept || null, spec ? [
(spec.references || []).map((r) => [r.imageId, r.role || 'mood', r.use || 'reference', r.label || '', r.note || '']),
spec.palette || [], spec.typography || '', spec.cameraRules || '',
- ] : null]),
+ ] : null, ...(project?.styleReferences?.length ? [project.styleReferences] : [])]),
lyrics: fingerprint((project?.lyricCues || []).map((c) => [c.text, c.startSec ?? null, c.endSec ?? null])),
scenes: fingerprint((project?.scenes || []).map((s) => [s.sceneId, s.startSec ?? null, s.endSec ?? null])),
};
@@ -403,6 +404,7 @@ export function writeCompiledTreatment(project, { baseRevision, draft, basis, co
...(existing || blankTreatment(now)),
brief: normalizeBrief({ graphicLanguage: draft.graphicLanguage || existing?.brief?.graphicLanguage }, existing?.brief, now),
arc: normalizeArc(draft.arc),
+ ...(project.styleReferences?.length ? { styleLook: draft.styleLook ?? '', styleReferencesBasis: draft.styleReferencesBasis ?? null } : {}),
shotDirections: normalizeShotDirections(draft.shotDirections),
// A new compile proposes a fresh checklist: earlier verdicts reviewed
// different shots/direction.
diff --git a/server/services/musicVideo/treatmentDraft.js b/server/services/musicVideo/treatmentDraft.js
index 154ef72d19..e0db9997f4 100644
--- a/server/services/musicVideo/treatmentDraft.js
+++ b/server/services/musicVideo/treatmentDraft.js
@@ -1,3 +1,4 @@
+import { musicVideoStyleBasis, musicVideoStylePrompt } from '../../lib/musicVideoConditioning.js';
import { musicVideoCreativeContext } from '../../lib/musicVideoCreativeContext.js';
/**
* Music Video — treatment compiler (#8980).
@@ -372,6 +373,8 @@ export function buildTreatmentPrompt(project, draft) {
spec.palette?.length && `Palette: ${spec.palette.join(' ')}`,
spec.cameraRules && `Camera rules: ${quote(spec.cameraRules)}`,
].filter(Boolean);
+ const styleLook = musicVideoStylePrompt(project);
+ if (styleLook) briefLines.push(styleLook);
const refs = (spec.references || []).map((r) => `- ${r.role || 'mood'} reference${r.label ? ` "${quote(r.label, 80)}"` : ''} (use: ${r.use || 'reference'})${r.note ? ` — ${quote(r.note, 120)}` : ''}`);
const notes = brief.referenceNotes.map((n) => `- ${n.note ? quote(n.note, 300) : '(no note)'}${n.url ? ` [source: ${quote(n.url, 200)}]` : ''}`);
const beatLines = draft.arc.beats.map((b) => `sectionIndex ${b.sectionIndexes[0]}: "${b.label}" ${b.startSec.toFixed(1)}–${b.endSec.toFixed(1)}s, energy ${b.energy}, role ${b.role.toUpperCase()}`);
@@ -394,7 +397,7 @@ The planned shots (index; arc role / section; duration; the lyric lines sung dur
${shotLines.join('\n')}
Write the treatment:
-- For each section, an "objective" (what the picture must achieve there) and a "rationale" tied to the audience, the lyrics or the emotion. Keep the roles as given.
+${project.styleReferences?.length ? '- "styleLook": one short sentence summarizing palette, lighting, lens language and grain from the moodboard captions; do not invent subjects or places.\n' : ''}- For each section, an "objective" (what the picture must achieve there) and a "rationale" tied to the audience, the lyrics or the emotion. Keep the roles as given.
- Two or three recurring "motifs" (an image, object, color or gesture) with how each changes across the arc.
- The balance of "performance", "cutaway" and "graphic" shots as percentages, with a rationale.
- "graphicLanguage": a concise visual note for the graphic cards and typography (HUD, pictograms, counters), honoring any graphic direction in the brief.
@@ -493,5 +496,7 @@ export function mergeAiTreatment(project, draft, parsed) {
}
const scenes = directions.map((d) => scenesById.get(d.sceneId)).filter(Boolean);
const graphicLanguage = brief.graphicLanguage || strField(parsed.graphicLanguage, 1000) || draft.graphicLanguage;
- return { ...finalize(project, brief, arc, directions, scenes), graphicLanguage };
+ return { ...finalize(project, brief, arc, directions, scenes), graphicLanguage,
+ ...(project.styleReferences?.length ? { styleLook: strField(parsed.styleLook, 1000) ?? '', styleReferencesBasis: musicVideoStyleBasis(project) } : {}),
+ };
}
diff --git a/server/services/sharing/peerSyncAssets.js b/server/services/sharing/peerSyncAssets.js
index eb439b4e5f..bb85489f38 100644
--- a/server/services/sharing/peerSyncAssets.js
+++ b/server/services/sharing/peerSyncAssets.js
@@ -581,6 +581,7 @@ export async function referenceMusicVideoAssetManifest(project, { linkedTrack }
...scenes.map((s) => (isStr(s?.referenceImageId) ? s.referenceImageId : null)).filter(Boolean),
...takeIds('image'),
...specRefs.map((r) => (isStr(r?.imageId) ? r.imageId : null)).filter(Boolean),
+ ...(Array.isArray(project?.styleReferences) ? project.styleReferences : []).map((r) => (isStr(r?.imageId) ? r.imageId : null)).filter(Boolean),
])];
if (imageNames.length) {
const entries = imageNames.map(imageAssetReference);
diff --git a/server/services/sharing/peerSyncAssets.test.js b/server/services/sharing/peerSyncAssets.test.js
index 19d9f2e411..df6e1f87b4 100644
--- a/server/services/sharing/peerSyncAssets.test.js
+++ b/server/services/sharing/peerSyncAssets.test.js
@@ -176,12 +176,13 @@ describe('buildMusicVideoAssetManifest — scene takes + visual spec (#8965)', (
});
it('ships every take and moodboard reference a peer may select, not only the selected slot', async () => {
- for (const name of ['selected.png', 'candidate.png', 'mood.png']) writeImage(name, Buffer.from(name));
+ for (const name of ['selected.png', 'candidate.png', 'mood.png', 'style.png']) writeImage(name, Buffer.from(name));
writeVideo('clip-a.mp4', Buffer.from('a'));
writeVideo('clip-b.mp4', Buffer.from('b'));
const manifest = await buildMusicVideoAssetManifest({
trackId: null,
uploadedAudioFilename: null,
+ styleReferences: [{ imageId: 'style.png', caption: 'silver grain' }, { imageId: '../escape.png' }],
visualSpec: { references: [{ id: 'r1', imageId: 'mood.png' }, { id: 'r2', imageId: '../escape.png' }] },
scenes: [{
sceneId: 's1',
@@ -197,7 +198,7 @@ describe('buildMusicVideoAssetManifest — scene takes + visual spec (#8965)', (
});
const keys = manifest.map((m) => `${m.kind}:${m.filename}`).sort();
expect(keys).toEqual([
- 'image:candidate.png', 'image:mood.png', 'image:selected.png',
+ 'image:candidate.png', 'image:mood.png', 'image:selected.png', 'image:style.png',
'video:clip-a.mp4', 'video:clip-b.mp4',
]);
});