Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix: autonomous music video waits for the final render before reporting Finished (#10149)
Adam Eivyca2d7665dbbd
diff --git a/client/src/components/musicVideo/AutonomousRunPanel.jsx b/client/src/components/musicVideo/AutonomousRunPanel.jsxindex 1b2875af0f..c9ab34817f 100644--- a/client/src/components/musicVideo/AutonomousRunPanel.jsx+++ b/client/src/components/musicVideo/AutonomousRunPanel.jsx@@ -2,14 +2,14 @@ import { useState } from 'react';import { Link } from 'react-router';import { AlertTriangle, CheckCircle2, Circle, CircleDot, ExternalLink, Loader2, Pause, Play, RotateCcw, Wand2, X, XCircle } from 'lucide-react';import {- AUTONOMOUS_CHECKPOINT_LABELS, AUTONOMOUS_LYRICS_STEP_LABELS, AUTONOMOUS_SONG_STEP_LABELS, AUTONOMOUS_STATUS_LABELS, AUTONOMOUS_VIEWABLE_STAGES,+ AUTONOMOUS_CHECKPOINT_LABELS, AUTONOMOUS_LYRICS_STEP_LABELS, AUTONOMOUS_PRODUCE_STEP_LABELS, AUTONOMOUS_SONG_STEP_LABELS, AUTONOMOUS_STATUS_LABELS, AUTONOMOUS_VIEWABLE_STAGES,autonomousStageOutput, autonomousStageRows, isAutonomousLive,} from '../../lib/musicVideoAutonomous.js';import { productionReviewStopGuidance } from '../../lib/musicVideoStages.js';import AutoApproveFields from './AutoApproveFields.jsx';// The stages that report a sub-step while they run (the server's `stages[id].step`).-const STEP_LABELS = { lyrics: AUTONOMOUS_LYRICS_STEP_LABELS, song: AUTONOMOUS_SONG_STEP_LABELS };+const STEP_LABELS = { lyrics: AUTONOMOUS_LYRICS_STEP_LABELS, produce: AUTONOMOUS_PRODUCE_STEP_LABELS, song: AUTONOMOUS_SONG_STEP_LABELS };const STATUS_TONES = {running: 'text-port-accent', 'awaiting-approval': 'text-port-warning', 'needs-human': 'text-port-warning', stopped: 'text-port-warning',@@ -78,6 +78,8 @@ export default function AutonomousRunPanel({ project, auto, readiness, selectedSconst changed = editable && draft !== editable.value;const canRetry = ['needs-human', 'failed', 'stopped'].includes(run.status) || run.interrupted;const tone = STATUS_TONES[run.status] || '';+ // A failed run that only has the final render left retries just that.+ const retryLabel = run.status === 'failed' && run.stage === 'produce' && (run.output?.renderJobId || run.output?.productionDone) ? 'Retry render' : run.status === 'failed' ? 'Retry' : 'Resume';// A stale or hand-edited `?run-stage=` that names no finished, viewable stage opens nothing.const selectedRow = rows.find((row) => row.id === selectedStage && row.status === 'done' && AUTONOMOUS_VIEWABLE_STAGES.includes(row.id)) || null;const selected = selectedRow?.id || null;@@ -145,6 +147,12 @@ export default function AutonomousRunPanel({ project, auto, readiness, selectedS</p>)}+ {run.status === 'completed' && project.renderHistoryId && (+ <Link to={`/music-video/${encodeURIComponent(project.id)}/review`} className="inline-flex items-center gap-1 text-sm text-port-accent hover:underline min-h-[44px] sm:min-h-0">+ Watch final video <ExternalLink size={12} aria-hidden="true" />+ </Link>+ )}+{guidance?.historical && <p className="text-xs text-port-text-muted break-words">Historical stop reason: {guidance.historical}</p>}{awaiting && (@@ -192,7 +200,7 @@ export default function AutonomousRunPanel({ project, auto, readiness, selectedS<div className="flex flex-wrap gap-2">{canRetry && !awaiting && (<button type="button" disabled={auto.busy} onClick={() => resume()} className={buttonClass}>- <Play size={14} aria-hidden="true" /> {run.status === 'failed' ? 'Retry' : 'Resume'}+ <Play size={14} aria-hidden="true" /> {retryLabel}</button>)}{run.status === 'running' && !run.interrupted && (diff --git a/client/src/components/musicVideo/AutonomousRunPanel.test.jsx b/client/src/components/musicVideo/AutonomousRunPanel.test.jsxindex 813b78a145..944a85dd5f 100644--- a/client/src/components/musicVideo/AutonomousRunPanel.test.jsx+++ b/client/src/components/musicVideo/AutonomousRunPanel.test.jsx@@ -75,8 +75,8 @@ function PanelWithUrl({ project, auto }) {);}-function Harness({ initial, url = '/music-video/mv-1' }) {- const [project, setProject] = useState({ id: 'mv-1', autonomousRun: initial });+function Harness({ initial, url = '/music-video/mv-1', extra = {} }) {+ const [project, setProject] = useState({ id: 'mv-1', autonomousRun: initial, ...extra });const auto = useAutonomousMusicVideo({ project, replaceProject: setProject });return <MemoryRouter initialEntries={[url]}><PanelWithUrl project={project} auto={auto} /></MemoryRouter>;}@@ -140,6 +140,22 @@ describe('AutonomousRunPanel', () => {await waitFor(() => expect(api.resumeAutonomousMusicVideo).toHaveBeenCalledWith('mv-1', {}, { silent: true }));});+ it('reads "Rendering final video" while the render runs, links the final video once finished, and retries only the render when it failed', () => {+ const produce = (step) => baseRun({ stage: 'produce', status: 'running', stages: stages({ style: { status: 'done' }, produce: { status: 'running', step } }), output: { renderJobId: 'job-1' } });+ const { unmount } = render(<Harness initial={produce('rendering')} />);+ expect(screen.getByRole('status').textContent).toContain('Rendering final video');+ expect(screen.queryByRole('link', { name: /watch final video/i })).toBeNull();+ unmount();++ const failed = baseRun({ stage: 'produce', status: 'failed', error: 'ffmpeg exit 1', output: { renderJobId: 'job-1' } });+ const { unmount: unmountFailed } = render(<Harness initial={failed} />);+ expect(screen.getByRole('button', { name: /retry render/i })).toBeTruthy();+ unmountFailed();++ render(<Harness initial={baseRun({ stage: 'produce', status: 'completed' })} extra={{ renderHistoryId: 'job-1' }} />);+ expect(screen.getByRole('link', { name: /watch final video/i }).getAttribute('href')).toBe('/music-video/mv-1/review');+ });+it('flags a run left over from before a server restart and offers to resume it', () => {render(<Harness initial={baseRun({ interrupted: true })} />);expect(screen.getByText(/interrupted — resume to continue/i)).toBeTruthy();diff --git a/client/src/lib/musicVideoAutonomous.js b/client/src/lib/musicVideoAutonomous.jsindex cef02714b2..d5cad3fdad 100644--- a/client/src/lib/musicVideoAutonomous.js+++ b/client/src/lib/musicVideoAutonomous.js@@ -154,6 +154,11 @@ export const AUTONOMOUS_SONG_STEP_LABELS = Object.freeze({importing: 'Importing into the music library',});+/** What the Produce stage is doing once production is done (the server's `stages.produce.step`). */+export const AUTONOMOUS_PRODUCE_STEP_LABELS = Object.freeze({+ rendering: 'Rendering final video',+});+/*** What a completed stage produced, read-only: `[{ key, label, text?, href? }]`* (empty when the stage stored nothing). A text field carries `multiline` whendiff --git a/server/services/musicVideo/autonomousService.js b/server/services/musicVideo/autonomousService.jsindex 3b11fa3ab4..eb6570b860 100644--- a/server/services/musicVideo/autonomousService.js+++ b/server/services/musicVideo/autonomousService.js@@ -31,7 +31,11 @@ import { assertProductionApproval, productionReadiness, productionProofNeedsRend** Production is delegated: `produce` starts the server-owned production run (or* the code render) and finishes when that reports back over the `production`- * event. Only explicit start/resume requests begin work.+ * event. Either way `produce` stays running ("Rendering final video") until the+ * final render job settles over the `render` event: success completes the run,+ * failure parks it `failed` and Retry re-renders only. A run interrupted while+ * rendering re-checks `renderHistoryId` on resume (reattach, finish, or render+ * again). Only explicit start/resume requests begin work.** Production review (art → storyboard → proof) parks `produce` until approved.* An authenticated start/resume can grant `brief.autoApprove` for planning;@@ -91,6 +95,8 @@ const defaults = {acceptDocument: async (...args) => (await import('./documentGeneration.js')).acceptMixedMediaDocument(...args),generateCode: async (...args) => (await import('./codeGeneration.js')).generateMusicVideoCode(...args),renderVideo: async (...args) => (await import('./render.js')).renderMusicVideo(...args),+ activeRenderJobId: async (projectId) => (await import('./render.js')).getActiveRenderJobId(projectId),+ cancelRender: async (jobId) => (await import('./render.js')).cancelRender(jobId),// The review persistence path; session authority was checked on start/resume.approveProductionReview: async (...args) => (await import('./productionReviewService.js')).approveProductionReview(...args),wait: (ms) => new Promise((resolve) => { setTimeout(resolve, ms); }),@@ -152,6 +158,7 @@ const stagePatch = (run, stage, patch) => ({ stages: { [stage]: { ...run.stages[// ---- production review auto-approval (brief.autoApprove) --------------------------+const RENDER_STEP = 'rendering';const PROOF_POLL_MS = 5_000;const PROOF_WAIT_MAX_MS = 90 * 60_000;const autoApproves = (run, stage) => normalizeAutoApprove(run.brief.autoApprove).includes(stage);@@ -421,7 +428,8 @@ const STAGES = {if (autoApproves(run, 'proof')) await awaitProofExcerpt(project.id, run);assertProductionApproval(await getProject(project.id));const render = await deps.renderVideo(project.id);- return { output: { renderJobId: render?.jobId || null } };+ // The run is not finished until the MP4 exists: stay on produce and let the render's own event settle it.+ return { output: { renderJobId: render?.jobId || null }, wait: true, step: RENDER_STEP };}const started = await deps.startProduction(project.id, {directive: trimTo([run.brief.prompt, run.brief.guidance].filter(Boolean).join('\n\n'), 4000),@@ -474,8 +482,10 @@ async function advance(projectId) {}const finishedAt = new Date().toISOString();if (result.wait) {- await patchRun(projectId, (r) => ({ output: result.output, ...stagePatch(r, stage, { status: 'running' }) }));- console.log(`🎬 Autonomous music video ${short(run.id)} handed ${stage} to production`);+ await patchRun(projectId, (r) => ({ output: result.output, ...stagePatch(r, stage, { status: 'running', step: result.step || null }) }));+ console.log(`🎬 Autonomous music video ${short(run.id)} handed ${stage} to ${result.step === RENDER_STEP ? 'the final render' : 'production'}`);+ // The render may have settled before its job id was stored on the run.+ if (result.step === RENDER_STEP) await reconcileFinalRender(projectId);return;}const next = nextAutonomousStage(stage);@@ -631,6 +641,12 @@ export async function resumeAutonomousVideo(projectId, edits = {}, { autoApprove.catch((err) => console.warn(`⚠️ Autonomous music video ${short(out.run.id)} could not unlink the retaken track: ${err.message}`));console.log(`🎬 Autonomous music video ${short(out.run.id)} retaking its song`);}+ if (out.run.stage === 'produce' && (out.run.output.renderJobId || out.run.output.productionDone)) {+ // Production (or the code render) already finished; only the final render is left.+ await reconcileFinalRender(projectId, { restart: true });+ const latest = await getProject(projectId);+ return { project: presentProjectAutonomousRun(latest), run: presentAutonomousRun(projectAutonomousRun(latest)) };+ }if (out.run.stage === 'produce' && out.run.output.productionRunId) {const { resumeProduction } = await import('./productionService.js');const failure = await resumeProduction(projectId, out.run.output.productionRunId, { acceptBasis: true }).then(() => null, (err) => err);@@ -667,6 +683,7 @@ export async function cancelAutonomousVideo(projectId) {const { run } = await requireRun(projectId);if (!(AUTONOMOUS_LIVE_STATUSES.includes(run.status) || run.status === 'failed')) throw runError(409, 'NOT_CANCELABLE', `A ${run.status} run cannot be canceled`);const out = await patchRun(projectId, () => ({ status: 'canceled', awaiting: null }));+ if (run.output.renderJobId) await deps.cancelRender(run.output.renderJobId).catch(() => {});if (run.output.productionRunId) {const { cancelProduction } = await import('./productionService.js');await cancelProduction(projectId, run.output.productionRunId).catch(() => {});@@ -695,13 +712,10 @@ async function onProductionEvent({ projectId, runId, run: production }) {if (!['running', 'needs-human'].includes(run.status)) return;const reason = trimTo(production.stopReason || production.error || '', 500);if (production.status === 'completed') {- const render = await deps.renderVideo(projectId).catch((err) => ({ error: err }));- await patchRun(projectId, (r) => ({- status: 'completed',- ...stagePatch(r, 'produce', { status: render.error ? 'failed' : 'done', finishedAt: new Date().toISOString(), error: render.error ? trimTo(render.error.message, 500) : null }),- ...(render.error ? { error: `The draft is ready, but the final render did not start: ${trimTo(render.error.message, 400)}` } : { output: { renderJobId: render.jobId || null } }),- }));- console.log(`✅ Autonomous music video ${short(run.id)} finished${render.error ? ' (final render did not start)' : ' — final render started'}`);+ // A repeated completion event must not start a second render.+ if (run.output.renderJobId) return;+ await patchRun(projectId, () => ({ status: 'running', processId: PROCESS_ID, output: { productionDone: true } }));+ await reconcileFinalRender(projectId, { restart: true });} else if (production.status === 'failed') {await park(projectId, 'failed', { error: reason || 'Production failed', errorCode: 'PRODUCTION_FAILED' });} else if (production.status === 'canceled') {@@ -711,6 +725,69 @@ async function onProductionEvent({ projectId, runId, run: production }) {}}+// ---- final render completion -----------------------------------------------------++/** Park the run as failed on its final render, with the stage marked failed so Retry re-renders only. */+async function failFinalRender(projectId, message, errorCode = 'FINAL_RENDER_FAILED') {+ const error = trimTo(message, 500);+ await patchRun(projectId, (r) => stagePatch(r, 'produce', { status: 'failed', error, step: null }));+ await park(projectId, 'failed', { error, errorCode });+}++async function completeFinalRender(projectId, run) {+ await patchRun(projectId, (r) => ({+ status: 'completed',+ ...stagePatch(r, 'produce', { status: 'done', finishedAt: new Date().toISOString(), error: null, step: null }),+ error: null, errorCode: null,+ }));+ console.log(`✅ Autonomous music video ${short(run.id)} finished — final video rendered`);+}++/** The run, when it is live on its produce stage waiting for the final render (job id or not yet started). */+const runAwaitingRender = (project) => {+ const run = projectAutonomousRun(project);+ return run && run.stage === 'produce' && run.status === 'running' && (run.output.renderJobId || run.output.productionDone) ? run : null;+};++/**+ * Settle a run waiting on its final render from the project's own record — the+ * race where the render ended before its job id was stored, and a resume after+ * a restart (the job died with the process). Still rendering → keep waiting;+ * `renderHistoryId` equal to the job id → it finished; otherwise it failed, or+ * with `restart` (an explicit resume, or production just completed) render again.+ */+async function reconcileFinalRender(projectId, { restart = false } = {}) {+ const project = await getProject(projectId).catch(() => null);+ const run = runAwaitingRender(project);+ if (!run) return;+ const jobId = run.output.renderJobId || null;+ if (jobId && (project.status === 'rendering' || (await deps.activeRenderJobId(projectId)) === jobId)) {+ await patchRun(projectId, (r) => stagePatch(r, 'produce', { status: 'running', step: RENDER_STEP }));+ return;+ }+ if (jobId && project.renderHistoryId === jobId) return completeFinalRender(projectId, run);+ if (!restart) return failFinalRender(projectId, project.renderError || 'The final render did not finish');+ const render = await deps.renderVideo(projectId).catch((err) => ({ error: err }));+ if (render.error) return failFinalRender(projectId, `The final render did not start: ${render.error.message}`, render.error.code || 'FINAL_RENDER_FAILED');+ await patchRun(projectId, (r) => ({ output: { renderJobId: render.jobId || null }, ...stagePatch(r, 'produce', { status: 'running', error: null, step: RENDER_STEP }), error: null, errorCode: null }));+ console.log(`🎬 Autonomous music video ${short(run.id)} is rendering the final video`);+ // A render that settled before its id was stored.+ await reconcileFinalRender(projectId);+}++async function onRenderEvent({ projectId, jobId, status, error }) {+ if (!projectId || !jobId) return;+ const project = await getProject(projectId).catch(() => null);+ const run = runAwaitingRender(project);+ if (!run || run.output.renderJobId !== jobId) return;+ if (status === 'completed') return completeFinalRender(projectId, run);+ return failFinalRender(projectId, error || (status === 'canceled' ? 'The final render was cancelled' : 'The final render failed'));+}++musicVideoEvents.on('render', (event) => {+ onRenderEvent(event).catch((err) => console.error(`❌ Autonomous music video could not settle on its final render: ${err.message}`));+});+musicVideoEvents.on('production', (event) => {onProductionEvent(event).catch((err) => console.error(`❌ Autonomous music video could not settle on production: ${err.message}`));});@@ -730,4 +807,4 @@ async function settleBackground(timeoutMs = 10_000) {}}-export const __testing = { onProductionEvent, advance, settleBackground };+export const __testing = { onProductionEvent, onRenderEvent, advance, settleBackground };diff --git a/server/services/musicVideo/autonomousService.test.js b/server/services/musicVideo/autonomousService.test.jsindex e661311877..d0fb900954 100644--- a/server/services/musicVideo/autonomousService.test.js+++ b/server/services/musicVideo/autonomousService.test.js@@ -95,6 +95,9 @@ beforeEach(() => {generateDocument: stub('document', async () => ({ document: { directory: 'music-video/mv-auto/composition/example' } })),acceptDocument: stub('accept-document', async (id, directory) => { store.get(id).composition.document = { directory }; return {}; }),renderVideo: stub('render', async () => ({ jobId: 'render-1' })),+ // The render job stays live until a test settles it with a `render` event.+ activeRenderJobId: vi.fn(async () => 'render-1'),+ cancelRender: vi.fn(async () => true),};service.__setAutonomousDepsForTests(doubles);});@@ -177,7 +180,74 @@ describe('startAutonomousVideo', () => {expect(runOf().status).toBe('running');await service.__testing.onProductionEvent({ projectId: 'mv-auto', runId: 'mvpr-1', run: { status: 'completed' } });- expect(runOf()).toMatchObject({ status: 'completed', output: expect.objectContaining({ renderJobId: 'render-1' }) });+ // Production being done is not the run being done: it reads "Rendering final video" until the render settles.+ expect(runOf()).toMatchObject({ status: 'running', stage: 'produce', stages: { produce: { status: 'running', step: 'rendering' } }, output: expect.objectContaining({ renderJobId: 'render-1' }) });+ // A repeated completion event does not start a second render.+ await service.__testing.onProductionEvent({ projectId: 'mv-auto', runId: 'mvpr-1', run: { status: 'completed' } });+ expect(doubles.renderVideo).toHaveBeenCalledOnce();+ // Another job's settlement is not ours.+ await service.__testing.onRenderEvent({ projectId: 'mv-auto', jobId: 'other', status: 'completed' });+ expect(runOf().status).toBe('running');++ await service.__testing.onRenderEvent({ projectId: 'mv-auto', jobId: 'render-1', status: 'completed' });+ expect(runOf()).toMatchObject({ status: 'completed', stages: { produce: { status: 'done', step: null } } });+ });++ it('parks failed when the final render fails after production, and Retry re-renders without resuming production', async () => {+ await service.startAutonomousVideo({ prompt: 'p' });+ await vi.waitFor(() => expect(runOf()?.output.productionRunId).toBe('mvpr-1'));+ await service.__testing.onProductionEvent({ projectId: 'mv-auto', runId: 'mvpr-1', run: { status: 'completed' } });+ await service.__testing.onRenderEvent({ projectId: 'mv-auto', jobId: 'render-1', status: 'failed', error: 'ffmpeg exit 1' });+ expect(runOf()).toMatchObject({ status: 'failed', error: 'ffmpeg exit 1', errorCode: 'FINAL_RENDER_FAILED', stages: { produce: { status: 'failed' } } });++ doubles.renderVideo.mockResolvedValueOnce({ jobId: 'render-2' });+ doubles.activeRenderJobId.mockResolvedValue('render-2');+ await service.resumeAutonomousVideo('mv-auto');+ expect(doubles.renderVideo).toHaveBeenCalledTimes(2);+ expect(runOf()).toMatchObject({ status: 'running', error: null, output: expect.objectContaining({ renderJobId: 'render-2' }), stages: { produce: { step: 'rendering' } } });+ await service.__testing.onRenderEvent({ projectId: 'mv-auto', jobId: 'render-2', status: 'completed' });+ expect(runOf().status).toBe('completed');+ });++ it('fails the run when the final render cannot start after production, and Retry tries again', async () => {+ await service.startAutonomousVideo({ prompt: 'p' });+ await vi.waitFor(() => expect(runOf()?.output.productionRunId).toBe('mvpr-1'));+ doubles.renderVideo.mockRejectedValueOnce(Object.assign(new Error('no audio'), { code: 'NO_AUDIO' }));+ await service.__testing.onProductionEvent({ projectId: 'mv-auto', runId: 'mvpr-1', run: { status: 'completed' } });+ expect(runOf()).toMatchObject({ status: 'failed', errorCode: 'NO_AUDIO', error: expect.stringContaining('did not start') });+ await service.resumeAutonomousVideo('mv-auto');+ expect(runOf()).toMatchObject({ status: 'running', output: expect.objectContaining({ renderJobId: 'render-1' }) });+ });++ it('settles from the project record when the render ended before its job id was stored', async () => {+ doubles.activeRenderJobId.mockResolvedValue(null);+ await service.startAutonomousVideo({ prompt: 'p' });+ await vi.waitFor(() => expect(runOf()?.output.productionRunId).toBe('mvpr-1'));+ store.get('mv-auto').renderHistoryId = 'render-1';+ await service.__testing.onProductionEvent({ projectId: 'mv-auto', runId: 'mvpr-1', run: { status: 'completed' } });+ expect(runOf().status).toBe('completed');+ });++ it('after a restart during the final render: finishes if the MP4 landed, otherwise renders again', async () => {+ await service.startAutonomousVideo({ prompt: 'p' });+ await vi.waitFor(() => expect(runOf()?.output.productionRunId).toBe('mvpr-1'));+ await service.__testing.onProductionEvent({ projectId: 'mv-auto', runId: 'mvpr-1', run: { status: 'completed' } });+ // The previous process died mid-render.+ store.get('mv-auto').autonomousRun.processId = 'proc-previous';+ doubles.activeRenderJobId.mockResolvedValue(null);+ store.get('mv-auto').renderHistoryId = 'render-1';+ await service.resumeAutonomousVideo('mv-auto');+ expect(doubles.renderVideo).toHaveBeenCalledOnce();+ expect(runOf().status).toBe('completed');++ // Same interruption, but the render never produced a file.+ store.get('mv-auto').autonomousRun = { ...runOf(), status: 'running', processId: 'proc-previous', stages: { ...runOf().stages, produce: { ...runOf().stages.produce, status: 'running' } } };+ delete store.get('mv-auto').renderHistoryId;+ doubles.renderVideo.mockResolvedValueOnce({ jobId: 'render-3' });+ doubles.activeRenderJobId.mockResolvedValue('render-3');+ await service.resumeAutonomousVideo('mv-auto');+ expect(doubles.renderVideo).toHaveBeenCalledTimes(2);+ expect(runOf().output.renderJobId).toBe('render-3');});it('parks needs-human when production parks, and failed when it fails', async () => {@@ -196,7 +266,27 @@ describe('startAutonomousVideo', () => {expect(doubles.acceptDocument).toHaveBeenCalledWith('mv-auto', 'music-video/mv-auto/composition/example');expect(doubles.generateDocument).toHaveBeenCalledWith('mv-auto', { providerId: 'prov', model: 'm' });expect(store.get('mv-auto').composition).toMatchObject({ mode: 'document', authoringRenderer: 'three' });- await settled('completed');+ // Queued is not finished: the run waits on the render job.+ await vi.waitFor(() => expect(runOf()).toMatchObject({ status: 'running', stage: 'produce', output: { renderJobId: 'render-1' }, stages: { produce: { step: 'rendering' } } }));+ await service.__testing.onRenderEvent({ projectId: 'mv-auto', jobId: 'render-1', status: 'completed' });+ expect(runOf().status).toBe('completed');+ });++ it('code path: a failed final render parks the run failed, and a restart re-checks the render', async () => {+ await service.startAutonomousVideo({ prompt: 'p', tools: ['code:render'], authoring: { providerId: 'prov', model: 'm' } });+ await vi.waitFor(() => expect(runOf()?.output.renderJobId).toBe('render-1'));+ await service.__testing.onRenderEvent({ projectId: 'mv-auto', jobId: 'render-1', status: 'failed', error: 'Render cancelled' });+ expect(runOf()).toMatchObject({ status: 'failed', errorCode: 'FINAL_RENDER_FAILED', error: 'Render cancelled' });++ doubles.renderVideo.mockResolvedValueOnce({ jobId: 'render-2' });+ doubles.activeRenderJobId.mockResolvedValue('render-2');+ await service.resumeAutonomousVideo('mv-auto');+ expect(runOf()).toMatchObject({ status: 'running', output: { renderJobId: 'render-2' } });+ // Interrupted while rendering: the render is still live in this process, so resume reattaches.+ store.get('mv-auto').autonomousRun.processId = 'proc-previous';+ await service.resumeAutonomousVideo('mv-auto');+ expect(doubles.renderVideo).toHaveBeenCalledTimes(2);+ expect(runOf()).toMatchObject({ status: 'running', output: { renderJobId: 'render-2' } });});it('resolves the direction LLM once per text stage: brief and lyrics run on the resolved TUI route, effort included, and the route is recorded (#9545)', async () => {@@ -483,6 +573,7 @@ describe('failure and retry', () => {await vi.waitFor(() => expect(runOf()?.output.productionRunId).toBe('mvpr-1'));await expect(service.resumeAutonomousVideo('mv-auto')).rejects.toMatchObject({ code: 'ALREADY_RUNNING' });await service.__testing.onProductionEvent({ projectId: 'mv-auto', runId: 'mvpr-1', run: { status: 'completed' } });+ await service.__testing.onRenderEvent({ projectId: 'mv-auto', jobId: 'render-1', status: 'completed' });await expect(service.resumeAutonomousVideo('mv-auto')).rejects.toMatchObject({ code: 'NOT_RESUMABLE' });});});@@ -718,6 +809,8 @@ it('parks standalone code at real human gates and replaces a stale proof beforeexpect(doubles.renderVideo).not.toHaveBeenCalled();approve('proof');await service.resumeAutonomousVideo('mv-auto');+ await vi.waitFor(() => expect(runOf()?.output.renderJobId).toBe('render-1'));+ await service.__testing.onRenderEvent({ projectId: 'mv-auto', jobId: 'render-1', status: 'completed' });await settled('completed');expect(doubles.renderVideo).toHaveBeenCalledOnce();expect(doubles.generateDocument).toHaveBeenCalledOnce();diff --git a/server/services/musicVideo/events.js b/server/services/musicVideo/events.jsindex a1d6834f7d..0bdc93b98a 100644--- a/server/services/musicVideo/events.js+++ b/server/services/musicVideo/events.js@@ -37,6 +37,12 @@ import { EventEmitter } from 'events';// (a stage settled, a checkpoint is waiting, it needs the director, it// finished); bridged to `music-video:autonomous`.//+// A final render adds:+// 'render' → { projectId, jobId, status: 'completed'|'failed'|'canceled', error }+// — a final music-video render job settled and its project write landed+// (server-only; an autonomous run waiting on its final render finishes or+// fails from it).+//// The Cast & Sets check-in adds:// 'cast-and-sets' → { projectId, stage, project } — the check-in stage// advanced (direction, an image landed, the sheet is ready, approved);diff --git a/server/services/musicVideo/render.js b/server/services/musicVideo/render.jsindex b3f2c60ddd..eca29c7ba7 100644--- a/server/services/musicVideo/render.js+++ b/server/services/musicVideo/render.js@@ -87,6 +87,15 @@ export const isLocalRenderMark = (renderingOn, instanceId) => !renderingOn || re// partial-output pointer alongside the status.const settledRender = (status, extra = {}) => ({ status, ...extra, renderingOn: null, renderPartialFilename: null });+// Tell listeners (the autonomous run waiting on its final render) that a render+// job reached a terminal state. Emitted after the project record's terminal+// write, with the outcome read off the job the caller already settled.+const emitRenderSettled = (projectId, job) => musicVideoEvents.emit('render', {+ projectId, jobId: job.id,+ status: job.status === 'complete' ? 'completed' : job.status === 'canceled' ? 'canceled' : 'failed',+ error: job.lastError || null,+});+export const attachRenderSseClient = (jobId, res) => attachSse(jobs, jobId, res);// #8964 loop semantics. A scene saved before shot planning existed has no@@ -713,6 +722,7 @@ async function renderSeekedMode(projectId, project, handOff, renderer, options =await updateProject(projectId, settledRender(patch.status, { renderError: patch.status === 'failed' ? job.lastError?.slice(0, 2000) || 'Render failed' : null, ...patch.extra })).catch((err) => {console.error(`❌ Music-video ${renderer.label} render [${jobId.slice(0, 8)}] project ${projectId.slice(0, 8)} status→${patch.status} write failed: ${err.message}`);});+ emitRenderSettled(projectId, job);if (options.productionRunId) musicVideoEvents.emit('document-render', { projectId, runId: options.productionRunId, attemptId: options.productionRenderAttemptId, jobId, status: patch.status === 'complete' ? 'completed' : 'failed', error: job.lastError || null });closeJobAfterDelay(jobs, jobId);};@@ -897,6 +907,7 @@ export async function renderMusicVideo(projectId, options = {}) {await updateProject(projectId, settledRender('failed')).catch((updateErr) => {console.error(`❌ Music-video render [${jobId.slice(0, 8)}] project ${projectId.slice(0, 8)} status→failed write failed: ${updateErr.message}`);});+ emitRenderSettled(projectId, job);await releaseScratch();closeJobAfterDelay(jobs, jobId);},@@ -919,6 +930,7 @@ export async function renderMusicVideo(projectId, options = {}) {await updateProject(projectId, settledRender(targetStatus)).catch((updateErr) => {console.error(`❌ Music-video render [${jobId.slice(0, 8)}] project ${projectId.slice(0, 8)} status→${targetStatus} write failed: ${updateErr.message}`);});+ emitRenderSettled(projectId, job);await releaseScratch();closeJobAfterDelay(jobs, jobId);return;@@ -956,6 +968,7 @@ export async function renderMusicVideo(projectId, options = {}) {await updateProject(projectId, settledRender('complete', { renderHistoryId: jobId, renderDependencies: captureMusicVideoEvidence(project) })).catch((updateErr) => {console.error(`❌ Music-video render [${jobId.slice(0, 8)}] project ${projectId.slice(0, 8)} status→complete write failed: ${updateErr.message}`);});+ emitRenderSettled(projectId, job);console.log(`✅ Music video rendered [${jobId.slice(0, 8)}]: ${filename}`);broadcastSse(job, { type: 'complete', result: { id: jobId, filename, thumbnail: thumb, path: `/data/videos/${filename}` } });} catch (err) {@@ -966,6 +979,7 @@ export async function renderMusicVideo(projectId, options = {}) {await updateProject(projectId, settledRender('failed')).catch((updateErr) => {console.error(`❌ Music-video render [${jobId.slice(0, 8)}] project ${projectId.slice(0, 8)} status→failed write failed: ${updateErr.message}`);});+ emitRenderSettled(projectId, job);} finally {projectRenders.delete(projectId);await releaseScratch();@@ -1009,6 +1023,7 @@ export async function renderMusicVideo(projectId, options = {}) {await updateProject(projectId, settledRender(targetStatus)).catch((updateErr) => {console.error(`❌ Music-video render [${jobId.slice(0, 8)}] project ${projectId.slice(0, 8)} status→${targetStatus} write failed: ${updateErr.message}`);});+ emitRenderSettled(projectId, job);await releaseScratch();closeJobAfterDelay(jobs, jobId);});diff --git a/server/services/musicVideo/render.terminal.test.js b/server/services/musicVideo/render.terminal.test.jsindex 87cdfc9808..39d3eb33cb 100644--- a/server/services/musicVideo/render.terminal.test.js+++ b/server/services/musicVideo/render.terminal.test.js@@ -84,6 +84,7 @@ import { loadHistory } from '../videoGen/local.js';import { getTrack } from '../tracks/index.js';import { getProject, listProjects, updateProject, mutateProjectRecord } from './projects.js';import { unlink } from 'fs/promises';+import { musicVideoEvents } from './events.js';const tick = () => new Promise((r) => setTimeout(r, 0));const lastProc = () => h.procs[h.procs.length - 1];@@ -110,12 +111,18 @@ describe('renderMusicVideo terminal handling (#2386)', () => {it('finalizes immediately on a PRE-spawn error and releases the project slot', async () => {const pid = 'pre-1';prime(pid);+ const settledEvents = [];+ const onRender = (e) => settledEvents.push(e);+ musicVideoEvents.on('render', onRender);const { jobId } = await renderMusicVideo(pid);const proc = lastProc();// No 'spawn' event → genuine spawn failure. 'close' will not follow.proc.emit('error', new Error('spawn ENOENT'));await tick();+ musicVideoEvents.off('render', onRender);+ // An autonomous run waiting on this render learns it failed (and why).+ expect(settledEvents).toEqual([{ projectId: pid, jobId, status: 'failed', error: expect.stringMatching(/Failed to spawn ffmpeg/) }]);expect(getRenderJobStatus(jobId).status).toBe('error');expect(getRenderJobStatus(jobId).error).toMatch(/Failed to spawn ffmpeg/);