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: confirm, count, cancel and partially run Music Video frame and clip batches (#10153)
Adam Eivy4f52ba8d4620
diff --git a/client/src/components/musicVideo/GenerationActions.test.jsx b/client/src/components/musicVideo/GenerationActions.test.jsxnew file mode 100644index 0000000000..1ab3b969e0--- /dev/null+++ b/client/src/components/musicVideo/GenerationActions.test.jsx@@ -0,0 +1,50 @@+import { describe, it, expect, vi } from 'vitest';+import { render, screen, fireEvent } from '@testing-library/react';+import { GenerationActions } from './ProjectActionGroups.jsx';++const scene = (order, extra = {}) => ({ sceneId: `s${order}`, order, startSec: order * 5, endSec: order * 5 + 5, prompt: 'p', ...extra });+const idleBatch = () => ({ state: null, cancel: vi.fn(), dismiss: vi.fn() });++const setup = ({ scenes, backend = 'fal', videoBatch = idleBatch(), pending } = {}) => {+ const sceneMedia = {+ genScenes: {}, genVideoScenes: {},+ frameBatch: idleBatch(), videoBatch,+ planMissingFrames: () => scenes.filter((s) => !s.referenceImageId),+ planMissingVideos: () => ({ pending: pending ?? scenes.filter((s) => s.referenceImageId && !s.videoHistoryId), skipped: 0 }),+ generateMissingFrames: vi.fn(),+ generateMissingVideos: vi.fn(),+ };+ const videoSettings = { settings: { backend }, saving: false, framePinSaving: false, videoBlockedReason: '', audioReactiveSelected: false };+ render(<GenerationActions project={{ id: 'p', scenes, audioAnalysis: { durationSec: 60 } }} videoSettings={videoSettings} sceneMedia={sceneMedia} />);+ return sceneMedia;+};++describe('GenerationActions batch confirm (#10153)', () => {+ it('submits nothing on the first click and generates only after the confirm shows count and estimate', () => {+ const media = setup({ scenes: [scene(0, { referenceImageId: 'a.png' }), scene(1, { referenceImageId: 'b.png' })] });+ fireEvent.click(screen.getByRole('button', { name: /^Videos 0\/2/ }));+ expect(media.generateMissingVideos).not.toHaveBeenCalled();+ expect(screen.getByRole('group', { name: 'Confirm clip batch' }).textContent).toMatch(/Generate 2 clips on fal .* est\. \$/);+ fireEvent.click(screen.getByRole('button', { name: 'Generate' }));+ expect(media.generateMissingVideos).toHaveBeenCalledTimes(1);+ });++ it('enables Videos with a partial set of frames and names the scene still waiting', () => {+ setup({ scenes: [scene(0, { referenceImageId: 'a.png' }), scene(1, { sectionLabel: 'Bridge' })] });+ const videos = screen.getByRole('button', { name: /Videos 0\/2 \(1 waiting for a frame: Bridge\)/ });+ expect(videos.disabled).toBe(false);+ });++ it('keeps Videos disabled when no scene has a frame yet', () => {+ setup({ scenes: [scene(0), scene(1)] });+ expect(screen.getByRole('button', { name: /^Videos 0\/2/ }).disabled).toBe(true);+ });++ it('shows the running batch with Cancel remaining wired to the batch', () => {+ const videoBatch = { ...idleBatch(), state: { total: 14, done: 6, failed: 2, canceled: 0, cancelRequested: false } };+ setup({ scenes: [scene(0, { referenceImageId: 'a.png' })], videoBatch });+ expect(screen.getByRole('status').textContent).toContain('Videos: 6 of 14 done · 2 failed');+ fireEvent.click(screen.getByRole('button', { name: 'Cancel remaining' }));+ expect(videoBatch.cancel).toHaveBeenCalledTimes(1);+ });+});diff --git a/client/src/components/musicVideo/ProjectActionGroups.jsx b/client/src/components/musicVideo/ProjectActionGroups.jsxindex 8a3723fff0..c9db105f13 100644--- a/client/src/components/musicVideo/ProjectActionGroups.jsx+++ b/client/src/components/musicVideo/ProjectActionGroups.jsx@@ -1,9 +1,10 @@import { useState } from 'react';-import { Film, Music, Activity, Image as ImageIcon, Video, Wand2 } from 'lucide-react';+import { Film, Music, Activity, Image as ImageIcon, Video, Wand2, X } from 'lucide-react';import { MUSCRIPTOR_MODELS } from '../../lib/muscriptorModels.js';import { isLayeredComposition, sceneRenderReady, sceneVisualLayer } from '../../lib/musicVideoLayers.js';import { compositionDraft, RENDER_STYLES } from './compositionDraft.js';import { projectServicesSummary } from '../../lib/musicVideoStages.js';+import { batchActive, batchSummary, scenesWaitingForFrame, videoBatchPreview, videosButtonLabel } from '../../lib/musicVideoBatchPlan.js';/*** The board-level actions the old single toolbar carried, split by the stage@@ -109,11 +110,33 @@ export function PlanActions({ project, busy, onPlan, onAutoArrange }) {);}+// One batch's running summary: "Videos: 6 of 14 done · 2 failed" with its+// Cancel remaining / Dismiss control. Counts arrive from socket events only.+function BatchStatus({ noun, batch }) {+ const { state } = batch;+ if (!state) return null;+ const active = batchActive(state);+ return (+ <div role="status" className="flex min-w-0 flex-wrap items-center gap-2 text-xs text-port-text-muted">+ <span className="min-w-0 break-words">{batchSummary(noun, state)}{active && state.cancelRequested ? ' · canceling…' : ''}</span>+ {active && !state.cancelRequested && (+ <button type="button" onClick={batch.cancel} className={`${buttonCls} !py-1 text-port-warning`}>Cancel remaining</button>+ )}+ {!active && (+ <button type="button" onClick={batch.dismiss} aria-label={`Dismiss ${noun.toLowerCase()} summary`} className="inline-flex min-h-[44px] min-w-[44px] items-center justify-center sm:min-h-0 sm:min-w-0"><X size={13} /></button>+ )}+ </div>+ );+}+/*** The batch generators, with the image and video services they render on (a* project option, edited in Setup › Project options; `onEditServices` goes there).*/export function GenerationActions({ project, videoSettings, sceneMedia, onEditServices }) {+ // The first click only opens the confirm line (count + estimate); nothing is+ // submitted until the second (#10153).+ const [confirming, setConfirming] = useState(null);const scenes = project.scenes || [];const sceneCount = scenes.length;// #8985: in a composed render a still needs only its frame and a title card@@ -129,9 +152,21 @@ export function GenerationActions({ project, videoSettings, sceneMedia, onEditSeconst uniqueVideoCount = uniqueCount(footageScenes, 'videoHistoryId');const missingFrameCount = frameScenes.length - referenceFrameCount;const missingVideoCount = footageScenes.length - renderableSceneCount;- const footageFramesReady = footageScenes.every((scene) => scene.referenceImageId);+ const waitingForFrame = scenesWaitingForFrame(footageScenes);+ const videoCandidateCount = footageScenes.filter((scene) => scene.referenceImageId && !scene.videoHistoryId).length;const generatingFrames = Object.keys(sceneMedia.genScenes).length > 0;const generatingVideos = Object.keys(sceneMedia.genVideoScenes).length > 0;+ const confirmFrames = confirming === 'frames' ? sceneMedia.planMissingFrames() : null;+ const confirmVideos = confirming === 'videos' ? sceneMedia.planMissingVideos() : null;+ const videoPreview = confirmVideos?.pending.length+ ? videoBatchPreview({+ scenes: confirmVideos.pending,+ backend: videoSettings.audioReactiveSelected ? 'local' : videoSettings.settings.backend,+ videoSettings: videoSettings.settings,+ songDurationSec: project.audioAnalysis?.durationSec ?? null,+ })+ : null;+ const submit = (run) => { setConfirming(null); run(); };const footageBlocked = codeMode ? 'This render style draws its own scene and does not generate footage' : '';return (<div className={groupCls}>@@ -142,7 +177,7 @@ export function GenerationActions({ project, videoSettings, sceneMedia, onEditSe)}</span><button- onClick={sceneMedia.generateMissingFrames}+ onClick={() => setConfirming('frames')}disabled={codeMode || videoSettings.framePinSaving || sceneCount === 0 || missingFrameCount === 0 || generatingFrames}title={footageBlocked || (videoSettings.framePinSaving? 'Saving the frame renderer…'@@ -152,16 +187,34 @@ export function GenerationActions({ project, videoSettings, sceneMedia, onEditSe<ImageIcon size={15} /> Frames {referenceFrameCount}/{frameScenes.length}</button><button- onClick={sceneMedia.generateMissingVideos}- disabled={codeMode || videoSettings.saving || footageScenes.length === 0 || missingVideoCount === 0 || !footageFramesReady || generatingVideos || !!videoSettings.videoBlockedReason}+ onClick={() => setConfirming('videos')}+ disabled={codeMode || videoSettings.saving || footageScenes.length === 0 || missingVideoCount === 0 || videoCandidateCount === 0 || generatingVideos || !!videoSettings.videoBlockedReason}title={footageBlocked || videoSettings.videoBlockedReason- || (!footageFramesReady- ? 'Generate every reference frame first'+ || (videoCandidateCount === 0 && missingVideoCount > 0+ ? 'Generate a reference frame first': (missingVideoCount > 0 ? `Generate ${missingVideoCount} missing scene video${missingVideoCount === 1 ? '' : 's'}` : 'Every scene has a video'))}className={buttonCls}>- <Video size={15} /> Videos {renderableSceneCount}/{footageScenes.length}+ <Video size={15} /> {videosButtonLabel({ renderableCount: renderableSceneCount, footageCount: footageScenes.length, waiting: waitingForFrame })}</button>+ {confirmFrames && (+ <div role="group" aria-label="Confirm frame batch" className="flex w-full min-w-0 flex-wrap items-center gap-2 text-sm">+ <span className="min-w-0 break-words">{confirmFrames.length > 0+ ? `Generate ${confirmFrames.length} reference frame${confirmFrames.length === 1 ? '' : 's'}`+ : 'Nothing to generate — every scene has a frame or is already rendering'}</span>+ {confirmFrames.length > 0 && <button type="button" onClick={() => submit(sceneMedia.generateMissingFrames)} className={`${buttonCls} bg-port-accent text-white`}>Generate</button>}+ <button type="button" onClick={() => setConfirming(null)} className={buttonCls}>Cancel</button>+ </div>+ )}+ {confirmVideos && (+ <div role="group" aria-label="Confirm clip batch" className="flex w-full min-w-0 flex-wrap items-center gap-2 text-sm">+ <span className="min-w-0 break-words">{videoPreview?.text || 'Nothing to generate — no waiting scene has a frame, or the lane cannot render them'}</span>+ {videoPreview && <button type="button" onClick={() => submit(sceneMedia.generateMissingVideos)} className={`${buttonCls} bg-port-accent text-white`}>Generate</button>}+ <button type="button" onClick={() => setConfirming(null)} className={buttonCls}>Cancel</button>+ </div>+ )}+ <BatchStatus noun="Frames" batch={sceneMedia.frameBatch} />+ <BatchStatus noun="Videos" batch={sceneMedia.videoBatch} />{(uniqueReferenceFrameCount < referenceFrameCount || uniqueVideoCount < renderableSceneCount) && (<spanclassName="text-[10px] px-2 py-1.5 rounded border border-port-warning/40 bg-port-warning/10 text-port-warning"diff --git a/client/src/components/musicVideo/SceneCard.jsx b/client/src/components/musicVideo/SceneCard.jsxindex d80e96cf9b..575346407b 100644--- a/client/src/components/musicVideo/SceneCard.jsx+++ b/client/src/components/musicVideo/SceneCard.jsx@@ -16,6 +16,7 @@ const STILL_MOVE_LABELS = [['hold', 'Hold'], ['push', 'Push in'], ['pan', 'Pan']import {falSceneTake, grokCoverage, isPerformanceScene, performanceBlockedReason, performanceCapability, planPerformanceWindow, shotSplitLimit,} from '../../lib/musicVideoShotTiming.js';+import SceneRenderProgress from './SceneRenderProgress.jsx';import { getFalVideoModel } from '../../lib/falVideoModels.js';// "est. $0.81 (5.05s at 1080P)" — or null when the take cannot be priced.@@ -66,7 +67,7 @@ const COVERAGE_TOLERANCE_SEC = 0.25;* jumps to the scene's start.*/export default function SceneCard({- scene, index, isLast, generatingFrame, generatingVideo,+ scene, index, isLast, generatingFrame, generatingVideo, frameProgress = null, videoProgress = null,settingsSaving, videoBlockedReason, canContinueShot,onMove, onDelete, onEditLocal, onSave,onGenerateFrame, onGenerateVideo, onContinueVideo,@@ -174,6 +175,8 @@ export default function SceneCard({{(generatingFrame || generatingVideo) && (<Activity size={14} className="shrink-0 animate-spin text-port-accent" aria-label="Generating" />)}+ <SceneRenderProgress kind="Frame" generating={generatingFrame} progress={frameProgress} />+ <SceneRenderProgress kind="Video" generating={generatingVideo} progress={videoProgress} /></summary><div className="space-y-2 p-3 pt-0"><div className="flex items-center justify-end gap-2">diff --git a/client/src/components/musicVideo/SceneRenderProgress.jsx b/client/src/components/musicVideo/SceneRenderProgress.jsxnew file mode 100644index 0000000000..828716e654--- /dev/null+++ b/client/src/components/musicVideo/SceneRenderProgress.jsx@@ -0,0 +1,22 @@+/**+ * A scene card's render status: "Queued" until the media-job queue reports the+ * job started, then "Running" with a bar once it reports progress (fraction+ * 0..1, from `*-gen:progress` socket events — never polled). Renders nothing+ * while no render is in flight for the scene.+ */+export default function SceneRenderProgress({ kind, generating, progress }) {+ if (!generating) return null;+ const running = !!progress;+ const fraction = typeof progress?.progress === 'number' ? progress.progress : null;+ const pct = fraction == null ? null : Math.round(fraction * 100);+ return (+ <span className="flex shrink-0 items-center gap-1.5 text-[11px] text-port-text-muted" data-testid="scene-render-progress">+ <span>{kind} {running ? 'running' : 'queued'}{pct != null ? ` ${pct}%` : ''}</span>+ {pct != null && (+ <span className="h-1.5 w-12 overflow-hidden rounded bg-port-border" role="progressbar" aria-label={`${kind} render progress`} aria-valuemin={0} aria-valuemax={100} aria-valuenow={pct}>+ <span className="block h-full bg-port-accent" style={{ width: `${pct}%` }} />+ </span>+ )}+ </span>+ );+}diff --git a/client/src/components/musicVideo/stages/BoardStage.jsx b/client/src/components/musicVideo/stages/BoardStage.jsxindex edc61aba0f..1bc5380654 100644--- a/client/src/components/musicVideo/stages/BoardStage.jsx+++ b/client/src/components/musicVideo/stages/BoardStage.jsx@@ -68,6 +68,8 @@ export default function BoardStage({ board }) {isLast={idx === scenes.length - 1}generatingFrame={sceneMedia.genScenes[scene.sceneId]}generatingVideo={sceneMedia.genVideoScenes[scene.sceneId]}+ frameProgress={sceneMedia.sceneProgress?.[scene.sceneId]}+ videoProgress={sceneMedia.videoSceneProgress?.[scene.sceneId]}settingsSaving={videoSettings.saving}videoBlockedReason={videoSettings.videoBlockedReason}lipSyncBackend={videoSettings.audioReactiveSelected ? 'local' : videoSettings.settings.backend}diff --git a/client/src/hooks/README.md b/client/src/hooks/README.mdindex 8036fb8a5b..16f4fe283a 100644--- a/client/src/hooks/README.md+++ b/client/src/hooks/README.md@@ -52,7 +52,8 @@ grep -i "what you want to do" client/src/hooks/README.md| `useImporterProgress` | Live analyze-phase stage checklist via the `importer:progress` socket (runId-filtered); exports `stageStatusIcon` for the status→icon lookup. | Importer analyze progress UI only. || `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. |-| `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). Returns `{ genScenes, 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. |+| `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. || `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. |@@ -264,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 }`. | 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), 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. || `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/index.js b/client/src/hooks/index.jsindex 55053d45da..208de54368 100644--- a/client/src/hooks/index.js+++ b/client/src/hooks/index.js@@ -59,6 +59,7 @@ export { default as useKeyboardShortcuts } from './useKeyboardShortcuts.js';export * from './useKeyboardShortcuts.js';export { default as useMediaJobProgress } from './useMediaJobProgress.js';export * from './useMediaJobSse.js';+export { default as useSceneBatch } from './useSceneBatch.js';export { default as useSceneRenderLifecycle } from './useSceneRenderLifecycle.js';export { default as useMusicVideoAutoReview } from './useMusicVideoAutoReview.js';export { default as useMusicVideoCastAndSets } from './useMusicVideoCastAndSets.js';diff --git a/client/src/hooks/useMusicVideoSceneMedia.batch.test.jsx b/client/src/hooks/useMusicVideoSceneMedia.batch.test.jsxnew file mode 100644index 0000000000..f430df26ec--- /dev/null+++ b/client/src/hooks/useMusicVideoSceneMedia.batch.test.jsx@@ -0,0 +1,69 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';+import { renderHook, act } 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 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() }));+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() } }));++const useMusicVideoSceneMedia = (await import('./useMusicVideoSceneMedia.js')).default;++const fire = (event, payload) => act(() => { handlers.get(event)?.(payload); });+const videoSettings = { settings: { backend: 'local' }, audioReactiveSelected: false, videoBlockedReason: '' };+// Ten footage scenes; the last one has no reference frame yet.+const project = {+ id: 'p1',+ scenes: Array.from({ length: 10 }, (_, i) => ({+ sceneId: `s${i}`, order: i, prompt: `shot ${i}`, startSec: i * 4, endSec: i * 4 + 4,+ ...(i < 9 ? { referenceImageId: `f${i}.png` } : {}),+ })),+};++const renderMedia = () => renderHook(() => useMusicVideoSceneMedia({ project, videoSettings, applyScenePatch: vi.fn() }));+const flush = () => act(() => new Promise((resolve) => setTimeout(resolve, 0)));++describe('useMusicVideoSceneMedia clip batch (#10153)', () => {+ beforeEach(() => { handlers.clear(); generateVideo.mockReset(); cancelMediaJob.mockClear(); });++ it('generates a clip for every scene that has a frame while one scene still waits for its own', async () => {+ let n = 0;+ generateVideo.mockImplementation(() => Promise.resolve({ status: 'queued', jobId: `job-${n++}` }));+ const { result } = renderMedia();+ expect(result.current.planMissingVideos().pending).toHaveLength(9);+ act(() => result.current.generateMissingVideos());+ await flush();+ expect(generateVideo).toHaveBeenCalledTimes(9);+ expect(result.current.videoBatch.state).toMatchObject({ total: 9, done: 0, failed: 0 });+ fire('video-gen:started', { generationId: 'job-0' });+ fire('video-gen:progress', { generationId: 'job-0', progress: 0.5 });+ expect(result.current.videoSceneProgress.s0).toEqual({ progress: 0.5 });+ fire('video-gen:completed', { generationId: 'job-0' });+ fire('video-gen:failed', { generationId: 'job-1' });+ expect(result.current.videoBatch.state).toMatchObject({ done: 1, failed: 1 });+ });++ it('Cancel remaining cancels every unfinished job and clears the spinners through the canceled event', async () => {+ let n = 0;+ generateVideo.mockImplementation(() => Promise.resolve({ status: 'queued', jobId: `job-${n++}` }));+ const { result } = renderMedia();+ act(() => result.current.generateMissingVideos());+ await flush();+ fire('video-gen:completed', { generationId: 'job-0' });+ act(() => result.current.videoBatch.cancel());+ expect(cancelMediaJob.mock.calls.map(([id]) => id).sort()).toEqual(Array.from({ length: 8 }, (_, i) => `job-${i + 1}`));+ for (let i = 1; i < 9; i += 1) fire('video-gen:canceled', { generationId: `job-${i}` });+ expect(Object.keys(result.current.genVideoScenes)).toEqual([]);+ expect(result.current.videoBatch.state).toMatchObject({ done: 1, canceled: 8, failed: 0 });+ });+});diff --git a/client/src/hooks/useMusicVideoSceneMedia.js b/client/src/hooks/useMusicVideoSceneMedia.jsindex bb7eb9b6e8..2ae6c6bc53 100644--- a/client/src/hooks/useMusicVideoSceneMedia.js+++ b/client/src/hooks/useMusicVideoSceneMedia.js@@ -5,6 +5,7 @@ import toast from '../components/ui/Toast';import { addMusicVideoSceneTake } from '../services/apiMusicVideo.js';import { generateImage } from '../services/apiSystem.js';import { generateVideo } from '../services/apiImageVideo.js';+import useSceneBatch from './useSceneBatch.js';import useSceneRenderLifecycle from './useSceneRenderLifecycle.js';import { isLtx2FamilyRuntime } from '../lib/runnerFamilies';import { isLayeredComposition, sceneVisualLayer } from '../lib/musicVideoLayers.js';@@ -87,11 +88,16 @@ const sceneSpanSec = (scene) => (typeof scene.startSec === 'number' && typeof sc* the director chose.*/export default function useMusicVideoSceneMedia({ project, videoSettings, applyScenePatch } = {}) {+ const frameBatch = useSceneBatch();+ const videoBatch = useSceneBatch();const frameLane = useSceneRenderLifecycle({attachEvent: 'music-video:scene-image',completedEvent: 'image-gen:completed',failedEvent: 'image-gen:failed',canceledEvent: 'image-gen:canceled',+ startedEvent: 'image-gen:started',+ progressEvent: 'image-gen:progress',+ onSettled: frameBatch.settled,apply: ({ projectId, sceneId, referenceImageId, takes }) =>applyScenePatch?.(projectId, sceneId, { referenceImageId, ...(Array.isArray(takes) ? { takes } : {}) }),failMessage: 'Frame render failed',@@ -101,6 +107,9 @@ export default function useMusicVideoSceneMedia({ project, videoSettings, applyScompletedEvent: 'video-gen:completed',failedEvent: 'video-gen:failed',canceledEvent: 'video-gen:canceled',+ startedEvent: 'video-gen:started',+ progressEvent: 'video-gen:progress',+ onSettled: videoBatch.settled,apply: ({ projectId, sceneId, videoHistoryId, takes }) =>applyScenePatch?.(projectId, sceneId, { videoHistoryId, ...(Array.isArray(takes) ? { takes } : {}) }),failMessage: 'Scene video render failed',@@ -146,9 +155,12 @@ export default function useMusicVideoSceneMedia({ project, videoSettings, applyS* true once it reaches the queue or finishes synchronously. The revision* hook (#9011) passes `revisionId` and awaits this to release a claimed* section whose kickoff never made it to the queue, and to count only- * confirmed submissions rather than every call it fired.+ * confirmed submissions rather than every call it fired. A queued job also+ * returns its `jobId`, and `onJob(jobId)` is told of it before the lane starts+ * tracking it (a batch registers the job there, so a terminal event that raced+ * ahead of the kickoff is still attributed to it).*/- const generateFrame = (scene, { revisionId } = {}) => {+ const generateFrame = (scene, { revisionId, onJob } = {}) => {const conditioning = conditioningReferences(project, scene);const problem = shotActionContractProblem(scene.direction?.actionContract, scene);if (problem) { toast.error(problem); return Promise.resolve({ ok: false }); }@@ -170,8 +182,9 @@ export default function useMusicVideoSceneMedia({ project, videoSettings, applyS// reconciles a terminal event that raced ahead of this .then (fast fail).const jobId = res?.jobId || res?.generationId;if (!jobId) { frameLane.clearScene(scene.sceneId); return { ok: false }; } // no id to track → don't strand the button+ onJob?.(jobId);frameLane.trackJob(jobId, scene.sceneId);- return { ok: true };+ return { ok: true, jobId };}const filename = res?.filename;if (filename) {@@ -199,11 +212,12 @@ export default function useMusicVideoSceneMedia({ project, videoSettings, applyS// the response carried no id to track. trackJob reconciles a terminal event// that raced ahead of this .then. Resolves `{ ok }` — see generateFrame's// doc comment for why the caller never sees a rejection.- const trackVideoJob = (res, sceneId) => {+ const trackVideoJob = (res, sceneId, onJob) => {const jobId = res?.jobId || res?.generationId;if (!jobId) { videoLane.clearScene(sceneId); return { ok: false }; }+ onJob?.(jobId);videoLane.trackJob(jobId, sceneId);- return { ok: true };+ return { ok: true, jobId };};const handleVideoError = (err, sceneId, fallbackMessage) => {@@ -223,7 +237,7 @@ export default function useMusicVideoSceneMedia({ project, videoSettings, applyS* Returns a promise that always resolves to `{ ok }` — see generateFrame's* doc comment. `revisionId` (optional) is the revision hook's kickoff tag (#9011).*/- const generateSceneVideo = (scene, { revisionId } = {}) => {+ const generateSceneVideo = (scene, { revisionId, onJob } = {}) => {if (!scene.referenceImageId) { toast.error('Generate a reference frame first'); return Promise.resolve({ ok: false }); }const problem = shotActionContractProblem(scene.direction?.actionContract, scene);if (problem) { toast.error(problem); return Promise.resolve({ ok: false }); }@@ -278,7 +292,7 @@ export default function useMusicVideoSceneMedia({ project, videoSettings, applyS} : {}),musicVideo: JSON.stringify({ projectId: project.id, sceneId: scene.sceneId, ...(revisionId ? { revisionId } : {}) }),})- .then((res) => trackVideoJob(res, scene.sceneId))+ .then((res) => trackVideoJob(res, scene.sceneId, onJob)).catch((err) => handleVideoError(err, scene.sceneId, 'Scene video generation failed'));};@@ -318,46 +332,69 @@ export default function useMusicVideoSceneMedia({ project, videoSettings, applySconst layered = isLayeredComposition(project);const frameScenes = scenes.filter((scene) => sceneVisualLayer(scene, { layered }) !== 'card');const footageScenes = scenes.filter((scene) => sceneVisualLayer(scene, { layered }) === 'footage');+ const planMissingFrames = () => frameScenes.filter((scene) =>+ !scene.referenceImageId && !genScenes[scene.sceneId] && buildFramePrompt(scene));++ // The clips a Videos batch would submit: a footage scene with a frame, no clip+ // and nothing in flight. A scene still waiting for its frame never blocks the+ // others (#10153). Performance shots the current lane cannot lip-sync are+ // dropped here and reported once (#8977).+ const planMissingVideos = () => {+ const candidates = footageScenes.filter((scene) =>+ scene.referenceImageId && !scene.videoHistoryId && !genVideoScenes[scene.sceneId] && buildShotPrompt(scene));+ const { settings, audioReactiveSelected } = videoSettings;+ const lipSyncBlocked = performanceBlockedReason(audioReactiveSelected ? 'local' : settings.backend);+ const pending = lipSyncBlocked ? candidates.filter((scene) => !isPerformanceScene(scene)) : candidates;+ return { pending, skipped: candidates.length - pending.length, lipSyncBlocked };+ };++ // Fire every scene at once, counting the batch so the board can show+ // "N of M done", and cancel what is left on request (useSceneBatch).+ const runBatch = (batch, pending, generate) => {+ batch.begin(pending.length);+ pending.forEach((scene) => generate(scene, { onJob: batch.register }).then((res) => {+ if (!res.ok) batch.kickoffFailed();+ else if (!res.jobId) batch.completedWithoutJob();+ }));+ };+const generateMissingFrames = () => {- const pending = frameScenes.filter((scene) =>- !scene.referenceImageId && !genScenes[scene.sceneId] && buildFramePrompt(scene));+ const pending = planMissingFrames();if (pending.length === 0) {toast.info('Every scene already has a reference frame');return;}- pending.forEach((scene) => generateFrame(scene));+ runBatch(frameBatch, pending, generateFrame);};const generateMissingVideos = () => {- const candidates = footageScenes.filter((scene) =>- scene.referenceImageId && !scene.videoHistoryId && !genVideoScenes[scene.sceneId] && buildShotPrompt(scene));- // Performance shots the current lane cannot lip-sync are skipped with one- // notice rather than a toast per scene (#8977).- const { settings, audioReactiveSelected } = videoSettings;- const lipSyncBlocked = performanceBlockedReason(audioReactiveSelected ? 'local' : settings.backend);- const pending = lipSyncBlocked ? candidates.filter((scene) => !isPerformanceScene(scene)) : candidates;- const skipped = candidates.length - pending.length;+ const { pending, skipped, lipSyncBlocked } = planMissingVideos();if (skipped > 0) toast.info(`Skipped ${skipped} performance shot${skipped === 1 ? '' : 's'}: ${lipSyncBlocked}`);- if (pending.length === 0 && skipped > 0) return;if (pending.length === 0) {- const referenceFrameCount = footageScenes.filter((scene) => scene.referenceImageId).length;- toast.info(referenceFrameCount < footageScenes.length- ? 'Generate every reference frame before generating the remaining videos'+ if (skipped > 0) return;+ toast.info(footageScenes.some((scene) => !scene.referenceImageId && !scene.videoHistoryId)+ ? 'Generate a reference frame first — no waiting scene has one yet': 'Every scene already has a video');return;}- pending.forEach((scene) => generateSceneVideo(scene));+ runBatch(videoBatch, pending, generateSceneVideo);};return {genScenes,genVideoScenes,+ sceneProgress: frameLane.sceneProgress,+ videoSceneProgress: videoLane.sceneProgress,+ frameBatch,+ videoBatch,conditioning,buildFramePrompt,buildShotPrompt,generateFrame,generateSceneVideo,continueSceneVideo,+ planMissingFrames,+ planMissingVideos,generateMissingFrames,generateMissingVideos,};diff --git a/client/src/hooks/useSceneBatch.js b/client/src/hooks/useSceneBatch.jsnew file mode 100644index 0000000000..fa1fc7f4e1--- /dev/null+++ b/client/src/hooks/useSceneBatch.js@@ -0,0 +1,59 @@+import { useCallback, useRef, useState } from 'react';+import { cancelMediaJob } from '../services/apiMediaJobs';++/**+ * Counter for one "generate every missing frame / clip" batch on the Music Video+ * board (#10153). The batch owns no socket subscription: the lane's+ * `useSceneRenderLifecycle` reports each tracked job's terminal outcome through+ * `settled`, and this hook only attributes it to the batch that registered the+ * job.+ *+ * - `begin(total)` — start a batch (replaces a finished one).+ * - `register(jobId)` — a kicked-off job belongs to the batch. After a+ * cancel request a late kickoff is canceled at once.+ * - `kickoffFailed()` — a scene whose request never reached the queue.+ * - `completedWithoutJob()` — a synchronous lane that finished inline.+ * - `settled({ jobId, outcome })` — wire as the lane's `onSettled`.+ * - `cancel()` — cancel every queued and running job of the batch+ * via the media-job cancel API; the spinners clear+ * through the lane's canceled-event path.+ * - `dismiss()` — drop a finished batch's summary.+ *+ * `state` is `null` or `{ total, done, failed, canceled, cancelRequested }`.+ */+export default function useSceneBatch() {+ const [state, setState] = useState(null);+ const jobsRef = useRef(new Set());+ const cancelRef = useRef(false);++ const bump = useCallback((field) => setState((prev) => (prev ? { ...prev, [field]: prev[field] + 1 } : prev)), []);+ const cancelJob = (jobId) => { cancelMediaJob(jobId, { silent: true }).catch(() => {}); };++ const begin = useCallback((total) => {+ jobsRef.current = new Set();+ cancelRef.current = false;+ setState({ total, done: 0, failed: 0, canceled: 0, cancelRequested: false });+ }, []);+ const register = useCallback((jobId) => {+ jobsRef.current.add(jobId);+ if (cancelRef.current) cancelJob(jobId);+ }, []);+ const kickoffFailed = useCallback(() => bump(cancelRef.current ? 'canceled' : 'failed'), [bump]);+ const completedWithoutJob = useCallback(() => bump('done'), [bump]);+ const settled = useCallback(({ jobId, outcome }) => {+ if (!jobsRef.current.delete(jobId)) return;+ // A running job canceled over the API reports `failed` before `canceled`.+ bump(outcome === 'completed' ? 'done' : outcome === 'canceled' || cancelRef.current ? 'canceled' : 'failed');+ }, [bump]);+ const cancel = useCallback(() => {+ cancelRef.current = true;+ setState((prev) => (prev ? { ...prev, cancelRequested: true } : prev));+ jobsRef.current.forEach(cancelJob);+ }, []);+ const dismiss = useCallback(() => {+ jobsRef.current = new Set();+ setState(null);+ }, []);++ return { state, begin, register, kickoffFailed, completedWithoutJob, settled, cancel, dismiss };+}diff --git a/client/src/hooks/useSceneBatch.test.jsx b/client/src/hooks/useSceneBatch.test.jsxnew file mode 100644index 0000000000..3b11cfdf6e--- /dev/null+++ b/client/src/hooks/useSceneBatch.test.jsx@@ -0,0 +1,45 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';+import { renderHook, act } from '@testing-library/react';++const cancelMediaJob = vi.fn(() => Promise.resolve({}));+vi.mock('../services/apiMediaJobs', () => ({ cancelMediaJob: (...a) => cancelMediaJob(...a) }));++const useSceneBatch = (await import('./useSceneBatch.js')).default;++describe('useSceneBatch', () => {+ beforeEach(() => cancelMediaJob.mockClear());++ it('counts outcomes only for jobs the batch registered', () => {+ const { result } = renderHook(() => useSceneBatch());+ act(() => { result.current.begin(4); result.current.register('a'); result.current.register('b'); });+ act(() => {+ result.current.settled({ jobId: 'a', outcome: 'completed' });+ result.current.settled({ jobId: 'b', outcome: 'failed' });+ result.current.settled({ jobId: 'unrelated', outcome: 'completed' });+ result.current.kickoffFailed();+ result.current.completedWithoutJob();+ });+ expect(result.current.state).toEqual({ total: 4, done: 2, failed: 2, canceled: 0, cancelRequested: false });+ });++ it('cancel() cancels every unsettled job and counts a running-cancel failure as canceled', () => {+ const { result } = renderHook(() => useSceneBatch());+ act(() => { result.current.begin(3); ['a', 'b', 'c'].forEach(result.current.register); });+ act(() => result.current.settled({ jobId: 'a', outcome: 'completed' }));+ act(() => result.current.cancel());+ expect(cancelMediaJob.mock.calls.map(([id]) => id).sort()).toEqual(['b', 'c']);+ act(() => {+ result.current.settled({ jobId: 'b', outcome: 'failed' }); // running-cancel reports failed first+ result.current.settled({ jobId: 'c', outcome: 'canceled' });+ });+ expect(result.current.state).toMatchObject({ done: 1, failed: 0, canceled: 2, cancelRequested: true });+ });++ it('a kickoff that resolves after cancel is canceled the moment it registers', () => {+ const { result } = renderHook(() => useSceneBatch());+ act(() => { result.current.begin(1); result.current.cancel(); });+ expect(cancelMediaJob).not.toHaveBeenCalled();+ act(() => result.current.register('late'));+ expect(cancelMediaJob).toHaveBeenCalledWith('late', { silent: true });+ });+});diff --git a/client/src/hooks/useSceneRenderLifecycle.js b/client/src/hooks/useSceneRenderLifecycle.jsindex 62be97be2a..9add6da2b3 100644--- a/client/src/hooks/useSceneRenderLifecycle.js+++ b/client/src/hooks/useSceneRenderLifecycle.js@@ -37,11 +37,19 @@ import toast from '../components/ui/Toast';* - `canceledEvent` — job cancel (e.g. `image-gen:canceled`). A queued-cancel* emits only this (no `failedEvent`), so without it the* spinner would stick — every queue-backed lane has one.+ * - `startedEvent` / `progressEvent` — optional `*-gen:started` / `*-gen:progress`+ * events; they feed `sceneProgress` (queued → running ++ * a 0..1 fraction) for the scene whose job they name.+ * - `onSettled({ jobId, sceneId, outcome })` — optional; called once per+ * tracked job with `'completed' | 'failed' | 'canceled'`+ * (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.*- * Returns `{ genScenes, startScene, clearScene, trackJob }`:+ * Returns `{ genScenes, sceneProgress, startScene, clearScene, trackJob }`+ * (`sceneProgress`: sceneId → `{ progress }` once a job reports running; a scene+ * in `genScenes` with no entry is still queued):* - `startScene(sceneId)` — light the spinner before the kickoff request.* - `clearScene(sceneId)` — drop the spinner (sync-lane finish, or a kickoff* that returns no trackable job id).@@ -55,21 +63,25 @@ export default function useSceneRenderLifecycle({completedEvent,failedEvent,canceledEvent,+ startedEvent,+ progressEvent,+ onSettled,apply,failMessage,}) {const [genScenes, setGenScenes] = useState({});+ const [sceneProgress, setSceneProgress] = useState({});// jobId → sceneId for renders this lane is awaiting.const pendingRef = useRef(new Map());- // jobId → failed(bool) for terminal events that beat their kickoff's+ // jobId → outcome ('completed' | 'failed' | 'canceled') for terminal events that beat their kickoff's// trackJob registration. Capped so unrelated jobs across the app can't grow// it unbounded; the kickoff reconciles its own entry on arrival.const orphanRef = useRef(new Map());// 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 });- cfgRef.current = { apply, failMessage };+ const cfgRef = useRef({ apply, failMessage, onSettled });+ cfgRef.current = { apply, failMessage, onSettled };const startScene = useCallback((sceneId) => setGenScenes((prev) => ({ ...prev, [sceneId]: true })),@@ -83,19 +95,27 @@ export default function useSceneRenderLifecycle({}),[],);+ const clearProgress = useCallback((sceneId) => setSceneProgress((prev) => {+ if (!(sceneId in prev)) return prev;+ const next = { ...prev };+ delete next[sceneId];+ return next;+ }), []);// The orphan-reconcile helper used by the kickoff `.then`: if the terminal// event already raced ahead, settle it now; otherwise register the pending job.const trackJob = useCallback((jobId, sceneId) => {if (orphanRef.current.has(jobId)) {- const failed = orphanRef.current.get(jobId);+ const outcome = orphanRef.current.get(jobId);orphanRef.current.delete(jobId);clearScene(sceneId);- if (failed) toast.error(cfgRef.current.failMessage);+ clearProgress(sceneId);+ if (outcome === 'failed') toast.error(cfgRef.current.failMessage);+ cfgRef.current.onSettled?.({ jobId, sceneId, outcome });return;}pendingRef.current.set(jobId, sceneId);- }, [clearScene]);+ }, [clearScene, clearProgress]);useEffect(() => {const onAttach = (data) => cfgRef.current.apply(data);@@ -105,7 +125,9 @@ export default function useSceneRenderLifecycle({// cleanup so a `getMediaJob` promise still in flight (or a re-arm) can't pop// a "render failed" toast onto whatever page the user navigated to.let mounted = true;- const settle = (data, failed) => {+ // `failed` is the toast bit (an orphan failure still owes its kickoff a+ // toast); `outcome` is what actually happened, for the batch counter.+ const settle = (data, failed, outcome) => {const jobId = data?.generationId || data?.jobId;if (!jobId) return;const sceneId = pendingRef.current.get(jobId);@@ -114,15 +136,28 @@ 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, !!failed);+ orphans.set(jobId, outcome);evictOldest(orphans, ORPHAN_BUFFER_MAX);return;}pendingRef.current.delete(jobId);clearScene(sceneId);+ clearProgress(sceneId);if (failed) toast.error(cfgRef.current.failMessage);+ cfgRef.current.onSettled?.({ jobId, sceneId, outcome });+ };+ const onCompleted = (data) => settle(data, false, 'completed');+ // started / progress: a tracked job is running; keep the fraction for its card.+ const onRunning = (data) => {+ const jobId = data?.generationId || data?.jobId;+ const sceneId = jobId && pendingRef.current.get(jobId);+ if (!sceneId) return;+ const progress = typeof data.progress === 'number' && Number.isFinite(data.progress)+ ? Math.min(1, Math.max(0, data.progress)) : null;+ setSceneProgress((prev) => (prev[sceneId]?.progress === progress && sceneId in prev+ ? prev+ : { ...prev, [sceneId]: { progress: progress ?? prev[sceneId]?.progress ?? null } }));};- const onCompleted = (data) => settle(data, false);// Deferred failure toast for an owned render. A render canceled WHILE RUNNING// reaches us as `failedEvent` (SIGTERM) just before `canceledEvent` — and// before the queue flips the job to 'canceled' — so neither the failed event@@ -158,7 +193,7 @@ export default function useSceneRenderLifecycle({// kickoff registration is toasted by the kickoff reconciliation; an// unrelated job is simply capped/evicted from the orphan map unseen.const owned = pendingRef.current.has(jobId);- settle(data, !owned);+ settle(data, !owned, 'failed');if (owned && !failTimers.has(jobId)) armFailToast(jobId);};// Queued-cancel emits no `failedEvent`; running-cancel emits failed then this.@@ -169,15 +204,19 @@ export default function useSceneRenderLifecycle({const t = failTimers.get(jobId);if (t) { clearTimeout(t); failTimers.delete(jobId); }}- settle(data, false);+ settle(data, false, 'canceled');};socket.on(attachEvent, onAttach);+ if (startedEvent) socket.on(startedEvent, onRunning);+ if (progressEvent) socket.on(progressEvent, onRunning);socket.on(completedEvent, onCompleted);socket.on(failedEvent, onFailed);socket.on(canceledEvent, onCanceled);return () => {socket.off(attachEvent, onAttach);+ if (startedEvent) socket.off(startedEvent, onRunning);+ if (progressEvent) socket.off(progressEvent, onRunning);socket.off(completedEvent, onCompleted);socket.off(failedEvent, onFailed);socket.off(canceledEvent, onCanceled);@@ -185,7 +224,7 @@ export default function useSceneRenderLifecycle({for (const t of failTimers.values()) clearTimeout(t);failTimers.clear();};- }, [attachEvent, completedEvent, failedEvent, canceledEvent, clearScene]);+ }, [attachEvent, completedEvent, failedEvent, canceledEvent, startedEvent, progressEvent, clearScene, clearProgress]);- return { genScenes, startScene, clearScene, trackJob };+ return { genScenes, sceneProgress, startScene, clearScene, trackJob };}diff --git a/client/src/hooks/useSceneRenderLifecycle.test.jsx b/client/src/hooks/useSceneRenderLifecycle.test.jsxindex c4d2b21d9e..b002c0a900 100644--- a/client/src/hooks/useSceneRenderLifecycle.test.jsx+++ b/client/src/hooks/useSceneRenderLifecycle.test.jsx@@ -152,3 +152,38 @@ describe('useSceneRenderLifecycle', () => {expect(result.current.genScenes.s1).toBe(true);});});++describe('useSceneRenderLifecycle progress and settled outcomes (#10153)', () => {+ beforeEach(() => { handlers.clear(); getMediaJob.mockReset(); toastError.mockReset(); });+ afterEach(cleanup);++ const PROGRESS_CFG = { startedEvent: 'image-gen:started', progressEvent: 'image-gen:progress' };++ it('a scene is queued until the job reports running, then carries its progress fraction', () => {+ const { result } = renderLane(PROGRESS_CFG);+ act(() => { result.current.startScene('s1'); result.current.trackJob('job-1', 's1'); });+ expect(result.current.sceneProgress.s1).toBeUndefined();+ fire('image-gen:started', { generationId: 'job-1', totalSteps: 20 });+ expect(result.current.sceneProgress.s1).toEqual({ progress: null });+ fire('image-gen:progress', { generationId: 'job-1', progress: 0.4 });+ expect(result.current.sceneProgress.s1).toEqual({ progress: 0.4 });+ fire('image-gen:progress', { generationId: 'someone-elses', progress: 0.9 });+ expect(result.current.sceneProgress).toEqual({ s1: { progress: 0.4 } });+ fire('image-gen:completed', { generationId: 'job-1' });+ expect(result.current.sceneProgress.s1).toBeUndefined();+ });++ it('reports each tracked job once with its terminal outcome, including an orphan that raced ahead', () => {+ const onSettled = vi.fn();+ const { result } = renderLane({ onSettled });+ act(() => { result.current.startScene('s1'); result.current.startScene('s2'); result.current.startScene('s3'); });+ act(() => { result.current.trackJob('a', 's1'); result.current.trackJob('b', 's2'); });+ fire('image-gen:completed', { generationId: 'a' });+ fire('image-gen:failed', { generationId: 'b' });+ fire('image-gen:canceled', { generationId: 'c' }); // terminal beats trackJob+ act(() => result.current.trackJob('c', 's3'));+ expect(onSettled.mock.calls.map(([e]) => [e.jobId, e.sceneId, e.outcome])).toEqual([+ ['a', 's1', 'completed'], ['b', 's2', 'failed'], ['c', 's3', 'canceled'],+ ]);+ });+});diff --git a/client/src/lib/README.md b/client/src/lib/README.mdindex 477cf83066..9a268f80c2 100644--- a/client/src/lib/README.md+++ b/client/src/lib/README.md@@ -61,6 +61,7 @@ grep -i "what you want to do" client/src/lib/README.md| `beatGrid.js` | Music-video beat-quantized timeline arranger (#1854). `buildBeatGridPoints(audioAnalysis)` merges beats/downbeats/section edges into one ranked snap-point list; `snapTimeToGrid(timeSec, gridPoints, toleranceSec)` finds the nearest point within tolerance; `computeSceneSpans(scenes, durationSec)` lays out scenes without a persisted `startSec`/`endSec` contiguously as a display-only fallback; `computeDragSpan({kind, startSpan, deltaSec, gridPoints, ...})` resolves a timeline drag gesture (`'move'` or `'right'` — no `'left'`, since the render can only trim from a clip's own frame 0) into a new span; `shouldMarkBeatAligned({kind, snapped, wasPersisted})` gates the `beatAligned` flag so a reposition-only drag can't silently promote an unpersisted scene's placeholder fallback duration into a "saved exactly" render duration; `autoArrangeScenes(scenes, audioAnalysis)` proposes a full `{ sceneId, startSec, endSec, beatAligned }[]` arrangement by distributing scenes across song sections weighted by each section's `energy` (#1915). Used by `components/musicVideo/BeatTimeline.jsx` and `pages/MusicVideo.jsx`. || `musicVideoAspect.js` | Re-export of `server/lib/musicVideoAspect.js`: `musicVideoAspect`, `musicVideoFrameGenSize`. Used by `hooks/useMusicVideoSceneMedia.js` so board frames match the project aspect. || `musicVideoMotion.js` | Re-export of `server/lib/musicVideoMotion.js` (`MOTION_CONTINUITY_CLAUSE`) for board motion prompts. |+| `musicVideoBatchPlan.js` | Pure helpers for the Music Video missing-frame / missing-clip batches (#10153): `videoBatchPreview` (count + fal estimate summed from `falSceneTake`, unpriced count), `scenesWaitingForFrame`, `videosButtonLabel`, `batchSummary`, `batchActive`, `batchSceneName`. Used by `components/musicVideo/ProjectActionGroups.jsx`. || `musicVideoLayers.js` | Music-video per-scene visual layers (#8985), re-exported from `server/lib/musicVideoLayers.js`: `MUSIC_VIDEO_VISUAL_LAYERS`, `MUSIC_VIDEO_STILL_MOVES`, `sceneVisualLayer(scene, { layered })`, `sceneHasAuthoredSpan`, `sceneRenderReady(scene, { layered })`. Used by `components/musicVideo/SceneCard.jsx`, `ProjectActionGroups.jsx` and `hooks/useMusicVideoSceneMedia.js`. || `musicVideoTakes.js` | Music-video scene takes view helpers (#8965): `sceneTakeList(scene, kind)` lists a scene's image/video takes with an un-materialized pre-takes selection appended as a read-only `legacy` take; `takePreviewKey`, `takeThumbUrl`, `takeClipUrl` (hover-preview clip), `sceneHasPendingDecision` (contact-sheet filter), `takeProvenance`; `TAKE_SLOT` maps a take kind to its selection field. Used by `components/musicVideo/SceneTakeStrip.jsx` and `pages/MusicVideo.jsx`. || `musicVideoShotTiming.js` | Re-export of `server/lib/musicVideoShotTiming.js` (#8977) — shot modes, the verified source-audio lip-sync capability table, `performanceBlockedReason`, `planPerformanceRepair` (measured accepted-prefix boundary, suffix interval and next spend), `planPerformanceWindow`, `grokCoverage`, `approximateMotionCues`, `shotSplitLimit` (when a scene offers a lyric-boundary split), `falSceneTake` (a fal take's model, length, resolution and estimated cost). Used by `hooks/useMusicVideoSceneMedia.js` and `components/musicVideo/SceneCard.jsx`. |diff --git a/client/src/lib/index.js b/client/src/lib/index.jsindex 9bd55bebbf..61b074b4f4 100644--- a/client/src/lib/index.js+++ b/client/src/lib/index.js@@ -69,6 +69,7 @@ export * from './issueLength.js';export * from './issueRefs.js';export * from './musicDuration.js';export * from './muscriptorModels.js';+export * from './musicVideoBatchPlan.js';export * from './musicVideoLayers.js';export * from './musicVideoAspect.js';export * from './musicVideoMotion.js';diff --git a/client/src/lib/musicVideoBatchPlan.js b/client/src/lib/musicVideoBatchPlan.jsnew file mode 100644index 0000000000..63178d6e97--- /dev/null+++ b/client/src/lib/musicVideoBatchPlan.js@@ -0,0 +1,62 @@+import { falSceneTake } from './musicVideoShotTiming.js';+import { getFalVideoModel } from './falVideoModels.js';+import { formatUsd } from '../utils/formatters.js';++/**+ * Pure helpers for the Music Video "generate the missing frames / clips"+ * batches (#10153): what a batch would submit, what it would cost, and the+ * running summary line. Nothing here touches the network.+ */++const plural = (n, word) => `${n} ${word}${n === 1 ? '' : 's'}`;++/** A scene's display name for a status line — the card's own heading. */+export const batchSceneName = (scene) => scene.sectionLabel || scene.label || `Scene ${(scene.order ?? 0) + 1}`;++/**+ * Footage scenes still waiting on a reference frame before a clip can be made.+ * They no longer block the Videos batch — only name themselves in its label.+ */+export const scenesWaitingForFrame = (footageScenes) =>+ footageScenes.filter((scene) => !scene.referenceImageId && !scene.videoHistoryId);++/** "Videos 9/10 (1 waiting for a frame: Chorus)" — the Videos button label. */+export function videosButtonLabel({ renderableCount, footageCount, waiting }) {+ const base = `Videos ${renderableCount}/${footageCount}`;+ if (waiting.length === 0) return base;+ const names = waiting.slice(0, 2).map(batchSceneName).join(', ');+ return `${base} (${waiting.length} waiting for a frame: ${names}${waiting.length > 2 ? ', …' : ''})`;+}++/**+ * The confirm line for a clip batch. fal takes are priced per scene with the+ * same `falSceneTake` the scene card shows; a scene it cannot price is counted+ * as unpriced. Local and Grok renders show the count only.+ */+export function videoBatchPreview({ scenes, backend, videoSettings, songDurationSec = null }) {+ const count = scenes.length;+ if (backend !== 'fal') return { count, backend, text: `Generate ${plural(count, 'clip')} on ${backend === 'grok' ? 'Grok' : 'the local renderer'}` };+ const takes = scenes.map((scene) => falSceneTake({ scene, videoSettings, songDurationSec }));+ const priced = takes.filter((take) => take.costUsd != null);+ const costUsd = priced.reduce((sum, take) => sum + take.costUsd, 0);+ const modelIds = [...new Set(takes.map((take) => take.modelId))];+ const model = modelIds.length === 1 ? (getFalVideoModel(modelIds[0])?.label || modelIds[0]) : `${modelIds.length} models`;+ const resolutions = [...new Set(takes.map((take) => take.resolution).filter(Boolean))];+ const unpriced = takes.length - priced.length;+ return {+ count, backend, costUsd, unpriced,+ text: `Generate ${plural(count, 'clip')} on fal / ${model}${resolutions.length === 1 ? ` ${resolutions[0]}` : ''}`+ + ` · est. ${formatUsd(costUsd)}${unpriced > 0 ? ` (${unpriced} unpriced)` : ''}`,+ };+}++/** "Videos: 6 of 14 done · 2 failed" plus the canceled tally once there is one. */+export function batchSummary(noun, state) {+ const parts = [`${noun}: ${state.done} of ${state.total} done`];+ if (state.failed > 0) parts.push(`${state.failed} failed`);+ if (state.canceled > 0) parts.push(`${state.canceled} canceled`);+ return parts.join(' · ');+}++/** True while at least one submitted scene has no outcome yet. */+export const batchActive = (state) => !!state && state.done + state.failed + state.canceled < state.total;diff --git a/client/src/lib/musicVideoBatchPlan.test.js b/client/src/lib/musicVideoBatchPlan.test.jsnew file mode 100644index 0000000000..525563f05a--- /dev/null+++ b/client/src/lib/musicVideoBatchPlan.test.js@@ -0,0 +1,39 @@+import { describe, it, expect } from 'vitest';+import { batchActive, batchSummary, scenesWaitingForFrame, videoBatchPreview, videosButtonLabel } from './musicVideoBatchPlan.js';++const scene = (order, extra = {}) => ({ sceneId: `s${order}`, order, startSec: order * 5, endSec: order * 5 + 5, ...extra });++describe('musicVideoBatchPlan', () => {+ it('sums fal takes into one estimate and counts what it cannot price', () => {+ const scenes = [scene(0), scene(1)];+ const priced = videoBatchPreview({ scenes, backend: 'fal', videoSettings: {} });+ expect(priced.count).toBe(2);+ expect(priced.costUsd).toBeGreaterThan(0);+ expect(priced.unpriced).toBe(0);+ expect(priced.text).toMatch(/^Generate 2 clips on fal \/ .* · est\. \$/);+ const uncurated = videoBatchPreview({ scenes, backend: 'fal', videoSettings: { falModelId: 'fal-ai/not-curated' } });+ expect(uncurated.unpriced).toBe(2);+ expect(uncurated.text).toContain('(2 unpriced)');+ });++ it('shows the count only for local and Grok renders', () => {+ expect(videoBatchPreview({ scenes: [scene(0)], backend: 'local', videoSettings: {} }).text).toBe('Generate 1 clip on the local renderer');+ expect(videoBatchPreview({ scenes: [scene(0), scene(1)], backend: 'grok', videoSettings: {} }).text).toBe('Generate 2 clips on Grok');+ });++ it('names the scenes waiting for a frame, ignoring ones that already have a clip', () => {+ const footage = [scene(0, { referenceImageId: 'a.png' }), scene(1, { sectionLabel: 'Chorus' }), scene(2, { videoHistoryId: 'v' })];+ const waiting = scenesWaitingForFrame(footage);+ expect(waiting.map((s) => s.sceneId)).toEqual(['s1']);+ expect(videosButtonLabel({ renderableCount: 1, footageCount: 3, waiting })).toBe('Videos 1/3 (1 waiting for a frame: Chorus)');+ expect(videosButtonLabel({ renderableCount: 3, footageCount: 3, waiting: [] })).toBe('Videos 3/3');+ });++ it('summarises a batch and knows when it is still running', () => {+ expect(batchSummary('Videos', { total: 14, done: 6, failed: 2, canceled: 0 })).toBe('Videos: 6 of 14 done · 2 failed');+ expect(batchSummary('Videos', { total: 14, done: 6, failed: 0, canceled: 8 })).toBe('Videos: 6 of 14 done · 8 canceled');+ expect(batchActive({ total: 3, done: 1, failed: 1, canceled: 0 })).toBe(true);+ expect(batchActive({ total: 3, done: 1, failed: 1, canceled: 1 })).toBe(false);+ expect(batchActive(null)).toBe(false);+ });+});