Skip to content

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

feat: generate a board-started auto-review run's revised sections on the server (#10014)

Adam Eivy30fc7a735d8d
diff --git a/client/src/components/musicVideo/AutoReviewPanel.jsx b/client/src/components/musicVideo/AutoReviewPanel.jsx
index 913a90298b..bc5129bca2 100644
--- a/client/src/components/musicVideo/AutoReviewPanel.jsx
+++ b/client/src/components/musicVideo/AutoReviewPanel.jsx
@@ -15,7 +15,12 @@ const STATUS_TONES = {
const CHECK_TONES = { pass: 'bg-port-success/20 text-port-success', fail: 'bg-port-error/20 text-port-error', unverified: 'bg-port-border text-port-text-muted' };
const CHECK_LABELS = { composition: 'Composition', continuity: 'Continuity', motion: 'Motion', audioSync: 'Stream-duration parity', lipSync: 'Temporal lip-sync' };
const ACTION_LABELS = {
- wait: (a) => (a.on === 'generation' ? 'Waiting for the revised sections to generate…' : 'Rendering the draft…'),
+ wait: (a) => {
+ if (a.on !== 'generation') return 'Rendering the draft…';
+ // The server submitted these itself (#10014) — no tab has to stay open.
+ const n = a.submitted?.length || 0;
+ return n ? `Generating ${n} revised section${n === 1 ? '' : 's'}…` : 'Waiting for the revised sections to generate…';
+ },
reviewing: () => 'Reviewing the draft (frames + continuous excerpt)…',
generate: (a) => `Generating ${a.sections?.length || 0} revised section${a.sections?.length === 1 ? '' : 's'}…`,
};
@@ -167,7 +172,7 @@ export default function AutoReviewPanel({ project, startSec, endSec, rangeValid,
</span>
{active && (
<div className="flex items-center gap-2">
- {/* After a reload the board may have missed a hand-out: Continue re-derives the step. */}
+ {/* The server generates a run's revised sections itself; Continue re-derives the step of a run that stalled (e.g. across a restart). */}
{run.status === 'running' && !autoReview.action && (
<button type="button" disabled={busy} onClick={() => autoReview.resume(run.id)} className="flex items-center gap-1 text-port-accent disabled:opacity-50 min-h-[44px] sm:min-h-0"><Play size={12} /> Continue</button>
)}
diff --git a/client/src/components/musicVideo/AutoReviewPanel.test.jsx b/client/src/components/musicVideo/AutoReviewPanel.test.jsx
index 2e0fc2062a..e3c8e25d09 100644
--- a/client/src/components/musicVideo/AutoReviewPanel.test.jsx
+++ b/client/src/components/musicVideo/AutoReviewPanel.test.jsx
@@ -1,9 +1,9 @@
/**
* Auto-review panel (#8988) rendered with the real useMusicVideoAutoReview
* hook over a mocked API and socket: a run starts only with the director's
- * explicit limits, the board submits exactly the sections a run hands out for
- * its own project, and a run stopped at a limit resumes only with the limits
- * the director raised.
+ * explicit limits, the board only REPORTS the sections the server submitted for
+ * its own project (the server generates them, #10014), and a run stopped at a
+ * limit resumes only with the limits the director raised.
*/
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { useState } from 'react';
@@ -41,9 +41,9 @@ const limitRun = {
attempts: [{ n: 1, excerptId: 'mve-1', review: null, revisionId: null }],
};
-function Harness({ initial, submitSections }) {
+function Harness({ initial }) {
const [project, setProject] = useState(initial);
- const autoReview = useMusicVideoAutoReview({ project, replaceProject: setProject, submitSections });
+ const autoReview = useMusicVideoAutoReview({ project, replaceProject: setProject });
return <AutoReviewPanel project={project} startSec={0} endSec={10} rangeValid rendering={false} autoReview={autoReview} />;
}
@@ -54,7 +54,7 @@ beforeEach(() => {
describe('AutoReviewPanel (#8988)', () => {
it('starts a run with the limits the director set, and refuses to start without valid ones', async () => {
api.startMusicVideoAutoReview.mockResolvedValue({ project: baseProject, run: { id: 'mvar-1', status: 'running' } });
- render(<Harness initial={baseProject} submitSections={vi.fn()} />);
+ render(<Harness initial={baseProject} />);
const start = screen.getByRole('button', { name: /start auto-review/i });
fireEvent.change(screen.getByLabelText('Max reviews'), { target: { value: '0' } });
@@ -68,24 +68,22 @@ describe('AutoReviewPanel (#8988)', () => {
));
});
- it('submits exactly the sections a run hands out for THIS project', async () => {
- const submitSections = vi.fn(async () => 1);
- render(<Harness initial={baseProject} submitSections={submitSections} />);
+ it('reports the sections the server itself submitted for THIS project, and never submits from the board (#10014)', async () => {
+ render(<Harness initial={baseProject} />);
const running = { ...limitRun, status: 'running', stopReason: null };
const project = { ...baseProject, autoReviews: [running] };
- const handout = { type: 'generate', revisionId: 'mvr-1', sections: [{ sceneId: 's2', kind: 'video' }] };
+ const submitted = { type: 'wait', on: 'generation', revisionId: 'mvr-1', submitted: [{ sceneId: 's2', kind: 'video', jobId: 'job-1' }] };
- act(() => listeners.get('music-video:auto-review')({ projectId: 'mv-other', run: running, project, action: handout }));
- expect(submitSections).not.toHaveBeenCalled();
+ act(() => listeners.get('music-video:auto-review')({ projectId: 'mv-other', run: running, project, action: submitted }));
+ expect(screen.queryByText(/Generating 1 revised section/)).not.toBeInTheDocument();
- act(() => listeners.get('music-video:auto-review')({ projectId: 'mv-1', run: running, project, action: handout }));
- expect(submitSections).toHaveBeenCalledWith(project, handout.sections, 'mvr-1');
+ act(() => listeners.get('music-video:auto-review')({ projectId: 'mv-1', run: running, project, action: submitted }));
expect(await screen.findByText(/Generating 1 revised section/)).toBeInTheDocument();
});
it('a run stopped at a limit resumes with the raised limit only', async () => {
api.resumeMusicVideoAutoReview.mockResolvedValue({ project: baseProject, run: { ...limitRun, status: 'running' } });
- render(<Harness initial={{ ...baseProject, autoReviews: [limitRun] }} submitSections={vi.fn()} />);
+ render(<Harness initial={{ ...baseProject, autoReviews: [limitRun] }} />);
expect(screen.getByText('Reached the 1-review attempt limit')).toBeInTheDocument();
fireEvent.change(screen.getAllByLabelText('Max reviews')[0], { target: { value: '3' } });
diff --git a/client/src/hooks/README.md b/client/src/hooks/README.md
index c030a7ce56..3f1f24d306 100644
--- a/client/src/hooks/README.md
+++ b/client/src/hooks/README.md
@@ -256,8 +256,8 @@ grep -i "what you want to do" client/src/hooks/README.md
| `useAutonomousMusicVideo` | Fully-autonomous run (prompt → lyrics → Suno song → video): applies the project pushed on `music-video:autonomous` and toasts the outcomes that need the director (checkpoint waiting, needs you, finished, failed). Returns `{ busy, resume(edits?, { inline }?), stop(), cancel() }` (an `inline` resume rejects instead of toasting, for errors shown next to the control). | The Music Video autonomous run panel. |
| `useMusicVideoProduction` | Server-owned production run (#9066): start a browserless plan → frames → clips → reviewed-draft run with an allowed provider/model pool and explicit limits, and Stop / Resume / Cancel it; applies the project pushed on `music-video:production` and toasts terminal outcomes. Returns `{ busy, start(body), resume(runId, body?), stop(runId), cancel(runId) }`. | The Music Video production panel. |
| `useMusicVideoRenderJob` | The final-render job (#1760 Phase 2): kickoff (409 → attach to the existing job), SSE progress, terminal-frame handling and non-terminal stream-close recovery. Thin `useSseJobSlot` adapter with 0–1 progress conversion; returns `{ active, pending, context, job, progress, start(projectId), cancel, reattach(projectId), reattaching }`; a project the server marks `rendering` re-attaches on load through a READ of the live job (`GET /:id/render`), never a POST (#9940); `onSettled(reason, projectId)` fires on every terminal frame; `onRendered(projectId, result)` / `onFailed(projectId)` key on the projectId captured at kickoff. | The Music Video "Render final" control. |
-| `useMusicVideoRevisions` | Selective section revision (#8987): open a revision from a reviewed draft excerpt (its flagged sections' takes are rejected, the rest kept), resume it from the server checkpoint — generating ONLY the sections the server reports as `needsGeneration` through the board's scene lanes, or adopting the draft re-render via `attachRender` once every revised section has a take — and cancel it. A server refusal toasts as a failure; a throw in the hook's own follow-up AFTER the server succeeded reloads the saved record instead (#9940), so an opened repair whose resume failed stays recoverable from the "Needs attention" banner. Returns `{ busy, revise(excerptId, sceneIds?), repair(basis), repairPerformance(sceneId, input), resume(revisionId), cancel(revisionId), submitSections(project, refs, revisionId) }`. | The Music Video excerpt panel. |
-| `useMusicVideoAutoReview` | Opt-in automatic review/retries (#8988): start a run over a draft window with explicit review (`maxAttempts`) and paid-generation (`maxGenerations`) limits plus a vision reviewer; applies the project pushed on `music-video:auto-review` and submits the revised sections a run hands out through `submitSections` while the board is open. Returns `{ busy, action, start(startSec, endSec, limits, reviewer), resume(runId, limits?), stop(runId), cancel(runId) }`. | The Music Video excerpt panel. |
+| `useMusicVideoRevisions` | Selective section revision (#8987): open a revision from a reviewed draft excerpt (its flagged sections' takes are rejected, the rest kept), resume it from the server checkpoint — generating ONLY the sections the server reports as `needsGeneration` through the board's scene lanes, or adopting the draft re-render via `attachRender` once every revised section has a take — and cancel it. A server refusal toasts as a failure; a throw in the hook's own follow-up AFTER the server succeeded reloads the saved record instead (#9940), so an opened repair whose resume failed stays recoverable from the "Needs attention" banner. Returns `{ busy, revise(excerptId, sceneIds?), repair(basis), repairPerformance(sceneId, input), resume(revisionId), cancel(revisionId) }`. | The Music Video excerpt panel. |
+| `useMusicVideoAutoReview` | Opt-in automatic review/retries (#8988): start a run over a draft window with explicit review (`maxAttempts`) and paid-generation (`maxGenerations`) limits plus a vision reviewer; applies the project pushed on `music-video:auto-review` and reports outcomes; the server generates a run's revised sections itself (#10014), so the board never submits them and a run completes with no tab open. Returns `{ busy, action, start(startSec, endSec, limits, reviewer), resume(runId, limits?), stop(runId), cancel(runId) }`. | The Music Video excerpt panel. |
| `useMusicVideoExcerpts` | Draft excerpt render + timecoded review notes (#8986): a `useSseJobSlot` render job over a chosen `[startSec, endSec)` window (any terminal frame reloads the project, since the persisted excerpt shape lives server-side) plus add/edit/delete review-note calls that apply the fresh whole project from each response. Returns `{ rendering, progress, deletingId, noteBusyId, startExcerpt(startSec, endSec), cancelExcerpt(excerptId), attachRender(jobId, projectId), deleteExcerpt(excerptId), addNote(excerptId, {atSec, note, verdict?}), editNote(excerptId, noteId, patch), deleteNote(excerptId, noteId) }`. | The Music Video excerpt panel. |
| `useMusicVideoPublishKit` | Music Video publishing kit (#9281): a `useSseJobSlot` build job (encodes, thumbnails, captions, chapters) whose terminal frame reloads the project, plus the one-call copy draft, per-field copy edits and thumbnail choice, each applying the returned project. Returns `{ building, progress, build(), cancelBuild(), drafting, saving, draftCopy(body), saveCopy(patch), selectThumbnail(filename) }`. | The Music Video Publish stage. |
| `useMusicVideoPublishing` | Music Video posting (#9282): per-platform drafts filled in the PortOS Browser. `prepare` returns the filled draft's summary and screenshot (a sign-in-required refusal is kept as the platform's error with its login URL), `submit` posts that reviewed draft and applies the returned project, `discard` closes it. Platforms are opt-in (#9287): it loads the saved `platforms` (enabled + optional account each) and per-platform `history` (posts, reception tally, recent notes across projects); `setPlatform` toggles one optimistically and `recordPost` saves a hand-made post's link or a post's reception and notes. Returns `{ drafts, busy, errors, prepare(target, options), submit(target), discard(target), platforms, history, enabledTargets, setPlatform(target, change), recordPost(target, body) }`. | The Music Video Publish stage's posting panel. |
diff --git a/client/src/hooks/useMusicVideoAutoReview.js b/client/src/hooks/useMusicVideoAutoReview.js
index fbddfda670..399aed34af 100644
--- a/client/src/hooks/useMusicVideoAutoReview.js
+++ b/client/src/hooks/useMusicVideoAutoReview.js
@@ -21,24 +21,22 @@ const OUTCOME_TOASTS = {
* Opt-in automatic review/retries (#8988). A run is started only by the
* director, with explicit limits on reviews (`maxAttempts`) and paid
* generations (`maxGenerations`); the server then renders the draft window,
- * reviews it, and revises only the flagged sections, reporting each step over
- * the `music-video:auto-review` socket event. This hook applies the pushed
- * project, and — while the board is open — submits the sections a run hands
- * out through the board's normal scene lanes (`submitSections`, from
- * `useMusicVideoRevisions`), tagged with the run's revision so the server's
- * enqueue guard charges them against the spend limit.
+ * reviews it, revises only the flagged sections and generates them itself
+ * (#10014) — so a run completes with no tab open and a tab never submits a
+ * second copy. It reports each step over the `music-video:auto-review` socket
+ * event; this hook only applies the pushed project and surfaces outcomes.
*
* Returns `{ busy, action, start(startSec, endSec, limits, reviewer), resume(runId, limits?), stop(runId), cancel(runId) }`
* — `action` is the latest step the server reported for this project's run.
*/
-export default function useMusicVideoAutoReview({ project, replaceProject, submitSections } = {}) {
+export default function useMusicVideoAutoReview({ project, replaceProject } = {}) {
const projectId = project?.id || null;
const [busy, setBusy] = useState(false);
const [action, setAction] = useState(null);
- const handlers = useRef({ replaceProject, submitSections });
+ const handlers = useRef({ replaceProject });
const lastStatus = useRef(new Map());
useEffect(() => {
- handlers.current = { replaceProject, submitSections };
+ handlers.current = { replaceProject };
});
useEffect(() => {
@@ -46,23 +44,8 @@ export default function useMusicVideoAutoReview({ project, replaceProject, submi
setAction(null);
const onAutoReview = (data) => {
if (data?.projectId !== projectId) return;
- const { replaceProject: replace, submitSections: submit } = handlers.current;
- if (data.project) replace?.(data.project);
+ if (data.project) handlers.current.replaceProject?.(data.project);
setAction(data.action || null);
- // Only a RUNNING run's hand-out is submitted — never one that raced a pause.
- // A run a production owns (#9066) is dispatched by the server, not the board.
- if (data.action?.type === 'generate' && data.run?.status === 'running' && !data.run.productionRunId
- && data.action.sections?.length && submit) {
- // The hand-out is the only thing driving a board-owned run forward, so a
- // throw here must not vanish: say so and point at Continue (#9940).
- // (The executor runs synchronously, so the hand-out starts this tick.)
- new Promise((resolve) => resolve(submit(data.project, data.action.sections, data.action.revisionId))).then((n) => {
- if (n) toast.info(`Auto-review: generating ${n} revised section${n === 1 ? '' : 's'}`);
- }).catch((err) => {
- console.error(`❌ Music Video auto-review hand-out failed: ${err?.message || 'unknown error'}`);
- toast.error(`Auto-review could not start its revised sections (${err?.message || 'unexpected error'}) — use Continue under "Needs attention" to try again.`);
- });
- }
const run = data.run;
if (run?.id && lastStatus.current.get(run.id) !== run.status) {
const seen = lastStatus.current.has(run.id);
diff --git a/client/src/hooks/useMusicVideoAutoReview.test.jsx b/client/src/hooks/useMusicVideoAutoReview.test.jsx
index adc32599e9..f7fea43eaa 100644
--- a/client/src/hooks/useMusicVideoAutoReview.test.jsx
+++ b/client/src/hooks/useMusicVideoAutoReview.test.jsx
@@ -34,38 +34,33 @@ beforeEach(() => {
vi.spyOn(console, 'error').mockImplementation(() => {});
});
-const setup = (submitSections) => {
+const setup = () => {
const replaceProject = vi.fn();
- const hook = renderHook(() => useMusicVideoAutoReview({ project, replaceProject, submitSections }));
+ const hook = renderHook(() => useMusicVideoAutoReview({ project, replaceProject }));
return { ...hook, replaceProject };
};
const flush = () => act(async () => { await new Promise((resolve) => setTimeout(resolve, 0)); });
-it('says so — and points at Continue — when handing out revised sections throws (#9940)', async () => {
- setup(vi.fn(() => Promise.reject(new Error('lane exploded'))));
- act(() => handlers.get('music-video:auto-review')(generateEvent));
- await flush();
- expect(toast.error).toHaveBeenCalledWith(expect.stringContaining('lane exploded'));
- expect(toast.error.mock.calls[0][0]).toContain('Continue');
-});
-
-it('reports how many revised sections the board submitted', async () => {
+it('applies the pushed project and never submits a revised section from the board (#10014)', async () => {
const submitSections = vi.fn(() => Promise.resolve(2));
- setup(submitSections);
- act(() => handlers.get('music-video:auto-review')(generateEvent));
+ const replaceProject = vi.fn();
+ const pushed = { ...project, autoReviews: [] };
+ const { result } = renderHook(() => useMusicVideoAutoReview({ project, replaceProject, submitSections }));
+ // A hand-out with a running run — the shape the board used to submit — is only applied.
+ act(() => handlers.get('music-video:auto-review')({ ...generateEvent, project: pushed }));
await flush();
- expect(submitSections).toHaveBeenCalledWith(project, generateEvent.action.sections, 'mvrev-example');
- expect(toast.info).toHaveBeenCalledWith('Auto-review: generating 2 revised sections');
+ expect(submitSections).not.toHaveBeenCalled();
+ expect(replaceProject).toHaveBeenCalledWith(pushed);
+ expect(result.current.action).toEqual(generateEvent.action);
expect(toast.error).not.toHaveBeenCalled();
});
-it('does not hand out sections for a run a production owns or one that is no longer running', async () => {
- const submitSections = vi.fn(() => Promise.resolve(1));
- setup(submitSections);
- act(() => handlers.get('music-video:auto-review')({ ...generateEvent, run: { ...generateEvent.run, productionRunId: 'mvpr-example' } }));
- act(() => handlers.get('music-video:auto-review')({ ...generateEvent, run: { ...generateEvent.run, status: 'stopped' } }));
+it('ignores another project\'s event', async () => {
+ const { result, replaceProject } = setup();
+ act(() => handlers.get('music-video:auto-review')({ ...generateEvent, projectId: 'mv-other' }));
await flush();
- expect(submitSections).not.toHaveBeenCalled();
+ expect(replaceProject).not.toHaveBeenCalled();
+ expect(result.current.action).toBeNull();
});
it('links a start refused for an open revision to it, reloading the record so the banner can show it', async () => {
@@ -74,7 +69,7 @@ it('links a start refused for an open revision to it, reloading the record so th
startMusicVideoAutoReview.mockRejectedValue(Object.assign(new Error('Finish or cancel the open revision before starting an auto-review run'), {
code: 'REVISION_IN_PROGRESS', context: { revisionId: 'mvrev-open' },
}));
- const { result, replaceProject } = setup(vi.fn());
+ const { result, replaceProject } = setup();
await act(async () => { await result.current.start(0, 10, { maxAttempts: 1, maxGenerations: 1 }); });
expect(getMusicVideoProject).toHaveBeenCalledWith('mv-example', { silent: true });
await flush();
diff --git a/client/src/hooks/useMusicVideoRevisions.js b/client/src/hooks/useMusicVideoRevisions.js
index 95e0b593d0..261934525d 100644
--- a/client/src/hooks/useMusicVideoRevisions.js
+++ b/client/src/hooks/useMusicVideoRevisions.js
@@ -50,10 +50,6 @@ const plural = (n, word) => `${n} ${word}${n === 1 ? '' : 's'}`;
* `replaceProject(project)` swaps the local record whole; `sceneMedia` is the
* `useMusicVideoSceneMedia` result; `attachRender(jobId, projectId)` is
* `useMusicVideoExcerpts().attachRender`.
- *
- * `submitSections(project, refs, revisionId)` exposes the same tagged
- * submission for an auto-review run's hand-outs (#8988); resolves to the
- * number of sections that reached the queue.
*/
export default function useMusicVideoRevisions({ project, replaceProject, sceneMedia, attachRender } = {}) {
const projectId = project?.id || null;
@@ -175,7 +171,5 @@ export default function useMusicVideoRevisions({ project, replaceProject, sceneM
.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.
- return { busy, repair, repairPerformance, revise, resume, cancel, submitSections: generateSections };
+ return { busy, repair, repairPerformance, revise, resume, cancel };
}
diff --git a/client/src/lib/musicVideoAttention.js b/client/src/lib/musicVideoAttention.js
index 165d7536c0..0d1bc3b2e2 100644
--- a/client/src/lib/musicVideoAttention.js
+++ b/client/src/lib/musicVideoAttention.js
@@ -1,7 +1,7 @@
/**
* "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
+ * Cast & Sets stage, a running auto-review that never handed out 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
@@ -87,13 +87,16 @@ export function deriveAttentionItems(project, { generatingSceneIds = null, draft
const owned = revisions.find((r) => r.id === ownedRevisionId);
if (owned?.status === 'open') {
const { rejected } = sectionProgress(project, owned);
- if (!rejected.some((s) => spinning(s.sceneId))) {
+ // The server generates a run's revised sections itself (#10014), so a
+ // claimed section is in flight there even though no spinner on this
+ // board shows it. Only a revision that was never handed out has stalled.
+ if (!rejected.some((s) => spinning(s.sceneId) || s.claimedAt)) {
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.',
+ detail: 'The server generates them as soon as the run reaches this step. If it stalled (for example across a restart), continue to hand them out again — nothing is generated beyond the limits you set for the run.',
runId: liveReview.id,
});
}
diff --git a/client/src/lib/musicVideoAttention.test.js b/client/src/lib/musicVideoAttention.test.js
index c8584b5f9a..1746134c66 100644
--- a/client/src/lib/musicVideoAttention.test.js
+++ b/client/src/lib/musicVideoAttention.test.js
@@ -56,6 +56,16 @@ describe('deriveAttentionItems (#9940)', () => {
expect(deriveAttentionItems(open, { generatingSceneIds: new Set(['scene-c']) })).toHaveLength(1);
});
+ it('does not flag an auto-review whose server already claimed a revised section — it is generating there with no spinner on this board (#10014)', () => {
+ const claimed = revision({ sections: [
+ { sceneId: 'scene-a', kind: 'video', verdict: 'rejected', claimedAt: '2026-01-01T00:00:00.000Z' },
+ { sceneId: 'scene-b', kind: 'image', verdict: 'rejected' },
+ ] });
+ expect(deriveAttentionItems(project({ revisions: [claimed], autoReviews: [run()] }))).toEqual([]);
+ // Never handed out (no section claimed): stalled, so Continue is offered.
+ expect(deriveAttentionItems(project({ revisions: [revision()], autoReviews: [run()] }))).toMatchObject([{ kind: 'auto-review' }]);
+ });
+
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([]);
diff --git a/client/src/pages/MusicVideo.jsx b/client/src/pages/MusicVideo.jsx
index a5cf0f14d4..3cc0a20640 100644
--- a/client/src/pages/MusicVideo.jsx
+++ b/client/src/pages/MusicVideo.jsx
@@ -252,7 +252,7 @@ export default function MusicVideo() {
// Selective section revision (#8987): regenerate only a draft's flagged
// sections, resumable from the server's checkpoint.
const revisions = useMusicVideoRevisions({ project: selected, replaceProject, sceneMedia, attachRender: excerpts.attachRender });
- const autoReview = useMusicVideoAutoReview({ project: selected, replaceProject, submitSections: revisions.submitSections });
+ const autoReview = useMusicVideoAutoReview({ project: selected, replaceProject });
const production = useMusicVideoProduction({ project: selected, replaceProject });
const autonomous = useAutonomousMusicVideo({ project: selected, replaceProject });
// Which finished autonomous stage's output is open (`?run-stage=lyrics`).
diff --git a/docs/features/product-surfaces.md b/docs/features/product-surfaces.md
index 52c0307e4c..6c72ff9926 100644
--- a/docs/features/product-surfaces.md
+++ b/docs/features/product-surfaces.md
@@ -110,7 +110,7 @@ An end-to-end creative production suite for authors, worldbuilders, filmmakers,
| **SongBook** | `/songbook` | Interactive chord charts, guitar tablature, lyric repertoire, and auto-scrolling practice sheet music. | — |
| **Creative Director** | `/creative-director` | Multi-scene episodic video production orchestrator: turn briefs into treatments, storyboards, render plans, and completed episodes. | — |
| **Creative Commissions** | `/creative-commission` | Standing briefs and scheduled/nightly autonomous media generation aligning with personal taste profiles and feedback. A universe and/or mood board can be picked as the style source: each run loads its style tags and reference images as the Creative Director's art-direction base, attaches those images to vision scene evaluation, and conditions local image renders on them. | — |
-| **Music Video Studio** | `/music-video` | A project opens on seven deep-linked stage tabs (`/music-video/:projectId/:stage` — `setup`, `cast-sets`, `board`, `produce`, `compose`, `review`, `publish`; a bottom tab bar on a phone) under a sticky header showing its progress, a one-line status (the stage it is in and whether it needs the director, the autopilot and production runs, the three production approvals, and what has been rendered), paid-generation spend against the cap, and the one next action for the stage it is in; a **Needs attention** banner under that status line lists any state a half-finished workflow left on the server — an open revision, an interrupted Cast & Sets stage, an auto-review waiting for its revised sections, a final render nobody is watching — with its Resume / Continue / Cancel / Reattach inline, derived from the saved record so it survives a reload; a preview player is docked beside every tab whenever anything is playable — the final render, the live composition document and each finished draft excerpt, picked from the dock (`?play=`) — and scene cards seek it. The autopilot run and production approvals fold to a summary line below the stage unless they need the director. Audio-reactive video creation, beat-detection synchronization, scene choreography, tempo alignment, and audience-driven pre-production treatments that direct each shot. Scenes are cutaways or lip-synced performance shots; a performance shot renders only on a verified source-audio provider (fal.ai MiniMax H3 lip-sync, 5–14.8s song slices placed at an exact edit in-point, cut from an optional full-length vocal stem when one is attached — uploaded, or separated from the song with a locally installed demucs) — Grok video is cutaway-only. The autopilot kickoff analyzes the song, imports the linked track's lyric sheet (its `[Verse]`/`[Chorus]` headers and stage directions kept as lyric markers that name the analysis sections and steer shot framing), separates the vocal, aligns every word with local whisper.cpp (large-v3-turbo, downloaded on first use), builds a Cast & Sets check-in (one creative-direction call that interprets the song, then a canonical character sheet, expression and looks sheets, one empty plate per set and in-set tests on the image queue, each later image conditioned on the character sheet; assembled into a self-contained sheet saved as a development artifact), stops for the director's review unless the brief auto-approves it, then plans against the approved references. Development artifacts (check-in sheets, animatics, treatments, storyboards; HTML/Markdown/MP4/PNG/JPG) are versioned per project, reviewed with notes and approve/request-changes, and viewed in a sandboxed viewer at `/music-video/:projectId/:stage/dev/:artifactId` (the stage-less `/music-video/:projectId/dev/:artifactId` still opens it). Draft excerpts are reviewed and selectively revised by hand, or by an opt-in auto-review run bounded by director-set review and paid-generation limits (a frame-only look never passes motion or audio sync). A server-owned production run (`/api/music-video/:id/production-runs`, #9066) plans an empty board, generates missing frames and clips only on a director-allowed image/video provider+model pool, hands the continuous draft to auto-review and dispatches its revisions — within explicit generation, review and (priced routes only) dollar limits, without the browser open, and never resuming on its own after a restart; the song is the sole audio unless a sound-design bed is explicitly chosen to mix under it. A footage or composed render can intercut (#9290): shots are re-cut on the song's section energy (every 2 beats in the loudest quarter, up to every 8 in the quietest) and on sung word onsets, alternating the host shot — a lip-synced take stays in sync — with unshown footage from a cutaway in the same section, so the edit gets faster without generating more clips; an autopilot production run defaults to it unless the director chose one cut per shot. Lyric lines sung two or more times are hooks: the treatment's text cues give them a word-by-word build (#9291) — each word lands on its sung onset in heavy caps, the newest in the accent color. Draft excerpts can be re-framed as vertical or square social cuts with faded audio edges, from suggested hook windows (#9280). The **Autonomous** entry point (`docs/features/music-video-autonomous.md`) starts from one prompt instead of a chosen track: it writes the brief, lyrics and a mood board, makes the song in Suno through the PortOS Browser, and runs the production — with optional approval checkpoints, and a `music-video-autopilot` scheduled task that turns unused Brain ideas into videos. The Publish stage (#9281) builds a release kit from the final render: an X-sized 1080p, a 720p preview, a hook teaser, thumbnail candidates, lyric captions (SRT) and YouTube chapters. It also drafts every platform's copy in one director-triggered provider call from their own making-of notes, and every field stays editable. Posting (#9282) fills each platform's post (YouTube, Suno, an X thread, Shorts, TikTok, Instagram Reels, Reddit, Stacker News) in a new PortOS Browser tab with the director's signed-in sessions, shows a screenshot and summary of the filled draft, and posts only when the director presses Post for that draft; the posted links are kept on the project. Reddit defaults to a native video post in r/aivideo — title and flair, no body — through the new composer's own Video button (#9307). Platforms are opt-in (#9287): a "Where you post" list turns each one on (all start off) and optionally names the account posted as — X and Reddit drafts filled while signed in as someone else are refused. Copy is drafted and posts are offered only for enabled platforms. Each post (including one recorded by hand) can be rated good, mixed or poor with notes; ratings roll up per platform across projects and are passed to later copy drafts. | — |
+| **Music Video Studio** | `/music-video` | A project opens on seven deep-linked stage tabs (`/music-video/:projectId/:stage` — `setup`, `cast-sets`, `board`, `produce`, `compose`, `review`, `publish`; a bottom tab bar on a phone) under a sticky header showing its progress, a one-line status (the stage it is in and whether it needs the director, the autopilot and production runs, the three production approvals, and what has been rendered), paid-generation spend against the cap, and the one next action for the stage it is in; a **Needs attention** banner under that status line lists any state a half-finished workflow left on the server — an open revision, an interrupted Cast & Sets stage, an auto-review waiting for its revised sections, a final render nobody is watching — with its Resume / Continue / Cancel / Reattach inline, derived from the saved record so it survives a reload; a preview player is docked beside every tab whenever anything is playable — the final render, the live composition document and each finished draft excerpt, picked from the dock (`?play=`) — and scene cards seek it. The autopilot run and production approvals fold to a summary line below the stage unless they need the director. Audio-reactive video creation, beat-detection synchronization, scene choreography, tempo alignment, and audience-driven pre-production treatments that direct each shot. Scenes are cutaways or lip-synced performance shots; a performance shot renders only on a verified source-audio provider (fal.ai MiniMax H3 lip-sync, 5–14.8s song slices placed at an exact edit in-point, cut from an optional full-length vocal stem when one is attached — uploaded, or separated from the song with a locally installed demucs) — Grok video is cutaway-only. The autopilot kickoff analyzes the song, imports the linked track's lyric sheet (its `[Verse]`/`[Chorus]` headers and stage directions kept as lyric markers that name the analysis sections and steer shot framing), separates the vocal, aligns every word with local whisper.cpp (large-v3-turbo, downloaded on first use), builds a Cast & Sets check-in (one creative-direction call that interprets the song, then a canonical character sheet, expression and looks sheets, one empty plate per set and in-set tests on the image queue, each later image conditioned on the character sheet; assembled into a self-contained sheet saved as a development artifact), stops for the director's review unless the brief auto-approves it, then plans against the approved references. Development artifacts (check-in sheets, animatics, treatments, storyboards; HTML/Markdown/MP4/PNG/JPG) are versioned per project, reviewed with notes and approve/request-changes, and viewed in a sandboxed viewer at `/music-video/:projectId/:stage/dev/:artifactId` (the stage-less `/music-video/:projectId/dev/:artifactId` still opens it). Draft excerpts are reviewed and selectively revised by hand, or by an opt-in auto-review run bounded by director-set review and paid-generation limits (a frame-only look never passes motion or audio sync). A run started from the board generates its revised sections on the server too (#10014), routed from the project's saved image and video pins, so it completes with no tab open; a section that cannot be generated unattended (a synchronous image backend, a clip lane only the board can submit) parks the run as needing the director, with the reason named. A server-owned production run (`/api/music-video/:id/production-runs`, #9066) plans an empty board, generates missing frames and clips only on a director-allowed image/video provider+model pool, hands the continuous draft to auto-review and dispatches its revisions — within explicit generation, review and (priced routes only) dollar limits, without the browser open, and never resuming on its own after a restart; the song is the sole audio unless a sound-design bed is explicitly chosen to mix under it. A footage or composed render can intercut (#9290): shots are re-cut on the song's section energy (every 2 beats in the loudest quarter, up to every 8 in the quietest) and on sung word onsets, alternating the host shot — a lip-synced take stays in sync — with unshown footage from a cutaway in the same section, so the edit gets faster without generating more clips; an autopilot production run defaults to it unless the director chose one cut per shot. Lyric lines sung two or more times are hooks: the treatment's text cues give them a word-by-word build (#9291) — each word lands on its sung onset in heavy caps, the newest in the accent color. Draft excerpts can be re-framed as vertical or square social cuts with faded audio edges, from suggested hook windows (#9280). The **Autonomous** entry point (`docs/features/music-video-autonomous.md`) starts from one prompt instead of a chosen track: it writes the brief, lyrics and a mood board, makes the song in Suno through the PortOS Browser, and runs the production — with optional approval checkpoints, and a `music-video-autopilot` scheduled task that turns unused Brain ideas into videos. The Publish stage (#9281) builds a release kit from the final render: an X-sized 1080p, a 720p preview, a hook teaser, thumbnail candidates, lyric captions (SRT) and YouTube chapters. It also drafts every platform's copy in one director-triggered provider call from their own making-of notes, and every field stays editable. Posting (#9282) fills each platform's post (YouTube, Suno, an X thread, Shorts, TikTok, Instagram Reels, Reddit, Stacker News) in a new PortOS Browser tab with the director's signed-in sessions, shows a screenshot and summary of the filled draft, and posts only when the director presses Post for that draft; the posted links are kept on the project. Reddit defaults to a native video post in r/aivideo — title and flair, no body — through the new composer's own Video button (#9307). Platforms are opt-in (#9287): a "Where you post" list turns each one on (all start off) and optionally names the account posted as — X and Reddit drafts filled while signed in as someone else are refused. Copy is drafted and posts are offered only for enabled platforms. Each post (including one recorded by hand) can be rated good, mixed or poor with notes; ratings roll up per platform across projects and are passed to later copy drafts. | — |
| **Sharing & Conflict Resolution** | `/sharing`, `/sharing/duplicates`, `/sharing/conflicts` | Collaborative asset exchange via cloud storage buckets (Google Drive, Dropbox, iCloud, Syncthing) with duplicate reconciliation and conflict recovery journals. | — |
---
diff --git a/server/routes/musicVideoAutoReview.test.js b/server/routes/musicVideoAutoReview.test.js
index c7b8779147..da70227783 100644
--- a/server/routes/musicVideoAutoReview.test.js
+++ b/server/routes/musicVideoAutoReview.test.js
@@ -39,7 +39,7 @@ const h = vi.hoisted(() => {
return p;
};
return {
- procs, spawn, jobs: [], verdicts: [], review: null, temporalInstalled: false, temporalCapability: null, temporalResult: null, temporalCalls: [], analysisAvailable: true, freezeStderr: '',
+ procs, spawn, jobs: [], verdicts: [], settings: null, submitError: null, submits: [], review: null, temporalInstalled: false, temporalCapability: null, temporalResult: null, temporalCalls: [], analysisAvailable: true, freezeStderr: '',
};
});
@@ -75,7 +75,7 @@ vi.mock('../lib/ffmpeg.js', async (importOriginal) => {
probeVideoStreamInfo: vi.fn(async () => ({ width: 640, height: 360, fps: 24, frameCount: null })),
};
});
-vi.mock('../lib/sseUtils.js', () => ({ broadcastSse: vi.fn(), attachSseClient: vi.fn(() => true), closeJobAfterDelay: vi.fn() }));
+vi.mock('../lib/sseUtils.js', async (importOriginal) => ({ ...(await importOriginal()), broadcastSse: vi.fn(), attachSseClient: vi.fn(() => true), closeJobAfterDelay: vi.fn() }));
vi.mock('../services/instanceIdentity.js', () => ({ ensureInstanceId: vi.fn(async () => 'inst-test') }));
vi.mock('../lib/killWithEscalation.js', () => ({ killWithEscalation: vi.fn((proc) => proc.emit('close', null, 'SIGTERM')) }));
// Real sheet files, so the reviewer sees a non-empty continuous strip.
@@ -87,9 +87,31 @@ vi.mock('../services/htmlComposition/encode.js', async () => {
vi.mock('../services/mediaJobQueue/index.js', async () => ({
mediaJobEvents: new (await import('events')).EventEmitter(),
listJobs: vi.fn(({ kind } = {}) => h.jobs.filter((j) => !kind || j.kind === kind)),
- enqueueJob: vi.fn(),
+ // The frame lane's queue write — the revision guard already ran in front of it.
+ enqueueJob: vi.fn(async ({ kind, params, owner }) => {
+ const job = { id: `job-${h.jobs.length + 1}`, kind, owner, status: 'queued', queuedAt: new Date().toISOString(), params };
+ h.jobs.push(job);
+ return { jobId: job.id };
+ }),
cancelJob: vi.fn(async () => {}),
}));
+// The video submit service's contract the dispatch relies on: the revision guard
+// runs last before the queue write; a refusal never reaches the queue.
+vi.mock('../services/videoGen/submitJob.js', () => ({
+ submitVideoGenJob: vi.fn(async (body) => {
+ h.submits.push(body);
+ if (h.submitError) throw h.submitError;
+ const { assertRevisionOpen: guard } = await import('../services/musicVideo/revisionService.js');
+ await guard(body.musicVideo.projectId, body.musicVideo.revisionId, { sceneId: body.musicVideo.sceneId, kind: 'video' });
+ const job = { id: `job-${h.jobs.length + 1}`, kind: 'video', status: 'queued', queuedAt: new Date().toISOString(), params: { musicVideo: body.musicVideo } };
+ h.jobs.push(job);
+ return { jobId: job.id };
+ }),
+}));
+vi.mock('../services/settings.js', async (importOriginal) => ({ ...(await importOriginal()), getSettings: vi.fn(async () => h.settings) }));
+vi.mock('../services/videoGen/modelSelection.js', () => ({
+ resolveVideoModelSelection: vi.fn(async () => ({ model: { id: 'ltx-example' }, modelId: 'ltx-example' })),
+}));
vi.mock('../services/promptRunner.js', () => ({
resolveProviderAndModel: vi.fn(async () => ({ provider: { id: 'reviewer', name: 'Reviewer', type: 'api' }, selectedModel: 'vision-1' })),
assertVisionRunUsedImages: vi.fn((_result, provider) => provider),
@@ -172,6 +194,9 @@ beforeEach(() => {
h.jobs.length = 0;
h.verdicts.length = 0;
h.analysisAvailable = true;
+ h.settings = { imageGen: { mode: 'local', local: { pythonPath: '/opt/example/python' }, codex: { enabled: true } } };
+ h.submitError = null;
+ h.submits.length = 0;
h.freezeStderr = '';
h.temporalInstalled = false;
h.temporalCapability = { protocolVersion: 1, id: 'example-analyzer', version: '1.0', ready: true, temporalLipSync: true, localOnly: true };
@@ -218,12 +243,14 @@ describe('opt-in automatic review/retries (#8988)', () => {
const revision = current.revisions.find((rv) => rv.id === attempt1.revisionId);
expect(revision.sections.filter((s) => s.verdict === 'rejected').map((s) => s.sceneId)).toEqual(['s2']);
- // The board submits s2: the enqueue guard charges it. A double submit
- // while its job is live, and any further paid job past the run's spend
- // limit, are refused BEFORE they reach the queue.
+ // The server submits s2 itself — no board is connected: the enqueue guard
+ // charged it, and tagged it with the revision. A double submit while its
+ // job is live, and any further paid job past the run's spend limit, are
+ // refused BEFORE they reach the queue.
const s2 = { sceneId: 's2', kind: 'video' };
- await assertRevisionOpen(p.id, revision.id, s2);
- h.jobs.push({ id: 'job-s2', kind: 'video', status: 'running', queuedAt: new Date().toISOString(), params: { musicVideo: { projectId: p.id, sceneId: 's2', revisionId: revision.id } } });
+ await vi.waitFor(() => expect(h.jobs).toHaveLength(1), { timeout: 5000, interval: 20 });
+ expect(h.submits).toHaveLength(1);
+ expect(h.submits[0]).toMatchObject({ backend: 'local', mode: 'image', sourceImageFile: 'f2.png', musicVideo: { projectId: p.id, sceneId: 's2', revisionId: revision.id } });
await expect(assertRevisionOpen(p.id, revision.id, s2)).rejects.toMatchObject({ code: 'AUTO_REVIEW_SECTION_IN_FLIGHT' });
await expect(assertRevisionOpen(p.id, revision.id, { sceneId: 's1', kind: 'video' })).rejects.toMatchObject({ code: 'AUTO_REVIEW_SPEND_LIMIT' });
h.jobs[0].status = 'completed';
@@ -249,6 +276,8 @@ describe('opt-in automatic review/retries (#8988)', () => {
let current = await settled(p.id, (x) => expect(run(x).attempts[0].revisionId).toBeTruthy());
const runId = run(current).id;
const reviewed = run(current).attempts[0].review;
+ // The server submits the flagged section before the director pauses.
+ await vi.waitFor(() => expect(h.jobs).toHaveLength(1), { timeout: 5000, interval: 20 });
expect((await request(app).post(`${base(p.id)}/auto-reviews/${runId}/stop`)).body.run.status).toBe('stopped');
// The take the board already paid for still lands — but a stopped run
@@ -269,41 +298,101 @@ describe('opt-in automatic review/retries (#8988)', () => {
current = await settled(p.id, (x) => expect(run(x).status).toBe('passed'));
expect(runPromptThroughProvider).toHaveBeenCalledTimes(2);
expect(run(current).attempts[0].review).toEqual(reviewed);
- expect(run(current).usage).toEqual({ reviews: 2, generations: 0 });
+ // The one generation was the server's own submission of the flagged section
+ // (before the pause); resuming does not pay for it again.
+ expect(run(current).usage).toEqual({ reviews: 2, generations: 1 });
+ expect(h.submits).toHaveLength(1);
expect(h.procs).toHaveLength(2);
});
- it('refunds a kickoff that never reached the queue, and pauses (not retries) when a revised generation fails', async () => {
+ it('pauses (not retries) when a server-submitted revised generation fails', async () => {
const p = await project();
h.verdicts.push(FAIL_S2);
await start(p.id, { maxAttempts: 2, maxGenerations: 2 });
await finishDraft(p.id, 1);
let current = await settled(p.id, (x) => expect(run(x).attempts[0].revisionId).toBeTruthy());
const revisionId = run(current).attempts[0].revisionId;
- const s2 = { sceneId: 's2', kind: 'video' };
-
- // The board's kickoff was charged but failed before the queue: releasing
- // the section returns the generation to the budget.
- await assertRevisionOpen(p.id, revisionId, s2);
+ await vi.waitFor(() => expect(h.jobs).toHaveLength(1), { timeout: 5000, interval: 20 });
expect(run(await projects.getProject(p.id)).usage.generations).toBe(1);
- await request(app).post(`${base(p.id)}/revisions/${revisionId}/release`).send({ sceneId: 's2' });
- expect(run(await projects.getProject(p.id)).usage.generations).toBe(0);
- // Resubmitted, queued, and the provider fails it: the run pauses for the
- // director instead of paying for a retry on its own.
- await assertRevisionOpen(p.id, revisionId, s2);
- const job = { id: 'job-s2', kind: 'video', status: 'failed', error: 'provider error', queuedAt: new Date().toISOString(), params: { musicVideo: { projectId: p.id, sceneId: 's2', revisionId } } };
+ // The provider fails the queued job: the run pauses for the director
+ // instead of paying for a retry on its own.
+ const job = { ...h.jobs[0], status: 'failed', error: 'provider error' };
mediaJobEvents.emit('failed', job);
current = await settled(p.id, (x) => expect(run(x).status).toBe('stopped'));
expect(run(current).stopReason).toMatch(/generation failed: provider error/);
expect(run(current).usage.generations).toBe(1);
expect(current.revisions.find((rv) => rv.id === revisionId).sections.find((s) => s.sceneId === 's2').claimedAt).toBeNull();
// That job DID reach the queue, so a later release never refunds it.
- h.jobs.push(job);
await request(app).post(`${base(p.id)}/revisions/${revisionId}/release`).send({ sceneId: 's2' });
expect(run(await projects.getProject(p.id)).usage.generations).toBe(1);
});
+ it('parks the run needs-human and refunds the charge when a revised section cannot reach the queue', async () => {
+ const p = await project();
+ h.verdicts.push(FAIL_S2);
+ h.submitError = Object.assign(new Error('The local video runtime refused the clip'), { status: 422, code: 'VIDEO_INVALID' });
+ await start(p.id, { maxAttempts: 2, maxGenerations: 2 });
+ await finishDraft(p.id, 1);
+ const current = await settled(p.id, (x) => expect(run(x).status).toBe('needs-human'));
+ expect(run(current).stopReason).toMatch(/clip for "s2" was refused: The local video runtime refused the clip/);
+ expect(h.jobs).toHaveLength(0);
+ expect(run(current).usage.generations).toBe(0); // never reached the queue → nothing spent
+ // Released, so resuming the revision hands it straight out again once the cause is fixed.
+ const revision = current.revisions.find((rv) => rv.id === run(current).attempts[0].revisionId);
+ expect(revision.status).toBe('open');
+ expect(revision.sections.find((s) => s.sceneId === 's2').claimedAt).toBeNull();
+ // Once the cause is fixed, resuming the open revision (the banner's Continue) re-derives the step and hands the section out again.
+ const resumed = await request(app).post(`${base(p.id)}/revisions/${revision.id}/resume`);
+ expect(resumed.body.needsGeneration).toEqual([expect.objectContaining({ sceneId: 's2', kind: 'video' })]);
+ });
+
+ it('parks the run needs-human, naming the section, when its clip cannot be generated without the board', async () => {
+ const p = await project();
+ await projects.updateProject(p.id, { videoSettings: { backend: 'local', generationMode: 'audioReactive' } });
+ h.verdicts.push(FAIL_S2);
+ await start(p.id, { maxAttempts: 2, maxGenerations: 2 });
+ await finishDraft(p.id, 1);
+ const current = await settled(p.id, (x) => expect(run(x).status).toBe('needs-human'));
+ expect(run(current).stopReason).toMatch(/clip for "s2" cannot be generated automatically: .*audio-reactive/);
+ expect(h.submits).toHaveLength(0);
+ expect(h.jobs).toHaveLength(0);
+ expect(run(current).usage.generations).toBe(0);
+ });
+
+ it('parks the run needs-human when the pinned video backend is not usable here, never substituting another', async () => {
+ vi.stubEnv('FAL_KEY', '');
+ const p = await project();
+ await projects.updateProject(p.id, { videoSettings: { backend: 'fal' } });
+ h.verdicts.push(FAIL_S2);
+ await start(p.id, { maxAttempts: 2, maxGenerations: 2 });
+ await finishDraft(p.id, 1);
+ const current = await settled(p.id, (x) => expect(run(x).status).toBe('needs-human'));
+ expect(run(current).stopReason).toMatch(/clip for "s2" cannot be generated automatically: .*fal.*not usable/);
+ expect(h.submits).toHaveLength(0);
+ expect(run(current).usage.generations).toBe(0);
+ vi.unstubAllEnvs();
+ });
+
+ it('dispatches a revised frame on the project\'s pinned image backend, tagged and charged like the board\'s lane', async () => {
+ const p = await project();
+ await projects.updateProject(p.id, { imageMode: 'codex' });
+ // A blocking problem at excerpt time 17s — inside the still s3 (song time 22s).
+ h.verdicts.push({ ...FAIL_S2, findings: [{ ...FAIL_S2.findings[0], atSec: 17 }] });
+ await start(p.id, { maxAttempts: 2, maxGenerations: 2 });
+ await finishDraft(p.id, 1);
+ const current = await settled(p.id, (x) => expect(run(x).attempts[0].revisionId).toBeTruthy());
+ const revisionId = run(current).attempts[0].revisionId;
+ expect(current.revisions.find((rv) => rv.id === revisionId).sections.filter((s) => s.verdict === 'rejected')).toEqual([expect.objectContaining({ sceneId: 's3', kind: 'image' })]);
+
+ await vi.waitFor(() => expect(h.jobs).toHaveLength(1), { timeout: 5000, interval: 20 });
+ expect(h.submits).toHaveLength(0); // a frame never touches the video lane
+ expect(h.jobs[0]).toMatchObject({ kind: 'image', owner: `music-video-auto-review:${revisionId}`, params: { mode: 'codex', musicVideo: { projectId: p.id, sceneId: 's3', revisionId } } });
+ expect(run(await projects.getProject(p.id)).usage.generations).toBe(1);
+ // The same section is not handed out twice while its job is live.
+ await expect(assertRevisionOpen(p.id, revisionId, { sceneId: 's3', kind: 'image' })).rejects.toMatchObject({ code: 'AUTO_REVIEW_SECTION_IN_FLIGHT' });
+ });
+
it('cancelling a run closes its open revision in the same write — nothing more is charged or allowed', async () => {
const p = await project();
h.verdicts.push(FAIL_S2);
diff --git a/server/services/musicVideo/autoReviewDispatch.js b/server/services/musicVideo/autoReviewDispatch.js
new file mode 100644
index 0000000000..c69eb81eeb
--- /dev/null
+++ b/server/services/musicVideo/autoReviewDispatch.js
@@ -0,0 +1,127 @@
+/**
+ * Music Video auto-review (#10014) — server-side dispatch of a STANDALONE run's
+ * revised sections.
+ *
+ * A run a production owns has its hand-outs dispatched by productionService
+ * (a pool route per step). A run the director started from the board has no
+ * pool, so its sections are generated here, without a browser: the board's two
+ * scene lanes, routed from the project's SAVED pins — the frame backend from
+ * the project's image pin through the MUSIC_VIDEO render target, the clip
+ * backend/model/fal options from `project.videoSettings` (a blank pin is the
+ * director's "follow the install default" choice, resolved exactly as the
+ * board's own request would be). The submission itself is the production
+ * lane (`dispatchProductionStep`), tagged with the run's revision so the
+ * revision guard still charges every job against `limits.maxGenerations`.
+ *
+ * A section this server cannot generate is NEVER skipped silently: dispatch
+ * stops and returns `halt` with the specific reason, and every section that
+ * did not reach the queue has its claim released (and its charge refunded) so
+ * the director can fix the cause and resume the revision.
+ */
+
+import { shotActionContractProblem } from '../../lib/musicVideoActionContract.js';
+import { QUEUEABLE_IMAGE_MODES, IMAGE_GEN_MODE } from '../../lib/generationModes.js';
+import { RENDER_TARGET, recordRenderPin } from '../../lib/renderTargets.js';
+import { getProject } from './projects.js';
+import { releaseRevisionSection } from './revisionService.js';
+import { dispatchProductionStep } from './productionDispatch.js';
+import { loadPoolEnv, routeUnavailableReason, sceneRequirement } from './productionPool.js';
+
+const unavailable = (reason) => ({ reason });
+
+/** The frame route a standalone run renders on: the project's image pin, then the MUSIC_VIDEO target, then the install default. */
+async function frameRoute(project, env) {
+ const [{ resolveRenderTargetConfig }, { selectLocalImageModelFromSettings }] = await Promise.all([
+ import('../imageGen/cloudProviderConfig.js'),
+ import('../imageGen/prepareParams.js'),
+ ]);
+ const pin = recordRenderPin(project);
+ const resolved = resolveRenderTargetConfig(env.settings, RENDER_TARGET.MUSIC_VIDEO, {
+ recordMode: pin.mode, recordModel: pin.modelId, fallbackMode: IMAGE_GEN_MODE.EXTERNAL, usableInstallFallback: true,
+ });
+ if (!QUEUEABLE_IMAGE_MODES.includes(resolved.mode)) {
+ return unavailable(`The ${resolved.mode} image backend renders synchronously and cannot run unattended — pin a queued frame backend, or generate this frame on the board`);
+ }
+ const model = resolved.mode === IMAGE_GEN_MODE.LOCAL
+ ? selectLocalImageModelFromSettings(env.settings, '', env.imageModels || [], resolved.modelCandidates)?.id || null
+ : resolved.cloud?.modelOverride || null;
+ return { route: { kind: 'image', mode: resolved.mode, model } };
+}
+
+/** The clip route a standalone run renders on: the project's saved video pin, or the ladder the board's blank pin resolves through. */
+async function clipRoute(project, env) {
+ const pin = project.videoSettings || {};
+ // The audio-reactive lane conditions every clip on a LoRA the board detects
+ // in its own catalog and sends with the request; it has no server-side route.
+ if (pin.backend === 'local' && pin.generationMode === 'audioReactive') {
+ return unavailable('This project renders clips in the audio-reactive lane, which only the board can submit — switch the video renderer, or generate this clip on the board');
+ }
+ const { resolveVideoMode } = await import('../videoGen/modes.js');
+ const mode = pin.backend || resolveVideoMode(null, env.settings, { target: RENDER_TARGET.MUSIC_VIDEO });
+ return { route: { kind: 'video', mode, model: mode === 'local' ? pin.modelId || null : null } };
+}
+
+/** Plan one section: `{ stepKind, route }` it can be submitted on, or `{ reason }` it cannot. */
+async function planSection(project, section, env) {
+ const scene = (project.scenes || []).find((entry) => entry.sceneId === section.sceneId);
+ if (!scene) return unavailable('its scene no longer exists');
+ const problem = shotActionContractProblem(scene.direction?.actionContract, scene);
+ if (problem) return unavailable(problem);
+ const stepKind = section.kind === 'image' ? 'frame' : 'clip';
+ const planned = stepKind === 'frame' ? await frameRoute(project, env) : await clipRoute(project, env);
+ if (planned.reason) return planned;
+ const refused = await routeUnavailableReason(planned.route, sceneRequirement(project, scene, stepKind), env);
+ return refused ? unavailable(refused) : { scene, stepKind, route: planned.route };
+}
+
+const label = (project, sceneId) => {
+ const scene = (project?.scenes || []).find((entry) => entry.sceneId === sceneId);
+ return `"${scene?.label || sceneId}"`;
+};
+
+/** How a refused submission stops the run: a spent limit is `limit-reached`; everything else needs the director. */
+const haltFor = (err, reason) => (err?.code === 'AUTO_REVIEW_SPEND_LIMIT'
+ ? { status: 'limit-reached', reason: err.message }
+ : { status: 'needs-human', reason });
+
+/**
+ * Submit `sections` (`[{ sceneId, kind: 'image'|'video' }]`, already claimed by
+ * `resumeRevision`) for the revision `revisionId` of a standalone run.
+ *
+ * Returns `{ submitted: [{ sceneId, kind, jobId }], halt }` — `halt` is
+ * `{ status, reason }` when a section could not be submitted (the run must
+ * stop), else null. Sections submitted before the refusal stay in flight; the
+ * refused one and every later one are released.
+ */
+export async function dispatchRevisedSections({ projectId, revisionId, sections }) {
+ const release = (pending) => Promise.all(pending.map((section) => releaseRevisionSection(projectId, revisionId, section.sceneId).catch(() => {})));
+ const env = await loadPoolEnv().catch((err) => ({ error: err }));
+ if (env.error) {
+ await release(sections);
+ return { submitted: [], halt: { status: 'needs-human', reason: `The revised sections could not be prepared for generation: ${env.error.message}` } };
+ }
+ const project = await getProject(projectId);
+ const submitted = [];
+ for (let i = 0; i < sections.length; i += 1) {
+ const section = sections[i];
+ const plan = project
+ ? await planSection(project, section, env).catch((err) => unavailable(err.message))
+ : unavailable('the project no longer exists');
+ const stopWith = async (halt) => {
+ // Sections already submitted stay in flight; this one and every later one are released.
+ await release(sections.slice(i));
+ return { submitted, halt };
+ };
+ if (plan.reason) {
+ return stopWith({ status: 'needs-human', reason: `The ${section.kind === 'image' ? 'frame' : 'clip'} for ${label(project, section.sceneId)} cannot be generated automatically: ${plan.reason}` });
+ }
+ const tag = { projectId, sceneId: section.sceneId, revisionId };
+ const sent = await dispatchProductionStep({ stepKind: plan.stepKind, project, scene: plan.scene, route: plan.route, tag, settings: env.settings })
+ .catch((err) => ({ error: err }));
+ // A job for this section is already live (an earlier hand-out of it): it is paid for and running.
+ if (sent.error?.code === 'AUTO_REVIEW_SECTION_IN_FLIGHT') continue;
+ if (sent.error) return stopWith(haltFor(sent.error, `The ${plan.stepKind} for ${label(project, section.sceneId)} was refused: ${sent.error.message}`));
+ submitted.push({ sceneId: section.sceneId, kind: section.kind, jobId: sent.jobId });
+ }
+ return { submitted, halt: null };
+}
diff --git a/server/services/musicVideo/autoReviewService.js b/server/services/musicVideo/autoReviewService.js
index 868e99647f..104e4ba65b 100644
--- a/server/services/musicVideo/autoReviewService.js
+++ b/server/services/musicVideo/autoReviewService.js
@@ -5,14 +5,14 @@
*
* `advanceAutoReview` derives the run's next step from the record and keeps
* taking steps until the run has to wait: for a draft render, for generation
- * jobs, or for the director's board to submit the sections it hands out
- * (generation goes through the board's normal scene lanes, tagged with the
- * run's revision — the same path a manual #8987 revision uses, so every job
- * passes the enqueue-time spend check in `assertRevisionOpen`).
+ * jobs. A board-owned run submits its revised sections itself, server-side
+ * (autoReviewDispatch.js, #10014), so it completes with no browser open; a
+ * production-owned run's hand-outs are dispatched by productionService. Every
+ * job is tagged with the run's revision, so it passes the enqueue-time spend
+ * check in `assertRevisionOpen`.
*
* What moves a run forward:
- * - the director — start, resume (and the board submitting handed-out
- * sections);
+ * - the director — start, resume;
* - completion events of work THIS run put in flight: its draft render
* finishing (`excerpt-render`) or a take landing on one of its revised
* sections (`scene-image` / `scene-video`).
@@ -339,9 +339,25 @@ async function takeSteps(projectId, runId) {
const current = findRun(fresh, runId);
// Paused or cancelled while the revision resumed: hand nothing out.
if (current.status !== 'running') return { project: fresh, run: current, action: { type: 'idle' } };
- if (resumed.needsGeneration.length) {
+ if (resumed.needsGeneration.length && run.productionRunId) {
+ // A production-owned run's hand-out is dispatched by productionService.
return { project: fresh, run: current, action: { type: 'generate', revisionId: step.revisionId, sections: resumed.needsGeneration } };
}
+ if (resumed.needsGeneration.length) {
+ // A board-owned run generates its own revised sections here, so it
+ // completes with no browser open (#10014).
+ const { dispatchRevisedSections } = await import('./autoReviewDispatch.js');
+ const sent = await dispatchRevisedSections({ projectId, revisionId: step.revisionId, sections: resumed.needsGeneration });
+ const after = await requireProject(projectId);
+ const latest = findRun(after, runId);
+ if (latest.status !== 'running') return { project: after, run: latest, action: { type: 'idle' } };
+ if (sent.halt) {
+ const out = await halt(projectId, runId, sent.halt);
+ return { ...out, action: { type: 'idle' } };
+ }
+ console.log(`🎬 Music Video auto-review ${short(runId)} submitted ${sent.submitted.length} revised section${sent.submitted.length === 1 ? '' : 's'}`);
+ return { project: after, run: latest, action: { type: 'wait', on: 'generation', revisionId: step.revisionId, submitted: sent.submitted } };
+ }
return { project: fresh, run: current, action: { type: 'wait', on: 'generation', revisionId: step.revisionId } };
}
diff --git a/server/services/musicVideo/productionDispatch.js b/server/services/musicVideo/productionDispatch.js
index ebb89eaca2..4fe1ab1609 100644
--- a/server/services/musicVideo/productionDispatch.js
+++ b/server/services/musicVideo/productionDispatch.js
@@ -19,6 +19,10 @@ import { currentPlateEvidence } from '../../lib/musicVideoPlateEvidence.js';
*
* A step carrying a `revisionId` (the review's revision of a failed section)
* passes the revision's enqueue-time guard first, exactly as the routes do.
+ *
+ * A STANDALONE auto-review run's revised sections (#10014) ride the same
+ * lanes with a tag that names no production run: only the production-step
+ * reservation is skipped, the revision guard still charges the spend limit.
*/
import { withMusicVideoStyle } from './styleReferences.js';
@@ -76,9 +80,12 @@ async function dispatchFrame({ project, scene, route, tag, settings }) {
: { pythonPath: settings.imageGen?.local?.pythonPath || null, modelId: route.model, ...common };
const params = await withMusicVideoStyle(project, baseParams, route.mode, route.model, settings);
await guardRevision(tag, 'image');
- const { assertProductionSubmission } = await import('./productionService.js');
- await assertProductionSubmission(tag.projectId, tag.productionRunId, tag.productionStepKey, { sceneId: tag.sceneId, kind: 'image' });
- const { jobId } = await enqueueJob({ kind: 'image', params, owner: `music-video-production:${tag.productionRunId}` });
+ if (tag.productionRunId) {
+ const { assertProductionSubmission } = await import('./productionService.js');
+ await assertProductionSubmission(tag.projectId, tag.productionRunId, tag.productionStepKey, { sceneId: tag.sceneId, kind: 'image' });
+ }
+ const owner = tag.productionRunId ? `music-video-production:${tag.productionRunId}` : `music-video-auto-review:${tag.revisionId}`;
+ const { jobId } = await enqueueJob({ kind: 'image', params, owner });
return { jobId };
}
@@ -127,7 +134,8 @@ async function dispatchClip({ project, scene, route, tag }) {
/**
* Dispatch one production step. `tag` is the full `musicVideo` job tag
* (`projectId`, `sceneId`, `productionRunId`, `productionStepKey`, optional
- * `revisionId`). Returns `{ jobId }`; throws when the submission is refused.
+ * `revisionId`; a standalone auto-review section carries only `projectId`,
+ * `sceneId` and `revisionId`). Returns `{ jobId }`; throws when the submission is refused.
*/
export async function dispatchProductionStep({ stepKind, project, scene, route, tag, settings }) {
return stepKind === 'frame'
diff --git a/server/services/musicVideo/productionDispatch.test.js b/server/services/musicVideo/productionDispatch.test.js
index 79a7079dde..8fdafa667c 100644
--- a/server/services/musicVideo/productionDispatch.test.js
+++ b/server/services/musicVideo/productionDispatch.test.js
@@ -15,6 +15,8 @@ const submitVideoGenJob = vi.fn(async () => ({ jobId: 'job-video' }));
vi.mock('../mediaJobQueue/index.js', () => ({ enqueueJob: (...a) => enqueueJob(...a) }));
vi.mock('../videoGen/submitJob.js', () => ({ submitVideoGenJob: (...a) => submitVideoGenJob(...a) }));
vi.mock('./productionService.js', () => ({ assertProductionSubmission: vi.fn(async () => {}) }));
+const assertRevisionOpen = vi.fn(async () => {});
+vi.mock('./revisionService.js', () => ({ assertRevisionOpen: (...a) => assertRevisionOpen(...a) }));
vi.mock('../imageGen/index.js', () => ({ resolveImageCleaners: () => ({ cleanC2PA: false, denoise: false }) }));
const { dispatchProductionStep } = await import('./productionDispatch.js');
@@ -96,6 +98,19 @@ describe('production scene dispatch (#9066)', () => {
expect(enqueueJob).not.toHaveBeenCalled();
});
+ it('dispatches a standalone auto-review frame (no production run): the revision guard runs, the production reservation does not (#10014)', async () => {
+ const revisionTag = { projectId: 'mv-example', sceneId: 'mvs-a', revisionId: 'mvr-example' };
+ await dispatchProductionStep({ stepKind: 'frame', project, scene, route: { kind: 'image', mode: 'codex', model: null }, tag: revisionTag, settings });
+ expect(assertRevisionOpen).toHaveBeenCalledWith('mv-example', 'mvr-example', { sceneId: 'mvs-a', kind: 'image' });
+ expect(assertProductionSubmission).not.toHaveBeenCalled();
+ expect(enqueueJob.mock.calls[0][0]).toMatchObject({ kind: 'image', owner: 'music-video-auto-review:mvr-example', params: { musicVideo: revisionTag } });
+ // A refused revision guard keeps the job out of the queue.
+ assertRevisionOpen.mockRejectedValueOnce(Object.assign(new Error('Spend limit'), { code: 'AUTO_REVIEW_SPEND_LIMIT' }));
+ await expect(dispatchProductionStep({ stepKind: 'frame', project, scene, route: { kind: 'image', mode: 'codex', model: null }, tag: revisionTag, settings }))
+ .rejects.toMatchObject({ code: 'AUTO_REVIEW_SPEND_LIMIT' });
+ expect(enqueueJob).toHaveBeenCalledTimes(1);
+ });
+
it('submits a clip with an explicit backend so the install pin ladder cannot substitute one', async () => {
const clipTag = { ...tag, productionStepKey: 'clip:mvs-a:base:1' };
await dispatchProductionStep({ stepKind: 'clip', project, scene, route: { kind: 'video', mode: 'grok', model: null }, tag: clipTag, settings });
diff --git a/server/services/musicVideo/productionPool.js b/server/services/musicVideo/productionPool.js
index a2c496fb3b..f20141b28c 100644
--- a/server/services/musicVideo/productionPool.js
+++ b/server/services/musicVideo/productionPool.js
@@ -195,6 +195,16 @@ async function routeIncapableReason(route, requirement, env) {
return null;
}
+/**
+ * Why `route` cannot generate `requirement` on this install right now, or null
+ * — the eligibility + capability checks a production step passes, for a caller
+ * with no pool to choose from (a standalone auto-review run, #10014).
+ */
+export async function routeUnavailableReason(route, requirement, env) {
+ const { ok, reason } = await routeEligibility(route, env);
+ return ok ? routeIncapableReason(route, requirement, env) : reason;
+}
+
/** Start-time check: every route in the pool must be eligible now. Throws 409 with every reason. */
export async function assertPoolEligible(pool, env) {
const problems = [];