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: reattach a reloaded Music Video final render and separate server from follow-up failures (#9940)
[._.]/ Adam Eivyabae1c5cf640
diff --git a/client/src/hooks/useMusicVideoRenderJob.js b/client/src/hooks/useMusicVideoRenderJob.jsindex e53f8eda1a..1c9d87f7c2 100644--- a/client/src/hooks/useMusicVideoRenderJob.js+++ b/client/src/hooks/useMusicVideoRenderJob.js@@ -1,9 +1,11 @@-import { useState } from 'react';+import { useEffect, useRef, useState } from 'react';import {+ getMusicVideoActiveRender,renderMusicVideoProject,musicVideoRenderEventsUrl,cancelMusicVideoRender,} from '../services/apiMusicVideo.js';+import toast from '../components/ui/Toast';import useSseJobSlot from './useSseJobSlot.js';const readRenderPercent = (frame) => Number.isFinite(frame.progress) ? frame.progress * 100 : undefined;@@ -20,8 +22,14 @@ const startRender = (projectId) => renderMusicVideoProject(projectId, { silent:* Final-render adapter over the shared SSE slot. Captures the project before* preparation begins, so navigation cannot replace the render or redirect its* callbacks. The job shape stays compatible with the existing cancel controls.+ *+ * A project the server marks `rendering` re-attaches on load (#9940) — the+ * same way excerpt renders do — through a READ of the live job+ * (`getMusicVideoActiveRender`), never a POST that would start a new render.+ * `reattach(projectId)` is the explicit retry the "Needs attention" banner+ * offers when that automatic attempt found no job or the slot was busy.*/-export default function useMusicVideoRenderJob({ onRendered, onFailed } = {}) {+export default function useMusicVideoRenderJob({ project, onRendered, onFailed } = {}) {const [failure, setFailure] = useState(null);const slot = useSseJobSlot({startRequest: startRender,@@ -40,13 +48,56 @@ export default function useMusicVideoRenderJob({ onRendered, onFailed } = {}) {lostConnectionMessage: 'Lost connection to the render — check Media History for the result',startErrorFallback: 'Failed to start render',});++ const [reattaching, setReattaching] = useState(false);+ const slotRef = useRef(slot);+ slotRef.current = slot;++ // Adopt the project's live render into the idle slot. Resolves true when it+ // is attached (or already is); false when there is none to attach to.+ const reattach = (projectId, { announce = true } = {}) => {+ if (!projectId) return Promise.resolve(false);+ setReattaching(true);+ return getMusicVideoActiveRender(projectId, { silent: true })+ .then(({ jobId }) => {+ if (!jobId) {+ if (announce) toast.info('No live render found on this machine — it may be rendering elsewhere, or it was interrupted');+ return false;+ }+ if (slotRef.current.jobId === jobId) return true;+ const attached = slotRef.current.attach(jobId, projectId);+ if (!attached && announce) toast.info('Another render already holds the progress view — finish or cancel it first');+ return attached;+ })+ .catch((err) => {+ if (announce) toast.error(err?.message || 'Could not look up the render');+ return false;+ })+ .finally(() => setReattaching(false));+ };++ const projectId = project?.id || null;+ const rendering = project?.status === 'rendering';+ useEffect(() => {+ if (!projectId || !rendering || slotRef.current.active) return undefined;+ let active = true;+ getMusicVideoActiveRender(projectId, { silent: true })+ .then(({ jobId }) => {+ if (active && jobId && !slotRef.current.active) slotRef.current.attach(jobId, projectId);+ })+ .catch(() => {});+ return () => { active = false; };+ }, [projectId, rendering]);+return {...slot,failure,- start: (projectId) => {+ reattaching,+ reattach,+ start: (id) => {if (slot.active) return;setFailure(null);- slot.start(projectId);+ slot.start(id);},job: slot.jobId ? { jobId: slot.jobId, projectId: slot.context } : null,progress: slot.active ? slot.percent : 0,diff --git a/client/src/hooks/useMusicVideoRevisions.js b/client/src/hooks/useMusicVideoRevisions.jsindex 7ac2751987..d1971c35a6 100644--- a/client/src/hooks/useMusicVideoRevisions.js+++ b/client/src/hooks/useMusicVideoRevisions.js@@ -1,6 +1,7 @@import { useState } from 'react';import toast from '../components/ui/Toast';import {+ getMusicVideoProject,startMusicVideoDependencyRepair,startMusicVideoRevision,repairMusicVideoPerformance,@@ -37,6 +38,14 @@ const plural = (n, word) => `${n} ${word}${n === 1 ? '' : 's'}`;* resume can hand that section out again immediately instead of waiting out* the server's claim lease.*+ * Two kinds of failure are told apart (#9940). A SERVER call that refuses or+ * throws means the action did not happen, so it toasts the error. A throw in+ * the client's own step AFTER the server succeeded — the resume that follows an+ * opened repair, applying the response — means the action DID happen: the+ * persisted record is reloaded (the open revision then offers Resume/Cancel+ * under "Needs attention") and a note says so, never a failure toast that+ * invites retrying completed work.+ ** `replaceProject(project)` swaps the local record whole; `sceneMedia` is the* `useMusicVideoSceneMedia` result; `attachRender(jobId, projectId)` is* `useMusicVideoExcerpts().attachRender`.@@ -49,6 +58,7 @@ export default function useMusicVideoRevisions({ project, replaceProject, sceneMconst projectId = project?.id || null;const [busy, setBusy] = useState(false);+ // The SERVER call: a failure here means the action did not happen.const run = (request) => {setBusy(true);return request()@@ -56,6 +66,21 @@ export default function useMusicVideoRevisions({ project, replaceProject, sceneM.finally(() => setBusy(false));};+ // The record the server holds, for when this tab's own follow-up broke after+ // the server succeeded. Best-effort: a failed reload leaves the next socket+ // event or page load to correct the board.+ const reloadProject = () => getMusicVideoProject(projectId, { silent: true }).then(replaceProject).catch(() => {});++ // Run the client's step that FOLLOWS a successful server call. A throw there+ // is not the server failing: reload the persisted record and say so.+ const settle = (res, step, done) => Promise.resolve()+ .then(() => step(res))+ .then(() => res, (err) => {+ console.error(`❌ Music Video revision follow-up failed: ${err?.message || 'unknown error'}`);+ toast.info(`${done} — it is saved; the board was refreshed.`);+ return reloadProject().then(() => res);+ });+const generateSections = async (next, refs, revisionId) => {const scenes = new Map((next.scenes || []).map((s) => [s.sceneId, s]));const kicks = [];@@ -79,56 +104,75 @@ export default function useMusicVideoRevisions({ project, replaceProject, sceneMreturn results.length - failed.length;};- const resume = (revisionId) => run(() => resumeMusicVideoRevision(projectId, revisionId, { silent: true })- .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;- }- if (res.revision?.sections?.some((section) => section.state === 'review-needed')) {- toast.info('Repair needs review — its reserved generation has no usable take; it will not submit again');- return res;- }- const submitted = await generateSections(res.project, res.needsGeneration || [], revisionId);- const waiting = (res.generating || []).length;- const parts = [- submitted ? `generating ${plural(submitted, 'section')}` : '',- waiting ? `${plural(waiting, 'section')} still in progress` : '',- ].filter(Boolean);- toast.info(`${parts.join('; ') || 'Waiting on the revised sections'} — resume again once their takes land`);- return res;- }));-- const startRevision = (excerptId, sceneIds) => run(() => startMusicVideoRevision(projectId, excerptId, sceneIds ? { sceneIds } : {}, { silent: true })- .then((res) => {- replaceProject(res.project);- if (res.skippedSceneIds?.length) toast.info(`Skipped ${plural(res.skippedSceneIds.length, 'title card')} — edit card text instead`);- return res;- }));+ const callResume = (revisionId) => resumeMusicVideoRevision(projectId, revisionId, { silent: true });++ // The client's half of a resume: adopt the record, adopt a started render,+ // or hand out the sections the server says still need a take.+ const applyResume = async (res, revisionId) => {+ 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;+ }+ if (res.revision?.sections?.some((section) => section.state === 'review-needed')) {+ toast.info('Repair needs review — its reserved generation has no usable take; it will not submit again');+ return;+ }+ const submitted = await generateSections(res.project, res.needsGeneration || [], revisionId);+ const waiting = (res.generating || []).length;+ const parts = [+ submitted ? `generating ${plural(submitted, 'section')}` : '',+ waiting ? `${plural(waiting, 'section')} still in progress` : '',+ ].filter(Boolean);+ toast.info(`${parts.join('; ') || 'Waiting on the revised sections'} — resume again once their takes land`);+ };++ // A director's own Resume: the resume request is the server call.+ const resume = (revisionId) => run(() => callResume(revisionId))+ .then((res) => (res ? settle(res, (r) => applyResume(r, revisionId), 'The revision resumed') : null));++ // The follow-up of an open/repair/revise step: the revision it opened is+ // saved, so ANY failure resuming it — the request or what follows — leaves it+ // open and recoverable rather than reporting the opening as failed.+ const resumeOpened = (opened) => {+ if (!opened?.revision) return null;+ const revisionId = opened.revision.id;+ setBusy(true);+ return callResume(revisionId)+ .then((res) => applyResume(res, revisionId).then(() => res))+ .catch((err) => {+ console.error(`❌ Music Video revision ${revisionId.slice(4, 12)} could not resume: ${err?.message || 'unknown error'}`);+ toast.info(`The revision is open but could not continue (${err?.message || 'unknown error'}) — resume or cancel it under "Needs attention" above.`);+ return reloadProject().then(() => null);+ })+ .finally(() => setBusy(false));+ };++ const startRevision = (excerptId, sceneIds) => run(() => startMusicVideoRevision(projectId, excerptId, sceneIds ? { sceneIds } : {}, { silent: true }))+ .then((res) => (res ? settle(res, (r) => {+ replaceProject(r.project);+ if (r.skippedSceneIds?.length) toast.info(`Skipped ${plural(r.skippedSceneIds.length, 'title card')} — edit card text instead`);+ }, 'The revision opened') : null));// The one-click path from a review: open the revision, then resume it at// once, which generates the rejected sections (an explicit director action).- const revise = (excerptId, sceneIds) => startRevision(excerptId, sceneIds)- .then((res) => (res?.revision ? resume(res.revision.id) : null));+ const revise = (excerptId, sceneIds) => startRevision(excerptId, sceneIds).then(resumeOpened);- const repairPerformance = (sceneId, input) => run(() => repairMusicVideoPerformance(projectId, sceneId, input, { silent: true })- .then((res) => { replaceProject(res.project); return res; }))- .then((res) => res?.revision ? resume(res.revision.id) : null);+ const repairPerformance = (sceneId, input) => run(() => repairMusicVideoPerformance(projectId, sceneId, input, { silent: true }))+ .then((res) => (res ? settle(res, (r) => replaceProject(r.project), 'The repair revision opened') : null))+ .then(resumeOpened);- const cancel = (revisionId) => run(() => cancelMusicVideoRevision(projectId, revisionId, { silent: true })- .then((res) => {- replaceProject(res.project);- const stopped = res.canceledJobIds?.length || 0;+ const cancel = (revisionId) => run(() => cancelMusicVideoRevision(projectId, revisionId, { silent: true }))+ .then((res) => (res ? settle(res, (r) => {+ replaceProject(r.project);+ const stopped = r.canceledJobIds?.length || 0;toast.info(stopped ? `Revision cancelled — stopped ${plural(stopped, 'generation job')}` : 'Revision cancelled');- return res;- }));+ }, 'The revision was cancelled') : null));- const repair = (basis) => run(() => startMusicVideoDependencyRepair(projectId, basis, { silent: true }).then((res) => {- replaceProject(res.project);- return res;- })).then((res) => res?.revision ? resume(res.revision.id) : null);+ const repair = (basis) => run(() => startMusicVideoDependencyRepair(projectId, basis, { silent: true }))+ .then((res) => (res ? settle(res, (r) => replaceProject(r.project), 'The repair revision opened') : null))+ .then(resumeOpened);// Also used by an opt-in auto-review run (#8988), which hands its revised// sections to the open board over the `music-video:auto-review` event.diff --git a/client/src/hooks/useMusicVideoRevisions.test.jsx b/client/src/hooks/useMusicVideoRevisions.test.jsxnew file mode 100644index 0000000000..c213a59b66--- /dev/null+++ b/client/src/hooks/useMusicVideoRevisions.test.jsx@@ -0,0 +1,97 @@+import { act, renderHook } from '@testing-library/react';+import { beforeEach, expect, it, vi } from 'vitest';+import toast from '../components/ui/Toast';+import useMusicVideoRevisions from './useMusicVideoRevisions.js';+import {+ getMusicVideoProject,+ resumeMusicVideoRevision,+ startMusicVideoDependencyRepair,+ cancelMusicVideoRevision,+} from '../services/apiMusicVideo.js';++vi.mock('../services/apiMusicVideo.js', () => ({+ getMusicVideoProject: vi.fn(),+ startMusicVideoDependencyRepair: vi.fn(),+ startMusicVideoRevision: vi.fn(),+ repairMusicVideoPerformance: vi.fn(),+ resumeMusicVideoRevision: vi.fn(),+ cancelMusicVideoRevision: vi.fn(),+ releaseMusicVideoRevisionSection: vi.fn(() => Promise.resolve()),+}));+vi.mock('../components/ui/Toast', () => ({ default: { error: vi.fn(), info: vi.fn(), success: vi.fn() } }));++const opened = { id: 'mv-example', revisions: [{ id: 'mvrev-example', status: 'open' }], scenes: [{ sceneId: 'scene-a' }] };+const persisted = { ...opened, updatedAt: 'after-reload' };++beforeEach(() => {+ vi.clearAllMocks();+ vi.spyOn(console, 'error').mockImplementation(() => {});+ startMusicVideoDependencyRepair.mockResolvedValue({ project: opened, revision: { id: 'mvrev-example' } });+ getMusicVideoProject.mockResolvedValue(persisted);+});++const setup = (sceneMedia = { generateFrame: vi.fn(), generateSceneVideo: vi.fn() }) => {+ const replaceProject = vi.fn();+ const hook = renderHook(() => useMusicVideoRevisions({ project: { id: 'mv-example' }, replaceProject, sceneMedia }));+ return { ...hook, replaceProject, sceneMedia };+};++it('a repair whose resume request fails leaves the opened revision recoverable, not reported as a failed repair (#9940)', async () => {+ resumeMusicVideoRevision.mockRejectedValue(new Error('Network down'));+ const { result, replaceProject } = setup();+ await act(async () => { await result.current.repair('basis-example'); });+ // The revision opened server-side: the record is reloaded so the banner can offer Resume/Cancel…+ expect(replaceProject).toHaveBeenLastCalledWith(persisted);+ expect(getMusicVideoProject).toHaveBeenCalledWith('mv-example', { silent: true });+ // …and nobody is told the repair failed.+ expect(toast.error).not.toHaveBeenCalled();+ expect(toast.info).toHaveBeenCalledWith(expect.stringContaining('Needs attention'));+ expect(result.current.busy).toBe(false);+});++it('a client step that throws AFTER a successful resume reloads the record instead of toasting a failure', async () => {+ resumeMusicVideoRevision.mockResolvedValue({+ project: opened, revision: { id: 'mvrev-example', sections: [] },+ needsGeneration: [{ sceneId: 'scene-a', kind: 'image' }], generating: [],+ });+ const sceneMedia = { generateFrame: vi.fn(() => { throw new Error('lane exploded'); }), generateSceneVideo: vi.fn() };+ const { result, replaceProject } = setup(sceneMedia);+ await act(async () => { await result.current.resume('mvrev-example'); });+ expect(sceneMedia.generateFrame).toHaveBeenCalled();+ expect(replaceProject).toHaveBeenLastCalledWith(persisted);+ expect(toast.error).not.toHaveBeenCalled();+ expect(toast.info).toHaveBeenCalledWith(expect.stringContaining('saved'));+});++it('a SERVER failure to open the repair is still a real failure: toast it, resume nothing, reload nothing', async () => {+ startMusicVideoDependencyRepair.mockRejectedValue(new Error('Finish or cancel the open revision first'));+ const { result } = setup();+ await act(async () => { await result.current.repair('basis-example'); });+ expect(toast.error).toHaveBeenCalledWith('Finish or cancel the open revision first');+ expect(resumeMusicVideoRevision).not.toHaveBeenCalled();+ expect(getMusicVideoProject).not.toHaveBeenCalled();+});++it('a cancel the server accepted but whose follow-up throws reloads rather than reporting a failed cancel', async () => {+ cancelMusicVideoRevision.mockResolvedValue({ project: opened, canceledJobIds: [] });+ const replaceProject = vi.fn()+ .mockImplementationOnce(() => { throw new Error('render crashed'); })+ .mockImplementation(() => {});+ const { result } = renderHook(() => useMusicVideoRevisions({ project: { id: 'mv-example' }, replaceProject, sceneMedia: {} }));+ await act(async () => { await result.current.cancel('mvrev-example'); });+ expect(replaceProject).toHaveBeenLastCalledWith(persisted);+ expect(toast.error).not.toHaveBeenCalled();+});++it('hands out only the sections the server says need a take once a repair resumes', async () => {+ resumeMusicVideoRevision.mockResolvedValue({+ project: opened, revision: { id: 'mvrev-example', sections: [] },+ needsGeneration: [{ sceneId: 'scene-a', kind: 'video' }], generating: [],+ });+ const generateSceneVideo = vi.fn(() => Promise.resolve({ ok: true }));+ const { result } = setup({ generateFrame: vi.fn(), generateSceneVideo });+ await act(async () => { await result.current.repair('basis-example'); });+ expect(generateSceneVideo).toHaveBeenCalledWith(opened.scenes[0], { revisionId: 'mvrev-example' });+ expect(getMusicVideoProject).not.toHaveBeenCalled();+ expect(toast.error).not.toHaveBeenCalled();+});diff --git a/client/src/hooks/useMusicVideoTreatment.js b/client/src/hooks/useMusicVideoTreatment.jsindex e49d70cb1c..a93eff269a 100644--- a/client/src/hooks/useMusicVideoTreatment.js+++ b/client/src/hooks/useMusicVideoTreatment.js@@ -121,16 +121,26 @@ export default function useMusicVideoTreatment({ project, onProjectPatch, replacsetApplying(true);// Apply joins the same write chain, so an edit or proof review started// meanwhile runs after it (with the revision it leaves) instead of racing it.+ // `.then(onApplied, onRefused)`, never `.then(…).catch(…)`: the second+ // handler is only for the SERVER refusing. A throw in this tab's own+ // follow-up runs after the server already applied the direction, so it+ // must not read as "Apply failed" and invite re-applying (#9940).const run = chainRef.current.then(() => applyMusicVideoTreatment(id, { revision, overwrite, addTextCues }, { silent: true })).then(({ project: next, result }) => {- replaceProject?.(next);- if (id === projectRef.current) setPreview(null);- const kept = result.promptsKept.length + result.conflicted.length;- toast.success(`Applied direction to ${result.directed} scene${result.directed === 1 ? '' : 's'}${kept ? ` — ${kept} hand-edited prompt${kept === 1 ? '' : 's'} kept` : ''}${result.textCuesAdded ? `, ${result.textCuesAdded} text cues added` : ''}`);+ try {+ replaceProject?.(next);+ if (id === projectRef.current) setPreview(null);+ const kept = result.promptsKept.length + result.conflicted.length;+ toast.success(`Applied direction to ${result.directed} scene${result.directed === 1 ? '' : 's'}${kept ? ` — ${kept} hand-edited prompt${kept === 1 ? '' : 's'} kept` : ''}${result.textCuesAdded ? `, ${result.textCuesAdded} text cues added` : ''}`);+ } catch (err) {+ console.error(`❌ Music Video treatment apply follow-up failed: ${err?.message || 'unknown error'}`);+ toast.info('The direction was applied — the board was refreshed.');+ getMusicVideoProject(id, { silent: true }).then((fresh) => replaceProject?.(fresh)).catch(() => {});+ if (id === projectRef.current) setPreview(null);+ }return result;- })- .catch((err) => {+ }, (err) => {// A stale review re-reads the preview so the director sees what changed.if (err?.status === 409) loadPreview();toast.error(err?.message || 'Apply failed');diff --git a/client/src/hooks/useMusicVideoTreatment.test.jsx b/client/src/hooks/useMusicVideoTreatment.test.jsxnew file mode 100644index 0000000000..e72a86c225--- /dev/null+++ b/client/src/hooks/useMusicVideoTreatment.test.jsx@@ -0,0 +1,61 @@+import { act, renderHook } from '@testing-library/react';+import { beforeEach, expect, it, vi } from 'vitest';+import toast from '../components/ui/Toast';+import useMusicVideoTreatment from './useMusicVideoTreatment.js';+import {+ applyMusicVideoTreatment,+ getMusicVideoProject,+ previewMusicVideoTreatmentApply,+} from '../services/apiMusicVideo.js';++vi.mock('../services/apiMusicVideo.js', () => ({+ getMusicVideoProject: vi.fn(),+ updateMusicVideoTreatment: vi.fn(),+ compileMusicVideoTreatment: vi.fn(),+ previewMusicVideoTreatmentApply: vi.fn(),+ applyMusicVideoTreatment: vi.fn(),+ reviewMusicVideoTreatmentProof: vi.fn(),+}));+vi.mock('../components/ui/Toast', () => ({ default: { error: vi.fn(), info: vi.fn(), success: vi.fn() } }));++const applied = { project: { id: 'mv-example', updatedAt: 'applied' }, result: { directed: 2, promptsKept: [], conflicted: [], textCuesAdded: 0 } };+const persisted = { id: 'mv-example', updatedAt: 'after-reload' };++beforeEach(() => {+ vi.clearAllMocks();+ vi.spyOn(console, 'error').mockImplementation(() => {});+ previewMusicVideoTreatmentApply.mockResolvedValue({ revision: 4 });+ getMusicVideoProject.mockResolvedValue(persisted);+});++// Apply needs a loaded review; reaching it is part of the director's flow.+const withPreview = async (replaceProject) => {+ const hook = renderHook(() => useMusicVideoTreatment({ project: { id: 'mv-example' }, onProjectPatch: vi.fn(), replaceProject }));+ await act(async () => { await hook.result.current.loadPreview(); });+ return hook;+};++it('reports a server refusal of Apply as a failure and re-reads the stale review (409)', async () => {+ applyMusicVideoTreatment.mockRejectedValue(Object.assign(new Error('The review is out of date'), { status: 409 }));+ const { result } = await withPreview(vi.fn());+ await act(async () => { await result.current.apply(); });+ expect(toast.error).toHaveBeenCalledWith('The review is out of date');+ expect(previewMusicVideoTreatmentApply).toHaveBeenCalledTimes(2);+});++it('does NOT report "Apply failed" when only this tab\'s follow-up threw after the server applied it (#9940)', async () => {+ applyMusicVideoTreatment.mockResolvedValue(applied);+ const replaceProject = vi.fn()+ .mockImplementationOnce(() => { throw new Error('render crashed'); })+ .mockImplementation(() => {});+ const { result } = await withPreview(replaceProject);+ let outcome;+ await act(async () => { outcome = await result.current.apply(); });+ // The server's result still reaches the caller, the record is reloaded, and no failure is announced.+ expect(outcome).toEqual(applied.result);+ expect(replaceProject).toHaveBeenLastCalledWith(persisted);+ expect(toast.error).not.toHaveBeenCalled();+ expect(toast.info).toHaveBeenCalledWith(expect.stringContaining('applied'));+ expect(result.current.applying).toBe(false);+ expect(result.current.preview).toBeNull();+});diff --git a/client/src/lib/README.md b/client/src/lib/README.mdindex db6636747c..c668ce0c2b 100644--- a/client/src/lib/README.md+++ b/client/src/lib/README.md@@ -65,6 +65,7 @@ grep -i "what you want to do" client/src/lib/README.md| `musicVideoTakes.js` | Music-video scene takes view helpers (#8965): `sceneTakeList(scene, kind)` lists a scene's image/video takes with an un-materialized pre-takes selection appended as a read-only `legacy` take; `takePreviewKey`, `takeThumbUrl`, `takeProvenance`; `TAKE_SLOT` maps a take kind to its selection field. Used by `components/musicVideo/SceneTakeStrip.jsx` and `pages/MusicVideo.jsx`. || `musicVideoShotTiming.js` | Re-export of `server/lib/musicVideoShotTiming.js` (#8977) — shot modes, the verified source-audio lip-sync capability table, `performanceBlockedReason`, `planPerformanceRepair` (measured accepted-prefix boundary, suffix interval and next spend), `planPerformanceWindow`, `grokCoverage`, `approximateMotionCues`, `shotSplitLimit` (when a scene offers a lyric-boundary split), `falSceneTake` (a fal take's model, length, resolution and estimated cost). Used by `hooks/useMusicVideoSceneMedia.js` and `components/musicVideo/SceneCard.jsx`. || `musicVideoStages.js` | Music Video page stage model: `MUSIC_VIDEO_STAGES` (setup → cast-sets → board → produce → compose → review), `resolveStageParam(value)` for the `:stage` route param, `deriveStages(project)` (per-stage `done`/`active`/`blocked`/`todo` + `current`, the first incomplete stage; a live production run pins Produce), `deriveNextAction(project, ctx)` (the one primary action the sticky header offers — approve Cast & Sets, stop/resume production, render final, …), `projectSpend(project)` (paid generation used vs. cap), `projectShotSummary(project)` (document shots or scene counts), and `currentProductionRun`; `productionReviewStopGuidance` separates current approval blockers from historical run stops. Used by `components/musicVideo/MusicVideoLayout.jsx` and `pages/MusicVideo.jsx`. |+| `musicVideoAttention.js` | Music Video "Needs attention" model (#9940): `deriveAttentionItems(project, live)` returns the banner rows for server-held states a client-orchestrated workflow can strand — an open/rendering revision, an interrupted Cast & Sets stage, a running auto-review waiting on its revised sections, a final render nobody is watching — derived from the persisted record so they survive a reload (healthy work this tab can see progressing is not flagged); `openRevisionOf(project)`; `ATTENTION_ANCHOR_ID` + `revealAttention()` scroll a refusal toast to the banner. Used by `components/musicVideo/NeedsAttentionBanner.jsx` and `pages/MusicVideo.jsx`. || `musicVideoPreview.js` | Pick the representative produced asset for a Music Video project card (`selectMusicVideoPreview`: final video → latest excerpt → latest rendered scene clip → latest scene reference frame → visual spec reference) for the main project grid. Pure, computed off the project record, with image path and fallback helpers (`musicVideoImageSrc`, `musicVideoImageFallback`). || `musicVideoUniverseRefs.js` | `pullUniverseCanonReferences(universe, existingReferences)` (#8978) maps a linked universe's characters/places/objects to visual-spec references (character/set/prop roles), skipping images already present and capping at `MUSIC_VIDEO_MAX_REFERENCES` (24, mirrors the server schema). Returns `{ next, added, skipped }`; the caller persists `next` via the ordinary visualSpec PATCH. Used by `components/musicVideo/VisualSpecPanel.jsx`. (The style snapshots are derived server-side, #9105.) || `musicVideoAutonomous.js` | Fully-autonomous Music Video, client half: re-exports the server stage vocabulary (`AUTONOMOUS_STAGES`, checkpoint ids, default tools/limits, `autonomousMedium`), the status/checkpoint labels, and owns the start form's `emptyAutonomousDraft` / `autonomousRequestFromDraft` mapping (including the Suno form options and `isSunoModelValid`) plus `autonomousStageRows(run)` and `isAutonomousLive(run)` for the run panel, and `autopilotDraftFromParams` / `autopilotParamsFromDraft` for the music-video-autopilot Schedule settings form. |diff --git a/client/src/lib/index.js b/client/src/lib/index.jsindex 4e511d2645..23dafcaa93 100644--- a/client/src/lib/index.js+++ b/client/src/lib/index.js@@ -74,6 +74,7 @@ export * from './musicVideoMotion.js';export * from './musicVideoTakes.js';export * from './musicVideoShotTiming.js';export * from './musicVideoStages.js';+export * from './musicVideoAttention.js';export * from './musicVideoUniverseRefs.js';export * from './musicVideoAutomation.js';export * from './musicVideoAutonomous.js';diff --git a/client/src/lib/musicVideoAttention.js b/client/src/lib/musicVideoAttention.jsnew file mode 100644index 0000000000..165d7536c0--- /dev/null+++ b/client/src/lib/musicVideoAttention.js@@ -0,0 +1,127 @@+/**+ * "Needs attention" for the Music Video header (#9940): the server-held states+ * a client-orchestrated workflow can strand — an open revision, an interrupted+ * Cast & Sets stage, a running auto-review waiting on its revised sections, a+ * final render nobody is watching. Request A opens server state and step B+ * finalizes it, so a throw or reload between them leaves a record that blocks+ * production while nothing on screen says why. Everything here is derived from+ * the PERSISTED project, never from what this tab remembers, so the same+ * answer holds after a reload.+ *+ * Pure: `deriveAttentionItems(project, live)` returns the banner's rows;+ * `NeedsAttentionBanner` renders them and the page wires their actions.+ */++/** The DOM id of the banner, so a refusal toast can scroll to it. */+export const ATTENTION_ANCHOR_ID = 'mv-needs-attention';++const OPEN_REVISION = new Set(['open', 'rendering']);+const SLOT = { image: 'referenceImageId', video: 'videoHistoryId' };+const asList = (value) => (Array.isArray(value) ? value : []);++/** The open or rendering revision the project holds, or null. */+export const openRevisionOf = (project) => asList(project?.revisions).find((r) => OPEN_REVISION.has(r.status)) || null;++// A rejected section's new take lives on its scene; count what has landed.+function sectionProgress(project, revision) {+ const scenes = new Map(asList(project?.scenes).map((s) => [s.sceneId, s]));+ const rejected = asList(revision?.sections).filter((s) => s.verdict === 'rejected');+ const ready = rejected.filter((s) => scenes.get(s.sceneId)?.[SLOT[s.kind]]).length;+ return { ready, total: rejected.length, rejected };+}++/**+ * The rows the "Needs attention" banner shows for `project`, in the order a+ * director would clear them. `live` names what THIS tab can already see+ * progressing, so healthy work is not flagged:+ * - `generatingSceneIds` — scenes with a frame/clip spinning on this board+ * - `draftRendering` — a draft excerpt render is attached to this tab+ * - `finalRenderAttached` — this tab already shows the final render's progress+ *+ * Row shape: `{ id, kind, tone, title, detail, … }` plus the ids the action+ * needs — `revisionId` + `canResume` (revision), `runId` (auto-review).+ */+export function deriveAttentionItems(project, { generatingSceneIds = null, draftRendering = false, finalRenderAttached = false } = {}) {+ if (!project) return [];+ const items = [];+ const spinning = (sceneId) => !!generatingSceneIds?.has?.(sceneId);++ // A board-driven auto-review run owns the revision it opened (a production+ // run's is dispatched server-side), so the run — not the revision — is the+ // thing to continue or cancel.+ const liveReview = asList(project.autoReviews).find((run) => run.status === 'running' && !run.productionRunId) || null;+ const ownedRevisionId = liveReview ? liveReview.attempts?.at?.(-1)?.revisionId || null : null;+ const revisions = asList(project.revisions);++ const revision = openRevisionOf(project);+ if (revision && revision.id !== ownedRevisionId) {+ const { ready, total, rejected } = sectionProgress(project, revision);+ const progressing = (revision.status === 'rendering' && draftRendering) || rejected.some((s) => spinning(s.sceneId));+ if (!progressing) {+ const rendering = revision.status === 'rendering';+ items.push({+ id: `revision:${revision.id}`,+ kind: 'revision',+ tone: 'warn',+ title: rendering ? 'A revision is re-rendering its draft' : 'A section revision is open',+ detail: rendering+ ? 'Production and auto-review wait for it. If the render is not progressing, cancel the revision.'+ : `New takes: ${ready} of ${total}. Production and auto-review wait until it is resumed or cancelled.`,+ revisionId: revision.id,+ canResume: !rendering,+ });+ }+ }++ if (project.castAndSets?.interrupted) {+ items.push({+ id: 'cast-and-sets',+ kind: 'cast-and-sets',+ tone: 'warn',+ title: 'The Cast & Sets check-in was interrupted',+ detail: 'A restart stopped it before it reached a checkpoint. Resume to continue from where it left off.',+ });+ }++ if (liveReview && ownedRevisionId) {+ const owned = revisions.find((r) => r.id === ownedRevisionId);+ if (owned?.status === 'open') {+ const { rejected } = sectionProgress(project, owned);+ if (!rejected.some((s) => spinning(s.sceneId))) {+ items.push({+ id: `auto-review:${liveReview.id}`,+ kind: 'auto-review',+ tone: 'warn',+ title: 'Auto-review is waiting for its revised sections',+ detail: 'The board hands them out while it is open. If you reloaded or closed it, continue to hand them out again — nothing is generated beyond the limits you set for the run.',+ runId: liveReview.id,+ });+ }+ }+ }++ if (project.status === 'rendering' && !finalRenderAttached) {+ items.push({+ id: 'final-render',+ kind: 'final-render',+ tone: 'warn',+ title: 'A final render is in progress',+ detail: 'Reattach to watch its progress or cancel it.',+ });+ }+ return items;+}++/**+ * The scroll target a refusal toast ("Finish or cancel the open revision")+ * links to. Scrolls the banner into view and focuses its first control; a+ * missing banner (the revision is not in the local record yet) is a no-op.+ */+export function revealAttention() {+ if (typeof document === 'undefined') return false;+ const banner = document.getElementById(ATTENTION_ANCHOR_ID);+ if (!banner) return false;+ banner.scrollIntoView?.({ block: 'nearest', behavior: 'smooth' });+ banner.querySelector?.('button')?.focus?.({ preventScroll: true });+ return true;+}diff --git a/client/src/lib/musicVideoAttention.test.js b/client/src/lib/musicVideoAttention.test.jsnew file mode 100644index 0000000000..c8584b5f9a--- /dev/null+++ b/client/src/lib/musicVideoAttention.test.js@@ -0,0 +1,107 @@+import { describe, expect, it } from 'vitest';+import { deriveAttentionItems, openRevisionOf } from './musicVideoAttention.js';++const scene = (sceneId, extra = {}) => ({ sceneId, ...extra });+const revision = (extra = {}) => ({+ id: 'mvrev-example',+ status: 'open',+ sections: [+ { sceneId: 'scene-a', kind: 'video', verdict: 'rejected' },+ { sceneId: 'scene-b', kind: 'image', verdict: 'rejected' },+ { sceneId: 'scene-c', kind: 'video', verdict: 'kept' },+ ],+ ...extra,+});+const project = (extra = {}) => ({+ id: 'mv-example',+ scenes: [scene('scene-a'), scene('scene-b'), scene('scene-c')],+ revisions: [],+ autoReviews: [],+ ...extra,+});+const run = (extra = {}) => ({+ id: 'mvar-example',+ status: 'running',+ attempts: [{ n: 1, revisionId: 'mvrev-example' }],+ ...extra,+});++describe('deriveAttentionItems (#9940)', () => {+ it('is empty for a healthy or missing project', () => {+ expect(deriveAttentionItems(null)).toEqual([]);+ expect(deriveAttentionItems(project())).toEqual([]);+ expect(deriveAttentionItems(project({ revisions: [revision({ status: 'complete' }), revision({ id: 'x', status: 'canceled' })] }))).toEqual([]);+ });++ it('surfaces an open revision with the id the server holds and how far its takes got', () => {+ const items = deriveAttentionItems(project({+ scenes: [scene('scene-a', { videoHistoryId: 'vh-1' }), scene('scene-b'), scene('scene-c')],+ revisions: [revision()],+ }));+ expect(items).toHaveLength(1);+ expect(items[0]).toMatchObject({ kind: 'revision', revisionId: 'mvrev-example', canResume: true });+ expect(items[0].detail).toContain('New takes: 1 of 2');+ });++ it('offers only Cancel while a revision re-renders its draft, and stays quiet when this tab is watching that render', () => {+ const rendering = project({ revisions: [revision({ status: 'rendering' })] });+ expect(deriveAttentionItems(rendering)[0]).toMatchObject({ kind: 'revision', canResume: false });+ expect(deriveAttentionItems(rendering, { draftRendering: true })).toEqual([]);+ });++ it('does not flag an open revision whose sections are spinning on this board', () => {+ const open = project({ revisions: [revision()] });+ expect(deriveAttentionItems(open, { generatingSceneIds: new Set(['scene-b']) })).toEqual([]);+ // A spinner on an unrelated scene proves nothing about this revision.+ expect(deriveAttentionItems(open, { generatingSceneIds: new Set(['scene-c']) })).toHaveLength(1);+ });++ it('flags an interrupted Cast & Sets stage but not one that is working or settled', () => {+ expect(deriveAttentionItems(project({ castAndSets: { status: 'imaging', interrupted: true } }))).toMatchObject([{ kind: 'cast-and-sets' }]);+ expect(deriveAttentionItems(project({ castAndSets: { status: 'imaging', interrupted: false } }))).toEqual([]);+ expect(deriveAttentionItems(project({ castAndSets: { status: 'approved' } }))).toEqual([]);+ });++ it('shows a running auto-review waiting on generation as ONE row — the run owns its revision', () => {+ const items = deriveAttentionItems(project({ revisions: [revision()], autoReviews: [run()] }));+ expect(items).toHaveLength(1);+ expect(items[0]).toMatchObject({ kind: 'auto-review', runId: 'mvar-example' });+ });++ it('leaves auto-review alone while it renders or reviews, when a production owns it, and while sections spin', () => {+ // The run is rendering the revised draft: nothing to hand out.+ expect(deriveAttentionItems(project({ revisions: [revision({ status: 'rendering' })], autoReviews: [run()] }))).toEqual([]);+ // A production run dispatches its own sections server-side.+ expect(deriveAttentionItems(project({ revisions: [revision()], autoReviews: [run({ productionRunId: 'mvpr-example' })] })))+ .toMatchObject([{ kind: 'revision' }]);+ // This board is already generating the hand-out.+ expect(deriveAttentionItems(project({ revisions: [revision()], autoReviews: [run()] }), { generatingSceneIds: new Set(['scene-a']) })).toEqual([]);+ // A paused run is not "waiting": its open revision is an ordinary revision.+ expect(deriveAttentionItems(project({ revisions: [revision()], autoReviews: [run({ status: 'stopped' })] })))+ .toMatchObject([{ kind: 'revision' }]);+ });++ it('flags a final render the server holds that this tab is not showing', () => {+ expect(deriveAttentionItems(project({ status: 'rendering' }))).toMatchObject([{ kind: 'final-render' }]);+ expect(deriveAttentionItems(project({ status: 'rendering' }), { finalRenderAttached: true })).toEqual([]);+ expect(deriveAttentionItems(project({ status: 'complete' }))).toEqual([]);+ });++ it('orders rows revision, cast & sets, auto-review, final render', () => {+ const items = deriveAttentionItems(project({+ status: 'rendering',+ castAndSets: { status: 'directing', interrupted: true },+ revisions: [revision({ id: 'mvrev-other' }), revision({ id: 'mvrev-owned' })],+ autoReviews: [run({ attempts: [{ n: 1, revisionId: 'mvrev-owned' }] })],+ }));+ expect(items.map((item) => item.kind)).toEqual(['revision', 'cast-and-sets', 'auto-review', 'final-render']);+ });+});++describe('openRevisionOf', () => {+ it('returns the open or rendering revision, else null', () => {+ expect(openRevisionOf(project({ revisions: [revision({ status: 'canceled' }), revision({ id: 'live', status: 'rendering' })] }))?.id).toBe('live');+ expect(openRevisionOf(project())).toBeNull();+ expect(openRevisionOf(null)).toBeNull();+ });+});diff --git a/client/src/services/apiMusicVideo.js b/client/src/services/apiMusicVideo.jsindex 00c45e6e24..728f2d0573 100644--- a/client/src/services/apiMusicVideo.js+++ b/client/src/services/apiMusicVideo.js@@ -158,6 +158,11 @@ export const cancelMusicVideoMidiTranscription = (jobId, options = {}) =>// the SSE URL below (subscribe with useSseProgress). cancel stops an in-flight job.export const renderMusicVideoProject = (id, options = {}) =>request(`/music-video/${encodeURIComponent(id)}/render`, { method: 'POST', ...options });+// Read-only: resolves { jobId } of the project's live final render on this+// install (null when none) so a reloaded page can re-attach to its progress+// stream. Never starts a render — only the POST above does (#9940).+export const getMusicVideoActiveRender = (id, options = {}) =>+ request(`/music-video/${encodeURIComponent(id)}/render`, options);export const getMusicVideoCodeDocument = (id, options = {}) =>request(`/music-video/${encodeURIComponent(id)}/code/document`, options);export const generateMusicVideoCode = (id, body = {}, options = {}) =>diff --git a/server/routes/musicVideo.js b/server/routes/musicVideo.jsindex 286a6d7a57..7cdd0fca50 100644--- a/server/routes/musicVideo.js+++ b/server/routes/musicVideo.js@@ -111,7 +111,7 @@ import {} from '../services/audioMidiTranscription.js';import { analyzeAudioFileManual, buildManualAnalysisFromCached } from '../services/musicVideo/audioAnalysis.js';import { analyzeProjectSong, resolveProjectAudioPath } from '../services/musicVideo/projectAudio.js';-import { renderMusicVideo, attachRenderSseClient, cancelRender } from '../services/musicVideo/render.js';+import { renderMusicVideo, attachRenderSseClient, cancelRender, getActiveRenderJobId } from '../services/musicVideo/render.js';import { prepareCodeRender } from '../services/musicVideo/codeRender.js';import { generateMusicVideoCode, regenerateMusicVideoCodeSection } from '../services/musicVideo/codeGeneration.js';import { startExcerptRender, attachExcerptRenderSseClient, cancelExcerptRender } from '../services/musicVideo/excerptRender.js';@@ -499,6 +499,12 @@ router.post('/:id/render', asyncHandler(async (req, res) => {res.json(await renderMusicVideo(req.params.id));}));+// Read-only: the live final-render job for a project (null when none runs on+// this instance), so a reloaded page re-attaches without POSTing a new render.+router.get('/:id/render', (req, res) => {+ res.json({ jobId: getActiveRenderJobId(req.params.id) });+});+router.post('/:id/production-review/feedback', asyncHandler(async (req, res) => {res.json(await addProductionFeedback(req.params.id, validateRequest(musicVideoProductionFeedbackSchema, req.body)));}));diff --git a/server/routes/musicVideo.test.js b/server/routes/musicVideo.test.jsindex 93f9dc5418..ba47c02fb9 100644--- a/server/routes/musicVideo.test.js+++ b/server/routes/musicVideo.test.js@@ -45,6 +45,7 @@ vi.mock('../services/musicVideo/render.js', () => ({renderMusicVideo: vi.fn(async () => ({ jobId: 'job-1' })),attachRenderSseClient: vi.fn(() => true),cancelRender: vi.fn(() => true),+ getActiveRenderJobId: vi.fn(() => null),}));// Same posture for the draft excerpt render (#8986) — the route's job is to@@ -659,6 +660,18 @@ describe('musicVideo routes', () => {expect(svc.addProjectScene).not.toHaveBeenCalled();});+ it('GET /:id/render reports the live job without starting a render (#9940)', async () => {+ renderSvc.getActiveRenderJobId.mockReturnValueOnce('job-live');+ const live = await request(app).get('/api/music-video/mv-1/render');+ expect(live.status).toBe(200);+ expect(live.body).toEqual({ jobId: 'job-live' });+ expect(renderSvc.getActiveRenderJobId).toHaveBeenCalledWith('mv-1');+ const idle = await request(app).get('/api/music-video/mv-1/render');+ expect(idle.body).toEqual({ jobId: null });+ // A page reload only READS — it must never kick off a render.+ expect(renderSvc.renderMusicVideo).not.toHaveBeenCalled();+ });+it('POST /render/:jobId/cancel cancels the job', async () => {const r = await request(app).post('/api/music-video/render/job-1/cancel').send({});expect(r.status).toBe(200);diff --git a/server/services/musicVideo/render.js b/server/services/musicVideo/render.jsindex 4e97ac7255..b3f2c60ddd 100644--- a/server/services/musicVideo/render.js+++ b/server/services/musicVideo/render.js@@ -127,6 +127,17 @@ function findCoverageShortfalls(clips, { toleranceSec = COVERAGE_TOLERANCE_SEC }return out;}+/**+ * The project's live final-render job on THIS instance, or null — a render+ * still preparing (no job id yet) or running on another machine reports null.+ * Read-only: lets a reloaded page re-attach to the render's progress stream+ * without POSTing /render, which would START one when none is live (#9940).+ */+export function getActiveRenderJobId(projectId) {+ const existing = projectRenders.get(projectId);+ return existing && existing !== PENDING && jobs.has(existing) ? existing : null;+}+export function getRenderJobStatus(jobId) {const job = jobs.get(jobId);if (!job) return null;