Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

fix: clarify Music Video review navigation and render feedback (#9866)

[._.]/368915e5530c
diff --git a/client/src/components/musicVideo/CompositionPreviewPlayer.jsx b/client/src/components/musicVideo/CompositionPreviewPlayer.jsx
index 5495f3b46f..aa49e168a2 100644
--- a/client/src/components/musicVideo/CompositionPreviewPlayer.jsx
+++ b/client/src/components/musicVideo/CompositionPreviewPlayer.jsx
@@ -161,14 +161,14 @@ export default function CompositionPreviewPlayer({ project, audioUrl, seekReques
)}
</div>
<div className="flex flex-wrap items-center gap-2">
- <button type="button" className={buttonCls} onClick={togglePlay} disabled={!preview || !audioUrl}>
+ <button type="button" className={buttonCls} onClick={togglePlay} disabled={!preview || !audioUrl || (!!previewError && !playing)}>
{playing ? <Pause size={14} /> : <Play size={14} />} {playing ? 'Pause' : 'Play'}
</button>
<label htmlFor={scrubId} className="sr-only">{draft ? 'Scrub the composition candidate' : 'Scrub the composition preview'}</label>
- <input id={scrubId} type="range" min={0} max={duration || 0} step={1 / fps} value={Math.min(t, duration || 0)}
+ <input disabled={!preview || !!previewError} id={scrubId} type="range" min={0} max={duration || 0} step={1 / fps} value={Math.min(t, duration || 0)}
onChange={(e) => { audioRef.current?.pause(); setPlaying(false); seek(Number(e.target.value)); }}
className="min-w-0 flex-1" />
- <span className="text-xs text-port-text-muted tabular-nums">{t.toFixed(2)}s / {duration.toFixed(1)}s</span>
+ <span className="text-xs text-port-text-muted tabular-nums">{previewError ? 'Preview unavailable' : preview ? `${t.toFixed(2)}s / ${duration.toFixed(1)}s` : !wanted ? 'Expand to load preview' : 'Loading preview…'}</span>
</div>
{lyric && <p className="text-xs italic break-words" aria-live="off" data-testid="preview-lyric">♪ {lyric}</p>}
{audioUrl && <audio ref={audioRef} src={audioUrl} preload="none" className="hidden" onEnded={() => setPlaying(false)} />}
diff --git a/client/src/components/musicVideo/CompositionPreviewPlayer.test.jsx b/client/src/components/musicVideo/CompositionPreviewPlayer.test.jsx
index 16e205ed8b..9f23c227f6 100644
--- a/client/src/components/musicVideo/CompositionPreviewPlayer.test.jsx
+++ b/client/src/components/musicVideo/CompositionPreviewPlayer.test.jsx
@@ -52,6 +52,9 @@ describe('CompositionPreviewPlayer', () => {
const { rerender } = render(<CompositionPreviewPlayer project={project} audioUrl={null} collapsed />);
await act(async () => {});
expect(api.getMusicVideoCompositionPreview).not.toHaveBeenCalled();
+ expect(screen.getByText('Expand to load preview')).toBeInTheDocument();
+ expect(screen.getByLabelText('Scrub the composition preview')).toBeDisabled();
+ expect(screen.queryByText('0.00s / 0.0s')).not.toBeInTheDocument();
rerender(<CompositionPreviewPlayer project={project} audioUrl={null} collapsed={false} />);
await screen.findByTitle('Composition document preview');
expect(api.getMusicVideoCompositionPreview).toHaveBeenCalledTimes(1);
diff --git a/client/src/components/musicVideo/ExcerptPanel.jsx b/client/src/components/musicVideo/ExcerptPanel.jsx
index a298afdc35..40a6424e3b 100644
--- a/client/src/components/musicVideo/ExcerptPanel.jsx
+++ b/client/src/components/musicVideo/ExcerptPanel.jsx
@@ -4,6 +4,7 @@ import { musicVideoAspect, MUSIC_VIDEO_ASPECTS } from '../../lib/musicVideoAspec
import { getMusicVideoSocialCuts } from '../../services/apiMusicVideo.js';
import RevisionPanel, { currentRevision } from './RevisionPanel.jsx';
import AutoReviewPanel from './AutoReviewPanel.jsx';
+import { formatCount } from '../../utils/formatters.js';
const VERDICT_STYLES = {
flagged: 'bg-port-error/20 text-port-error',
@@ -71,7 +72,7 @@ function NoteRow({ excerptId, note, busy, onEdit, onDelete, onSeek }) {
);
}
-function ExcerptCard({ excerpt, deleting, noteBusy, onDelete, onCancel, onAddNote, onEditNote, onDeleteNote, canRevise, onRevise }) {
+function ExcerptCard({ excerpt, activeRenderId, connected, deleting, noteBusy, onDelete, onCancel, onAddNote, onEditNote, onDeleteNote, canRevise, onRevise }) {
const videoRef = useRef(null);
const [draft, setDraft] = useState('');
const seek = (t) => { if (videoRef.current) { videoRef.current.currentTime = t; videoRef.current.play?.().catch(() => {}); } };
@@ -87,7 +88,7 @@ function ExcerptCard({ excerpt, deleting, noteBusy, onDelete, onCancel, onAddNot
return (
<li className="rounded border border-port-border p-2 space-y-2">
<div className="flex flex-wrap items-center justify-between gap-2 text-xs">
- <span className="font-medium">{fmt(excerpt.startSec)} – {fmt(excerpt.endSec)} <span className="text-port-text-muted">({STATUS_LABELS[excerpt.status] || excerpt.status})</span>
+ <span className="font-medium">{fmt(excerpt.startSec)} – {fmt(excerpt.endSec)} <span className="text-port-text-muted">({excerpt.status === 'rendering' && (activeRenderId !== excerpt.id || connected === false) ? 'Checking render status' : STATUS_LABELS[excerpt.status] || excerpt.status})</span>
{excerpt.aspect && excerpt.aspect !== '16:9' && <span className="ml-1.5 px-1.5 py-0.5 rounded bg-port-accent/20 text-port-accent text-[10px]">{excerpt.aspect}</span>}</span>
<div className="flex items-center gap-2">
{/* #8987: regenerate ONLY the sections holding a flagged note; the rest stay as approved. */}
@@ -101,6 +102,7 @@ function ExcerptCard({ excerpt, deleting, noteBusy, onDelete, onCancel, onAddNot
: <button type="button" disabled={deleting} onClick={() => onDelete(excerpt.id)} className="text-port-error flex items-center gap-1 disabled:opacity-50 min-h-[44px] sm:min-h-0"><Trash2 size={12} /> Delete</button>}
</div>
</div>
+ <p className="text-xs text-port-text-muted">{excerpt.dependencyState?.status === 'stale' ? 'Earlier inputs — retained for reference' : excerpt.dependencyState?.status === 'current' ? 'Matches current inputs · production approval is separate' : 'Draft · approval is separate'}{excerpt.createdAt ? ` · ${new Date(excerpt.createdAt).toISOString().replace('T', ' ').slice(0, 19)} UTC` : ''}</p>
{excerpt.status === 'error' && excerpt.error && <p role="alert" className="text-xs text-port-error">{excerpt.error}</p>}
{excerpt.status === 'complete' && excerpt.filename && (
<div className="space-y-2">
@@ -145,9 +147,18 @@ function ExcerptCard({ excerpt, deleting, noteBusy, onDelete, onCancel, onAddNot
* start) — a frame check alone can't prove motion/audio sync, so the video
* plays alongside the sheet rather than replacing it.
*/
-export default function ExcerptPanel({ project, rendering, progress, excerpts, revision = null, autoReview = null, ...actions }) {
+export default function ExcerptPanel({ project, rendering, occupied = rendering, progress, excerpts, activeRenderId = null, connected, revision = null, autoReview = null, ...actions }) {
+ const newest = [...excerpts].reverse();
+ const latestAttempt = newest[0];
+ const current = newest.find(e => e.status === 'complete' && e.filename && e.dependencyState?.status !== 'stale');
+ const visible = newest.filter(e => e.status === 'rendering' || e === current);
+ const history = newest.filter(e => !visible.includes(e));
+ const card = excerpt => <ExcerptCard key={excerpt.id} excerpt={excerpt} activeRenderId={activeRenderId} connected={connected}
+ deleting={actions.deletingId === excerpt.id} noteBusy={actions.noteBusyId}
+ onDelete={actions.deleteExcerpt} onCancel={actions.cancelExcerpt} onAddNote={actions.addNote}
+ onEditNote={actions.editNote} onDeleteNote={actions.deleteNote} canRevise={canRevise} onRevise={revision?.revise} />;
const activeRevision = currentRevision(project);
- const canRevise = !!revision && !revision.busy && !rendering
+ const canRevise = !!revision && !revision.busy && !occupied
&& !(activeRevision && (activeRevision.status === 'open' || activeRevision.status === 'rendering'));
const durationSec = project?.audioAnalysis?.durationSec ?? null;
const [startSec, setStartSec] = useState(0);
@@ -172,7 +183,7 @@ export default function ExcerptPanel({ project, rendering, progress, excerpts, r
};
return (
- <div className="space-y-2">
+ <div id="mv-draft-excerpts" tabIndex={-1} style={{ scrollMarginTop: 'calc(var(--mv-header-h, 9rem) + 1rem)' }} className="space-y-2">
<span className="text-xs text-port-text-muted flex items-center gap-1"><Film size={12} /> Draft excerpt</span>
<div className="flex flex-wrap items-end gap-2">
<div>
@@ -202,7 +213,7 @@ export default function ExcerptPanel({ project, rendering, progress, excerpts, r
Fade audio edges
</label>
)}
- <button type="button" disabled={rendering || !valid}
+ <button type="button" disabled={occupied || !valid}
onClick={() => render(startSec, endSec, canReframe ? { aspect: aspect === projectAspect ? null : aspect, fade } : undefined)}
className="flex items-center gap-1 bg-port-accent/20 text-port-accent disabled:opacity-50 rounded px-2 py-1.5 text-xs min-h-[44px] sm:min-h-0">
<Film size={13} /> Render excerpt
@@ -226,7 +237,7 @@ export default function ExcerptPanel({ project, rendering, progress, excerpts, r
<span className="min-w-0 flex-1 break-words">{s.label ? `“${s.label}”` : ''} <span className="text-port-text-muted">{s.reasons.join(' · ')}</span></span>
<button type="button" onClick={() => { setStartSec(s.startSec); setEndSec(s.endSec); }}
className="text-port-text-muted min-h-[44px] sm:min-h-0 px-1">Use range</button>
- <button type="button" disabled={rendering}
+ <button type="button" disabled={occupied}
onClick={() => { setStartSec(s.startSec); setEndSec(s.endSec); render(s.startSec, s.endSec, { aspect: projectAspect === '9:16' ? null : '9:16', fade: true }); }}
className="text-port-accent disabled:opacity-50 min-h-[44px] sm:min-h-0 px-1">Render 9:16</button>
</li>
@@ -235,33 +246,35 @@ export default function ExcerptPanel({ project, rendering, progress, excerpts, r
)}
</div>
)}
+ {occupied && !rendering && <p role="status" className="text-sm">A draft is rendering in another project. Wait for it to finish before starting another.</p>}
{rendering && (
<div>
<div className="h-1.5 bg-port-bg rounded overflow-hidden">
<div className="h-full bg-port-accent transition-all" style={{ width: `${progress}%` }} />
</div>
- <p className="text-xs text-port-text-muted mt-1">Rendering excerpt — {Math.round(progress)}%</p>
+ <p className="text-xs text-port-text-muted mt-1">{connected === false ? 'Connecting to draft render…' : `Rendering draft — ${Math.round(progress)}%`}</p>
</div>
)}
+ {['error', 'canceled'].includes(latestAttempt?.status) && <p role="status" className="text-sm text-port-warning">
+ {latestAttempt.status === 'error' ? `Latest draft attempt failed: ${latestAttempt.error || 'No error details recorded.'}` : 'Latest draft attempt was cancelled.'} Completed drafts are retained. Details are in Earlier and failed attempts.
+ </p>}
+ <details><summary className="cursor-pointer min-h-[44px] py-2 text-sm">Revision and automatic review tools</summary>
{revision && (
- <RevisionPanel project={project} busy={revision.busy || rendering}
+ <RevisionPanel project={project} busy={revision.busy || occupied}
genScenes={revision.genScenes} genVideoScenes={revision.genVideoScenes}
onResume={revision.resume} onCancel={revision.cancel} />
)}
{autoReview && (
<AutoReviewPanel project={project} startSec={startSec} endSec={endSec} rangeValid={valid}
- rendering={rendering} autoReview={autoReview} />
- )}
- {excerpts.length > 0 && (
- <ul className="space-y-2">
- {[...excerpts].reverse().map((excerpt) => (
- <ExcerptCard key={excerpt.id} excerpt={excerpt} deleting={actions.deletingId === excerpt.id} noteBusy={actions.noteBusyId}
- onDelete={actions.deleteExcerpt} onCancel={actions.cancelExcerpt}
- onAddNote={actions.addNote} onEditNote={actions.editNote} onDeleteNote={actions.deleteNote}
- canRevise={canRevise} onRevise={revision?.revise} />
- ))}
- </ul>
+ rendering={occupied} autoReview={autoReview} />
)}
+ </details>
+ {visible.length > 0 && <ul aria-label="Current draft and active renders" className="space-y-2">{visible.map(card)}</ul>}
+ {history.length > 0 && <details>
+ <summary className="cursor-pointer min-h-[44px] py-2 text-sm">Earlier and failed attempts ({formatCount(history.length)})</summary>
+ <p className="text-xs text-port-text-muted">Retained for comparison. These attempts do not block approval of the current work.</p>
+ <ul className="space-y-2">{history.map(card)}</ul>
+ </details>}
</div>
);
}
diff --git a/client/src/components/musicVideo/ExcerptPanel.test.jsx b/client/src/components/musicVideo/ExcerptPanel.test.jsx
index 1325dbf8ba..feb35dc8e8 100644
--- a/client/src/components/musicVideo/ExcerptPanel.test.jsx
+++ b/client/src/components/musicVideo/ExcerptPanel.test.jsx
@@ -47,3 +47,40 @@ describe('ExcerptPanel social cuts (#9280)', () => {
expect(start).toHaveBeenCalledWith(0, 15, undefined);
});
});
+
+
+it('keeps the current draft visible while retaining stale and failed attempts behind history', () => {
+ const current = { id: 'current', status: 'complete', filename: 'current.mp4', startSec: 0, endSec: 12, dependencyState: { status: 'current' } };
+ render(<ExcerptPanel project={documentProject} rendering={false} progress={0} excerpts={[
+ { ...current, id: 'older', filename: 'older.mp4', dependencyState: { status: 'stale' } }, current,
+ { id: 'failed', status: 'error', error: 'Render interrupted: encoder input closed', startSec: 0, endSec: 12 },
+ ]} startExcerpt={vi.fn()} />);
+ expect(screen.getByRole('list', { name: 'Current draft and active renders' })).toHaveTextContent('Matches current inputs');
+ const history = screen.getByText('Earlier and failed attempts (2)').closest('details');
+ expect(history.open).toBe(false);
+ expect(screen.getByRole('status')).toBeVisible();
+ expect(screen.getByRole('status')).toHaveTextContent('Latest draft attempt failed: Render interrupted');
+ fireEvent.click(screen.getByText('Earlier and failed attempts (2)'));
+ expect(history.open).toBe(true);
+ expect(screen.getByText('Earlier inputs — retained for reference')).toBeVisible();
+ expect(screen.getByRole('alert')).toHaveTextContent('Render interrupted');
+});
+
+it('explains an occupied render slot without attributing another project’s progress to this project', () => {
+ const start = vi.fn();
+ render(<ExcerptPanel project={documentProject} occupied rendering={false} progress={0} excerpts={[]} startExcerpt={start} />);
+ const button = screen.getByRole('button', { name: /Render excerpt/ });
+ expect(button).toBeDisabled();
+ fireEvent.click(button);
+ expect(start).not.toHaveBeenCalled();
+ expect(screen.getByRole('status')).toHaveTextContent('another project');
+ expect(screen.queryByText(/Rendering draft/)).toBeNull();
+});
+
+it('does not mislabel current footage after it has been approved as production proof', () => {
+ render(<ExcerptPanel project={{ ...documentProject, productionReview: { proof: { excerptId: 'proof' }, approvals: { proof: { excerptId: 'proof' } } } }} rendering={false} progress={0} excerpts={[
+ { id: 'proof', status: 'complete', filename: 'example.mp4', startSec: 0, endSec: 12, dependencyState: { status: 'current' } },
+ ]} startExcerpt={vi.fn()} />);
+ expect(screen.getByText(/Matches current inputs/)).toHaveTextContent('production approval is separate');
+ expect(screen.queryByText(/unapproved draft/)).toBeNull();
+});
diff --git a/client/src/components/musicVideo/MusicVideoProjectCard.jsx b/client/src/components/musicVideo/MusicVideoProjectCard.jsx
index 28a6a77c11..fb6bd5b9b4 100644
--- a/client/src/components/musicVideo/MusicVideoProjectCard.jsx
+++ b/client/src/components/musicVideo/MusicVideoProjectCard.jsx
@@ -5,7 +5,7 @@ import ScenePreview from '../creative-director/ScenePreview.jsx';
import ConfirmButtonPair from '../ui/ConfirmButtonPair.jsx';
import { selectMusicVideoPreview } from '../../lib/musicVideoPreview.js';
import { useVideoFileSrc } from '../../hooks/useVideoFileSrc.js';
-import { deriveStages, projectSpend, MUSIC_VIDEO_STAGES } from '../../lib/musicVideoStages.js';
+import { deriveStages, projectSpend, projectShotSummary, MUSIC_VIDEO_STAGES } from '../../lib/musicVideoStages.js';
export const STATUS_COLORS = {
draft: 'bg-port-border text-port-text',
@@ -253,7 +253,7 @@ export default function MusicVideoProjectCard({
<div className="space-y-1 pt-1.5 border-t border-port-border/40 text-[11px]">
<div className="flex items-center justify-between text-port-text-muted">
<span>
- {scenes.length} scene{scenes.length === 1 ? '' : 's'}
+ {projectShotSummary(project)}
{scenesWithClips > 0 ? ` · ${scenesWithClips} clip${scenesWithClips === 1 ? '' : 's'}` : ''}
{scenesWithFrames > 0 && scenesWithClips === 0 ? ` · ${scenesWithFrames} frame${scenesWithFrames === 1 ? '' : 's'}` : ''}
</span>
diff --git a/client/src/components/musicVideo/ProductionReviewPanel.jsx b/client/src/components/musicVideo/ProductionReviewPanel.jsx
index a681573b75..6d991d16a2 100644
--- a/client/src/components/musicVideo/ProductionReviewPanel.jsx
+++ b/client/src/components/musicVideo/ProductionReviewPanel.jsx
@@ -53,10 +53,10 @@ export default function ProductionReviewPanel({ project, review, onOpenArtifact,
return <section id="mv-production-review" aria-label="Production review" className={framed ? 'rounded-lg border border-port-border bg-port-card p-3 space-y-3' : 'space-y-3'}>
{framed && <h3 className="font-medium">Production review</h3>}
- <p className="text-sm text-port-text-muted">Every medium needs visual direction, a timed storyboard and a watched animated proof. Drafts and technical renders do not count as approval.</p>
+ <p className="text-sm text-port-text-muted">Approve the visual direction, then the timed storyboard, then a watched animated proof. Approving a development file or rendering a draft does not approve production.</p>
{review.error && <p role="alert" className="text-port-error">{review.error}</p>}
<ol className="grid gap-2 sm:grid-cols-3">
- {Object.entries(labels).map(([key, label]) => <li key={key} className="rounded border border-port-border p-2">
+ {Object.entries(labels).map(([key, label]) => <li key={key} id={`mv-review-${key}`} tabIndex={-1} style={{ scrollMarginTop: 'calc(var(--mv-header-h, 9rem) + 1rem)' }} className="rounded border border-port-border p-2 focus:outline focus:outline-2 focus:outline-port-accent">
<strong className="text-sm">{label}</strong>
<p role="status" className="text-xs">{ready?.[key].approved ? 'Approved for this revision' : 'Human review required'}</p>
{(ready?.[key].problems || []).map(problem => <p key={problem} className="mt-1 text-xs text-port-text-muted">{problem}</p>)}
@@ -65,6 +65,10 @@ export default function ProductionReviewPanel({ project, review, onOpenArtifact,
|| (key === 'proof' && (playbackBlocked || !playbackComplete))}>
Approve {label.toLowerCase()}
</button>
+ {!blocked && !password && !ready?.[key].approved && !ready?.[key].problems.length && (key !== 'proof' || (!playbackBlocked && playbackComplete)) && <button type="button" className="block min-h-[44px] text-xs text-port-accent" onClick={() => {
+ const input = document.getElementById(fieldId('password'));
+ input?.scrollIntoView({ block: 'center' }); input?.focus({ preventScroll: true });
+ }}>Enter your password to enable approval</button>}
</li>)}
</ol>
<label htmlFor={fieldId('password')} className="block text-sm">Instance password for this approval
@@ -206,13 +210,14 @@ export default function ProductionReviewPanel({ project, review, onOpenArtifact,
<p className="mt-1 whitespace-pre-wrap text-sm">{saved.motionLanguage || 'Save an energy target and timed choreography in the planning editor before judging the proof.'}</p>
<p className="mt-2 text-xs text-port-text-muted">Compare playback with this saved plan. If the chosen energy or actions are missing, record revision feedback with a time range before approving.</p>
</section>
- <div className="flex flex-wrap items-end gap-2">
+ <div id="mv-review-render" tabIndex={-1} style={{ scrollMarginTop: 'calc(var(--mv-header-h, 9rem) + 1rem)' }} className="flex flex-wrap items-end gap-2">
<label htmlFor={fieldId('proof-start')} className="text-sm">Proof start (seconds)<input id={fieldId('proof-start')} type="number" min="0" step="0.01" value={startSec} onChange={e => setStartSec(Number(e.target.value))} className={fieldClass} /></label>
<label htmlFor={fieldId('proof-end')} className="text-sm">Proof end (seconds)<input id={fieldId('proof-end')} type="number" min="0" step="0.01" value={endSec} onChange={e => setEndSec(Number(e.target.value))} className={fieldClass} /></label>
- <button type="button" className={buttonClass} disabled={blocked || review.proof.active} onClick={() => review.renderProof({ startSec, endSec, kind: 'prototype' })}>Render feasibility prototype — unapproved</button>
- <button type="button" className={buttonClass} disabled={blocked || !ready?.storyboard.approved || review.proof.active} onClick={() => review.renderProof({ startSec, endSec })}>Render animated proof</button>
+ <button type="button" className={buttonClass} disabled={blocked || review.proof.occupied || review.proof.active} onClick={() => review.renderProof({ startSec, endSec, kind: 'prototype' })}>Render feasibility prototype — unapproved</button>
+ <button type="button" className={buttonClass} disabled={blocked || !ready?.storyboard.approved || review.proof.occupied || review.proof.active} onClick={() => review.renderProof({ startSec, endSec })}>Render animated proof</button>
</div>
- {review.proof.active && <p role="status">Rendering proof…</p>}
+ {review.proof.occupied && !review.proof.active && <p role="status">Review evidence is rendering in another project. Wait for it to finish before starting another.</p>}
+ {review.proof.active && <p role="status">{review.proof.connected === false ? 'Connecting to review render…' : `Rendering review evidence — ${review.proof.percent ?? 0}%.`} Production approvals are separate.</p>}
<p className="text-xs text-port-text-muted">A feasibility prototype uses the current authored composition and master audio without approving the look or authorizing production. It can be made before art approval; it never becomes approved proof automatically.</p>
{prototype?.status === 'complete' && prototype.filename && <figure><video controls className="mt-2 w-full rounded" aria-label="Unapproved feasibility prototype" src={`/data/videos/${encodeURIComponent(prototype.filename)}`} /><figcaption className="text-sm">Unapproved feasibility prototype — separate from production proof</figcaption></figure>}
{excerpt?.status === 'complete' && excerpt.filename && <video controls className="mt-2 w-full rounded" aria-label="Animated proof with master audio" src={`/data/videos/${encodeURIComponent(excerpt.filename)}`} />}
diff --git a/client/src/components/musicVideo/stages/ReviewStage.jsx b/client/src/components/musicVideo/stages/ReviewStage.jsx
index 3f21861fae..a48e3bb38a 100644
--- a/client/src/components/musicVideo/stages/ReviewStage.jsx
+++ b/client/src/components/musicVideo/stages/ReviewStage.jsx
@@ -18,7 +18,7 @@ export default function ReviewStage({ board }) {
return (
<fieldset disabled={locked} className="min-w-0 space-y-3">
<RenderFailure project={project} renderJob={renderJob} />
- <DependencyImpactPanel project={project} busy={revisions.busy} onRepair={revisions.repair} />
+ <StageSection title="Dependency changes and repair"><DependencyImpactPanel project={project} busy={revisions.busy} onRepair={revisions.repair} /></StageSection>
<section id="mv-final-video" aria-label="Final render" className="rounded-lg border border-port-border bg-port-card p-3">
<div className="flex flex-wrap items-center justify-between gap-2">
<h3 className="text-sm font-medium">Final render</h3>
@@ -37,7 +37,10 @@ export default function ReviewStage({ board }) {
<ExcerptPanel
project={project}
rendering={excerpts.rendering}
+ occupied={excerpts.occupied}
progress={excerpts.progress}
+ activeRenderId={excerpts.activeRenderId}
+ connected={excerpts.connected}
excerpts={project.excerpts || []}
deletingId={excerpts.deletingId}
noteBusyId={excerpts.noteBusyId}
@@ -52,12 +55,14 @@ export default function ReviewStage({ board }) {
/>
</div>
+ <StageSection title="Development files" summary="Guides, storyboards and contact sheets">
<DevArtifactsPanel
project={project}
busy={devArtifacts.busy}
onOpen={board.openArtifact}
onUpload={board.onUploadArtifact}
/>
+ </StageSection>
<StageSection title="External handoff" summary="Export prompts, import files made in other tools">
<HandoffControls
diff --git a/client/src/hooks/README.md b/client/src/hooks/README.md
index 5a2d459eec..769ef47bec 100644
--- a/client/src/hooks/README.md
+++ b/client/src/hooks/README.md
@@ -42,7 +42,7 @@ grep -i "what you want to do" client/src/hooks/README.md
|---|---|---|
| `useQuotaUpdates` | Reconcile quota cards on scrape completion, reconnect and tab show; the caller owns the entry read. | Usage, Subscriptions and Quota Burn quota cards. |
| `useSseProgress` | Generic JSON-frame EventSource subscriber. | New SSE progress stream — start here, build on top. |
-| `useSseJobSlot` | Generic single-slot SSE job: captured target from preparation through completion, terminal-frame handling (`complete`/`error`/`canceled`), and `sse.closed`-without-terminal-frame recovery in one place. Returns `{ active, pending, jobId, percent, stage, context, start, attach, cancel }` (`attach(jobId, context)` adopts a job another request already started into the idle slot); reserves synchronously, exposes context during kickoff and ignores unmounted responses. Optional `readPercent` adapts other progress scales. Pass `startRequest`/`eventsUrl`/`cancelRequest` + per-feature toast copy. | Any "kick off a job → stream SSE → settle on terminal frame" hook. The reference-audio/YouTube/video-download/MIDI/music-video-render hooks all wrap this — don't re-roll the terminal-frame + lost-connection dance. |
+| `useSseJobSlot` | Generic single-slot SSE job: captured target from preparation through completion, terminal-frame handling (`complete`/`error`/`canceled`), and `sse.closed`-without-terminal-frame recovery in one place. Returns `{ active, pending, jobId, percent, stage, context, start, attach, cancel }` (`attach(jobId, context)` adopts a job another request already started into the idle slot); reserves synchronously, exposes context during kickoff and ignores unmounted responses. Optional `readPercent` adapts other progress scales; `connected` distinguishes a live stream from reconnecting, and `onSettled(reason, context)` refreshes persisted state after completion, failure, cancellation or a terminal disconnect. Pass `startRequest`/`eventsUrl`/`cancelRequest` + per-feature toast copy. | Any "kick off a job → stream SSE → settle on terminal frame" hook. The reference-audio/YouTube/video-download/MIDI/music-video-render hooks all wrap this — don't re-roll the terminal-frame + lost-connection dance. |
| `useInstallStream` | BYO-runtime install-log stream lifecycle: `stage`/`log`/`complete`/`error` frame dispatch, capped + optionally-debounced log accumulation, "connection lost" handling, ref-stashed `onComplete`, auto-scroll. `method: 'GET'` uses EventSource; `method: 'POST'` reads one fetch stream for a non-idempotent install. | A streamed install/setup modal that shows live SSE log lines (FLUX.2, video runtimes, OpenCode). Don't re-roll the teardown/onComplete-ref dance. |
| `useModelDownloadStatus` | Image/video model cache-status + SSE pre-download. `useDownloadableAssets(descriptors, options)` shares readiness and independent integrity dismissals across asset roles. `start(id)` commands a pull; `startWhenIdle(id)` requests one — it waits for the cache verdict, skips an already-resident repo, and queues behind whatever owns the single EventSource lane (`queuedModelId` while it waits, falsy id to retract). | Surfacing "Available" vs "Download" badge inline in the gen form; `startWhenIdle` for a picker where choosing an option IS the request for its weights. |
| `useAgyModels` | Live `agy models` probe (the AGENT models `--model` accepts) with `models`/`error`/`loading`/`refresh`; opt-in via an `enabled` flag so it never spawns for a disabled backend. | Any Agy model picker — the Settings default or the per-render override. Don't hardcode a model list: agy exits non-zero on an id outside this catalog. |
diff --git a/client/src/hooks/useMusicVideoExcerpts.js b/client/src/hooks/useMusicVideoExcerpts.js
index 45c80358ac..12f4e6e8ca 100644
--- a/client/src/hooks/useMusicVideoExcerpts.js
+++ b/client/src/hooks/useMusicVideoExcerpts.js
@@ -1,4 +1,4 @@
-import { useState } from 'react';
+import { useEffect, useRef, useState } from 'react';
import toast from '../components/ui/Toast';
import {
getMusicVideoProject,
@@ -31,6 +31,7 @@ const readPercent = (frame) => (Number.isFinite(frame.progress) ? frame.progress
*/
export default function useMusicVideoExcerpts({ project, replaceProject } = {}) {
const projectId = project?.id || null;
+ const seenJobs = useRef(new Set());
const [noteBusyId, setNoteBusyId] = useState(null);
const [deletingId, setDeletingId] = useState(null);
@@ -48,8 +49,9 @@ export default function useMusicVideoExcerpts({ project, replaceProject } = {})
eventsUrl: musicVideoExcerptRenderEventsUrl,
cancelRequest: cancelMusicVideoExcerptRender,
readPercent,
- onComplete: (_frame, id) => reload(id),
- onErrorFrame: (_frame, id) => { reload(id); return true; }, // reload already surfaces the persisted `error` field; skip the generic toast
+ onKickoffSuccess: id => seenJobs.current.add(id),
+ onSettled: (_reason, id) => reload(id),
+ onErrorFrame: () => true, // reload already surfaces the persisted `error` field; skip the generic toast
onKickoffError: (err) => {
if (err?.status === 409) { toast.error(err.message || 'An excerpt render is already in progress'); return true; }
return false;
@@ -61,13 +63,22 @@ export default function useMusicVideoExcerpts({ project, replaceProject } = {})
startErrorFallback: 'Failed to start the excerpt render',
});
+ useEffect(() => {
+ const excerpt = project?.excerpts?.find(e => e.status === 'rendering' && e.jobId);
+ if (excerpt && !seenJobs.current.has(excerpt.jobId) && job.attach(excerpt.jobId, projectId)) seenJobs.current.add(excerpt.jobId);
+ }, [project, projectId, job.active]);
+
// #9280: a social cut passes its own frame (`aspect`) and faded audio edges.
const startExcerpt = (startSec, endSec, { aspect = null, fade = false } = {}) => job.start({
startSec, endSec, ...(aspect ? { aspect } : {}), ...(fade ? { fade: true } : {}),
}, projectId);
// #8987: a selective revision's resume starts its draft re-render server-side;
// adopt that job so it shows the same progress and reloads on its finish.
- const attachRender = (jobId, id = projectId) => job.attach(jobId, id);
+ const attachRender = (jobId, id = projectId) => {
+ const attached = job.attach(jobId, id);
+ if (attached) seenJobs.current.add(jobId);
+ return attached;
+ };
// An excerpt's id IS its render job id, so any rendering excerpt — including
// one started before a reload, or by a revision — can be cancelled by id.
const cancelExcerpt = (excerptId) => cancelMusicVideoExcerptRender(excerptId, { silent: true })
@@ -106,8 +117,11 @@ export default function useMusicVideoExcerpts({ project, replaceProject } = {})
};
return {
- rendering: job.active,
- progress: job.active ? job.percent : 0,
+ occupied: job.active,
+ rendering: job.active && job.context === projectId,
+ activeRenderId: job.context === projectId ? job.jobId : null,
+ connected: job.connected,
+ progress: job.active && job.context === projectId ? job.percent : 0,
deletingId,
noteBusyId,
startExcerpt,
diff --git a/client/src/hooks/useMusicVideoExcerpts.test.jsx b/client/src/hooks/useMusicVideoExcerpts.test.jsx
new file mode 100644
index 0000000000..b910484426
--- /dev/null
+++ b/client/src/hooks/useMusicVideoExcerpts.test.jsx
@@ -0,0 +1,58 @@
+import { act, renderHook, waitFor } from '@testing-library/react';
+import { afterEach, beforeEach, expect, it, vi } from 'vitest';
+import { MockEventSource, lastEventSource } from '../test/mockEventSource.js';
+import useMusicVideoExcerpts from './useMusicVideoExcerpts.js';
+import { getMusicVideoProject, renderMusicVideoExcerpt } from '../services/apiMusicVideo.js';
+
+vi.mock('../services/apiMusicVideo.js', () => ({
+ getMusicVideoProject: vi.fn(), renderMusicVideoExcerpt: vi.fn(),
+ musicVideoExcerptRenderEventsUrl: id => `/events/${id}`,
+ cancelMusicVideoExcerptRender: vi.fn(), deleteMusicVideoExcerpt: vi.fn(),
+ addMusicVideoExcerptNote: vi.fn(), updateMusicVideoExcerptNote: vi.fn(), deleteMusicVideoExcerptNote: vi.fn(),
+}));
+vi.mock('../components/ui/Toast', () => ({ default: { error: vi.fn(), info: vi.fn(), success: vi.fn() } }));
+beforeEach(() => { vi.clearAllMocks(); MockEventSource.reset(); vi.stubGlobal('EventSource', MockEventSource); });
+afterEach(() => vi.unstubAllGlobals());
+
+it('retains the occupied slot when switching projects, then refreshes the render owner on failure', async () => {
+ const first = { id: 'first', excerpts: [] };
+ const second = { id: 'second', excerpts: [] };
+ const replaceProject = vi.fn();
+ getMusicVideoProject.mockResolvedValue(first);
+ renderMusicVideoExcerpt.mockResolvedValue({ jobId: 'draft-job' });
+ const { result, rerender } = renderHook(({ project }) => useMusicVideoExcerpts({ project, replaceProject }), { initialProps: { project: first } });
+ await act(async () => result.current.startExcerpt(0, 2));
+ rerender({ project: second });
+ expect(result.current).toMatchObject({ occupied: true, rendering: false, activeRenderId: null });
+ act(() => result.current.startExcerpt(0, 2));
+ expect(renderMusicVideoExcerpt).toHaveBeenCalledTimes(1);
+ await act(async () => lastEventSource().emit({ type: 'error', error: 'Synthetic interruption' }));
+ await waitFor(() => expect(replaceProject).toHaveBeenCalledWith(first));
+ expect(getMusicVideoProject).toHaveBeenCalledWith('first', { silent: true });
+ expect(result.current.occupied).toBe(false);
+});
+
+it('reattaches a persisted job after reopening and refreshes its completed record', async () => {
+ const project = { id: 'first', excerpts: [{ id: 'draft-job', jobId: 'draft-job', status: 'rendering' }] };
+ const finished = { ...project, excerpts: [{ id: 'draft-job', status: 'complete', filename: 'example.mp4' }] };
+ getMusicVideoProject.mockResolvedValue(finished);
+ const replaceProject = vi.fn();
+ const { result } = renderHook(() => useMusicVideoExcerpts({ project, replaceProject }));
+ expect(result.current).toMatchObject({ rendering: true, activeRenderId: 'draft-job', connected: false });
+ await act(async () => lastEventSource().emit({ type: 'complete' }));
+ await waitFor(() => expect(replaceProject).toHaveBeenCalledWith(finished));
+ expect(result.current.rendering).toBe(false);
+ expect(MockEventSource.instances).toHaveLength(1);
+});
+
+it('does not reattach its own settled job while the terminal refresh is still pending', async () => {
+ const project = { id: 'first', excerpts: [] };
+ renderMusicVideoExcerpt.mockResolvedValue({ jobId: 'draft-job' });
+ getMusicVideoProject.mockReturnValue(new Promise(() => {}));
+ const { result, rerender } = renderHook(({ project }) => useMusicVideoExcerpts({ project, replaceProject: vi.fn() }), { initialProps: { project } });
+ await act(async () => result.current.startExcerpt(0, 2));
+ rerender({ project: { ...project, excerpts: [{ id: 'draft-job', jobId: 'draft-job', status: 'rendering' }] } });
+ act(() => lastEventSource().emit({ type: 'complete' }));
+ expect(result.current.rendering).toBe(false);
+ expect(MockEventSource.instances).toHaveLength(1);
+});
diff --git a/client/src/hooks/useMusicVideoProductionReview.js b/client/src/hooks/useMusicVideoProductionReview.js
index d1785e559c..ee46ff9b44 100644
--- a/client/src/hooks/useMusicVideoProductionReview.js
+++ b/client/src/hooks/useMusicVideoProductionReview.js
@@ -30,7 +30,7 @@ export default function useMusicVideoProductionReview({ project, replaceProject
eventsUrl: musicVideoExcerptRenderEventsUrl, cancelRequest: cancelMusicVideoExcerptRender,
readPercent: frame => Number.isFinite(frame.progress) ? frame.progress * 100 : undefined,
onKickoffSuccess: (job, { id }) => { seenProofJobs.current.add(job); refresh(id).catch(err => setError(err.message)); },
- onComplete: (_frame, id) => { refresh(id).catch(err => setError(err.message)); },
+ onSettled: (_reason, id) => { refresh(id).catch(err => setError(err.message)); },
errorFallback: 'The proof render failed',
});
useEffect(() => {
@@ -49,7 +49,7 @@ export default function useMusicVideoProductionReview({ project, replaceProject
} catch (err) { if (latest.current === owner) setError(err.message); return null; }
finally { setBusy(false); }
};
- return { readiness: state?.owner === project ? state.readiness : null, busy, error, proof,
+ return { readiness: state?.owner === project ? state.readiness : null, busy, error, proof: { ...proof, occupied: proof.active, active: proof.active && proof.context === project?.id },
feedback: body => call(() => addMusicVideoProductionFeedback(project.id, { ...body, basis: state?.readiness.basis[body.stage] }, { silent: true })),
resolveFeedback: (feedbackId, resolution, password) => call(() => resolveMusicVideoProductionFeedback(project.id, { feedbackId, resolution, password }, { silent: true })),
importDocumentShots: body => call(() => importMusicVideoDocumentShots(project.id, body, { silent: true })),
diff --git a/client/src/hooks/useSseJobSlot.js b/client/src/hooks/useSseJobSlot.js
index 4c73e67e34..e5418a1819 100644
--- a/client/src/hooks/useSseJobSlot.js
+++ b/client/src/hooks/useSseJobSlot.js
@@ -13,6 +13,7 @@ const defaultReadPercent = (frame) => frame.percent;
* Options:
* - `startRequest(startArg)` → resolves `{ jobId }` — the feature's kickoff call.
* - `eventsUrl(jobId)` / `cancelRequest(jobId, { silent })` — SSE URL + cancel call.
+ * - `onSettled(reason, context)` — refresh saved state on success, failure, cancellation or disconnect.
* - `onComplete(frame, context)` — fires on the terminal `complete` frame.
* - `context` (the second `start` arg, or the start arg itself when omitted) is
* captured and exposed immediately at kickoff, including while `pending`.
@@ -46,6 +47,7 @@ export default function useSseJobSlot({
onErrorFrame,
onKickoffError,
onKickoffSuccess,
+ onSettled,
} = {}) {
// jobId is null during preparation; context already owns the target then.
const [job, setJob] = useState(null);
@@ -78,6 +80,7 @@ export default function useSseJobSlot({
useEffect(() => {
if (!job?.jobId || !latest) return;
if (sse.latestUrl && sse.latestUrl !== jobUrl) return;
+ if (['complete', 'error', 'canceled', 'cancelled'].includes(latest.type)) onSettled?.(latest.type, job.context);
if (latest.type === 'complete') {
clearJob();
onComplete?.(latest, job.context);
@@ -97,7 +100,9 @@ export default function useSseJobSlot({
useEffect(() => {
if (job?.jobId && sse.closed && !isTerminalSseFrame(latest)) {
if (sse.latestUrl && sse.latestUrl !== jobUrl) return;
+ const context = job.context;
clearJob();
+ onSettled?.('disconnected', context);
toast.info(lostConnectionMessage);
}
}, [sse.closed]);
@@ -141,6 +146,7 @@ export default function useSseJobSlot({
return {
active: !!job,
+ connected: sse.isOpen,
pending: !!job && !job.jobId,
jobId: job?.jobId ?? null,
percent: progress.percent,
diff --git a/client/src/hooks/useSseJobSlot.test.jsx b/client/src/hooks/useSseJobSlot.test.jsx
index 53080d907b..8fa18789bc 100644
--- a/client/src/hooks/useSseJobSlot.test.jsx
+++ b/client/src/hooks/useSseJobSlot.test.jsx
@@ -81,3 +81,18 @@ describe('unmounted kickoff ownership', () => {
expect(MockEventSource.instances).toHaveLength(0);
});
});
+
+
+it.each(['complete', 'error', 'canceled', 'disconnected'])('settles %s once against the captured project for a persisted-state refresh', async (reason) => {
+ const onSettled = vi.fn();
+ const { result } = renderHook(() => useSseJobSlot({ eventsUrl: id => `/events/${id}`, onSettled }));
+ act(() => result.current.attach('synthetic-render', 'synthetic-project'));
+ act(() => { lastEventSource().onopen(); });
+ expect(result.current.connected).toBe(true);
+ act(() => {
+ if (reason === 'disconnected') lastEventSource().fail();
+ else lastEventSource().emit({ type: reason });
+ });
+ expect(result.current.active).toBe(false);
+ expect(onSettled).toHaveBeenCalledExactlyOnceWith(reason, 'synthetic-project');
+});
diff --git a/client/src/hooks/useSseProgress.js b/client/src/hooks/useSseProgress.js
index b6678ee02b..d78e9033f4 100644
--- a/client/src/hooks/useSseProgress.js
+++ b/client/src/hooks/useSseProgress.js
@@ -73,12 +73,12 @@ export function useSseProgress(url, { enabled = true } = {}) {
}
};
es.onerror = () => {
+ setIsOpen(false);
// EventSource fails (no auto-retry) on a non-2xx / non-event-stream
// response — readyState CLOSED. Surface that as a terminal close so the
// consumer stops waiting; transient errors (readyState CONNECTING) are
// left alone so the browser's own retry can recover.
if (es.readyState === EventSource.CLOSED) {
- setIsOpen(false);
setClosed(true);
}
};
diff --git a/client/src/hooks/useSseProgress.test.jsx b/client/src/hooks/useSseProgress.test.jsx
index 73de006661..d83e084c21 100644
--- a/client/src/hooks/useSseProgress.test.jsx
+++ b/client/src/hooks/useSseProgress.test.jsx
@@ -87,3 +87,15 @@ describe('useSseProgress', () => {
expect(isTerminalSseFrame(null)).toBe(false);
});
});
+
+it('reports a transient outage and recovers without ending the job stream', () => {
+ const { result } = renderHook(() => useSseProgress('/reconnect'));
+ act(() => last().onopen());
+ expect(result.current.isOpen).toBe(true);
+ act(() => last().fail(MockEventSource.CONNECTING));
+ expect(result.current.isOpen).toBe(false);
+ expect(result.current.closed).toBe(false);
+ expect(last().closed).toBe(false);
+ act(() => last().onopen());
+ expect(result.current.isOpen).toBe(true);
+});
diff --git a/client/src/lib/README.md b/client/src/lib/README.md
index d07c3891d5..3f869e7330 100644
--- a/client/src/lib/README.md
+++ b/client/src/lib/README.md
@@ -64,7 +64,7 @@ grep -i "what you want to do" client/src/lib/README.md
| `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`, `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`. |
-| `musicVideoStages.js` | Music Video page stage model: `MUSIC_VIDEO_STAGES` (setup → cast-sets → board → produce → compose → review), `resolveStageParam(value)` for the `:stage` route param, `deriveStages(project)` (per-stage `done`/`active`/`blocked`/`todo` + `current`, the first incomplete stage; a live production run pins Produce), `deriveNextAction(project, ctx)` (the one primary action the sticky header offers — approve Cast & Sets, stop/resume production, render final, …), `projectSpend(project)` (paid generation used vs. cap) and `currentProductionRun`. Used by `components/musicVideo/MusicVideoLayout.jsx` and `pages/MusicVideo.jsx`. |
+| `musicVideoStages.js` | Music Video page stage model: `MUSIC_VIDEO_STAGES` (setup → cast-sets → board → produce → compose → review), `resolveStageParam(value)` for the `:stage` route param, `deriveStages(project)` (per-stage `done`/`active`/`blocked`/`todo` + `current`, the first incomplete stage; a live production run pins Produce), `deriveNextAction(project, ctx)` (the one primary action the sticky header offers — approve Cast & Sets, stop/resume production, render final, …), `projectSpend(project)` (paid generation used vs. cap), `projectShotSummary(project)` (document shots or scene counts), and `currentProductionRun`. Used by `components/musicVideo/MusicVideoLayout.jsx` and `pages/MusicVideo.jsx`. |
| `musicVideoPreview.js` | Pick the representative produced asset for a Music Video project card (`selectMusicVideoPreview`: final video → latest excerpt → latest rendered scene clip → latest scene reference frame → visual spec reference) for the main project grid. Pure, computed off the project record, with image path and fallback helpers (`musicVideoImageSrc`, `musicVideoImageFallback`). |
| `musicVideoUniverseRefs.js` | `pullUniverseCanonReferences(universe, existingReferences)` (#8978) maps a linked universe's characters/places/objects to visual-spec references (character/set/prop roles), skipping images already present and capping at `MUSIC_VIDEO_MAX_REFERENCES` (24, mirrors the server schema). Returns `{ next, added, skipped }`; the caller persists `next` via the ordinary visualSpec PATCH. Used by `components/musicVideo/VisualSpecPanel.jsx`. (The style snapshots are derived server-side, #9105.) |
| `musicVideoAutonomous.js` | Fully-autonomous Music Video, client half: re-exports the server stage vocabulary (`AUTONOMOUS_STAGES`, checkpoint ids, default tools/limits, `autonomousMedium`), the status/checkpoint labels, and owns the start form's `emptyAutonomousDraft` / `autonomousRequestFromDraft` mapping (including the Suno form options and `isSunoModelValid`) plus `autonomousStageRows(run)` and `isAutonomousLive(run)` for the run panel, and `autopilotDraftFromParams` / `autopilotParamsFromDraft` for the music-video-autopilot Schedule settings form. |
diff --git a/client/src/lib/musicVideoStages.js b/client/src/lib/musicVideoStages.js
index a2cf186777..86a0d140fb 100644
--- a/client/src/lib/musicVideoStages.js
+++ b/client/src/lib/musicVideoStages.js
@@ -6,7 +6,7 @@
*/
import { isLayeredComposition, sceneRenderReady } from './musicVideoLayers.js';
import { AUTONOMOUS_STATUS_LABELS } from './musicVideoAutonomous.js';
-import { formatTimecode } from '../utils/formatters.js';
+import { formatCount, formatTimecode } from '../utils/formatters.js';
export const MUSIC_VIDEO_STAGES = [
{ id: 'setup', label: 'Setup', title: 'Setup' },
@@ -33,6 +33,13 @@ export const currentProductionRun = (project) => {
return runs.find((r) => RESUMABLE_RUN_STATUSES.has(r.status)) || runs[runs.length - 1] || null;
};
+export function projectShotSummary(project) {
+ const draft = project?.productionReview?.draft;
+ const document = project?.composition?.mode === 'document' && draft?.storyboardSource === 'document';
+ const count = (document ? draft.storyboard : project?.scenes)?.length || 0;
+ return `${formatCount(count)} ${document ? 'document shot' : 'scene'}${count === 1 ? '' : 's'}`;
+}
+
export const projectHasAudio = (project) => !!(project?.trackId || project?.uploadedAudioFilename);
/**
@@ -72,7 +79,7 @@ export function listPreviewSources(project, { finalVideoSrc = null } = {}) {
sources.push({
id: `excerpt:${excerpt.id}`, kind: 'video', src: `/data/videos/${excerpt.filename}`,
startSec: excerpt.startSec, endSec: excerpt.endSec,
- label: `Draft ${formatTimecode(excerpt.startSec)}–${formatTimecode(excerpt.endSec)}`,
+ label: `${excerpt.dependencyState?.status === 'stale' ? 'Older draft' : 'Draft'} ${formatTimecode(excerpt.startSec)}–${formatTimecode(excerpt.endSec)} · ${excerpt.id.slice(-6)}`,
});
}
return sources;
@@ -109,12 +116,13 @@ export function describeProjectStatus(project, { progress, nextAction = null, re
const allDone = progress.stages.every((stage) => stage.state === 'done');
// A goto into Production review is a human approval, not something the app does by itself.
const needsYou = entry?.state === 'blocked' || nextAction?.id === 'review-production' || nextAction?.id === 'approve-cast-sets';
- const headline = allDone
+ const activeEvidence = ['draft-progress', 'proof-progress'].includes(nextAction?.id);
+ const headline = activeEvidence ? 'Review render in progress' : allDone
? 'Published'
: `Stage ${index + 1} of ${MUSIC_VIDEO_STAGES.length}: ${entry?.label || ''}${needsYou ? ' · needs you' : ''}`;
const facts = [];
const auto = project.autonomousRun;
- if (auto) {
+ if (auto && nextAction?.id !== 'review-production' && !activeEvidence) {
const label = auto.interrupted ? 'interrupted' : (AUTONOMOUS_STATUS_LABELS[auto.status] || auto.status).toLowerCase();
const tone = auto.status === 'completed' ? 'ok' : auto.status === 'running' && !auto.interrupted ? 'muted' : 'warn';
facts.push({ id: 'autopilot', label: `Autopilot ${label}`, tone });
@@ -129,7 +137,7 @@ export function describeProjectStatus(project, { progress, nextAction = null, re
if (project.renderHistoryId) facts.push({ id: 'render', label: 'Final render ready', tone: 'ok' });
else if (drafts) facts.push({ id: 'render', label: `${drafts} draft ${drafts === 1 ? 'excerpt' : 'excerpts'}, no final render`, tone: 'muted' });
else facts.push({ id: 'render', label: 'Nothing rendered yet', tone: 'muted' });
- return { headline, tone: allDone ? 'ok' : needsYou ? 'warn' : 'muted', facts };
+ return { headline, tone: activeEvidence ? 'muted' : allDone ? 'ok' : needsYou ? 'warn' : 'muted', facts };
}
/** Resolve the `:stage` route param; an unknown or missing value is null. */
@@ -196,7 +204,7 @@ export function deriveStages(project, readiness = project?.productionReadiness)
* over the stage: they own the project until they settle.
*/
export function deriveNextAction(project, {
- renderActive = false, renderProgress = 0, renderPending = false, renderBlockedByOther = false,
+ draftActive = false, proofActive = false, renderActive = false, renderProgress = 0, renderPending = false, renderBlockedByOther = false,
kickoffRunning = false, kickoffStep = '', kickoffBlockedReason = null,
planning = false, analyzing = false, readiness = project?.productionReadiness,
} = {}) {
@@ -206,9 +214,11 @@ export function deriveNextAction(project, {
const cast = project.castAndSets || null;
const scenes = project.scenes || [];
+ if (proofActive) return { id: 'proof-progress', kind: 'goto', stage: 'review', anchor: 'mv-review-render', label: 'View review render' };
+ if (draftActive) return { id: 'draft-progress', kind: 'goto', stage: 'review', anchor: 'mv-draft-excerpts', label: 'View draft render' };
if (projectHasAudio(project) && project.audioAnalysis && !CAST_WORKING.has(cast?.status) && !readiness?.readyForProduction && run?.status !== 'running' && !renderActive && !kickoffRunning) {
return { id: 'review-production', kind: 'goto', stage: !readiness?.art.approved ? 'cast-sets' : !readiness?.storyboard.approved ? 'board' : 'review',
- anchor: 'mv-production-review', label: !readiness?.art.approved ? 'Review art direction' : !readiness?.storyboard.approved ? 'Review timed storyboard' : 'Review animated proof' };
+ anchor: !readiness?.art.approved ? 'mv-review-art' : !readiness?.storyboard.approved ? 'mv-review-storyboard' : 'mv-review-proof', label: !readiness?.art.approved ? 'Review art direction' : !readiness?.storyboard.approved ? 'Review timed storyboard' : 'Review animated proof' };
}
if (run && RESUMABLE_RUN_STATUSES.has(run.status)) {
if (run.status === 'running' && !run.interrupted) return { id: 'stop-production', kind: 'run', label: 'Stop production', runId: run.id };
diff --git a/client/src/lib/musicVideoStages.test.js b/client/src/lib/musicVideoStages.test.js
index 86708f1dfa..69b46f3fa1 100644
--- a/client/src/lib/musicVideoStages.test.js
+++ b/client/src/lib/musicVideoStages.test.js
@@ -159,7 +159,7 @@ describe('describeProjectStatus', () => {
expect(status.headline).toBe('Stage 2 of 7: Cast & Sets · needs you');
expect(status.tone).toBe('warn');
expect(status.facts.map((fact) => fact.label)).toEqual([
- 'Autopilot paused', 'Approvals: 0 of 3 approved · needs art, storyboard, proof', 'Nothing rendered yet',
+ 'Approvals: 0 of 3 approved · needs art, storyboard, proof', 'Nothing rendered yet',
]);
});
@@ -184,3 +184,11 @@ describe('describeProjectStatus', () => {
expect(done.facts.map((fact) => fact.label)).toEqual(['Approvals: All 3 approved', 'Final render ready']);
});
});
+
+it('links active draft and proof jobs to their own evidence controls before offering approval', () => {
+ const project = { id: 'example', trackId: 'song', audioAnalysis: {}, scenes: [] };
+ expect(deriveNextAction(project, { draftActive: true })).toMatchObject({ id: 'draft-progress', anchor: 'mv-draft-excerpts' });
+ expect(deriveNextAction(project, { proofActive: true })).toMatchObject({ id: 'proof-progress', anchor: 'mv-review-render' });
+ const nextAction = deriveNextAction(project, { draftActive: true });
+ expect(describeProjectStatus(project, { progress: deriveStages(project), nextAction })).toMatchObject({ headline: 'Review render in progress', tone: 'muted' });
+});
diff --git a/client/src/pages/MusicVideo.jsx b/client/src/pages/MusicVideo.jsx
index a4035cba85..1d79484d2d 100644
--- a/client/src/pages/MusicVideo.jsx
+++ b/client/src/pages/MusicVideo.jsx
@@ -1,7 +1,7 @@
import ProductionReviewPanel from '../components/musicVideo/ProductionReviewPanel.jsx';
import useMusicVideoProductionReview from '../hooks/useMusicVideoProductionReview.js';
import { useEffect, useState, useCallback, useMemo, useRef } from 'react';
-import { useParams, useNavigate, useSearchParams } from 'react-router';
+import { useParams, useNavigate, useSearchParams, useLocation } from 'react-router';
import { Plus, Film, Copy, Trash2, Wand2 } from 'lucide-react';
import toast from '../components/ui/Toast';
import ConfirmButtonPair from '../components/ui/ConfirmButtonPair';
@@ -79,7 +79,7 @@ import { isLtx2FamilyRuntime } from '../lib/runnerFamilies';
import { videoPosterForJob } from '../lib/creativeDirectorPreview.js';
import { sceneTakeList } from '../lib/musicVideoTakes.js';
import {
- approvalSummary, deriveNextAction, deriveStages, describeProjectStatus, listPreviewSources, projectSpend, resolveStageParam,
+ approvalSummary, deriveNextAction, deriveStages, projectShotSummary, describeProjectStatus, listPreviewSources, projectSpend, resolveStageParam,
} from '../lib/musicVideoStages.js';
import { AUTONOMOUS_STATUS_LABELS, AUTONOMOUS_VIEWABLE_STAGES } from '../lib/musicVideoAutonomous.js';
@@ -101,9 +101,7 @@ const STAGE_VIEWS = {
setup: SetupStage, 'cast-sets': CastSetsStage, board: BoardStage, produce: ProduceStage, compose: ComposeStage, review: ReviewStage, publish: PublishStage,
};
-// The shared autopilot section stays unfolded only while the run is working or
-// waiting on the director; a paused, finished or cancelled run folds to its summary line.
-const AUTOPILOT_OPEN_STATUSES = new Set(['running', 'awaiting-approval', 'needs-human', 'failed']);
+// Keep active work open; historical runs remain available behind their summary.
const autopilotSummary = (run) => {
const label = run.interrupted ? 'Interrupted — resume to continue' : AUTONOMOUS_STATUS_LABELS[run.status] || run.status;
return run.error ? `${label} — ${run.error}` : label;
@@ -774,23 +772,22 @@ export default function MusicVideo() {
// ---- stage plumbing -------------------------------------------------------
// A header action that lands on a control (Attach a track, Set up production)
// scrolls to and focuses it once its stage has rendered.
- const [pendingAnchor, setPendingAnchor] = useState(null);
+ const location = useLocation();
useEffect(() => {
- if (!pendingAnchor || pendingAnchor.stage !== activeStage) return;
- const el = document.getElementById(pendingAnchor.id);
+ const anchor = location.hash.slice(1);
+ if (!anchor || !selected) return;
+ const el = document.getElementById(anchor);
+ if (!el) return;
// An anchor inside a folded section (Production review) unfolds it first.
- const fold = el?.closest?.('details');
- if (fold) fold.open = true;
- el?.scrollIntoView?.({ block: 'center', behavior: 'smooth' });
- const focusable = el?.matches?.('button, input, select, textarea, a') ? el : el?.querySelector?.('button, input, select, textarea, a');
+ for (let fold = el.closest('details'); fold; fold = fold.parentElement?.closest('details')) fold.open = true;
+ el.scrollIntoView?.({ block: 'start', behavior: 'instant' });
+ const focusable = el.matches('[tabindex], button, input, select, textarea, a') ? el : el.querySelector('button:not(:disabled), input:not(:disabled), select:not(:disabled), textarea:not(:disabled), a');
focusable?.focus?.({ preventScroll: true });
- setPendingAnchor(null);
- }, [pendingAnchor, activeStage]);
+ }, [activeStage, location.key, selectedId, !!selected]);
const goToStage = (stage, anchor = null) => {
- setPendingAnchor(anchor ? { stage, id: anchor } : null);
// The dock's picked source (`?play=`) follows the director across tabs.
const play = searchParams.get('play');
- navigate(`/music-video/${encodeURIComponent(selected.id)}/${stage}${play ? `?play=${encodeURIComponent(play)}` : ''}`);
+ navigate(`/music-video/${encodeURIComponent(selected.id)}/${stage}${play ? `?play=${encodeURIComponent(play)}` : ''}${anchor ? `#${anchor}` : ''}`, { replace: activeStage === stage });
};
// The docked preview: scene cards seek it; on a phone it is a mini-player
@@ -808,6 +805,8 @@ export default function MusicVideo() {
const nextAction = selected ? deriveNextAction(selected, {
readiness: productionReview.readiness,
renderActive: renderTargetsSelected,
+ draftActive: excerpts.rendering,
+ proofActive: productionReview.proof.active,
renderProgress: renderJob.progress,
renderPending: renderJob.pending,
renderBlockedByOther: !!renderJob.active && !renderTargetsSelected,
@@ -987,7 +986,7 @@ export default function MusicVideo() {
<option value="">{loading ? 'Loading projects…' : 'Select a project…'}</option>
{projects.map((project) => (
<option key={project.id} value={project.id}>
- {project.name} · {project.scenes?.length || 0} scenes · {project.status}
+ {project.name} · {projectShotSummary(project)} · {project.status}
</option>
))}
</select>
@@ -1171,7 +1170,7 @@ export default function MusicVideo() {
key={`autonomous-${selected.id}`}
title="Autopilot run"
summary={autopilotSummary(autopilotRun)}
- defaultOpen={!!runStage || autopilotRun.interrupted || AUTOPILOT_OPEN_STATUSES.has(autopilotRun.status)}
+ defaultOpen={!!runStage || (autopilotRun.status === 'running' && !autopilotRun.interrupted)}
>
<AutonomousRunPanel project={selected} auto={autonomous} selectedStage={runStage} onSelectStage={setRunStage} framed={false} />
</StageSection>
diff --git a/client/src/pages/MusicVideo.test.jsx b/client/src/pages/MusicVideo.test.jsx
index 9b52aa8fb1..c678e9e188 100644
--- a/client/src/pages/MusicVideo.test.jsx
+++ b/client/src/pages/MusicVideo.test.jsx
@@ -37,8 +37,8 @@ const { sseState, ytSseStates, getYtSseState } = vi.hoisted(() => {
// This page suite exercises existing controls with production approvals already granted.
// ProductionReviewPanel and route integration suites exercise the real approval refusals.
-vi.mock('../hooks/useMusicVideoProductionReview.js', () => ({ default: () => ({
- readiness: { readyForProduction: true, basis: {}, art: { approved: true, problems: [] }, storyboard: { approved: true, problems: [] }, proof: { approved: true, problems: [] } },
+vi.mock('../hooks/useMusicVideoProductionReview.js', () => ({ default: ({ project }) => ({
+ readiness: project?.productionReadiness || { readyForProduction: true, basis: {}, art: { approved: true, problems: [] }, storyboard: { approved: true, problems: [] }, proof: { approved: true, problems: [] } },
busy: false, error: null, proof: { active: false }, save: vi.fn(), prepare: vi.fn(), approve: vi.fn(), renderProof: vi.fn(),
}) }));
@@ -329,7 +329,7 @@ const openCreateForm = async () => {
// Back / ⌘K jump, which bypass the in-app selectProject guard).
function LocationProbe() {
const loc = useLocation();
- return <div data-testid="loc">{loc.pathname}</div>;
+ return <div data-testid="loc">{loc.pathname}{loc.hash}</div>;
}
function NavTo({ to }) {
const navigate = useNavigate();
@@ -350,6 +350,7 @@ beforeEach(() => {
getMusicVideoProject.mockImplementation(async id => (await listMusicVideoProjects()).find(project => project.id === id));
sseState.latest = null;
sseState.closed = false;
+ sseState.isOpen = true;
ytSseStates.clear();
});
@@ -556,7 +557,7 @@ describe('MusicVideo draft excerpt render (#8986)', () => {
// the component until something else does — force one (mirrors the
// existing render-job tests' use of this same mock).
fireEvent.click(screen.getByRole('button', { name: /New project/i }));
- await screen.findByText(/Rendering excerpt — 50%/);
+ await screen.findByText(/Rendering draft — 50%/);
});
it('reloads the project on a completed excerpt render and shows the player + contact sheet + notes', async () => {
@@ -682,7 +683,7 @@ describe('MusicVideo selective section revision (#8987)', () => {
fireEvent.click(await findEnabledByRole('button', { name: /Render revised draft/i }));
await waitFor(() => expect(resumeMusicVideoRevision).toHaveBeenCalledWith('mv-1', 'mvr-1', { silent: true }));
- await screen.findByText(/Rendering excerpt/);
+ await screen.findByText(/Rendering draft/);
expect(generateVideo).not.toHaveBeenCalled();
expect(generateImage).not.toHaveBeenCalled();
});
@@ -2483,3 +2484,31 @@ describe('MusicVideo main page project cards', () => {
expect(deleteMusicVideoProject).toHaveBeenCalledWith(PROJECT_WITH_CLIP.id, { silent: true });
});
});
+
+
+describe('direct production review navigation', () => {
+ it('focuses the exact step on repeated clicks and restores its deep link with Back/Forward without approval', async () => {
+ const project = { ...PROJECT_ANALYZED, scenes: [], composition: { mode: 'document' },
+ productionReview: { draft: { storyboardSource: 'document', storyboard: [{ id: 'shot-1' }, { id: 'shot-2' }] } },
+ productionReadiness: { readyForProduction: false, basis: {}, art: { approved: false, problems: [] },
+ storyboard: { approved: false, problems: ['Approve art first'] }, proof: { approved: false, problems: ['Approve storyboard first'] } } };
+ listMusicVideoProjects.mockResolvedValue([project]);
+ render(<MemoryRouter initialEntries={['/music-video/mv-3/review']}><LocationProbe /><NavTo to={-1} /><NavTo to={1} />{MV_ROUTES}</MemoryRouter>);
+ const action = await screen.findByRole('button', { name: 'Review art direction' });
+ expect(screen.getByLabelText('Project')).toHaveTextContent('2 document shots');
+ fireEvent.click(action);
+ const art = document.getElementById('mv-review-art');
+ await waitFor(() => expect(art).toHaveFocus());
+ expect(art.closest('details').open).toBe(true);
+ expect(screen.getByTestId('loc')).toHaveTextContent('/cast-sets#mv-review-art');
+ fireEvent.click(screen.getByRole('button', { name: 'Review art direction' }));
+ expect(art).toHaveFocus();
+ expect(screen.getByRole('button', { name: 'Approve art direction' })).toBeDisabled();
+ fireEvent.click(screen.getByRole('button', { name: 'Enter your password to enable approval' }));
+ expect(screen.getByLabelText('Instance password for this approval')).toHaveFocus();
+ fireEvent.click(screen.getByRole('button', { name: 'go--1' }));
+ expect(screen.getByTestId('loc')).toHaveTextContent('/review');
+ fireEvent.click(screen.getByRole('button', { name: 'go-1' }));
+ await waitFor(() => expect(art).toHaveFocus());
+ });
+});
diff --git a/server/services/htmlComposition/encode.js b/server/services/htmlComposition/encode.js
index 0e1407c56e..639e6e2274 100644
--- a/server/services/htmlComposition/encode.js
+++ b/server/services/htmlComposition/encode.js
@@ -71,13 +71,16 @@ export async function encodeComposition(page, contract, outputPath, { musicPath,
let exited = false;
let stopping = false;
let stopReason = null;
+ let exitDetail = '';
+ let inputError = null;
proc.stderr.on('data', chunk => { stderr = (stderr + chunk.toString()).slice(-2000); });
const finished = new Promise((resolve, reject) => {
proc.on('error', reject);
- proc.stdin.on('error', reject);
+ proc.stdin.on('error', error => { inputError = error; reject(error); });
proc.once('close', (code, exitSignal) => {
exited = true;
const origin = stopReason ? `; encoder ${stopReason}` : exitSignal ? '; external signal (no encoder stop requested)' : '';
+ exitDetail = `ffmpeg exited with ${code ?? exitSignal ?? 'unknown status'}${origin}${stderr ? `: ${stderr}` : ''}`;
code === 0 ? resolve() : reject(new Error(`ffmpeg failed (${code ?? exitSignal ?? 'unknown'}${origin}): ${stderr}`));
});
});
@@ -149,6 +152,15 @@ export async function encodeComposition(page, contract, outputPath, { musicPath,
await finished;
page.check();
return shutter ? { sampleHistogram: histogram } : {};
+ } catch (error) {
+ if (error.code === 'EPIPE' || inputError?.code === 'EPIPE') {
+ // A closed pipe often arrives before the process's close event. Preserve
+ // that event's signal and stderr instead of persisting just 'write EPIPE'.
+ stop('input pipe closed');
+ if (!exited) await new Promise(resolve => proc.once('close', resolve));
+ throw new Error(`Render interrupted: encoder stopped accepting frames (EPIPE); ${exitDetail}. A server restart or encoder exit can interrupt a draft. Existing completed drafts are retained.`);
+ }
+ throw error;
} finally {
signal?.removeEventListener('abort', abort);
stop('cleanup requested');
diff --git a/server/services/htmlComposition/encode.musicVideo.test.js b/server/services/htmlComposition/encode.musicVideo.test.js
index de3902132c..efaa01b892 100644
--- a/server/services/htmlComposition/encode.musicVideo.test.js
+++ b/server/services/htmlComposition/encode.musicVideo.test.js
@@ -145,3 +145,18 @@ describe('encodeComposition process termination diagnostics', () => {
})).rejects.toThrow(`ffmpeg failed (${message}): synthetic diagnostic`);
});
});
+
+
+it('preserves the exit signal and stderr when EPIPE arrives before the encoder closes', async () => {
+ const spawnProcess = () => {
+ const proc = new EventEmitter(); proc.stderr = new EventEmitter(); proc.stdin = new EventEmitter();
+ proc.stdin.write = (_bytes, callback) => {
+ const error = Object.assign(new Error('write EPIPE'), { code: 'EPIPE' });
+ callback(error); proc.stdin.emit('error', error);
+ setImmediate(() => { proc.stderr.emit('data', 'synthetic encoder stopped'); proc.emit('close', null, 'SIGTERM'); });
+ };
+ return proc;
+ };
+ await expect(encodeComposition(page, contract(0.25), '/tmp/interrupted.mp4', { spawnProcess }))
+ .rejects.toThrow(/Render interrupted:.*EPIPE.*SIGTERM.*synthetic encoder stopped/);
+});
diff --git a/server/services/musicVideo/excerptRender.js b/server/services/musicVideo/excerptRender.js
index aba4e6ea0d..8a1082e016 100644
--- a/server/services/musicVideo/excerptRender.js
+++ b/server/services/musicVideo/excerptRender.js
@@ -217,8 +217,8 @@ async function launchSeekedExcerpt({ projectId, project: stored, startSec, endSe
const log = canceled ? console.log : console.error;
log(`${canceled ? '🛑' : '❌'} Music-video ${renderer.label} excerpt ${canceled ? 'cancelled' : 'failed'} [${jobId.slice(4, 12)}]: ${reason}`);
await unlink(outputPath).catch(() => {});
- broadcastSse(job, { type: canceled ? 'canceled' : 'error', error: reason });
await finalize({ status: canceled ? 'canceled' : 'error', error: canceled ? null : reason, filename: null, jobId: null });
+ broadcastSse(job, { type: canceled ? 'canceled' : 'error', error: reason });
});
return { jobId, excerptId };
}
@@ -318,9 +318,8 @@ export async function startExcerptRender(projectId, { startSec, endSec, aspect =
// gates its 'complete' broadcast on it, so a director is never told an
// excerpt is ready when the record never actually recorded it (the project
// would otherwise stay stuck 'rendering' while the client believes it's
- // done). The error/cancel paths already broadcast their OWN terminal type
- // before calling this, so their write failing only delays the record
- // catching up (boot recovery clears a truly stuck one).
+ // done). Error/cancel paths attempt persistence before notifying clients
+ // to refresh; boot recovery clears a record if that write also fails.
const finalize = async (patch) => {
projectExcerptRenders.delete(projectId);
const persisted = await mutateProjectRecord(projectId, (current) => ({
@@ -432,8 +431,8 @@ export async function startExcerptRender(projectId, { startSec, endSec, aspect =
job.status = 'error';
job.lastError = `Finalize failed: ${err.message}`;
console.error(`❌ Music-video excerpt render finalize failed [${jobId.slice(4, 12)}]: ${err.message}`);
- broadcastSse(job, { type: 'error', error: 'Excerpt render finalize failed' });
await finalize({ status: 'error', error: 'Finalize failed', filename: null, jobId: null });
+ broadcastSse(job, { type: 'error', error: 'Excerpt render finalize failed' });
}
},
});
diff --git a/server/services/musicVideo/render.document.test.js b/server/services/musicVideo/render.document.test.js
index 2a88bb4498..16a2b35fda 100644
--- a/server/services/musicVideo/render.document.test.js
+++ b/server/services/musicVideo/render.document.test.js
@@ -15,6 +15,10 @@ import { cleanupTempDataRoots, lazyTempDataRoot, makePathsProxy } from '../../li
vi.mock('../../lib/paths.js', async (importOriginal) => makePathsProxy(await importOriginal(), {
dataRoot: () => lazyTempDataRoot('portos-mv-document-plan-'),
}));
+vi.mock('../../lib/sseUtils.js', async load => ({ ...await load(), broadcastSse: vi.fn((...args) => broadcastOriginal(...args)) }));
+const { broadcastSse: broadcastOriginal } = await vi.importActual('../../lib/sseUtils.js');
+const { broadcastSse } = await import('../../lib/sseUtils.js');
+
vi.mock('../../lib/ffmpeg.js', async (importOriginal) => ({ ...(await importOriginal()), generateThumbnail: vi.fn(async () => 'thumb.jpg') }));
vi.mock('../instanceIdentity.js', () => ({ ensureInstanceId: vi.fn(async () => 'instance-test') }));
vi.mock('../videoGen/local.js', () => ({ loadHistory: vi.fn(async () => []), mutateVideoHistory: vi.fn(async () => {}) }));
@@ -156,3 +160,25 @@ it('persists a document failure for returning operators and clears it after a su
await renderMusicVideo(id);
await vi.waitFor(async () => expect(await projects.getProject(id)).toMatchObject({ status: 'complete', renderError: null }));
});
+
+it.each(['error', 'canceled'])('persists document excerpt %s before notifying subscribers to refresh', async (status) => {
+ const id = await documentProject();
+ await importDocumentTemplate(id);
+ let rejectEncode;
+ encodeDocumentComposition.mockImplementationOnce(() => new Promise((resolve, reject) => { rejectEncode = reject; }));
+ const { excerptId } = await startExcerptRender(id, { startSec: 0, endSec: 2 });
+ await vi.waitFor(() => expect(rejectEncode).toBeTypeOf('function'));
+ const snapshots = [];
+ broadcastSse.mockImplementation((job, frame) => {
+ if (frame.type === status) snapshots.push(projects.getProject(id));
+ return broadcastOriginal(job, frame);
+ });
+ try {
+ rejectEncode(Object.assign(new Error('Synthetic encoder interruption'), status === 'canceled' ? { code: 'CANCELED' } : {}));
+ await vi.waitFor(() => expect(snapshots).toHaveLength(1));
+ const snapshot = await snapshots[0];
+ expect(snapshot.excerpts.find(e => e.id === excerptId)).toMatchObject({ status, jobId: null });
+ } finally {
+ broadcastSse.mockImplementation(broadcastOriginal);
+ }
+});