Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat: wire the Needs attention banner, kickoff Stop and render reattach into the Music Video page (#9940)
[._.]/ Adam Eivyb12107f0f8aa
diff --git a/client/src/components/musicVideo/AutopilotPanel.jsx b/client/src/components/musicVideo/AutopilotPanel.jsxindex 27eeca358b..69741cf40f 100644--- a/client/src/components/musicVideo/AutopilotPanel.jsx+++ b/client/src/components/musicVideo/AutopilotPanel.jsx@@ -277,7 +277,7 @@ function StartForm({ project, production }) {}/** The brief: tools, guidance and budget, with the one-click kickoff. */-function BriefSection({ project, onSave, onKickoff, kickoffBusy, kickoffStep, kickoffBlockedReason }) {+function BriefSection({ project, onSave, onKickoff, onCancelKickoff, kickoffBusy, kickoffStep, kickoffBlockedReason }) {const [draft, setDraft] = useState(null);const [saving, setSaving] = useState(false);const automation = project.automation || null;@@ -329,6 +329,16 @@ function BriefSection({ project, onSave, onKickoff, kickoffBusy, kickoffStep, ki><Play size={14} /> {kickoffBusy ? 'Working…' : 'Analyze & plan'}</button>+ {onCancelKickoff && (+ <button+ type="button"+ onClick={onCancelKickoff}+ title="Stop the kickoff before its next step (or at once while it waits on Cast & Sets). Work the server already started keeps running."+ className="flex items-center gap-1 rounded border border-port-border px-3 py-1.5 text-sm text-port-error min-h-[44px] sm:min-h-0"+ >+ <X size={14} /> Stop+ </button>+ )}</div></>);@@ -419,10 +429,11 @@ function ProductionSection({ project, production, readiness }) {* budget, kickoff) and its server-side production run (allowed routes,* generation and spend caps, the run log). Edits PATCH through `onSave`, which* owns the error toast; `production` is the `useMusicVideoProduction` slot.- * `kickoffStep` names the kickoff step running now.+ * `kickoffStep` names the kickoff step running now; `onCancelKickoff` (passed+ * only while one runs) stops it (#9940).*/export default function AutopilotPanel({- project, production, readiness, onSave, onKickoff, kickoffBusy, kickoffStep = null, kickoffBlockedReason,+ project, production, readiness, onSave, onKickoff, onCancelKickoff, kickoffBusy, kickoffStep = null, kickoffBlockedReason,}) {return (<section className="bg-port-card border border-port-border rounded-lg p-3 space-y-3 min-w-0" aria-label="Autopilot">@@ -430,6 +441,7 @@ export default function AutopilotPanel({project={project}onSave={onSave}onKickoff={onKickoff}+ onCancelKickoff={onCancelKickoff}kickoffBusy={kickoffBusy}kickoffStep={kickoffStep}kickoffBlockedReason={kickoffBlockedReason}diff --git a/client/src/components/musicVideo/AutopilotPanel.test.jsx b/client/src/components/musicVideo/AutopilotPanel.test.jsxindex cdc518b478..d87bde1f0c 100644--- a/client/src/components/musicVideo/AutopilotPanel.test.jsx+++ b/client/src/components/musicVideo/AutopilotPanel.test.jsx@@ -66,6 +66,40 @@ function KickoffHarness({ project, steps }) {const cue = (id, text, words) => ({ id, text, startSec: null, endSec: null, ...(words ? { words } : {}) });describe('AutopilotPanel kickoff', () => {+ it('offers Stop while a kickoff runs, and Stop ends a wait on the Cast & Sets check-in (#9940)', async () => {+ const waiting = deferred();+ const base = { id: 'mv-1', automation, audioAnalysis: { sections: [] }, lyricCues: [] };+ const steps = {+ castAndSets: vi.fn(() => waiting.promise),+ cancelCastAndSets: vi.fn(() => waiting.resolve(null)),+ plan: vi.fn(async () => {}),+ };+ function StoppableHarness() {+ const kickoff = useMusicVideoKickoff(steps);+ return (+ <AutopilotPanel+ project={base}+ production={IDLE_PRODUCTION}+ onSave={vi.fn()}+ onKickoff={() => kickoff.run(base)}+ onCancelKickoff={kickoff.running ? kickoff.cancel : undefined}+ kickoffBusy={kickoff.running}+ kickoffStep={kickoff.stepLabel}+ />+ );+ }+ render(<StoppableHarness />);+ expect(screen.queryByRole('button', { name: /Stop/ })).toBeNull();+ fireEvent.click(screen.getByRole('button', { name: /Analyze & plan/ }));+ expect(await screen.findByRole('status')).toHaveTextContent('Building the Cast & Sets check-in…');+ fireEvent.click(screen.getByRole('button', { name: /Stop/ }));+ // The run ends — the button is usable again and nothing was planned.+ await waitFor(() => expect(screen.getByRole('button', { name: /Analyze & plan/ }).disabled).toBe(false));+ expect(steps.cancelCastAndSets).toHaveBeenCalledTimes(1);+ expect(steps.plan).not.toHaveBeenCalled();+ expect(screen.queryByRole('button', { name: /Stop/ })).toBeNull();+ });+it('analyzes, imports track lyrics, separates vocals, aligns and plans — showing each step', async () => {const order = [];const base = { id: 'mv-1', trackId: 't1', automation, lyricCues: [] };diff --git a/client/src/components/musicVideo/DependencyImpactPanel.jsx b/client/src/components/musicVideo/DependencyImpactPanel.jsxindex ee6c0e21ec..5850a72767 100644--- a/client/src/components/musicVideo/DependencyImpactPanel.jsx+++ b/client/src/components/musicVideo/DependencyImpactPanel.jsx@@ -1,7 +1,10 @@import { useEffect, useState } from 'react';import { getMusicVideoDependencyImpact } from '../../services/apiMusicVideo.js';+import { openRevisionOf } from '../../lib/musicVideoAttention.js';import { formatCount } from '../../utils/formatters.js';+const REVISION_HINT_ID = 'mv-repair-blocked-hint';+/** Preview first; only the director's Repair action starts any work. */export default function DependencyImpactPanel({ project, busy, onRepair }) {const [result, setResult] = useState(null);@@ -18,7 +21,7 @@ export default function DependencyImpactPanel({ project, busy, onRepair }) {});return () => { active = false; };}, [project, retry]);- const revisionActive = (project.revisions || []).some((revision) => ['open', 'rendering'].includes(revision.status));+ const revisionActive = !!openRevisionOf(project);if (error) return <div role="alert" className="text-xs text-port-error">{error} <button type="button" onClick={() => setRetry((value) => value + 1)}>Retry dependency check</button></div>;if (!result || (!result.shots.length && !result.evidence.length)) return null;return (@@ -35,9 +38,15 @@ export default function DependencyImpactPanel({ project, busy, onRepair }) {: 'No new clips needed'}; {formatCount(result.estimate.evidenceRebuilds)} evidence records need rebuilding or review. Historical assets are retained.</p>{!result.shots.length && <p>Selected takes can be kept. Rebuild the draft and review it again; historical passing reviews cannot approve changed dependencies.</p>}<button type="button" disabled={busy || revisionActive} onClick={() => onRepair(result.basis)}+ aria-describedby={revisionActive ? REVISION_HINT_ID : undefined}className="min-h-[44px] rounded border border-port-border px-3 text-port-accent disabled:opacity-50">Repair affected dependencies</button>+ {revisionActive && (+ <p id={REVISION_HINT_ID} className="text-port-warning">+ A revision is already open — resume or cancel it (under "Needs attention" above) before repairing.+ </p>+ )}</section>);}diff --git a/client/src/components/musicVideo/DependencyImpactPanel.test.jsx b/client/src/components/musicVideo/DependencyImpactPanel.test.jsxindex ecac0abb6e..79b660ab32 100644--- a/client/src/components/musicVideo/DependencyImpactPanel.test.jsx+++ b/client/src/components/musicVideo/DependencyImpactPanel.test.jsx@@ -33,4 +33,14 @@ describe('rendered stale impact', () => {resolveOld({ shots: [], evidence: [] });await waitFor(() => expect(screen.getByRole('button', { name: 'Repair affected dependencies' })).toBeDisabled());});+ it('says WHY Repair is disabled while a revision is open, and offers it again once that is gone (#9940)', async () => {+ getMusicVideoDependencyImpact.mockResolvedValue(impact);+ const { rerender } = render(<DependencyImpactPanel project={{ ...project, revisions: [{ id: 'mvrev-open', status: 'open' }] }} onRepair={vi.fn()} />);+ const button = await screen.findByRole('button', { name: 'Repair affected dependencies' });+ expect(button).toBeDisabled();+ expect(button).toHaveAccessibleDescription(/A revision is already open — resume or cancel it/);+ rerender(<DependencyImpactPanel project={{ ...project, revisions: [{ id: 'mvrev-open', status: 'canceled' }] }} onRepair={vi.fn()} />);+ await waitFor(() => expect(screen.getByRole('button', { name: 'Repair affected dependencies' })).toBeEnabled());+ expect(screen.queryByText(/already open/)).not.toBeInTheDocument();+ });});diff --git a/client/src/components/musicVideo/NeedsAttentionBanner.test.jsx b/client/src/components/musicVideo/NeedsAttentionBanner.test.jsxindex 771da82426..83a729b84b 100644--- a/client/src/components/musicVideo/NeedsAttentionBanner.test.jsx+++ b/client/src/components/musicVideo/NeedsAttentionBanner.test.jsx@@ -2,7 +2,7 @@ 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 { MUSIC_VIDEO_STAGES } from '../../lib/musicVideoStages.js';import { deriveAttentionItems } from '../../lib/musicVideoAttention.js';const actions = () => ({diff --git a/client/src/components/musicVideo/stages/ProduceStage.jsx b/client/src/components/musicVideo/stages/ProduceStage.jsxindex 7513b2ec61..378e0da9b4 100644--- a/client/src/components/musicVideo/stages/ProduceStage.jsx+++ b/client/src/components/musicVideo/stages/ProduceStage.jsx@@ -18,6 +18,7 @@ export default function ProduceStage({ board }) {readiness={board.productionReadiness}onSave={board.saveAutomation}onKickoff={board.onKickoff}+ onCancelKickoff={kickoff.running ? kickoff.cancel : undefined}kickoffBusy={board.busy.analyzing || board.busy.planning || kickoff.running}kickoffStep={kickoff.stepLabel}kickoffBlockedReason={board.autopilotBlockedReason}diff --git a/client/src/components/musicVideo/workflowErrorToast.test.jsx b/client/src/components/musicVideo/workflowErrorToast.test.jsxnew file mode 100644index 0000000000..febc85dd9c--- /dev/null+++ b/client/src/components/musicVideo/workflowErrorToast.test.jsx@@ -0,0 +1,51 @@+import { beforeEach, expect, it, vi } from 'vitest';+import { fireEvent, render, screen } from '@testing-library/react';+import toast from '../ui/Toast';+import { toastWorkflowError } from './workflowErrorToast.jsx';+import { ATTENTION_ANCHOR_ID } from '../../lib/musicVideoAttention.js';++vi.mock('../ui/Toast', () => ({ default: Object.assign(vi.fn(), { error: vi.fn(), info: vi.fn(), success: vi.fn(), dismiss: vi.fn() }) }));++beforeEach(() => vi.clearAllMocks());++it('toasts an ordinary failure as plain text and reloads nothing', () => {+ const reload = vi.fn();+ toastWorkflowError(new Error('Provider refused'), 'Production request failed', { reload });+ expect(toast.error).toHaveBeenCalledWith('Provider refused');+ expect(reload).not.toHaveBeenCalled();+});++it('falls back to the caller\'s message when the error carries none', () => {+ toastWorkflowError({}, 'Production request failed');+ expect(toast.error).toHaveBeenCalledWith('Production request failed');+});++it('links a refusal for an open revision to the Needs attention banner (#9940)', () => {+ document.body.innerHTML = `<section id="${ATTENTION_ANCHOR_ID}"><button type="button">Resume</button></section>`;+ document.getElementById(ATTENTION_ANCHOR_ID).scrollIntoView = vi.fn();+ const reload = vi.fn(() => Promise.resolve());+ const err = Object.assign(new Error('Finish or cancel the open revision before starting production'), {+ code: 'REVISION_IN_PROGRESS', context: { revisionId: 'mvrev-example' },+ });+ toastWorkflowError(err, 'Production request failed', { reload });++ // The local record is refreshed so the banner can show a revision this tab never saw…+ expect(reload).toHaveBeenCalledTimes(1);+ const [content, options] = toast.error.mock.calls[0];+ expect(options.label).toMatch(/revision/i);+ // …and the toast carries a link that lands on its Resume/Cancel.+ render(content({ id: 'toast-1' }));+ expect(screen.getByText(/Finish or cancel the open revision/)).toBeInTheDocument();+ fireEvent.click(screen.getByRole('button', { name: 'Show revision' }));+ expect(document.getElementById(ATTENTION_ANCHOR_ID).scrollIntoView).toHaveBeenCalled();+ expect(document.activeElement).toBe(document.querySelector(`#${ATTENTION_ANCHOR_ID} button`));+ expect(toast.dismiss).toHaveBeenCalledWith('toast-1');+});++it('survives a failed reload and a banner that is not on screen', () => {+ document.body.innerHTML = '';+ const err = Object.assign(new Error('Open revision'), { code: 'REVISION_IN_PROGRESS' });+ expect(() => toastWorkflowError(err, 'x', { reload: () => Promise.reject(new Error('offline')) })).not.toThrow();+ render(toast.error.mock.calls[0][0]({ id: 'toast-2' }));+ expect(() => fireEvent.click(screen.getByRole('button', { name: 'Show revision' }))).not.toThrow();+});diff --git a/client/src/hooks/README.md b/client/src/hooks/README.mdindex 8d66c81612..5c9bfe7e6c 100644--- a/client/src/hooks/README.md+++ b/client/src/hooks/README.md@@ -248,15 +248,15 @@ grep -i "what you want to do" client/src/hooks/README.md| `useReferenceAudioImport` | One round reference-audio-import job slot (#2120): start/cancel + SSE progress + terminal-frame handling via `POST /api/rounds/reference-audio/import`. Returns `{ active, percent, stage, start(url, context), cancel }`; `onComplete(filename, context)` fires with the uploads-dir filename to persist on the reference. Call once per surface that can independently kick off a download. | The reference-audio attach controls (`ReferenceAudioAttach`) — the "Download from URL" convenience. || `useMidiTranscription` | One audio → MIDI transcription job slot (MuScriptor): start/cancel + SSE stage progress + terminal-frame handling, generic over the Rounds and Music Video API surfaces (pass `startRequest`/`eventsUrl`/`cancelRequest`). Returns `{ active, stage, stageLabel, context, start(context), cancel }` (`stageLabel` is the ready-to-render human label for the current STAGE — including a distinct "Downloading model…" for the first-use weight download, which also fires a one-time toast; `context` is the in-flight job's captured target, for per-target UI gates); `onComplete(frame, context)` fires with the terminal frame (`filename`, `model`, any server-merged extras). | The Rounds reference "Transcribe MIDI" control and the Music Video MIDI button. || `useMusicVideoYoutubeImport` | The Music Video page's two independent `useYoutubeTrackImport` slots (create form + detail-view track row) plus their URL drafts, the detail slot's captured target project, and the URL-nav backstop that bounces a deep link / Back / ⌘K jump away from an in-flight import back to its project. Returns `{ createUrl, setCreateUrl, editUrl, setEditUrl, createJob, editJob, startCreate, startEdit, switchBlockedMessage }`. | The Music Video page. Reuse `switchBlockedMessage` for any additional guard (delete, list picker) so every surface says the same thing. |-| `useMusicVideoKickoff` | The Music Video autopilot kickoff sequence — analyze → import track lyrics → separate vocals → align words → Cast & Sets check-in → plan — each step skipped when its result already exists and handed the freshest project. A failed analysis stops the run; a failed lyric/vocal/align step still plans; the check-in gates the plan (a sheet waiting for review ends the run until the director approves). Returns `{ step, stepLabel, running, run(project) }`. | The Music Video "Analyze & plan" button. |-| `useMusicVideoCastAndSets` | The Cast & Sets check-in before the plan: applies the project pushed on `music-video:cast-and-sets` / `music-video:dev-artifact` and exposes start / regenerate(notes?) / resume / approve / skip, plus `runToCheckpoint(project)` (start if absent, resolve at review/approved/skipped/failed) for the kickoff. | The Music Video autopilot card and sheet viewer. |+| `useMusicVideoKickoff` | The Music Video autopilot kickoff sequence — analyze → import track lyrics → separate vocals → align words → Cast & Sets check-in → plan — each step skipped when its result already exists and handed the freshest project. A failed analysis stops the run; a failed lyric/vocal/align step still plans; the check-in gates the plan (a sheet waiting for review ends the run until the director approves). A step that throws is toasted by name, a failed or interrupted check-in ends the run with a note, and `cancel()` (#9940) stops it. Returns `{ step, stepLabel, running, run(project), cancel() }`. | The Music Video "Analyze & plan" button. |+| `useMusicVideoCastAndSets` | The Cast & Sets check-in before the plan: applies the project pushed on `music-video:cast-and-sets` / `music-video:dev-artifact` and exposes start / regenerate(notes?) / resume / approve / skip, plus `runToCheckpoint(project)` (start if absent, resolve at review/approved/skipped/failed — or `interrupted` by a restart, which would otherwise never settle) for the kickoff and `cancelWait()` to abandon that wait. | The Music Video autopilot card and sheet viewer. || `useMusicVideoDevArtifacts` | A project's development files ("ingredients"): import a file or a new version, add/resolve notes, approve / request changes, remove; applies the returned project. Returns `{ busy, upload, addNote, resolveNote, review, remove }`. | The Music Video Development section and viewer drawer. || `useMusicVideoVocalSeparation` | "Separate vocals" (demucs) as a `useSseJobSlot`: `start(projectId)` for the button, `run(projectId)` as a promise resolving with the project carrying its new stem (or null on failure/cancel), `stageLabel` for install/separation progress, `onSeparated(projectId, project)` on success. | The Music Video vocal-stem control and the autopilot kickoff. || `useMusicVideoMidiJob` | `useMidiTranscription` bound to the music-video API surface, plus the MuScriptor model-size picker state (read fresh at each kickoff). Returns the slot (`active`/`stage`/`stageLabel`/`context`/`start(projectId)`/`cancel`/`installGate`/`gatedGate`) plus `{ model, setModel }`; `onTranscribed(projectId, midiTranscription)` fires on a non-discarded terminal frame. | The Music Video MIDI button + model select. || `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 }`; `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. Returns `{ busy, revise(excerptId, sceneIds?), resume(revisionId), cancel(revisionId), submitSections(project, refs, revisionId) }`. | The Music Video excerpt 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. || `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. |diff --git a/client/src/hooks/useMusicVideoAutoReview.test.jsx b/client/src/hooks/useMusicVideoAutoReview.test.jsxnew file mode 100644index 0000000000..adc32599e9--- /dev/null+++ b/client/src/hooks/useMusicVideoAutoReview.test.jsx@@ -0,0 +1,84 @@+import { act, renderHook } from '@testing-library/react';+import { beforeEach, expect, it, vi } from 'vitest';+import toast from '../components/ui/Toast';+import useMusicVideoAutoReview from './useMusicVideoAutoReview.js';+import { getMusicVideoProject, startMusicVideoAutoReview } 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(),+ startMusicVideoAutoReview: vi.fn(),+ resumeMusicVideoAutoReview: vi.fn(),+ stopMusicVideoAutoReview: vi.fn(),+ cancelMusicVideoAutoReview: vi.fn(),+}));+vi.mock('../components/ui/Toast', () => ({ default: Object.assign(vi.fn(), { error: vi.fn(), info: vi.fn(), success: vi.fn(), dismiss: vi.fn() }) }));++const project = { id: 'mv-example', scenes: [] };+const generateEvent = {+ projectId: 'mv-example',+ project,+ run: { id: 'mvar-example', status: 'running', attempts: [] },+ action: { type: 'generate', revisionId: 'mvrev-example', sections: [{ sceneId: 'scene-a', kind: 'video' }] },+};++beforeEach(() => {+ vi.clearAllMocks();+ handlers.clear();+ vi.spyOn(console, 'error').mockImplementation(() => {});+});++const setup = (submitSections) => {+ const replaceProject = vi.fn();+ const hook = renderHook(() => useMusicVideoAutoReview({ project, replaceProject, submitSections }));+ 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 () => {+ const submitSections = vi.fn(() => Promise.resolve(2));+ setup(submitSections);+ act(() => handlers.get('music-video:auto-review')(generateEvent));+ await flush();+ expect(submitSections).toHaveBeenCalledWith(project, generateEvent.action.sections, 'mvrev-example');+ expect(toast.info).toHaveBeenCalledWith('Auto-review: generating 2 revised sections');+ 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' } }));+ await flush();+ expect(submitSections).not.toHaveBeenCalled();+});++it('links a start refused for an open revision to it, reloading the record so the banner can show it', async () => {+ const persisted = { ...project, revisions: [{ id: 'mvrev-open', status: 'open' }] };+ getMusicVideoProject.mockResolvedValue(persisted);+ 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());+ await act(async () => { await result.current.start(0, 10, { maxAttempts: 1, maxGenerations: 1 }); });+ expect(getMusicVideoProject).toHaveBeenCalledWith('mv-example', { silent: true });+ await flush();+ expect(replaceProject).toHaveBeenCalledWith(persisted);+ // A render-prop toast (with its "Show revision" link), not a bare message.+ expect(typeof toast.error.mock.calls[0][0]).toBe('function');+});diff --git a/client/src/hooks/useMusicVideoRenderJob.js b/client/src/hooks/useMusicVideoRenderJob.jsindex 1c9d87f7c2..0c4e537aa9 100644--- a/client/src/hooks/useMusicVideoRenderJob.js+++ b/client/src/hooks/useMusicVideoRenderJob.js@@ -26,16 +26,19 @@ const startRender = (projectId) => renderMusicVideoProject(projectId, { silent:* A project the server marks `rendering` re-attaches on load (#9940) — the* same way excerpt renders do — through a READ of the live job* (`getMusicVideoActiveRender`), never a POST that would start a new render.+ * `onSettled(reason, projectId)` fires on every terminal frame (complete, error,+ * cancelled) and on a dropped stream.* `reattach(projectId)` is the explicit retry the "Needs attention" banner* offers when that automatic attempt found no job or the slot was busy.*/-export default function useMusicVideoRenderJob({ project, onRendered, onFailed } = {}) {+export default function useMusicVideoRenderJob({ project, onRendered, onFailed, onSettled } = {}) {const [failure, setFailure] = useState(null);const slot = useSseJobSlot({startRequest: startRender,eventsUrl: musicVideoRenderEventsUrl,cancelRequest: cancelMusicVideoRender,readPercent: readRenderPercent,+ onSettled,onComplete: (frame, projectId) => { setFailure(null); onRendered?.(projectId, frame.result || {}); },onErrorFrame: (frame, projectId) => {setFailure({ projectId, message: frame.error || 'Render failed' });diff --git a/client/src/hooks/useMusicVideoRenderJob.test.jsx b/client/src/hooks/useMusicVideoRenderJob.test.jsxindex e27eaf0341..d0a40d9994 100644--- a/client/src/hooks/useMusicVideoRenderJob.test.jsx+++ b/client/src/hooks/useMusicVideoRenderJob.test.jsx@@ -1,11 +1,12 @@import { afterEach, beforeEach, expect, it, vi } from 'vitest';-import { act, renderHook } from '@testing-library/react';+import { act, renderHook, waitFor } from '@testing-library/react';import useMusicVideoRenderJob from './useMusicVideoRenderJob.js';import { MockEventSource, lastEventSource } from '../test/mockEventSource';-import { renderMusicVideoProject } from '../services/apiMusicVideo.js';+import toast from '../components/ui/Toast';+import { getMusicVideoActiveRender, renderMusicVideoProject } from '../services/apiMusicVideo.js';vi.mock('../services/apiMusicVideo.js', () => ({- renderMusicVideoProject: vi.fn(), musicVideoRenderEventsUrl: id => `/events/${id}`, cancelMusicVideoRender: vi.fn(),+ getMusicVideoActiveRender: vi.fn(), renderMusicVideoProject: vi.fn(), musicVideoRenderEventsUrl: id => `/events/${id}`, cancelMusicVideoRender: vi.fn(),}));vi.mock('../components/ui/Toast', () => ({ default: { error: vi.fn(), info: vi.fn(), success: vi.fn() } }));beforeEach(() => { vi.clearAllMocks(); MockEventSource.reset(); vi.stubGlobal('EventSource', MockEventSource); });@@ -24,3 +25,42 @@ it('retains kickoff and terminal failures after the shared SSE slot clears, thenexpect(result.current.failure).toEqual({ projectId: 'mv-example', message: 'Document capture failed' });expect(onFailed).toHaveBeenCalledWith('mv-example', 'Document capture failed');});++// #9940: a reload while the server renders must show the render without a click.+it('reattaches a live final render on load by READING it, never by starting one', async () => {+ getMusicVideoActiveRender.mockResolvedValue({ jobId: 'job-live' });+ const onRendered = vi.fn();+ const { result } = renderHook(() => useMusicVideoRenderJob({ project: { id: 'mv-example', status: 'rendering' }, onRendered }));+ await waitFor(() => expect(result.current.active).toBe(true));+ expect(result.current).toMatchObject({ jobId: 'job-live', context: 'mv-example' });+ expect(getMusicVideoActiveRender).toHaveBeenCalledWith('mv-example', { silent: true });+ // The POST that would start a render is never made by a page load.+ expect(renderMusicVideoProject).not.toHaveBeenCalled();+ act(() => lastEventSource().emit({ type: 'progress', progress: 0.4 }));+ expect(result.current.progress).toBe(40);+ act(() => lastEventSource().emit({ type: 'complete', result: { id: 'hist-example' } }));+ expect(onRendered).toHaveBeenCalledWith('mv-example', { id: 'hist-example' });+});++it('stays idle — and still starts nothing — when no live render is found or the project is not rendering', async () => {+ getMusicVideoActiveRender.mockResolvedValue({ jobId: null });+ const stale = renderHook(() => useMusicVideoRenderJob({ project: { id: 'mv-example', status: 'rendering' } }));+ await waitFor(() => expect(getMusicVideoActiveRender).toHaveBeenCalledTimes(1));+ expect(stale.result.current.active).toBe(false);+ renderHook(() => useMusicVideoRenderJob({ project: { id: 'mv-idle', status: 'complete' } }));+ expect(getMusicVideoActiveRender).toHaveBeenCalledTimes(1);+ expect(renderMusicVideoProject).not.toHaveBeenCalled();+});++it('reattach() is the explicit retry: it attaches a live job and explains when there is none', async () => {+ getMusicVideoActiveRender.mockResolvedValueOnce({ jobId: null });+ const { result } = renderHook(() => useMusicVideoRenderJob({ project: { id: 'mv-example', status: 'complete' } }));+ let found;+ await act(async () => { found = await result.current.reattach('mv-example'); });+ expect(found).toBe(false);+ expect(toast.info).toHaveBeenCalledWith(expect.stringContaining('No live render'));+ getMusicVideoActiveRender.mockResolvedValueOnce({ jobId: 'job-late' });+ await act(async () => { found = await result.current.reattach('mv-example'); });+ expect(found).toBe(true);+ expect(result.current.jobId).toBe('job-late');+});diff --git a/client/src/pages/MusicVideo.jsx b/client/src/pages/MusicVideo.jsxindex 5b77025145..a5cf0f14d4 100644--- a/client/src/pages/MusicVideo.jsx+++ b/client/src/pages/MusicVideo.jsx@@ -24,6 +24,7 @@ import {importMusicVideoLyrics,importMusicVideoTrackLyrics,alignMusicVideoLyrics,+ getMusicVideoProject,} from '../services/apiMusicVideo.js';import useFieldDraft from '../hooks/useFieldDraft.js';import useMusicVideoYoutubeImport from '../hooks/useMusicVideoYoutubeImport.js';@@ -62,6 +63,7 @@ import MusicVideoLayout, { MUSIC_VIDEO_SCROLL_ID } from '../components/musicVideimport StageSection from '../components/musicVideo/StageSection.jsx';import MusicVideoProjectCard from '../components/musicVideo/MusicVideoProjectCard.jsx';import PreviewDock from '../components/musicVideo/PreviewDock.jsx';+import NeedsAttentionBanner from '../components/musicVideo/NeedsAttentionBanner.jsx';import SetupStage from '../components/musicVideo/stages/SetupStage.jsx';import CastSetsStage from '../components/musicVideo/stages/CastSetsStage.jsx';import BoardStage from '../components/musicVideo/stages/BoardStage.jsx';@@ -78,6 +80,7 @@ import { autoArrangeScenes } from '../lib/beatGrid.js';import { isLtx2FamilyRuntime } from '../lib/runnerFamilies';import { videoPosterForJob } from '../lib/creativeDirectorPreview.js';import { sceneTakeList } from '../lib/musicVideoTakes.js';+import { deriveAttentionItems } from '../lib/musicVideoAttention.js';import {productionReviewStopGuidance, approvalSummary, deriveNextAction, deriveStages, projectShotSummary, describeProjectStatus, listPreviewSources, projectSpend, resolveStageParam,} from '../lib/musicVideoStages.js';@@ -217,6 +220,13 @@ export default function MusicVideo() {onTranscribed: (projectId, midiTranscription) => patchProject(projectId, { midiTranscription }),});const renderJob = useMusicVideoRenderJob({+ project: selected,+ // A cancelled or dropped render says nothing about the project's status: ask+ // the server, or the board keeps showing a render that is gone (#9940).+ onSettled: (reason, projectId) => {+ if (reason === 'complete' || reason === 'error') return;+ getMusicVideoProject(projectId, { silent: true }).then(replaceProject).catch(() => {});+ },onRendered: (projectId, result) => patchProject(projectId, (project) => ({renderHistoryId: result.id || project.renderHistoryId,status: 'complete', renderError: null,@@ -463,6 +473,7 @@ export default function MusicVideo() {}).catch((err) => { toast.error(err?.message || 'Could not align the words — planning without word timings'); return null; }),castAndSets: (project) => castSets.runToCheckpoint(project),+ cancelCastAndSets: () => castSets.cancelWait(),plan: (project) => handlePlan(project),});// Approve & continue: the kickoff resumes past the check-in and plans —@@ -835,6 +846,15 @@ export default function MusicVideo() {planning,analyzing,}) : null;+ // What the server holds that this tab might not be showing (#9940): derived+ // from the saved record, so it survives a reload. Work this tab can see+ // progressing (spinning sections, an attached render) is not flagged.+ const attentionItems = selected ? deriveAttentionItems(selected, {+ generatingSceneIds: new Set([...Object.keys(sceneMedia.genScenes || {}), ...Object.keys(sceneMedia.genVideoScenes || {})]+ .filter((sceneId) => sceneMedia.genScenes?.[sceneId] || sceneMedia.genVideoScenes?.[sceneId])),+ draftRendering: excerpts.rendering,+ finalRenderAttached: renderTargetsSelected,+ }) : [];const runNextAction = () => {if (!selected || !nextAction || nextAction.disabled || compositionSavePending > 0) return;if (nextAction.kind === 'goto') { goToStage(nextAction.stage, nextAction.anchor); return; }@@ -1212,6 +1232,20 @@ export default function MusicVideo() {onNextAction={runNextAction}spend={projectSpend(selected)}status={describeProjectStatus(selected, { progress, nextAction, readiness: productionReview.readiness })}+ attention={(+ <NeedsAttentionBanner+ items={attentionItems}+ busy={revisions.busy || castSets.busy || autoReview.busy || renderJob.reattaching}+ actions={{+ onResumeRevision: revisions.resume,+ onCancelRevision: revisions.cancel,+ onResumeCastAndSets: () => castSets.resume(),+ onContinueAutoReview: (runId) => autoReview.resume(runId),+ onCancelAutoReview: (runId) => autoReview.cancel(runId),+ onReattachRender: () => renderJob.reattach(selected.id),+ }}+ />+ )}dock={previewSources.length ? (<PreviewDockproject={selected}