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: tag music-video generation jobs with the revision id (#9011)
[._.]/ Adam Eivy8128ff661516
diff --git a/client/src/hooks/useMusicVideoRevisions.js b/client/src/hooks/useMusicVideoRevisions.jsindex 9aceef8119..3255b2ebc7 100644--- a/client/src/hooks/useMusicVideoRevisions.js+++ b/client/src/hooks/useMusicVideoRevisions.js@@ -4,6 +4,7 @@ import {startMusicVideoRevision,resumeMusicVideoRevision,cancelMusicVideoRevision,+ releaseMusicVideoRevisionSection,} from '../services/apiMusicVideo.js';const plural = (n, word) => `${n} ${word}${n === 1 ? '' : 's'}`;@@ -25,6 +26,15 @@ const plural = (n, word) => `${n} ${word}${n === 1 ? '' : 's'}`;** `revise(excerptId, sceneIds?)` opens a revision and immediately resumes it.*+ * Each submission rides tagged with the revision's id (#9011), so the server+ * can cancel or refuse exactly this revision's own generation and never a+ * board render started by hand for the same scene. `resume` awaits every+ * kickoff's confirmed-submission promise (`generateFrame`/`generateSceneVideo`+ * now return one) before counting it as "generating" — a request that never+ * reached the queue also releases its claim (`release`) so the very next+ * resume can hand that section out again immediately instead of waiting out+ * the server's claim lease.+ ** `replaceProject(project)` swaps the local record whole; `sceneMedia` is the* `useMusicVideoSceneMedia` result; `attachRender(jobId, projectId)` is* `useMusicVideoExcerpts().attachRender`.@@ -40,33 +50,38 @@ export default function useMusicVideoRevisions({ project, replaceProject, sceneM.finally(() => setBusy(false));};- const generateSections = (next, refs) => {+ const generateSections = async (next, refs, revisionId) => {const scenes = new Map((next.scenes || []).map((s) => [s.sceneId, s]));- let submitted = 0;+ const kicks = [];for (const { sceneId, kind } of refs) {const scene = scenes.get(sceneId);if (!scene) continue;if (kind === 'image') {if (sceneMedia?.genScenes?.[sceneId]) continue;- sceneMedia?.generateFrame(scene);+ kicks.push(sceneMedia.generateFrame(scene, { revisionId }).then((r) => ({ sceneId, ok: r?.ok !== false })));} else {if (sceneMedia?.genVideoScenes?.[sceneId]) continue;- sceneMedia?.generateSceneVideo(scene);+ kicks.push(sceneMedia.generateSceneVideo(scene, { revisionId }).then((r) => ({ sceneId, ok: r?.ok !== false })));}- submitted += 1;}- return submitted;+ const results = await Promise.all(kicks);+ const failed = results.filter((r) => !r.ok);+ // Best-effort: a release that itself fails just leaves the section claimed+ // for the rest of the lease — the next resume after it lapses still works.+ await Promise.all(failed.map(({ sceneId }) =>+ releaseMusicVideoRevisionSection(projectId, revisionId, sceneId, { silent: true }).catch(() => {})));+ return results.length - failed.length;};const resume = (revisionId) => run(() => resumeMusicVideoRevision(projectId, revisionId, { silent: true })- .then((res) => {+ .then(async (res) => {replaceProject(res.project);if (res.render?.jobId) {attachRender?.(res.render.jobId, res.project.id);toast.info('Every revised section has a new take — rendering the revised draft');return res;}- const submitted = generateSections(res.project, res.needsGeneration || []);+ const submitted = await generateSections(res.project, res.needsGeneration || [], revisionId);const waiting = (res.generating || []).length;const parts = [submitted ? `generating ${plural(submitted, 'section')}` : '',diff --git a/client/src/hooks/useMusicVideoSceneMedia.js b/client/src/hooks/useMusicVideoSceneMedia.jsindex d0da5b3f09..92f71aeaf9 100644--- a/client/src/hooks/useMusicVideoSceneMedia.js+++ b/client/src/hooks/useMusicVideoSceneMedia.js@@ -135,16 +135,23 @@ export default function useMusicVideoSceneMedia({ project, videoSettings, applyS* conditioning inputs (`referenceImageFiles`). A backend that can't consume* them refuses the render, and the toast names that capability gap instead of* quietly rendering without the references.+ *+ * Returns a promise that always RESOLVES (never rejects) to `{ ok }` — `ok`+ * is false when the kickoff request itself failed (refused, network error),+ * true once it reaches the queue or finishes synchronously. The revision+ * hook (#9011) passes `revisionId` and awaits this to release a claimed+ * section whose kickoff never made it to the queue, and to count only+ * confirmed submissions rather than every call it fired.*/- const generateFrame = (scene) => {+ const generateFrame = (scene, { revisionId } = {}) => {const prompt = buildFramePrompt(scene);- if (!prompt) { toast.error('Add a frame prompt or shot prompt first'); return; }+ if (!prompt) { toast.error('Add a frame prompt or shot prompt first'); return Promise.resolve({ ok: false }); }const projectId = project.id;frameLane.startScene(scene.sceneId);- generateImage({+ return generateImage({prompt,...(conditioning.length ? { referenceImageFiles: conditioning.map((ref) => ref.imageId) } : {}),- musicVideo: { projectId, sceneId: scene.sceneId },+ musicVideo: { projectId, sceneId: scene.sceneId, ...(revisionId ? { revisionId } : {}) },}, { silent: true }).then((res) => {const stillRunning = res?.status === 'queued' || res?.status === 'running';@@ -153,9 +160,9 @@ export default function useMusicVideoSceneMedia({ project, videoSettings, applyS// (and the durable scene-image event lands the generated frame). trackJob// reconciles a terminal event that raced ahead of this .then (fast fail).const jobId = res?.jobId || res?.generationId;- if (!jobId) { frameLane.clearScene(scene.sceneId); return; } // no id to track → don't strand the button+ if (!jobId) { frameLane.clearScene(scene.sceneId); return { ok: false }; } // no id to track → don't strand the buttonframeLane.trackJob(jobId, scene.sceneId);- return;+ return { ok: true };}const filename = res?.filename;if (filename) {@@ -166,6 +173,7 @@ export default function useMusicVideoSceneMedia({ project, videoSettings, applyS.catch((err) => toast.error(err?.message || 'Failed to attach frame'));}frameLane.clearScene(scene.sceneId);+ return { ok: true };}).catch((err) => {if (conditioning.length && REFERENCE_CAPABILITY_CODES.has(err?.code)) {@@ -174,21 +182,25 @@ export default function useMusicVideoSceneMedia({ project, videoSettings, applyStoast.error(err?.message || 'Frame generation failed');}frameLane.clearScene(scene.sceneId);+ return { ok: false };});};// Correlate a kicked-off video job with its scene, or clear the spinner when// the response carried no id to track. trackJob reconciles a terminal event- // that raced ahead of this .then.+ // that raced ahead of this .then. Resolves `{ ok }` — see generateFrame's+ // doc comment for why the caller never sees a rejection.const trackVideoJob = (res, sceneId) => {const jobId = res?.jobId || res?.generationId;- if (!jobId) { videoLane.clearScene(sceneId); return; }+ if (!jobId) { videoLane.clearScene(sceneId); return { ok: false }; }videoLane.trackJob(jobId, sceneId);+ return { ok: true };};const handleVideoError = (err, sceneId, fallbackMessage) => {toast.error(err?.message || fallbackMessage);videoLane.clearScene(sceneId);+ return { ok: false };};/**@@ -198,13 +210,16 @@ export default function useMusicVideoSceneMedia({ project, videoSettings, applyS* event clear the spinner; the finished clip's history id lands durably via* music-video:scene-video (musicVideoSceneVideoHook). generateVideo() throws on* a non-OK response, so the catch owns the only error toast (no double-toast).+ *+ * Returns a promise that always resolves to `{ ok }` — see generateFrame's+ * doc comment. `revisionId` (optional) is the revision hook's kickoff tag (#9011).*/- const generateSceneVideo = (scene) => {- if (!scene.referenceImageId) { toast.error('Generate a reference frame first'); return; }+ const generateSceneVideo = (scene, { revisionId } = {}) => {+ if (!scene.referenceImageId) { toast.error('Generate a reference frame first'); return Promise.resolve({ ok: false }); }const basePrompt = buildShotPrompt(scene);- if (!basePrompt) { toast.error('Add a shot prompt first'); return; }+ if (!basePrompt) { toast.error('Add a shot prompt first'); return Promise.resolve({ ok: false }); }const { settings, audioReactiveSelected, detectedAudioReactiveLora, videoBlockedReason } = videoSettings;- if (videoBlockedReason) { toast.error(videoBlockedReason); return; }+ if (videoBlockedReason) { toast.error(videoBlockedReason); return Promise.resolve({ ok: false }); }// #8977: a performance shot lip-syncs to the master recording, which only a// verified source-audio provider can do — never a cutaway lane with an// invented voice. The server slices the song and re-checks the capability.@@ -212,7 +227,7 @@ export default function useMusicVideoSceneMedia({ project, videoSettings, applySconst performanceBlocked = performance? (audioReactiveSelected ? performanceBlockedReason('local') : performanceBlockedReason(settings.backend)): null;- if (performanceBlocked) { toast.error(performanceBlocked); return; }+ if (performanceBlocked) { toast.error(performanceBlocked); return Promise.resolve({ ok: false }); }const spanSec = sceneSpanSec(scene);// Grok's CLI lane takes no timed controls: phrase intents ride as prose// whose timing is explicitly approximate. The environmental-motion guard@@ -222,7 +237,7 @@ export default function useMusicVideoSceneMedia({ project, videoSettings, applyS? `${basePrompt}. ${AUDIO_REACTIVE_PERFORMANCE_GUARD}`: [basePrompt, motionCues].filter(Boolean).join('. ');videoLane.startScene(scene.sceneId);- generateVideo({+ return generateVideo({prompt,...(settings.backend ? { backend: settings.backend } : {}),...(settings.backend === 'grok'@@ -248,7 +263,7 @@ export default function useMusicVideoSceneMedia({ project, videoSettings, applySloraFilenames: [detectedAudioReactiveLora.filename],loraScales: [settings.audioReactiveScale],} : {}),- musicVideo: JSON.stringify({ projectId: project.id, sceneId: scene.sceneId }),+ musicVideo: JSON.stringify({ projectId: project.id, sceneId: scene.sceneId, ...(revisionId ? { revisionId } : {}) }),}).then((res) => trackVideoJob(res, scene.sceneId)).catch((err) => handleVideoError(err, scene.sceneId, 'Scene video generation failed'));@@ -297,7 +312,7 @@ export default function useMusicVideoSceneMedia({ project, videoSettings, applyStoast.info('Every scene already has a reference frame');return;}- pending.forEach(generateFrame);+ pending.forEach((scene) => generateFrame(scene));};const generateMissingVideos = () => {@@ -318,7 +333,7 @@ export default function useMusicVideoSceneMedia({ project, videoSettings, applyS: 'Every scene already has a video');return;}- pending.forEach(generateSceneVideo);+ pending.forEach((scene) => generateSceneVideo(scene));};return {diff --git a/client/src/pages/MusicVideo.test.jsx b/client/src/pages/MusicVideo.test.jsxindex 3d48250063..0a298a27a2 100644--- a/client/src/pages/MusicVideo.test.jsx+++ b/client/src/pages/MusicVideo.test.jsx@@ -500,7 +500,7 @@ describe('MusicVideo selective section revision (#8987)', () => {await waitFor(() => expect(resumeMusicVideoRevision).toHaveBeenCalledWith('mv-1', 'mvr-1', { silent: true }));expect(startMusicVideoRevision).toHaveBeenCalledWith('mv-1', 'mve-1', {}, { silent: true });await waitFor(() => expect(generateVideo).toHaveBeenCalledTimes(1));- expect(JSON.parse(generateVideo.mock.calls[0][0].musicVideo)).toEqual({ projectId: 'mv-1', sceneId: 's2' });+ expect(JSON.parse(generateVideo.mock.calls[0][0].musicVideo)).toEqual({ projectId: 'mv-1', sceneId: 's2', revisionId: 'mvr-1' });const panel = screen.getByLabelText('Section revision');expect(within(panel).getByText('Kept')).toBeInTheDocument();});diff --git a/client/src/services/apiMusicVideo.js b/client/src/services/apiMusicVideo.jsindex 846b76a3de..de28c088a4 100644--- a/client/src/services/apiMusicVideo.js+++ b/client/src/services/apiMusicVideo.js@@ -174,6 +174,13 @@ export const resumeMusicVideoRevision = (id, revisionId, options = {}) =>request(`/music-video/${encodeURIComponent(id)}/revisions/${encodeURIComponent(revisionId)}/resume`, { method: 'POST', ...options });export const cancelMusicVideoRevision = (id, revisionId, options = {}) =>request(`/music-video/${encodeURIComponent(id)}/revisions/${encodeURIComponent(revisionId)}/cancel`, { method: 'POST', ...options });+// A generation kickoff that failed before reaching the queue (#9011): clears+// the section's claim so the next resume hands it out again immediately+// instead of waiting out the lease. Body: { sceneId } → { project, revision }.+export const releaseMusicVideoRevisionSection = (id, revisionId, sceneId, options = {}) =>+ request(`/music-video/${encodeURIComponent(id)}/revisions/${encodeURIComponent(revisionId)}/release`, {+ method: 'POST', body: JSON.stringify({ sceneId }), ...options,+ });// ---- Pre-production treatment (#8980) ----// A structured brief, a compiled whole-song arc, per-shot direction keyed to thediff --git a/server/lib/musicVideoValidation.js b/server/lib/musicVideoValidation.jsindex ab54952f45..82a558ae9b 100644--- a/server/lib/musicVideoValidation.js+++ b/server/lib/musicVideoValidation.js@@ -382,6 +382,13 @@ export const musicVideoRevisionStartSchema = z.object({sceneIds: z.array(z.string().min(1).max(200)).min(1).max(500).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.+export const musicVideoRevisionReleaseSchema = z.object({+ sceneId: z.string().min(1).max(200),+}).strict();+export const musicVideoProjectCreateSchema = z.object({name: z.string().min(1).max(200),mode: z.enum(MUSIC_VIDEO_MODES).optional(),diff --git a/server/routes/imageGen.js b/server/routes/imageGen.jsindex 50275bfd41..f3631a211a 100644--- a/server/routes/imageGen.js+++ b/server/routes/imageGen.js@@ -220,6 +220,9 @@ const generateSchema = z.object({musicVideo: z.object({projectId: z.string().min(1).max(200),sceneId: z.string().min(1).max(200),+ // Selective section revision (#9011): see the matching comment on the+ // video route's musicVideo schema (server/routes/videoGen.js).+ revisionId: z.string().min(1).max(200).optional(),}).optional(),// Durable catalog attach (#1359). When present, the mediaJobQueue completion// hook (catalogImageAttachHook) files the finished render onto this catalog@@ -540,6 +543,17 @@ router.post('/generate', imageGenUploads, asyncHandler(async (req, res) => {for (const p of uploadedTempPaths) unlinkGuarded(p).catch(() => {});});}++ // Selective section revision (#9011): a kickoff tagged for a revision that+ // has since closed is refused before any provider dispatch, closing the+ // cancel/kickoff race server-side. No-op when the tag carries no+ // revisionId; `res.on('close')` above already covers any staged uploads.+ // Deferred import since only this rare path needs the revision service.+ if (params.musicVideo?.revisionId) {+ const { assertRevisionOpen } = await import('../services/musicVideo/revisionService.js');+ await assertRevisionOpen(params.musicVideo.projectId, params.musicVideo.revisionId);+ }+// Local + codex both go through mediaJobQueue (separate lanes — codex// doesn't share MLX). External SD-API stays synchronous: it's a remote// call with no local single-flight constraint to absorb. `settings` anddiff --git a/server/routes/musicVideo.js b/server/routes/musicVideo.jsindex 1ba85503c2..24566b5d12 100644--- a/server/routes/musicVideo.js+++ b/server/routes/musicVideo.js@@ -34,6 +34,7 @@ import {musicVideoExcerptNoteSchema,musicVideoExcerptNoteUpdateSchema,musicVideoRevisionStartSchema,+ musicVideoRevisionReleaseSchema,isPaginationRequested,paginateArray,} from '../lib/validation.js';@@ -71,7 +72,9 @@ import { analyzeAudioFile, analyzeAudioFileManual, buildManualAnalysisFromCachedimport { renderMusicVideo, attachRenderSseClient, cancelRender } from '../services/musicVideo/render.js';import { startExcerptRender, attachExcerptRenderSseClient, cancelExcerptRender } from '../services/musicVideo/excerptRender.js';import { deleteExcerpt, addReviewNote, editReviewNote, deleteReviewNote } from '../services/musicVideo/excerptService.js';-import { startRevision, resumeRevision, cancelRevision } from '../services/musicVideo/revisionService.js';+import {+ startRevision, resumeRevision, cancelRevision, releaseRevisionSection,+} from '../services/musicVideo/revisionService.js';import { planProject } from '../services/musicVideo/planner.js';import { parseLyricCues } from '../services/musicVideo/timedText.js';import {@@ -395,6 +398,15 @@ router.post('/:id/revisions/:revisionId/cancel', asyncHandler(async (req, res) =res.json(await cancelRevision(req.params.id, req.params.revisionId));}));+// A generation kickoff that failed client-side before reaching the queue+// (network error, a refused request) leaves its section claimed for the+// full lease with nothing running — clear the claim so the very next resume+// hands the section out again immediately (#9011).+router.post('/:id/revisions/:revisionId/release', asyncHandler(async (req, res) => {+ const input = validateRequest(musicVideoRevisionReleaseSchema, req.body || {});+ res.json(await releaseRevisionSection(req.params.id, req.params.revisionId, input.sceneId));+}));+// --- Director scene board ---router.post('/:id/scenes', asyncHandler(async (req, res) => {diff --git a/server/routes/musicVideoRevision.test.js b/server/routes/musicVideoRevision.test.jsindex a5a37fd5a7..469ee28bb6 100644--- a/server/routes/musicVideoRevision.test.js+++ b/server/routes/musicVideoRevision.test.js@@ -63,6 +63,7 @@ vi.mock('../services/musicVideo/render.js', async (importOriginal) => ({const { default: musicVideoRoutes } = await import('./musicVideo.js');const projects = await import('../services/musicVideo/projects.js');const { recoverStuckMusicVideoExcerpts } = await import('../services/musicVideo/excerptRender.js');+const { assertRevisionOpen } = await import('../services/musicVideo/revisionService.js');const app = express();app.use(express.json());@@ -295,6 +296,52 @@ describe('selective section revision (#8987)', () => {expect(h.cancelJob).toHaveBeenCalledTimes(1);});+ it('cancelling an open revision leaves a same-scene job tagged for a different revision running (#9011)', async () => {+ const project = await reviewedProject();+ const { body: { revision } } = await request(app).post(`${base(project.id)}/excerpt/mve-draft/revisions`).send({});+ const now = new Date().toISOString();+ h.jobs.push(+ { id: 'job-this-revision', kind: 'video', status: 'running', queuedAt: now, params: { musicVideo: { projectId: project.id, sceneId: 's2', revisionId: revision.id } } },+ // A hand-started board render tagged with a DIFFERENT (e.g. superseded) revision for the+ // same scene: cancelling THIS revision must never touch it, exact revisionId match or not.+ { id: 'job-other-revision', kind: 'video', status: 'running', queuedAt: now, params: { musicVideo: { projectId: project.id, sceneId: 's2', revisionId: 'mvr-some-other-revision' } } },+ );+ const r = await request(app).post(`${base(project.id)}/revisions/${revision.id}/cancel`);+ expect(r.status).toBe(200);+ expect(r.body.canceledJobIds).toEqual(['job-this-revision']);+ expect(h.cancelJob).toHaveBeenCalledTimes(1);+ });++ it('release clears a claimed section so the very next resume hands it out again immediately (#9011)', async () => {+ const project = await reviewedProject();+ const { body: { revision } } = await request(app).post(`${base(project.id)}/excerpt/mve-draft/revisions`).send({});+ const first = await request(app).post(`${base(project.id)}/revisions/${revision.id}/resume`);+ expect(first.body.needsGeneration).toEqual([{ sceneId: 's2', kind: 'video' }]);++ // A resume right away sees s2 claimed — nothing left to hand out, since the+ // kickoff is presumed already on its way to the queue.+ const claimed = await request(app).post(`${base(project.id)}/revisions/${revision.id}/resume`);+ expect(claimed.body.needsGeneration).toEqual([]);+ expect(claimed.body.generating).toEqual([{ sceneId: 's2', kind: 'video' }]);++ // The kickoff never reached the queue (e.g. a network error): release the+ // claim, and the very next resume offers s2 again without waiting out the lease.+ const released = await request(app).post(`${base(project.id)}/revisions/${revision.id}/release`).send({ sceneId: 's2' });+ expect(released.status).toBe(200);+ const again = await request(app).post(`${base(project.id)}/revisions/${revision.id}/resume`);+ expect(again.body.needsGeneration).toEqual([{ sceneId: 's2', kind: 'video' }]);+ });++ it('refuses a generation kickoff tagged for a revision that is no longer open (#9011)', async () => {+ const project = await reviewedProject();+ const { body: { revision } } = await request(app).post(`${base(project.id)}/excerpt/mve-draft/revisions`).send({});+ await expect(assertRevisionOpen(project.id, revision.id)).resolves.toBeUndefined();+ await expect(assertRevisionOpen(project.id, undefined)).resolves.toBeUndefined(); // no tag → no-op++ await request(app).post(`${base(project.id)}/revisions/${revision.id}/cancel`);+ await expect(assertRevisionOpen(project.id, revision.id)).rejects.toMatchObject({ status: 409, code: 'REVISION_CLOSED' });+ });+it('refuses a second open revision, a section outside the draft, and a draft without a section map', async () => {const project = await reviewedProject();const first = await request(app).post(`${base(project.id)}/excerpt/mve-draft/revisions`).send({ sceneIds: ['s1'] });diff --git a/server/routes/videoGen.js b/server/routes/videoGen.jsindex eb67804135..228a708a34 100644--- a/server/routes/videoGen.js+++ b/server/routes/videoGen.js@@ -461,6 +461,13 @@ const generateBodySchema = z.object({z.object({projectId: z.string().min(1).max(200),sceneId: z.string().min(1).max(200),+ // Selective section revision (#9011): names the open revision this+ // generation was submitted for. The completion hook rides it along+ // unused; the submit service refuses the kickoff (409 REVISION_CLOSED)+ // when this revision has since closed, and cancel/state matching in+ // revisionGenerationJobs/revisionSectionStates uses it for an exact+ // match instead of the pre-#9011 scene+time heuristic.+ revisionId: z.string().min(1).max(200).optional(),}).optional(),),// FableLoom scene-video render. The media-job completion hook files thediff --git a/server/services/musicVideo/revision.js b/server/services/musicVideo/revision.jsindex 3818629c87..a3ab1fe352 100644--- a/server/services/musicVideo/revision.js+++ b/server/services/musicVideo/revision.js@@ -182,8 +182,20 @@ export function startRevisionOnProject(project, excerptId, { sceneIds } = {}, no};}-const tagMatches = (job, projectId, sceneId) =>- job?.params?.musicVideo?.projectId === projectId && job.params.musicVideo.sceneId === sceneId;+// A job's music-video tag matches this revision's section EXACTLY when it+// carries `revisionId` (#9011) — added by the revision hook at kickoff time,+// so a job another surface tagged with a different (or no) revisionId can+// never be mistaken for this revision's own generation. A job with no+// `revisionId` at all (submitted before this field existed, or a board+// generation never told which revision, if any, is open) falls back to the+// pre-#9011 scene+time heuristic so an in-flight legacy job is still tracked+// through a rolling deploy.+const tagMatches = (job, projectId, sceneId, revision) => {+ const tag = job?.params?.musicVideo;+ if (tag?.projectId !== projectId || tag?.sceneId !== sceneId) return false;+ if (isNonBlankStr(tag.revisionId)) return tag.revisionId === revision.id;+ return typeof job.queuedAt === 'string' && job.queuedAt >= revision.createdAt;+};const within = (iso, windowMs, nowMs) => {const t = typeof iso === 'string' ? Date.parse(iso) : NaN;@@ -210,7 +222,7 @@ export function revisionSectionStates(project, revision, jobs = [], nowMs = Dateif (!scene) return { ...section, state: 'removed' };if (isNonBlankStr(scene[TAKE_SLOT[section.kind]])) return { ...section, state: 'ready' };const takes = Array.isArray(scene.takes) ? scene.takes : [];- const pending = jobs.some((job) => job?.kind === section.kind && tagMatches(job, project.id, section.sceneId) && (+ const pending = jobs.some((job) => job?.kind === section.kind && tagMatches(job, project.id, section.sceneId, revision) && (job.status === 'queued' || job.status === 'running'// Completed after the revision opened, but its take isn't on the scene// yet: the attach hook is still writing it. Asking again would pay twice.@@ -239,8 +251,7 @@ function resumableRevision(project, revisionId) {export function revisionGenerationJobs(project, revision, jobs = []) {const rejected = (revision.sections || []).filter((s) => s.verdict === 'rejected');return jobs.filter((job) => (job?.status === 'queued' || job?.status === 'running')- && typeof job.queuedAt === 'string' && job.queuedAt >= revision.createdAt- && rejected.some((s) => job.kind === s.kind && tagMatches(job, project.id, s.sceneId)));+ && rejected.some((s) => job.kind === s.kind && tagMatches(job, project.id, s.sceneId, revision)));}/**@@ -313,3 +324,36 @@ export function cancelRevisionOnProject(project, revisionId, now = new Date().toconst next = { ...revision, status: 'canceled', updatedAt: now };return { project: replaceRevision(project, next), revision: next, renderExcerptId: revision.status === 'rendering' ? revision.renderExcerptId : null };}++/**+ * Guard for a generation route's enqueue step (#9011): a video/image request+ * tagged with a `revisionId` that no longer names an open (or rendering)+ * revision is refused BEFORE it reaches the queue, rather than being cancelled+ * moments later by whatever closed the revision. Throws 404/409; a project or+ * revision that no longer exists is treated the same as one that closed —+ * there is nothing left to hand this generation's output to. No-op when the+ * project itself is gone (the route's own lookup reports that separately).+ */+export function assertRevisionOpenForGeneration(project, revisionId) {+ if (!project) return;+ resumableRevision(project, revisionId);+}++/**+ * A resume that claimed a section for generation (`claimRevisionGeneration`)+ * but whose kickoff never reached the queue (submission failed client-side or+ * the route refused it) leaves that section claimed for the full lease+ * (`GENERATION_CLAIM_LEASE_MS`) with nothing actually running. Clearing the+ * claim here lets the very next resume hand the section out again immediately+ * instead of waiting out the lease. A no-op if the section isn't found or+ * isn't rejected — best-effort cleanup, never a reason to fail the caller.+ */+export function releaseRevisionClaim(project, revisionId, sceneId, now = new Date().toISOString()) {+ const revision = resumableRevision(project, revisionId);+ const next = {+ ...revision,+ sections: revision.sections.map((s) => (s.sceneId === sceneId && s.verdict === 'rejected' ? { ...s, claimedAt: null } : s)),+ updatedAt: now,+ };+ return { project: replaceRevision(project, next), revision: next };+}diff --git a/server/services/musicVideo/revisionService.js b/server/services/musicVideo/revisionService.jsindex 5557cf2733..ebbe7ebb63 100644--- a/server/services/musicVideo/revisionService.js+++ b/server/services/musicVideo/revisionService.js@@ -22,9 +22,11 @@import { getProject, mutateProjectRecord } from './projects.js';import { cancelExcerptRender, startExcerptRender } from './excerptRender.js';import {+ assertRevisionOpenForGeneration,cancelRevisionOnProject,claimRevisionGeneration,projectRevisions,+ releaseRevisionClaim,revisionGenerationJobs,revisionSectionStates,startRevisionOnProject,@@ -35,6 +37,29 @@ export async function startRevision(projectId, excerptId, input = {}) {return mutateProjectRecord(projectId, (current) => startRevisionOnProject(current, excerptId, input));}+/**+ * Enqueue-time guard (#9011): a video/image request tagged with a revision+ * refuses BEFORE the job reaches the queue when that revision is no longer+ * open — the generation route calls this ahead of `enqueueJob` so a closed+ * revision's cancel/kickoff race is closed server-side rather than raced.+ * Throws 404/409 (ServerError, code REVISION_CLOSED); a no-op when the tag+ * carries no revisionId.+ */+export async function assertRevisionOpen(projectId, revisionId) {+ if (!revisionId) return;+ const project = await getProject(projectId);+ assertRevisionOpenForGeneration(project, revisionId);+}++/**+ * Clear a claimed section's `claimedAt` after its generation kickoff failed to+ * reach the queue, so the very next resume hands it out again immediately+ * instead of waiting out the claim lease. Returns `{ project, revision }`.+ */+export async function releaseRevisionSection(projectId, revisionId, sceneId) {+ return mutateProjectRecord(projectId, (current) => releaseRevisionClaim(current, revisionId, sceneId));+}+/*** Continue a revision from its checkpoint. Returns* `{ project, revision, needsGeneration, generating, render }` — `render` is thediff --git a/server/services/videoGen/submitJob.js b/server/services/videoGen/submitJob.jsindex ba925d8bbc..4be3a3beb8 100644--- a/server/services/videoGen/submitJob.js+++ b/server/services/videoGen/submitJob.js@@ -32,6 +32,16 @@ import {import { VIDEO_GEN_LOCAL_ONLY_FIELD_NAMES } from './requestFields.js';const submitValidatedVideoGenJob = async (body, uploads) => {+ // Selective section revision (#9011): a kickoff tagged for a revision that+ // has since closed (cancelled, or already resolved by another resume) is+ // refused before any staging happens, closing the cancel/kickoff race+ // server-side rather than relying on the client to have seen the cancel in+ // time. A no-op when the tag carries no revisionId — deferred import since+ // only this rare path needs the revision service's closure.+ if (body.musicVideo?.revisionId) {+ const { assertRevisionOpen } = await import('../musicVideo/revisionService.js');+ await assertRevisionOpen(body.musicVideo.projectId, body.musicVideo.revisionId);+ }let fableLoomRenderSettings = null;if (body.fableLoom) {const taggedLoom = await getLoom(body.fableLoom.loomId);diff --git a/server/services/videoGen/submitJob.test.js b/server/services/videoGen/submitJob.test.jsindex cbf39c4a6f..3814b240df 100644--- a/server/services/videoGen/submitJob.test.js+++ b/server/services/videoGen/submitJob.test.js@@ -11,6 +11,7 @@ const mocks = vi.hoisted(() => ({prepareRemoteMediaJob: vi.fn(),prepareVideoGenParams: vi.fn(),preparePerformanceShot: vi.fn(async () => null),+ assertRevisionOpen: vi.fn(async () => {}),}));vi.mock('../../lib/federatedMediaRequest.js', () => ({@@ -29,6 +30,7 @@ vi.mock('../fableLoom/visualConditioning.js', () => ({}));vi.mock('../mediaJobQueue/index.js', () => ({ enqueueJob: mocks.enqueueJob }));vi.mock('../musicVideo/performanceShot.js', () => ({ preparePerformanceShot: mocks.preparePerformanceShot }));+vi.mock('../musicVideo/revisionService.js', () => ({ assertRevisionOpen: mocks.assertRevisionOpen }));vi.mock('./prepareParams.js', async (importOriginal) => ({...await importOriginal(),cleanupMultipartTemp: mocks.cleanupMultipartTemp,@@ -227,5 +229,22 @@ describe('submitVideoGenJob', () => {expect(prepared.cleanupStaged).toHaveBeenCalledTimes(1);expect(mocks.enqueueJob).not.toHaveBeenCalled();});++ it('refuses a kickoff tagged for a revision that has since closed, before any staging (#9011)', async () => {+ const closed = Object.assign(new Error('This revision is already canceled'), { status: 409, code: 'REVISION_CLOSED' });+ mocks.assertRevisionOpen.mockRejectedValueOnce(closed);+ const tagged = { ...musicVideo, revisionId: 'mvr-1' };++ await expect(submitVideoGenJob({ prompt: 'singer', backend: 'fal', musicVideo: tagged }, {})).rejects.toBe(closed);+ expect(mocks.assertRevisionOpen).toHaveBeenCalledWith('mv-1', 'mvr-1');+ expect(mocks.prepareVideoGenParams).not.toHaveBeenCalled();+ expect(mocks.enqueueJob).not.toHaveBeenCalled();+ });++ it('does not check for a revision when the tag carries no revisionId', async () => {+ mocks.prepareVideoGenParams.mockResolvedValue(falPrepared());+ await submitVideoGenJob({ prompt: 'singer', backend: 'fal', musicVideo }, {});+ expect(mocks.assertRevisionOpen).not.toHaveBeenCalled();+ });});});