Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat: server-owned Music Video production run with an allowed provider/model pool (#9066)
[._.]/ Adam Eivy13bda8a94f4b
diff --git a/client/src/hooks/useMusicVideoAutoReview.js b/client/src/hooks/useMusicVideoAutoReview.jsindex ef7c99bb19..81911b5d06 100644--- a/client/src/hooks/useMusicVideoAutoReview.js+++ b/client/src/hooks/useMusicVideoAutoReview.js@@ -48,7 +48,9 @@ export default function useMusicVideoAutoReview({ project, replaceProject, submiif (data.project) replace?.(data.project);setAction(data.action || null);// Only a RUNNING run's hand-out is submitted — never one that raced a pause.- if (data.action?.type === 'generate' && data.run?.status === 'running' && data.action.sections?.length && submit) {+ // A run a production owns (#9066) is dispatched by the server, not the board.+ if (data.action?.type === 'generate' && data.run?.status === 'running' && !data.run.productionRunId+ && data.action.sections?.length && submit) {submit(data.project, data.action.sections, data.action.revisionId).then((n) => {if (n) toast.info(`Auto-review: generating ${n} revised section${n === 1 ? '' : 's'}`);});diff --git a/docs/features/product-surfaces.md b/docs/features/product-surfaces.mdindex 2d05a3ec26..95fbf992c3 100644--- a/docs/features/product-surfaces.md+++ b/docs/features/product-surfaces.md@@ -110,7 +110,7 @@ An end-to-end creative production suite for authors, worldbuilders, filmmakers,| **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, 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, tempo alignment, and audience-driven pre-production treatments that direct each shot. Scenes are cutaways or lip-synced performance shots; a performance shot renders only on a verified source-audio provider (fal.ai MiniMax H3 lip-sync, 5–14.8s song slices placed at an exact edit in-point, cut from an optional full-length vocal stem when one is attached) — Grok video is cutaway-only. Draft excerpts are reviewed and selectively revised by hand, or by an opt-in auto-review run bounded by director-set review and paid-generation limits (a frame-only look never passes motion or audio sync); the song is the sole audio unless a sound-design bed is explicitly chosen to mix under it. | — |+| **Music Video Studio** | `/music-video` | Audio-reactive video creation, beat-detection synchronization, scene choreography, tempo alignment, and audience-driven pre-production treatments that direct each shot. Scenes are cutaways or lip-synced performance shots; a performance shot renders only on a verified source-audio provider (fal.ai MiniMax H3 lip-sync, 5–14.8s song slices placed at an exact edit in-point, cut from an optional full-length vocal stem when one is attached) — Grok video is cutaway-only. Draft excerpts are reviewed and selectively revised by hand, or by an opt-in auto-review run bounded by director-set review and paid-generation limits (a frame-only look never passes motion or audio sync). A server-owned production run (`/api/music-video/:id/production-runs`, #9066) plans an empty board, generates missing frames and clips only on a director-allowed image/video provider+model pool, hands the continuous draft to auto-review and dispatches its revisions — within explicit generation, review and (priced routes only) dollar limits, without the browser open, and never resuming on its own after a restart; the song is the sole audio unless a sound-design bed is explicitly chosen to mix under it. | — || **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/lib/musicVideoValidation.js b/server/lib/musicVideoValidation.jsindex c4cdd5c2fe..98a929023f 100644--- a/server/lib/musicVideoValidation.js+++ b/server/lib/musicVideoValidation.js@@ -16,6 +16,7 @@ import {MUSIC_VIDEO_AUTOMATION_GUIDANCE_MAX,MUSIC_VIDEO_AUTOMATION_TOOL_IDS,} from './musicVideoAutomation.js';+import { IMAGE_GEN_MODES, VIDEO_GEN_MODES } from './generationModes.js';// A project is authored hands-on (director) or seeded by the AI planner// (autonomous); both share the same record + scene board.@@ -465,6 +466,36 @@ export const musicVideoAutoReviewResumeSchema = z.object({limits: musicVideoAutoReviewLimitsSchema.partial().optional(),}).strict();+// ---- Server-owned production run (#9066) -----------------------------------+// The allowed pool: explicit image/video render backends (and models) the run+// may dispatch to — re-checked for eligibility and capability at every+// dispatch. Every limit but the dollar cap is required; the cap is accepted+// only when every metered route has a known price (services/musicVideo/production.js).+const musicVideoProductionRouteSchema = z.discriminatedUnion('kind', [+ z.object({ kind: z.literal('image'), mode: z.enum(IMAGE_GEN_MODES), model: z.string().trim().min(1).max(200).nullable().optional() }).strict(),+ z.object({ kind: z.literal('video'), mode: z.enum(VIDEO_GEN_MODES), model: z.string().trim().min(1).max(200).nullable().optional() }).strict(),+]);++export const musicVideoProductionLimitsSchema = z.object({+ maxGenerations: z.number().int().min(1).max(500),+ maxReviewAttempts: z.number().int().min(1).max(10),+ spendCapUsd: z.number().min(0).max(100000).nullable().optional(),+}).strict();++export const musicVideoProductionStartSchema = z.object({+ directive: z.string().max(4000).optional(),+ pool: z.array(musicVideoProductionRouteSchema).min(1).max(12),+ limits: musicVideoProductionLimitsSchema,+ providerId: z.string().min(1).max(200).nullable().optional(),+ model: z.string().min(1).max(200).nullable().optional(),+}).strict();++// Resume may RAISE a limit; `acceptBasis` continues against a changed creative setup.+export const musicVideoProductionResumeSchema = z.object({+ limits: musicVideoProductionLimitsSchema.partial().optional(),+ acceptBasis: z.boolean().optional(),+}).strict();+// A generation kickoff that failed before reaching the queue (#9011) — names// the rejected section whose claim should clear so the next resume can hand// it out again immediately instead of waiting out GENERATION_CLAIM_LEASE_MS.diff --git a/server/lib/syncWire.js b/server/lib/syncWire.jsindex 4ae7cb54d0..a62d014c88 100644--- a/server/lib/syncWire.js+++ b/server/lib/syncWire.js@@ -42,13 +42,15 @@ export function sanitizeSoftDeleteFields(raw) {/*** Remove Music Video render choices that belong to the receiving install.+ * The production-run checkpoint (#9066) is always stripped: it names this+ * install's providers and jobs, and a peer must never execute (or hash) it.* Transport keeps the legacy `videoSettings.backend` by default so an older* receiver is not regressed; upgraded receivers and content hashing opt into* stripping it as well.*/export function stripMusicVideoLocalRenderPins(record, { stripVideoBackend = true } = {}) {if (!record || typeof record !== 'object' || Array.isArray(record)) return record;- const { imageMode: _imageMode, imageModelId: _imageModelId, ...shared } = record;+ const { imageMode: _imageMode, imageModelId: _imageModelId, productionRuns: _productionRuns, ...shared } = record;if (stripVideoBackend && shared.videoSettings&& typeof shared.videoSettings === 'object' && !Array.isArray(shared.videoSettings)) {const { backend: _backend, ...sharedVideoSettings } = shared.videoSettings;diff --git a/server/routes/musicVideo.js b/server/routes/musicVideo.jsindex 54d08a9667..2d5ae848d0 100644--- a/server/routes/musicVideo.js+++ b/server/routes/musicVideo.js@@ -39,6 +39,8 @@ import {musicVideoRevisionReleaseSchema,musicVideoAutoReviewStartSchema,musicVideoAutoReviewResumeSchema,+ musicVideoProductionStartSchema,+ musicVideoProductionResumeSchema,isPaginationRequested,paginateArray,} from '../lib/validation.js';@@ -87,6 +89,9 @@ import {import {startAutoReview, resumeAutoReview, stopAutoReview, cancelAutoReview,} from '../services/musicVideo/autoReviewService.js';+import {+ startProduction, resumeProduction, stopProduction, cancelProduction, getProduction,+} from '../services/musicVideo/productionService.js';import { planProject } from '../services/musicVideo/planner.js';import { parseLyricCues } from '../services/musicVideo/timedText.js';import { alignProjectLyrics } from '../services/musicVideo/lyricAlign.js';@@ -494,6 +499,33 @@ router.post('/:id/auto-reviews/:runId/cancel', asyncHandler(async (req, res) =>res.json(await cancelAutoReview(req.params.id, req.params.runId));}));+// --- Server-owned production run (#9066) ---+// Start/resume write the checkpoint and return at once; the run advances in+// the background (plan → frames → clips → reviewed draft → revisions) from+// queue completion events and reports over `music-video:production`. Only+// these explicit requests start or resume a run — nothing at boot does.+router.post('/:id/production-runs', asyncHandler(async (req, res) => {+ const { providerId, model, ...input } = validateRequest(musicVideoProductionStartSchema, req.body || {});+ res.status(201).json(await startProduction(req.params.id, { ...input, reviewer: { providerId, model } }));+}));++router.get('/:id/production-runs/:runId', asyncHandler(async (req, res) => {+ res.json(await getProduction(req.params.id, req.params.runId));+}));++router.post('/:id/production-runs/:runId/resume', asyncHandler(async (req, res) => {+ const input = validateRequest(musicVideoProductionResumeSchema, req.body || {});+ res.json(await resumeProduction(req.params.id, req.params.runId, input));+}));++router.post('/:id/production-runs/:runId/stop', asyncHandler(async (req, res) => {+ res.json(await stopProduction(req.params.id, req.params.runId));+}));++router.post('/:id/production-runs/:runId/cancel', asyncHandler(async (req, res) => {+ res.json(await cancelProduction(req.params.id, req.params.runId));+}));+// --- Director scene board ---router.post('/:id/scenes', asyncHandler(async (req, res) => {diff --git a/server/services/musicVideo/autoReview.js b/server/services/musicVideo/autoReview.jsindex 3ac8d56c62..30097c34da 100644--- a/server/services/musicVideo/autoReview.js+++ b/server/services/musicVideo/autoReview.js@@ -122,7 +122,7 @@ const touchRun = (run, patch, now) => ({ ...run, ...patch, updatedAt: now });* Start a run over `[startSec, endSec)`. Refuses while another run is live or* a manual revision is open (the run needs the revision slot for its own).*/-export function startAutoReviewOnProject(project, { startSec, endSec, limits, reviewer = {} }, now = new Date().toISOString()) {+export function startAutoReviewOnProject(project, { startSec, endSec, limits, reviewer = {}, productionRunId = null }, now = new Date().toISOString()) {const live = activeAutoReview(project);if (live) throw autoReviewError(409, 'AUTO_REVIEW_IN_PROGRESS', 'Finish, cancel or resume the existing auto-review run first', { runId: live.id });const openRevision = projectRevisions(project).find((r) => r.status === 'open' || r.status === 'rendering');@@ -139,6 +139,10 @@ export function startAutoReviewOnProject(project, { startSec, endSec, limits, remodel: isNonBlankStr(reviewer.model) ? reviewer.model : null,},usage: { reviews: 0, generations: 0 },+ // #9066: a production run that handed this run its draft dispatches the+ // run's revised sections server-side (productionService.js), so the board+ // must not also submit them.+ ...(isNonBlankStr(productionRunId) ? { productionRunId } : {}),attempts: [{ n: 1, excerptId: null, renderFailures: 0, reviewStartedAt: null, review: null, revisionId: null }],stopReason: null,error: null,diff --git a/server/services/musicVideo/events.js b/server/services/musicVideo/events.jsindex 1366acbecc..929aa9113e 100644--- a/server/services/musicVideo/events.js+++ b/server/services/musicVideo/events.js@@ -24,5 +24,11 @@ import { EventEmitter } from 'events';// 'auto-review' → { projectId, runId, run, action, project } — an// auto-review run advanced; socket.js bridges it to// `music-video:auto-review` so an open board can submit the sections the-// run hands out for generation and show the run's progress.+// run hands out for generation and show the run's progress. A run a+// production owns (`run.productionRunId`) is dispatched server-side instead.+//+// #9066 adds:+// 'production' → { projectId, runId, run, action, project } — a server-owned+// production run advanced (steps, route choices, spend, halts); socket.js+// bridges it to `music-video:production`.export const musicVideoEvents = new EventEmitter();diff --git a/server/services/musicVideo/handoff.js b/server/services/musicVideo/handoff.jsindex 6a98686f62..a3cca6c90f 100644--- a/server/services/musicVideo/handoff.js+++ b/server/services/musicVideo/handoff.js@@ -92,6 +92,12 @@ function composePrompt(primary, fallback, project, clause) {].filter(Boolean).join(', ');}+/** A scene's composed reference-frame prompt (also the server-owned production run's, #9066). */+export const sceneFramePrompt = (project, scene) => composePrompt(scene.framePrompt, scene.prompt, project, scene.direction?.frameClause);++/** A scene's composed shot (motion) prompt. */+export const sceneShotPrompt = (project, scene) => composePrompt(scene.prompt, scene.framePrompt, project, scene.direction?.motionClause);+/** Build the export manifest for a project. */export function buildHandoffManifest(project, { now = new Date().toISOString() } = {}) {const spec = project.visualSpec || null;@@ -128,8 +134,8 @@ export function buildHandoffManifest(project, { now = new Date().toISOString() }endSec: scene.endSec ?? null,lyricText: scene.lyricText || '',visualIntent: scene.visualIntent || '',- framePrompt: composePrompt(scene.framePrompt, scene.prompt, project, scene.direction?.frameClause),- shotPrompt: composePrompt(scene.prompt, scene.framePrompt, project, scene.direction?.motionClause),+ framePrompt: sceneFramePrompt(project, scene),+ shotPrompt: sceneShotPrompt(project, scene),referenceFiles: conditioning,selected: {referenceImageId: scene.referenceImageId || null,diff --git a/server/services/musicVideo/planner.js b/server/services/musicVideo/planner.jsindex f04c1f1aa7..1f757f662a 100644--- a/server/services/musicVideo/planner.js+++ b/server/services/musicVideo/planner.js@@ -235,9 +235,11 @@ async function tryProposeScenePrompts(project, shots, { providerId, model } = {}* @param {string} [options.providerId] — pin a specific provider instead of* the active one.* @param {string} [options.model] — model override for the prompt-seeding call.+ * @param {string} [options.directive] — a production run's directive (#9066),+ * added to the director guidance the first-pass prompts are written under.* @returns {Promise<{ project: object, scenesAdded: number, promptsSeeded: boolean, promptsSkippedReason: string|null, pacing: object }>}*/-export async function planProject(id, { seedPrompts = true, providerId, model } = {}) {+export async function planProject(id, { seedPrompts = true, providerId, model, directive } = {}) {const project = await getProject(id);if (!project) throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });@@ -264,7 +266,9 @@ export async function planProject(id, { seedPrompts = true, providerId, model }let promptsSeeded = false;let promptsSkippedReason = seedPrompts ? null : 'not-requested';if (seedPrompts) {- const { seeded, reason } = await tryProposeScenePrompts(project, shots, { providerId, model });+ const guidance = [project.automation?.guidance?.trim(), directive?.trim()].filter(Boolean).join('\n');+ const planning = directive?.trim() ? { ...project, automation: { ...project.automation, guidance } } : project;+ const { seeded, reason } = await tryProposeScenePrompts(planning, shots, { providerId, model });if (seeded) {promptsSeeded = true;for (const [idx, fields] of seeded) {diff --git a/server/services/musicVideo/production.js b/server/services/musicVideo/production.jsnew file mode 100644index 0000000000..099fd41f4a--- /dev/null+++ b/server/services/musicVideo/production.js@@ -0,0 +1,494 @@+/**+ * Music Video — server-owned production run (#9066): pure record transforms.+ *+ * A production run is an install-local checkpoint on the project+ * (`project.productionRuns[]`) that exists only because the director pressed+ * Start with:+ *+ * - a free-text `directive` (steers the plan when the board is empty);+ * - an allowlist `pool` of image/video `{ kind, mode, model }` routes — the+ * only routes any step may dispatch to (re-checked at dispatch, see+ * productionPool.js; there is never a silent fallback to another route);+ * - `limits`: `maxGenerations` (paid scene-generation jobs, including the+ * review's revisions), `maxReviewAttempts` (reviewer calls on the+ * continuous excerpt) and an optional `spendCapUsd`, accepted only when+ * every metered route in the pool has a known price.+ *+ * The run records a `basis` — a checksum of the creative setup (concept,+ * visual spec, treatment brief, automation brief, audio analysis, pacing,+ * composition) — at Start. Any later change halts the run `needs-replan`;+ * only an explicit resume that accepts the new basis continues.+ *+ * Every dispatch is a STEP with a stable key, reserved (and charged) in one+ * serialized write BEFORE the job is enqueued, then linked to its job id.+ * The queue (not the record) is the in-flight truth: a scene with a live job+ * for its slot — ours or the director's — is never dispatched again, so a+ * lost write between enqueue and link cannot cause a duplicate job. A step+ * settles exactly once (duplicate completion events are no-ops), and only a+ * step whose job provably never reached the queue is refunded.+ *+ * `processId` pins a running run to the server process that started or+ * resumed it: after a restart the checkpoint loads, completion events of+ * already-queued jobs still settle their steps, but nothing is dispatched+ * until the director explicitly resumes.+ *+ * Peer sync: `productionRuns` is WIRE-LOCAL (lib/syncWire.js) — the pool names+ * this install's providers, and a peer must never execute another machine's+ * run. `mergeProjectRecord` restores the local runs over a newer remote copy.+ */++import { randomUUID } from 'crypto';+import { ServerError } from '../../lib/errorHandler.js';+import { canonicalSnapshotChecksum } from '../../lib/snapshotChecksum.js';+import { isNonBlankStr, trimTo } from '../../lib/textUtils.js';+import { sceneVisualLayer } from '../../lib/musicVideoLayers.js';+import { projectAutoReviews } from './autoReview.js';+import { projectRevisions } from './revision.js';++const PRODUCTION_LIMIT_BOUNDS = Object.freeze({+ maxGenerations: Object.freeze({ min: 1, max: 500 }),+ maxReviewAttempts: Object.freeze({ min: 1, max: 10 }),+ spendCapUsd: Object.freeze({ min: 0, max: 100000 }),+});+const PRODUCTION_DIRECTIVE_MAX = 4000;+const PRODUCTION_POOL_MAX = 12;+const PRODUCTION_STATUSES = Object.freeze([+ 'running', 'stopped', 'limit-reached', 'blocked', 'needs-replan', 'completed', 'needs-human', 'failed', 'canceled',+]);+const RESUMABLE = new Set(['running', 'stopped', 'limit-reached', 'blocked', 'needs-replan']);+const LIVE_STEP = new Set(['reserved', 'queued']);+const LIVE_JOB = new Set(['queued', 'running']);+// A scene slot whose generation failed this many times needs a director.+const MAX_SLOT_FAILURES = 2;+// A reserved step whose job never showed up in the queue after this long did+// not reach it (enqueue persists synchronously before returning).+const RESERVATION_LEASE_MS = 60_000;+const MAX_PROJECT_RUNS = 10;+const MAX_RUN_STEPS = 1000;+const MAX_ERROR_LEN = 500;++const productionError = (status, code, message, context) =>+ new ServerError(message, { status, code, ...(context ? { context } : {}) });++/** The run array on a project, tolerating a legacy record with none. */+export const projectProductionRuns = (project) => (Array.isArray(project?.productionRuns) ? project.productionRuns : []);++/** The run that is still live (running or resumable), if any. */+const activeProductionRun = (project) => projectProductionRuns(project).find((r) => RESUMABLE.has(r.status)) || null;++export function findProductionRun(project, runId) {+ const run = projectProductionRuns(project).find((r) => r.id === runId);+ if (!run) throw productionError(404, 'NOT_FOUND', 'Production run not found');+ return run;+}++function replaceRun(project, run) {+ return { ...project, productionRuns: projectProductionRuns(project).map((r) => (r.id === run.id ? run : r)) };+}++function mutateRun(project, runId, fn, now) {+ const run = findProductionRun(project, runId);+ const next = { ...run, ...fn(run), updatedAt: now };+ return { project: replaceRun(project, next), run: next };+}++function pruneRuns(runs) {+ const next = runs.slice();+ for (let i = 0; i < next.length && next.length > MAX_PROJECT_RUNS;) {+ if (RESUMABLE.has(next[i].status)) i += 1;+ else next.splice(i, 1);+ }+ return next;+}++/**+ * The creative inputs a run was planned against. Scenes are deliberately NOT+ * part of it: the run itself seeds and fills them, and a director editing one+ * scene's prompt mid-run changes only what that scene generates next.+ */+function productionBasisRevision(project) {+ const pick = (value) => value ?? null;+ return canonicalSnapshotChecksum({+ concept: pick(project?.concept),+ visualSpec: pick(project?.visualSpec),+ brief: pick(project?.treatment?.brief),+ automation: pick(project?.automation),+ audio: {+ trackId: pick(project?.trackId),+ uploadedAudioFilename: pick(project?.uploadedAudioFilename),+ sections: pick(project?.audioAnalysis?.sections),+ durationSec: pick(project?.audioAnalysis?.durationSec),+ },+ pacing: pick(project?.pacing),+ composition: pick(project?.composition?.mode),+ });+}++const intIn = (value, { min, max }, name) => {+ if (!Number.isInteger(value) || value < min || value > max) {+ throw productionError(422, 'VALIDATION_ERROR', `${name} must be a whole number from ${min} to ${max}`);+ }+ return value;+};++/** Every limit but the dollar cap is REQUIRED — a run never picks its own budget. */+function normalizeProductionLimits(limits) {+ const cap = limits?.spendCapUsd;+ if (cap != null && !(typeof cap === 'number' && cap >= PRODUCTION_LIMIT_BOUNDS.spendCapUsd.min && cap <= PRODUCTION_LIMIT_BOUNDS.spendCapUsd.max)) {+ throw productionError(422, 'VALIDATION_ERROR', `spendCapUsd must be a number from 0 to ${PRODUCTION_LIMIT_BOUNDS.spendCapUsd.max}, or null`);+ }+ return {+ maxGenerations: intIn(limits?.maxGenerations, PRODUCTION_LIMIT_BOUNDS.maxGenerations, 'maxGenerations'),+ maxReviewAttempts: intIn(limits?.maxReviewAttempts, PRODUCTION_LIMIT_BOUNDS.maxReviewAttempts, 'maxReviewAttempts'),+ spendCapUsd: cap == null ? null : cap,+ };+}++/** A pool route's identity: the same backend + model always compares equal. */+export const routeKey = (route) => `${route.kind}:${route.mode}:${route.model || ''}`;++/** De-duplicate a validated pool, keeping the director's order (it is the preference order). */+export function normalizeProductionPool(pool) {+ const seen = new Set();+ const out = [];+ for (const entry of Array.isArray(pool) ? pool : []) {+ if (!entry || (entry.kind !== 'image' && entry.kind !== 'video') || !isNonBlankStr(entry.mode)) continue;+ const route = { kind: entry.kind, mode: entry.mode.trim(), model: isNonBlankStr(entry.model) ? entry.model.trim() : null };+ if (seen.has(routeKey(route))) continue;+ seen.add(routeKey(route));+ out.push(route);+ }+ if (!out.length) throw productionError(422, 'VALIDATION_ERROR', 'The allowed pool needs at least one image or video route');+ if (out.length > PRODUCTION_POOL_MAX) throw productionError(422, 'VALIDATION_ERROR', `The allowed pool holds at most ${PRODUCTION_POOL_MAX} routes`);+ return out;+}++/** Is `route` literally a member of the run's allowlist? */+export const poolHasRoute = (run, route) => !!route && run.pool.some((r) => routeKey(r) === routeKey(route));++/**+ * Start a run. Refuses while another production run, an auto-review run, or+ * a manual revision is live — the run needs those slots for its own review.+ * `pricing` maps routeKey → price per generation in USD (0 for local, null+ * when unknown); a dollar cap requires every route to have a known price.+ */+export function startProductionOnProject(project, {+ directive = '', pool, limits, reviewer = {}, processId, pricing = {},+}, now = new Date().toISOString()) {+ const live = activeProductionRun(project);+ if (live) throw productionError(409, 'PRODUCTION_IN_PROGRESS', 'Finish, cancel or resume the existing production run first', { runId: live.id });+ const liveReview = projectAutoReviews(project).find((r) => ['running', 'stopped', 'limit-reached'].includes(r.status));+ if (liveReview) throw productionError(409, 'AUTO_REVIEW_IN_PROGRESS', 'Finish or cancel the auto-review run before starting production', { runId: liveReview.id });+ const openRevision = projectRevisions(project).find((r) => r.status === 'open' || r.status === 'rendering');+ if (openRevision) throw productionError(409, 'REVISION_IN_PROGRESS', 'Finish or cancel the open revision before starting production', { revisionId: openRevision.id });+ if (project?.composition?.mode === 'code') {+ throw productionError(409, 'PRODUCTION_UNSUPPORTED', 'A code-rendered project generates no footage — render it directly');+ }+ if (!Array.isArray(project?.audioAnalysis?.sections) || !project.audioAnalysis.sections.length) {+ throw productionError(409, 'NOT_ANALYZED', 'Analyze the song before starting production');+ }+ const normalizedPool = normalizeProductionPool(pool);+ const normalizedLimits = normalizeProductionLimits(limits);+ if (normalizedLimits.spendCapUsd !== null) {+ const unpriced = normalizedPool.filter((r) => typeof pricing[routeKey(r)] !== 'number');+ if (unpriced.length) {+ throw productionError(409, 'PRODUCTION_COST_UNKNOWN',+ `A dollar cap needs a known price for every route; ${unpriced.map((r) => `${r.kind} ${r.mode}${r.model ? ` (${r.model})` : ''}`).join(', ')} has none. Remove the cap (the generation limit still applies) or remove those routes.`);+ }+ }+ const run = {+ id: `mvpr-${randomUUID()}`,+ status: 'running',+ directive: trimTo(typeof directive === 'string' ? directive : '', PRODUCTION_DIRECTIVE_MAX) || '',+ pool: normalizedPool,+ pricing: Object.fromEntries(normalizedPool.map((r) => [routeKey(r), typeof pricing[routeKey(r)] === 'number' ? pricing[routeKey(r)] : null])),+ limits: normalizedLimits,+ reviewer: {+ providerId: isNonBlankStr(reviewer.providerId) ? reviewer.providerId : null,+ model: isNonBlankStr(reviewer.model) ? reviewer.model : null,+ },+ basis: { revision: productionBasisRevision(project), capturedAt: now },+ usage: { generations: 0, spentUsd: 0 },+ planned: false,+ reviewRunId: null,+ steps: [],+ processId: processId || null,+ stopReason: null,+ error: null,+ createdAt: now,+ updatedAt: now,+ };+ return { project: { ...project, productionRuns: pruneRuns([...projectProductionRuns(project), run]), updatedAt: now }, run };+}++// ---- deriving the next step -------------------------------------------------++const SLOT = Object.freeze({ frame: 'referenceImageId', clip: 'videoHistoryId' });+const JOB_KIND = Object.freeze({ frame: 'image', clip: 'video' });++/** The scenes that need a still frame and a clip, per the project's render mode. */+function productionTargets(project) {+ const layered = project?.composition?.mode === 'composed';+ const scenes = Array.isArray(project?.scenes) ? project.scenes : [];+ return {+ frame: scenes.filter((s) => sceneVisualLayer(s, { layered }) !== 'card'),+ clip: scenes.filter((s) => sceneVisualLayer(s, { layered }) === 'footage'),+ };+}++/** A live media job generating this scene slot — ours, a revision's, or the director's own. */+function liveSlotJob(jobs, projectId, sceneId, stepKind) {+ return (jobs || []).find((job) => job?.kind === JOB_KIND[stepKind] && LIVE_JOB.has(job.status)+ && job.params?.musicVideo?.projectId === projectId && job.params.musicVideo.sceneId === sceneId) || null;+}++const slotSteps = (run, sceneId, stepKind, revisionId = null) => run.steps+ .filter((s) => s.sceneId === sceneId && s.kind === stepKind && (s.revisionId || null) === revisionId);++/**+ * Pure: what the run should do next, from the record and the queue alone:+ * `plan` — the board is empty: seed it (one planner call, first time only);+ * `dispatch` — generate `kind` (frame|clip) for `sceneId`;+ * `review` — every scene holds its media: hand the continuous excerpt+ * `[startSec, endSec)` to an auto-review run;+ * `wait` — work in flight (generation jobs, or the review run);+ * `halt` — stop now with `status` + `reason`;+ * `idle` — not running, or pinned to another process (restart).+ */+export function nextProductionStep(project, run, { jobs = [], processId = null } = {}) {+ if (run.status !== 'running') return { type: 'idle' };+ if (!processId || run.processId !== processId) return { type: 'idle', interrupted: true };+ if (productionBasisRevision(project) !== run.basis.revision) {+ return { type: 'halt', status: 'needs-replan', reason: 'The creative setup changed since Start — review it, then resume against the new setup' };+ }+ if (run.reviewRunId) {+ const review = projectAutoReviews(project).find((r) => r.id === run.reviewRunId);+ if (!review) return { type: 'halt', status: 'needs-human', reason: 'The review run is gone — watch the draft yourself' };+ if (review.status === 'running') return { type: 'wait', on: 'review' };+ if (review.status === 'passed') return { type: 'halt', status: 'completed', reason: null };+ if (review.status === 'stopped' || review.status === 'limit-reached') {+ return { type: 'halt', status: review.status === 'limit-reached' ? 'limit-reached' : 'stopped', reason: `The review paused: ${review.stopReason || review.status}` };+ }+ return { type: 'halt', status: 'needs-human', reason: review.stopReason || `The review ended ${review.status}` };+ }+ const scenes = Array.isArray(project.scenes) ? project.scenes : [];+ if (!scenes.length) {+ if (run.planned) return { type: 'halt', status: 'blocked', reason: 'Planning produced no scenes — check the song analysis' };+ return { type: 'plan' };+ }+ const targets = productionTargets(project);+ let waiting = false;+ for (const stepKind of ['frame', 'clip']) {+ for (const scene of targets[stepKind]) {+ if (scene[SLOT[stepKind]]) continue;+ // A clip is generated from the scene's frame; wait for it.+ if (stepKind === 'clip' && !scene.referenceImageId) { waiting = true; continue; }+ const steps = slotSteps(run, scene.sceneId, stepKind);+ if (steps.some((s) => LIVE_STEP.has(s.status)) || liveSlotJob(jobs, project.id, scene.sceneId, stepKind)) { waiting = true; continue; }+ const failures = steps.filter((s) => s.status === 'failed' || s.status === 'canceled').length;+ if (failures >= MAX_SLOT_FAILURES) {+ return { type: 'halt', status: 'needs-human', reason: `"${scene.label || scene.sceneId}" failed to generate its ${stepKind} ${failures} times — generate it by hand or change the pool, then resume` };+ }+ return { type: 'dispatch', kind: stepKind, sceneId: scene.sceneId };+ }+ }+ if (waiting) return { type: 'wait', on: 'generation' };+ const spans = scenes.filter((s) => typeof s.startSec === 'number' && typeof s.endSec === 'number' && s.endSec > s.startSec);+ if (!spans.length) return { type: 'halt', status: 'blocked', reason: 'No scene is timed on the song, so there is no excerpt to review' };+ return {+ type: 'review',+ startSec: Math.min(...spans.map((s) => s.startSec)),+ endSec: Math.max(...spans.map((s) => s.endSec)),+ };+}++// ---- dispatch accounting ------------------------------------------------------++/**+ * Reserve (and charge) one generation step BEFORE its job is enqueued. Throws+ * 409 when the run is not running in this process, the slot already has a+ * live step (a concurrent advance or a double submit), or a limit would be+ * exceeded — so a job past the budget is refused before it is paid for.+ * Returns `{ project, run, step }`.+ */+export function reserveProductionStep(project, runId, {+ kind, sceneId, revisionId = null, route, rationale = '', processId,+}, now = new Date().toISOString()) {+ let step = null;+ const out = mutateRun(project, runId, (run) => {+ if (run.status !== 'running') throw productionError(409, 'PRODUCTION_NOT_RUNNING', `This production run is ${run.status}`);+ if (run.processId !== processId) throw productionError(409, 'PRODUCTION_INTERRUPTED', 'The server restarted since this run was started — resume it first');+ if (!poolHasRoute(run, route)) throw productionError(409, 'PRODUCTION_ROUTE_NOT_ALLOWED', `${route?.kind} ${route?.mode} is not in this run's allowed pool`);+ const existing = slotSteps(run, sceneId, kind, revisionId);+ if (existing.some((s) => LIVE_STEP.has(s.status))) {+ throw productionError(409, 'PRODUCTION_STEP_IN_FLIGHT', 'This scene is already generating for the production run', { sceneId });+ }+ if (run.usage.generations >= run.limits.maxGenerations) {+ throw productionError(409, 'PRODUCTION_SPEND_LIMIT', `This production run reached its ${run.limits.maxGenerations}-generation limit`);+ }+ const price = run.pricing?.[routeKey(route)];+ const costUsd = typeof price === 'number' ? price : null;+ if (run.limits.spendCapUsd !== null) {+ if (costUsd === null) throw productionError(409, 'PRODUCTION_COST_UNKNOWN', 'This route has no known price, so the dollar cap cannot bound it');+ if (run.usage.spentUsd + costUsd > run.limits.spendCapUsd + 1e-9) {+ throw productionError(409, 'PRODUCTION_BUDGET_EXHAUSTED', `The next generation would exceed the $${run.limits.spendCapUsd} cap`);+ }+ }+ if (run.steps.length >= MAX_RUN_STEPS) throw productionError(409, 'PRODUCTION_STEP_LIMIT', 'This run recorded its maximum number of steps');+ step = {+ key: `${kind}:${sceneId}:${revisionId || 'base'}:${existing.length + 1}`,+ kind,+ sceneId,+ revisionId,+ route: { kind: route.kind, mode: route.mode, model: route.model || null },+ rationale: trimTo(rationale, MAX_ERROR_LEN) || '',+ costUsd,+ status: 'reserved',+ jobId: null,+ error: null,+ reservedAt: now,+ settledAt: null,+ };+ return {+ usage: { generations: run.usage.generations + 1, spentUsd: run.usage.spentUsd + (costUsd || 0) },+ steps: [...run.steps, step],+ };+ }, now);+ return { ...out, step };+}++const refund = (run, step) => ({+ generations: Math.max(0, run.usage.generations - 1),+ spentUsd: Math.max(0, run.usage.spentUsd - (step.costUsd || 0)),+});++/**+ * Settle a step. `queued` links its job; `completed`/`failed`/`canceled` end+ * it; `refused` ends a step whose submission never reached the queue and+ * refunds its charge. Idempotent: a step already in a terminal state is left+ * untouched (duplicate completion events), and only a reserved step can be+ * refused — a charge whose job reached the queue stays spent.+ * Returns `{ project, run, step, changed }`.+ */+export function settleProductionStep(project, runId, stepKey, { status, jobId = null, error = null }, now = new Date().toISOString()) {+ const run = findProductionRun(project, runId);+ const step = run.steps.find((s) => s.key === stepKey);+ if (!step) return { project, run, step: null, changed: false };+ const allowed = status === 'queued' ? step.status === 'reserved'+ : status === 'refused' ? step.status === 'reserved'+ : LIVE_STEP.has(step.status);+ if (!allowed) return { project, run, step, changed: false };+ const settled = {+ ...step,+ status,+ jobId: jobId || step.jobId,+ error: error ? trimTo(String(error), MAX_ERROR_LEN) : step.error,+ settledAt: status === 'queued' ? null : now,+ };+ const out = mutateRun(project, runId, (r) => ({+ steps: r.steps.map((s) => (s.key === stepKey ? settled : s)),+ ...(status === 'refused' ? { usage: refund(r, step) } : {}),+ }), now);+ return { ...out, step: settled, changed: true };+}++/** The step a media job belongs to (by its tag, then by job id). */+export function stepForJob(run, job) {+ const tag = job?.params?.musicVideo;+ return run.steps.find((s) => (tag?.productionStepKey && s.key === tag.productionStepKey) || (job?.id && s.jobId === job.id)) || null;+}++/**+ * Reconcile the run's live steps against the queue (resume, after a restart):+ * a step whose job is found adopts its state; a reserved step with no job+ * after the lease never reached the queue and is refunded. Returns+ * `{ project, run }`.+ */+export function reconcileProductionSteps(project, runId, jobs = [], nowMs = Date.now(), now = new Date(nowMs).toISOString()) {+ const run = findProductionRun(project, runId);+ let usage = run.usage;+ const steps = run.steps.map((step) => {+ if (!LIVE_STEP.has(step.status)) return step;+ const job = (jobs || []).find((j) => (step.jobId && j.id === step.jobId)+ || (j.params?.musicVideo?.productionRunId === runId && j.params.musicVideo.productionStepKey === step.key));+ if (job) {+ if (LIVE_JOB.has(job.status)) return { ...step, status: 'queued', jobId: job.id };+ if (job.status === 'completed') return { ...step, status: 'completed', jobId: job.id, settledAt: now };+ return { ...step, status: job.status === 'canceled' ? 'canceled' : 'failed', jobId: job.id, error: trimTo(String(job.error || job.status), MAX_ERROR_LEN), settledAt: now };+ }+ if (step.status === 'reserved' && nowMs - Date.parse(step.reservedAt) >= RESERVATION_LEASE_MS) {+ usage = refund({ usage }, step);+ return { ...step, status: 'refused', error: 'The submission never reached the queue', settledAt: now };+ }+ // A queued step whose job left the queue's history: the take (if any)+ // already landed; count it settled without guessing the outcome.+ if (step.status === 'queued') return { ...step, status: 'failed', error: 'The job is no longer in the queue history', settledAt: now };+ return step;+ });+ return mutateRun(project, runId, () => ({ steps, usage }), now);+}++// ---- lifecycle ---------------------------------------------------------------++/** Mark the board as planned by this run (so an empty plan halts instead of looping). */+export const markProductionPlanned = (project, runId, now = new Date().toISOString()) =>+ mutateRun(project, runId, () => ({ planned: true }), now);++/** Link the auto-review run this production handed its draft to. */+export const attachProductionReview = (project, runId, reviewRunId, now = new Date().toISOString()) =>+ mutateRun(project, runId, () => ({ reviewRunId }), now);++/** Stop the run with a status/reason. */+export function haltProduction(project, runId, { status, reason = null, error = null }, now = new Date().toISOString()) {+ if (!PRODUCTION_STATUSES.includes(status) || status === 'running') throw new Error(`haltProduction: invalid status ${status}`);+ return mutateRun(project, runId, (run) => {+ if (!RESUMABLE.has(run.status)) throw productionError(409, 'PRODUCTION_CLOSED', `This production run is already ${run.status}`);+ return { status, stopReason: reason, error: error ? trimTo(String(error), MAX_ERROR_LEN) : null };+ }, now);+}++/** Director Stop: nothing new is dispatched; work in flight keeps its evidence. */+export function stopProductionOnProject(project, runId, now = new Date().toISOString()) {+ const run = findProductionRun(project, runId);+ if (!RESUMABLE.has(run.status)) throw productionError(409, 'PRODUCTION_CLOSED', `This production run is already ${run.status}`);+ return haltProduction(project, runId, { status: 'stopped', reason: 'Stopped by the director' }, now);+}++/**+ * Explicit resume: re-pins the run to this process. `limits` may only RAISE a+ * budget. A run halted on a changed creative setup continues only when the+ * director accepts the new basis (`acceptBasis`), which re-snapshots it.+ */+export function resumeProductionOnProject(project, runId, { limits, acceptBasis = false, processId } = {}, now = new Date().toISOString()) {+ return mutateRun(project, runId, (run) => {+ if (!RESUMABLE.has(run.status)) throw productionError(409, 'PRODUCTION_CLOSED', `This production run is ${run.status} — start a new run instead`);+ const basisChanged = productionBasisRevision(project) !== run.basis.revision;+ if (basisChanged && !acceptBasis) {+ throw productionError(409, 'PRODUCTION_BASIS_CHANGED', 'The creative setup changed since Start — resume with the new setup accepted, or cancel');+ }+ const nextLimits = limits ? normalizeProductionLimits({ ...run.limits, ...limits }) : run.limits;+ const lowered = nextLimits.maxGenerations < run.limits.maxGenerations+ || nextLimits.maxReviewAttempts < run.limits.maxReviewAttempts+ || (run.limits.spendCapUsd !== null && (nextLimits.spendCapUsd === null ? false : nextLimits.spendCapUsd < run.limits.spendCapUsd));+ if (lowered) throw productionError(422, 'VALIDATION_ERROR', 'Resuming can only raise a limit, never lower it');+ if (run.limits.spendCapUsd === null && nextLimits.spendCapUsd !== null) {+ throw productionError(422, 'VALIDATION_ERROR', 'A dollar cap can only be set at Start');+ }+ return {+ status: 'running',+ limits: nextLimits,+ processId,+ stopReason: null,+ error: null,+ ...(basisChanged ? { basis: { revision: productionBasisRevision(project), capturedAt: now } } : {}),+ };+ }, now);+}++/** Cancel (terminal). The caller cancels the run's queued jobs and review. */+export function cancelProductionOnProject(project, runId, now = new Date().toISOString()) {+ return haltProduction(project, runId, { status: 'canceled', reason: 'Cancelled by the director' }, now);+}++/** Generations still affordable before the limit. */+export const remainingProductionGenerations = (run) => Math.max(0, run.limits.maxGenerations - run.usage.generations);diff --git a/server/services/musicVideo/productionDispatch.js b/server/services/musicVideo/productionDispatch.jsnew file mode 100644index 0000000000..9b3ceb6e6e--- /dev/null+++ b/server/services/musicVideo/productionDispatch.js@@ -0,0 +1,114 @@+/**+ * Music Video production run (#9066) — server-side scene generation.+ *+ * The board's two scene lanes (`generateFrame` / `generateSceneVideo` in+ * client/src/hooks/useMusicVideoSceneMedia.js) rebuilt without a browser: the+ * same composed prompts (handoff.js), the same conditioning references, the+ * same `musicVideo` job tag the completion hooks file takes from, so a+ * production take is indistinguishable from a hand-generated one. The tag+ * additionally names the production run and step (`productionRunId`,+ * `productionStepKey`) so completion and failure events correlate to exactly+ * one step.+ *+ * Every dispatch names its route explicitly — the backend (and model) the+ * run's pool allowed — and is refused rather than resolved to anything else:+ * the image mode is checked against what the render-target resolver actually+ * picked, and the video body always carries an explicit `backend`, so the+ * install's pin ladder can never substitute a different provider.+ *+ * A step carrying a `revisionId` (the review's revision of a failed section)+ * passes the revision's enqueue-time guard first, exactly as the routes do.+ */++import { ServerError } from '../../lib/errorHandler.js';+import { resolveGalleryImage } from '../../lib/pathSafety.js';+import { RENDER_TARGET } from '../../lib/renderTargets.js';+import { approximateMotionCues, grokCoverage } from '../../lib/musicVideoShotTiming.js';+import { sceneFramePrompt, sceneShotPrompt } from './handoff.js';+import { conditioningReferences } from './productionPool.js';++const unprompted = (scene, what) => new ServerError(+ `"${scene.label || scene.sceneId}" has no ${what} prompt to generate from`,+ { status: 422, code: 'PRODUCTION_SCENE_UNPROMPTED', context: { sceneId: scene.sceneId } },+);++async function guardRevision(tag, kind) {+ if (!tag.revisionId) return;+ const { assertRevisionOpen } = await import('./revisionService.js');+ await assertRevisionOpen(tag.projectId, tag.revisionId, { sceneId: tag.sceneId, kind });+}++/** Enqueue a scene's reference frame on exactly `route`. Returns `{ jobId }`. */+async function dispatchFrame({ project, scene, route, tag, settings }) {+ const prompt = sceneFramePrompt(project, scene);+ if (!prompt) throw unprompted(scene, 'frame');+ const referenceImagePaths = conditioningReferences(project)+ .map((ref) => resolveGalleryImage(ref.imageId, { mustExist: false })).filter(Boolean);+ const [{ resolveRenderTargetConfig }, { resolveImageCleaners }, { enqueueJob }] = await Promise.all([+ import('../imageGen/cloudProviderConfig.js'),+ import('../imageGen/index.js'),+ import('../mediaJobQueue/index.js'),+ ]);+ const resolved = resolveRenderTargetConfig(settings, RENDER_TARGET.MUSIC_VIDEO, { mode: route.mode, model: route.model });+ if (resolved.mode !== route.mode) {+ throw new ServerError(`The ${route.mode} image backend is not available; the run will not substitute ${resolved.mode}`, { status: 409, code: 'PRODUCTION_ROUTE_INELIGIBLE' });+ }+ if (resolved.cloud && !resolved.cloud.enabled) throw resolved.cloud.disabledError;+ const { cleanC2PA, denoise } = resolveImageCleaners(undefined, settings, route.mode);+ const common = {+ prompt,+ cleanC2PA,+ denoise,+ ...(referenceImagePaths.length ? { referenceImagePaths, referenceImageStrengths: referenceImagePaths.map(() => 1) } : {}),+ musicVideo: tag,+ };+ const params = resolved.cloud+ ? { ...resolved.cloud.jobParams, ...common }+ : { pythonPath: settings.imageGen?.local?.pythonPath || null, modelId: route.model, ...common };+ await guardRevision(tag, 'image');+ const { jobId } = await enqueueJob({ kind: 'image', params, owner: `music-video-production:${tag.productionRunId}` });+ return { jobId };+}++/** Enqueue a scene's i2v clip on exactly `route` through the video submit service. Returns `{ jobId }`. */+async function dispatchClip({ project, scene, route, tag }) {+ if (!scene.referenceImageId) {+ throw new ServerError(`"${scene.label || scene.sceneId}" has no reference frame yet`, { status: 409, code: 'PRODUCTION_FRAME_MISSING' });+ }+ const base = sceneShotPrompt(project, scene);+ if (!base) throw unprompted(scene, 'shot');+ const spanSec = typeof scene.startSec === 'number' && typeof scene.endSec === 'number' && scene.endSec > scene.startSec+ ? scene.endSec - scene.startSec : null;+ const isGrok = route.mode === 'grok';+ const prompt = [base, isGrok ? approximateMotionCues(project.phrases, scene.startSec, scene.endSec) : ''].filter(Boolean).join('. ');+ const byBackend = {+ local: { modelId: route.model, disableAudio: true },+ grok: { grokDuration: spanSec != null ? grokCoverage(spanSec).requestSec : (project.videoSettings?.grokDuration || 10), disableAudio: true },+ // A performance clip's length follows its song slice (server-side).+ fal: { ...(route.model ? { falModelId: route.model } : {}), ...(scene.shotMode === 'performance' || !project.videoSettings?.falDuration ? {} : { falDuration: project.videoSettings.falDuration }) },+ reactor: { disableAudio: true },+ };+ const { submitVideoGenJob } = await import('../videoGen/submitJob.js');+ // The submit service runs the revision guard itself as its last step before+ // the queue write (submitJob.js), like every board-submitted clip.+ const { jobId } = await submitVideoGenJob({+ prompt,+ backend: route.mode,+ mode: 'image',+ sourceImageFile: scene.referenceImageId,+ ...(byBackend[route.mode] || {}),+ musicVideo: tag,+ }, {});+ return { jobId };+}++/**+ * Dispatch one production step. `tag` is the full `musicVideo` job tag+ * (`projectId`, `sceneId`, `productionRunId`, `productionStepKey`, optional+ * `revisionId`). Returns `{ jobId }`; throws when the submission is refused.+ */+export async function dispatchProductionStep({ stepKind, project, scene, route, tag, settings }) {+ return stepKind === 'frame'+ ? dispatchFrame({ project, scene, route, tag, settings })+ : dispatchClip({ project, scene, route, tag, settings });+}diff --git a/server/services/musicVideo/productionDispatch.test.js b/server/services/musicVideo/productionDispatch.test.jsnew file mode 100644index 0000000000..0e51dfc373--- /dev/null+++ b/server/services/musicVideo/productionDispatch.test.js@@ -0,0 +1,63 @@+/**+ * Music Video production run (#9066) — the browserless scene lanes. Pins the+ * contract the orchestration test doubles out: a step renders on EXACTLY its+ * pool route (a disabled backend refuses instead of resolving to another),+ * carries the step's job tag for correlation, and conditions on the visual+ * spec's references like the board does. The real render-target resolver runs;+ * only the queue and the video submit service are doubled.+ */++import { describe, it, expect, vi, beforeEach } from 'vitest';++const enqueueJob = vi.fn(async () => ({ jobId: 'job-image' }));+const submitVideoGenJob = vi.fn(async () => ({ jobId: 'job-video' }));+vi.mock('../mediaJobQueue/index.js', () => ({ enqueueJob: (...a) => enqueueJob(...a) }));+vi.mock('../videoGen/submitJob.js', () => ({ submitVideoGenJob: (...a) => submitVideoGenJob(...a) }));+vi.mock('../imageGen/index.js', () => ({ resolveImageCleaners: () => ({ cleanC2PA: false, denoise: false }) }));++const { dispatchProductionStep } = await import('./productionDispatch.js');++const project = {+ id: 'mv-example',+ concept: { style: 'noir' },+ visualSpec: { references: [{ imageId: 'ref-example.png', condition: true }, { imageId: 'mood.png', condition: false }] },+ scenes: [],+};+const scene = { sceneId: 'mvs-a', framePrompt: 'a lighthouse', prompt: 'waves roll', startSec: 0, endSec: 4, referenceImageId: 'frame-example.png' };+const tag = { projectId: 'mv-example', sceneId: 'mvs-a', productionRunId: 'mvpr-example', productionStepKey: 'frame:mvs-a:base:1' };+const settings = { imageGen: { mode: 'local', local: { pythonPath: '/opt/example/python' }, codex: { enabled: true, model: 'codex-image' }, grok: { enabled: false } } };++beforeEach(() => vi.clearAllMocks());++describe('production scene dispatch (#9066)', () => {+ it('enqueues a frame on the chosen cloud route with the step tag and the conditioning references', async () => {+ await dispatchProductionStep({ stepKind: 'frame', project, scene, route: { kind: 'image', mode: 'codex', model: null }, tag, settings });+ const { kind, params, owner } = enqueueJob.mock.calls[0][0];+ expect(kind).toBe('image');+ expect(owner).toBe('music-video-production:mvpr-example');+ expect(params).toMatchObject({ mode: 'codex', musicVideo: tag, referenceImageStrengths: [1] });+ expect(params.prompt).toMatch(/^a lighthouse, noir/);+ expect(params.referenceImagePaths).toHaveLength(1);+ expect(params.referenceImagePaths[0]).toMatch(/ref-example\.png$/);+ });++ 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/);+ expect(enqueueJob).not.toHaveBeenCalled();+ });++ it('renders a local frame on the pool\'s exact model', async () => {+ await dispatchProductionStep({ stepKind: 'frame', project, scene, route: { kind: 'image', mode: 'local', model: 'flux2-dev' }, tag, settings });+ expect(enqueueJob.mock.calls[0][0].params).toMatchObject({ modelId: 'flux2-dev', pythonPath: '/opt/example/python' });+ expect(enqueueJob.mock.calls[0][0].params).not.toHaveProperty('mode');+ });++ it('submits a clip with an explicit backend so the install pin ladder cannot substitute one', async () => {+ const clipTag = { ...tag, productionStepKey: 'clip:mvs-a:base:1' };+ await dispatchProductionStep({ stepKind: 'clip', project, scene, route: { kind: 'video', mode: 'grok', model: null }, tag: clipTag, settings });+ expect(submitVideoGenJob).toHaveBeenCalledWith(expect.objectContaining({+ backend: 'grok', mode: 'image', sourceImageFile: 'frame-example.png', grokDuration: 6, musicVideo: clipTag,+ }), {});+ });+});diff --git a/server/services/musicVideo/productionPool.js b/server/services/musicVideo/productionPool.jsnew file mode 100644index 0000000000..089d2fd766--- /dev/null+++ b/server/services/musicVideo/productionPool.js@@ -0,0 +1,186 @@+/**+ * Music Video production run (#9066) — the allowed provider/model pool.+ *+ * A pool route is `{ kind: 'image'|'video', mode, model }`: a render backend+ * from the shared alphabets (lib/generationModes.js) plus, where the backend+ * takes one, a model id. Eligibility is re-derived from LIVE settings and+ * catalogs every time — at Start (every route must be eligible) and again at+ * dispatch for the route a step picked — so a backend disabled, a key removed+ * or a local model uninstalled mid-run refuses that step before enqueue+ * instead of silently falling back to something the director did not allow.+ *+ * Capability is per scene: a frame conditioned on the visual spec's reference+ * images needs a backend (and local model) that consumes reference images, and+ * a performance shot needs a source-audio lip-sync video provider. A route+ * that cannot serve a scene is skipped for that scene with the reason+ * recorded; when no pool route can, the run halts with every reason listed.+ *+ * `metered` routes spend money or remote quota. PortOS has no price catalog+ * for any of them, so their price is unknown (null) and a run with a dollar+ * cap refuses them; local routes cost $0.+ */++import { ServerError } from '../../lib/errorHandler.js';+import { QUEUEABLE_IMAGE_MODES, VIDEO_GEN_MODES } from '../../lib/generationModes.js';+import { MUSIC_VIDEO_AUTOMATION_TOOLS } from '../../lib/musicVideoAutomation.js';+import { isPerformanceScene, performanceBlockedReason } from '../../lib/musicVideoShotTiming.js';+import { maxInputImages, supportsCloudModelOverride } from '../../lib/imageGenCapabilities.js';+import { isHardwareCompatible } from '../../lib/systemCapabilities.js';+import { RUNNER_FAMILIES } from '../../lib/runners.js';+import { poolHasRoute, routeKey } from './production.js';++// The image backends accept at most four reference images for most models;+// mirrors the board's MAX_CONDITIONING_REFERENCES (useMusicVideoSceneMedia.js).+const MAX_CONDITIONING_REFERENCES = 4;++const describe = (route) => `${route.kind} ${route.mode}${route.model ? ` (${route.model})` : ''}`;+const isMetered = (route) => MUSIC_VIDEO_AUTOMATION_TOOLS.some((t) => t.id === `${route.kind}:${route.mode}` && t.metered);++/** The price per generation this install can vouch for: 0 for local, null (unknown) for metered. */+const routePriceUsd = (route) => (isMetered(route) ? null : 0);++/** routeKey → price map for a pool. */+export const poolPricing = (pool) => Object.fromEntries(pool.map((r) => [routeKey(r), routePriceUsd(r)]));++/** The visual-spec references a frame is conditioned on (capped to the backend limit). */+export const conditioningReferences = (project) => (project?.visualSpec?.references || [])+ .filter((ref) => ref?.condition && ref.imageId).slice(0, MAX_CONDITIONING_REFERENCES);++/** What a scene's `kind` generation needs from a route. */+export function sceneRequirement(project, scene, stepKind) {+ return stepKind === 'frame'+ ? { kind: 'image', conditioning: conditioningReferences(project).length }+ : { kind: 'video', performance: isPerformanceScene(scene) };+}++/**+ * The live facts eligibility reads. Loaded lazily (the catalogs are heavy)+ * and injectable for tests.+ */+export async function loadPoolEnv() {+ const [{ getSettings }, { getImageModels }, { resolveVideoModelSelection }] = await Promise.all([+ import('../settings.js'),+ import('../../lib/mediaModels.js'),+ import('../videoGen/modelSelection.js'),+ ]);+ const { isVideoModeUsable } = await import('../videoGen/modes.js');+ return {+ settings: await getSettings(),+ imageModels: getImageModels(),+ resolveVideoModel: (modelId) => resolveVideoModelSelection(modelId),+ isVideoModeUsable,+ };+}++/**+ * Is `route` runnable on this install right now? Returns `{ ok, reason }`.+ * Covers the explicit opt-in toggles (a cloud CLI spends quota only when+ * enabled), configured API keys, installed + hardware-compatible local+ * models, and whether a named cloud model can actually be selected.+ */+async function routeEligibility(route, env) {+ const { settings } = env;+ if (route.kind === 'image') {+ if (!QUEUEABLE_IMAGE_MODES.includes(route.mode)) {+ return { ok: false, reason: `${describe(route)} renders synchronously and cannot run unattended; choose a queued image backend` };+ }+ if (route.mode === 'local') {+ if (!settings?.imageGen?.local?.pythonPath) return { ok: false, reason: 'The local image runtime is not configured in Settings' };+ const model = (env.imageModels || []).find((m) => m.id === route.model);+ if (!route.model || !model) return { ok: false, reason: `Local image model "${route.model || '(none)'}" is not installed` };+ if (!isHardwareCompatible(model.hardwareCompatibility)) return { ok: false, reason: `Local image model "${route.model}" cannot run on this hardware` };+ return { ok: true, reason: null };+ }+ if (settings?.imageGen?.[route.mode]?.enabled !== true) {+ return { ok: false, reason: `${describe(route)} is not enabled in Settings → Image Gen` };+ }+ const configured = settings.imageGen[route.mode].model || null;+ if (route.model && route.model !== configured && !supportsCloudModelOverride(route.mode)) {+ return { ok: false, reason: `${route.mode} image gen cannot select model "${route.model}"; it renders with its configured model only` };+ }+ return { ok: true, reason: null };+ }+ if (!VIDEO_GEN_MODES.includes(route.mode)) return { ok: false, reason: `Unknown video backend "${route.mode}"` };+ if (!env.isVideoModeUsable(settings, route.mode)) {+ return { ok: false, reason: `${describe(route)} is not usable — enable it or configure its API key in Settings` };+ }+ if (route.mode === 'local') {+ if (!settings?.imageGen?.local?.pythonPath) return { ok: false, reason: 'The local video runtime is not configured in Settings' };+ if (!route.model) return { ok: false, reason: 'A local video route must name its model' };+ const { model } = await env.resolveVideoModel(route.model);+ if (!model) return { ok: false, reason: `Local video model "${route.model}" is not installed` };+ if (!isHardwareCompatible(model.hardwareCompatibility)) return { ok: false, reason: `Local video model "${route.model}" cannot run on this hardware` };+ }+ return { ok: true, reason: null };+}++/** Why `route` cannot serve this scene requirement, or null when it can. */+function routeIncapableReason(route, requirement, env) {+ if (route.kind !== requirement.kind) return `${describe(route)} does not generate ${requirement.kind === 'image' ? 'frames' : 'clips'}`;+ if (requirement.kind === 'image' && requirement.conditioning > 0) {+ const limit = route.mode === 'local' ? null : maxInputImages(route.mode);+ if (limit != null && requirement.conditioning > limit) {+ return `${describe(route)} takes at most ${limit} reference image${limit === 1 ? '' : 's'}; the visual spec conditions on ${requirement.conditioning}`;+ }+ if (route.mode === 'local') {+ const model = (env.imageModels || []).find((m) => m.id === route.model);+ if (model?.runner !== RUNNER_FAMILIES.FLUX2 && model?.pipelineClass !== 'QwenImage21Pipeline') {+ return `Local model "${route.model}" cannot use reference images (FLUX.2 and Qwen Image 2.1 only)`;+ }+ }+ }+ if (requirement.kind === 'video' && requirement.performance) {+ return performanceBlockedReason(route.mode);+ }+ return null;+}++/** Start-time check: every route in the pool must be eligible now. Throws 409 with every reason. */+export async function assertPoolEligible(pool, env) {+ const problems = [];+ for (const route of pool) {+ const { ok, reason } = await routeEligibility(route, env);+ if (!ok) problems.push(reason);+ }+ if (problems.length) {+ throw new ServerError(`Some allowed routes cannot run: ${problems.join('; ')}`, { status: 409, code: 'PRODUCTION_ROUTE_INELIGIBLE', context: { problems } });+ }+}++/**+ * Dispatch-time enforcement for ONE chosen route: it must be a literal member+ * of the run's pool, eligible right now, and capable of this scene. Throws+ * 409 before anything is enqueued — there is never a fallback to another route.+ */+export async function assertRouteAllowed(run, route, requirement, env) {+ if (!poolHasRoute(run, route)) {+ throw new ServerError(`${route ? describe(route) : 'That route'} is not in this run's allowed pool`, { status: 409, code: 'PRODUCTION_ROUTE_NOT_ALLOWED' });+ }+ const { ok, reason } = await routeEligibility(route, env);+ if (!ok) throw new ServerError(reason, { status: 409, code: 'PRODUCTION_ROUTE_INELIGIBLE' });+ const incapable = routeIncapableReason(route, requirement, env);+ if (incapable) throw new ServerError(incapable, { status: 409, code: 'PRODUCTION_ROUTE_INCAPABLE' });+}++/**+ * The default chooser: the first route in the director's pool order that is+ * eligible and capable. Returns `{ route, rationale }`, or `{ route: null,+ * reasons }` listing why every candidate was passed over.+ */+export async function chooseProductionRoute(run, requirement, env) {+ const reasons = [];+ const candidates = run.pool.filter((r) => r.kind === requirement.kind);+ if (!candidates.length) return { route: null, reasons: [`The allowed pool has no ${requirement.kind} route`] };+ for (const route of candidates) {+ const { ok, reason } = await routeEligibility(route, env);+ if (!ok) { reasons.push(reason); continue; }+ const incapable = routeIncapableReason(route, requirement, env);+ if (incapable) { reasons.push(incapable); continue; }+ const skipped = reasons.length ? ` (skipped ${reasons.length} earlier route${reasons.length === 1 ? '' : 's'}: ${reasons.join('; ')})` : '';+ const need = requirement.kind === 'image'+ ? (requirement.conditioning ? `frame conditioned on ${requirement.conditioning} reference image${requirement.conditioning === 1 ? '' : 's'}` : 'unconditioned frame')+ : (requirement.performance ? 'lip-synced performance shot' : 'cutaway clip');+ return { route, rationale: `First eligible ${requirement.kind} route in the allowed pool for ${/^[aeiou]/.test(need) ? 'an' : 'a'} ${need}${skipped}` };+ }+ return { route: null, reasons };+}diff --git a/server/services/musicVideo/productionService.js b/server/services/musicVideo/productionService.jsnew file mode 100644index 0000000000..2fe43aad1d--- /dev/null+++ b/server/services/musicVideo/productionService.js@@ -0,0 +1,434 @@+/**+ * Music Video — server-owned production run (#9066): the orchestrator over the+ * pure checkpoint in production.js, the pool rules in productionPool.js and+ * the browserless scene lanes in productionDispatch.js.+ *+ * `advanceProduction` derives the run's next step from the record and the+ * media queue and keeps taking steps until it has to wait — for generation+ * jobs, or for the auto-review run it handed the finished draft to. The+ * browser is never in the loop: frames, clips and the review's revised+ * sections are all dispatched from here, so closing the tab stalls nothing.+ *+ * What moves a run forward:+ * - the director — Start, Resume;+ * - completion events of work THIS run put in flight: a take landing on a+ * scene (`scene-image` / `scene-video`), one of its jobs failing or being+ * cancelled, and its review run handing out revised sections or ending.+ * Nothing at boot advances a run. A run is pinned to the process that started+ * or resumed it (`processId`), so after a restart its checkpoint loads and+ * late completion events still settle their steps, but nothing is dispatched+ * — and no provider is called — until the director resumes. Advances for one+ * run are coalesced in-process, and every dispatch reserves its step in a+ * serialized write first, so an event arriving mid-step cannot dispatch twice.+ */++import { randomUUID } from 'crypto';+import { ServerError } from '../../lib/errorHandler.js';+import { getProject, mutateProjectRecord } from './projects.js';+import { musicVideoEvents } from './events.js';+import {+ attachProductionReview,+ cancelProductionOnProject,+ findProductionRun,+ haltProduction,+ markProductionPlanned,+ normalizeProductionPool,+ nextProductionStep,+ projectProductionRuns,+ reconcileProductionSteps,+ remainingProductionGenerations,+ reserveProductionStep,+ resumeProductionOnProject,+ settleProductionStep,+ startProductionOnProject,+ stepForJob,+ stopProductionOnProject,+} from './production.js';+import {+ assertPoolEligible,+ assertRouteAllowed,+ chooseProductionRoute,+ loadPoolEnv,+ poolPricing,+ sceneRequirement,+} from './productionPool.js';++// One id per server process: a run records the process that may dispatch for it.+const PROCESS_ID = `proc-${randomUUID()}`;+const MAX_STEPS_PER_ADVANCE = 32;+// The review's revision budget is bounded by the auto-review run's own limit.+const AUTO_REVIEW_MAX_GENERATIONS = 100;+// Refusals that mean "this run cannot continue as configured" — never retried.+const LIMIT_CODES = new Set(['PRODUCTION_SPEND_LIMIT', 'PRODUCTION_BUDGET_EXHAUSTED']);++const advancing = new Map();+const short = (id) => String(id || '').slice(5, 13);++// Test seam: the heavy collaborators (live settings/catalogs, the queue, the+// generation lanes) are swappable so orchestration is testable with injected+// queue events. Production code never calls the setter.+const defaults = {+ loadEnv: loadPoolEnv,+ chooseRoute: chooseProductionRoute,+ dispatch: async (args) => (await import('./productionDispatch.js')).dispatchProductionStep(args),+ queue: async () => import('../mediaJobQueue/index.js'),+ planProject: async (...args) => (await import('./planner.js')).planProject(...args),+ autoReview: async () => import('./autoReviewService.js'),+ releaseRevisionSection: async (...args) => (await import('./revisionService.js')).releaseRevisionSection(...args),+};+let deps = { ...defaults };+export function __setProductionDepsForTests(overrides) { deps = { ...defaults, ...overrides }; }+export function __advanceProductionForTests(projectId, runId) { return advanceProduction(projectId, runId); }++async function requireProject(projectId) {+ const project = await getProject(projectId);+ if (!project) throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });+ return project;+}++async function liveJobs() {+ const { listJobs } = await deps.queue();+ return [...listJobs({ kind: 'image' }), ...listJobs({ kind: 'video' })];+}++/** The run as reported to the director: `interrupted` when a restart unpinned it. */+const present = (run) => ({ ...run, interrupted: run.status === 'running' && run.processId !== PROCESS_ID });++function publish(projectId, project, run, action) {+ musicVideoEvents.emit('production', { projectId, runId: run.id, run: present(run), action, project });+}++async function halt(projectId, runId, { status, reason, error = null }) {+ const out = await mutateProjectRecord(projectId, (current) => haltProduction(current, runId, { status, reason, error }));+ const log = status === 'failed' ? console.error : status === 'completed' ? console.log : console.warn;+ log(`${status === 'completed' ? '✅' : status === 'failed' ? '❌' : '⏸️'} Music Video production ${short(runId)} ${status}${reason ? `: ${reason}` : ''}`);+ return out;+}++// ---- dispatching one generation ----------------------------------------------++/**+ * Choose a pool route for one scene slot, enforce it, reserve the step, and+ * enqueue. Returns `{ ok: true }`, or `{ halt: {status, reason} }` when the+ * run cannot continue as configured, or `{ ok: false }` when the slot is+ * simply busy (another advance got there first).+ */+async function dispatchSlot(projectId, runId, { stepKind, sceneId, revisionId = null }) {+ const project = await requireProject(projectId);+ const run = findProductionRun(project, runId);+ const scene = (project.scenes || []).find((s) => s.sceneId === sceneId);+ if (!scene) return { ok: false };+ const requirement = sceneRequirement(project, scene, stepKind);+ const env = await deps.loadEnv();+ const choice = await deps.chooseRoute(run, requirement, env);+ if (!choice?.route) {+ return { halt: { status: 'blocked', reason: `No allowed route can generate the ${stepKind} for "${scene.label || sceneId}": ${(choice?.reasons || []).join('; ')}` } };+ }+ // Enforced for ANY chooser — a model's pick outside the pool never reaches the queue.+ const refused = await assertRouteAllowed(run, choice.route, requirement, env).then(() => null, (err) => err);+ if (refused) return { halt: { status: 'blocked', reason: refused.message } };++ const reserved = await mutateProjectRecord(projectId, (current) => reserveProductionStep(current, runId, {+ kind: stepKind, sceneId, revisionId, route: choice.route, rationale: choice.rationale, processId: PROCESS_ID,+ })).catch((err) => ({ error: err }));+ if (reserved.error) {+ const code = reserved.error.code;+ if (LIMIT_CODES.has(code)) return { halt: { status: 'limit-reached', reason: reserved.error.message } };+ if (code === 'PRODUCTION_STEP_IN_FLIGHT' || code === 'PRODUCTION_NOT_RUNNING' || code === 'PRODUCTION_INTERRUPTED') return { ok: false };+ throw reserved.error;+ }+ const { step } = reserved;+ const tag = { projectId, sceneId, productionRunId: runId, productionStepKey: step.key, ...(revisionId ? { revisionId } : {}) };+ const sent = await deps.dispatch({ stepKind, project, scene, route: choice.route, tag, settings: env.settings })+ .catch((err) => ({ error: err }));+ if (sent.error) {+ await mutateProjectRecord(projectId, (current) => settleProductionStep(current, runId, step.key, { status: 'refused', error: sent.error.message }));+ if (revisionId) await deps.releaseRevisionSection(projectId, revisionId, sceneId).catch(() => {});+ console.warn(`⚠️ Music Video production ${short(runId)} ${stepKind} for ${sceneId} refused: ${sent.error.message}`);+ return { halt: { status: 'blocked', reason: `The ${stepKind} for "${scene.label || sceneId}" was refused: ${sent.error.message}` } };+ }+ const linked = await mutateProjectRecord(projectId, (current) => settleProductionStep(current, runId, step.key, { status: 'queued', jobId: sent.jobId }));+ console.log(`🎬 Music Video production ${short(runId)} ${stepKind} ${sceneId} → ${choice.route.mode}${choice.route.model ? `/${choice.route.model}` : ''} job ${String(sent.jobId).slice(0, 8)}`);+ // Stopped while this submission was in flight: its job must not run.+ if (linked.run.status !== 'running') await cancelOwnedJobs(runId, { includeRunning: false, jobIds: [sent.jobId] });+ return { ok: true };+}++// ---- the step loop --------------------------------------------------------------++async function takeSteps(projectId, runId) {+ for (let i = 0; i < MAX_STEPS_PER_ADVANCE; i += 1) {+ const project = await requireProject(projectId);+ const run = findProductionRun(project, runId);+ const step = nextProductionStep(project, run, { jobs: await liveJobs(), processId: PROCESS_ID });++ if (step.type === 'idle' || step.type === 'wait') return { project, run, action: step };++ if (step.type === 'halt') {+ const out = await halt(projectId, runId, { status: step.status, reason: step.reason });+ return { ...out, action: { type: 'idle' } };+ }++ if (step.type === 'plan') {+ // Marked first: a crash mid-plan must not re-plan (and re-pay) on resume.+ await mutateProjectRecord(projectId, (current) => markProductionPlanned(current, runId));+ const planned = await deps.planProject(projectId, { seedPrompts: true, directive: run.directive }).catch((err) => ({ error: err }));+ if (planned.error) {+ const out = await halt(projectId, runId, { status: 'blocked', reason: `Planning failed: ${planned.error.message}` });+ return { ...out, action: { type: 'idle' } };+ }+ console.log(`🪄 Music Video production ${short(runId)} planned ${planned.scenesAdded} scene(s)`);+ continue;+ }++ if (step.type === 'dispatch') {+ const res = await dispatchSlot(projectId, runId, { stepKind: step.kind, sceneId: step.sceneId });+ if (res.halt) {+ const out = await halt(projectId, runId, res.halt);+ return { ...out, action: { type: 'idle' } };+ }+ if (!res.ok) {+ const fresh = await requireProject(projectId);+ return { project: fresh, run: findProductionRun(fresh, runId), action: { type: 'wait', on: 'generation' } };+ }+ continue;+ }++ if (step.type === 'review') {+ const { startAutoReview } = await deps.autoReview();+ const started = await startAutoReview(projectId, {+ startSec: step.startSec,+ endSec: step.endSec,+ limits: {+ maxAttempts: run.limits.maxReviewAttempts,+ maxGenerations: Math.min(AUTO_REVIEW_MAX_GENERATIONS, remainingProductionGenerations(run)),+ },+ reviewer: run.reviewer,+ productionRunId: runId,+ }).catch((err) => ({ error: err }));+ if (started.error) {+ const out = await halt(projectId, runId, { status: 'blocked', reason: `The draft review could not start: ${started.error.message}` });+ return { ...out, action: { type: 'idle' } };+ }+ await mutateProjectRecord(projectId, (current) => attachProductionReview(current, runId, started.run.id));+ console.log(`🔎 Music Video production ${short(runId)} handed the draft [${step.startSec}, ${step.endSec}]s to review ${short(started.run.id)}`);+ continue;+ }+ throw new Error(`Unknown production step ${step.type}`);+ }+ const project = await requireProject(projectId);+ return { project, run: findProductionRun(project, runId), action: { type: 'wait', on: 'step-budget' } };+}++/**+ * Advance a run as far as it can go right now. Concurrent calls for one run+ * coalesce onto the in-flight advance, which then takes one more pass.+ * Returns `{ project, run, action }`.+ */+function advanceProduction(projectId, runId) {+ const live = advancing.get(runId);+ if (live) {+ live.again = true;+ return live.promise;+ }+ const entry = { again: false, promise: null };+ entry.promise = (async () => {+ try {+ let result;+ do {+ entry.again = false;+ result = await takeSteps(projectId, runId);+ } while (entry.again);+ publish(projectId, result.project, result.run, result.action);+ return result;+ } finally {+ advancing.delete(runId);+ }+ })();+ advancing.set(runId, entry);+ return entry.promise;+}++function advanceInBackground(projectId, runId) {+ armJobListeners();+ return advanceProduction(projectId, runId).catch(async (err) => {+ console.error(`❌ Music Video production ${short(runId)} step failed: ${err.message}`);+ await halt(projectId, runId, { status: 'stopped', reason: `A step failed: ${err.message}`, error: err.message })+ .then((out) => publish(projectId, out.project, out.run, { type: 'idle' }))+ .catch(() => {});+ });+}++/** Cancel this run's queued (and optionally running) jobs. Evidence (records, takes, steps) is kept. */+async function cancelOwnedJobs(runId, { includeRunning = false, jobIds = null } = {}) {+ const { cancelJob } = await deps.queue();+ const owned = (await liveJobs()).filter((job) => job.params?.musicVideo?.productionRunId === runId+ && (job.status === 'queued' || (includeRunning && job.status === 'running'))+ && (!jobIds || jobIds.includes(job.id)));+ for (const job of owned) {+ await cancelJob(job.id).catch((err) => console.error(`❌ Music Video production ${short(runId)} could not cancel job ${job.id.slice(0, 8)}: ${err.message}`));+ }+ if (owned.length) console.log(`🛑 Music Video production ${short(runId)} cancelled ${owned.length} job(s)`);+ return owned.map((j) => j.id);+}++// ---- director actions -----------------------------------------------------------++/**+ * Start a run (explicit director request). Every pool route must be eligible+ * now. Returns `{ project, run }`; the run advances in the background.+ */+export async function startProduction(projectId, { directive, pool: requested, limits, reviewer }) {+ await requireProject(projectId);+ const pool = normalizeProductionPool(requested);+ await assertPoolEligible(pool, await deps.loadEnv());+ const out = await mutateProjectRecord(projectId, (current) => startProductionOnProject(current, {+ directive, pool, limits, reviewer, processId: PROCESS_ID, pricing: poolPricing(pool),+ }));+ console.log(`🎬 Music Video production ${short(out.run.id)} started: ${out.run.pool.length} allowed route(s), ≤${out.run.limits.maxGenerations} generations, ≤${out.run.limits.maxReviewAttempts} reviews`);+ advanceInBackground(projectId, out.run.id);+ return { project: out.project, run: present(out.run) };+}++/**+ * Resume a run: settle its steps against the queue, re-pin it to this process+ * (optionally raising limits / accepting a changed creative setup), resume its+ * paused review, and continue. Returns `{ project, run }`.+ */+export async function resumeProduction(projectId, runId, { limits, acceptBasis = false } = {}) {+ const jobs = await liveJobs();+ await mutateProjectRecord(projectId, (current) => reconcileProductionSteps(current, runId, jobs));+ const out = await mutateProjectRecord(projectId, (current) => resumeProductionOnProject(current, runId, { limits, acceptBasis, processId: PROCESS_ID }));+ const review = out.run.reviewRunId+ ? (out.project.autoReviews || []).find((r) => r.id === out.run.reviewRunId)+ : null;+ if (review && (review.status === 'stopped' || review.status === 'limit-reached')) {+ const { resumeAutoReview } = await deps.autoReview();+ const headroom = Math.min(AUTO_REVIEW_MAX_GENERATIONS, review.usage.generations + remainingProductionGenerations(out.run));+ await resumeAutoReview(projectId, review.id, {+ limits: {+ maxAttempts: Math.max(review.limits.maxAttempts, out.run.limits.maxReviewAttempts),+ maxGenerations: Math.max(review.limits.maxGenerations, headroom),+ },+ }).catch((err) => console.warn(`⚠️ Music Video production ${short(runId)} could not resume its review: ${err.message}`));+ }+ advanceInBackground(projectId, runId);+ const fresh = await requireProject(projectId);+ return { project: fresh, run: present(findProductionRun(fresh, runId)) };+}++/** Stop: nothing new is dispatched and queued owned jobs are cancelled; running ones land. */+export async function stopProduction(projectId, runId) {+ const out = await mutateProjectRecord(projectId, (current) => stopProductionOnProject(current, runId));+ await cancelOwnedJobs(runId);+ const review = out.run.reviewRunId ? (out.project.autoReviews || []).find((r) => r.id === out.run.reviewRunId) : null;+ if (review?.status === 'running') {+ const { stopAutoReview } = await deps.autoReview();+ await stopAutoReview(projectId, review.id).catch(() => {});+ }+ const fresh = await requireProject(projectId);+ const run = findProductionRun(fresh, runId);+ publish(projectId, fresh, run, { type: 'idle' });+ return { project: fresh, run: present(run) };+}++/** Cancel (terminal): every owned job still live is cancelled, and the review with its revision. */+export async function cancelProduction(projectId, runId) {+ const out = await mutateProjectRecord(projectId, (current) => cancelProductionOnProject(current, runId));+ await cancelOwnedJobs(runId, { includeRunning: true });+ const review = out.run.reviewRunId ? (out.project.autoReviews || []).find((r) => r.id === out.run.reviewRunId) : null;+ if (review && ['running', 'stopped', 'limit-reached'].includes(review.status)) {+ const { cancelAutoReview } = await deps.autoReview();+ await cancelAutoReview(projectId, review.id).catch(() => {});+ }+ const fresh = await requireProject(projectId);+ const run = findProductionRun(fresh, runId);+ publish(projectId, fresh, run, { type: 'idle' });+ return { project: fresh, run: present(run) };+}++/** One run as the director sees it (`interrupted` after a restart). */+export async function getProduction(projectId, runId) {+ const project = await requireProject(projectId);+ return { run: present(findProductionRun(project, runId)) };+}++// ---- completion events of work a run put in flight --------------------------------++const runningHere = (run) => run?.status === 'running' && run.processId === PROCESS_ID;++/** A job this run dispatched ended: settle its step (idempotent), then continue. */+async function onProductionJobEnded(job) {+ const tag = job?.params?.musicVideo;+ if (!tag?.projectId || !tag.productionRunId) return;+ const project = await getProject(tag.projectId);+ const run = project ? projectProductionRuns(project).find((r) => r.id === tag.productionRunId) : null;+ if (!run || !stepForJob(run, job)) return;+ const status = job.status === 'completed' ? 'completed' : job.status === 'canceled' ? 'canceled' : 'failed';+ const out = await mutateProjectRecord(tag.projectId, (current) => {+ const r = findProductionRun(current, tag.productionRunId);+ const step = stepForJob(r, job);+ return step ? settleProductionStep(current, r.id, step.key, { status, jobId: job.id, error: status === 'completed' ? null : (job.error || job.status) }) : { project: current, changed: false };+ });+ if (out.changed && status !== 'completed' && runningHere(out.run)) await advanceProduction(tag.projectId, tag.productionRunId);+}++/**+ * The review run a production owns advanced: dispatch the revised sections it+ * handed out (the board never submits those), or continue when it ended.+ */+async function onOwnedReviewAdvanced({ projectId, run: review, action } = {}) {+ if (!projectId || !review?.productionRunId) return;+ const project = await getProject(projectId);+ const run = project ? projectProductionRuns(project).find((r) => r.id === review.productionRunId) : null;+ if (!runningHere(run)) return;+ if (action?.type === 'generate' && review.status === 'running' && action.sections?.length) {+ for (const section of action.sections) {+ const stepKind = section.kind === 'image' ? 'frame' : 'clip';+ const res = await dispatchSlot(projectId, run.id, { stepKind, sceneId: section.sceneId, revisionId: action.revisionId });+ if (res.halt) {+ // The revision's claim is released so a resume hands the section out again.+ await deps.releaseRevisionSection(projectId, action.revisionId, section.sceneId).catch(() => {});+ const out = await halt(projectId, run.id, res.halt);+ publish(projectId, out.project, out.run, { type: 'idle' });+ const { stopAutoReview } = await deps.autoReview();+ await stopAutoReview(projectId, review.id).catch(() => {});+ return;+ }+ }+ return;+ }+ if (review.status !== 'running') await advanceProduction(projectId, run.id);+}++/** A take landed on a scene: a running run waiting on generation continues. */+async function onSceneTake({ projectId } = {}) {+ if (!projectId) return;+ const project = await getProject(projectId);+ const run = project ? projectProductionRuns(project).find(runningHere) : null;+ if (run) await advanceProduction(projectId, run.id);+}++const guarded = (label, fn) => (payload) => {+ Promise.resolve().then(() => fn(payload))+ .catch((err) => console.error(`❌ Music Video production could not continue after ${label}: ${err.message}`));+};++musicVideoEvents.on('scene-image', guarded('a frame landed', onSceneTake));+musicVideoEvents.on('scene-video', guarded('a clip landed', onSceneTake));+musicVideoEvents.on('auto-review', guarded('its review advanced', onOwnedReviewAdvanced));++// The queue listener is armed on a run's first Start/Resume (never at boot);+// the queue module is deferred because only this path needs it.+let jobListenersArmed = false;+function armJobListeners() {+ if (jobListenersArmed) return;+ jobListenersArmed = true;+ deps.queue().then(({ mediaJobEvents }) => {+ const onEnded = guarded('a job ended', onProductionJobEnded);+ for (const event of ['completed', 'failed', 'canceled']) mediaJobEvents.on(event, onEnded);+ }).catch((err) => {+ jobListenersArmed = false;+ console.error(`❌ Music Video production could not watch generation jobs: ${err.message}`);+ });+}diff --git a/server/services/musicVideo/productionService.test.js b/server/services/musicVideo/productionService.test.jsnew file mode 100644index 0000000000..c9046da0cf--- /dev/null+++ b/server/services/musicVideo/productionService.test.js@@ -0,0 +1,358 @@+/**+ * Music Video production run (#9066) — orchestration contract with injected+ * queue events. The project store is an in-memory double with the real+ * store's serialized read-modify-write; the queue, generation lanes and+ * review service are doubles; the checkpoint (production.js) and the pool+ * rules (productionPool.js) are real.+ */++import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';+import { EventEmitter } from 'events';++// ---- in-memory project store with a single write tail ----------------------+const store = new Map();+let writeTail = Promise.resolve();+const clone = (v) => JSON.parse(JSON.stringify(v));+vi.mock('./projects.js', () => ({+ getProject: async (id) => (store.has(id) ? clone(store.get(id)) : null),+ mutateProjectRecord: (id, transform) => {+ const run = writeTail.then(() => {+ if (!store.has(id)) throw Object.assign(new Error('Project not found'), { status: 404 });+ const out = transform(clone(store.get(id)));+ store.set(id, clone(out.project));+ return out;+ });+ writeTail = run.catch(() => {});+ return run;+ },+}));++const { musicVideoEvents } = await import('./events.js');+const service = await import('./productionService.js');++// ---- queue, lanes and review doubles ------------------------------------------+let jobs;+let nextJobId;+const mediaJobEvents = new EventEmitter();+const queue = {+ listJobs: ({ kind } = {}) => jobs.filter((j) => !kind || j.kind === kind),+ cancelJob: vi.fn(async (id) => {+ const job = jobs.find((j) => j.id === id);+ if (job) job.status = 'canceled';+ }),+ mediaJobEvents,+};+const dispatch = vi.fn();+const planProject = vi.fn();+const startAutoReview = vi.fn();+const autoReview = { startAutoReview, resumeAutoReview: vi.fn(), stopAutoReview: vi.fn(async () => {}), cancelAutoReview: vi.fn(async () => {}) };++const env = {+ settings: { imageGen: { local: { pythonPath: '/opt/example/python' }, codex: { enabled: true, model: 'codex-image' }, grok: { enabled: false } } },+ imageModels: [{ id: 'flux2-dev', runner: 'flux2' }, { id: 'sd-basic', runner: 'mflux' }],+ resolveVideoModel: async (id) => ({ model: id === 'ltx-example' ? { id } : null }),+ isVideoModeUsable: (_settings, mode) => mode === 'local',+};++const POOL = [+ { kind: 'image', mode: 'local', model: 'flux2-dev' },+ { kind: 'image', mode: 'codex', model: null },+ { kind: 'video', mode: 'local', model: 'ltx-example' },+];+const LIMITS = { maxGenerations: 10, maxReviewAttempts: 2 };++function seedProject(overrides = {}) {+ const project = {+ id: 'mv-example',+ name: 'Example Video',+ concept: { style: 'noir' },+ audioAnalysis: { sections: [{ startSec: 0, endSec: 8, label: 'Verse' }], durationSec: 8 },+ scenes: [+ { sceneId: 'mvs-a', label: 'A', framePrompt: 'a lighthouse', prompt: 'waves roll', startSec: 0, endSec: 4, takes: [] },+ { sceneId: 'mvs-b', label: 'B', framePrompt: 'a harbor', prompt: 'boats sway', startSec: 4, endSec: 8, takes: [] },+ ],+ ...overrides,+ };+ store.set(project.id, project);+ return project;+}++const current = () => clone(store.get('mv-example'));+const theRun = () => current().productionRuns[0];+const liveSteps = () => theRun().steps.filter((s) => s.status === 'reserved' || s.status === 'queued');++// The queue double: a dispatch lands one queued job tagged with the step.+const enqueueing = ({ stepKind, tag }) => {+ const id = `job-${nextJobId += 1}`;+ jobs.push({ id, kind: stepKind === 'frame' ? 'image' : 'video', status: 'queued', queuedAt: new Date().toISOString(), params: { musicVideo: tag } });+ return Promise.resolve({ jobId: id });+};++/** Complete a job and file its take the way the scene hooks do, then emit the hook event. */+function completeJob(jobId) {+ const job = jobs.find((j) => j.id === jobId);+ job.status = 'completed';+ const project = store.get('mv-example');+ const scene = project.scenes.find((s) => s.sceneId === job.params.musicVideo.sceneId);+ if (job.kind === 'image') scene.referenceImageId = `${jobId}.png`;+ else scene.videoHistoryId = jobId;+ mediaJobEvents.emit('completed', job);+ musicVideoEvents.emit(job.kind === 'image' ? 'scene-image' : 'scene-video', { projectId: 'mv-example', sceneId: scene.sceneId });+}++const settle = async () => {+ // Let fire-and-forget listeners reach their advance, then wait for it.+ for (let i = 0; i < 5; i += 1) await new Promise((r) => setTimeout(r, 0));+ const run = store.get('mv-example')?.productionRuns?.[0];+ if (run) await service.__advanceProductionForTests('mv-example', run.id);+};++async function start(input = {}) {+ const out = await service.startProduction('mv-example', { directive: 'moody, slow', pool: POOL, limits: LIMITS, reviewer: {}, ...input });+ await settle();+ return out;+}++beforeEach(() => {+ store.clear();+ jobs = [];+ nextJobId = 0;+ vi.clearAllMocks();+ dispatch.mockImplementation(enqueueing);+ planProject.mockResolvedValue({ scenesAdded: 0 });+ startAutoReview.mockImplementation(async (projectId, input) => {+ const reviewRun = { id: 'mvar-example', status: 'running', productionRunId: input.productionRunId, limits: input.limits, usage: { reviews: 0, generations: 0 } };+ const project = store.get(projectId);+ project.autoReviews = [...(project.autoReviews || []), reviewRun];+ return { run: reviewRun };+ });+ service.__setProductionDepsForTests({+ loadEnv: async () => env,+ dispatch,+ queue: async () => queue,+ planProject,+ autoReview: async () => autoReview,+ releaseRevisionSection: vi.fn(async () => {}),+ });+});++// A test's background advances finish before the next test resets the doubles.+afterEach(settle);++describe('music video production run (#9066)', () => {+ it('produces a reviewed draft from one Start: frames, then clips, then the continuous-excerpt review', async () => {+ seedProject();+ await start();+ // Both frames go out on the first eligible pool route; clips wait for their frame.+ expect(dispatch.mock.calls.map(([a]) => [a.stepKind, a.scene.sceneId, a.route.mode])).toEqual([+ ['frame', 'mvs-a', 'local'], ['frame', 'mvs-b', 'local'],+ ]);+ expect(dispatch.mock.calls[0][0].tag).toMatchObject({ projectId: 'mv-example', sceneId: 'mvs-a', productionRunId: theRun().id });++ completeJob('job-1');+ completeJob('job-2');+ await settle();+ expect(dispatch.mock.calls.slice(2).map(([a]) => [a.stepKind, a.scene.sceneId, a.route.mode])).toEqual([+ ['clip', 'mvs-a', 'local'], ['clip', 'mvs-b', 'local'],+ ]);++ completeJob('job-3');+ completeJob('job-4');+ await settle();+ expect(startAutoReview).toHaveBeenCalledTimes(1);+ expect(startAutoReview.mock.calls[0][1]).toMatchObject({ startSec: 0, endSec: 8, productionRunId: theRun().id, limits: { maxAttempts: 2, maxGenerations: 6 } });+ expect(theRun()).toMatchObject({ status: 'running', reviewRunId: 'mvar-example', usage: { generations: 4 } });+ expect(theRun().steps.every((s) => s.status === 'completed' && s.rationale)).toBe(true);++ // Only a passed continuous review completes the run — never the frames alone.+ store.get('mv-example').autoReviews[0].status = 'passed';+ musicVideoEvents.emit('auto-review', { projectId: 'mv-example', run: { ...store.get('mv-example').autoReviews[0] }, action: { type: 'idle' } });+ await settle();+ expect(theRun().status).toBe('completed');+ });++ it('plans an empty board once, with the directive, before generating', async () => {+ seedProject({ scenes: [] });+ planProject.mockImplementation(async () => {+ store.get('mv-example').scenes = [{ sceneId: 'mvs-p', framePrompt: 'x', prompt: 'y', startSec: 0, endSec: 4, takes: [] }];+ return { scenesAdded: 1 };+ });+ await start();+ expect(planProject).toHaveBeenCalledWith('mv-example', { seedPrompts: true, directive: 'moody, slow' });+ expect(dispatch).toHaveBeenCalledTimes(1);+ });++ it('refuses a route outside the allowed pool before anything is enqueued', async () => {+ seedProject();+ const chooseRoute = vi.fn(async () => ({ route: { kind: 'image', mode: 'grok', model: null }, rationale: 'model pick' }));+ service.__setProductionDepsForTests({ loadEnv: async () => env, dispatch, queue: async () => queue, planProject, autoReview: async () => autoReview, chooseRoute });+ await start();+ expect(dispatch).not.toHaveBeenCalled();+ expect(theRun()).toMatchObject({ status: 'blocked', usage: { generations: 0 } });+ expect(theRun().stopReason).toMatch(/not in this run's allowed pool/);+ });++ it('lets the chooser pick any eligible member of the pool', async () => {+ seedProject();+ const chooseRoute = vi.fn(async () => ({ route: { kind: 'image', mode: 'codex', model: null }, rationale: 'model pick' }));+ service.__setProductionDepsForTests({ loadEnv: async () => env, dispatch, queue: async () => queue, planProject, autoReview: async () => autoReview, chooseRoute });+ await start();+ expect(dispatch.mock.calls.map(([a]) => a.route.mode)).toEqual(['codex', 'codex']);+ expect(theRun().steps[0].rationale).toBe('model pick');+ });++ it('refuses Start when a pool route lacks entitlement (disabled cloud backend, missing local model)', async () => {+ seedProject();+ await expect(service.startProduction('mv-example', {+ pool: [{ kind: 'image', mode: 'grok' }, { kind: 'video', mode: 'local', model: 'not-installed' }], limits: LIMITS,+ })).rejects.toMatchObject({ code: 'PRODUCTION_ROUTE_INELIGIBLE', message: expect.stringMatching(/grok.*not enabled.*not-installed.*not installed/s) });+ expect(current().productionRuns).toBeUndefined();+ });++ it('skips a route that cannot condition on the visual-spec references', async () => {+ seedProject({ visualSpec: { references: [{ imageId: 'ref.png', condition: true }] } });+ await start({ pool: [{ kind: 'image', mode: 'local', model: 'sd-basic' }, { kind: 'image', mode: 'codex' }, POOL[2]] });+ expect(dispatch.mock.calls.map(([a]) => a.route.mode)).toEqual(['codex', 'codex']);+ expect(theRun().steps[0].rationale).toMatch(/skipped 1 earlier route.*cannot use reference images/);+ });++ it('halts with the capability reason when no pool route can condition on the references', async () => {+ seedProject({ visualSpec: { references: [{ imageId: 'ref.png', condition: true }] } });+ await start({ pool: [{ kind: 'image', mode: 'local', model: 'sd-basic' }, POOL[2]] });+ expect(dispatch).not.toHaveBeenCalled();+ expect(theRun()).toMatchObject({ status: 'blocked', stopReason: expect.stringMatching(/cannot use reference images/) });+ });++ it('refuses a performance shot on a pool with no lip-sync video route, naming why', async () => {+ seedProject();+ store.get('mv-example').scenes[0].shotMode = 'performance';+ await start();+ completeJob('job-1');+ completeJob('job-2');+ await settle();+ expect(theRun()).toMatchObject({ status: 'blocked', stopReason: expect.stringMatching(/cannot lip-sync/) });+ expect(dispatch.mock.calls.some(([a]) => a.stepKind === 'clip' && a.scene.sceneId === 'mvs-a')).toBe(false);+ });++ it('settles a duplicated completion event once and never re-dispatches for it', async () => {+ seedProject();+ await start();+ const job = jobs[0];+ job.status = 'failed';+ job.error = 'out of memory';+ mediaJobEvents.emit('failed', job);+ mediaJobEvents.emit('failed', job);+ await settle();+ const steps = theRun().steps.filter((s) => s.sceneId === 'mvs-a');+ expect(steps.map((s) => s.status)).toEqual(['failed', 'queued']);+ // One retry for the failed slot, not one per duplicate event.+ expect(dispatch.mock.calls.filter(([a]) => a.scene.sceneId === 'mvs-a')).toHaveLength(2);+ });++ it('coalesces concurrent advances so each slot is dispatched once', async () => {+ seedProject();+ let release;+ const gate = new Promise((r) => { release = r; });+ dispatch.mockImplementation(async (args) => { await gate; return enqueueing(args); });+ const started = service.startProduction('mv-example', { pool: POOL, limits: LIMITS });+ const { run } = await started;+ const racing = Promise.all([1, 2, 3].map(() => service.__advanceProductionForTests('mv-example', run.id)));+ release();+ await racing;+ await settle();+ expect(dispatch.mock.calls.map(([a]) => a.scene.sceneId)).toEqual(['mvs-a', 'mvs-b']);+ expect(jobs).toHaveLength(2);+ });++ it('never re-dispatches a slot the queue already has a live job for (lost link after enqueue)', async () => {+ seedProject();+ jobs.push({ id: 'job-orphan', kind: 'image', status: 'running', params: { musicVideo: { projectId: 'mv-example', sceneId: 'mvs-a' } } });+ await start();+ expect(dispatch.mock.calls.map(([a]) => a.scene.sceneId)).toEqual(['mvs-b']);+ });++ it('Stop during a dispatch cancels the job that raced it and dispatches nothing more', async () => {+ seedProject();+ let release;+ const gate = new Promise((r) => { release = r; });+ dispatch.mockImplementationOnce(async (args) => { await gate; return enqueueing(args); });+ const { run } = await service.startProduction('mv-example', { pool: POOL, limits: LIMITS });+ await new Promise((r) => setTimeout(r, 0));+ await service.stopProduction('mv-example', run.id);+ release();+ await settle();+ expect(dispatch).toHaveBeenCalledTimes(1);+ expect(queue.cancelJob).toHaveBeenCalledWith('job-1');+ expect(jobs[0].status).toBe('canceled');+ expect(theRun()).toMatchObject({ status: 'stopped' });+ // Evidence stays: the step and its charge are kept.+ expect(theRun().steps).toHaveLength(1);+ });++ it('stops at the generation limit instead of paying for the next job', async () => {+ seedProject();+ await start({ limits: { maxGenerations: 1, maxReviewAttempts: 1 } });+ expect(dispatch).toHaveBeenCalledTimes(1);+ expect(theRun()).toMatchObject({ status: 'limit-reached', usage: { generations: 1 } });+ });++ it('refuses a dollar cap when a metered route has no known price', async () => {+ seedProject();+ await expect(service.startProduction('mv-example', { pool: POOL, limits: { ...LIMITS, spendCapUsd: 5 } }))+ .rejects.toMatchObject({ code: 'PRODUCTION_COST_UNKNOWN' });+ // A local-only pool prices every route at $0, so the cap is enforceable.+ await service.startProduction('mv-example', { pool: [POOL[0], POOL[2]], limits: { ...LIMITS, spendCapUsd: 5 } });+ await settle();+ expect(theRun().limits.spendCapUsd).toBe(5);+ });++ it('after a restart nothing dispatches until an explicit resume, which neither duplicates live jobs nor re-charges them', async () => {+ seedProject();+ await start();+ expect(dispatch).toHaveBeenCalledTimes(2);+ // Simulate a restart: the checkpoint names another process; a job finished meanwhile.+ store.get('mv-example').productionRuns[0].processId = 'proc-previous';+ completeJob('job-1');+ await settle();+ expect(dispatch).toHaveBeenCalledTimes(2);+ expect(theRun().steps.find((s) => s.jobId === 'job-1').status).toBe('completed');++ const resumed = await service.resumeProduction('mv-example', theRun().id);+ expect(resumed.run.interrupted).toBe(false);+ await settle();+ // job-2 is still queued, so only scene A's clip goes out.+ expect(dispatch.mock.calls.slice(2).map(([a]) => [a.stepKind, a.scene.sceneId])).toEqual([['clip', 'mvs-a']]);+ expect(theRun().usage.generations).toBe(3);+ });++ it('halts when the creative setup changes, and continues only when resume accepts the new basis', async () => {+ seedProject();+ await start();+ store.get('mv-example').concept = { style: 'pastel' };+ completeJob('job-1');+ await settle();+ expect(theRun()).toMatchObject({ status: 'needs-replan' });+ const before = dispatch.mock.calls.length;++ await expect(service.resumeProduction('mv-example', theRun().id)).rejects.toMatchObject({ code: 'PRODUCTION_BASIS_CHANGED' });+ await service.resumeProduction('mv-example', theRun().id, { acceptBasis: true });+ await settle();+ expect(theRun()).toMatchObject({ status: 'running', basis: { capturedAt: expect.any(String) } });+ expect(dispatch.mock.calls.length).toBe(before + 1);+ });++ it('dispatches the review\'s revised sections server-side, tagged with its revision', async () => {+ seedProject();+ await start();+ completeJob('job-1'); completeJob('job-2');+ await settle();+ completeJob('job-3'); completeJob('job-4');+ await settle();+ const reviewRun = store.get('mv-example').autoReviews[0];+ store.get('mv-example').scenes[0].videoHistoryId = null;+ musicVideoEvents.emit('auto-review', { projectId: 'mv-example', run: { ...reviewRun }, action: { type: 'generate', revisionId: 'mvrv-example', sections: [{ sceneId: 'mvs-a', kind: 'video' }] } });+ await settle();+ const last = dispatch.mock.calls.at(-1)[0];+ expect(last).toMatchObject({ stepKind: 'clip', tag: { revisionId: 'mvrv-example', sceneId: 'mvs-a' } });+ });+});diff --git a/server/services/musicVideo/projectsLogic.js b/server/services/musicVideo/projectsLogic.jsindex 9e730addd6..414f6a87be 100644--- a/server/services/musicVideo/projectsLogic.js+++ b/server/services/musicVideo/projectsLogic.js@@ -219,6 +219,8 @@ export function cloneProjectRecord(source, {// A revision is in-progress work against the SOURCE's takes; the clone// starts with none (its carried-over notes can open a fresh one).revisions: [],+ // #9066: a production run executes against the SOURCE's scenes and jobs.+ ...(Array.isArray(source.productionRuns) ? { productionRuns: [] } : {}),renderHistoryId: null,// #9010: the source's in-flight render mark is not the clone's.renderingOn: null,@@ -614,6 +616,8 @@ export function mergeProjectRecord(local, remoteRaw) {remote = { ...remote };if (Object.hasOwn(local, 'imageMode')) remote.imageMode = local.imageMode;if (Object.hasOwn(local, 'imageModelId')) remote.imageModelId = local.imageModelId;+ // #9066: this install's production-run checkpoint survives a newer remote.+ if (Object.hasOwn(local, 'productionRuns')) remote.productionRuns = local.productionRuns;if (local.videoSettings && typeof local.videoSettings === 'object'&& !Array.isArray(local.videoSettings) && Object.hasOwn(local.videoSettings, 'backend')) {const remoteVideoSettings = remote.videoSettings && typeof remote.videoSettings === 'object'diff --git a/server/services/musicVideo/projectsLogic.test.js b/server/services/musicVideo/projectsLogic.test.jsindex 157e6c5caf..7016177e2f 100644--- a/server/services/musicVideo/projectsLogic.test.js+++ b/server/services/musicVideo/projectsLogic.test.js@@ -536,6 +536,20 @@ describe('mergeProjectRecord (#1770 LWW)', () => {expect(next.videoSettings).toEqual({ modelId: 'shared-video-model' });});+ it('keeps the production-run checkpoint install-local: never on the wire, never taken from a peer, kept over a newer remote (#9066)', async () => {+ const { sanitizeRecordForWire } = await import('../../lib/syncWire.js');+ const runs = [{ id: 'mvpr-local', status: 'running', pool: [{ kind: 'image', mode: 'codex', model: null }] }];+ const local = { id: 'mv-1', updatedAt: '2026-01-01T00:00:00Z', name: 'local', productionRuns: runs };+ expect(sanitizeRecordForWire('musicVideoProject', local)).not.toHaveProperty('productionRuns');++ const foreign = [{ id: 'mvpr-foreign', status: 'running' }];+ expect(mergeProjectRecord(null, { id: 'mv-2', updatedAt: '2026-01-02T00:00:00Z', productionRuns: foreign }).next)+ .not.toHaveProperty('productionRuns');+ const { next } = mergeProjectRecord(local, { id: 'mv-1', updatedAt: '2026-01-05T00:00:00Z', name: 'remote edit', productionRuns: foreign });+ expect(next.name).toBe('remote edit');+ expect(next.productionRuns).toEqual(runs);+ });+it('remote with a newer updatedAt wins', () => {const local = { id: 'mv-1', updatedAt: '2026-01-01T00:00:00Z', name: 'old' };const remote = { id: 'mv-1', updatedAt: '2026-01-05T00:00:00Z', name: 'new' };diff --git a/server/services/socket.js b/server/services/socket.jsindex 59b9f9e73f..b43a1ae8c0 100644--- a/server/services/socket.js+++ b/server/services/socket.js@@ -442,6 +442,11 @@ function setupMusicVideoEventForwarding() {musicVideoEvents.on('auto-review', (data) => {if (ioInstance) ioInstance.emit('music-video:auto-review', data);});+ // A server-owned production run advanced (#9066): progress, route choices,+ // spend and Stop/Resume state, without a refetch.+ musicVideoEvents.on('production', (data) => {+ if (ioInstance) ioInstance.emit('music-video:production', data);+ });}let aiStatusForwardingSetup = false;