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: preserve render ownership with the shared SSE job slot

[._.]/ Adam Eivy822733d80ab2
diff --git a/client/src/components/musicVideo/ProjectToolbar.jsx b/client/src/components/musicVideo/ProjectToolbar.jsx
index d41f8f04f8..2d8f4bc37b 100644
--- a/client/src/components/musicVideo/ProjectToolbar.jsx
+++ b/client/src/components/musicVideo/ProjectToolbar.jsx
@@ -123,20 +123,23 @@ export default function ProjectToolbar({
>
<Copy size={15} /> {busy.cloning ? 'Forking…' : `Fork v${nextVersion}`}
</button>
- {renderJob.job ? (
- <button onClick={renderJob.cancel} title="Cancel render"
+ {renderJob.active && renderJob.context === project.id ? (
+ <button onClick={renderJob.cancel} disabled={renderJob.pending}
+ title={renderJob.pending ? 'Preparing render' : 'Cancel render'}
className="flex items-center gap-1 bg-port-warning/20 text-port-warning border border-port-border rounded px-2 py-1.5 text-sm min-h-[44px] sm:min-h-0">
- <Activity size={15} className="animate-spin" /> {renderJob.progress}% · Cancel
+ <Activity size={15} className="animate-spin" /> {renderJob.pending ? 'Preparing render…' : `${renderJob.progress}% · Cancel`}
</button>
) : (
- <button onClick={() => renderJob.start(project.id)} disabled={sceneCount === 0 || renderableSceneCount !== sceneCount}
- title={sceneCount === 0
- ? 'Add scenes first'
- : renderableSceneCount !== sceneCount
- ? `Generate videos for all ${sceneCount} scenes first`
- : 'Render the complete music video over the track'}
+ <button onClick={() => renderJob.start(project.id)} disabled={renderJob.active || sceneCount === 0 || renderableSceneCount !== sceneCount}
+ title={renderJob.active
+ ? 'Wait for the other project render to finish, or return to it to cancel'
+ : sceneCount === 0
+ ? 'Add scenes first'
+ : renderableSceneCount !== sceneCount
+ ? `Generate videos for all ${sceneCount} scenes first`
+ : 'Render the complete music video over the track'}
className="flex items-center gap-1 bg-port-accent text-white rounded px-2 py-1.5 text-sm min-h-[44px] sm:min-h-0 disabled:opacity-50">
- <Film size={15} /> Render final
+ <Film size={15} /> {renderJob.active ? 'Rendering another project…' : 'Render final'}
</button>
)}
<button onClick={onDelete} title="Delete project" aria-label="Delete project"
diff --git a/client/src/hooks/README.md b/client/src/hooks/README.md
index 9c1517fddb..e888c6be88 100644
--- a/client/src/hooks/README.md
+++ b/client/src/hooks/README.md
@@ -40,7 +40,7 @@ grep -i "what you want to do" client/src/hooks/README.md
| Hook | Purpose | Use when |
|---|---|---|
| `useSseProgress` | Generic JSON-frame EventSource subscriber. | New SSE progress stream — start here, build on top. |
-| `useSseJobSlot` | Generic single-slot SSE job: `pending`/`job` state, terminal-frame handling (`complete`/`error`/`canceled`), and `sse.closed`-without-terminal-frame recovery in one place. Returns `{ active, percent, stage, context, start, cancel }`; 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 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, cancel }`; 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. |
| `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. |
@@ -224,7 +224,7 @@ grep -i "what you want to do" client/src/hooks/README.md
| `useMidiTranscription` | One audio → MIDI transcription job slot (MuScriptor): start/cancel + SSE stage progress + terminal-frame handling, generic over the Rounds and Music Video API surfaces (pass `startRequest`/`eventsUrl`/`cancelRequest`). Returns `{ active, stage, stageLabel, context, start(context), cancel }` (`stageLabel` is the ready-to-render human label for the current STAGE — including a distinct "Downloading model…" for the first-use weight download, which also fires a one-time toast; `context` is the in-flight job's captured target, for per-target UI gates); `onComplete(frame, context)` fires with the terminal frame (`filename`, `model`, any server-merged extras). | The Rounds reference "Transcribe MIDI" control and the Music Video MIDI button. |
| `useMusicVideoYoutubeImport` | The Music Video page's two independent `useYoutubeTrackImport` slots (create form + detail-view track row) plus their URL drafts, the detail slot's captured target project, and the URL-nav backstop that bounces a deep link / Back / ⌘K jump away from an in-flight import back to its project. Returns `{ createUrl, setCreateUrl, editUrl, setEditUrl, createJob, editJob, startCreate, startEdit, switchBlockedMessage }`. | The Music Video page. Reuse `switchBlockedMessage` for any additional guard (delete, list picker) so every surface says the same thing. |
| `useMusicVideoMidiJob` | `useMidiTranscription` bound to the music-video API surface, plus the MuScriptor model-size picker state (read fresh at each kickoff). Returns the slot (`active`/`stage`/`stageLabel`/`context`/`start(projectId)`/`cancel`/`installGate`/`gatedGate`) plus `{ model, setModel }`; `onTranscribed(projectId, midiTranscription)` fires on a non-discarded terminal frame. | The Music Video MIDI button + model select. |
-| `useMusicVideoRenderJob` | The final-render job (#1760 Phase 2): kickoff (409 → attach to the existing job), SSE progress, terminal-frame handling and non-terminal stream-close recovery. Returns `{ job, progress, start(projectId), cancel }`; `onRendered(projectId, result)` / `onFailed(projectId)` key on the projectId captured at kickoff. | The Music Video "Render final" control. |
+| `useMusicVideoRenderJob` | The final-render job (#1760 Phase 2): kickoff (409 → attach to the existing job), SSE progress, terminal-frame handling and non-terminal stream-close recovery. Thin `useSseJobSlot` adapter with 0–1 progress conversion; returns `{ active, pending, context, job, progress, start(projectId), cancel }`; `onRendered(projectId, result)` / `onFailed(projectId)` key on the projectId captured at kickoff. | The Music Video "Render final" control. |
| `useMusicVideoModelSettings` | A project's saved render pins — video backend/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, 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) 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 suffix), and the batch "generate the missing ones" actions. Returns `{ genScenes, genVideoScenes, 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. |
| `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/useMusicVideoRenderJob.js b/client/src/hooks/useMusicVideoRenderJob.js
index a75b0cc202..f4fc20021c 100644
--- a/client/src/hooks/useMusicVideoRenderJob.js
+++ b/client/src/hooks/useMusicVideoRenderJob.js
@@ -1,76 +1,42 @@
-import { useEffect, useState } from 'react';
-import toast from '../components/ui/Toast';
import {
renderMusicVideoProject,
musicVideoRenderEventsUrl,
cancelMusicVideoRender,
} from '../services/apiMusicVideo.js';
-import { useSseProgress, isTerminalSseFrame } from './useSseProgress.js';
+import useSseJobSlot from './useSseJobSlot.js';
+
+const readRenderPercent = (frame) => Number.isFinite(frame.progress) ? frame.progress * 100 : undefined;
+
+// A server-owned render may already exist after returning to the page. Attach
+// through the same successful kickoff path; a still-preparing 409 has no jobId.
+const startRender = (projectId) => renderMusicVideoProject(projectId, { silent: true })
+ .catch((err) => {
+ if (err?.status === 409 && err?.context?.jobId) return { jobId: err.context.jobId };
+ throw err;
+ });
/**
- * The music-video final-render job (#1760, Phase 2): assemble the scene clips
- * over the master audio bed. The kickoff returns a jobId; progress streams over
- * SSE via useSseProgress. One slot per page — a project can only have one final
- * render in flight, and a second kickoff for the same project attaches to the
- * existing job (409 → `err.context.jobId`).
- *
- * `onRendered(projectId, result)` / `onFailed(projectId)` fire on the terminal
- * frame keyed on the projectId captured at kickoff, so a project switch mid-
- * render can't misattribute the result to whatever is selected by then.
+ * Final-render adapter over the shared SSE slot. Captures the project before
+ * preparation begins, so navigation cannot replace the render or redirect its
+ * callbacks. The job shape stays compatible with the existing cancel controls.
*/
export default function useMusicVideoRenderJob({ onRendered, onFailed } = {}) {
- const [job, setJob] = useState(null); // { jobId, projectId } while in flight
- const sse = useSseProgress(job ? musicVideoRenderEventsUrl(job.jobId) : null);
- const progress = job ? Math.round((sse.latest?.progress ?? 0) * 100) : 0;
-
- // React to terminal SSE frames: record the render on the project, surface the
- // outcome, and clear the in-flight job.
- useEffect(() => {
- const frame = sse.latest;
- if (!job || !frame) return;
- if (frame.type === 'complete') {
- onRendered?.(job.projectId, frame.result || {});
- toast.success('Music video rendered');
- setJob(null);
- } else if (frame.type === 'error') {
- toast.error(frame.error || 'Render failed');
- onFailed?.(job.projectId);
- setJob(null);
- } else if (frame.type === 'canceled' || frame.type === 'cancelled') {
- toast.info('Render cancelled');
- setJob(null);
- }
- }, [sse.latest]);
-
- // Stream closed on a NON-terminal frame (server restart mid-render, or the job
- // was pruned before/after attach so the 404 closes the stream) — recover so the
- // spinner can't hang. Gating on `!latest` is wrong: `latest` holds the last
- // *progress* frame once any progress streamed, so it would never fire. Mirror
- // VideoTimelineEditor: recover whenever the final frame isn't terminal.
- useEffect(() => {
- if (job && sse.closed && !isTerminalSseFrame(sse.latest)) {
- setJob(null);
- toast.info('Lost connection to the render — check Media History for the result');
- }
- }, [sse.closed]);
-
- const start = (projectId) => {
- renderMusicVideoProject(projectId, { silent: true })
- .then(({ jobId }) => setJob({ jobId, projectId }))
- .catch((err) => {
- // 409 → a render is already in flight for this project; attach to it.
- if (err?.status === 409 && err?.context?.jobId) {
- setJob({ jobId: err.context.jobId, projectId });
- return;
- }
- toast.error(err?.message || 'Failed to start render');
- });
- };
-
- const cancel = () => {
- if (!job) return;
- cancelMusicVideoRender(job.jobId, { silent: true }).catch(() => {});
+ const slot = useSseJobSlot({
+ startRequest: startRender,
+ eventsUrl: musicVideoRenderEventsUrl,
+ cancelRequest: cancelMusicVideoRender,
+ readPercent: readRenderPercent,
+ onComplete: (frame, projectId) => onRendered?.(projectId, frame.result || {}),
+ onErrorFrame: (_frame, projectId) => { onFailed?.(projectId); },
+ successToast: () => 'Music video rendered',
+ errorFallback: 'Render failed',
+ canceledMessage: 'Render cancelled',
+ lostConnectionMessage: 'Lost connection to the render — check Media History for the result',
+ startErrorFallback: 'Failed to start render',
+ });
+ return {
+ ...slot,
+ job: slot.jobId ? { jobId: slot.jobId, projectId: slot.context } : null,
+ progress: slot.active ? slot.percent : 0,
};
-
- return { job, progress, start, cancel };
}
diff --git a/client/src/hooks/useSseJobSlot.js b/client/src/hooks/useSseJobSlot.js
index 487d5561ad..f369570d4e 100644
--- a/client/src/hooks/useSseJobSlot.js
+++ b/client/src/hooks/useSseJobSlot.js
@@ -1,42 +1,29 @@
-import { useEffect, useState } from 'react';
+import { useEffect, useRef, useState } from 'react';
import toast from '../components/ui/Toast';
import { useSseProgress, isTerminalSseFrame } from './useSseProgress.js';
+import useMounted from './useMounted.js';
+
+const defaultReadPercent = (frame) => frame.percent;
/**
- * One generic single-slot SSE job — the shared machinery every "kick off a job,
- * stream progress over SSE, settle on the terminal frame" hook re-implements:
- *
- * - `pending` covers the gap between clicking Start and the kickoff request
- * resolving, when `job` is still null — without it a fast double-click could
- * fire a second request whose response silently orphans the first job.
- * - the terminal-frame effect (`complete` / `error` / `canceled|cancelled`),
- * - the `sse.closed`-without-a-terminal-frame recovery (server restart mid-job,
- * or the job was pruned before/after attach) so the spinner can't hang.
- *
- * Call it once per UI surface that can independently kick off a job so each owns
- * its own job + SSE subscription — a shared slot would let a second kickoff
- * orphan the first's in-flight job (its SSE subscription would never re-attach).
- *
- * The three feature hooks (`useReferenceAudioImport`, `useYoutubeTrackImport`,
- * `useVideoDownload`) and `useMidiTranscription` are thin wrappers over this;
- * the recovery + terminal-frame logic lives here in exactly one place (#2368).
+ * One single-slot SSE job: kickoff, captured target, progress and terminal
+ * recovery. Reserve the slot synchronously, including the preparation window
+ * before the server returns a jobId. Each independent surface owns one slot.
*
* Options:
* - `startRequest(startArg)` → resolves `{ jobId }` — the feature's kickoff call.
* - `eventsUrl(jobId)` / `cancelRequest(jobId, { silent })` — SSE URL + cancel call.
* - `onComplete(frame, context)` — fires on the terminal `complete` frame.
* - `context` (the second `start` arg, or the start arg itself when omitted) is
- * captured at kickoff so a slow-finishing job still attaches to the right
- * target even if the caller's own state changed while it was in flight.
- * - `trimStartArg` — when true, `start(url, context)` trims `url` and no-ops on
- * empty (the URL-import hooks); when false, `start(context)` passes through.
+ * captured and exposed immediately at kickoff, including while `pending`.
+ * - `trimStartArg` — trims URL input and ignores an empty start when true.
+ * - `readPercent(frame)` — optional projection to 0–100 (default: frame.percent).
+ * Missing/non-finite values preserve the last reported progress.
* - `successToast(frame)` — optional; toast.success its return when truthy.
* - `errorFallback` / `canceledMessage` / `lostConnectionMessage` /
* `startErrorFallback` — the per-feature toast copy.
- * - `onErrorFrame(frame, context)` → return true to suppress the default error
- * toast (the MIDI gated-repo prompt intercepts here).
- * - `onKickoffError(err, startArg)` → return true to suppress the default kickoff
- * error toast (the MIDI first-use install gate intercepts here).
+ * - `onErrorFrame(frame, context)` → return true to suppress the error toast.
+ * - `onKickoffError(err, startArg)` → return true to suppress the kickoff toast.
* - `onKickoffSuccess(jobId, startArg)` — fires when the kickoff resolves.
*/
export default function useSseJobSlot({
@@ -45,6 +32,7 @@ export default function useSseJobSlot({
cancelRequest,
onComplete,
trimStartArg = false,
+ readPercent = defaultReadPercent,
successToast,
errorFallback = 'Job failed',
canceledMessage = 'Job cancelled',
@@ -54,52 +42,57 @@ export default function useSseJobSlot({
onKickoffError,
onKickoffSuccess,
} = {}) {
- const [job, setJob] = useState(null); // { jobId, context }
- const [pending, setPending] = useState(false);
+ // jobId is null during preparation; context already owns the target then.
+ const [job, setJob] = useState(null);
const [progress, setProgress] = useState({ percent: 0, stage: null });
- const jobUrl = job ? eventsUrl(job.jobId) : null;
+ const slotRef = useRef(null);
+ const mounted = useMounted();
+ useEffect(() => () => { slotRef.current = null; }, []);
+ const jobUrl = job?.jobId ? eventsUrl(job.jobId) : null;
const sse = useSseProgress(jobUrl);
const latest = sse.latest;
+ const percent = latest ? readPercent(latest) : undefined;
- // Metadata and warning frames intentionally omit progress fields. Preserve the
- // last announced values across those sparse frames instead of flashing 0% /
- // "starting" between real progress updates.
- //
- // `latestUrl` is only a STALE-FRAME guard: the real hook sets it alongside
- // `latest`, so a mismatch means the frame belongs to a previous job. An absent
- // `latestUrl` means "unknown", not "mismatched" — treating it as a mismatch
- // would silently freeze progress for any consumer whose SSE seam is stubbed.
+ const clearJob = () => {
+ slotRef.current = null;
+ setJob(null);
+ };
+
+ // Sparse metadata/warning frames preserve progress. A known mismatched URL
+ // belongs to an older stream; absent URL identity remains tolerated for the
+ // existing SSE test seams.
useEffect(() => {
- if (!job || !latest) return;
+ if (!job?.jobId || !latest) return;
if (sse.latestUrl && sse.latestUrl !== jobUrl) return;
setProgress((prev) => ({
- percent: Number.isFinite(latest.percent) ? Math.round(latest.percent) : prev.percent,
+ percent: Number.isFinite(percent) ? Math.round(percent) : prev.percent,
stage: typeof latest.stage === 'string' && latest.stage ? latest.stage : prev.stage,
}));
- }, [latest, job, jobUrl, sse.latestUrl]);
+ }, [latest, job, jobUrl, sse.latestUrl, percent]);
useEffect(() => {
- if (!job || !latest) return;
+ if (!job?.jobId || !latest) return;
+ if (sse.latestUrl && sse.latestUrl !== jobUrl) return;
if (latest.type === 'complete') {
+ clearJob();
onComplete?.(latest, job.context);
const msg = successToast?.(latest);
if (msg) toast.success(msg);
- setJob(null);
} else if (latest.type === 'error') {
+ clearJob();
if (!onErrorFrame?.(latest, job.context)) {
toast.error(latest.error || errorFallback);
}
- setJob(null);
} else if (latest.type === 'canceled' || latest.type === 'cancelled') {
+ clearJob();
toast.info(canceledMessage);
- setJob(null);
}
- }, [latest]);
+ }, [latest, sse.latestUrl]);
- // Stream closed without a terminal frame — recover so the spinner can't hang.
useEffect(() => {
- if (job && sse.closed && !isTerminalSseFrame(latest)) {
- setJob(null);
+ if (job?.jobId && sse.closed && !isTerminalSseFrame(latest)) {
+ if (sse.latestUrl && sse.latestUrl !== jobUrl) return;
+ clearJob();
toast.info(lostConnectionMessage);
}
}, [sse.closed]);
@@ -107,28 +100,35 @@ export default function useSseJobSlot({
const start = (startArg, context) => {
const arg = trimStartArg ? (startArg ?? '').trim() : startArg;
if (trimStartArg && !arg) return;
- if (job || pending) return;
+ if (!mounted.current || slotRef.current) return;
+ const slot = { jobId: null, context: context === undefined ? arg : context };
+ slotRef.current = slot;
+ setJob(slot);
setProgress({ percent: 0, stage: null });
- setPending(true);
+ const isCurrent = () => mounted.current && slotRef.current === slot;
startRequest(arg)
.then(({ jobId }) => {
+ if (!isCurrent()) return;
onKickoffSuccess?.(jobId, arg);
- setJob({ jobId, context: context === undefined ? arg : context });
+ setJob({ jobId, context: slot.context });
})
.catch((err) => {
+ if (!isCurrent()) return;
+ clearJob();
if (onKickoffError?.(err, arg)) return;
toast.error(err?.message || startErrorFallback);
- })
- .finally(() => setPending(false));
+ });
};
const cancel = () => {
- if (!job) return;
+ if (!mounted.current || !job?.jobId) return;
cancelRequest(job.jobId, { silent: true }).catch(() => {});
};
return {
- active: pending || !!job,
+ active: !!job,
+ pending: !!job && !job.jobId,
+ jobId: job?.jobId ?? null,
percent: progress.percent,
stage: progress.stage,
context: job?.context ?? null,
diff --git a/client/src/hooks/useSseJobSlot.test.jsx b/client/src/hooks/useSseJobSlot.test.jsx
new file mode 100644
index 0000000000..53080d907b
--- /dev/null
+++ b/client/src/hooks/useSseJobSlot.test.jsx
@@ -0,0 +1,83 @@
+import { StrictMode } from 'react';
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
+import { renderHook, act } from '@testing-library/react';
+import useSseJobSlot from './useSseJobSlot.js';
+import { MockEventSource, lastEventSource } from '../test/mockEventSource';
+import toast from '../components/ui/Toast';
+
+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());
+
+// Direct starts in the same React turn uniquely exercise the synchronous guard;
+// a rendered disabled button cannot cover a retained callback invoked twice.
+it('reserves one slot synchronously and keeps default progress/terminal behavior across successive jobs', async () => {
+ let resolveKickoff;
+ const startRequest = vi.fn()
+ .mockImplementationOnce(() => new Promise((resolve) => { resolveKickoff = resolve; }))
+ .mockResolvedValueOnce({ jobId: 'second-job' });
+ const onComplete = vi.fn();
+ const { result } = renderHook(() => useSseJobSlot({
+ startRequest, eventsUrl: (id) => `/events/${id}`, onComplete,
+ }), { wrapper: StrictMode });
+ act(() => {
+ result.current.start('first-target');
+ result.current.start('second-target');
+ });
+ expect(startRequest).toHaveBeenCalledTimes(1);
+ expect(result.current).toMatchObject({ active: true, pending: true, context: 'first-target' });
+ expect(MockEventSource.instances).toHaveLength(0);
+ await act(async () => { resolveKickoff({ jobId: 'first-job' }); });
+ expect(lastEventSource().url).toBe('/events/first-job');
+ act(() => {
+ result.current.start('second-target');
+ lastEventSource().emit({ type: 'progress', percent: 42.4, stage: 'download' });
+ });
+ expect(startRequest).toHaveBeenCalledTimes(1);
+ act(() => { lastEventSource().emit({ type: 'metadata' }); });
+ expect(result.current).toMatchObject({ percent: 42, stage: 'download' });
+ act(() => { lastEventSource().emit({ type: 'complete', filename: 'example.wav' }); });
+ expect(onComplete).toHaveBeenCalledWith({ type: 'complete', filename: 'example.wav' }, 'first-target');
+ expect(result.current.active).toBe(false);
+
+ // Real useSseProgress retains its prior terminal frame across the idle gap.
+ // Starting again must neither replay it nor immediately end the new slot.
+ await act(async () => { result.current.start('second-target'); });
+ expect(result.current).toMatchObject({ active: true, pending: false, context: 'second-target', percent: 0 });
+ expect(lastEventSource().url).toBe('/events/second-job');
+ expect(onComplete).toHaveBeenCalledTimes(1);
+});
+
+describe('unmounted kickoff ownership', () => {
+ it.each(['resolve', 'reject'])('ignores a late %s and refuses starts through an unmounted callback', async (outcome) => {
+ let resolveKickoff;
+ let rejectKickoff;
+ const startRequest = vi.fn(() => new Promise((resolve, reject) => {
+ resolveKickoff = resolve;
+ rejectKickoff = reject;
+ }));
+ const onKickoffSuccess = vi.fn();
+ const onKickoffError = vi.fn();
+ const { result, unmount } = renderHook(() => useSseJobSlot({
+ startRequest, eventsUrl: (id) => `/events/${id}`, onKickoffSuccess, onKickoffError,
+ }));
+ const start = result.current.start;
+ act(() => { start('example-target'); });
+ unmount();
+ await act(async () => {
+ start('stale-target');
+ if (outcome === 'resolve') resolveKickoff({ jobId: 'late-job' });
+ else rejectKickoff(new Error('Late failure'));
+ });
+ expect(startRequest).toHaveBeenCalledTimes(1);
+ expect(onKickoffSuccess).not.toHaveBeenCalled();
+ expect(onKickoffError).not.toHaveBeenCalled();
+ expect(toast.error).not.toHaveBeenCalled();
+ expect(MockEventSource.instances).toHaveLength(0);
+ });
+});
diff --git a/client/src/pages/MusicVideo.jsx b/client/src/pages/MusicVideo.jsx
index 0de90e6223..3d62794333 100644
--- a/client/src/pages/MusicVideo.jsx
+++ b/client/src/pages/MusicVideo.jsx
@@ -109,10 +109,10 @@ export default function MusicVideo() {
applyScenePatch: patchScene,
});
- // The in-flight render already resolved the project's audio at kickoff;
+ // Preparation is already resolving the project's audio at kickoff;
// relinking the track now would leave the project pointing at a NEW track
// while the video that finishes rendering was produced from the OLD one.
- const renderTargetsSelected = !!(renderJob.job && selected && renderJob.job.projectId === selected.id);
+ const renderTargetsSelected = !!(renderJob.active && selected && renderJob.context === selected.id);
// `midiTargetsSelected` gates the track-change controls, since the .mid being
// produced is of the CURRENT audio (mirrors renderTargetsSelected).
const midiTargetsSelected = !!(midi.active && selected && midi.context === selected.id);
@@ -549,7 +549,7 @@ export default function MusicVideo() {
onChangeTrack={handleChangeTrack}
/>
<RenderStatusPanel
- rendering={!!renderJob.job}
+ rendering={renderTargetsSelected}
progress={renderJob.progress}
renderHistoryId={selected.renderHistoryId}
finalVideo={finalVideo}
diff --git a/client/src/pages/MusicVideo.test.jsx b/client/src/pages/MusicVideo.test.jsx
index 975a0d6128..c26959c756 100644
--- a/client/src/pages/MusicVideo.test.jsx
+++ b/client/src/pages/MusicVideo.test.jsx
@@ -110,7 +110,7 @@ vi.mock('../components/PageHeader', () => ({ default: ({ title }) => <div>{title
import MusicVideo from './MusicVideo.jsx';
import {
listMusicVideoProjects, createMusicVideoProject, cloneMusicVideoProject, renderMusicVideoProject, planMusicVideoProject, updateMusicVideoProject,
- deleteMusicVideoProject, transcribeMusicVideoMidi,
+ deleteMusicVideoProject, transcribeMusicVideoMidi, cancelMusicVideoRender,
} from '../services/apiMusicVideo.js';
import { importTrackFromYoutube, trackImportEventsUrl, listTracks } from '../services/apiTracks.js';
import { generateVideo, getVideoGenStatus } from '../services/apiImageVideo.js';
@@ -219,6 +219,92 @@ describe('MusicVideo render control (#1760)', () => {
await waitFor(() => expect(renderMusicVideoProject).toHaveBeenCalledWith('mv-1', { silent: true }));
});
+ it('reserves preparation across project navigation and applies completion to the captured project', async () => {
+ const other = { ...PROJECT_WITH_CLIP, id: 'mv-other', name: 'Other Project' };
+ listMusicVideoProjects.mockResolvedValue([PROJECT_WITH_CLIP, other]);
+ let resolveKickoff;
+ renderMusicVideoProject.mockImplementationOnce(() => new Promise((resolve) => { resolveKickoff = resolve; }));
+ renderMV();
+ await selectProject(PROJECT_WITH_CLIP.id);
+
+ fireEvent.click(screen.getByRole('button', { name: /^Render final$/ }));
+ expect(screen.getByRole('button', { name: 'Preparing render…' })).toBeDisabled();
+ expect(screen.getByLabelText('Change track')).toBeDisabled();
+ fireEvent.change(screen.getByLabelText('Change track'), { target: { value: 'other-track' } });
+ expect(updateMusicVideoProject).not.toHaveBeenCalled();
+
+ await selectProject(other.id);
+ const otherRender = screen.getByRole('button', { name: 'Rendering another project…' });
+ expect(otherRender).toBeDisabled();
+ fireEvent.click(otherRender);
+ expect(renderMusicVideoProject).toHaveBeenCalledTimes(1);
+ expect(screen.getByLabelText('Change track')).not.toBeDisabled();
+ expect(screen.queryByTitle('Cancel render')).not.toBeInTheDocument();
+
+ await act(async () => { resolveKickoff({ jobId: 'render-first' }); });
+ sseState.latest = { type: 'progress', progress: 0.375 };
+ await selectProject(PROJECT_WITH_CLIP.id);
+ expect(screen.getByTitle('Cancel render')).toHaveTextContent('38%');
+ expect(screen.getByLabelText('Change track')).toBeDisabled();
+
+ // A metadata frame omits progress; the final-render adapter keeps 38%.
+ sseState.latest = { type: 'status', message: 'Finishing output' };
+ fireEvent.click(screen.getByRole('button', { name: /New project/i }));
+ expect(screen.getByTitle('Cancel render')).toHaveTextContent('38%');
+ await selectProject(other.id);
+ sseState.latest = { type: 'complete', result: { id: 'rh-9' } };
+ fireEvent.change(screen.getByPlaceholderText('Project name'), { target: { value: 'Unrelated draft' } });
+ await waitFor(() => expect(toast.success).toHaveBeenCalledWith('Music video rendered'));
+ expect(screen.queryByText(/Open in Media History/i)).not.toBeInTheDocument();
+ await selectProject(PROJECT_WITH_CLIP.id);
+ expect(screen.getByText(/Open in Media History/i).closest('a')).toHaveAttribute('href', expect.stringContaining('preview=video%3Arh-9'));
+ });
+
+ it('recovers from a preparing 409 and attaches/cancels an existing render with a job id', async () => {
+ renderMusicVideoProject
+ .mockRejectedValueOnce(Object.assign(new Error('Render is still preparing'), { status: 409, context: { jobId: null } }))
+ .mockRejectedValueOnce(Object.assign(new Error('Render already exists'), { status: 409, context: { jobId: 'existing-render' } }));
+ await openProject(PROJECT_WITH_CLIP);
+ fireEvent.click(screen.getByRole('button', { name: /^Render final$/ }));
+ await waitFor(() => expect(toast.error).toHaveBeenCalledWith('Render is still preparing'));
+ expect(screen.getByRole('button', { name: /^Render final$/ })).toBeEnabled();
+ expect(screen.getByLabelText('Change track')).toBeEnabled();
+
+ fireEvent.click(screen.getByRole('button', { name: /^Render final$/ }));
+ fireEvent.click(await screen.findByTitle('Cancel render'));
+ expect(cancelMusicVideoRender).toHaveBeenCalledWith('existing-render', { silent: true });
+ expect(toast.error).toHaveBeenCalledTimes(1);
+ sseState.latest = { type: 'canceled' };
+ fireEvent.click(screen.getByRole('button', { name: /New project/i }));
+ expect(toast.info).toHaveBeenCalledWith('Render cancelled');
+ expect(screen.getByRole('button', { name: /^Render final$/ })).toBeEnabled();
+ });
+
+ it('attributes a render failure after navigation and releases the slot after a dropped stream', async () => {
+ const other = { ...PROJECT_WITH_CLIP, id: 'mv-other', name: 'Other Project' };
+ listMusicVideoProjects.mockResolvedValue([PROJECT_WITH_CLIP, other]);
+ renderMV();
+ await selectProject(PROJECT_WITH_CLIP.id);
+ fireEvent.click(screen.getByRole('button', { name: /^Render final$/ }));
+ await screen.findByTitle('Cancel render');
+ await selectProject(other.id);
+ sseState.latest = { type: 'error', error: 'Renderer stopped' };
+ fireEvent.click(screen.getByRole('button', { name: /New project/i }));
+ expect(toast.error).toHaveBeenCalledWith('Renderer stopped');
+ expect(screen.getByLabelText('Project').querySelector('option[value="mv-1"]')).toHaveTextContent('failed');
+ expect(screen.getByLabelText('Project').querySelector('option[value="mv-other"]')).toHaveTextContent('ready');
+
+ sseState.latest = null;
+ fireEvent.click(screen.getByRole('button', { name: /^Render final$/ }));
+ await screen.findByTitle('Cancel render');
+ sseState.latest = { type: 'progress', progress: 0.4 };
+ fireEvent.change(screen.getByPlaceholderText('Project name'), { target: { value: 'Draft' } });
+ sseState.closed = true;
+ fireEvent.change(screen.getByPlaceholderText('Project name'), { target: { value: 'Draft updated' } });
+ expect(toast.info).toHaveBeenCalledWith('Lost connection to the render — check Media History for the result');
+ expect(screen.getByRole('button', { name: /^Render final$/ })).toBeEnabled();
+ });
+
it('disables Render when no scene has a generated clip', async () => {
await openProject(PROJECT_NO_CLIP);
const renderBtn = await screen.findByRole('button', { name: /^Render final$/ });