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: add a Needs attention banner and recover interrupted Music Video workflows (#9940)

[._.]/ Adam Eivy83d86fc1cc12
diff --git a/client/src/components/musicVideo/MusicVideoLayout.jsx b/client/src/components/musicVideo/MusicVideoLayout.jsx
index e06564d780..2800977b65 100644
--- a/client/src/components/musicVideo/MusicVideoLayout.jsx
+++ b/client/src/components/musicVideo/MusicVideoLayout.jsx
@@ -43,12 +43,14 @@ const DOCK_CLASSES = 'max-lg:fixed max-lg:inset-x-0 max-lg:bottom-0 max-lg:z-30
*
* `progress` is `deriveStages(project)`; `nextAction` is `deriveNextAction(…)`;
* `status` is `describeProjectStatus(…)`, the one "where it stands" line under
- * the name. `dock` is the `PreviewDock` element (or null when there is nothing
+ * the name. `attention` is the `NeedsAttentionBanner` element (or null): it sits
+ * under that line so a stranded revision, interrupted check-in or unwatched
+ * render is visible on every tab, with its Resume/Cancel inline (#9940). `dock` is the `PreviewDock` element (or null when there is nothing
* to preview).
*/
export default function MusicVideoLayout({
project, trackLabel, stage, onStageChange, progress, nextAction, onNextAction, spend, status = null,
- dock, projectPanels, children,
+ attention = null, dock, projectPanels, children,
}) {
const headerRef = useRef(null);
const rootRef = useRef(null);
@@ -125,6 +127,7 @@ export default function MusicVideoLayout({
))}
</p>
)}
+ {attention}
<nav
aria-label="Stages"
className="max-md:fixed max-md:inset-x-0 max-md:bottom-0 max-md:z-40 max-md:border-t max-md:border-port-border max-md:bg-port-bg max-md:pb-[env(safe-area-inset-bottom)]"
diff --git a/client/src/components/musicVideo/NeedsAttentionBanner.jsx b/client/src/components/musicVideo/NeedsAttentionBanner.jsx
new file mode 100644
index 0000000000..1a01b7d0aa
--- /dev/null
+++ b/client/src/components/musicVideo/NeedsAttentionBanner.jsx
@@ -0,0 +1,91 @@
+import { AlertTriangle, Link2, Play, X } from 'lucide-react';
+import { ATTENTION_ANCHOR_ID } from '../../lib/musicVideoAttention.js';
+
+const BUTTON = 'inline-flex min-h-[44px] items-center gap-1 rounded border border-port-border px-2.5 text-xs disabled:opacity-50 sm:min-h-0 sm:py-1';
+const PRIMARY = `${BUTTON} text-port-accent`;
+const DANGER = `${BUTTON} text-port-error`;
+
+// The inline exits for one row. Each names what it acts on, so two rows never
+// share an accessible name.
+function ItemActions({ item, busy, actions }) {
+ switch (item.kind) {
+ case 'revision':
+ return (
+ <>
+ {item.canResume && (
+ <button type="button" disabled={busy} aria-label="Resume the open revision" onClick={() => actions.onResumeRevision?.(item.revisionId)} className={PRIMARY}>
+ <Play size={12} aria-hidden="true" /> Resume
+ </button>
+ )}
+ <button type="button" disabled={busy} aria-label="Cancel the open revision" onClick={() => actions.onCancelRevision?.(item.revisionId)} className={DANGER}>
+ <X size={12} aria-hidden="true" /> Cancel
+ </button>
+ </>
+ );
+ case 'cast-and-sets':
+ return (
+ <button type="button" disabled={busy} aria-label="Resume the Cast & Sets check-in" onClick={() => actions.onResumeCastAndSets?.()} className={PRIMARY}>
+ <Play size={12} aria-hidden="true" /> Resume
+ </button>
+ );
+ case 'auto-review':
+ return (
+ <>
+ <button type="button" disabled={busy} aria-label="Continue the auto-review run" onClick={() => actions.onContinueAutoReview?.(item.runId)} className={PRIMARY}>
+ <Play size={12} aria-hidden="true" /> Continue
+ </button>
+ <button type="button" disabled={busy} aria-label="Cancel the auto-review run" onClick={() => actions.onCancelAutoReview?.(item.runId)} className={DANGER}>
+ <X size={12} aria-hidden="true" /> Cancel run
+ </button>
+ </>
+ );
+ case 'final-render':
+ return (
+ <button type="button" disabled={busy} aria-label="Reattach to the final render" onClick={() => actions.onReattachRender?.()} className={PRIMARY}>
+ <Link2 size={12} aria-hidden="true" /> Reattach
+ </button>
+ );
+ default:
+ return null;
+ }
+}
+
+/**
+ * The Music Video header's "Needs attention" banner (#9940): one row per
+ * server-held state a client-orchestrated workflow can strand — an open
+ * revision, an interrupted Cast & Sets stage, an auto-review waiting on its
+ * revised sections, a final render nobody is watching — each with the inline
+ * exit (Resume / Continue / Cancel / Reattach) so a recoverable record never
+ * looks permanently stuck. `items` comes from `deriveAttentionItems`; `actions`
+ * are the page's handlers (`onResumeRevision(id)`, `onCancelRevision(id)`,
+ * `onResumeCastAndSets()`, `onContinueAutoReview(runId)`,
+ * `onCancelAutoReview(runId)`, `onReattachRender()`). Renders nothing when
+ * there is nothing to attend to.
+ */
+export default function NeedsAttentionBanner({ items, busy = false, actions = {} }) {
+ if (!items?.length) return null;
+ return (
+ <section
+ id={ATTENTION_ANCHOR_ID}
+ aria-label="Needs attention"
+ className="max-h-[40vh] space-y-1.5 overflow-y-auto rounded border border-port-warning/40 bg-port-warning/5 p-2 text-xs"
+ >
+ <h3 className="flex items-center gap-1 font-medium text-port-warning">
+ <AlertTriangle size={12} aria-hidden="true" /> Needs attention
+ </h3>
+ <ul className="space-y-1.5">
+ {items.map((item) => (
+ <li key={item.id} className="flex min-w-0 flex-wrap items-center gap-x-3 gap-y-1">
+ <span className="min-w-0 flex-1 basis-60">
+ <span className="font-medium">{item.title}</span>
+ <span className="block text-port-text-muted">{item.detail}</span>
+ </span>
+ <span className="flex flex-wrap items-center gap-2">
+ <ItemActions item={item} busy={busy} actions={actions} />
+ </span>
+ </li>
+ ))}
+ </ul>
+ </section>
+ );
+}
diff --git a/client/src/components/musicVideo/NeedsAttentionBanner.test.jsx b/client/src/components/musicVideo/NeedsAttentionBanner.test.jsx
new file mode 100644
index 0000000000..771da82426
--- /dev/null
+++ b/client/src/components/musicVideo/NeedsAttentionBanner.test.jsx
@@ -0,0 +1,77 @@
+import { describe, expect, it, vi } from 'vitest';
+import { fireEvent, render, screen, within } from '@testing-library/react';
+import NeedsAttentionBanner from './NeedsAttentionBanner.jsx';
+import MusicVideoLayout from './MusicVideoLayout.jsx';
+import { MUSIC_VIDEO_STAGES, } from '../../lib/musicVideoStages.js';
+import { deriveAttentionItems } from '../../lib/musicVideoAttention.js';
+
+const actions = () => ({
+ onResumeRevision: vi.fn(), onCancelRevision: vi.fn(), onResumeCastAndSets: vi.fn(),
+ onContinueAutoReview: vi.fn(), onCancelAutoReview: vi.fn(), onReattachRender: vi.fn(),
+});
+
+const stranded = {
+ id: 'mv-example',
+ status: 'rendering',
+ scenes: [{ sceneId: 'scene-a' }],
+ castAndSets: { status: 'imaging', interrupted: true },
+ revisions: [{ id: 'mvrev-open', status: 'open', sections: [{ sceneId: 'scene-a', kind: 'video', verdict: 'rejected' }] }],
+ autoReviews: [],
+};
+
+describe('NeedsAttentionBanner (#9940)', () => {
+ it('renders nothing when there is nothing to attend to', () => {
+ const { container } = render(<NeedsAttentionBanner items={[]} />);
+ expect(container).toBeEmptyDOMElement();
+ });
+
+ it('offers Resume and Cancel for an open revision, wired to the id the project holds', () => {
+ const handlers = actions();
+ render(<NeedsAttentionBanner items={deriveAttentionItems({ ...stranded, status: 'complete', castAndSets: null })} actions={handlers} />);
+ const banner = screen.getByRole('region', { name: 'Needs attention' });
+ expect(banner).toHaveTextContent('A section revision is open');
+ fireEvent.click(within(banner).getByRole('button', { name: 'Resume the open revision' }));
+ expect(handlers.onResumeRevision).toHaveBeenCalledWith('mvrev-open');
+ fireEvent.click(within(banner).getByRole('button', { name: 'Cancel the open revision' }));
+ expect(handlers.onCancelRevision).toHaveBeenCalledWith('mvrev-open');
+ });
+
+ it('covers an interrupted check-in, a waiting auto-review and an unwatched final render, each with its own exit', () => {
+ const handlers = actions();
+ const project = {
+ ...stranded,
+ revisions: [{ id: 'mvrev-owned', status: 'open', sections: [{ sceneId: 'scene-a', kind: 'image', verdict: 'rejected' }] }],
+ autoReviews: [{ id: 'mvar-example', status: 'running', attempts: [{ n: 1, revisionId: 'mvrev-owned' }] }],
+ };
+ render(<NeedsAttentionBanner items={deriveAttentionItems(project)} actions={handlers} />);
+ fireEvent.click(screen.getByRole('button', { name: 'Resume the Cast & Sets check-in' }));
+ expect(handlers.onResumeCastAndSets).toHaveBeenCalledTimes(1);
+ fireEvent.click(screen.getByRole('button', { name: 'Continue the auto-review run' }));
+ expect(handlers.onContinueAutoReview).toHaveBeenCalledWith('mvar-example');
+ fireEvent.click(screen.getByRole('button', { name: 'Cancel the auto-review run' }));
+ expect(handlers.onCancelAutoReview).toHaveBeenCalledWith('mvar-example');
+ fireEvent.click(screen.getByRole('button', { name: 'Reattach to the final render' }));
+ expect(handlers.onReattachRender).toHaveBeenCalledTimes(1);
+ // The run owns its revision: no second, competing Resume for it.
+ expect(screen.queryByRole('button', { name: 'Resume the open revision' })).not.toBeInTheDocument();
+ });
+
+ it('shows only Cancel while a revision re-renders, and disables every exit while a request is busy', () => {
+ const rendering = { ...stranded, status: 'complete', castAndSets: null, revisions: [{ ...stranded.revisions[0], status: 'rendering' }] };
+ render(<NeedsAttentionBanner items={deriveAttentionItems(rendering)} busy actions={actions()} />);
+ expect(screen.queryByRole('button', { name: 'Resume the open revision' })).not.toBeInTheDocument();
+ expect(screen.getByRole('button', { name: 'Cancel the open revision' })).toBeDisabled();
+ });
+
+ it('sits in the Music Video header under the status line, on every stage', () => {
+ render(<MusicVideoLayout project={{ id: 'example-project', name: 'Example Project' }} stage="board"
+ onStageChange={() => {}} progress={{ current: 'board', stages: MUSIC_VIDEO_STAGES.map((stage) => ({ ...stage, state: 'todo' })) }}
+ spend={{ spentUsd: 0 }}
+ status={{ headline: 'Stage 3 of 7: Board', tone: 'muted', facts: [] }}
+ attention={<NeedsAttentionBanner items={deriveAttentionItems(stranded)} actions={actions()} />} />);
+ const header = screen.getByRole('banner');
+ expect(within(header).getByRole('region', { name: 'Needs attention' })).toBeInTheDocument();
+ // Both live in the sticky header, so a director never has to hunt for the way out.
+ expect(within(header).getByRole('status', { name: 'Project status' })).toBeInTheDocument();
+ });
+});
diff --git a/client/src/components/musicVideo/workflowErrorToast.jsx b/client/src/components/musicVideo/workflowErrorToast.jsx
new file mode 100644
index 0000000000..834f7566d1
--- /dev/null
+++ b/client/src/components/musicVideo/workflowErrorToast.jsx
@@ -0,0 +1,33 @@
+import toast from '../ui/Toast';
+import { revealAttention } from '../../lib/musicVideoAttention.js';
+
+/**
+ * Toast a failed Music Video workflow request (production, auto-review or a
+ * revision start). A refusal because a revision is open (`REVISION_IN_PROGRESS`
+ * — the server's `context.revisionId` names it) carries a "Show revision" link
+ * to the "Needs attention" banner, where Resume and Cancel live, instead of a
+ * dead-end message about a revision the page does not point to (#9940).
+ *
+ * `reload()` refreshes the local record first: the revision may have been
+ * opened where this tab never saw it, and the banner can only show what the
+ * local project holds.
+ */
+export function toastWorkflowError(err, fallback, { reload } = {}) {
+ if (err?.code !== 'REVISION_IN_PROGRESS') {
+ toast.error(err?.message || fallback);
+ return;
+ }
+ Promise.resolve(reload?.()).catch(() => {});
+ toast.error((t) => (
+ <span className="flex flex-wrap items-center gap-3 text-xs">
+ <span className="text-gray-200">{err.message || 'Finish or cancel the open revision first'}</span>
+ <button
+ type="button"
+ onClick={() => { revealAttention(); toast.dismiss(t.id); }}
+ className="inline-flex min-h-[44px] shrink-0 items-center rounded border border-port-border px-2 py-0.5 text-[11px] text-port-accent hover:border-port-accent/40 hover:text-white sm:min-h-0"
+ >
+ Show revision
+ </button>
+ </span>
+ ), { duration: 12000, label: 'An open revision is blocking this' });
+}
diff --git a/client/src/hooks/useMusicVideoAutoReview.js b/client/src/hooks/useMusicVideoAutoReview.js
index 81911b5d06..d4413a7212 100644
--- a/client/src/hooks/useMusicVideoAutoReview.js
+++ b/client/src/hooks/useMusicVideoAutoReview.js
@@ -1,7 +1,9 @@
import { useEffect, useRef, useState } from 'react';
import toast from '../components/ui/Toast';
import socket from '../services/socket';
+import { toastWorkflowError } from '../components/musicVideo/workflowErrorToast.jsx';
import {
+ getMusicVideoProject,
startMusicVideoAutoReview,
resumeMusicVideoAutoReview,
stopMusicVideoAutoReview,
@@ -51,8 +53,13 @@ export default function useMusicVideoAutoReview({ project, replaceProject, submi
// 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) {
- submit(data.project, data.action.sections, data.action.revisionId).then((n) => {
+ // 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).
+ Promise.resolve().then(() => 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;
@@ -66,6 +73,10 @@ export default function useMusicVideoAutoReview({ project, replaceProject, submi
return () => socket.off('music-video:auto-review', onAutoReview);
}, [projectId]);
+ // A refusal for an open revision links to it; reload so the banner can show
+ // a revision this tab never saw.
+ const reload = () => getMusicVideoProject(projectId, { silent: true }).then((next) => handlers.current.replaceProject?.(next));
+
const call = (request) => {
setBusy(true);
return request()
@@ -74,7 +85,7 @@ export default function useMusicVideoAutoReview({ project, replaceProject, submi
if (res?.run) lastStatus.current.set(res.run.id, res.run.status);
return res;
})
- .catch((err) => { toast.error(err?.message || 'Auto-review request failed'); return null; })
+ .catch((err) => { toastWorkflowError(err, 'Auto-review request failed', { reload }); return null; })
.finally(() => setBusy(false));
};
diff --git a/client/src/hooks/useMusicVideoCastAndSets.js b/client/src/hooks/useMusicVideoCastAndSets.js
index 1f369b6675..1761277aa7 100644
--- a/client/src/hooks/useMusicVideoCastAndSets.js
+++ b/client/src/hooks/useMusicVideoCastAndSets.js
@@ -15,6 +15,10 @@ import {
// Where a stage stops needing the server: the autopilot continues past an
// approved or skipped one, and waits for the director at `review` or `failed`.
const CHECKPOINTS = new Set(['review', 'approved', 'skipped', 'failed']);
+// A working stage a server restart unpinned (`interrupted`) will never reach a
+// checkpoint on its own — it waits for the director's Resume. A kickoff watching
+// it must stop watching, not wait forever (#9940).
+const reachedCheckpoint = (stage) => CHECKPOINTS.has(stage?.status) || stage?.interrupted === true;
/**
* The Cast & Sets check-in (runs before the shot plan). The server does the
@@ -25,10 +29,11 @@ const CHECKPOINTS = new Set(['review', 'approved', 'skipped', 'failed']);
*
* `runToCheckpoint(project)` is the autopilot kickoff's step: it starts the
* check-in when there is none and resolves with the project once the stage
- * reaches a checkpoint (`review`, `approved`, `skipped`, `failed`), or null
- * when it could not start.
+ * reaches a checkpoint (`review`, `approved`, `skipped`, `failed`, or
+ * `interrupted` by a restart), or null when it could not start or the wait was
+ * abandoned with `cancelWait()` (the kickoff's Cancel).
*
- * Returns `{ busy, start, regenerate, editDirection, resume, approve, skip, runToCheckpoint }`.
+ * Returns `{ busy, start, regenerate, editDirection, resume, approve, skip, runToCheckpoint, cancelWait }`.
*/
export default function useMusicVideoCastAndSets({ project, replaceProject } = {}) {
const projectId = project?.id || null;
@@ -51,7 +56,7 @@ export default function useMusicVideoCastAndSets({ project, replaceProject } = {
snapshotRevision.current += 1;
replaceRef.current?.(next);
const w = waiter.current;
- if (w && w.projectId === projectId && CHECKPOINTS.has(next.castAndSets?.status)) {
+ if (w && w.projectId === projectId && reachedCheckpoint(next.castAndSets)) {
waiter.current = null;
w.resolve(next);
}
@@ -118,7 +123,7 @@ export default function useMusicVideoCastAndSets({ project, replaceProject } = {
const runToCheckpoint = (target) => {
if (!target?.id) return Promise.resolve(null);
const status = target.castAndSets?.status;
- if (CHECKPOINTS.has(status)) return Promise.resolve(target);
+ if (reachedCheckpoint(target.castAndSets)) return Promise.resolve(target);
const reached = new Promise((resolve) => { waiter.current = { projectId: target.id, resolve }; });
// A stage already underway just needs watching; otherwise start one.
if (status) return reached;
@@ -134,5 +139,13 @@ export default function useMusicVideoCastAndSets({ project, replaceProject } = {
});
};
- return { busy, start, regenerate, editDirection, resume, approve, skip, runToCheckpoint };
+ // Stop a kickoff's wait without touching the stage: the server keeps working.
+ const cancelWait = () => {
+ const w = waiter.current;
+ if (!w) return;
+ waiter.current = null;
+ w.resolve(null);
+ };
+
+ return { busy, start, regenerate, editDirection, resume, approve, skip, runToCheckpoint, cancelWait };
}
diff --git a/client/src/hooks/useMusicVideoCastAndSets.test.jsx b/client/src/hooks/useMusicVideoCastAndSets.test.jsx
new file mode 100644
index 0000000000..ceedd897d6
--- /dev/null
+++ b/client/src/hooks/useMusicVideoCastAndSets.test.jsx
@@ -0,0 +1,67 @@
+import { act, renderHook } from '@testing-library/react';
+import { beforeEach, expect, it, vi } from 'vitest';
+import useMusicVideoCastAndSets from './useMusicVideoCastAndSets.js';
+import { getMusicVideoProject, startMusicVideoCastAndSets } from '../services/apiMusicVideo.js';
+
+const handlers = new Map();
+vi.mock('../services/socket', () => ({
+ default: {
+ on: vi.fn((event, fn) => handlers.set(event, fn)),
+ off: vi.fn((event) => handlers.delete(event)),
+ },
+}));
+vi.mock('../services/apiMusicVideo.js', () => ({
+ getMusicVideoProject: vi.fn(),
+ startMusicVideoCastAndSets: vi.fn(),
+ regenerateMusicVideoCastAndSets: vi.fn(),
+ editMusicVideoCastAndSetsDirection: vi.fn(),
+ resumeMusicVideoCastAndSets: vi.fn(),
+ approveMusicVideoCastAndSets: vi.fn(),
+ skipMusicVideoCastAndSets: vi.fn(),
+}));
+vi.mock('../components/ui/Toast', () => ({ default: { error: vi.fn(), info: vi.fn(), success: vi.fn() } }));
+
+const withStage = (castAndSets) => ({ id: 'mv-example', castAndSets });
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ handlers.clear();
+ getMusicVideoProject.mockResolvedValue(withStage({ status: 'imaging' }));
+});
+
+const setup = () => renderHook(() => useMusicVideoCastAndSets({ project: { id: 'mv-example' }, replaceProject: vi.fn() }));
+
+it('resolves at once for a stage a restart already interrupted, without starting another (#9940)', async () => {
+ const { result } = setup();
+ const target = withStage({ status: 'imaging', interrupted: true });
+ await expect(result.current.runToCheckpoint(target)).resolves.toBe(target);
+ expect(startMusicVideoCastAndSets).not.toHaveBeenCalled();
+});
+
+it('ends a wait on a working stage when the server then reports it interrupted', async () => {
+ const { result } = setup();
+ let settled;
+ act(() => { settled = result.current.runToCheckpoint(withStage({ status: 'imaging' })); });
+ // A reconnect/visibility refresh (or a push) delivers the restarted server's view.
+ const interrupted = withStage({ status: 'imaging', interrupted: true });
+ act(() => handlers.get('music-video:cast-and-sets')({ projectId: 'mv-example', project: interrupted }));
+ await expect(settled).resolves.toBe(interrupted);
+});
+
+it('keeps waiting while the stage is genuinely still working', async () => {
+ const { result } = setup();
+ let done = false;
+ act(() => { result.current.runToCheckpoint(withStage({ status: 'imaging' })).then(() => { done = true; }); });
+ act(() => handlers.get('music-video:cast-and-sets')({ projectId: 'mv-example', project: withStage({ status: 'assembling', interrupted: false }) }));
+ await Promise.resolve();
+ expect(done).toBe(false);
+});
+
+it('cancelWait releases a pending wait with null and leaves the stage alone', async () => {
+ const { result } = setup();
+ let settled;
+ act(() => { settled = result.current.runToCheckpoint(withStage({ status: 'imaging' })); });
+ act(() => result.current.cancelWait());
+ await expect(settled).resolves.toBeNull();
+ expect(startMusicVideoCastAndSets).not.toHaveBeenCalled();
+});
diff --git a/client/src/hooks/useMusicVideoKickoff.js b/client/src/hooks/useMusicVideoKickoff.js
index eac33e5ddf..047eda6128 100644
--- a/client/src/hooks/useMusicVideoKickoff.js
+++ b/client/src/hooks/useMusicVideoKickoff.js
@@ -1,4 +1,5 @@
import { useRef, useState } from 'react';
+import toast from '../components/ui/Toast';
import useMounted from './useMounted.js';
export const MUSIC_VIDEO_KICKOFF_STEPS = Object.freeze({
@@ -11,11 +12,18 @@ export const MUSIC_VIDEO_KICKOFF_STEPS = Object.freeze({
});
const hasCues = (project) => (project?.lyricCues || []).length > 0;
+const stepName = (id) => MUSIC_VIDEO_KICKOFF_STEPS[id].replace(/…$/, '');
// A step reports its own failure; one that throws or rejects anyway counts as
-// failed rather than stranding the run half way.
-const attempt = (step, project) => Promise.resolve().then(() => step(project)).catch(() => null);
+// failed rather than stranding the run half way — and says so, so the run never
+// ends without a word (#9940).
+const attempt = (id, step, project) => Promise.resolve().then(() => step(project)).catch((err) => {
+ console.error(`❌ Music Video kickoff step "${id}" threw: ${err?.message || 'unknown error'}`);
+ toast.error(`Kickoff: ${stepName(id)} failed — ${err?.message || 'unexpected error'}`);
+ return null;
+});
const allAligned = (project) => hasCues(project) && project.lyricCues.every((cue) => (cue.words || []).length > 0);
const castAndSetsDone = (project) => ['approved', 'skipped'].includes(project?.castAndSets?.status);
+const castAndSetsStopped = (project) => !!project?.castAndSets && (project.castAndSets.interrupted || project.castAndSets.status === 'failed');
/**
* The Music Video autopilot kickoff ("Analyze & plan"): analyze → import the
@@ -34,57 +42,82 @@ const castAndSetsDone = (project) => ['approved', 'skipped'].includes(project?.c
* skipped. In review mode the stage stops at `review`, so the run ends there
* ("Waiting for your check-in"); the director approves and runs the kickoff
* again, which skips every finished step and plans. Auto mode approves itself
- * and the run continues straight to the plan. The step is optional so a caller
- * without it plans directly.
+ * and the run continues straight to the plan. A stage that failed or was
+ * interrupted by a restart also ends the run — with a note saying why, since
+ * the director must resume it. The step is optional so a caller without it
+ * plans directly.
+ *
+ * `cancel()` ends the run (#9940): it abandons a Cast & Sets wait at once
+ * (`cancelCastAndSets` — the server keeps working on the stage) and stops
+ * before the next step otherwise. A request already in flight finishes.
*
- * Returns `{ step, stepLabel, running, run(project) }`; `step` names the
- * running step (a key of MUSIC_VIDEO_KICKOFF_STEPS).
+ * Returns `{ step, stepLabel, running, run(project), cancel() }`; `step` names
+ * the running step (a key of MUSIC_VIDEO_KICKOFF_STEPS).
*/
-export default function useMusicVideoKickoff({ analyze, importLyrics, separateVocals, alignLyrics, castAndSets, plan }) {
+export default function useMusicVideoKickoff({ analyze, importLyrics, separateVocals, alignLyrics, castAndSets, cancelCastAndSets, plan }) {
const [step, setStep] = useState(null);
const busy = useRef(false);
+ const cancelled = useRef(false);
const mounted = useMounted();
const enter = (id) => { if (mounted.current) setStep(id); };
const run = async (start) => {
if (!start || busy.current) return;
busy.current = true;
+ cancelled.current = false;
let project = start;
try {
if (!project.audioAnalysis) {
enter('analyze');
- project = await attempt(analyze, project);
- if (!project?.audioAnalysis) return;
+ project = await attempt('analyze', analyze, project);
+ if (!project?.audioAnalysis || cancelled.current) return;
}
if (!hasCues(project) && project.trackId) {
enter('lyrics');
- project = (await attempt(importLyrics, project)) || project;
+ project = (await attempt('lyrics', importLyrics, project)) || project;
+ if (cancelled.current) return;
}
if (hasCues(project) && !project.vocalStemFilename) {
enter('vocals');
- project = (await attempt(separateVocals, project)) || project;
+ project = (await attempt('vocals', separateVocals, project)) || project;
+ if (cancelled.current) return;
}
if (hasCues(project) && !allAligned(project)) {
enter('align');
- project = (await attempt(alignLyrics, project)) || project;
+ project = (await attempt('align', alignLyrics, project)) || project;
+ if (cancelled.current) return;
}
// Code-first projects keep the check-in: the server directs it in the
// procedural medium (how the characters are built and move, how the
// world behaves), not as a photographic cast.
if (castAndSets && !castAndSetsDone(project)) {
enter('castAndSets');
- const checked = await attempt(castAndSets, project);
- // Waiting for the director (review), or the check-in failed: stop here.
- if (!castAndSetsDone(checked)) return;
+ const checked = await attempt('castAndSets', castAndSets, project);
+ if (cancelled.current) return;
+ // Waiting for the director (review), or the check-in failed or was
+ // interrupted: stop here, and say why when the director has to act.
+ if (!castAndSetsDone(checked)) {
+ if (castAndSetsStopped(checked)) {
+ toast.info(`Kickoff paused: the Cast & Sets check-in ${checked.castAndSets.interrupted ? 'was interrupted by a restart' : 'failed'} — resume it, then run the kickoff again.`);
+ }
+ return;
+ }
project = checked;
}
enter('plan');
- await attempt(plan, project);
+ await attempt('plan', plan, project);
} finally {
busy.current = false;
enter(null);
}
};
- return { step, stepLabel: step ? MUSIC_VIDEO_KICKOFF_STEPS[step] : null, running: step !== null, run };
+ const cancel = () => {
+ if (!busy.current || cancelled.current) return;
+ cancelled.current = true;
+ cancelCastAndSets?.();
+ toast.info('Kickoff stopped — work the server already started keeps running.');
+ };
+
+ return { step, stepLabel: step ? MUSIC_VIDEO_KICKOFF_STEPS[step] : null, running: step !== null, run, cancel };
}
diff --git a/client/src/hooks/useMusicVideoKickoff.test.jsx b/client/src/hooks/useMusicVideoKickoff.test.jsx
new file mode 100644
index 0000000000..a2ea242ff4
--- /dev/null
+++ b/client/src/hooks/useMusicVideoKickoff.test.jsx
@@ -0,0 +1,90 @@
+import { act, renderHook } from '@testing-library/react';
+import { beforeEach, expect, it, vi } from 'vitest';
+import toast from '../components/ui/Toast';
+import useMusicVideoKickoff from './useMusicVideoKickoff.js';
+
+vi.mock('../components/ui/Toast', () => ({ default: { error: vi.fn(), info: vi.fn(), success: vi.fn() } }));
+
+const analyzed = { id: 'mv-example', audioAnalysis: { sections: [{}] }, lyricCues: [] };
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ vi.spyOn(console, 'error').mockImplementation(() => {});
+});
+
+const steps = (overrides = {}) => ({
+ analyze: vi.fn(async () => analyzed),
+ importLyrics: vi.fn(async (project) => project),
+ separateVocals: vi.fn(async (project) => project),
+ alignLyrics: vi.fn(async (project) => project),
+ castAndSets: vi.fn(async (project) => ({ ...project, castAndSets: { status: 'approved' } })),
+ plan: vi.fn(async () => {}),
+ ...overrides,
+});
+
+it('says which step threw instead of ending the run in silence (#9940)', async () => {
+ const analyze = vi.fn(() => { throw new Error('beat tracker crashed'); });
+ const config = steps({ analyze });
+ const { result } = renderHook(() => useMusicVideoKickoff(config));
+ await act(async () => { await result.current.run({ id: 'mv-example' }); });
+ expect(toast.error).toHaveBeenCalledWith(expect.stringContaining('Analyzing the song failed'));
+ expect(toast.error.mock.calls[0][0]).toContain('beat tracker crashed');
+ expect(config.plan).not.toHaveBeenCalled();
+ expect(result.current.running).toBe(false);
+});
+
+it('ends on an interrupted Cast & Sets stage with a note, and plans nothing', async () => {
+ const config = steps({ castAndSets: vi.fn(async (project) => ({ ...project, castAndSets: { status: 'imaging', interrupted: true } })) });
+ const { result } = renderHook(() => useMusicVideoKickoff(config));
+ await act(async () => { await result.current.run(analyzed); });
+ expect(config.plan).not.toHaveBeenCalled();
+ expect(toast.info).toHaveBeenCalledWith(expect.stringContaining('interrupted by a restart'));
+ expect(result.current.running).toBe(false);
+});
+
+it('stays silent when the check-in simply waits for the director (review)', async () => {
+ const config = steps({ castAndSets: vi.fn(async (project) => ({ ...project, castAndSets: { status: 'review' } })) });
+ const { result } = renderHook(() => useMusicVideoKickoff(config));
+ await act(async () => { await result.current.run(analyzed); });
+ expect(config.plan).not.toHaveBeenCalled();
+ expect(toast.info).not.toHaveBeenCalled();
+});
+
+it('Cancel ends a kickoff stuck waiting on Cast & Sets and plans nothing', async () => {
+ let release;
+ const waiting = new Promise((resolve) => { release = resolve; });
+ const config = steps({
+ castAndSets: vi.fn(() => waiting),
+ cancelCastAndSets: vi.fn(() => release(null)),
+ });
+ const { result } = renderHook(() => useMusicVideoKickoff(config));
+ let finished;
+ act(() => { finished = result.current.run(analyzed); });
+ expect(result.current.step).toBe('castAndSets');
+ await act(async () => { result.current.cancel(); await finished; });
+ expect(config.cancelCastAndSets).toHaveBeenCalledTimes(1);
+ expect(config.plan).not.toHaveBeenCalled();
+ expect(result.current.running).toBe(false);
+});
+
+it('Cancel stops before the next step when no wait is in flight', async () => {
+ let finishAnalyze;
+ const config = steps({ analyze: vi.fn(() => new Promise((resolve) => { finishAnalyze = () => resolve(analyzed); })) });
+ const { result } = renderHook(() => useMusicVideoKickoff(config));
+ let finished;
+ act(() => { finished = result.current.run({ id: 'mv-example' }); });
+ // The step starts on the next microtask; let analyze begin before cancelling.
+ await act(async () => { await Promise.resolve(); });
+ act(() => result.current.cancel());
+ await act(async () => { finishAnalyze(); await finished; });
+ expect(config.castAndSets).not.toHaveBeenCalled();
+ expect(config.plan).not.toHaveBeenCalled();
+});
+
+it('runs the whole sequence to the plan when every step succeeds', async () => {
+ const config = steps();
+ const { result } = renderHook(() => useMusicVideoKickoff(config));
+ await act(async () => { await result.current.run({ id: 'mv-example' }); });
+ expect(config.plan).toHaveBeenCalledTimes(1);
+ expect(toast.error).not.toHaveBeenCalled();
+});
diff --git a/client/src/hooks/useMusicVideoProduction.js b/client/src/hooks/useMusicVideoProduction.js
index ef8077a8f3..eae04c62ac 100644
--- a/client/src/hooks/useMusicVideoProduction.js
+++ b/client/src/hooks/useMusicVideoProduction.js
@@ -1,7 +1,9 @@
import { useEffect, useRef, useState } from 'react';
import toast from '../components/ui/Toast';
import socket from '../services/socket';
+import { toastWorkflowError } from '../components/musicVideo/workflowErrorToast.jsx';
import {
+ getMusicVideoProject,
startMusicVideoProduction,
resumeMusicVideoProduction,
stopMusicVideoProduction,
@@ -50,6 +52,10 @@ export default function useMusicVideoProduction({ project, replaceProject } = {}
return () => socket.off('music-video:production', onProduction);
}, [projectId]);
+ // A refusal for an open revision links to it; reload so the banner can show
+ // a revision this tab never saw.
+ const reload = () => getMusicVideoProject(projectId, { silent: true }).then((next) => replaceRef.current?.(next));
+
const call = (request) => {
setBusy(true);
return request()
@@ -58,7 +64,7 @@ export default function useMusicVideoProduction({ project, replaceProject } = {}
if (res?.run) lastStatus.current.set(res.run.id, res.run.status);
return res;
})
- .catch((err) => { toast.error(err?.message || 'Production request failed'); return null; })
+ .catch((err) => { toastWorkflowError(err, 'Production request failed', { reload }); return null; })
.finally(() => setBusy(false));
};
diff --git a/client/src/hooks/useMusicVideoRevisions.js b/client/src/hooks/useMusicVideoRevisions.js
index d1971c35a6..95e0b593d0 100644
--- a/client/src/hooks/useMusicVideoRevisions.js
+++ b/client/src/hooks/useMusicVideoRevisions.js
@@ -1,5 +1,6 @@
import { useState } from 'react';
import toast from '../components/ui/Toast';
+import { toastWorkflowError } from '../components/musicVideo/workflowErrorToast.jsx';
import {
getMusicVideoProject,
startMusicVideoDependencyRepair,
@@ -62,7 +63,7 @@ export default function useMusicVideoRevisions({ project, replaceProject, sceneM
const run = (request) => {
setBusy(true);
return request()
- .catch((err) => { toast.error(err?.message || 'Revision request failed'); return null; })
+ .catch((err) => { toastWorkflowError(err, 'Revision request failed', { reload: reloadProject }); return null; })
.finally(() => setBusy(false));
};
diff --git a/server/routes/musicVideo.js b/server/routes/musicVideo.js
index 7cdd0fca50..9cf238c5dc 100644
--- a/server/routes/musicVideo.js
+++ b/server/routes/musicVideo.js
@@ -180,6 +180,7 @@ import {
approveCastAndSets,
skipCastAndSets,
getCastAndSets,
+ presentProjectCastAndSets,
} from '../services/musicVideo/castAndSetsService.js';
const router = Router();
@@ -200,7 +201,7 @@ const projectUpdateSchema = musicVideoProjectUpdateSchema.extend(recordRenderPin
// passes `limit`/`offset`, the response becomes the bounded
// `{ items, total, limit, offset }` envelope every paginated PortOS list shares.
router.get('/', asyncHandler(async (req, res) => {
- const projects = await listProjects();
+ const projects = (await listProjects()).map(presentProjectCastAndSets);
if (!isPaginationRequested(req.query)) {
return res.json(projects);
}
@@ -212,7 +213,8 @@ router.get('/:id', asyncHandler(async (req, res) => {
if (!p) throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });
// Transient (never persisted): lets a reloaded page reattach to a running publishing-kit build.
const activePublishKitBuild = getActivePublishKitBuild(p.id);
- res.json(activePublishKitBuild ? { ...p, activePublishKitBuild } : p);
+ const presented = presentProjectCastAndSets(p);
+ res.json(activePublishKitBuild ? { ...presented, activePublishKitBuild } : presented);
}));
router.post('/', asyncHandler(async (req, res) => {
diff --git a/server/routes/musicVideoRevision.test.js b/server/routes/musicVideoRevision.test.js
index c33d870c54..2fc75ef074 100644
--- a/server/routes/musicVideoRevision.test.js
+++ b/server/routes/musicVideoRevision.test.js
@@ -387,6 +387,12 @@ describe('selective section revision (#8987)', () => {
const second = await request(app).post(`${base(project.id)}/excerpt/mve-draft/revisions`).send({});
expect(second.status).toBe(409);
expect(second.body.code).toBe('REVISION_IN_PROGRESS');
+ // Every refusal names the blocking revision so the board can link to it (#9940).
+ expect(second.body.context).toEqual({ revisionId: first.body.revision.id });
+ const repair = await request(app).post(`${base(project.id)}/dependency-repairs`).send({ basis: 'basis-example' });
+ expect(repair.status).toBe(409);
+ expect(repair.body.code).toBe('REVISION_IN_PROGRESS');
+ expect(repair.body.context).toEqual({ revisionId: first.body.revision.id });
const outside = await request(app).post(`${base(project.id)}/revisions/${first.body.revision.id}/cancel`);
expect(outside.status).toBe(200);
diff --git a/server/services/musicVideo/castAndSetsService.js b/server/services/musicVideo/castAndSetsService.js
index c8ed15dac2..92bda03008 100644
--- a/server/services/musicVideo/castAndSetsService.js
+++ b/server/services/musicVideo/castAndSetsService.js
@@ -99,6 +99,16 @@ let deps = { ...defaults };
export function __setCastAndSetsDepsForTests(overrides) { deps = { ...defaults, ...overrides }; }
export const __castAndSetsProcessId = () => PROCESS_ID;
+/**
+ * The project as a CLIENT reads it. Only this process knows its own id, so only
+ * the server can tell a working stage a restart unpinned (`interrupted`) from
+ * one still running here; a raw record read would show every such stage as
+ * live forever (#9940). Not for write paths — never persist the result.
+ */
+export const presentProjectCastAndSets = (project) => (project?.castAndSets
+ ? { ...project, castAndSets: presentCastAndSets(project.castAndSets, PROCESS_ID) }
+ : project);
+
async function requireProject(id) {
const project = await getProject(id);
if (!project) throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });
diff --git a/server/services/musicVideo/castAndSetsService.test.js b/server/services/musicVideo/castAndSetsService.test.js
index b148f2541a..144cde824a 100644
--- a/server/services/musicVideo/castAndSetsService.test.js
+++ b/server/services/musicVideo/castAndSetsService.test.js
@@ -283,6 +283,27 @@ describe('Cast & Sets production accounting', () => {
});
});
+describe('Cast & Sets restart presentation (#9940)', () => {
+ it('project reads mark a working stage a restart unpinned as interrupted — but never store the flag', async () => {
+ const project = await seed();
+ const pin = (processId) => projects.mutateProjectRecord(project.id, (record) => ({
+ project: { ...record, castAndSets: { ...(record.castAndSets || { revision: 1, status: 'imaging' }), processId } },
+ }));
+ await pin('proc-before-restart');
+ // The client has no way to know the server's process id, so the read must say it.
+ const one = await request(app).get(`/api/music-video/${project.id}`);
+ expect(one.body.castAndSets).toMatchObject({ status: 'imaging', interrupted: true });
+ const list = await request(app).get('/api/music-video');
+ expect(list.body.find((p) => p.id === project.id).castAndSets.interrupted).toBe(true);
+
+ await pin(service.__castAndSetsProcessId());
+ const live = await request(app).get(`/api/music-video/${project.id}`);
+ expect(live.body.castAndSets.interrupted).toBe(false);
+ // Derived for the reader only: the record on disk stays the source of truth.
+ expect((await current(project.id)).castAndSets).not.toHaveProperty('interrupted');
+ });
+});
+
describe('Cast & Sets check-in', () => {
it('directs, renders the character sheet first, builds the sheet, waits for review, and applies the approval', async () => {
const project = await seed();
diff --git a/server/services/musicVideo/revision.js b/server/services/musicVideo/revision.js
index 788ca3171a..ca9b573099 100644
--- a/server/services/musicVideo/revision.js
+++ b/server/services/musicVideo/revision.js
@@ -428,7 +428,7 @@ export function releaseRevisionClaim(project, revisionId, sceneId, now = new Dat
export function startDependencyRepairOnProject(project, impact, { basis }, now = new Date().toISOString()) {
const active = projectRevisions(project).find(isActive);
if (active?.dependencyBasis === basis) return { project, revision: active, skippedSceneIds: [] };
- if (active) throw revisionError(409, 'REVISION_IN_PROGRESS', 'Finish or cancel the open revision before repairing dependencies');
+ if (active) throw revisionError(409, 'REVISION_IN_PROGRESS', 'Finish or cancel the open revision before repairing dependencies', { revisionId: active.id });
if (basis !== impact.basis) throw revisionError(409, 'DEPENDENCY_PREVIEW_CHANGED', 'Assets changed after the repair preview — review the impact again');
if (!impact.shots.length && !impact.evidence.length) throw revisionError(422, 'NOTHING_TO_REVISE', 'All recorded dependencies are current');
if (codeFirst(project)) {