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: persist scene render failures with scene and reason, restore in-flight scene renders after reload (#10154)
Adam Eivyafd7afdd19e5
diff --git a/client/src/components/musicVideo/CodeVideoPanel.jsx b/client/src/components/musicVideo/CodeVideoPanel.jsxindex c17c6abeb9..a1af0c3961 100644--- a/client/src/components/musicVideo/CodeVideoPanel.jsx+++ b/client/src/components/musicVideo/CodeVideoPanel.jsx@@ -51,6 +51,7 @@ export default function CodeVideoPanel({ project, audioUrl, onProject, productiouseEffect(() => {if (!section || requested === section.id) return undefined;setSearchParams((prev) => {+ if (!requested && prev.has('section')) return prev;const next = new URLSearchParams(prev);next.set('section', section.id);return next;diff --git a/client/src/components/musicVideo/CodeVideoPanel.test.jsx b/client/src/components/musicVideo/CodeVideoPanel.test.jsxindex 48ba172b91..cea0981be5 100644--- a/client/src/components/musicVideo/CodeVideoPanel.test.jsx+++ b/client/src/components/musicVideo/CodeVideoPanel.test.jsx@@ -120,6 +120,7 @@ describe('CodeVideoPanel section select (#10163)', () => {it('changes the ?section= param when a section is selected', async () => {renderPanel();const select = await screen.findByLabelText('Section to regenerate');+ await waitFor(() => expect(select.value).toBe('a'));fireEvent.change(select, { target: { value: 'b' } });await waitFor(() => {expect(select.value).toBe('b');diff --git a/client/src/components/musicVideo/SceneCard.jsx b/client/src/components/musicVideo/SceneCard.jsxindex 5235a803cf..9e8cdcf331 100644--- a/client/src/components/musicVideo/SceneCard.jsx+++ b/client/src/components/musicVideo/SceneCard.jsx@@ -136,7 +136,12 @@ export default function SceneCard({// #10152: what needs the director's attention, visible without opening the card.const attention = sceneAttention(scene, { layered, footageOptional, lipSyncBackend, songDurationSec, clipSec, failed: failedScenes || {} });const generatingLane = generatingFrame && generatingVideo ? 'Frame + clip' : generatingFrame ? 'Frame' : generatingVideo ? 'Clip' : null;+ // #10154: the server-persisted failure of the last render, shown until a+ // retry is in flight (or lands a take, which clears it server-side).+ const failure = scene.lastFailure && !(scene.lastFailure.lane === 'video' ? generatingVideo : generatingFrame)+ ? scene.lastFailure : null;return (+ <div className="min-w-0"><detailsref={detailsRef}id={`scene-${scene.sceneId}`}@@ -144,7 +149,7 @@ export default function SceneCard({onToggle={(e) => {onToggleExpand?.(scene.sceneId, e.currentTarget.open);}}- className="group min-w-0 rounded-lg border border-port-border bg-port-card"+ className="group rounded-lg border border-port-border bg-port-card"><summaryonClick={() => onSeek?.(scene)}@@ -479,5 +484,19 @@ export default function SceneCard({onOpenPreview={onOpenPreview} /></div></details>+ {failure && (+ <div className="mt-1 flex items-start gap-2 rounded border border-port-error/40 bg-port-error/10 px-2 py-1 text-xs text-port-error">+ <AlertTriangle size={14} className="mt-0.5 shrink-0" aria-hidden="true" />+ <span className="min-w-0 flex-1 break-words">+ {failure.lane === 'video' ? 'Video' : 'Frame'} failed: {failure.error}+ </span>+ <button type="button"+ onClick={() => (failure.lane === 'video' ? onGenerateVideo?.(scene) : onGenerateFrame?.(scene))}+ className="inline-flex min-h-[44px] shrink-0 items-center px-1 font-medium underline sm:min-h-0">+ Retry+ </button>+ </div>+ )}+ </div>);}diff --git a/client/src/components/musicVideo/SceneCard.test.jsx b/client/src/components/musicVideo/SceneCard.test.jsxindex a11c51e6e3..f2c7ad7cdb 100644--- a/client/src/components/musicVideo/SceneCard.test.jsx+++ b/client/src/components/musicVideo/SceneCard.test.jsx@@ -29,3 +29,27 @@ describe('performance speaker save boundary', () => {await waitFor(() => expect(generate.disabled).toBe(false));});});++describe('persisted render failure chip (#10154)', () => {+ const failedScene = (lane) => ({ sceneId: 's1', startSec: 0, endSec: 5, referenceImageId: 'frame.png', takes: [],+ lastFailure: { lane, error: 'CUDA out of memory', at: '2026-10-05T00:00:00.000Z' } });++ it('shows "Frame failed: <reason>" with a Retry that re-runs the failed lane, and hides while retrying', () => {+ const onGenerateFrame = vi.fn();+ const onGenerateVideo = vi.fn();+ const props = { index: 0, onEditLocal: vi.fn(), onSave: vi.fn(), onGenerateFrame, onGenerateVideo };+ const { rerender } = render(<SceneCard scene={failedScene('image')} {...props} />);+ expect(screen.getByText(/Frame failed: CUDA out of memory/)).toBeTruthy();+ fireEvent.click(screen.getByRole('button', { name: 'Retry' }));+ expect(onGenerateFrame).toHaveBeenCalledWith(expect.objectContaining({ sceneId: 's1' }));+ expect(onGenerateVideo).not.toHaveBeenCalled();++ rerender(<SceneCard scene={failedScene('image')} generatingFrame {...props} />);+ expect(screen.queryByText(/Frame failed/)).toBeNull();++ rerender(<SceneCard scene={failedScene('video')} {...props} />);+ expect(screen.getByText(/Video failed: CUDA out of memory/)).toBeTruthy();+ fireEvent.click(screen.getByRole('button', { name: 'Retry' }));+ expect(onGenerateVideo).toHaveBeenCalledTimes(1);+ });+});diff --git a/client/src/hooks/README.md b/client/src/hooks/README.mdindex 16f4fe283a..1a2e933c9b 100644--- a/client/src/hooks/README.md+++ b/client/src/hooks/README.md@@ -53,7 +53,7 @@ grep -i "what you want to do" client/src/hooks/README.md| `useProcessLogs` | Live PM2 log tail for one process over the shared socket: owns the `logs:subscribe`/`line`/`subscribed`/`error` lifecycle, per-`processName` frame filtering, and a 1000-line ring buffer. Pass `appId` so an app with its own PM2_HOME streams from the right home. Returns `{ logs, subscribed, status, statusDetail, retry, clear }`; `status` is `connecting`/`live`/`closed`/`error`/`disconnected`, shared by every consumer — a closed/errored/disconnected stream keeps its lines and `retry()` resubscribes once (#9959). | Any surface showing a PM2 process's live output (Processes tab, desktop-app launch progress). || `useMediaJobProgress` | Live progress for a single `mediaJobQueue` job. | Subscribing to a known media-job id. || `useSceneBatch` | Counter for one Music Video "generate every missing frame / clip" batch (#10153): `{ state, begin, register, kickoffFailed, completedWithoutJob, settled, cancel, dismiss }`. Fed by a lane's `onSettled`; `cancel()` cancels the batch's queued and running jobs through the media-job cancel API (spinners clear via the lane's canceled event). | A batch of per-scene renders that needs "N of M done · K failed" and "Cancel remaining". |-| `useSceneRenderLifecycle` | One Music Video board lane's async-render lifecycle: owns the per-scene spinner state (`genScenes`), job-id→scene correlation, orphan-terminal reconcile, and the durable-attach + `*-gen:completed/failed/canceled` socket subscription (with running-cancel toast disambiguation). Optional `startedEvent` / `progressEvent` feed `sceneProgress` (queued → running + fraction) and `onSettled({ jobId, sceneId, outcome })` reports each tracked job's terminal outcome. Returns `{ genScenes, sceneProgress, startScene, clearScene, trackJob }`. | A board lane that kicks media-job renders per scene and clears spinners from terminal events (reference frame, i2v clip). One call per lane. |+| `useSceneRenderLifecycle` | One Music Video board lane's async-render lifecycle: owns the per-scene spinner state (`genScenes`), job-id→scene correlation, orphan-terminal reconcile, and the durable-attach + `*-gen:completed/failed/canceled` socket subscription (with running-cancel toast disambiguation). Optional `startedEvent` / `progressEvent` feed `sceneProgress` (queued → running + fraction) and `onSettled({ jobId, sceneId, outcome })` reports each tracked job's terminal outcome; failure toasts name the scene + the failed event's `error` and a batch collapses into one summary toast; `restoreJobs([{ jobId, sceneId }])` re-lights spinners after a reload (#10154). Returns `{ genScenes, sceneProgress, failedScenes, startScene, clearScene, trackJob, restoreJobs }`. | A board lane that kicks media-job renders per scene and clears spinners from terminal events (reference frame, i2v clip). One call per lane. || `useSlotInFlight` | Whether a render slot (`{ jobId, filename }`) has an in-flight render; returns `{ inFlight, setStatus }`. A present `filename` (or 5s grace on a stale/expired job) clears `inFlight` so the render button never sticks "loading". | A render button that should disable + spin only while its own slot is actually rendering (comic pages, covers). Wire `setStatus` to the slot's `MediaJobThumb` `onStatus`. || `useMediaJobSse` | The one owner of a displayed media render's lifecycle: `start(kickoff, handlers, { jobIdOf, ifIdle, onKickoffError })` runs the POST (or an active-job read), adopts the acknowledged job and awaits its `/{kind}-gen/:id/events` terminal frame; `cancel()` cancels only that job (before the acknowledgement it cancels the eventual job once, opening no stream); `dispose()` (also on unmount) detaches without cancelling durable work. A cancelled/detached/superseded run settles once with an error `isMediaRunEnded()` recognises. `attach()` stays the bare transport. | POST-then-attach (or resume-then-attach) media render flows — Video Gen, Image Gen, Settings Test Render. Don't keep a page-local job id / run token / reject ref / raw `EventSource` close. || `useOpenClawStream` | OpenClaw SSE chat stream. | OpenClaw file-browser chat surface only. |@@ -265,7 +265,7 @@ grep -i "what you want to do" client/src/hooks/README.md| `useMusicVideoPublishKit` | Music Video publishing kit (#9281): a `useSseJobSlot` build job (encodes, thumbnails, captions, chapters) whose terminal frame reloads the project, plus the one-call copy draft, per-field copy edits and thumbnail choice, each applying the returned project. Returns `{ building, progress, build(), cancelBuild(), drafting, saving, draftCopy(body), saveCopy(patch), selectThumbnail(filename) }`. | The Music Video Publish stage. || `useMusicVideoPublishing` | Music Video posting (#9282): per-platform drafts filled in the PortOS Browser. `prepare` returns the filled draft's summary and screenshot (a sign-in-required refusal is kept as the platform's error with its login URL), `submit` posts that reviewed draft and applies the returned project, `discard` closes it. Platforms are opt-in (#9287): it loads the saved `platforms` (enabled + optional account each) and per-platform `history` (posts, reception tally, recent notes across projects); `setPlatform` toggles one optimistically and `recordPost` saves a hand-made post's link or a post's reception and notes. Returns `{ drafts, busy, errors, prepare(target, options), submit(target), discard(target), platforms, history, enabledTargets, setPlatform(target, change), recordPost(target, body) }`. | The Music Video Publish stage's posting panel. || `useMusicVideoModelSettings` | A project's saved render pins — video backend (local/Grok/fal.ai)/model/generation-mode/audio-reactive LoRA + the image-side frame pin — with the Video Gen catalog they read from. Optimistic-local + silent PATCH, rollback + toast on failure; `saving` gates the dependent generate buttons. Returns `{ models, modelsLoading, defaultModel, falEnabled, saving, settings, effectiveModelId, activeModel, audioReactiveModels, audioReactiveLoras, detectedAudioReactiveLora, audioReactiveReady, audioReactiveSelected, videoBlockedReason, change, changeFramePin }`. `videoBlockedReason` is the single "why can't I generate" string (an unavailable audio-reactive setup, or a fal.ai pin with no configured API key) shared by the disabled buttons, their tooltips, and the blocked-call toast. | The Music Video renderer selects and anything building a scene-clip job payload from them. |-| `useMusicVideoSceneMedia` | Both per-scene generation lanes (reference frame + scene clip) over `useSceneRenderLifecycle`, the frame/shot prompt builders (concept-style + visual-spec direction suffix), visual-spec reference-image conditioning with explicit unsupported-backend feedback (#8965), and the batch "generate the missing ones" actions. Returns `{ genScenes, genVideoScenes, conditioning, buildFramePrompt, buildShotPrompt, generateFrame, generateSceneVideo, continueSceneVideo, generateMissingFrames, generateMissingVideos, planMissingFrames, planMissingVideos, frameBatch, videoBatch, sceneProgress, videoSceneProgress }` (the batches run counted via `useSceneBatch`; the board confirms count + estimate before calling `generateMissing*`). | The Music Video scene board — don't re-wire the two lanes or re-derive the i2v/a2v/extend payloads. |+| `useMusicVideoSceneMedia` | Both per-scene generation lanes (reference frame + scene clip) over `useSceneRenderLifecycle`, the frame/shot prompt builders (concept-style + visual-spec direction suffix), visual-spec reference-image conditioning with explicit unsupported-backend feedback (#8965), the batch "generate the missing ones" actions, restores in-flight scene renders from the server queue on mount (`getMusicVideoSceneJobs`) so a reload doesn't invite duplicate submits, and folds the persisted `scene.lastFailure` (socket `music-video:scene-failure`) onto the scene (#10154). Returns `{ genScenes, genVideoScenes, conditioning, buildFramePrompt, buildShotPrompt, generateFrame, generateSceneVideo, continueSceneVideo, generateMissingFrames, generateMissingVideos, planMissingFrames, planMissingVideos, frameBatch, videoBatch, sceneProgress, videoSceneProgress }` (the batches run counted via `useSceneBatch`; the board confirms count + estimate before calling `generateMissing*`). | The Music Video scene board — don't re-wire the two lanes or re-derive the i2v/a2v/extend payloads. || `useMusicVideoTakes` | Scene-take review + external-asset handoff for the Music Video board (#8965): serialized select / reject / note / gallery-import take mutations folded back as scene patches, the handoff manifest download, and the handoff import (gallery upload per file, then scene association by file tag with provider provenance). Returns `{ busy, selectTake, reviewTake, importTake, exportHandoff, importHandoffFiles }`. | The Music Video board's take strips, contact sheet and handoff row — don't re-sequence take mutations per call site. || `useMusicVideoTreatment` | The Music Video pre-production treatment (#8980): serialized brief/arc/shot-direction saves that each carry the latest known treatment revision (a 409 from a newer copy reloads the project), explicit compile (AI or deterministic) with skip-reason feedback, the Apply review (`loadPreview` → `apply({ overwrite, addTextCues })`) and proof verdicts. Returns `{ compiling, preview, previewing, applying, save, compile, loadPreview, apply, reviewProof, clearPreview }`. | The Music Video treatment panel — don't re-derive the revision bookkeeping per call site. || `useMusicVideoManualTempo` | The manual-tempo fallback for a project whose auto-detected BPM is null: BPM/offset drafts (reset on project switch), tap-tempo estimation, and the persisted `setMusicVideoManualTempo` call. Returns `{ bpm, setBpm, offset, setOffset, saving, tap, submit }`. | The Music Video "No tempo detected" row. |diff --git a/client/src/hooks/useMusicVideoSceneMedia.batch.test.jsx b/client/src/hooks/useMusicVideoSceneMedia.batch.test.jsxindex f430df26ec..c175b8f5d0 100644--- a/client/src/hooks/useMusicVideoSceneMedia.batch.test.jsx+++ b/client/src/hooks/useMusicVideoSceneMedia.batch.test.jsx@@ -12,7 +12,10 @@ vi.mock('../services/socket', () => ({const generateVideo = vi.fn();vi.mock('../services/apiImageVideo.js', () => ({ generateVideo: (...a) => generateVideo(...a) }));vi.mock('../services/apiSystem.js', () => ({ generateImage: vi.fn() }));-vi.mock('../services/apiMusicVideo.js', () => ({ addMusicVideoSceneTake: vi.fn() }));+vi.mock('../services/apiMusicVideo.js', () => ({+ addMusicVideoSceneTake: vi.fn(),+ getMusicVideoSceneJobs: vi.fn(async () => ({ jobs: [] })),+}));const cancelMediaJob = vi.fn(() => Promise.resolve({}));vi.mock('../services/apiMediaJobs', () => ({ getMediaJob: vi.fn(), cancelMediaJob: (...a) => cancelMediaJob(...a) }));vi.mock('../components/ui/Toast', () => ({ default: { error: vi.fn(), info: vi.fn(), success: vi.fn() } }));diff --git a/client/src/hooks/useMusicVideoSceneMedia.js b/client/src/hooks/useMusicVideoSceneMedia.jsindex e473d19fc2..e3dee4bf00 100644--- a/client/src/hooks/useMusicVideoSceneMedia.js+++ b/client/src/hooks/useMusicVideoSceneMedia.js@@ -1,8 +1,10 @@import { shotActionContractProblem, shotActionPrompt } from '../../../server/lib/musicVideoActionContract.js';import { musicVideoConditioningReferences, MUSIC_VIDEO_MAX_CONDITIONING_REFERENCES } from '../../../server/lib/musicVideoConditioning.js';import { musicVideoCreativeContext } from '../../../server/lib/musicVideoCreativeContext.js';+import { useEffect, useRef } from 'react';+import socket from '../services/socket';import toast from '../components/ui/Toast';-import { addMusicVideoSceneTake } from '../services/apiMusicVideo.js';+import { addMusicVideoSceneTake, getMusicVideoSceneJobs } from '../services/apiMusicVideo.js';import { generateImage } from '../services/apiSystem.js';import { generateVideo } from '../services/apiImageVideo.js';import useSceneBatch from './useSceneBatch.js';@@ -90,6 +92,14 @@ const sceneSpanSec = (scene) => (typeof scene.startSec === 'number' && typeof scexport default function useMusicVideoSceneMedia({ project, videoSettings, applyScenePatch } = {}) {const frameBatch = useSceneBatch();const videoBatch = useSceneBatch();+ // Latest scenes for the failure toasts' scene names, read lazily (a lane+ // callback fires long after the render that created it).+ const projectRef = useRef(project);+ projectRef.current = project;+ const sceneLabel = (sceneId) => {+ const scene = projectRef.current?.scenes?.find((s) => s.sceneId === sceneId);+ return scene ? (scene.sectionLabel || scene.label || `Scene ${(scene.order ?? 0) + 1}`) : '';+ };const frameLane = useSceneRenderLifecycle({attachEvent: 'music-video:scene-image',completedEvent: 'image-gen:completed',@@ -98,9 +108,10 @@ export default function useMusicVideoSceneMedia({ project, videoSettings, applySstartedEvent: 'image-gen:started',progressEvent: 'image-gen:progress',onSettled: frameBatch.settled,- apply: ({ projectId, sceneId, referenceImageId, takes }) =>- applyScenePatch?.(projectId, sceneId, { referenceImageId, ...(Array.isArray(takes) ? { takes } : {}) }),+ apply: ({ projectId, sceneId, referenceImageId, takes, lastFailure }) =>+ applyScenePatch?.(projectId, sceneId, { referenceImageId, ...(Array.isArray(takes) ? { takes } : {}), ...(lastFailure !== undefined ? { lastFailure } : {}) }),failMessage: 'Frame render failed',+ sceneLabel,});const videoLane = useSceneRenderLifecycle({attachEvent: 'music-video:scene-video',@@ -110,10 +121,40 @@ export default function useMusicVideoSceneMedia({ project, videoSettings, applySstartedEvent: 'video-gen:started',progressEvent: 'video-gen:progress',onSettled: videoBatch.settled,- apply: ({ projectId, sceneId, videoHistoryId, takes }) =>- applyScenePatch?.(projectId, sceneId, { videoHistoryId, ...(Array.isArray(takes) ? { takes } : {}) }),+ apply: ({ projectId, sceneId, videoHistoryId, takes, lastFailure }) =>+ applyScenePatch?.(projectId, sceneId, { videoHistoryId, ...(Array.isArray(takes) ? { takes } : {}), ...(lastFailure !== undefined ? { lastFailure } : {}) }),failMessage: 'Scene video render failed',+ sceneLabel,});++ // The server persists a failed scene render on the scene (#10154); fold it in+ // live so the card's "failed · Retry" chip appears without a refetch.+ const applyRef = useRef(applyScenePatch);+ applyRef.current = applyScenePatch;+ useEffect(() => {+ const onFailure = ({ projectId, sceneId, lastFailure }) => applyRef.current?.(projectId, sceneId, { lastFailure: lastFailure ?? null });+ socket.on('music-video:scene-failure', onFailure);+ return () => socket.off('music-video:scene-failure', onFailure);+ }, []);++ // After a reload the lanes' spinners (React state) are gone while the queue+ // keeps rendering — restore them from the server so the batch actions skip+ // those scenes and no duplicate (possibly paid) render is submitted (#10154).+ const projectId = project?.id;+ const { restoreJobs: restoreFrameJobs } = frameLane;+ const { restoreJobs: restoreVideoJobs } = videoLane;+ useEffect(() => {+ if (!projectId) return undefined;+ let live = true;+ getMusicVideoSceneJobs(projectId, { silent: true })+ .then(({ jobs }) => {+ if (!live || !Array.isArray(jobs)) return;+ restoreFrameJobs(jobs.filter((j) => j.lane === 'image'));+ restoreVideoJobs(jobs.filter((j) => j.lane === 'video'));+ })+ .catch(() => {}); // best-effort: a failed lookup just means no restored spinners+ return () => { live = false; };+ }, [projectId, restoreFrameJobs, restoreVideoJobs]);const genScenes = frameLane.genScenes;const genVideoScenes = videoLane.genScenes;const failedScenes = { frame: frameLane.failedScenes, video: videoLane.failedScenes };diff --git a/client/src/hooks/useMusicVideoSceneMedia.test.jsx b/client/src/hooks/useMusicVideoSceneMedia.test.jsxnew file mode 100644index 0000000000..44860900e2--- /dev/null+++ b/client/src/hooks/useMusicVideoSceneMedia.test.jsx@@ -0,0 +1,77 @@+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';+import { renderHook, act, cleanup, waitFor } from '@testing-library/react';++const handlers = new Map();+vi.mock('../services/socket', () => ({+ default: {+ on: (event, fn) => { handlers.set(event, fn); },+ off: (event, fn) => { if (handlers.get(event) === fn) handlers.delete(event); },+ emit: () => {},+ },+}));++const getMusicVideoSceneJobs = vi.fn();+vi.mock('../services/apiMusicVideo.js', () => ({+ addMusicVideoSceneTake: vi.fn(),+ getMusicVideoSceneJobs: (...a) => getMusicVideoSceneJobs(...a),+}));+vi.mock('../services/apiMediaJobs', () => ({ getMediaJob: vi.fn(async () => ({ status: 'failed' })) }));+const generateImage = vi.fn(async () => ({ status: 'queued', jobId: 'new-job' }));+vi.mock('../services/apiSystem.js', () => ({ generateImage: (...a) => generateImage(...a) }));+vi.mock('../services/apiImageVideo.js', () => ({ generateVideo: vi.fn() }));+vi.mock('../components/ui/Toast', () => ({ default: { error: vi.fn(), info: vi.fn(), success: vi.fn() } }));++const useMusicVideoSceneMedia = (await import('./useMusicVideoSceneMedia.js')).default;++const project = {+ id: 'p1',+ scenes: [+ { sceneId: 's1', order: 0, label: 'Intro', prompt: 'a lighthouse', referenceImageId: null, takes: [] },+ { sceneId: 's2', order: 1, label: 'Verse', prompt: 'a harbor', referenceImageId: null, takes: [] },+ ],+};++const setup = () => {+ const applyScenePatch = vi.fn();+ const view = renderHook(() => useMusicVideoSceneMedia({ project, videoSettings: { settings: {} }, applyScenePatch }));+ return { ...view, applyScenePatch };+};++describe('useMusicVideoSceneMedia in-flight restore and failure chip (#10154)', () => {+ beforeEach(() => { handlers.clear(); generateImage.mockClear(); getMusicVideoSceneJobs.mockReset(); });+ afterEach(cleanup);++ it('restores spinners for the server queue\'s in-flight renders after a reload, and "generate missing" skips them', async () => {+ getMusicVideoSceneJobs.mockResolvedValue({ jobs: [+ { jobId: 'job-a', lane: 'image', sceneId: 's1', status: 'running' },+ { jobId: 'job-b', lane: 'video', sceneId: 's2', status: 'queued' },+ ] });+ const { result } = setup();+ expect(getMusicVideoSceneJobs).toHaveBeenCalledWith('p1', { silent: true });+ await waitFor(() => expect(result.current.genScenes.s1).toBe(true));+ expect(result.current.genVideoScenes.s2).toBe(true);++ act(() => { result.current.generateMissingFrames(); });+ await waitFor(() => expect(generateImage).toHaveBeenCalledTimes(1));+ expect(generateImage.mock.calls[0][0].musicVideo).toMatchObject({ projectId: 'p1', sceneId: 's2' });+ });++ it('a failed lookup leaves the board usable (no restored spinners, no throw)', async () => {+ getMusicVideoSceneJobs.mockRejectedValue(new Error('offline'));+ const { result } = setup();+ await act(async () => { await Promise.resolve(); });+ expect(result.current.genScenes).toEqual({});+ });++ it('folds a persisted scene failure (and its later clearing) onto the scene', async () => {+ getMusicVideoSceneJobs.mockResolvedValue({ jobs: [] });+ const { applyScenePatch } = setup();+ const lastFailure = { lane: 'image', error: 'CUDA out of memory', at: '2026-10-05T00:00:00.000Z' };+ act(() => handlers.get('music-video:scene-failure')({ projectId: 'p1', sceneId: 's1', lastFailure }));+ expect(applyScenePatch).toHaveBeenCalledWith('p1', 's1', { lastFailure });++ // A landed frame's attach event carries lastFailure: null and clears the chip.+ act(() => handlers.get('music-video:scene-image')({ projectId: 'p1', sceneId: 's1', referenceImageId: 'f.png', takes: [], lastFailure: null }));+ expect(applyScenePatch).toHaveBeenLastCalledWith('p1', 's1', { referenceImageId: 'f.png', takes: [], lastFailure: null });+ });+});diff --git a/client/src/hooks/useSceneRenderLifecycle.js b/client/src/hooks/useSceneRenderLifecycle.jsindex 3e53653e56..ed9e3da6fb 100644--- a/client/src/hooks/useSceneRenderLifecycle.js+++ b/client/src/hooks/useSceneRenderLifecycle.js@@ -4,6 +4,23 @@ import { getMediaJob } from '../services/apiMediaJobs';import { evictOldest, ORPHAN_BUFFER_MAX } from '../lib/boundedMap';import toast from '../components/ui/Toast';+// Failures landing within this window of each other are one batch.+const FAILURE_BATCH_WINDOW_MS = 600;+const MAX_NAMED_SCENES = 3;++// One toast for however many scenes failed in the window: names the scene (or+// the first few, with a count) and the first reported reason.+function failureToastMessage(failMessage, failures) {+ const reason = failures.find((f) => f.error)?.error;+ const labels = [...new Set(failures.map((f) => f.label).filter(Boolean))];+ if (failures.length === 1) {+ return `${failMessage}${labels[0] ? `: ${labels[0]}` : ''}${reason ? ` — ${reason}` : ''}`;+ }+ const named = labels.slice(0, MAX_NAMED_SCENES).join(', ');+ const more = labels.length > MAX_NAMED_SCENES ? `, +${labels.length - MAX_NAMED_SCENES} more` : '';+ return `${failMessage} for ${failures.length} scenes${named ? ` (${named}${more})` : ''}${reason ? ` — ${reason}` : ''}`;+}+/*** Per-scene async-render lifecycle for a Music Video board lane (reference* frame OR i2v clip — #1798). One call owns everything one lane needs to drive@@ -45,9 +62,15 @@ import toast from '../components/ui/Toast';* (the batch counter in `useSceneBatch` listens here).* - `apply(data)` — fold the finished asset onto the matching scene* (functional setProjects update); called on `attachEvent`.- * - `failMessage` — the toast string for a confirmed render failure.+ * - `failMessage` — the toast headline for a confirmed render failure+ * (e.g. 'Frame render failed').+ * - `sceneLabel(sceneId)` — OPTIONAL display name of a scene, so the failure+ * toast says WHICH scene failed. Failure toasts also+ * carry the failed event's `error`, and failures that+ * land within a short window (a batch) collapse into ONE+ * summary toast instead of one identical toast per scene.*- * Returns `{ genScenes, sceneProgress, failedScenes, startScene, clearScene, trackJob }`+ * Returns `{ genScenes, sceneProgress, failedScenes, startScene, clearScene, trackJob, restoreJobs }`* (`sceneProgress`: sceneId → `{ progress }` once a job reports running; a scene* in `genScenes` with no entry is still queued;* `failedScenes` — sceneId → true after a confirmed render failure this session, until that scene renders again):@@ -58,6 +81,9 @@ import toast from '../components/ui/Toast';* event clears the right scene's spinner; reconciles an already-arrived* orphan terminal inline (clears the spinner, toasts on failure) instead of* registering a job that's already done.+ * - `restoreJobs([{ jobId, sceneId }])` — after a reload, re-light the+ * spinners for renders the server's queue still has in flight (#10154) and+ * correlate their jobs so the terminal events clear them as usual.*/export default function useSceneRenderLifecycle({attachEvent,@@ -69,6 +95,7 @@ export default function useSceneRenderLifecycle({onSettled,apply,failMessage,+ sceneLabel,}) {const [genScenes, setGenScenes] = useState({});const [sceneProgress, setSceneProgress] = useState({});@@ -89,8 +116,30 @@ export default function useSceneRenderLifecycle({// Latest `apply` / `failMessage` without re-subscribing the socket every// render — the effect keys on the (static) event names and reads the mutable// callbacks through this ref, mirroring the original `[]`-deps effects.- const cfgRef = useRef({ apply, failMessage, onSettled });- cfgRef.current = { apply, failMessage, onSettled };+ const cfgRef = useRef({ apply, failMessage, onSettled, sceneLabel });+ cfgRef.current = { apply, failMessage, onSettled, sceneLabel };+ // Failures waiting for the batch window to close, and that window's timer.+ const failuresRef = useRef([]);+ const flushTimerRef = useRef(null);++ // Queue one confirmed failure; the toast fires once the window closes so a+ // batch of failures reads as one summary rather than N identical toasts.+ const reportFailure = useCallback((sceneId, error) => {+ failuresRef.current.push({ label: cfgRef.current.sceneLabel?.(sceneId) || '', error: typeof error === 'string' ? error.trim() : '' });+ if (flushTimerRef.current) return;+ flushTimerRef.current = setTimeout(() => {+ flushTimerRef.current = null;+ const failures = failuresRef.current;+ failuresRef.current = [];+ if (failures.length) toast.error(failureToastMessage(cfgRef.current.failMessage, failures));+ }, FAILURE_BATCH_WINDOW_MS);+ }, []);+ // A navigated-away page must not pop a late failure toast onto another view.+ useEffect(() => () => {+ clearTimeout(flushTimerRef.current);+ flushTimerRef.current = null;+ failuresRef.current = [];+ }, []);const startScene = useCallback((sceneId) => { markFailed(sceneId, false); setGenScenes((prev) => ({ ...prev, [sceneId]: true })); },@@ -115,19 +164,33 @@ export default function useSceneRenderLifecycle({// event already raced ahead, settle it now; otherwise register the pending job.const trackJob = useCallback((jobId, sceneId) => {if (orphanRef.current.has(jobId)) {- const outcome = orphanRef.current.get(jobId);+ const orphan = orphanRef.current.get(jobId);orphanRef.current.delete(jobId);clearScene(sceneId);clearProgress(sceneId);- if (outcome === 'failed') {+ const failed = typeof orphan === 'object' ? orphan.failed : orphan === 'failed';+ const outcome = (typeof orphan === 'object' ? orphan.outcome : orphan) || (failed ? 'failed' : 'completed');+ const error = typeof orphan === 'object' ? orphan.error : undefined;+ if (failed || outcome === 'failed') {markFailed(sceneId, true);- toast.error(cfgRef.current.failMessage);+ reportFailure(sceneId, error);}cfgRef.current.onSettled?.({ jobId, sceneId, outcome });return;}pendingRef.current.set(jobId, sceneId);- }, [clearScene, clearProgress, markFailed]);+ }, [clearScene, clearProgress, markFailed, reportFailure]);++ const restoreJobs = useCallback((entries) => {+ const list = (Array.isArray(entries) ? entries : []).filter((e) => e?.jobId && e?.sceneId);+ if (list.length === 0) return;+ setGenScenes((prev) => {+ const next = { ...prev };+ for (const { sceneId } of list) next[sceneId] = true;+ return next;+ });+ for (const { jobId, sceneId } of list) trackJob(jobId, sceneId);+ }, [trackJob]);useEffect(() => {const onAttach = (data) => cfgRef.current.apply(data);@@ -148,7 +211,7 @@ export default function useSceneRenderLifecycle({// unrelated job). Stash it so a slightly-late registration can// reconcile; cap so other pages' renders can't grow this unbounded.const orphans = orphanRef.current;- orphans.set(jobId, outcome);+ orphans.set(jobId, { failed: !!failed, outcome, error: data?.error });evictOldest(orphans, ORPHAN_BUFFER_MAX);return;}@@ -157,7 +220,7 @@ export default function useSceneRenderLifecycle({clearProgress(sceneId);if (failed) {markFailed(sceneId, true);- toast.error(cfgRef.current.failMessage);+ reportFailure(sceneId, data?.error);}cfgRef.current.onSettled?.({ jobId, sceneId, outcome });};@@ -183,7 +246,7 @@ export default function useSceneRenderLifecycle({// the failure transition) hasn't landed yet, so it re-polls a bounded number// of times rather than toasting prematurely (the spinner is already cleared,// so giving up silently never strands the UI).- const armFailToast = (jobId, sceneId, attempt = 0) => {+ const armFailToast = (jobId, sceneId, error, attempt = 0) => {failTimers.set(jobId, setTimeout(() => {failTimers.delete(jobId);if (!mounted) return; // navigated away before the timer fired@@ -192,10 +255,19 @@ export default function useSceneRenderLifecycle({if (!mounted) return; // unmounted while the status fetch was in flightconst status = job?.status;if (status === 'canceled') return; // user cancel — never a failure toast- if (status === 'failed' || status === 'error') { markFailed(sceneId, true); toast.error(cfgRef.current.failMessage); return; }- if (attempt < 2) armFailToast(jobId, sceneId, attempt + 1); // non-terminal: wait, don't toast yet+ if (status === 'failed' || status === 'error') {+ markFailed(sceneId, true);+ reportFailure(sceneId, error || job?.error);+ return;+ }+ if (attempt < 2) armFailToast(jobId, sceneId, error, attempt + 1); // non-terminal: wait, don't toast yet})- .catch(() => { if (mounted) { markFailed(sceneId, true); toast.error(cfgRef.current.failMessage); } });+ .catch(() => {+ if (mounted) {+ markFailed(sceneId, true);+ reportFailure(sceneId, error);+ }+ });}, 800));};const onFailed = (data) => {@@ -207,10 +279,10 @@ export default function useSceneRenderLifecycle({// orphan WITH the failure bit so a fast-fail that raced ahead of its own// kickoff registration is toasted by the kickoff reconciliation; an// unrelated job is simply capped/evicted from the orphan map unseen.- const ownedScene = pendingRef.current.get(jobId);- const owned = !!ownedScene;+ const ownedSceneId = pendingRef.current.get(jobId);+ const owned = !!ownedSceneId;settle(data, !owned, 'failed');- if (owned && !failTimers.has(jobId)) armFailToast(jobId, ownedScene);+ if (owned && !failTimers.has(jobId)) armFailToast(jobId, ownedSceneId, data?.error);};// Queued-cancel emits no `failedEvent`; running-cancel emits failed then this.// Either way clear the spinner and cancel any pending failure toast.@@ -240,7 +312,7 @@ export default function useSceneRenderLifecycle({for (const t of failTimers.values()) clearTimeout(t);failTimers.clear();};- }, [attachEvent, completedEvent, failedEvent, canceledEvent, startedEvent, progressEvent, clearScene, clearProgress, markFailed]);+ }, [attachEvent, completedEvent, failedEvent, canceledEvent, startedEvent, progressEvent, clearScene, clearProgress, markFailed, reportFailure]);- return { genScenes, sceneProgress, failedScenes, startScene, clearScene, trackJob };+ return { genScenes, sceneProgress, failedScenes, startScene, clearScene, trackJob, restoreJobs };}diff --git a/client/src/hooks/useSceneRenderLifecycle.test.jsx b/client/src/hooks/useSceneRenderLifecycle.test.jsxindex b002c0a900..7fd24dcfec 100644--- a/client/src/hooks/useSceneRenderLifecycle.test.jsx+++ b/client/src/hooks/useSceneRenderLifecycle.test.jsx@@ -19,6 +19,13 @@ vi.mock('../components/ui/Toast', () => ({ default: { error: (...a) => toastErroconst useSceneRenderLifecycle = (await import('./useSceneRenderLifecycle.js')).default;+// An owned failure re-polls the job (800ms timer + fetch) and THEN queues its+// toast on the batch window, so drain timers, microtasks, then the window.+const settleFailureToasts = async () => {+ await act(async () => { await vi.advanceTimersByTimeAsync(1000); });+ await act(async () => { await vi.advanceTimersByTimeAsync(1000); });+};+const fire = (event, payload) => act(() => { handlers.get(event)?.(payload); });const IMAGE_CFG = {@@ -85,13 +92,53 @@ describe('useSceneRenderLifecycle', () => {expect(toastError).not.toHaveBeenCalled();});- it('trackJob reconciles a FAILED orphan and toasts the failure', () => {- const { result } = renderLane();+ it('trackJob reconciles a FAILED orphan and toasts the failure, naming the scene and the reason', () => {+ vi.useFakeTimers();+ const { result } = renderLane({ sceneLabel: (id) => ({ s1: 'Verse 1' })[id] });act(() => result.current.startScene('s1'));- fire('image-gen:failed', { generationId: 'job-1' });+ fire('image-gen:failed', { generationId: 'job-1', error: 'CUDA out of memory' });act(() => result.current.trackJob('job-1', 's1'));expect(result.current.genScenes.s1).toBeUndefined();- expect(toastError).toHaveBeenCalledWith('Frame render failed');+ act(() => { vi.runAllTimers(); });+ expect(toastError).toHaveBeenCalledTimes(1);+ expect(toastError).toHaveBeenCalledWith('Frame render failed: Verse 1 — CUDA out of memory');+ vi.useRealTimers();+ });++ it('collapses a batch of failures into one summary toast instead of one identical toast per scene', async () => {+ vi.useFakeTimers();+ const labels = { s1: 'Intro', s2: 'Verse 1', s3: 'Chorus', s4: 'Bridge' };+ const { result } = renderLane({ sceneLabel: (id) => labels[id] });+ act(() => {+ ['s1', 's2', 's3', 's4'].forEach((id, i) => { result.current.startScene(id); result.current.trackJob(`job-${i}`, id); });+ });+ // Owned failures re-poll the job before toasting (running-cancel disambiguation).+ getMediaJob.mockResolvedValue({ status: 'failed' });+ ['job-0', 'job-1', 'job-2', 'job-3'].forEach((id) => fire('image-gen:failed', { generationId: id, error: 'provider quota exceeded' }));+ await settleFailureToasts();+ expect(toastError).toHaveBeenCalledTimes(1);+ expect(toastError).toHaveBeenCalledWith('Frame render failed for 4 scenes (Intro, Verse 1, Chorus, +1 more) — provider quota exceeded');+ vi.useRealTimers();+ });++ it('does not pop a late failure toast after the board unmounts', () => {+ vi.useFakeTimers();+ const { result, unmount } = renderLane();+ act(() => result.current.startScene('s1'));+ fire('image-gen:failed', { generationId: 'job-1', error: 'boom' });+ act(() => result.current.trackJob('job-1', 's1'));+ unmount();+ act(() => { vi.runAllTimers(); });+ expect(toastError).not.toHaveBeenCalled();+ vi.useRealTimers();+ });++ it('restoreJobs re-lights spinners after a reload and the job terminal event clears the right scene', () => {+ const { result } = renderLane();+ act(() => result.current.restoreJobs([{ jobId: 'job-1', sceneId: 's1' }, { jobId: 'job-2', sceneId: 's2' }]));+ expect(result.current.genScenes).toEqual({ s1: true, s2: true });+ fire('image-gen:completed', { generationId: 'job-2' });+ expect(result.current.genScenes).toEqual({ s1: true });});it('queued-cancel (canceled with no prior failed) clears the spinner silently', () => {@@ -111,7 +158,7 @@ describe('useSceneRenderLifecycle', () => {// Spinner clears at once; toast is deferred pending the re-poll.expect(result.current.genScenes.s1).toBeUndefined();expect(toastError).not.toHaveBeenCalled();- await act(async () => { await vi.runAllTimersAsync(); });+ await settleFailureToasts();expect(getMediaJob).toHaveBeenCalledWith('job-1');expect(toastError).toHaveBeenCalledWith('Frame render failed');vi.useRealTimers();diff --git a/client/src/pages/MusicVideo.test.jsx b/client/src/pages/MusicVideo.test.jsxindex b1192584a2..7bf986d502 100644--- a/client/src/pages/MusicVideo.test.jsx+++ b/client/src/pages/MusicVideo.test.jsx@@ -71,6 +71,7 @@ vi.mock('../services/apiMusicVideo.js', () => ({musicVideoVocalSeparationEventsUrl: (jobId) => `/api/music-video/vocal-stem/separate/${jobId}/events`,cancelMusicVideoVocalSeparation: vi.fn(async () => ({ ok: true })),getMusicVideoActiveRender: vi.fn(async () => ({ jobId: null })),+ getMusicVideoSceneJobs: vi.fn(async () => ({ jobs: [] })),renderMusicVideoProject: vi.fn(async () => ({ jobId: 'job-1' })),musicVideoRenderEventsUrl: (jobId) => `/api/music-video/render/${jobId}/events`,cancelMusicVideoRender: vi.fn(async () => ({ ok: true })),diff --git a/client/src/services/apiMusicVideo.js b/client/src/services/apiMusicVideo.jsindex 8169caacb4..e2a3da1f45 100644--- a/client/src/services/apiMusicVideo.js+++ b/client/src/services/apiMusicVideo.js@@ -172,6 +172,11 @@ export const renderMusicVideoProject = (id, options = {}) =>// stream. Never starts a render — only the POST above does (#9940).export const getMusicVideoActiveRender = (id, options = {}) =>request(`/music-video/${encodeURIComponent(id)}/render`, options);+// Read-only: resolves { jobs: [{ jobId, lane: 'image'|'video', sceneId, status }] }+// — the project's in-flight scene frame/clip renders on this install — so a+// reloaded board restores its spinners instead of allowing duplicate submits (#10154).+export const getMusicVideoSceneJobs = (id, options = {}) =>+ request(`/music-video/${encodeURIComponent(id)}/scene-jobs`, options);export const getMusicVideoCodeDocument = (id, options = {}) =>request(`/music-video/${encodeURIComponent(id)}/code/document`, options);export const generateMusicVideoCode = (id, body = {}, options = {}) =>diff --git a/server/lib/musicVideoValidation.js b/server/lib/musicVideoValidation.jsindex e5d841b74d..eb3009f639 100644--- a/server/lib/musicVideoValidation.js+++ b/server/lib/musicVideoValidation.js@@ -1141,6 +1141,14 @@ export const musicVideoSceneCreateSchema = z.object({{ message: 'endSec must be >= startSec', path: ['endSec'] },);+// The last render failure persisted on a scene by the scene image/video hooks+// (#10154): which lane failed, why (one bounded line), and when.+export const musicVideoSceneLastFailureSchema = z.object({+ lane: z.enum(['image', 'video']),+ error: z.string().max(300),+ at: z.string().max(64),+}).strict();+// Times are nullable here so clearing a Start/End input (the UI sends `null`)// is accepted. The endSec >= startSec invariant can't be checked on the partial// patch alone (the paired value may live on the existing record), so the merged@@ -1168,6 +1176,10 @@ export const musicVideoSceneUpdateSchema = z.object({performanceSpeaker: z.string().trim().max(120).nullable().optional(),referenceImageId: z.string().max(256).nullable().optional(),videoHistoryId: z.string().max(64).nullable().optional(),+ // #10154: the last generation failure the render hooks persisted. The board+ // may send `null` to dismiss it; a full object is accepted so a client that+ // round-trips the scene doesn't 400.+ lastFailure: musicVideoSceneLastFailureSchema.nullable().optional(),}).strict();// Reorder the board: the full set of scene ids in their new order.diff --git a/server/routes/musicVideo.js b/server/routes/musicVideo.jsindex a7b32a334c..277e6836ca 100644--- a/server/routes/musicVideo.js+++ b/server/routes/musicVideo.js@@ -112,6 +112,7 @@ import {} from '../services/audioMidiTranscription.js';import { analyzeAudioFileManual, buildManualAnalysisFromCached } from '../services/musicVideo/audioAnalysis.js';import { analyzeProjectSong, resolveProjectAudioPath } from '../services/musicVideo/projectAudio.js';+import { listInFlightSceneJobs } from '../services/musicVideo/sceneJobs.js';import { renderMusicVideo, attachRenderSseClient, cancelRender, getActiveRenderJobId } from '../services/musicVideo/render.js';import { prepareCodeRender } from '../services/musicVideo/codeRender.js';import { generateMusicVideoCode, regenerateMusicVideoCodeSection } from '../services/musicVideo/codeGeneration.js';@@ -555,6 +556,12 @@ router.get('/:id/render', (req, res) => {res.json({ jobId: getActiveRenderJobId(req.params.id) });});+// Read-only: this project's in-flight scene frame/clip renders (#10154), so a+// reloaded board restores its spinners instead of letting a duplicate be submitted.+router.get('/:id/scene-jobs', (req, res) => {+ res.json({ jobs: listInFlightSceneJobs(req.params.id) });+});+router.post('/:id/production-review/feedback', asyncHandler(async (req, res) => {res.json(await addProductionFeedback(req.params.id, validateRequest(musicVideoProductionFeedbackSchema, req.body)));}));diff --git a/server/services/musicVideo/events.js b/server/services/musicVideo/events.jsindex 0bdc93b98a..2b712a5540 100644--- a/server/services/musicVideo/events.js+++ b/server/services/musicVideo/events.js@@ -16,6 +16,13 @@ import { EventEmitter } from 'events';// synchronous external-SD-API lane (which returns the image filename inline and// lets the client add it as a take through the takes route; video renders// always ride the queue, so the clip attach is hook-only).+// 'scene-failure' → { projectId, sceneId, lastFailure: { lane, error, at } | null }+//+// `scene-image` / `scene-video` also carry the scene's `lastFailure` (null once a+// take lands for that lane). 'scene-failure' is emitted by the same hooks when a+// render FAILS (#10154) after the failure is persisted on the scene, bridged to+// `music-video:scene-failure`, so the board's "Frame failed: <reason> · Retry"+// chip appears without a refetch and survives a reload.//// #8988 adds two more:// 'excerpt-render' → { projectId, excerptId, status } — a draft excerptdiff --git a/server/services/musicVideo/projects.js b/server/services/musicVideo/projects.jsindex 809d2663ac..32a5e7922f 100644--- a/server/services/musicVideo/projects.js+++ b/server/services/musicVideo/projects.js@@ -22,6 +22,7 @@ import { assertMusicVideoMediaSelections } from '../../lib/musicVideoMediaPolicy* sweep. The soft-delete fields were already on the record, so this was additive.*/+import { setSceneLastFailure } from './takes.js';import { presentMusicVideoDependencies, retainMusicVideoDependencies } from '../../lib/musicVideoDependencies.js';import { createRecordStoreBackendSelector } from '../../lib/pgFileFacade.js';import { emitRecordUpdated, emitRecordDeleted, autoSubscribeRecordToAllPeers } from '../sharing/recordEvents.js';@@ -258,6 +259,15 @@ export async function appendSceneTakes(id, sceneId, inputs) {return result;}+/**+ * Persist (or clear, with `failure` null) a scene's last generation failure —+ * `{ lane: 'image'|'video', error, at }` (#10154). Returns the updated scene.+ */+export async function recordSceneFailure(id, sceneId, failure) {+ const { scene } = await mutateProjectRecord(id, (current) => setSceneLastFailure(current, sceneId, failure));+ return scene;+}+/** Append takes across scenes in one write (handoff import): `{ project, appended }`. */export async function appendTakesAcrossScenes(id, items) {const result = await (await selectBackend()).appendTakesAcrossScenes(id, items);diff --git a/server/services/musicVideo/sceneFailure.js b/server/services/musicVideo/sceneFailure.jsnew file mode 100644index 0000000000..aeea1894ad--- /dev/null+++ b/server/services/musicVideo/sceneFailure.js@@ -0,0 +1,19 @@+/**+ * Persist a failed scene render on the scene (#10154).+ *+ * The scene image/video completion hooks call this from their `onTerminal`+ * handler. A `failed` job is recorded as `scene.lastFailure` and announced on+ * `musicVideoEvents` 'scene-failure'; a `canceled` job is the director's own+ * action, never a failure, and is ignored. A deleted project/scene 404s inside+ * `recordSceneFailure`, which the hook scaffold logs rather than throws.+ */++import { recordSceneFailure } from './projects.js';+import { musicVideoEvents } from './events.js';++export async function recordSceneLastFailure({ projectId, sceneId }, status, job, lane) {+ if (status !== 'failed') return;+ const scene = await recordSceneFailure(projectId, sceneId, { lane, error: job?.error });+ musicVideoEvents.emit('scene-failure', { projectId, sceneId, lastFailure: scene.lastFailure ?? null });+ console.log(`⚠️ music-video scene ${lane} failed ${projectId.slice(0, 8)}/${sceneId}: ${scene.lastFailure?.error}`);+}diff --git a/server/services/musicVideo/sceneJobs.js b/server/services/musicVideo/sceneJobs.jsnew file mode 100644index 0000000000..cdd8ec6710--- /dev/null+++ b/server/services/musicVideo/sceneJobs.js@@ -0,0 +1,27 @@+/**+ * The scene renders a project still has in flight (#10154).+ *+ * The board's per-scene spinners live in React state, so a reload used to drop+ * them while the media-job queue kept rendering (and the completion hooks kept+ * attaching the result). This reads the queue — the one source of truth — for+ * the live image/video jobs tagged with `params.musicVideo.{projectId,sceneId}`+ * so a reloaded board can restore the spinners and not re-submit duplicates+ * (paid ones on fal). Only `queued`/`running` jobs qualify; cast-and-sets jobs+ * carry the same tag key but no `sceneId`, so they are excluded.+ */++import { listJobs } from '../mediaJobQueue/index.js';++const LANE_BY_KIND = Object.freeze({ image: 'image', video: 'video' });++export function listInFlightSceneJobs(projectId) {+ const out = [];+ for (const job of listJobs()) {+ if (job.status !== 'queued' && job.status !== 'running') continue;+ const lane = LANE_BY_KIND[job.kind];+ const tag = job.params?.musicVideo;+ if (!lane || tag?.projectId !== projectId || !tag.sceneId) continue;+ out.push({ jobId: job.id, lane, sceneId: tag.sceneId, status: job.status });+ }+ return out;+}diff --git a/server/services/musicVideo/sceneJobs.test.js b/server/services/musicVideo/sceneJobs.test.jsnew file mode 100644index 0000000000..b9f8aac366--- /dev/null+++ b/server/services/musicVideo/sceneJobs.test.js@@ -0,0 +1,27 @@+import { describe, it, expect, vi } from 'vitest';++const jobs = vi.hoisted(() => ({ list: [] }));+vi.mock('../mediaJobQueue/index.js', () => ({ listJobs: () => jobs.list }));++const { listInFlightSceneJobs } = await import('./sceneJobs.js');++const job = (over) => ({ id: 'j', kind: 'image', status: 'running', params: { musicVideo: { projectId: 'p1', sceneId: 's1' } }, ...over });++describe('listInFlightSceneJobs (#10154)', () => {+ it('returns only this project\'s live scene frame/clip jobs', () => {+ jobs.list = [+ job({ id: 'a', status: 'running' }),+ job({ id: 'b', kind: 'video', status: 'queued', params: { musicVideo: { projectId: 'p1', sceneId: 's2' } } }),+ job({ id: 'done', status: 'completed' }),+ job({ id: 'failed', status: 'failed' }),+ job({ id: 'other-project', params: { musicVideo: { projectId: 'p2', sceneId: 's1' } } }),+ job({ id: 'cast-sets', params: { musicVideo: { projectId: 'p1', key: 'cast-1' } } }),+ job({ id: 'untagged', params: {} }),+ job({ id: 'audio', kind: 'audio' }),+ ];+ expect(listInFlightSceneJobs('p1')).toEqual([+ { jobId: 'a', lane: 'image', sceneId: 's1', status: 'running' },+ { jobId: 'b', lane: 'video', sceneId: 's2', status: 'queued' },+ ]);+ });+});diff --git a/server/services/musicVideo/takes.js b/server/services/musicVideo/takes.jsindex 9421721763..7f6be493c9 100644--- a/server/services/musicVideo/takes.js+++ b/server/services/musicVideo/takes.js@@ -35,6 +35,9 @@ export const TAKE_SLOT = Object.freeze({ image: 'referenceImageId', video: 'vide// candidate; a selected take is never pruned.export const MAX_SCENE_TAKES = 60;+// A recorded failure reason is a one-line chip, not a log: bound it.+export const MAX_FAILURE_ERROR_CHARS = 300;+// Optional provenance text: bounded, and null (not '') when absent.const clip = (v, max) => (isNonBlankStr(v) ? trimTo(v, max) : null);@@ -139,9 +142,32 @@ function appendToScene(scene, inputs, now) {if (!isNonBlankStr(next[field]) && take.status !== 'rejected' && take.use !== 'motion-reference' && !musicVideoTakeChanges({ scenes: [scene] }, scene, take).length) next[field] = take.assetId;}next.takes = pruneTakes(takes, next);+ // A take landing for the lane a failure was recorded against is the retry+ // succeeding — drop the "failed" chip (#10154).+ if (next.lastFailure && appended.some((t) => t.kind === next.lastFailure.lane)) delete next.lastFailure;return { scene: next, appended };}+/**+ * Record (or, with `failure` null, clear) the last generation failure on a+ * scene (#10154): `{ lane: 'image'|'video', error, at }`. Persisted so the+ * board shows which scene failed and why after a reload, instead of a toast+ * that vanishes and a card that silently returns to idle. Throws 404 for a+ * deleted scene so a late failure can't resurrect it.+ */+export function setSceneLastFailure(project, sceneId, failure) {+ const idx = findSceneIndex(project, sceneId);+ const { lastFailure: _previous, ...rest } = project.scenes[idx];+ const scene = failure+ ? { ...rest, lastFailure: {+ lane: failure.lane === 'video' ? 'video' : 'image',+ error: trimTo(String(failure.error || '').replace(/\s+/g, ' ').trim(), MAX_FAILURE_ERROR_CHARS) || 'Render failed',+ at: failure.at || new Date().toISOString(),+ } }+ : rest;+ return { project: replaceScene(project, idx, scene), scene };+}+/** Append takes to one scene. Throws 404 for a deleted/unknown scene. */export function appendSceneTakes(project, sceneId, inputs) {for (const input of inputs) assertMusicVideoMedia(project, input.kind, 'take import');diff --git a/server/services/musicVideoSceneHooks.test.js b/server/services/musicVideoSceneHooks.test.jsindex a1fc5a5ce7..0da25567e0 100644--- a/server/services/musicVideoSceneHooks.test.js+++ b/server/services/musicVideoSceneHooks.test.js@@ -55,6 +55,7 @@ describe('music-video scene completion hooks → takes', () => {const capture = (event) => (data) => emitted.push({ event, ...data });const onImage = capture('scene-image');const onVideo = capture('scene-video');+ const onFailure = capture('scene-failure');let project;let scene;@@ -67,6 +68,7 @@ describe('music-video scene completion hooks → takes', () => {emitted = [];musicVideoEvents.on('scene-image', onImage);musicVideoEvents.on('scene-video', onVideo);+ musicVideoEvents.on('scene-failure', onFailure);project = await projects.createProject({ name: 'Example Video' });scene = await projects.addProjectScene(project.id, { prompt: 'a lighthouse at dusk' });});@@ -76,6 +78,7 @@ describe('music-video scene completion hooks → takes', () => {videoHook.__testing.reset();musicVideoEvents.off('scene-image', onImage);musicVideoEvents.off('scene-video', onVideo);+ musicVideoEvents.off('scene-failure', onFailure);});afterAll(() => rmSync(TEST_DATA_ROOT, { recursive: true, force: true }));@@ -176,4 +179,60 @@ describe('music-video scene completion hooks → takes', () => {expect(tombstone.scenes[0].takes.map((t) => t.assetId)).toEqual(['kept.png']);expect(emitted).toHaveLength(1);});++ // #10154 — a failed render is persisted on the scene so the board can say+ // which scene failed and why (including after a reload), and a landed take+ // for the same lane retires it.+ describe('scene lastFailure (#10154)', () => {+ it('records a failed frame and clip render on the scene and announces it', async () => {+ mediaJobEvents.emit('failed', { ...imageJob(project.id, scene.sceneId, 'x.png'), status: 'failed', error: 'CUDA out of memory\n at step 3' });+ await waitFor(() => emitted.some((e) => e.event === 'scene-failure'));+ let stored = await sceneOf(project.id, scene.sceneId);+ expect(stored.lastFailure).toMatchObject({ lane: 'image', error: 'CUDA out of memory at step 3' });+ expect(typeof stored.lastFailure.at).toBe('string');+ expect(emitted.find((e) => e.event === 'scene-failure')).toMatchObject({ projectId: project.id, sceneId: scene.sceneId, lastFailure: stored.lastFailure });++ mediaJobEvents.emit('failed', { ...videoJob(project.id, scene.sceneId, 'clip-x'), status: 'failed', error: 'provider timed out' });+ await waitFor(async () => (await sceneOf(project.id, scene.sceneId)).lastFailure?.lane === 'video');+ stored = await sceneOf(project.id, scene.sceneId);+ expect(stored.lastFailure).toMatchObject({ lane: 'video', error: 'provider timed out' });+ });++ it('does not record a cancel as a failure', async () => {+ mediaJobEvents.emit('canceled', { ...imageJob(project.id, scene.sceneId, 'x.png'), status: 'canceled', error: 'Canceled' });+ // A later failure for the surviving scene proves the cancel was processed first.+ const other = await projects.addProjectScene(project.id, { prompt: 'second' });+ mediaJobEvents.emit('failed', { ...imageJob(project.id, other.sceneId, 'y.png'), status: 'failed', error: 'boom' });+ await waitFor(() => emitted.some((e) => e.event === 'scene-failure'));+ expect((await sceneOf(project.id, scene.sceneId)).lastFailure).toBeUndefined();+ expect((await sceneOf(project.id, other.sceneId)).lastFailure).toMatchObject({ error: 'boom' });+ });++ it('a landed take for the failed lane clears it; the other lane keeps it', async () => {+ mediaJobEvents.emit('failed', { ...videoJob(project.id, scene.sceneId, 'clip-x'), status: 'failed', error: 'clip broke' });+ await waitFor(async () => (await sceneOf(project.id, scene.sceneId)).lastFailure?.lane === 'video');++ mediaJobEvents.emit('completed', imageJob(project.id, scene.sceneId, 'frame.png'));+ await waitFor(() => emitted.some((e) => e.event === 'scene-image'));+ expect((await sceneOf(project.id, scene.sceneId)).lastFailure).toMatchObject({ lane: 'video' });+ expect(emitted.find((e) => e.event === 'scene-image').lastFailure).toMatchObject({ lane: 'video' });++ await projects.updateScene(project.id, scene.sceneId, { referenceImageId: 'frame.png' });+ mediaJobEvents.emit('completed', videoJob(project.id, scene.sceneId, 'clip-ok'));+ await waitFor(() => emitted.some((e) => e.event === 'scene-video'));+ expect((await sceneOf(project.id, scene.sceneId)).lastFailure).toBeUndefined();+ expect(emitted.find((e) => e.event === 'scene-video').lastFailure).toBeNull();+ });++ it('a failure for a deleted scene is dropped without resurrecting it', async () => {+ const other = await projects.addProjectScene(project.id, { prompt: 'second' });+ await projects.deleteScene(project.id, scene.sceneId);+ mediaJobEvents.emit('failed', { ...imageJob(project.id, scene.sceneId, 'late.png'), status: 'failed', error: 'late' });+ mediaJobEvents.emit('failed', { ...imageJob(project.id, other.sceneId, 'kept.png'), status: 'failed', error: 'kept' });+ await waitFor(() => emitted.some((e) => e.event === 'scene-failure'));+ const stored = await projects.getProject(project.id);+ expect(stored.scenes.map((s) => s.sceneId)).toEqual([other.sceneId]);+ expect(emitted.filter((e) => e.event === 'scene-failure')).toHaveLength(1);+ });+ });});diff --git a/server/services/musicVideoSceneImageHook.js b/server/services/musicVideoSceneImageHook.jsindex 32c9d05194..0652a2f73e 100644--- a/server/services/musicVideoSceneImageHook.js+++ b/server/services/musicVideoSceneImageHook.js@@ -31,6 +31,7 @@import { createMediaJobImageHook } from './mediaJobImageHook.js';import { appendSceneTakes } from './musicVideo/projects.js';import { musicVideoEvents } from './musicVideo/events.js';+import { recordSceneLastFailure } from './musicVideo/sceneFailure.js';const hook = createMediaJobImageHook({label: 'music-video scene-image',@@ -64,10 +65,15 @@ const hook = createMediaJobImageHook({sceneId,referenceImageId: scene.referenceImageId ?? null,takes: scene.takes,+ // A landed frame retires this lane's recorded failure (takes.js).+ lastFailure: scene.lastFailure ?? null,takeId: appended[0]?.takeId ?? null,});console.log(`🎞️ music-video scene image take ${projectId.slice(0, 8)}/${sceneId} ← ${filename}`);},+ // A render that FAILED (a cancel is not a failure) is recorded on the scene+ // so the board can say which scene failed and why, including after a reload.+ onTerminal: (ctx, status, job) => recordSceneLastFailure(ctx, status, job, 'image'),});export function initMusicVideoSceneImageHook() {diff --git a/server/services/musicVideoSceneVideoHook.js b/server/services/musicVideoSceneVideoHook.jsindex c9849dfe1d..eeea852c72 100644--- a/server/services/musicVideoSceneVideoHook.js+++ b/server/services/musicVideoSceneVideoHook.js@@ -34,6 +34,7 @@ import { createMediaJobImageHook } from './mediaJobImageHook.js';import { basename } from 'path';import { appendSceneTakes } from './musicVideo/projects.js';import { musicVideoEvents } from './musicVideo/events.js';+import { recordSceneLastFailure } from './musicVideo/sceneFailure.js';const hook = createMediaJobImageHook({label: 'music-video scene-video',@@ -87,10 +88,15 @@ const hook = createMediaJobImageHook({sceneId,videoHistoryId: scene.videoHistoryId ?? null,takes: scene.takes,+ // A landed clip retires this lane's recorded failure (takes.js).+ lastFailure: scene.lastFailure ?? null,takeId: appended[0]?.takeId ?? null,});console.log(`🎬 music-video scene clip take ${projectId.slice(0, 8)}/${sceneId} ← ${videoHistoryId.slice(0, 8)}`);},+ // A render that FAILED (a cancel is not a failure) is recorded on the scene+ // so the board can say which scene failed and why, including after a reload.+ onTerminal: (ctx, status, job) => recordSceneLastFailure(ctx, status, job, 'video'),});export function initMusicVideoSceneVideoHook() {diff --git a/server/services/socket.js b/server/services/socket.jsindex 97a724464e..3eabccc2d6 100644--- a/server/services/socket.js+++ b/server/services/socket.js@@ -311,6 +311,8 @@ const SIMPLE_BRIDGES = [// production run advancing (#9066) — all without a client refetch.{ emitter: musicVideoEvents, event: 'scene-image', channel: 'music-video:scene-image' },{ emitter: musicVideoEvents, event: 'scene-video', channel: 'music-video:scene-video' },+ // A scene render failed (or its recorded failure cleared) — #10154.+ { emitter: musicVideoEvents, event: 'scene-failure', channel: 'music-video:scene-failure' },{ emitter: musicVideoEvents, event: 'auto-review', channel: 'music-video:auto-review' },{ emitter: musicVideoEvents, event: 'production', channel: 'music-video:production' },// A fully-autonomous run (prompt → lyrics → Suno song → video) advancing.