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
fix: count Cast & Sets images against production run limits (#9238)
Adam Eivyc6d0b780b67b
diff --git a/server/services/musicVideo/castAndSetsService.js b/server/services/musicVideo/castAndSetsService.jsindex e75f90b71b..be8d4cd908 100644--- a/server/services/musicVideo/castAndSetsService.js+++ b/server/services/musicVideo/castAndSetsService.js@@ -67,7 +67,7 @@ import {} from './castAndSetsPlan.js';import { renderCastAndSetsSheet } from './castAndSetsSheet.js';import { findDevArtifact, reviewDevArtifact, resolveDevArtifactNotes } from './devArtifacts.js';-import { rebaseProductionAfterCheckin } from './production.js';+import { findProductionRun, haltProduction, rebaseProductionAfterCheckin, reserveProductionStep, settleProductionStep } from './production.js';const PROCESS_ID = `proc-${randomUUID()}`;const short = (id) => String(id || '').slice(3, 11);@@ -105,7 +105,7 @@ function publish(projectId, project) {}async function fail(projectId, reason, error = null) {- const out = await mutateProjectRecord(projectId, (current) => setCastAndSetsStatus(current, 'failed', { reason, error }));+ const out = await mutateProjectRecord(projectId, (current) => setCastAndSetsStatus(refundUnusedCheckinSteps(current), 'failed', { reason, error }));console.error(`❌ Music Video Cast & Sets ${short(projectId)} failed: ${reason}`);publish(projectId, out.project);return out;@@ -254,28 +254,96 @@ async function enqueueImage(project, stage, key) {...(referenceImagePaths.length ? { referenceImagePaths, referenceImageStrengths: referenceImagePaths.map(() => 1) } : {}),// The completion hook files the result by this tag. No `sceneId`, so the// scene-frame hook ignores the job.- musicVideo: { projectId: project.id, castAndSets: { key, revision: stage.revision } },+ musicVideo: {+ projectId: project.id, castAndSets: { key, revision: stage.revision },+ ...(stage.productionRunId ? {+ productionRunId: stage.productionRunId,+ productionStepKey: checkinStep(project, stage, key)?.key,+ } : {}),+ },};const params = await deps.imageParams(await deps.getSettings(), stage.route, common);return deps.enqueue({ kind: 'image', params, owner: `music-video-cast-sets:${project.id}` });}+// Check-in slots use the existing production ledger; the revision separates+// regenerated images and a terminal attempt permits a charged retry.+function checkinStep(project, stage, key) {+ const run = findProductionRun(project, stage.productionRunId);+ return run.steps.findLast((step) => step.kind === 'checkin'+ && step.sceneId === key && step.revisionId === String(stage.revision));+}++// Images never submitted must not remain charged after the check-in ends.+function refundUnusedCheckinSteps(project) {+ const runId = project.castAndSets?.productionRunId;+ if (!runId) return project;+ let next = project;+ for (const step of findProductionRun(project, runId).steps) {+ if (step.kind === 'checkin' && step.status === 'reserved'+ && project.castAndSets.images?.[step.sceneId]?.status !== 'queued') {+ next = settleProductionStep(next, runId, step.key, {+ status: 'refused', error: 'The check-in stopped before this image was submitted',+ }).project;+ }+ }+ return next;+}++/** Reserve the WHOLE pending plan in one write before any job can be queued. */+async function reserveCheckinPlan(projectId) {+ return mutateProjectRecord(projectId, (current) => {+ const stage = current.castAndSets;+ if (!stage?.productionRunId) return { project: current };+ const run = findProductionRun(current, stage.productionRunId);+ let next = current;+ for (const [key, image] of Object.entries(stage.images)) {+ if (image.status !== 'pending') continue;+ const step = checkinStep(next, stage, key);+ if (step?.status === 'reserved') continue;+ next = reserveProductionStep(next, run.id, {+ kind: 'checkin', sceneId: key, revisionId: String(stage.revision),+ route: { kind: 'image', ...stage.route }, processId: run.processId,+ }).project;+ }+ return { project: next };+ });+}+async function dispatchKey(projectId, key) {- const reserved = await mutateProjectRecord(projectId, (current) => reserveCastAndSetsImage(current, key, { processId: PROCESS_ID }))+ const reserved = await mutateProjectRecord(projectId, (current) => {+ if (current.castAndSets?.productionRunId) {+ const run = findProductionRun(current, current.castAndSets.productionRunId);+ if (run.status !== 'running' || checkinStep(current, current.castAndSets, key)?.status !== 'reserved') {+ throw new ServerError('The production run is not dispatching this image', { status: 409, code: 'CAST_SETS_NOT_RUNNING' });+ }+ }+ return reserveCastAndSetsImage(current, key, { processId: PROCESS_ID });+ }).catch((err) => ({ error: err }));if (reserved.error) {if (['CAST_SETS_IMAGE_BUSY', 'CAST_SETS_NOT_RUNNING'].includes(reserved.error.code)) return;throw reserved.error;}+ const productionStep = reserved.stage.productionRunId ? checkinStep(reserved.project, reserved.stage, key) : null;+ const runId = reserved.stage.productionRunId;const sent = await enqueueImage(reserved.project, reserved.stage, key).catch((err) => ({ error: err }));if (sent?.error || !sent?.jobId) {const reason = sent?.error?.message || 'The image job was not queued';- const out = await mutateProjectRecord(projectId, (current) => settleCastAndSetsImage(current, key, { error: reason }));+ const out = await mutateProjectRecord(projectId, (current) => {+ const next = productionStep ? settleProductionStep(current, runId, productionStep.key, { status: 'refused', error: reason }).project : current;+ const settled = settleCastAndSetsImage(next, key, { error: reason });+ if (settled.stage?.status === 'failed') settled.project = refundUnusedCheckinSteps(settled.project);+ return settled;+ });console.warn(`⚠️ Music Video Cast & Sets ${short(projectId)} ${key} refused: ${reason}`);publish(projectId, out.project);return;}- await mutateProjectRecord(projectId, (current) => linkCastAndSetsJob(current, key, sent.jobId));+ await mutateProjectRecord(projectId, (current) => {+ const next = productionStep ? settleProductionStep(current, runId, productionStep.key, { status: 'queued', jobId: sent.jobId }).project : current;+ return linkCastAndSetsJob(next, key, sent.jobId);+ });console.log(`🎭 Music Video Cast & Sets ${short(projectId)} ${key} → ${reserved.stage.route.mode} job ${String(sent.jobId).slice(0, 8)}`);}@@ -311,6 +379,23 @@ async function advanceOnce(projectId) {await assemble(projectId);return;}+ if (stage.productionRunId) {+ const run = findProductionRun(project, stage.productionRunId);+ if (run.status !== 'running') return;+ const reserved = await reserveCheckinPlan(projectId).catch((error) => ({ error }));+ if (reserved.error) {+ const limit = ['PRODUCTION_SPEND_LIMIT', 'PRODUCTION_BUDGET_EXHAUSTED'].includes(reserved.error.code);+ const out = await mutateProjectRecord(projectId, (current) => {+ const failed = setCastAndSetsStatus(refundUnusedCheckinSteps(current), 'failed', { reason: reserved.error.message });+ return haltProduction(failed.project, stage.productionRunId, {+ status: limit ? 'limit-reached' : 'blocked', reason: reserved.error.message,+ });+ });+ musicVideoEvents.emit('production', { projectId, runId: out.run.id, run: out.run, action: { type: 'idle' }, project: out.project });+ publish(projectId, out.project);+ return;+ }+ }const keys = dispatchableImageKeys(stage);for (const key of keys) await dispatchKey(projectId, key);if (keys.length) publish(projectId, await requireProject(projectId));@@ -427,7 +512,7 @@ export async function skipCastAndSets(projectId) {const base = current.castAndSets ? current : { ...current, castAndSets: { revision: 0, images: {}, plan: {}, createdAt: now } };if (base.castAndSets.status === 'approved') throw new ServerError('The Cast & Sets check-in is already approved', { status: 409, code: 'CAST_SETS_EXISTS' });// A skip also releases work in flight for it: this process stops dispatching.- return settleAndRebase(setCastAndSetsStatus(base, 'skipped', { reason: 'Skipped by the director' }, now), now);+ return settleAndRebase(setCastAndSetsStatus(refundUnusedCheckinSteps(base), 'skipped', { reason: 'Skipped by the director' }, now), now);});console.log(`⏭️ Music Video Cast & Sets ${short(projectId)} skipped`);publish(projectId, out.project);@@ -515,10 +600,18 @@ export async function getCastAndSets(projectId) {* Settles its key (idempotent) and, when the stage is dispatching in this* process, continues. Returns true when the record changed.*/-export async function onCastAndSetsImageSettled({ projectId, key, jobId = null, filename = null, error = null }) {+export async function onCastAndSetsImageSettled({ projectId, key, jobId = null, filename = null, error = null, productionRunId = null, productionStepKey = null, status = null }) {const project = await getProject(projectId);if (!project?.castAndSets?.images?.[key]) return false;- const out = await mutateProjectRecord(projectId, (current) => settleCastAndSetsImage(current, key, { jobId, filename, error }));+ const out = await mutateProjectRecord(projectId, (current) => {+ const next = productionRunId && productionStepKey+ ? settleProductionStep(current, productionRunId, productionStepKey, {+ status: filename ? 'completed' : status === 'canceled' ? 'canceled' : 'failed', jobId, error,+ }).project : current;+ const settled = settleCastAndSetsImage(next, key, { jobId, filename, error });+ if (settled.stage?.status === 'failed') settled.project = refundUnusedCheckinSteps(settled.project);+ return settled;+ });if (!out.changed) return false;publish(projectId, out.project);if (out.stage?.processId === PROCESS_ID && out.stage.status === 'imaging') {diff --git a/server/services/musicVideo/castAndSetsService.test.js b/server/services/musicVideo/castAndSetsService.test.jsindex aee60146af..3ff1b90b48 100644--- a/server/services/musicVideo/castAndSetsService.test.js+++ b/server/services/musicVideo/castAndSetsService.test.js@@ -23,6 +23,7 @@ vi.mock('../settings.js', () => ({ getSettings: vi.fn(async () => ({})) }));const { default: musicVideoRoutes } = await import('../../routes/musicVideo.js');const projects = await import('./projects.js');const service = await import('./castAndSetsService.js');+const production = await import('./production.js');const app = express();app.use(express.json());@@ -88,7 +89,7 @@ async function land(projectId, keys = null) {job.landed = true;const filename = `${job.id}.png`;writeFileSync(join(IMAGES(), filename), PNG);- await service.onCastAndSetsImageSettled({ projectId, key: keyOf(job), jobId: job.id, filename });+ await service.onCastAndSetsImageSettled({ projectId, key: keyOf(job), jobId: job.id, filename, productionRunId: job.params.musicVideo.productionRunId, productionStepKey: job.params.musicVideo.productionStepKey });}}@@ -136,6 +137,87 @@ beforeEach(() => {});afterAll(cleanupTempDataRoots);+async function productionCheckin(limits, price = 0.25) {+ const project = await seed();+ const { run } = await projects.mutateProjectRecord(project.id, (current) => production.startProductionOnProject(current, {+ pool: [{ kind: 'image', mode: 'codex', model: null }],+ processId: 'example-process', limits: { maxReviewAttempts: 2, ...limits }, pricing: { 'image:codex:': price },+ }));+ await service.startCastAndSets(project.id, { productionRunId: run.id });+ return { project, run };+}++describe('Cast & Sets production accounting', () => {+ it.each([+ { maxGenerations: 2 },+ { maxGenerations: 20, spendCapUsd: 0.5 },+ ])('rejects the entire plan before queueing when its limit is insufficient: %j', async (limits) => {+ const { project } = await productionCheckin(limits);+ await until(async () => (await current(project.id)).productionRuns[0].status === 'limit-reached', 'the budget halt');+ const saved = await current(project.id);+ expect(jobs).toHaveLength(0);+ expect(saved.productionRuns[0].usage).toEqual({ generations: 0, spentUsd: 0 });+ expect(saved.productionRuns[0].steps).toHaveLength(0);+ expect(saved.castAndSets.status).toBe('failed');+ });++ it('charges every image once, links its job, and settles completion idempotently', async () => {+ const { project, run } = await productionCheckin({ maxGenerations: 20, spendCapUsd: 5 });+ await runTo(project.id, 'review');+ const saved = await current(project.id);+ const count = Object.keys(saved.castAndSets.plan).length;+ expect(jobs).toHaveLength(count);+ expect(saved.productionRuns[0].usage).toEqual({ generations: count, spentUsd: count * 0.25 });+ expect(saved.productionRuns[0].steps).toHaveLength(count);+ for (const job of jobs) {+ expect(job.params.musicVideo.productionRunId).toBe(run.id);+ expect(saved.productionRuns[0].steps.find((s) => s.key === job.params.musicVideo.productionStepKey))+ .toMatchObject({ status: 'completed', jobId: job.id, kind: 'checkin' });+ }+ const job = jobs[0];+ await service.onCastAndSetsImageSettled({+ projectId: project.id, key: keyOf(job), jobId: job.id, filename: job.id + '.png',+ productionRunId: run.id, productionStepKey: job.params.musicVideo.productionStepKey,+ });+ expect((await current(project.id)).productionRuns[0].usage).toEqual(saved.productionRuns[0].usage);+ });++ it('refunds a refused submission and charges a new attempt when resumed', async () => {+ enqueue.mockRejectedValueOnce(new Error('Example queue refusal'));+ const { project } = await productionCheckin({ maxGenerations: 20 });+ await until(async () => jobs.length === 3, 'the other initial images');+ const before = await current(project.id);+ const count = Object.keys(before.castAndSets.plan).length;+ expect(before.productionRuns[0].usage.generations).toBe(count - 1);+ expect(before.productionRuns[0].steps.find((s) => s.sceneId === 'character')).toMatchObject({ status: 'refused' });+ await land(project.id);+ await runTo(project.id, 'review');+ const after = await current(project.id);+ expect(after.productionRuns[0].usage.generations).toBe(count);+ expect(after.productionRuns[0].steps.filter((s) => s.sceneId === 'character').map((s) => s.status))+ .toEqual(['refused', 'completed']);+ });++ it('charges failed queued jobs and their retry, and refunds images skipped before submission', async () => {+ const { project, run } = await productionCheckin({ maxGenerations: 20 });+ await until(async () => jobs.length === 4, 'the initial images');+ const job = jobs.find((j) => keyOf(j) === 'character');+ job.landed = true;+ await service.onCastAndSetsImageSettled({+ projectId: project.id, key: keyOf(job), jobId: job.id, error: 'Example render failure',+ productionRunId: run.id, productionStepKey: job.params.musicVideo.productionStepKey,+ });+ await until(async () => jobs.length === 5, 'the retry');+ const saved = await current(project.id);+ const count = Object.keys(saved.castAndSets.plan).length;+ expect(saved.productionRuns[0].usage.generations).toBe(count + 1);+ await service.skipCastAndSets(project.id);+ const skipped = await current(project.id);+ expect(skipped.productionRuns[0].usage.generations).toBe(5);+ expect(skipped.productionRuns[0].steps.filter((s) => s.status === 'reserved')).toHaveLength(0);+ });+});+describe('Cast & Sets check-in', () => {it('directs, renders the character sheet first, builds the sheet, waits for review, and applies the approval', async () => {const project = await seed();diff --git a/server/services/musicVideoCastSetsImageHook.js b/server/services/musicVideoCastSetsImageHook.jsindex 3f5f8a613d..be38745503 100644--- a/server/services/musicVideoCastSetsImageHook.js+++ b/server/services/musicVideoCastSetsImageHook.js@@ -29,13 +29,13 @@ const hook = createMediaJobImageHook({serializeKey: ({ projectId }) => projectId,describe: ({ projectId, key }) => `${projectId}/${key}`,attach: ({ projectId, key, filename, job }) => settle({- projectId, key, filename, jobId: typeof job.id === 'string' ? job.id : null,+ projectId, key, filename, productionRunId: job.params?.musicVideo?.productionRunId, productionStepKey: job.params?.musicVideo?.productionStepKey, jobId: typeof job.id === 'string' ? job.id : null,}).then((changed) => (changed ? { filename } : null)),onAttached: ({ projectId, key, filename }) => {console.log(`🎭 music-video cast & sets ${projectId.slice(0, 11)}/${key} ← ${filename}`);},onTerminal: ({ projectId, key, job }, status) => settle({- projectId, key, jobId: typeof job?.id === 'string' ? job.id : null, error: job?.error || `The render was ${status}`,+ projectId, key, status, productionRunId: job?.params?.musicVideo?.productionRunId, productionStepKey: job?.params?.musicVideo?.productionStepKey, jobId: typeof job?.id === 'string' ? job.id : null, error: job?.error || `The render was ${status}`,}),});