Skip to content

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

fix: let a parked music-video production run swap its video model and continue (#10473)

[._.]/ Adam Eivy3ab772db3dab
diff --git a/server/lib/musicVideoValidation.js b/server/lib/musicVideoValidation.js
index b9bc4e5bf6..d42d7779fb 100644
--- a/server/lib/musicVideoValidation.js
+++ b/server/lib/musicVideoValidation.js
@@ -874,10 +874,12 @@ export const musicVideoProductionStartSchema = z.object({
model: z.string().min(1).max(200).nullable().optional(),
}).strict();
-// Resume may RAISE a limit; `acceptBasis` continues against a changed creative setup.
+// Resume may RAISE a limit; `acceptBasis` continues against a changed creative setup;
+// `pool` replaces the allowed routes (e.g. swaps a refused video model), validated like Start.
export const musicVideoProductionResumeSchema = z.object({
limits: musicVideoProductionLimitsSchema.partial().optional(),
acceptBasis: z.boolean().optional(),
+ pool: z.array(musicVideoProductionRouteSchema).max(12).optional(),
}).strict();
// ---- Fully-autonomous run: one prompt → lyrics → Suno song → video --------------
diff --git a/server/services/musicVideo/autonomousService.js b/server/services/musicVideo/autonomousService.js
index 93a03d8a7e..7774a2ad91 100644
--- a/server/services/musicVideo/autonomousService.js
+++ b/server/services/musicVideo/autonomousService.js
@@ -60,6 +60,7 @@ import { probeVideoDuration } from '../../lib/ffmpeg.js';
import { ServerError } from '../../lib/errorHandler.js';
import { trimTo } from '../../lib/textUtils.js';
import { assertFootageVideoModelsCapable, loadPoolEnv } from './productionPool.js';
+import { PRODUCTION_RESUMABLE_STATUSES } from './production.js';
import {
AUTONOMOUS_DEFAULT_LIMITS,
AUTONOMOUS_LIVE_STATUSES,
@@ -1013,7 +1014,7 @@ const STAGES = {
}
const started = await deps.startProduction(project.id, {
directive: trimTo([run.brief.prompt, run.brief.guidance].filter(Boolean).join('\n\n'), 4000),
- pool: autonomousPool(run.brief.tools, run.brief.models).filter((route) => musicVideoAllowsMedia(project, route.kind)),
+ pool: briefProductionPool(run.brief, project),
limits: { ...run.brief.limits, ...(run.brief.budgetUsd != null ? { spendCapUsd: run.brief.budgetUsd } : {}) },
// The orchestrator also judges production's plates and drafts when the run has one.
reviewer: isOrchestratedRun(run)
@@ -1133,14 +1134,21 @@ const emptyStages = () => Object.fromEntries(AUTONOMOUS_STAGE_IDS.map((id) => [i
* Start a run from one prompt: creates the project (autonomous mode, no track
* yet) and begins the pipeline in the background. Returns `{ project, run }`.
*/
+/** The production pool a brief allows on this project. */
+const briefProductionPool = (brief, project) => autonomousPool(brief.tools, brief.models)
+ .filter((route) => musicVideoAllowsMedia(project, route.kind));
+
+/** Refuse a pinned video model that cannot animate a frame (#10457) before the run records it. */
+async function assertBriefVideoModelsCapable(tools, models) {
+ const pool = autonomousPool(tools, models);
+ if (pool.some((route) => route.kind === 'video' && route.model)) await assertFootageVideoModelsCapable(pool, await loadPoolEnv());
+}
+
export async function startAutonomousVideo(input, { autoApproveAuthorized = false } = {}) {
const brief = { ...normalizeAutonomousBrief(input), ...autoApproveGrant(input?.autoApprove, autoApproveAuthorized) };
if (!brief.prompt) throw runError(400, 'VALIDATION_ERROR', 'A prompt is required');
if (brief.orchestrator) Object.assign(brief, orchestratorGrant(autoApproveAuthorized));
- const footagePool = autonomousPool(brief.tools, brief.models);
- if (footagePool.some((route) => route.kind === 'video' && route.model)) {
- await assertFootageVideoModelsCapable(footagePool, await loadPoolEnv());
- }
+ await assertBriefVideoModelsCapable(brief.tools, brief.models);
const now = new Date().toISOString();
const created = await deps.createProject({
name: brief.name || trimTo(brief.prompt.replace(/\s+/g, ' '), 60) || 'Autonomous music video',
@@ -1216,9 +1224,10 @@ const SONG_OUTPUT_KEYS = ['trackId', 'sunoSongIds', 'songSource', 'songFallbackR
export async function resumeAutonomousVideo(projectId, edits = {}, { autoApproveAuthorized = false } = {}) {
const { run } = await requireRun(projectId);
- // A model swap only takes effect in a new production run (its pool is fixed at start).
+ // A model swap is validated like Start, then replaces the parked production run's pool (#10473).
const modelsPatch = briefModelsPatch(run.brief, edits.models);
assertResumable(run);
+ if (modelsPatch) await assertBriefVideoModelsCapable(run.brief.tools, modelsPatch);
// "Auto-approve the rest": replaces the brief's grant (an empty list clears it).
const grant = edits.autoApprove !== undefined ? autoApproveGrant(edits.autoApprove, autoApproveAuthorized) : null;
const retake = edits.retakeSong === true;
@@ -1296,7 +1305,7 @@ export async function resumeAutonomousVideo(projectId, edits = {}, { autoApprove
return { project: presentProjectAutonomousRun(latest), run: presentAutonomousRun(projectAutonomousRun(latest)) };
}
if (out.run.stage === 'produce' && out.run.output.productionRunId) {
- return resumeDelegatedProduction(projectId, out.run, { restart: modelsChanged, limits: edits.limits });
+ return resumeDelegatedProduction(projectId, out.run, { swapModels: modelsChanged, limits: edits.limits });
}
advanceInBackground(projectId);
return { project: out.project, run: presentAutonomousRun(out.run) };
@@ -1324,22 +1333,23 @@ const PRODUCTION_LIVE = new Set(['running', 'limit-reached', 'blocked', 'needs-r
/**
* Hand a resumed run back to production. It follows the newest production run started
* since the run began (the director may have replaced its own by hand) and resumes it
- * with any raised limits, or finishes straight to the final render when that run is
- * already complete. A model swap, or no production run left to follow, starts a new
- * one from the brief by re-entering `produce`.
+ * with any raised limits and swapped models, or finishes straight to the final render
+ * when that run is already complete. No production run left to follow — or a model
+ * swap on one that cannot resume — starts a new one from the brief by re-entering `produce`.
*/
-async function resumeDelegatedProduction(projectId, run, { restart = false, limits } = {}) {
+async function resumeDelegatedProduction(projectId, run, { swapModels = false, limits } = {}) {
const project = await getProject(projectId);
const runs = Array.isArray(project.productionRuns) ? project.productionRuns : [];
const current = runs.find((r) => r.id === run.output.productionRunId) || null;
- const adopt = restart ? null : runs
+ const newest = runs
.filter((r) => ADOPTABLE_PRODUCTION.has(r.status) && String(r.createdAt || '') >= String(run.createdAt || ''))
.sort((a, b) => String(b.createdAt || '').localeCompare(String(a.createdAt || '')))[0] || null;
+ const adopt = swapModels && newest && !PRODUCTION_RESUMABLE_STATUSES.has(newest.status) ? null : newest;
if (!adopt) {
// Unlink first: the old run's own "canceled" event must no longer match this run.
const out = await patchRun(projectId, (r) => ({ output: { productionRunId: null }, ...stagePatch(r, 'produce', { status: 'pending', error: null, step: null }) }));
if (current && PRODUCTION_LIVE.has(current.status)) await deps.cancelProduction(projectId, current.id).catch(() => {});
- console.log(`🎬 Autonomous music video ${short(run.id)} starting a new production run${restart ? ' with the new models' : ''}`);
+ console.log(`🎬 Autonomous music video ${short(run.id)} starting a new production run${swapModels ? ' with the new models' : ''}`);
advanceInBackground(projectId);
return { project: out.project, run: presentAutonomousRun(out.run) };
}
@@ -1353,7 +1363,11 @@ async function resumeDelegatedProduction(projectId, run, { restart = false, limi
} else {
// Resuming a "running" run is safe and re-pins one left by a previous server process.
const productionLimits = limits ? Object.fromEntries(Object.entries(limits).filter(([, v]) => v != null)) : undefined;
- const failure = await deps.resumeProduction(projectId, adopt.id, { acceptBasis: true, ...(productionLimits ? { limits: productionLimits } : {}) })
+ const failure = await deps.resumeProduction(projectId, adopt.id, {
+ acceptBasis: true,
+ ...(productionLimits ? { limits: productionLimits } : {}),
+ ...(swapModels ? { pool: briefProductionPool(run.brief, project) } : {}),
+ })
.then(() => null, (err) => err);
if (failure) {
const parked = await park(projectId, 'needs-human', { error: trimTo(`Production could not resume: ${failure.message}`, 500), errorCode: failure.code || null });
diff --git a/server/services/musicVideo/autonomousService.test.js b/server/services/musicVideo/autonomousService.test.js
index dfad1c4464..64b0e87c22 100644
--- a/server/services/musicVideo/autonomousService.test.js
+++ b/server/services/musicVideo/autonomousService.test.js
@@ -11,6 +11,13 @@ vi.mock('./productionReview.js', async (load) => {
},
};
});
+// Footage needs image-to-video: one fake model is text-only, every other id is not installed.
+vi.mock('./productionPool.js', async (load) => ({
+ ...(await load()),
+ loadPoolEnv: async () => ({
+ resolveVideoModel: async (id) => ({ modelId: id, model: id === 'example-text-only' ? { id, name: 'Example Text Model', supportedModes: ['text'] } : null }),
+ }),
+}));
vi.mock('./productionReviewService.js', () => ({
prepareProductionReview: vi.fn(async () => {}),
renderProductionProof: vi.fn(async () => ({ jobId: 'proof-example' })),
@@ -308,7 +315,7 @@ describe('startAutonomousVideo', () => {
expect(runOf()).toMatchObject({ status: 'running', output: expect.objectContaining({ productionRunId: 'mvpr-manual', productionDone: true, renderJobId: 'render-1' }) });
});
- it('resumes a parked run with raised limits, and a model swap starts a new production run with the new pool', async () => {
+ it('resumes a parked run with raised limits, and a model swap continues that run with the new pool', async () => {
await delegated();
store.get('mv-auto').productionRuns[0].status = 'limit-reached';
await service.__testing.onProductionEvent({ projectId: 'mv-auto', runId: 'mvpr-1', run: { status: 'limit-reached', stopReason: 'generation limit' } });
@@ -320,6 +327,26 @@ describe('startAutonomousVideo', () => {
store.get('mv-auto').productionRuns[0].status = 'blocked';
await service.__testing.onProductionEvent({ projectId: 'mv-auto', runId: 'mvpr-1', run: { status: 'blocked', stopReason: 'no image-to-video' } });
+ // A text-only replacement is refused like Start, before the brief or production changes.
+ await expect(service.resumeAutonomousVideo('mv-auto', { models: { 'video:local': 'example-text-only' } }))
+ .rejects.toMatchObject({ status: 400, code: 'VIDEO_MODEL_TEXT_ONLY', message: expect.stringMatching(/Example Text Model.*image-to-video/) });
+ expect(runOf().brief.models).toEqual({ 'video:local': 'text-only' });
+ expect(doubles.resumeProduction).toHaveBeenCalledTimes(1);
+
+ await service.resumeAutonomousVideo('mv-auto', { models: { 'video:local': 'image-capable' } });
+ expect(doubles.resumeProduction).toHaveBeenLastCalledWith('mv-auto', 'mvpr-1', {
+ acceptBasis: true, pool: [{ kind: 'image', mode: 'local' }, { kind: 'video', mode: 'local', model: 'image-capable' }],
+ });
+ expect(doubles.cancelProduction).not.toHaveBeenCalled();
+ expect(doubles.startProduction).toHaveBeenCalledOnce();
+ expect(runOf()).toMatchObject({ status: 'running', brief: expect.objectContaining({ models: { 'video:local': 'image-capable' } }), output: expect.objectContaining({ productionRunId: 'mvpr-1' }) });
+ await expect(service.resumeAutonomousVideo('mv-auto', { models: { 'image:fal': 'x' } })).rejects.toMatchObject({ code: 'VALIDATION_ERROR' });
+ });
+
+ it('starts a new production run with the swapped models when the old one cannot resume', async () => {
+ await delegated();
+ store.get('mv-auto').productionRuns[0].status = 'needs-human';
+ await service.__testing.onProductionEvent({ projectId: 'mv-auto', runId: 'mvpr-1', run: { status: 'needs-human', stopReason: 'review ended' } });
doubles.startProduction.mockResolvedValueOnce({ run: { id: 'mvpr-2' } });
// Like the real service, canceling the old run publishes its own "canceled" event.
doubles.cancelProduction.mockImplementationOnce(async (projectId, runId) => {
@@ -330,8 +357,6 @@ describe('startAutonomousVideo', () => {
expect(doubles.cancelProduction).toHaveBeenCalledWith('mv-auto', 'mvpr-1');
await vi.waitFor(() => expect(runOf().output.productionRunId).toBe('mvpr-2'));
expect(doubles.startProduction.mock.calls[1][1].pool).toEqual([{ kind: 'image', mode: 'local' }, { kind: 'video', mode: 'local', model: 'image-capable' }]);
- await expect(service.resumeAutonomousVideo('mv-auto', { models: { 'image:fal': 'x' } })).rejects.toMatchObject({ code: 'VALIDATION_ERROR' });
- expect(runOf()).toMatchObject({ status: 'running', output: expect.objectContaining({ productionRunId: 'mvpr-2' }) });
});
it('re-pins a production run left running by a previous server process', async () => {
diff --git a/server/services/musicVideo/production.js b/server/services/musicVideo/production.js
index 9ea10ece41..9c7a5b1e9a 100644
--- a/server/services/musicVideo/production.js
+++ b/server/services/musicVideo/production.js
@@ -62,6 +62,8 @@ 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']);
+/** Statuses Resume accepts. */
+export const PRODUCTION_RESUMABLE_STATUSES = RESUMABLE;
const LIVE_STEP = new Set(['reserved', 'queued']);
const LIVE_JOB = new Set(['queued', 'running']);
// A reserved step whose job never showed up in the queue after this long did
@@ -182,6 +184,16 @@ export function normalizeProductionPool(pool, { allowEmpty = false } = {}) {
return out;
}
+/** The pool's per-route prices (null when unknown); a dollar cap needs every route priced. */
+function boundPoolPricing(pool, pricing, spendCapUsd) {
+ const unpriced = spendCapUsd === null ? [] : pool.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.`);
+ }
+ return Object.fromEntries(pool.map((r) => [routeKey(r), typeof pricing[routeKey(r)] === 'number' ? pricing[routeKey(r)] : null]));
+}
+
/** Is `route` literally a member of the run's allowlist? */
export const poolHasRoute = (run, route) => !!route && run.pool.some((r) => routeKey(r) === routeKey(route));
@@ -217,18 +229,13 @@ export function startProductionOnProject(project, {
const normalizedLimits = normalizeProductionLimits(limits);
if (normalizedLimits.spendCapUsd !== null) {
if (codeFirst && authoring.costUsd == null) throw productionError(409, 'PRODUCTION_COST_UNKNOWN', 'Code-authoring has no bounded dollar price. Choose a free/local authoring provider or remove the dollar cap; every authoring call still consumes the generation limit.');
- 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])),
+ pricing: boundPoolPricing(normalizedPool, pricing, normalizedLimits.spendCapUsd),
limits: normalizedLimits,
...(codeFirst ? { authoring: { ...authoring }, documentCheckpoint: null, finalRender: null } : {}),
reviewer: {
@@ -339,10 +346,12 @@ const productionRetryBasis = (project, sceneId, kind) => {
});
};
+// With no route given, only a refusal by a route still in the pool counts: a
+// resume that swapped that route out (#10473) lets the slot go to the new one.
const terminalRefusal = (project, run, sceneId, kind, route = null) =>
run.steps.find((step) => step.sceneId === sceneId && step.kind === kind && step.retryBlocked
&& step.retryBasis === productionRetryBasis(project, sceneId, kind)
- && (!route || routeKey(step.route) === routeKey(route)));
+ && (route ? routeKey(step.route) === routeKey(route) : poolHasRoute(run, step.route)));
/** All code-first work stays tied to the process and approved plan that reserved it. */
export function assertProductionActive(project, runId, processId) {
@@ -468,7 +477,7 @@ export function nextProductionStep(project, run, { jobs = [], processId = null }
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 refused = terminalRefusal(project, run, scene.sceneId, stepKind);
- if (refused) return { type: 'halt', status: 'blocked', reason: `"${scene.label || scene.sceneId}" has a terminal ${stepKind} refusal (${refused.errorCode}). Change its inputs or start a new run with another supported route; Resume will not repeat it.` };
+ if (refused) return { type: 'halt', status: 'blocked', reason: `"${scene.label || scene.sceneId}" has a terminal ${stepKind} refusal (${refused.errorCode}). Change its inputs or resume with another supported route; Resume will not repeat it.` };
// A paid failure is not evidence that the same operation will work next
// time. Pause before another charge; explicit Resume permits a transient retry.
const failed = steps.find((s) => s.status === 'failed' && !(run.retryAcknowledged || []).includes(s.key));
@@ -752,7 +761,7 @@ export function stopProductionOnProject(project, runId, now = new Date().toISOSt
* 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()) {
+export function resumeProductionOnProject(project, runId, { limits, acceptBasis = false, processId, pool = null, pricing = {} } = {}, 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`);
if (normalizeMusicVideoProductionPolicy(project?.productionPolicy).strategy === 'code-first' && !run.authoring) throw productionError(409, 'PRODUCTION_AUTHORING_REQUIRED', 'Cancel this legacy run and start a code-first run with an authoring model');
@@ -770,9 +779,13 @@ export function resumeProductionOnProject(project, runId, { limits, acceptBasis
if (run.limits.spendCapUsd === null && nextLimits.spendCapUsd !== null) {
throw productionError(422, 'VALIDATION_ERROR', 'A dollar cap can only be set at Start');
}
+ // A replacement pool (a swapped model, #10473) is checked like Start; the
+ // caller has already proven every route eligible on this install.
+ const nextPool = pool ? normalizeProductionPool(pool, { allowEmpty: !!run.authoring }) : null;
return {
status: 'running',
limits: nextLimits,
+ ...(nextPool ? { pool: nextPool, pricing: boundPoolPricing(nextPool, pricing, nextLimits.spendCapUsd) } : {}),
processId,
resumedAt: now,
retryAcknowledged: run.steps.filter((step) => step.status === 'failed').map((step) => step.key),
diff --git a/server/services/musicVideo/productionService.js b/server/services/musicVideo/productionService.js
index 33d18d9fba..04e05a67d7 100644
--- a/server/services/musicVideo/productionService.js
+++ b/server/services/musicVideo/productionService.js
@@ -642,15 +642,23 @@ export async function startProduction(projectId, { directive, pool: requested, l
/**
* 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 }`.
+ * (optionally raising limits / accepting a changed creative setup / replacing
+ * its pool, e.g. a refused video model, #10473), resume its paused review, and
+ * continue. A replacement pool is validated exactly like Start's.
+ * Returns `{ project, run }`.
*/
-export async function resumeProduction(projectId, runId, { limits, acceptBasis = false } = {}) {
+export async function resumeProduction(projectId, runId, { limits, acceptBasis = false, pool: requested } = {}) {
const before = await requireProject(projectId);
- const priorReviewId = findProductionRun(before, runId).reviewRunId;
+ const prior = findProductionRun(before, runId);
+ const priorReviewId = prior.reviewRunId;
+ const pool = requested ? normalizeProductionPool(requested, { allowEmpty: !!prior.authoring }) : null;
+ if (pool) await assertPoolEligible(pool, await deps.loadEnv());
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 out = await mutateProjectRecord(projectId, (current) => resumeProductionOnProject(current, runId, {
+ limits, acceptBasis, processId: PROCESS_ID, ...(pool ? { pool, pricing: poolPricing(pool, current) } : {}),
+ }));
+ if (pool) console.log(`🎬 Music Video production ${short(runId)} resumed with a replaced pool: ${pool.length} allowed route(s)`);
if (priorReviewId && !out.run.reviewRunId) {
const oldReview = before.autoReviews?.find((entry) => entry.id === priorReviewId);
if (oldReview && ['running', 'stopped', 'limit-reached'].includes(oldReview.status)) await (await deps.autoReview()).cancelAutoReview(projectId, priorReviewId);
diff --git a/server/services/musicVideo/productionService.test.js b/server/services/musicVideo/productionService.test.js
index 59655a05ce..1cab9711e4 100644
--- a/server/services/musicVideo/productionService.test.js
+++ b/server/services/musicVideo/productionService.test.js
@@ -77,7 +77,9 @@ const autoReview = { startAutoReview, resumeAutoReview: vi.fn(), stopAutoReview:
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 }),
+ resolveVideoModel: async (id) => ({ model: {
+ 'ltx-example': { id }, 'ltx-alt': { id }, 'example-text': { id, name: 'Example Text Model', supportedModes: ['text'] },
+ }[id] || null }),
isVideoModeUsable: (_settings, mode) => mode === 'local',
};
@@ -425,6 +427,29 @@ describe('music video production run (#9066)', () => {
expect(theRun().usage.generations).toBe(2);
});
+ it('continues a run blocked on its video model once Resume swaps that model, refusing a text-only one like Start', async () => {
+ seedProject();
+ await start();
+ completeJob('job-1');
+ completeJob('job-2');
+ dispatch.mockRejectedValueOnce(Object.assign(new Error('Model does not support image-to-video'), { status: 422, code: 'VIDEO_MODE_UNSUPPORTED' }));
+ await settle();
+ expect(theRun()).toMatchObject({ status: 'blocked', stopReason: expect.stringMatching(/refused/) });
+ const clips = () => dispatch.mock.calls.filter(([a]) => a.stepKind === 'clip').map(([a]) => a.route.model);
+ expect(clips()).toEqual(['ltx-example']);
+
+ const swapTo = (model) => POOL.map((route) => (route.kind === 'video' ? { ...route, model } : route));
+ await expect(service.resumeProduction('mv-example', theRun().id, { pool: swapTo('example-text') }))
+ .rejects.toMatchObject({ code: 'PRODUCTION_ROUTE_INELIGIBLE', message: expect.stringMatching(/Example Text Model.*image-to-video/) });
+ expect(theRun()).toMatchObject({ status: 'blocked', pool: POOL });
+
+ await service.resumeProduction('mv-example', theRun().id, { pool: swapTo('ltx-alt') });
+ await settle();
+ expect(theRun()).toMatchObject({ status: 'running', pool: swapTo('ltx-alt') });
+ expect(theRun().pricing).toHaveProperty(['video:local:ltx-alt']);
+ expect(clips()).toEqual(['ltx-example', 'ltx-alt', 'ltx-alt']);
+ });
+
it('allows explicit Resume after a transient submission failure without spending on the refusal', async () => {
seedProject();
dispatch.mockRejectedValueOnce(Object.assign(new Error('Provider temporarily unavailable'), { status: 503 }));