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([issue-9546]): show live cast references and submitted prompts (#9568)

[._.]/8bb3c2936d1c
diff --git a/client/src/components/musicVideo/CastAndSetsCheckin.jsx b/client/src/components/musicVideo/CastAndSetsCheckin.jsx
index d43b44c8fd..03cc34776c 100644
--- a/client/src/components/musicVideo/CastAndSetsCheckin.jsx
+++ b/client/src/components/musicVideo/CastAndSetsCheckin.jsx
@@ -1,5 +1,6 @@
import { CheckCircle2, Eye, Play, RotateCcw, SkipForward, Users } from 'lucide-react';
import Pill from '../ui/Pill.jsx';
+import CastAndSetsReferenceProgress from './CastAndSetsReferenceProgress.jsx';
const WORKING = new Set(['directing', 'imaging', 'assembling']);
const buttonClass = 'flex items-center gap-1 rounded px-3 py-1.5 text-sm min-h-[44px] sm:min-h-0 disabled:opacity-50';
@@ -47,6 +48,7 @@ export default function CastAndSetsCheckin({ project, busy, onOpenSheet, onAppro
{stage.revision > 1 && <span className="text-[11px] text-port-text-muted">revision {stage.revision}</span>}
</div>
<p className={`text-xs ${stage.status === 'review' ? 'text-port-warning' : 'text-port-text-muted'}`} role="status">{statusLine(stage)}</p>
+ <CastAndSetsReferenceProgress stage={stage} />
<div className="flex flex-wrap gap-2">
{sheet && (
<button type="button" onClick={() => onOpenSheet(sheet.id)} className={`${buttonClass} border border-port-border`}>
diff --git a/client/src/components/musicVideo/CastAndSetsCheckin.test.jsx b/client/src/components/musicVideo/CastAndSetsCheckin.test.jsx
new file mode 100644
index 0000000000..2b4e5ebf14
--- /dev/null
+++ b/client/src/components/musicVideo/CastAndSetsCheckin.test.jsx
@@ -0,0 +1,133 @@
+import { useState } from 'react';
+import { act, fireEvent, render, screen, within } from '@testing-library/react';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import CastSetsStage from './stages/CastSetsStage.jsx';
+import useMusicVideoCastAndSets from '../../hooks/useMusicVideoCastAndSets';
+
+const { listeners, api, getMediaJob } = vi.hoisted(() => ({
+ listeners: new Map(),
+ api: { getMusicVideoProject: vi.fn(), startMusicVideoCastAndSets: vi.fn(), regenerateMusicVideoCastAndSets: vi.fn(), resumeMusicVideoCastAndSets: vi.fn(), approveMusicVideoCastAndSets: vi.fn(), skipMusicVideoCastAndSets: vi.fn() },
+ getMediaJob: vi.fn(),
+}));
+vi.mock('../../services/socket', () => ({ default: {
+ on: (event, fn) => { if (!listeners.has(event)) listeners.set(event, new Set()); listeners.get(event).add(fn); },
+ off: (event, fn) => listeners.get(event)?.delete(fn),
+} }));
+vi.mock('../../services/apiMusicVideo.js', () => api);
+vi.mock('../../services/apiMediaJobs', () => ({ getMediaJob }));
+vi.mock('../ui/Toast', () => ({ default: { success: vi.fn(), error: vi.fn() } }));
+
+const emit = async (event, data) => act(async () => { for (const fn of listeners.get(event) || []) fn(data); });
+const plan = {
+ character: { key: 'character', label: 'Keeper', prompt: 'Planned keeper portrait', deps: [], refKeys: [], moodRefs: true },
+ set: { key: 'set', label: 'Lamp room', prompt: 'Planned lamp room', deps: ['character'], refKeys: ['character'] },
+ looks: { key: 'looks', label: 'Wardrobe', prompt: 'Planned wardrobe', deps: ['character'], refKeys: ['character'] },
+};
+const project = (images = {}, extra = {}) => ({ id: 'example-project', castAndSets: { revision: 1, status: 'imaging', plan, images, moodImages: [{ kind: 'image-ref', filename: 'mood.png' }], ...extra } });
+const done = (filename, prompt) => ({ status: 'done', jobId: `job-${filename}`, imageId: filename, submittedPrompt: prompt, submittedRevision: 1, submittedReferences: [{ kind: 'image-ref', filename: 'mood.png' }] });
+let selectProject;
+function Harness({ initial }) {
+ const [value, setValue] = useState(initial);
+ selectProject = setValue;
+ const actions = useMusicVideoCastAndSets({ project: value, replaceProject: setValue });
+ return <CastSetsStage board={{ project: value, locked: true, castSets: actions, kickoff: { running: true }, devArtifacts: { busy: false }, openArtifact: vi.fn(), approveCastAndSets: actions.approve, skipCastAndSets: actions.skip }} />;
+}
+const stage = (next) => emit('music-video:cast-and-sets', { projectId: next.id, project: next });
+const card = (name) => within(screen.getByRole('article', { name }));
+const deferred = () => {
+ let resolve;
+ const promise = new Promise((r) => { resolve = r; });
+ return { promise, resolve };
+};
+
+beforeEach(() => {
+ listeners.clear();
+ vi.clearAllMocks();
+ getMediaJob.mockResolvedValue({ status: 'queued' });
+ api.getMusicVideoProject.mockReset();
+});
+afterEach(() => vi.restoreAllMocks());
+
+describe('Cast & Sets incremental references', () => {
+ it('shows plan, completion, failure and regeneration from sockets while prompts and images remain inspectable', async () => {
+ const view = render(<Harness initial={project()} />);
+ expect(card('Keeper').getByText('Planned prompt')).not.toBeDisabled();
+ expect(screen.getByRole('article', { name: 'Keeper' }).closest('fieldset[disabled]')).toBeNull();
+ expect(card('Keeper').getByText('Planned keeper portrait')).toBeInTheDocument();
+ expect(card('Lamp room').getByText('Waiting for Keeper')).toBeInTheDocument();
+
+ const character = done('keeper.png', 'Submitted keeper portrait with silver grain');
+ const partial = project({ character, set: { status: 'queued', jobId: 'set-job' }, looks: { status: 'pending' } });
+ await stage(partial);
+ expect(card('Keeper').getByRole('img', { name: 'Keeper — generated reference' })).toHaveAttribute('src', '/data/images/keeper.png');
+ expect(card('Keeper').getByText(character.submittedPrompt)).toBeInTheDocument();
+ expect(card('Keeper').getByRole('img', { name: 'Keeper input: mood.png' })).toHaveAttribute('src', '/data/image-refs/mood.png');
+ expect(getMediaJob).toHaveBeenCalledWith('set-job');
+ expect(getMediaJob).not.toHaveBeenCalledWith(character.jobId);
+ const progressImage = 'data:image/png;base64,ZXhhbXBsZQ==';
+ await emit('image-gen:progress', { generationId: 'set-job', progress: 0.5, message: 'Drawing room', currentImage: progressImage });
+ expect(card('Lamp room').getByText('Rendering')).toBeInTheDocument();
+ expect(card('Lamp room').getByRole('progressbar')).toHaveAttribute('value', '0.5');
+ expect(card('Lamp room').getByRole('img', { name: 'Lamp room — in-progress render' })).toHaveAttribute('src', progressImage);
+
+ const room = done('room.png', 'Submitted room prompt');
+ await stage(project({ character, set: room, looks: { status: 'queued', jobId: 'looks-job' } }));
+ expect(card('Lamp room').getByRole('img', { name: 'Lamp room — generated reference' })).toHaveAttribute('src', '/data/images/room.png');
+ await emit('image-gen:failed', { generationId: 'looks-job', error: 'Example render failure' });
+ expect(card('Wardrobe').getByText('Failed')).toBeInTheDocument();
+ expect(card('Wardrobe').getByText('Example render failure')).toBeInTheDocument();
+
+ await stage(project({ character: { status: 'queued', jobId: 'new-character', imageId: 'keeper.png' }, set: room, looks: { status: 'pending' } }, { revision: 2 }));
+ expect(card('Keeper').getByRole('img', { name: 'Keeper — previous revision' })).toHaveAttribute('src', '/data/images/keeper.png');
+ expect(card('Keeper').getByText('Previous revision — replacement pending')).toBeInTheDocument();
+ expect(card('Lamp room').getByText('Retained from revision 1')).toBeInTheDocument();
+ await emit('image-gen:completed', { generationId: 'set-job', filename: 'obsolete.png' });
+ expect(card('Keeper').queryByRole('img', { name: 'Keeper — generated reference' })).not.toBeInTheDocument();
+ await emit('image-gen:completed', { generationId: 'new-character' });
+ expect(card('Keeper').getByRole('img', { name: 'Keeper — previous revision' })).toHaveAttribute('src', '/data/images/keeper.png');
+ const reloaded = project({ character: { ...done('keeper-new.png', 'New submitted prompt'), submittedRevision: 2 }, set: room }, { revision: 2, interrupted: true });
+ await stage(reloaded);
+ view.unmount();
+ getMediaJob.mockClear();
+ render(<Harness initial={reloaded} />);
+ expect(card('Keeper').getByText('New submitted prompt')).toBeInTheDocument();
+ expect(card('Keeper').getByRole('link', { name: 'Keeper — generated reference' })).toHaveAttribute('href', '/data/images/keeper-new.png');
+ expect(card('Wardrobe').getByText('Interrupted')).toBeInTheDocument();
+ expect(screen.getByRole('button', { name: 'Resume' })).toBeDisabled();
+ expect(getMediaJob).not.toHaveBeenCalled();
+ });
+
+ it('refreshes once on reconnect or tab return and ignores reads superseded by sockets or a project switch', async () => {
+ const first = deferred();
+ api.getMusicVideoProject.mockReturnValueOnce(first.promise);
+ const view = render(<Harness initial={project()} />);
+ await emit('connect');
+ await emit('connect');
+ expect(api.getMusicVideoProject).toHaveBeenCalledTimes(1);
+ await stage(project({ character: done('latest.png', 'Newest prompt') }));
+ await act(async () => first.resolve(project()));
+ expect(card('Keeper').getByText('Newest prompt')).toBeInTheDocument();
+
+ const second = deferred();
+ api.getMusicVideoProject.mockReturnValueOnce(second.promise);
+ let visibility = 'hidden';
+ vi.spyOn(document, 'visibilityState', 'get').mockImplementation(() => visibility);
+ fireEvent(document, new Event('visibilitychange'));
+ visibility = 'visible';
+ fireEvent(document, new Event('visibilitychange'));
+ fireEvent(document, new Event('visibilitychange'));
+ expect(api.getMusicVideoProject).toHaveBeenCalledTimes(2);
+ await act(async () => second.resolve(project({ looks: { status: 'failed', error: 'Missed failure' } }, { status: 'failed' })));
+ expect(card('Wardrobe').getByText('Missed failure')).toBeInTheDocument();
+
+ const stale = deferred();
+ api.getMusicVideoProject.mockReturnValueOnce(stale.promise);
+ await emit('connect');
+ await act(async () => selectProject({ id: 'another-project', castAndSets: { revision: 1, status: 'imaging', plan: { other: { key: 'other', label: 'Other cast', prompt: 'Other plan' } }, images: {} } }));
+ await act(async () => stale.resolve(project({ character: done('stale.png', 'Stale prompt') })));
+ expect(screen.queryByText('Stale prompt')).not.toBeInTheDocument();
+ expect(card('Other cast').getByText('Other plan')).toBeInTheDocument();
+ view.unmount();
+ expect([...listeners.values()].every((set) => set.size === 0)).toBe(true);
+ });
+});
diff --git a/client/src/components/musicVideo/CastAndSetsReferenceProgress.jsx b/client/src/components/musicVideo/CastAndSetsReferenceProgress.jsx
new file mode 100644
index 0000000000..0f911ffc1b
--- /dev/null
+++ b/client/src/components/musicVideo/CastAndSetsReferenceProgress.jsx
@@ -0,0 +1,94 @@
+import useMediaJobProgress from '../../hooks/useMediaJobProgress';
+import { formatCount } from '../../utils/formatters';
+
+const imageSource = ({ kind, filename }) => `/data/${kind === 'image-ref' ? 'image-refs' : 'images'}/${encodeURIComponent(filename)}`;
+
+function ReferenceCard({ item, stage }) {
+ const image = stage.images?.[item.key] || {};
+ // Old images remain visible during regeneration, but only a persisted done
+ // record can bypass the new job's subscription.
+ const live = useMediaJobProgress(image.status === 'queued' ? image.jobId : null);
+ const finishing = image.status === 'queued' && live.status === 'completed';
+ const completedFilename = finishing ? live.filename : null;
+ const filename = completedFilename || image.imageId;
+ const previous = !!filename && image.status !== 'done' && !completedFilename;
+ const currentImage = live.status === 'running' && typeof live.currentImage === 'string' && live.currentImage.startsWith('data:image/') ? live.currentImage : null;
+ const retained = image.status === 'done' && image.submittedRevision < stage.revision;
+ const waiting = (item.deps || []).filter((key) => stage.images?.[key]?.status !== 'done')
+ .map((key) => stage.plan?.[key]?.label || key);
+ const error = image.error || (image.status === 'queued' ? live.error : null);
+ let status = 'Waiting';
+ if (image.status === 'done') status = 'Complete';
+ else if (image.status === 'failed' || live.status === 'failed') status = 'Failed';
+ else if (live.status === 'canceled') status = 'Canceled';
+ else if (finishing) status = 'Saving result';
+ else if (live.status === 'running') status = 'Rendering';
+ else if (stage.interrupted) status = 'Interrupted';
+ else if (image.status === 'queued') status = image.jobId ? 'Queued' : 'Preparing';
+ else if (stage.status === 'failed') status = 'Waiting for resume';
+ else if (error) status = 'Waiting to retry';
+ else if (waiting.length) status = `Waiting for ${waiting.join(', ')}`;
+
+ const submitted = typeof image.submittedPrompt === 'string';
+ const plannedReferences = [
+ ...(item.refKeys || []).flatMap((key) => stage.images?.[key]?.imageId
+ ? [{ kind: 'image', filename: stage.images[key].imageId }] : []),
+ ...(item.moodRefs ? stage.moodImages || [] : []),
+ ];
+ const references = submitted ? image.submittedReferences || [] : plannedReferences;
+ const src = filename ? imageSource({ kind: 'image', filename }) : null;
+ return (
+ <article className="min-w-0 rounded border border-port-border bg-port-bg p-2 space-y-2" aria-label={item.label || item.key}>
+ <div className="flex min-w-0 flex-wrap items-baseline justify-between gap-1">
+ <h4 className="text-xs font-medium break-words [overflow-wrap:anywhere]">{item.label || item.key}</h4>
+ <span className="text-[11px] text-port-text-muted break-words" role="status">{status}</span>
+ </div>
+ {currentImage && <figure className="space-y-1">
+ <img src={currentImage} alt={`${item.label || item.key} — in-progress render`} className="w-full max-h-64 rounded object-contain" />
+ <figcaption className="text-[11px] text-port-text-muted">In-progress preview</figcaption>
+ </figure>}
+ {src && (
+ <figure className="space-y-1">
+ <a href={src} target="_blank" rel="noreferrer" className="block rounded focus-visible:outline focus-visible:outline-port-accent">
+ <img src={src} alt={`${item.label || item.key} — ${previous ? 'previous revision' : 'generated reference'}`}
+ className={`w-full ${currentImage ? 'max-h-24' : 'max-h-64'} rounded object-contain`} loading="lazy" />
+ </a>
+ {(previous || retained) && <figcaption className="text-[11px] text-port-text-muted">{previous ? 'Previous revision — replacement pending' : `Retained from revision ${formatCount(image.submittedRevision)}`}</figcaption>}
+ </figure>
+ )}
+ {error && <p role="alert" className="text-xs text-port-error break-words [overflow-wrap:anywhere]">{error}</p>}
+ {live.status === 'running' && <progress aria-label={`${item.label || item.key} rendering progress`} className="w-full" max={1} value={Math.max(0, Math.min(1, live.progress || 0))} />}
+ {live.status === 'running' && live.statusMsg && <p className="text-[11px] text-port-text-muted break-words">{live.statusMsg}</p>}
+ <details className="min-w-0 text-xs">
+ <summary className="cursor-pointer min-h-[44px] sm:min-h-0 py-1 text-port-accent">{submitted ? 'Submitted prompt' : 'Planned prompt'}</summary>
+ {!submitted && <p className="text-[11px] text-port-text-muted">The submitted prompt has not been recorded. Style instructions may be added when queued.</p>}
+ <p className="mt-1 whitespace-pre-wrap break-words [overflow-wrap:anywhere]">{submitted ? image.submittedPrompt : item.prompt || 'No planned prompt recorded.'}</p>
+ {image.submittedPromptTruncated && <p className="mt-1 text-port-warning">The recorded prompt is truncated.</p>}
+ {image.submittedReferencesTruncated && <p className="mt-1 text-port-warning">Only the first {formatCount(16)} image inputs are recorded.</p>}
+ {references.length > 0 && (
+ <div className="mt-2 space-y-1">
+ <p className="text-port-text-muted">{submitted ? 'Submitted image inputs' : 'Planned image inputs'}</p>
+ <div className="flex flex-wrap gap-2">
+ {references.map((ref, index) => (
+ <a key={`${ref.kind}:${ref.filename}:${index}`} href={imageSource(ref)} target="_blank" rel="noreferrer"
+ className="min-w-0 w-16 rounded focus-visible:outline focus-visible:outline-port-accent" title={ref.filename}>
+ <img src={imageSource(ref)} alt={`${item.label || item.key} input: ${ref.filename}`} className="h-16 w-16 rounded object-contain" loading="lazy" />
+ </a>
+ ))}
+ </div>
+ </div>
+ )}
+ </details>
+ </article>
+ );
+}
+
+export default function CastAndSetsReferenceProgress({ stage }) {
+ const items = Object.values(stage.plan || {});
+ if (!items.length) return null;
+ return (
+ <div className="grid min-w-0 grid-cols-[repeat(auto-fit,minmax(min(100%,15rem),1fr))] gap-2" aria-label="Cast and set references">
+ {items.map((item) => <ReferenceCard key={item.key} item={item} stage={stage} />)}
+ </div>
+ );
+}
diff --git a/client/src/components/musicVideo/stages/CastSetsStage.jsx b/client/src/components/musicVideo/stages/CastSetsStage.jsx
index 656957a30b..bae1012b45 100644
--- a/client/src/components/musicVideo/stages/CastSetsStage.jsx
+++ b/client/src/components/musicVideo/stages/CastSetsStage.jsx
@@ -8,12 +8,12 @@ import DevArtifactsPanel from '../DevArtifactsPanel.jsx';
export default function CastSetsStage({ board }) {
const { project, locked, castSets, kickoff } = board;
return (
- <fieldset disabled={locked} className="min-w-0 space-y-3">
+ <div className="min-w-0 space-y-3">
{project.castAndSets ? (
<div className="rounded-lg border border-port-border bg-port-card p-3">
<CastAndSetsCheckin
project={project}
- busy={castSets.busy || kickoff.running}
+ busy={locked || castSets.busy || kickoff.running}
onOpenSheet={board.openArtifact}
onApprove={board.approveCastAndSets}
onRegenerate={() => castSets.regenerate()}
@@ -35,6 +35,6 @@ export default function CastSetsStage({ board }) {
title="Cast & Sets sheets"
emptyText="The check-in sheet appears here once the cast and sets are built"
/>
- </fieldset>
+ </div>
);
}
diff --git a/client/src/hooks/useMusicVideoCastAndSets.js b/client/src/hooks/useMusicVideoCastAndSets.js
index fd5ef60be7..d0ec8c6c2c 100644
--- a/client/src/hooks/useMusicVideoCastAndSets.js
+++ b/client/src/hooks/useMusicVideoCastAndSets.js
@@ -1,7 +1,9 @@
import { useEffect, useRef, useState } from 'react';
import toast from '../components/ui/Toast';
import socket from '../services/socket';
+import { subscribeVisibility } from './useVisibilityEvent';
import {
+ getMusicVideoProject,
startMusicVideoCastAndSets,
regenerateMusicVideoCastAndSets,
resumeMusicVideoCastAndSets,
@@ -31,30 +33,60 @@ export default function useMusicVideoCastAndSets({ project, replaceProject } = {
const projectId = project?.id || null;
const [busy, setBusy] = useState(false);
const replaceRef = useRef(replaceProject);
+ const snapshotRevision = useRef(0);
const waiter = useRef(null);
useEffect(() => {
replaceRef.current = replaceProject;
- });
+ }, [replaceProject]);
+ useEffect(() => {
+ snapshotRevision.current += 1;
+ }, [project]);
useEffect(() => {
if (!projectId) return undefined;
- const onStage = (data) => {
- if (data?.projectId !== projectId || !data.project) return;
- replaceRef.current?.(data.project);
+ let active = true;
+ let pending = null;
+ const applyProject = (next) => {
+ snapshotRevision.current += 1;
+ replaceRef.current?.(next);
const w = waiter.current;
- if (w && w.projectId === projectId && CHECKPOINTS.has(data.project.castAndSets?.status)) {
+ if (w && w.projectId === projectId && CHECKPOINTS.has(next.castAndSets?.status)) {
waiter.current = null;
- w.resolve(data.project);
+ w.resolve(next);
}
};
+ const onStage = (data) => {
+ if (data?.projectId !== projectId || !data.project) return;
+ applyProject(data.project);
+ };
const onArtifact = (data) => {
- if (data?.projectId === projectId && data.project) replaceRef.current?.(data.project);
+ if (data?.projectId === projectId && data.project) applyProject(data.project);
+ };
+ // Recover events missed while disconnected or hidden, once per transition.
+ // A newer socket snapshot or a project switch wins over an in-flight read.
+ const refresh = () => {
+ if (pending) return pending;
+ const revision = snapshotRevision.current;
+ pending = getMusicVideoProject(projectId, { silent: true }).then((next) => {
+ if (active && next?.id === projectId && revision === snapshotRevision.current) applyProject(next);
+ }).catch(() => {}).finally(() => { pending = null; });
+ return pending;
};
socket.on('music-video:cast-and-sets', onStage);
socket.on('music-video:dev-artifact', onArtifact);
+ socket.on('connect', refresh);
+ let visibility = document.visibilityState;
+ const unsubscribeVisibility = subscribeVisibility((next) => {
+ const changed = visibility !== next;
+ visibility = next;
+ if (changed && next === 'visible') refresh();
+ });
return () => {
+ active = false;
+ unsubscribeVisibility();
socket.off('music-video:cast-and-sets', onStage);
socket.off('music-video:dev-artifact', onArtifact);
+ socket.off('connect', refresh);
// A kickoff waiting on this project ends rather than hanging.
if (waiter.current?.projectId === projectId) {
waiter.current.resolve(null);
diff --git a/server/services/musicVideo/castAndSets.js b/server/services/musicVideo/castAndSets.js
index 83bbe7ef74..3c8324bd33 100644
--- a/server/services/musicVideo/castAndSets.js
+++ b/server/services/musicVideo/castAndSets.js
@@ -16,7 +16,8 @@
* direction, // castAndSetsDirection.js shape
* moodImages: [{ kind, filename }],
* plan: { [key]: { key, kind, label, prompt, deps, refKeys, moodRefs?, setId?, testIndex? } },
- * images: { [key]: { status, jobId, imageId, history, failures, error, updatedAt } },
+ * images: { [key]: { status, jobId, imageId, history, failures, error, updatedAt,
+ * submittedPrompt?, submittedPromptTruncated?, submittedReferences?, submittedRevision? } },
* artifactId, artifactVersion, notesApplied,
* createdAt, updatedAt, approvedAt,
* }
@@ -187,11 +188,11 @@ export function reserveCastAndSetsImage(project, key, { processId }, now = new D
}
/** Link the queued job to its key. */
-export function linkCastAndSetsJob(project, key, jobId, now = new Date().toISOString()) {
+export function linkCastAndSetsJob(project, key, jobId, submission = {}, now = new Date().toISOString()) {
const stage = requireStage(project);
const img = stage.images?.[key];
- if (!img) return { project, stage };
- return write(project, { ...stage, images: { ...stage.images, [key]: { ...img, jobId, updatedAt: now } } }, now);
+ if (!img || (submission.submittedRevision != null && submission.submittedRevision !== stage.revision)) return { project, stage };
+ return write(project, { ...stage, images: { ...stage.images, [key]: { ...img, ...submission, jobId, updatedAt: now } } }, now);
}
/**
@@ -200,10 +201,11 @@ export function linkCastAndSetsJob(project, key, jobId, now = new Date().toISOSt
* retried once (back to pending); the second consecutive failure stops the
* stage `failed`. Returns `{ project, stage, changed }`.
*/
-export function settleCastAndSetsImage(project, key, { jobId = null, filename = null, error = null }, now = new Date().toISOString()) {
+export function settleCastAndSetsImage(project, key, { jobId = null, filename = null, error = null, revision = null }, now = new Date().toISOString()) {
const stage = project?.castAndSets;
const img = stage?.images?.[key];
- if (!img || img.status !== 'queued' || (jobId && img.jobId && img.jobId !== jobId)) return { project, stage, changed: false };
+ if (!img || img.status !== 'queued' || (revision != null && revision !== stage.revision)
+ || (jobId && img.jobId && img.jobId !== jobId)) return { project, stage, changed: false };
if (filename) {
const history = img.imageId && img.imageId !== filename ? [...(img.history || []), img.imageId].slice(-MAX_HISTORY) : (img.history || []);
const next = { ...img, status: 'done', jobId: jobId || img.jobId, imageId: filename, history, failures: 0, error: null, updatedAt: now };
diff --git a/server/services/musicVideo/castAndSetsService.js b/server/services/musicVideo/castAndSetsService.js
index 1d912a2e4a..6787cecd95 100644
--- a/server/services/musicVideo/castAndSetsService.js
+++ b/server/services/musicVideo/castAndSetsService.js
@@ -28,7 +28,7 @@ import { withMusicVideoStyle } from './styleReferences.js';
import { randomUUID } from 'crypto';
import { readFile } from 'fs/promises';
-import { extname } from 'path';
+import { basename, extname } from 'path';
import { ServerError } from '../../lib/errorHandler.js';
import { QUEUEABLE_IMAGE_MODES } from '../../lib/generationModes.js';
import { resolveGalleryImage, resolveImageRef } from '../../lib/pathSafety.js';
@@ -73,6 +73,8 @@ import { findProductionRun, haltProduction, rebaseProductionAfterCheckin, reserv
const PROCESS_ID = `proc-${randomUUID()}`;
const short = (id) => String(id || '').slice(3, 11);
const MAX_KEY_NOTES = 8;
+const MAX_SUBMITTED_PROMPT = 20_000;
+const MAX_SUBMITTED_REFERENCES = 16;
// Test seam: provider, queue, settings and mood-board access are swappable.
const defaults = {
@@ -266,7 +268,25 @@ async function enqueueImage(project, stage, key) {
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}` });
+ // Persist the actual styled queue input, with only served local references.
+ // Never expose the absolute host paths used by the provider transport.
+ const submittedReferences = (params.referenceImagePaths || []).flatMap((path) => {
+ if (typeof path !== 'string') return [];
+ const filename = basename(path);
+ if (resolveGalleryImage(filename, { mustExist: false }) === path) return [{ kind: 'image', filename }];
+ if (resolveImageRef(filename, { mustExist: false }) === path) return [{ kind: 'image-ref', filename }];
+ return [];
+ });
+ const prompt = String(params.prompt || '');
+ const submission = {
+ submittedPrompt: prompt.slice(0, MAX_SUBMITTED_PROMPT),
+ submittedPromptTruncated: prompt.length > MAX_SUBMITTED_PROMPT,
+ submittedReferences: submittedReferences.slice(0, MAX_SUBMITTED_REFERENCES),
+ submittedReferencesTruncated: submittedReferences.length > MAX_SUBMITTED_REFERENCES,
+ submittedRevision: stage.revision,
+ };
+ const sent = await deps.enqueue({ kind: 'image', params, owner: `music-video-cast-sets:${project.id}` });
+ return { ...sent, submission };
}
// Check-in slots use the existing production ledger; the revision separates
@@ -335,7 +355,7 @@ async function dispatchKey(projectId, key) {
const reason = sent?.error?.message || 'The image job was not queued';
const out = await mutateProjectRecord(projectId, (current) => {
const next = productionStep ? settleProductionStep(current, runId, productionStep.key, { status: 'refused', error: reason }).project : current;
- const settled = settleCastAndSetsImage(next, key, { error: reason });
+ const settled = settleCastAndSetsImage(next, key, { error: reason, revision: reserved.stage.revision });
if (settled.stage?.status === 'failed') settled.project = refundUnusedCheckinSteps(settled.project);
return settled;
});
@@ -343,10 +363,11 @@ async function dispatchKey(projectId, key) {
publish(projectId, out.project);
return;
}
- await mutateProjectRecord(projectId, (current) => {
+ const linked = await mutateProjectRecord(projectId, (current) => {
const next = productionStep ? settleProductionStep(current, runId, productionStep.key, { status: 'queued', jobId: sent.jobId }).project : current;
- return linkCastAndSetsJob(next, key, sent.jobId);
+ return linkCastAndSetsJob(next, key, sent.jobId, sent.submission);
});
+ publish(projectId, linked.project);
console.log(`🎭 Music Video Cast & Sets ${short(projectId)} ${key} → ${reserved.stage.route.mode} job ${String(sent.jobId).slice(0, 8)}`);
}
@@ -603,15 +624,16 @@ export async function getCastAndSets(projectId) {
* Settles its key (idempotent) and, when the stage is dispatching in this
* process, continues. Returns true when the record changed.
*/
-export async function onCastAndSetsImageSettled({ projectId, key, jobId = null, filename = null, error = null, productionRunId = null, productionStepKey = null, status = null }) {
+export async function onCastAndSetsImageSettled({ projectId, key, jobId = null, filename = null, error = null, revision = null, productionRunId = null, productionStepKey = null, status = null }) {
const project = await getProject(projectId);
if (!project?.castAndSets?.images?.[key]) return false;
const out = await mutateProjectRecord(projectId, (current) => {
+ if (revision != null && revision !== current.castAndSets?.revision) return { project: current, changed: false };
const next = productionRunId && productionStepKey
? settleProductionStep(current, productionRunId, productionStepKey, {
status: filename ? 'completed' : status === 'canceled' ? 'canceled' : 'failed', jobId, error,
}).project : current;
- const settled = settleCastAndSetsImage(next, key, { jobId, filename, error });
+ const settled = settleCastAndSetsImage(next, key, { jobId, filename, error, revision });
if (settled.stage?.status === 'failed') settled.project = refundUnusedCheckinSteps(settled.project);
return settled;
});
diff --git a/server/services/musicVideo/castAndSetsService.test.js b/server/services/musicVideo/castAndSetsService.test.js
index 40761d856d..5712cd9141 100644
--- a/server/services/musicVideo/castAndSetsService.test.js
+++ b/server/services/musicVideo/castAndSetsService.test.js
@@ -56,11 +56,13 @@ const DIRECTION = {
};
let jobs;
-const enqueue = vi.fn(async ({ params }) => {
+const queueJob = async ({ params }) => {
const id = `job-${jobs.length + 1}`;
jobs.push({ id, params });
return { jobId: id };
-});
+};
+const enqueue = vi.fn(queueJob);
+let imageParamsOverrides;
const runPrompt = vi.fn();
const board = {
id: 'mb-1',
@@ -90,7 +92,7 @@ async function land(projectId, keys = null) {
job.landed = true;
const filename = `${job.id}.png`;
writeFileSync(join(IMAGES(), filename), PNG);
- await service.onCastAndSetsImageSettled({ projectId, key: keyOf(job), jobId: job.id, filename, productionRunId: job.params.musicVideo.productionRunId, productionStepKey: job.params.musicVideo.productionStepKey });
+ await service.onCastAndSetsImageSettled({ projectId, key: keyOf(job), revision: job.params.musicVideo.castAndSets.revision, jobId: job.id, filename, productionRunId: job.params.musicVideo.productionRunId, productionStepKey: job.params.musicVideo.productionStepKey });
}
}
@@ -142,6 +144,7 @@ beforeEach(() => {
rmSync(join(ROOT(), 'music-video'), { recursive: true, force: true });
mkdirSync(IMAGES(), { recursive: true });
jobs = [];
+ imageParamsOverrides = {};
vi.clearAllMocks();
runPrompt.mockResolvedValue({ text: `Here you go:\n\`\`\`json\n${JSON.stringify(DIRECTION)}\n\`\`\`` });
service.__setCastAndSetsDepsForTests({
@@ -149,7 +152,7 @@ beforeEach(() => {
runPrompt,
getSettings: async () => ({}),
enqueue,
- imageParams: async (_settings, route, common) => ({ mode: route.mode, ...common }),
+ imageParams: async (_settings, route, common) => ({ mode: route.mode, ...common, ...imageParamsOverrides }),
resolveRoute: async () => ({ mode: 'codex', model: null }),
loadBoard: async () => board,
boardItemImage: async () => (item) => (item.type === 'image' ? { kind: 'image', filename: item.file } : null),
@@ -349,10 +352,65 @@ describe('Cast & Sets check-in', () => {
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' }] });
+ const snapshots = [];
+ const onStage = (event) => { if (event.projectId === project.id) snapshots.push(event.project.castAndSets); };
+ musicVideoEvents.on('cast-and-sets', onStage);
+ onTestFinished(() => musicVideoEvents.off('cast-and-sets', onStage));
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$/);
+ const firstDispatch = snapshots.find((stage) => Object.values(stage.images).filter((image) => image.jobId).length === 1);
+ expect(firstDispatch.images.character).toMatchObject({
+ status: 'queued', submittedPrompt: jobs[0].params.prompt, submittedPromptTruncated: false,
+ submittedReferences: [{ kind: 'image', filename: 'style.png' }], submittedRevision: 1,
+ });
+ const saved = (await current(project.id)).castAndSets.images.character;
+ expect(saved.submittedPrompt).toBe(jobs[0].params.prompt);
+ expect(saved.submittedPrompt).toContain('silver grain');
+});
+
+it('bounds submitted diagnostics and records only references served from approved image roots', async () => {
+ const { PATHS } = await import('../../lib/paths.js');
+ imageParamsOverrides = {
+ prompt: 'x'.repeat(20_010),
+ referenceImagePaths: [join(ROOT(), 'private', 'unserved.png'), join(PATHS.imageRefs, 'uploaded.png'),
+ ...Array.from({ length: 17 }, (_, i) => join(IMAGES(), `example-${i}.png`))],
+ };
+ const project = await seed({ visualSpec: null });
+ await service.startCastAndSets(project.id);
+ await runTo(project.id, 'review');
+ const saved = (await current(project.id)).castAndSets.images.character;
+ expect(saved.submittedPrompt).toHaveLength(20_000);
+ expect(saved.submittedPromptTruncated).toBe(true);
+ expect(saved.submittedReferences).toHaveLength(16);
+ expect(saved.submittedReferences[0]).toEqual({ kind: 'image-ref', filename: 'uploaded.png' });
+ expect(saved.submittedReferencesTruncated).toBe(true);
+ expect(JSON.stringify(saved)).not.toContain(ROOT());
+ expect(JSON.stringify(saved)).not.toContain('unserved.png');
+});
+
+it('ignores a previous revision completion while regeneration has reserved a key but has no job id yet', async () => {
+ const project = await seed();
+ await service.startCastAndSets(project.id);
+ await runTo(project.id, 'review');
+ const previous = jobs.find((job) => keyOf(job) === 'character');
+ let release;
+ const held = new Promise((resolve) => { release = resolve; });
+ enqueue.mockImplementationOnce(async (job) => { await held; return queueJob(job); });
+ onTestFinished(release);
+ await service.regenerateCastAndSets(project.id, { notes: [{ target: 'character', text: 'Shorter braid' }] });
+ await until(async () => (await current(project.id)).castAndSets.images.character.status === 'queued', 'the reserved regeneration');
+ const before = (await current(project.id)).castAndSets;
+ expect(before.images.character).toMatchObject({ status: 'queued', jobId: null, imageId: `${previous.id}.png` });
+ expect(await service.onCastAndSetsImageSettled({
+ projectId: project.id, key: 'character', revision: previous.params.musicVideo.castAndSets.revision,
+ jobId: previous.id, filename: 'obsolete.png',
+ })).toBe(false);
+ expect((await current(project.id)).castAndSets).toEqual(before);
+ release();
+ await runTo(project.id, 'review');
+ expect((await current(project.id)).castAndSets.images.character.imageId).not.toBe(`${previous.id}.png`);
});
diff --git a/server/services/musicVideoCastSetsImageHook.js b/server/services/musicVideoCastSetsImageHook.js
index be38745503..406b8fb3c2 100644
--- a/server/services/musicVideoCastSetsImageHook.js
+++ b/server/services/musicVideoCastSetsImageHook.js
@@ -24,18 +24,18 @@ const hook = createMediaJobImageHook({
initLog: '🎭 Music Video Cast & Sets image hook initialized',
tagKey: 'musicVideo',
identify: (tag) => (tag?.projectId && typeof tag.castAndSets?.key === 'string'
- ? { projectId: tag.projectId, key: tag.castAndSets.key }
+ ? { projectId: tag.projectId, key: tag.castAndSets.key, revision: tag.castAndSets.revision }
: null),
serializeKey: ({ projectId }) => projectId,
describe: ({ projectId, key }) => `${projectId}/${key}`,
- attach: ({ projectId, key, filename, job }) => settle({
- projectId, key, filename, productionRunId: job.params?.musicVideo?.productionRunId, productionStepKey: job.params?.musicVideo?.productionStepKey, jobId: typeof job.id === 'string' ? job.id : null,
+ attach: ({ projectId, key, revision, filename, job }) => settle({
+ projectId, key, revision, filename, productionRunId: job.params?.musicVideo?.productionRunId, productionStepKey: job.params?.musicVideo?.productionStepKey, jobId: typeof job.id === 'string' ? job.id : null,
}).then((changed) => (changed ? { filename } : null)),
onAttached: ({ projectId, key, filename }) => {
console.log(`🎭 music-video cast & sets ${projectId.slice(0, 11)}/${key} ← ${filename}`);
},
- onTerminal: ({ projectId, key, job }, status) => settle({
- projectId, key, status, productionRunId: job?.params?.musicVideo?.productionRunId, productionStepKey: job?.params?.musicVideo?.productionStepKey, jobId: typeof job?.id === 'string' ? job.id : null, error: job?.error || `The render was ${status}`,
+ onTerminal: ({ projectId, key, revision, job }, status) => settle({
+ projectId, key, revision, status, productionRunId: job?.params?.musicVideo?.productionRunId, productionStepKey: job?.params?.musicVideo?.productionStepKey, jobId: typeof job?.id === 'string' ? job.id : null, error: job?.error || `The render was ${status}`,
}),
});