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: give commission style-source reference images to scene evaluation and local renders (#8724)

[._.]/ Adam Eivy93446e5b747a
diff --git a/docs/features/product-surfaces.md b/docs/features/product-surfaces.md
index 5009946778..e647bdf83c 100644
--- a/docs/features/product-surfaces.md
+++ b/docs/features/product-surfaces.md
@@ -109,7 +109,7 @@ An end-to-end creative production suite for authors, worldbuilders, filmmakers,
| **Rounds & Rounds Guide** | `/rounds`, `/rounds/guide` | Composition and learning tool for a cappella musical rounds, multi-part vocal harmonies, lead sheets, and solfège notation. | — |
| **SongBook** | `/songbook` | Interactive chord charts, guitar tablature, lyric repertoire, and auto-scrolling practice sheet music. | — |
| **Creative Director** | `/creative-director` | Multi-scene episodic video production orchestrator: turn briefs into treatments, storyboards, render plans, and completed episodes. | — |
-| **Creative Commissions** | `/creative-commission` | Standing briefs and scheduled/nightly autonomous media generation aligning with personal taste profiles and feedback. A universe and/or mood board can be picked as the style source: each run loads its style tags and reference images as the Creative Director's art-direction base. | — |
+| **Creative Commissions** | `/creative-commission` | Standing briefs and scheduled/nightly autonomous media generation aligning with personal taste profiles and feedback. A universe and/or mood board can be picked as the style source: each run loads its style tags and reference images as the Creative Director's art-direction base, attaches those images to vision scene evaluation, and conditions local image renders on them. | — |
| **Music Video Studio** | `/music-video` | Audio-reactive video creation, beat-detection synchronization, scene choreography, and tempo alignment. | — |
| **Sharing & Conflict Resolution** | `/sharing`, `/sharing/duplicates`, `/sharing/conflicts` | Collaborative asset exchange via cloud storage buckets (Google Drive, Dropbox, iCloud, Syncthing) with duplicate reconciliation and conflict recovery journals. | — |
diff --git a/server/services/creative/tools/media.js b/server/services/creative/tools/media.js
index b41dbfd1c2..e033e9d553 100644
--- a/server/services/creative/tools/media.js
+++ b/server/services/creative/tools/media.js
@@ -280,6 +280,27 @@ async function enforceRenderBackendPin(kind, params, project) {
};
}
+/**
+ * Condition a LOCAL image render on the owning project's style reference
+ * images (#8724) — the universe / mood-board images a Creative Commission's
+ * style source resolved at fire time.
+ *
+ * Runs after the backend pin, so `params.mode` is final: absent means the
+ * queue's local default, which is also what an unpinned project renders on.
+ * Cloud modes are left alone — their "input image" wiring edits that image
+ * rather than borrowing its style. A planner that already chose its own
+ * `referenceImagePaths` wins. A project without style references (every bare
+ * CD project) returns `params` untouched.
+ */
+async function applyStyleReferenceImages(params, project) {
+ if (!project?.styleReferenceImages?.length) return params;
+ if (params?.mode && params.mode !== IMAGE_GEN_MODE.LOCAL) return params;
+ if (Array.isArray(params?.referenceImagePaths) && params.referenceImagePaths.length) return params;
+ const { styleReferenceImagePaths } = await import('../../creativeStyleSources.js');
+ const referenceImagePaths = styleReferenceImagePaths(project.styleReferenceImages);
+ return referenceImagePaths.length ? { ...params, referenceImagePaths } : params;
+}
+
// Load the owning CD project ONCE per enqueue — both the video preset
// reconciliation and the render-backend pin read from it, and re-reading would
// double the store round-trips per plan step. Null outside a project context (a
@@ -324,6 +345,7 @@ const mediaTool = (kind, label) => ({
if (kind === 'video') params = enforceVideoRenderPreset(params, project);
if (kind === 'image') params = enforceImageRenderPreset(params, project);
params = await enforceRenderBackendPin(kind, params, project);
+ if (kind === 'image') params = await applyStyleReferenceImages(params, project);
// Resolve the selected local model AFTER the backend ladder has applied
// project/install pins. The same model-catalog fields that drive Video
// Gen's visible controls then snap the autonomous job onto that model's
diff --git a/server/services/creative/tools/media.test.js b/server/services/creative/tools/media.test.js
index c2608f1aba..2c81023b7c 100644
--- a/server/services/creative/tools/media.test.js
+++ b/server/services/creative/tools/media.test.js
@@ -1,4 +1,7 @@
-import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
+import { describe, it, expect, vi, beforeEach, afterEach, beforeAll, afterAll } from 'vitest';
+import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from 'fs';
+import { tmpdir } from 'os';
+import { join } from 'path';
// Mock only what the media tools reach for. The queue is the observable
// boundary — every assertion here is about the params that land on it, because
@@ -31,6 +34,7 @@ vi.mock('../../federatedMedia/remoteSubmission.js', () => ({
import { enqueueJob } from '../../mediaJobQueue/index.js';
import { getProject } from '../../creativeDirector/local.js';
+import { PATHS } from '../../../lib/fileUtils.js';
import { MEDIA_TOOLS, reconcileVideoParamsWithModel } from './media.js';
const tool = (name) => MEDIA_TOOLS.find((t) => t.name === name);
@@ -255,6 +259,69 @@ describe('render-backend pin — image (#3135)', () => {
});
});
+describe('commission style reference images (#8724)', () => {
+ // Real files under temp gallery / image-ref roots, so the filename → path
+ // resolution the render actually receives is exercised, not stubbed.
+ let tempRoot;
+ const saved = {};
+ beforeAll(() => {
+ tempRoot = mkdtempSync(join(tmpdir(), 'cd-style-refs-'));
+ saved.images = PATHS.images;
+ saved.imageRefs = PATHS.imageRefs;
+ PATHS.images = join(tempRoot, 'images');
+ PATHS.imageRefs = join(tempRoot, 'image-refs');
+ mkdirSync(PATHS.images, { recursive: true });
+ mkdirSync(PATHS.imageRefs, { recursive: true });
+ writeFileSync(join(PATHS.images, 'board-pin.png'), 'x');
+ writeFileSync(join(PATHS.imageRefs, 'universe-ref.png'), 'x');
+ });
+ afterAll(() => {
+ PATHS.images = saved.images;
+ PATHS.imageRefs = saved.imageRefs;
+ rmSync(tempRoot, { recursive: true, force: true });
+ });
+
+ const styledProject = (extra = {}) => ({
+ id: 'cd-1',
+ styleReferenceImages: [
+ { kind: 'image-ref', filename: 'universe-ref.png', label: 'Universe style reference', origin: 'universe' },
+ { kind: 'image', filename: 'board-pin.png', label: 'Pinned image', origin: 'mood-board' },
+ // Deleted since the fire (or never synced to this peer) — skipped.
+ { kind: 'image', filename: 'gone.png', label: 'Missing', origin: 'mood-board' },
+ ],
+ ...extra,
+ });
+
+ it('conditions a local render on the project style references', async () => {
+ getProject.mockResolvedValue(styledProject());
+ await run('media_enqueueImageJob', { prompt: 'p' }, { projectId: 'cd-1' });
+ expect(enqueued().params.referenceImagePaths).toEqual([
+ join(PATHS.imageRefs, 'universe-ref.png'),
+ join(PATHS.images, 'board-pin.png'),
+ ]);
+ });
+
+ it('keeps the references the planner chose itself', async () => {
+ getProject.mockResolvedValue(styledProject());
+ await run('media_enqueueImageJob', { prompt: 'p', referenceImagePaths: ['/planner/pick.png'] }, { projectId: 'cd-1' });
+ expect(enqueued().params.referenceImagePaths).toEqual(['/planner/pick.png']);
+ });
+
+ it('leaves a cloud-pinned render unchanged', async () => {
+ getSettings.mockResolvedValue({ imageGen: { grok: { enabled: true, grokPath: '/bin/grok' } } });
+ getProject.mockResolvedValue(styledProject({ renderBackend: { image: { mode: 'grok' } } }));
+ await run('media_enqueueImageJob', { prompt: 'p' }, { projectId: 'cd-1' });
+ expect(enqueued().params.mode).toBe('grok');
+ expect(enqueued().params).not.toHaveProperty('referenceImagePaths');
+ });
+
+ it('enqueues byte-identical params for a project without style references', async () => {
+ getProject.mockResolvedValue({ id: 'cd-1' });
+ await run('media_enqueueImageJob', { prompt: 'p' }, { projectId: 'cd-1' });
+ expect(enqueued().params).toEqual({ prompt: 'p' });
+ });
+});
+
describe('render-backend pin — video (#3135)', () => {
it('locks a video commission to the form duration instead of a planner beat', async () => {
getProject.mockResolvedValue({
diff --git a/server/services/creativeCommissions/scheduler.js b/server/services/creativeCommissions/scheduler.js
index 6a5547443f..ae5eeba53e 100644
--- a/server/services/creativeCommissions/scheduler.js
+++ b/server/services/creativeCommissions/scheduler.js
@@ -490,6 +490,10 @@ async function fireCommission(commission, trigger) {
name: `${baseName}${dateSuffix}`,
...projectParams,
styleSpec: composeCommissionStyleSpec(commission.brief?.styleSpec, styleSource),
+ // The style source's reference images as data, not just served paths in
+ // the styleSpec text: scene evaluation attaches them to its vision call
+ // and local image renders condition on them (#8724).
+ styleReferenceImages: styleSource?.images,
directive,
// The back-pointer, NOT a copy of the commission's provider pin. agentBridge
// resolves that pin live from this id at every dispatch, so an edit to the
diff --git a/server/services/creativeCommissions/scheduler.test.js b/server/services/creativeCommissions/scheduler.test.js
index d6dba75d91..427e53c267 100644
--- a/server/services/creativeCommissions/scheduler.test.js
+++ b/server/services/creativeCommissions/scheduler.test.js
@@ -89,9 +89,10 @@ vi.mock('../domainUsage.js', () => ({
recordDomainUsage: (...a) => recordUsageMock(...a),
}));
const resolveUniverseStyleMock = vi.fn();
+const resolveMoodBoardStyleMock = vi.fn(async () => ({ board: null, images: [] }));
vi.mock('../creativeStyleSources.js', () => ({
resolveUniverseStyleSource: (...a) => resolveUniverseStyleMock(...a),
- resolveMoodBoardStyleSource: async () => ({ board: null, images: [] }),
+ resolveMoodBoardStyleSource: (...a) => resolveMoodBoardStyleMock(...a),
}));
const {
@@ -323,6 +324,34 @@ describe('runScheduledCommission gates', () => {
expect(params.styleSpec.endsWith('flat')).toBe(true);
});
+ it('hands the mood board pinned images to the project as structured style references (#8724)', async () => {
+ resolveMoodBoardStyleMock.mockResolvedValueOnce({
+ board: { name: 'Example Board', items: [] },
+ images: [
+ { kind: 'image', filename: 'pin-a.png', label: 'Dusk street', origin: 'mood-board', path: '/abs/images/pin-a.png', url: '/data/images/pin-a.png' },
+ { kind: 'image-ref', filename: 'pin-b.png', label: 'pin-b.png', origin: 'mood-board', path: '/abs/image-refs/pin-b.png', url: '/data/image-refs/pin-b.png' },
+ ],
+ });
+ getCommissionMock.mockResolvedValue(videoCommission({
+ brief: { intent: 'surreal', styleSpec: 'flat', constraints: { moodBoardId: 'board-1' } },
+ }));
+ await runScheduledCommission('commission-1');
+ const [params] = createProjectMock.mock.calls[0];
+ // Filenames, never the absolute paths the resolver used to find them.
+ expect(params.styleReferenceImages).toEqual([
+ { kind: 'image', filename: 'pin-a.png', label: 'Dusk street', origin: 'mood-board' },
+ { kind: 'image-ref', filename: 'pin-b.png', label: 'pin-b.png', origin: 'mood-board' },
+ ]);
+ // The served-path list stays in the styleSpec for the agent-driven stages.
+ expect(params.styleSpec).toContain('/data/images/pin-a.png');
+ });
+
+ it('passes no style references for a commission without a style source', async () => {
+ getCommissionMock.mockResolvedValue(videoCommission());
+ await runScheduledCommission('commission-1');
+ expect(createProjectMock.mock.calls[0][0].styleReferenceImages).toBeUndefined();
+ });
+
it('does NOT surface when the fire is skipped (nothing was generated)', async () => {
creativeModeMock.mockReturnValue('off');
getCommissionMock.mockResolvedValue(videoCommission());
diff --git a/server/services/creativeCommissions/styleSource.js b/server/services/creativeCommissions/styleSource.js
index b9c2d6d06c..f404aee56e 100644
--- a/server/services/creativeCommissions/styleSource.js
+++ b/server/services/creativeCommissions/styleSource.js
@@ -11,7 +11,10 @@
* planner never sees the project styleSpec) and the project's styleSpec (what
* the treatment and evaluation stages judge against). Reference images are
* listed by their served `/data/...` path — the same convention the treatment
- * prompt uses for a starting image — never by an absolute machine path.
+ * prompt uses for a starting image — never by an absolute machine path. They
+ * are also returned as structured `images` (kind + filename) so the CD project
+ * can hand the pixels to the stages that build their own model calls (scene
+ * evaluation) and to local image renders (#8724).
*
* Board selection on the stored brief (`brief.constraints.moodBoardId`):
* absent / null follows the universe's linked board, '' means no board, any
@@ -71,7 +74,9 @@ function renderCommissionStyleSource({ universe = null, board = null, images = [
/**
* Resolve a commission's configured universe / mood board. Returns null when
* neither is configured, else
- * `{ universeId, universeName, moodBoardId, moodBoardName, universeMissing, text }`.
+ * `{ universeId, universeName, moodBoardId, moodBoardName, universeMissing, text, images }`.
+ * `images` is `[{ kind: 'image' | 'image-ref', filename, label, origin }]` —
+ * filenames only, never absolute paths, since it is persisted on the project.
* `universeMissing` is true when the configured universe no longer exists, so
* the directive drops it from the planner's scope instead of pointing a series
* at a deleted universe.
@@ -97,7 +102,8 @@ export async function resolveCommissionStyleSource(commission) {
: noBoard;
const universeMissing = !!universeId && !universe;
if (!universe && !board && !universeMissing) return null;
- const text = renderCommissionStyleSource({ universe, board, images: [...universeImages, ...boardImages] });
+ const images = [...universeImages, ...boardImages];
+ const text = renderCommissionStyleSource({ universe, board, images });
return {
universeId: universe ? universeId : null,
universeName: universe?.name || null,
@@ -105,6 +111,7 @@ export async function resolveCommissionStyleSource(commission) {
moodBoardName: board?.name || null,
universeMissing,
text,
+ images: images.map(({ kind, filename, label, origin }) => ({ kind, filename, label, origin })),
};
}
diff --git a/server/services/creativeDirector/projectsLogic.js b/server/services/creativeDirector/projectsLogic.js
index b197cd655f..fb2b619640 100644
--- a/server/services/creativeDirector/projectsLogic.js
+++ b/server/services/creativeDirector/projectsLogic.js
@@ -175,6 +175,25 @@ export function mirrorStatus(status) {
return (typeof status === 'string' && status ? status : 'draft').slice(0, STATUS_COLUMN_MAX);
}
+const STYLE_REFERENCE_IMAGE_KINDS = new Set(['image', 'image-ref']);
+const STYLE_REFERENCE_IMAGES_MAX = 4;
+
+// Canonical `styleReferenceImages`: entries with a known kind and a filename,
+// capped. The resolvers that later turn a filename into a path basename it, so
+// a malformed entry can at worst name a missing file, which is skipped.
+function normalizeStyleReferenceImages(images) {
+ if (!Array.isArray(images)) return [];
+ return images
+ .filter((image) => STYLE_REFERENCE_IMAGE_KINDS.has(image?.kind) && typeof image.filename === 'string' && image.filename)
+ .slice(0, STYLE_REFERENCE_IMAGES_MAX)
+ .map(({ kind, filename, label, origin }) => ({
+ kind,
+ filename,
+ label: typeof label === 'string' && label ? label : filename,
+ origin: origin === 'universe' || origin === 'mood-board' ? origin : null,
+ }));
+}
+
/**
* Build a fresh project record. The caller supplies the already-created media
* collection id (collection creation is a side effect both backends perform
@@ -186,8 +205,9 @@ export function buildProjectRecord(input, { id, now, collectionId }) {
styleSpec = '', startingImageFile = null, userStory = null,
disableAudio = true, autoAcceptScenes = false, sourceIssueId = null, commissionId = null,
cast = [], generateFirstPass = false, directive = null,
- modelOverrides = {}, renderBackend = null,
+ modelOverrides = {}, renderBackend = null, styleReferenceImages = null,
} = input;
+ const referenceImages = normalizeStyleReferenceImages(styleReferenceImages);
const videoDraft = input.workspace === 'video'
? creativeDirectorVideoDraftSchema.parse(input.videoDraft || {
durationRange: { min: targetDurationSeconds, max: targetDurationSeconds },
@@ -252,6 +272,15 @@ export function buildProjectRecord(input, { id, now, collectionId }) {
// Additive: the whole record round-trips through the JSONB column verbatim
// (sanitizeProjectForSync / mergeProjectRecord), so no schema-version bump.
commissionId,
+ // The commission style source's reference images (#8724) —
+ // `[{ kind: 'image' | 'image-ref', filename, label, origin }]`, filenames
+ // only. Scene evaluation attaches them next to the rendered frames and a
+ // local image render uses them as `referenceImagePaths` when the planner
+ // set none. SERVER-MANAGED like `commissionId` (not in the public
+ // create/update schema) and OMITTED when empty, so a bare or unpinned
+ // project's record is unchanged. Additive JSONB — no schema-version bump; a
+ // peer without the files just resolves fewer of them.
+ ...(referenceImages.length ? { styleReferenceImages: referenceImages } : {}),
collectionId,
timelineProjectId: null,
finalVideoId: null,
diff --git a/server/services/creativeDirector/projectsLogic.test.js b/server/services/creativeDirector/projectsLogic.test.js
index 79274db28c..3562be7d83 100644
--- a/server/services/creativeDirector/projectsLogic.test.js
+++ b/server/services/creativeDirector/projectsLogic.test.js
@@ -149,6 +149,30 @@ describe('buildProjectRecord', () => {
expect(bad.cast).toEqual([]);
});
+ it('stores commission style references as filenames only, and omits the field when there are none (#8724)', () => {
+ const ctx = { id: 'cd-1', now: '2026-06-07T00:00:00.000Z', collectionId: 'col-1' };
+ const base = { name: 'X', aspectRatio: '1:1', quality: 'draft', modelId: 'm', targetDurationSeconds: 9 };
+ // A bare or unpinned project's record is unchanged — no key at all.
+ expect(buildProjectRecord(base, ctx)).not.toHaveProperty('styleReferenceImages');
+ expect(buildProjectRecord({ ...base, styleReferenceImages: [] }, ctx)).not.toHaveProperty('styleReferenceImages');
+
+ const record = buildProjectRecord({
+ ...base,
+ styleReferenceImages: [
+ { kind: 'image', filename: 'a.png', label: 'A', origin: 'mood-board', path: '/abs/a.png' },
+ { kind: 'video', filename: 'clip.mp4', label: 'not an image kind', origin: 'mood-board' },
+ { kind: 'image-ref', filename: 'b.png', origin: 'universe' },
+ { kind: 'image', filename: 'c.png' }, { kind: 'image', filename: 'd.png' }, { kind: 'image', filename: 'e.png' },
+ ],
+ }, ctx);
+ expect(record.styleReferenceImages).toEqual([
+ { kind: 'image', filename: 'a.png', label: 'A', origin: 'mood-board' },
+ { kind: 'image-ref', filename: 'b.png', label: 'b.png', origin: 'universe' },
+ { kind: 'image', filename: 'c.png', label: 'c.png', origin: null },
+ { kind: 'image', filename: 'd.png', label: 'd.png', origin: null },
+ ]);
+ });
+
it('defaults renderBackend to null and persists a supplied pin (#3135)', () => {
const ctx = { id: 'cd-1', now: '2026-06-07T00:00:00.000Z', collectionId: 'col-1' };
const base = { name: 'X', aspectRatio: '1:1', quality: 'draft', modelId: 'm', targetDurationSeconds: 9 };
diff --git a/server/services/creativeDirector/sceneEvaluator.js b/server/services/creativeDirector/sceneEvaluator.js
index 017285f0d5..ba6308d8b8 100644
--- a/server/services/creativeDirector/sceneEvaluator.js
+++ b/server/services/creativeDirector/sceneEvaluator.js
@@ -210,13 +210,19 @@ export async function evaluateSceneWithVision(project, scene) {
}).catch((err) => console.log(`⚠️ CD vision recordRun(running) failed: ${err.message}`));
try {
- const prompt = buildEvaluateVisionPrompt(project, scene, frames.length);
+ // The commission style source's reference images (#8724) ride AFTER the
+ // frames so the prompt can name each group by position. A project without
+ // them sends exactly the frames, as before.
+ const references = project.styleReferenceImages?.length
+ ? (await import('../creativeStyleSources.js')).styleReferenceImagePaths(project.styleReferenceImages)
+ : [];
+ const prompt = buildEvaluateVisionPrompt(project, scene, frames.length, { referenceCount: references.length });
const result = await runPromptThroughProvider({
provider: target.provider,
model: target.model,
prompt,
source: 'cd-scene-evaluate',
- screenshots: frames,
+ screenshots: [...frames, ...references],
timeout: target.provider.timeout ?? DEFAULT_VISION_EVAL_TIMEOUT_MS,
...(project.workspace === 'video' ? { allowFallback: false } : {}),
});
diff --git a/server/services/creativeDirector/sceneEvaluator.test.js b/server/services/creativeDirector/sceneEvaluator.test.js
index 8dba4eb88f..48b4f06817 100644
--- a/server/services/creativeDirector/sceneEvaluator.test.js
+++ b/server/services/creativeDirector/sceneEvaluator.test.js
@@ -23,6 +23,7 @@ const mocks = vi.hoisted(() => ({
enqueueEvaluateTask: vi.fn(),
advanceAfterSceneSettled: vi.fn(),
existsSync: vi.fn(() => true),
+ styleReferenceImagePaths: vi.fn(),
}));
vi.mock('fs', () => ({ existsSync: mocks.existsSync }));
@@ -50,6 +51,9 @@ vi.mock('./local.js', () => ({
}));
vi.mock('./agentBridge.js', () => ({ enqueueEvaluateTask: mocks.enqueueEvaluateTask }));
vi.mock('./completionHook.js', () => ({ advanceAfterSceneSettled: mocks.advanceAfterSceneSettled }));
+// Filename → path resolution is covered against real files at the
+// media_enqueueImageJob boundary; here it only has to hand back paths.
+vi.mock('../creativeStyleSources.js', () => ({ styleReferenceImagePaths: mocks.styleReferenceImagePaths }));
const {
parseVisionVerdict,
@@ -244,6 +248,31 @@ describe('evaluateSceneWithVision', () => {
expect(mocks.runPromptThroughProvider).not.toHaveBeenCalled();
});
+ it('attaches the project style reference images after the frames and tells the model which is which (#8724)', async () => {
+ const styleReferenceImages = [{ kind: 'image', filename: 'board-pin.png', label: 'Pinned', origin: 'mood-board' }];
+ mocks.styleReferenceImagePaths.mockReturnValue(['/data/images/board-pin.png']);
+ mocks.runPromptThroughProvider.mockResolvedValue({ text: '{"accepted": true}', model: 'qwen2.5-vl', provider: OLLAMA });
+ await evaluateSceneWithVision({ ...project, styleReferenceImages }, scene);
+ expect(mocks.styleReferenceImagePaths).toHaveBeenCalledWith(styleReferenceImages);
+ const call = mocks.runPromptThroughProvider.mock.calls[0][0];
+ expect(call.screenshots).toEqual([
+ resolvePath('/data/video-thumbnails/job-1-f1.jpg'),
+ resolvePath('/data/video-thumbnails/job-1-f2.jpg'),
+ '/data/images/board-pin.png',
+ ]);
+ expect(call.prompt).toContain('After the scene frames come 1 style reference image(s)');
+ });
+
+ it('sends only the frames and the unchanged prompt for a project without style references', async () => {
+ mocks.runPromptThroughProvider.mockResolvedValue({ text: '{"accepted": true}', model: 'qwen2.5-vl', provider: OLLAMA });
+ await evaluateSceneWithVision(project, scene);
+ const call = mocks.runPromptThroughProvider.mock.calls[0][0];
+ expect(call.screenshots).toHaveLength(2);
+ expect(call.prompt).toContain("in order (first = start, last = end).\n\n## Scene\n");
+ expect(call.prompt).not.toContain('style reference');
+ expect(mocks.styleReferenceImagePaths).not.toHaveBeenCalled();
+ });
+
it('uses the single-thumbnail fallback when no sampled frames are present', async () => {
mocks.runPromptThroughProvider.mockResolvedValue({ text: '{"accepted": true}', model: 'qwen2.5-vl', provider: OLLAMA });
await evaluateSceneWithVision(project, { ...scene, evaluationFrames: [] });
diff --git a/server/services/creativeDirectorPrompts.js b/server/services/creativeDirectorPrompts.js
index 281e6b58c8..f96b45b961 100644
--- a/server/services/creativeDirectorPrompts.js
+++ b/server/services/creativeDirectorPrompts.js
@@ -272,9 +272,11 @@ export const CD_MAX_SCENE_RETRIES = 3;
* @param {object} project
* @param {object} scene
* @param {number} frameCount — how many frames are attached to the call
+ * @param {{ referenceCount?: number }} [options] — style reference images
+ * attached AFTER the frames (#8724); 0 leaves the prompt unchanged
* @returns {string}
*/
-export function buildEvaluateVisionPrompt(project, scene, frameCount) {
+export function buildEvaluateVisionPrompt(project, scene, frameCount, { referenceCount = 0 } = {}) {
const total = project.treatment?.scenes?.length;
const positionLabel = total ? `${(scene.order ?? 0) + 1}/${total}` : `${(scene.order ?? 0) + 1}/?`;
const styleSpec = (project.styleSpec || '').trim()
@@ -287,11 +289,16 @@ export function buildEvaluateVisionPrompt(project, scene, frameCount) {
const frameLine = frameCount > 1
? `You are shown ${frameCount} frames sampled across the scene's timeline, in order (first = start, last = end).`
: 'You are shown a single representative frame from the scene.';
+ // Style reference images follow the frames in the same request (#8724).
+ // They are the art-direction target, not part of the render.
+ const referenceLine = referenceCount > 0
+ ? `\nAfter the scene frames come ${referenceCount} style reference image(s) from the project's universe / mood board. They are NOT part of the render — judge style adherence against them (palette, texture, lighting, composition) alongside the style spec.\n`
+ : '';
return `You are the creative director for the video project "${project.name}". Evaluate a freshly-rendered scene and decide whether it works.
${frameLine}
-
+${referenceLine}
## Scene
- Position: ${positionLabel}
- Intent: ${scene.intent || '(unspecified)'}
diff --git a/server/services/creativeStyleSources.js b/server/services/creativeStyleSources.js
index 85b692d3eb..dd740d5ba8 100644
--- a/server/services/creativeStyleSources.js
+++ b/server/services/creativeStyleSources.js
@@ -24,10 +24,27 @@ const IMAGE_DIRS = {
};
// A local image as a prompt reference, or null when the file is missing.
+// `kind` + `filename` are the machine-independent identity a caller persists
+// (never `path`, which embeds this install's data dir); `url` is the served
+// path a prompt can cite.
function localReference(kind, filename, label, origin) {
const dir = IMAGE_DIRS[kind];
const path = dir?.resolve(filename);
- return path ? { label, origin, path, url: `${dir.urlPrefix}${encodeURIComponent(filename)}` } : null;
+ return path ? { kind, filename, label, origin, path, url: `${dir.urlPrefix}${encodeURIComponent(filename)}` } : null;
+}
+
+/**
+ * Resolve persisted style reference images (`{ kind, filename }`, as a style
+ * source returns them) back to absolute local paths for a model call or a
+ * render. Files that are gone — deleted since, or never synced to this peer —
+ * and unknown kinds are skipped, so the result may be shorter than the input.
+ */
+export function styleReferenceImagePaths(images) {
+ if (!Array.isArray(images)) return [];
+ const paths = images
+ .map((image) => IMAGE_DIRS[image?.kind]?.resolve(image?.filename) || null)
+ .filter(Boolean);
+ return [...new Set(paths)];
}
// Resolve reference candidates in order until `slots` are filled, so a