Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat: run lyric word alignment as a job with progress, cancel, dedupe and reload reattach (#10155)
Adam Eivy95b16eca709e
diff --git a/client/src/components/musicVideo/LyricsPanel.jsx b/client/src/components/musicVideo/LyricsPanel.jsxindex 122ed00f53..bdafa5be31 100644--- a/client/src/components/musicVideo/LyricsPanel.jsx+++ b/client/src/components/musicVideo/LyricsPanel.jsx@@ -322,7 +322,8 @@ export default function LyricsPanel({ project, onEditLocal, onSave, onImport, im}}onBlur={() => saveCues()} className={`${inputCls} min-w-0 flex-1 basis-40`} />{onAlign && (- <button type="button" onClick={() => runAlign(cue.id)} disabled={aligning}+ <button type="button" onClick={() => runAlign(cue.id)} disabled={aligning || !hasAudio}+ title={hasAudio ? undefined : 'Attach a song before aligning words'}aria-label={`Re-align line ${i + 1}`}className="min-h-[44px] sm:min-h-0 text-port-accent disabled:opacity-50">Re-align</button>)}diff --git a/client/src/components/musicVideo/stages/SetupStage.jsx b/client/src/components/musicVideo/stages/SetupStage.jsxindex 760db0781e..2f67dc9e19 100644--- a/client/src/components/musicVideo/stages/SetupStage.jsx+++ b/client/src/components/musicVideo/stages/SetupStage.jsx@@ -43,7 +43,7 @@ function SongStep({ number, title, done, children }) {}/** Whole-song word alignment; the page's handler is silent, so errors surface here. */-function AlignWords({ disabled, aligning, onAlign }) {+function AlignWords({ disabled, aligning, status, onAlign }) {const [error, setError] = useState('');const run = () => {setError('');@@ -58,6 +58,13 @@ function AlignWords({ disabled, aligning, onAlign }) {className="min-h-[44px] rounded border border-port-border bg-port-bg px-2 py-1.5 text-sm text-port-accent disabled:opacity-50 sm:min-h-0">{aligning ? 'Aligning…' : 'Align all words'}</button>+ {status && (+ <div role="status" className="flex flex-wrap items-center gap-2 text-xs text-port-text-muted">+ <span>{status.label}{status.percent > 0 ? ` ${status.percent}%` : ''}</span>+ <button type="button" onClick={status.onCancel}+ className="min-h-[44px] rounded border border-port-border px-2 text-port-error sm:min-h-0">Cancel</button>+ </div>+ )}{error && <p role="alert" className="text-xs text-port-error">{error}</p>}</>);@@ -83,7 +90,7 @@ const directionSummary = (project) => {export default function SetupStage({ board }) {const {project, tracks, trackName, audioFilename, locked, youtube, separation, midi, midiBound, renderBound, tempo, busy,- conceptDraft, styleDraft, importingLyrics, aligningLyrics, treatment,+ conceptDraft, styleDraft, importingLyrics, aligningLyrics, alignStatus, treatment,autopilotRun, autonomous, runStage, onSelectStage,} = board;const songOpen = !projectHasAudio(project) || !project.audioAnalysis;@@ -161,6 +168,7 @@ export default function SetupStage({ board }) {<AlignWordsdisabled={cues.length === 0 || !projectHasAudio(project)}aligning={aligningLyrics}+ status={alignStatus}onAlign={board.onAlignLyrics}/></SongStep>diff --git a/client/src/hooks/README.md b/client/src/hooks/README.mdindex 8036fb8a5b..5ff0065b28 100644--- a/client/src/hooks/README.md+++ b/client/src/hooks/README.md@@ -254,6 +254,7 @@ grep -i "what you want to do" client/src/hooks/README.md| `useMusicVideoCastAndSets` | The Cast & Sets check-in before the plan: applies the project pushed on `music-video:cast-and-sets` / `music-video:dev-artifact` and exposes start / regenerate(notes?) / resume / approve / skip, plus `runToCheckpoint(project)` (start if absent, resolve at review/approved/skipped/failed — or `interrupted` by a restart, which would otherwise never settle) for the kickoff and `cancelWait()` to abandon that wait. | The Music Video autopilot card and sheet viewer. || `useMusicVideoDevArtifacts` | A project's development files ("ingredients"): import a file or a new version, add/resolve notes, approve / request changes, remove; applies the returned project. Returns `{ busy, upload, addNote, resolveNote, review, remove }`. | The Music Video Development section and viewer drawer. || `useMusicVideoVocalSeparation` | "Separate vocals" (demucs) as a `useSseJobSlot`: `start(projectId)` for the button, `run(projectId)` as a promise resolving with the project carrying its new stem (or null on failure/cancel), `stageLabel` for install/separation progress, `onSeparated(projectId, project)` on success. | The Music Video vocal-stem control and the autopilot kickoff. |+| `useMusicVideoLyricAlign` | Lyric word alignment as a `useSseJobSlot` (#10155): `run(projectId, cueId?)` is a promise resolving with the aligned project (null on cancel/dropped stream, rejecting with the server message on failure), `attach(jobId, projectId)` adopts a running job after a reload, `stageLabel`/`percent` for model-download and per-phrase progress, `onAligned(projectId, project)` on success. Slot context is `{ projectId, cueId }`. | Music Video Setup Align words / Re-align and the autopilot kickoff. || `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. || `useAutonomousMusicVideo` | Fully-autonomous run (prompt → lyrics → Suno song → video): applies the project pushed on `music-video:autonomous` and toasts the outcomes that need the director (checkpoint waiting, needs you, finished, failed). Returns `{ busy, resume(edits?, { inline }?), stop(), cancel() }` (an `inline` resume rejects instead of toasting, for errors shown next to the control). | The Music Video autonomous run panel. || `useMusicVideoProduction` | Server-owned production run (#9066): start a browserless plan → frames → clips → reviewed-draft run with an allowed provider/model pool and explicit limits, and Stop / Resume / Cancel it; applies the project pushed on `music-video:production` and toasts terminal outcomes. Returns `{ busy, start(body), resume(runId, body?), stop(runId), cancel(runId) }`. | The Music Video production panel. |diff --git a/client/src/hooks/index.js b/client/src/hooks/index.jsindex 55053d45da..61d0054381 100644--- a/client/src/hooks/index.js+++ b/client/src/hooks/index.js@@ -68,6 +68,7 @@ export { default as useMusicVideoPublishKit } from './useMusicVideoPublishKit.jsexport { default as useMusicVideoPublishing } from './useMusicVideoPublishing.js';export { default as useMusicVideoKickoff } from './useMusicVideoKickoff.js';export { default as useMusicVideoManualTempo } from './useMusicVideoManualTempo.js';+export { default as useMusicVideoLyricAlign } from './useMusicVideoLyricAlign.js';export { default as useMusicVideoMidiJob } from './useMusicVideoMidiJob.js';export { default as useMusicVideoModelSettings } from './useMusicVideoModelSettings.js';export { default as useMusicVideoProduction } from './useMusicVideoProduction.js';diff --git a/client/src/hooks/useMidiTranscription.js b/client/src/hooks/useMidiTranscription.jsindex 4e8d356ca8..1457b362d7 100644--- a/client/src/hooks/useMidiTranscription.js+++ b/client/src/hooks/useMidiTranscription.js@@ -154,6 +154,7 @@ export default function useMidiTranscription({ startRequest, eventsUrl, cancelRestageLabel: midiStageLabel(slot.stage),context: slot.context,start,+ attach: slot.attach,cancel: slot.cancel,installGate,gatedGate,diff --git a/client/src/hooks/useMusicVideoLyricAlign.js b/client/src/hooks/useMusicVideoLyricAlign.jsnew file mode 100644index 0000000000..d6a473c48d--- /dev/null+++ b/client/src/hooks/useMusicVideoLyricAlign.js@@ -0,0 +1,82 @@+import { useEffect, useRef } from 'react';+import toast from '../components/ui/Toast';+import useSseJobSlot from './useSseJobSlot.js';+import {+ alignMusicVideoLyrics,+ musicVideoLyricAlignEventsUrl,+ cancelMusicVideoLyricAlign,+} from '../services/apiMusicVideo.js';++/** Human label for the alignment job's current progress frame. */+export function lyricAlignStageLabel(frame) {+ switch (frame?.stage) {+ case 'decoding': return 'Decoding the song…';+ case 'loading-model': return 'Loading the speech model…';+ case 'downloading-model': return 'Downloading the speech model (first run only)…';+ case 'transcribing': return frame.total > 1 ? `Transcribing phrase ${frame.current} of ${frame.total}…` : 'Transcribing…';+ case 'saving': return 'Saving word timings…';+ default: return 'Starting…';+ }+}++/**+ * Lyric word alignment (#10155) as one SSE job slot. `run(projectId, cueId?)`+ * starts the job as a promise for the page handlers and the autopilot kickoff — it resolves with the updated+ * project, null when cancelled or the stream dropped, and rejects with the+ * server's message on failure so the panel beside the button can show it. A+ * job reattached after a reload has no waiter, so its failure toasts instead.+ * `attach(jobId, projectId)` adopts a running job. `onAligned(projectId, project)`+ * fires on success. The slot `context` is `{ projectId, cueId }`.+ */+export default function useMusicVideoLyricAlign({ onAligned } = {}) {+ const waiter = useRef(null);+ const settle = (fn) => {+ const pending = waiter.current;+ waiter.current = null;+ if (pending) fn(pending);+ };+ const slot = useSseJobSlot({+ startRequest: ({ projectId, cueId }) => alignMusicVideoLyrics(projectId, cueId ? { cueId } : {}, { silent: true }),+ eventsUrl: musicVideoLyricAlignEventsUrl,+ cancelRequest: cancelMusicVideoLyricAlign,+ onComplete: (frame, { projectId, cueId }) => {+ if (frame.project) onAligned?.(projectId, frame.project);+ toast.success(cueId ? 'Re-aligned that line' : 'Aligned words to the vocal');+ settle((pending) => pending.resolve(frame.project || null));+ },+ errorFallback: 'Could not align the words to the vocal',+ canceledMessage: 'Lyric alignment cancelled',+ lostConnectionMessage: 'Lost connection to the lyric alignment',+ onErrorFrame: (frame) => {+ if (!waiter.current) return false;+ settle((pending) => pending.reject(new Error(frame.error || 'Could not align the words to the vocal. Try Align words again.')));+ return true;+ },+ onKickoffError: (err) => {+ if (!waiter.current) return false;+ settle((pending) => pending.reject(err));+ return true;+ },+ });++ // Cancel and a dropped stream clear the slot without a callback; release+ // whoever is waiting on it.+ useEffect(() => {+ if (!slot.active && waiter.current?.started) settle((pending) => pending.resolve(null));+ if (slot.active && waiter.current) waiter.current.started = true;+ }, [slot.active]);+ useEffect(() => () => settle((pending) => pending.resolve(null)), []);++ const run = (projectId, cueId = null) => new Promise((resolve, reject) => {+ if (slot.active) { resolve(null); return; }+ waiter.current = { resolve, reject, started: false };+ slot.start({ projectId, cueId });+ });++ return {+ ...slot,+ stageLabel: slot.active ? lyricAlignStageLabel(slot.latest) : null,+ run,+ attach: (jobId, projectId) => slot.attach(jobId, { projectId, cueId: null }),+ };+}diff --git a/client/src/hooks/useMusicVideoLyricAlign.test.jsx b/client/src/hooks/useMusicVideoLyricAlign.test.jsxnew file mode 100644index 0000000000..93321f319c--- /dev/null+++ b/client/src/hooks/useMusicVideoLyricAlign.test.jsx@@ -0,0 +1,57 @@+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';+import { renderHook, act } from '@testing-library/react';+import useMusicVideoLyricAlign, { lyricAlignStageLabel } from './useMusicVideoLyricAlign.js';+import { MockEventSource, lastEventSource } from '../test/mockEventSource';+import { alignMusicVideoLyrics } from '../services/apiMusicVideo.js';++vi.mock('../components/ui/Toast', () => ({ default: { error: vi.fn(), info: vi.fn(), success: vi.fn() } }));+vi.mock('../services/apiMusicVideo.js', () => ({+ alignMusicVideoLyrics: vi.fn(async () => ({ jobId: 'job-1' })),+ musicVideoLyricAlignEventsUrl: (id) => `/events/${id}`,+ cancelMusicVideoLyricAlign: vi.fn(async () => ({ ok: true })),+}));++beforeEach(() => {+ vi.clearAllMocks();+ MockEventSource.reset();+ vi.stubGlobal('EventSource', MockEventSource);+});+afterEach(() => { vi.unstubAllGlobals(); });++describe('useMusicVideoLyricAlign', () => {+ it('shows stage progress and resolves run() with the project on completion', async () => {+ const onAligned = vi.fn();+ const { result } = renderHook(() => useMusicVideoLyricAlign({ onAligned }));+ let outcome;+ await act(async () => { outcome = result.current.run('p-1'); });+ expect(alignMusicVideoLyrics).toHaveBeenCalledWith('p-1', {}, { silent: true });+ expect(result.current.context).toEqual({ projectId: 'p-1', cueId: null });+ act(() => { lastEventSource().emit({ type: 'progress', stage: 'transcribing', current: 2, total: 5, percent: 20 }); });+ expect(result.current.stageLabel).toBe('Transcribing phrase 2 of 5…');+ expect(result.current.percent).toBe(20);+ act(() => { lastEventSource().emit({ type: 'complete', project: { id: 'p-1', lyricCues: [] } }); });+ await expect(outcome).resolves.toEqual({ id: 'p-1', lyricCues: [] });+ expect(onAligned).toHaveBeenCalledWith('p-1', { id: 'p-1', lyricCues: [] });+ });++ it('rejects run() with the server message so the panel can show it', async () => {+ const { result } = renderHook(() => useMusicVideoLyricAlign());+ let outcome;+ await act(async () => { outcome = result.current.run('p-1', 'lc-1'); });+ expect(alignMusicVideoLyrics).toHaveBeenCalledWith('p-1', { cueId: 'lc-1' }, { silent: true });+ const failed = expect(outcome).rejects.toThrow('whisper missing');+ act(() => { lastEventSource().emit({ type: 'error', error: 'whisper missing' }); });+ await failed;+ });++ it('attach adopts a job a reload left running', async () => {+ const { result } = renderHook(() => useMusicVideoLyricAlign());+ act(() => { expect(result.current.attach('job-9', 'p-1')).toBe(true); });+ expect(lastEventSource().url).toBe('/events/job-9');+ expect(result.current.active).toBe(true);+ });++ it('labels the first-run model download', () => {+ expect(lyricAlignStageLabel({ stage: 'downloading-model', percent: 40 })).toMatch(/Downloading the speech model/);+ });+});diff --git a/client/src/pages/MusicVideo.jsx b/client/src/pages/MusicVideo.jsxindex 4f0944318c..77958d32ac 100644--- a/client/src/pages/MusicVideo.jsx+++ b/client/src/pages/MusicVideo.jsx@@ -26,7 +26,7 @@ import {reorderMusicVideoScenes,importMusicVideoLyrics,importMusicVideoTrackLyrics,- alignMusicVideoLyrics,+ getMusicVideoActiveJobs,getMusicVideoProject,} from '../services/apiMusicVideo.js';import useFieldDraft from '../hooks/useFieldDraft.js';@@ -35,6 +35,7 @@ import useMusicVideoMidiJob from '../hooks/useMusicVideoMidiJob.js';import useMusicVideoKickoff from '../hooks/useMusicVideoKickoff.js';import useMusicVideoCastAndSets from '../hooks/useMusicVideoCastAndSets.js';import useMusicVideoDevArtifacts from '../hooks/useMusicVideoDevArtifacts.js';+import useMusicVideoLyricAlign from '../hooks/useMusicVideoLyricAlign.js';import useMusicVideoVocalSeparation from '../hooks/useMusicVideoVocalSeparation.js';import useMusicVideoRenderJob from '../hooks/useMusicVideoRenderJob.js';import useMusicVideoExcerpts from '../hooks/useMusicVideoExcerpts.js';@@ -210,7 +211,6 @@ export default function MusicVideo() {const [cloningId, setCloningId] = useState(null);const cloning = !!cloningId;const [importingLyrics, setImportingLyrics] = useState(false);- const [aligningLyrics, setAligningLyrics] = useState(false);const [creating, setCreating] = useState(false);const [form, setForm] = useState(emptyCreateForm);@@ -314,6 +314,9 @@ export default function MusicVideo() {const separation = useMusicVideoVocalSeparation({onSeparated: (projectId, project) => patchProject(projectId, { vocalStemFilename: project.vocalStemFilename, updatedAt: project.updatedAt }),});+ const lyricAlign = useMusicVideoLyricAlign({+ onAligned: (projectId, project) => patchProject(projectId, { lyricCues: project.lyricCues, audioAnalysis: project.audioAnalysis, updatedAt: project.updatedAt }),+ });const midi = useMusicVideoMidiJob({onTranscribed: (projectId, midiTranscription) => patchProject(projectId, { midiTranscription }),});@@ -566,12 +569,7 @@ export default function MusicVideo() {}).catch((err) => { toast.error(err?.message || 'Could not import the track lyrics'); return null; }),separateVocals: (project) => separation.run(project.id),- alignLyrics: (project) => alignMusicVideoLyrics(project.id, {}, { silent: true })- .then((next) => {- patchProject(next.id, { lyricCues: next.lyricCues, audioAnalysis: next.audioAnalysis, updatedAt: next.updatedAt });- toast.success('Aligned words to the vocal');- return next;- })+ alignLyrics: (project) => lyricAlign.run(project.id).catch((err) => { toast.error(err?.message || 'Could not align the words — planning without word timings'); return null; }),castAndSets: (project) => castSets.runToCheckpoint(project),cancelCastAndSets: () => castSets.cancelWait(),@@ -760,16 +758,31 @@ export default function MusicVideo() {};// Alignment is a click, never an import side effect. The panel shows the// whisper setup error itself, so this request stays silent.- const handleAlignLyrics = (cueId) => {- const projectId = selected.id;- setAligningLyrics(true);- return alignMusicVideoLyrics(projectId, cueId ? { cueId } : {}, { silent: true })- .then((project) => {- patchProject(projectId, { lyricCues: project.lyricCues, audioAnalysis: project.audioAnalysis, updatedAt: project.updatedAt });- toast.success(cueId ? 'Re-aligned that line' : 'Aligned words to the vocal');+ const handleAlignLyrics = (cueId) => lyricAlign.run(selected.id, cueId);+ // The slot is page-wide but the job belongs to one project: only that+ // project's Setup shows "Aligning…".+ const aligningLyrics = Boolean(lyricAlign.active && selected && lyricAlign.context?.projectId === selected.id);+ const alignStatus = aligningLyrics ? { label: lyricAlign.stageLabel, percent: lyricAlign.percent, onCancel: lyricAlign.cancel } : null;++ // A reload (or another tab) leaves server jobs running that this page has no+ // slot for. Reattach alignment, vocal separation and MIDI so Setup shows them+ // running (#10155); each attach is a no-op while its slot is already busy.+ const reattachRef = useRef({});+ reattachRef.current = { lyricAlign, separation, midi };+ useEffect(() => {+ if (!selectedId) return undefined;+ let current = true;+ getMusicVideoActiveJobs(selectedId, { silent: true })+ .then(({ alignment, separation: separationJob, midi: midiJob }) => {+ if (!current) return;+ const slots = reattachRef.current;+ if (alignment) slots.lyricAlign.attach(alignment, selectedId);+ if (separationJob) slots.separation.attach(separationJob, selectedId);+ if (midiJob) slots.midi.attach(midiJob, selectedId);})- .finally(() => setAligningLyrics(false));- };+ .catch(() => {});+ return () => { current = false; };+ }, [selectedId]);// Buffered so a concept/style keystroke doesn't fire a round-trip per character,// and a focus-without-edit blur doesn't re-PATCH an unchanged value.const conceptDraft = useFieldDraft(selected?.concept?.prompt, (v) => commitConcept({ prompt: v }));@@ -1032,6 +1045,7 @@ export default function MusicVideo() {styleDraft,importingLyrics,aligningLyrics,+ alignStatus,autopilotBlockedReason,canContinueShot,replaceProject,diff --git a/client/src/pages/MusicVideo.test.jsx b/client/src/pages/MusicVideo.test.jsxindex 4592508803..c33b7d9d14 100644--- a/client/src/pages/MusicVideo.test.jsx+++ b/client/src/pages/MusicVideo.test.jsx@@ -66,6 +66,9 @@ vi.mock('../services/apiMusicVideo.js', () => ({importMusicVideoLyrics: vi.fn(),importMusicVideoTrackLyrics: vi.fn(),alignMusicVideoLyrics: vi.fn(),+ musicVideoLyricAlignEventsUrl: (jobId) => `/api/music-video/lyrics/align/${jobId}/events`,+ cancelMusicVideoLyricAlign: vi.fn(async () => ({ ok: true })),+ getMusicVideoActiveJobs: vi.fn(async () => ({ alignment: null, separation: null, midi: null })),separateMusicVideoVocals: vi.fn(async () => ({ jobId: 'sep-job-1' })),musicVideoVocalSeparationEventsUrl: (jobId) => `/api/music-video/vocal-stem/separate/${jobId}/events`,cancelMusicVideoVocalSeparation: vi.fn(async () => ({ ok: true })),@@ -246,7 +249,7 @@ import {selectMusicVideoSceneTake, reviewMusicVideoSceneTake, importMusicVideoHandoff,addMusicVideoSceneTake, getMusicVideoHandoffBundle,renderMusicVideoExcerpt, deleteMusicVideoExcerpt, addMusicVideoExcerptNote,- updateMusicVideoExcerptNote, deleteMusicVideoExcerptNote, getMusicVideoProject, getMusicVideoActiveRender,+ updateMusicVideoExcerptNote, deleteMusicVideoExcerptNote, getMusicVideoProject, getMusicVideoActiveRender, getMusicVideoActiveJobs,startMusicVideoRevision, resumeMusicVideoRevision, cancelMusicVideoRevision,startMusicVideoCastAndSets, approveMusicVideoCastAndSets, stopMusicVideoProduction,getMusicVideoPublishPlatforms, draftMusicVideoPublishCopy,@@ -1478,15 +1481,28 @@ describe('MusicVideo lyrics and shot coverage (#8964)', () => {}];await openProject({ ...PROJECT_ANALYZED, lyricCues: [{ id: 'lc-1', text: 'walking home', startSec: null, endSec: null }] }, 'setup');expect(alignMusicVideoLyrics).not.toHaveBeenCalled();- alignMusicVideoLyrics.mockResolvedValue({ id: 'mv-3', lyricCues: cues, updatedAt: 't' });+ alignMusicVideoLyrics.mockResolvedValue({ jobId: 'align-job-1' });fireEvent.click(screen.getByRole('button', { name: 'Align words' }));await waitFor(() => expect(alignMusicVideoLyrics).toHaveBeenCalledWith('mv-3', {}, { silent: true }));+ await settle();+ sseState.latest = { type: 'complete', project: { id: 'mv-3', lyricCues: cues, updatedAt: 't' } };+ forceRerender();expect(await screen.findByText('walking')).toHaveClass('text-port-accent');expect(screen.getByText('home')).toHaveClass('text-port-warning');+ sseState.latest = null;fireEvent.click(screen.getByRole('button', { name: 'Re-align line 1' }));await waitFor(() => expect(alignMusicVideoLyrics).toHaveBeenLastCalledWith('mv-3', { cueId: 'lc-1' }, { silent: true }));});+ it('reattaches to an alignment the server is still running after a reload (#10155)', async () => {+ getMusicVideoActiveJobs.mockResolvedValueOnce({ alignment: 'align-live', separation: null, midi: null });+ await openProject({ ...PROJECT_ANALYZED, lyricCues: [{ id: 'lc-1', text: 'walking home', startSec: null, endSec: null }] }, 'setup');+ const running = await screen.findAllByRole('button', { name: 'Aligning…' });+ running.forEach((button) => expect(button).toBeDisabled());+ expect(screen.getByRole('button', { name: 'Re-align line 1' })).toBeDisabled();+ expect(alignMusicVideoLyrics).not.toHaveBeenCalled();+ });+it('flags a non-looping shot longer than its clip and trims it; a legacy scene is left alone', async () => {const project = {...PROJECT_WITH_CLIP,diff --git a/client/src/services/apiMusicVideo.js b/client/src/services/apiMusicVideo.jsindex 8169caacb4..a8b7e5f5f5 100644--- a/client/src/services/apiMusicVideo.js+++ b/client/src/services/apiMusicVideo.js@@ -66,11 +66,21 @@ export const importMusicVideoTrackLyrics = (id, body = {}, options = {}) => requ});// Align director lyric lines to the vocal (#9074). Body `{}` aligns every line;-// `{ cueId }` re-aligns one line. Resolves to the updated project. Runs only+// `{ cueId }` re-aligns one line. Kickoff resolves to { jobId, reused? } (#10155):+// stages stream over SSE and the terminal `complete` frame carries the updated+// project. A request while one runs for the project returns that job. Runs only// when the caller invokes it — there is no boot or import hook.export const alignMusicVideoLyrics = (id, body = {}, options = {}) => request(`/music-video/${encodeURIComponent(id)}/lyrics/align`, {method: 'POST', body: JSON.stringify(body), ...options,});+export const musicVideoLyricAlignEventsUrl = (jobId) =>+ `/api/music-video/lyrics/align/${encodeURIComponent(jobId)}/events`;+export const cancelMusicVideoLyricAlign = (jobId, options = {}) =>+ request(`/music-video/lyrics/align/${encodeURIComponent(jobId)}/cancel`, { method: 'POST', ...options });+// Read-only: { alignment, separation, midi } live job ids (null when none) so a+// reloaded Setup reattaches instead of starting a new run.+export const getMusicVideoActiveJobs = (id, options = {}) =>+ request(`/music-video/${encodeURIComponent(id)}/active-jobs`, options);// ---- Director scene board ----export const addMusicVideoScene = (id, scene, options = {}) => request(`/music-video/${encodeURIComponent(id)}/scenes`, {diff --git a/server/routes/musicVideo.js b/server/routes/musicVideo.jsindex 92833c5436..60d5a5e3b0 100644--- a/server/routes/musicVideo.js+++ b/server/routes/musicVideo.js@@ -108,6 +108,7 @@ import { getHistoryItem } from '../services/videoGen/history.js';import {startMidiTranscription,attachMidiTranscriptionSseClient,+ getActiveMidiTranscriptionJobId,cancelMidiTranscription,} from '../services/audioMidiTranscription.js';import { analyzeAudioFileManual, buildManualAnalysisFromCached } from '../services/musicVideo/audioAnalysis.js';@@ -152,7 +153,12 @@ import { buildDocumentPreview } from '../services/musicVideo/documentPreview.js'import { acceptMixedMediaDocument, generateMixedMediaDocument, readMixedMediaCandidate, regenerateMixedMediaSection, reviseMixedMediaEvents } from '../services/musicVideo/documentGeneration.js';import { isZipUpload } from '../lib/zipStream.js';import { parseLyricCues } from '../services/musicVideo/timedText.js';-import { alignProjectLyrics } from '../services/musicVideo/lyricAlign.js';+import {+ attachLyricAlignSseClient,+ cancelLyricAlign,+ getActiveLyricAlignJobId,+ startLyricAlign,+} from '../services/musicVideo/lyricAlignJob.js';import { importTrackLyrics, MAX_LYRIC_CUES } from '../services/musicVideo/trackLyrics.js';import { offsetLyricMarkers } from '../services/musicVideo/lyricMarkers.js';import {@@ -471,13 +477,39 @@ router.post('/:id/lyrics/import-track', asyncHandler(async (req, res) => {res.json(await importTrackLyrics(req.params.id, { mode }));}));-// Word-level alignment (#9074). Nothing here runs until the director clicks-// Align words or a line's Re-align (or starts an autopilot run). The first-// alignment downloads the music-grade whisper model; no whisper.cpp at all is-// a 503 with install steps, not an empty timing list.+// Word-level alignment (#9074) as a job (#10155). Nothing here runs until the+// director clicks Align words or a line's Re-align (or starts an autopilot+// run). Kickoff returns 202 + a jobId; stages (model download %, decoding,+// transcribing window n/m) stream over SSE with cancel, and the terminal+// `complete` frame carries the updated project. One job per project: a second+// request returns the running job (`reused: true`). The first alignment+// downloads the music-grade whisper model; no whisper.cpp at all is an error+// frame with install steps, not an empty timing list.router.post('/:id/lyrics/align', asyncHandler(async (req, res) => {const { cueId } = validateRequest(musicVideoLyricsAlignSchema, req.body || {});- res.json(await alignProjectLyrics(req.params.id, { cueId }));+ res.status(202).json(await startLyricAlign(req.params.id, { cueId }));+}));++router.get('/lyrics/align/:jobId/events', (req, res) => {+ if (!attachLyricAlignSseClient(req.params.jobId, res)) {+ throw new ServerError('Alignment job not found or expired', { status: 404, code: 'NOT_FOUND' });+ }+});++router.post('/lyrics/align/:jobId/cancel', (req, res) => {+ res.json({ ok: cancelLyricAlign(req.params.jobId) });+});++// Read-only: the project's live alignment, vocal-separation and MIDI jobs on+// this instance (null when none), so a reloaded Setup reattaches to each+// instead of POSTing a new run.+router.get('/:id/active-jobs', asyncHandler(async (req, res) => {+ const { getActiveVocalSeparationJobId } = await import('../services/musicVideo/vocalSeparation.js');+ res.json({+ alignment: getActiveLyricAlignJobId(req.params.id),+ separation: getActiveVocalSeparationJobId(req.params.id),+ midi: getActiveMidiTranscriptionJobId(req.params.id),+ });}));// --- Audio → MIDI transcription (MuScriptor) ---@@ -505,6 +537,7 @@ router.post('/:id/transcribe-midi', asyncHandler(async (req, res) => {audioPath,outputName: `${project.name || 'music-video'}-midi`,model,+ ownerKey: projectId,// Land the .mid in the music dir (not uploads) so the peer-sync asset// manifest federates it with the project's other audio — the manifest// only ships known asset kinds/directories, and `music` is one.diff --git a/server/routes/musicVideo.test.js b/server/routes/musicVideo.test.jsindex 11d8d8536c..5c3bcef1b0 100644--- a/server/routes/musicVideo.test.js+++ b/server/routes/musicVideo.test.js@@ -70,6 +70,7 @@ vi.mock('../services/audioMidiTranscription.js', () => ({startMidiTranscription: vi.fn(async () => ({ jobId: 'midi-job-1', model: 'medium' })),attachMidiTranscriptionSseClient: vi.fn(() => true),cancelMidiTranscription: vi.fn(() => true),+ getActiveMidiTranscriptionJobId: vi.fn(() => null),}));vi.mock('../services/musicVideo/lyricAlign.js', () => ({@@ -430,14 +431,64 @@ describe('musicVideo routes', () => {});describe('POST /:id/lyrics/align (#9074)', () => {- it('aligns only when the route is called, and accepts a single-line re-align', async () => {+ const alignable = { id: 'mv-1', lyricCues: [{ id: 'lc-1', text: 'walking home' }] };++ // Hold the mocked alignment open so the job stays "running" for the test.+ const holdAlignment = () => {+ let release;+ alignProjectLyrics.mockImplementationOnce(() => new Promise((resolve) => { release = () => resolve({ id: 'mv-1', lyricCues: [] }); }));+ return () => release();+ };++ it('starts a job only when the route is called, and a second click reuses it (#10155)', async () => {+ svc.getProject.mockResolvedValue(alignable);+ expect(alignProjectLyrics).not.toHaveBeenCalled();+ const release = holdAlignment();+ const first = await request(app).post('/api/music-video/mv-1/lyrics/align').send({});+ expect(first.status).toBe(202);+ expect(first.body.jobId).toEqual(expect.any(String));+ expect(first.body.reused).toBeUndefined();+ const second = await request(app).post('/api/music-video/mv-1/lyrics/align').send({ cueId: 'lc-1' });+ expect(second.status).toBe(202);+ expect(second.body).toEqual({ jobId: first.body.jobId, reused: true });+ expect(alignProjectLyrics).toHaveBeenCalledTimes(1);+ expect(alignProjectLyrics).toHaveBeenCalledWith('mv-1', expect.objectContaining({ cueId: null }));+ const active = await request(app).get('/api/music-video/mv-1/active-jobs');+ expect(active.body).toEqual({ alignment: first.body.jobId, separation: null, midi: null });+ release();+ await vi.waitFor(async () => {+ expect((await request(app).get('/api/music-video/mv-1/active-jobs')).body.alignment).toBeNull();+ });+ });++ it('fails before a job exists when the project or its lyrics are missing', async () => {+ svc.getProject.mockResolvedValue({ id: 'mv-1', lyricCues: [] });+ const none = await request(app).post('/api/music-video/mv-1/lyrics/align').send({});+ expect(none.status).toBe(400);+ expect(none.body.code).toBe('NO_LYRICS');+ svc.getProject.mockResolvedValue(alignable);+ const gone = await request(app).post('/api/music-video/mv-1/lyrics/align').send({ cueId: 'lc-gone' });+ expect(gone.status).toBe(404);expect(alignProjectLyrics).not.toHaveBeenCalled();- const all = await request(app).post('/api/music-video/mv-1/lyrics/align').send({});- expect(all.status).toBe(200);- expect(alignProjectLyrics).toHaveBeenCalledWith('mv-1', { cueId: undefined });- const one = await request(app).post('/api/music-video/mv-1/lyrics/align').send({ cueId: 'lc-1' });- expect(one.status).toBe(200);- expect(alignProjectLyrics).toHaveBeenLastCalledWith('mv-1', { cueId: 'lc-1' });+ });++ it('cancels a running job and 404s the stream of an unknown one', async () => {+ svc.getProject.mockResolvedValue(alignable);+ let isCancelled;+ alignProjectLyrics.mockImplementationOnce((_id, opts) => new Promise((_resolve, reject) => {+ isCancelled = opts.isCancelled;+ const timer = setInterval(() => {+ if (opts.isCancelled()) { clearInterval(timer); reject(Object.assign(new Error('cancelled'), { canceled: true })); }+ }, 5);+ }));+ const { body: { jobId } } = await request(app).post('/api/music-video/mv-1/lyrics/align').send({});+ expect(isCancelled()).toBe(false);+ const cancel = await request(app).post(`/api/music-video/lyrics/align/${jobId}/cancel`);+ expect(cancel.body).toEqual({ ok: true });+ await vi.waitFor(async () => {+ expect((await request(app).get('/api/music-video/mv-1/active-jobs')).body.alignment).toBeNull();+ });+ expect((await request(app).get('/api/music-video/lyrics/align/nope/events')).status).toBe(404);});it('rejects an unknown body and a cue id the schema cannot store', async () => {diff --git a/server/services/audioMidiTranscription.js b/server/services/audioMidiTranscription.jsindex 272927b0cc..7675369ce5 100644--- a/server/services/audioMidiTranscription.js+++ b/server/services/audioMidiTranscription.js@@ -110,6 +110,15 @@ export function buildMuscriptorArgs({ pythonPath, scriptPath = MUSCRIPTOR_SCRIPT// jobId -> { clients, lastPayload, process }const transcriptionJobs = new Map();+// ownerKey (e.g. a music-video project id) -> running jobId, so a reloaded page can reattach.+const activeByOwner = new Map();++/** The running transcription job id started for `ownerKey`, or null. */+export function getActiveMidiTranscriptionJobId(ownerKey) {+ const jobId = activeByOwner.get(ownerKey);+ return jobId && transcriptionJobs.get(jobId) && !transcriptionJobs.get(jobId).settled ? jobId : null;+}+export const attachMidiTranscriptionSseClient = (jobId, res) => attachSse(transcriptionJobs, jobId, res);/**@@ -146,7 +155,7 @@ export function cancelMidiTranscription(jobId) {* `PATHS.music` so the file federates to peers alongside the project's other* audio (the peer-sync asset manifest only ships known directories).*/-export async function startMidiTranscription({ audioPath, outputName = 'transcription', model, onComplete, destDir = PATHS.uploads }) {+export async function startMidiTranscription({ audioPath, outputName = 'transcription', model, onComplete, destDir = PATHS.uploads, ownerKey = null }) {// Gate on the actual import, not just the binary — a partial venv (binary// present, `muscriptor` not importable) must still 503 so the in-app// installer re-opens to repair it instead of failing later in the sidecar.@@ -162,6 +171,7 @@ export async function startMidiTranscription({ audioPath, outputName = 'transcriconst tempOut = join(tmpdir(), `portos-midi-${jobId}.mid`);const job = { id: jobId, status: 'running', clients: [], process: null, cancelRequested: false, settled: false };transcriptionJobs.set(jobId, job);+ if (ownerKey) activeByOwner.set(ownerKey, jobId);console.log(`🎹 MIDI transcription ${shortId(jobId)} [${resolvedModel}] — ${audioPath}`);(async () => {@@ -240,6 +250,7 @@ export async function startMidiTranscription({ audioPath, outputName = 'transcribroadcastSse(job, frame);} finally {job.settled = true;+ if (ownerKey && activeByOwner.get(ownerKey) === jobId) activeByOwner.delete(ownerKey);await unlink(tempOut).catch(() => {});closeJobAfterDelay(transcriptionJobs, jobId);}diff --git a/server/services/musicVideo/lyricAlign.js b/server/services/musicVideo/lyricAlign.jsindex 08783126d0..282e84a82a 100644--- a/server/services/musicVideo/lyricAlign.js+++ b/server/services/musicVideo/lyricAlign.js@@ -55,9 +55,9 @@ async function decodeSourceToWav(sourcePath) {}// Lazy: the runner pulls the download/spawn helpers only an alignment needs.-async function resolveTranscriber() {+async function resolveTranscriber(onDownloadProgress) {const { resolveAlignmentTranscriber } = await import('./lyricTranscriber.js');- return resolveAlignmentTranscriber();+ return resolveAlignmentTranscriber({ onDownloadProgress });}const audioKey = (project) => `${project?.trackId ?? ''}\u0000${project?.uploadedAudioFilename ?? ''}\u0000${project?.vocalStemFilename ?? ''}`;@@ -83,6 +83,10 @@ function relabeledAnalysis(project, cues) {* against the full vocal so a repeated chorus keeps its own occurrence.*/export async function alignProjectLyrics(projectId, options = {}) {+ const onProgress = options.onProgress || (() => {});+ const checkCancel = () => {+ if (options.isCancelled?.()) throw Object.assign(new Error('cancelled'), { canceled: true });+ };const deps = {getProject,updateProject,@@ -101,9 +105,11 @@ export async function alignProjectLyrics(projectId, options = {}) {const cue = cueId ? cues.find((entry) => entry.id === cueId) : null;if (cueId && !cue) throw new ServerError('That lyric line is no longer on the project.', { status: 404, code: 'NOT_FOUND' });+ onProgress({ stage: 'decoding' });const { path: audioPath, source, mixPath } = await deps.resolveAudio(project);const wav = await deps.decodeAudio(audioPath);const mixWav = mixPath ? await deps.decodeAudio(mixPath) : null;+ checkCancel();const windowed = cue&& typeof cue.startSec === 'number'&& typeof cue.endSec === 'number'@@ -116,15 +122,22 @@ export async function alignProjectLyrics(projectId, options = {}) {const phrases = mixWav ? detectVocalPhrases(vocalPcm(wav)) : [];const windows = mixWav ? phraseWindows(phrases, wavDurationSec(mixWav)) : [];- const transcriber = await deps.resolveTranscriber();+ onProgress({ stage: 'loading-model' });+ const transcriber = await deps.resolveTranscriber((download) => onProgress({ stage: 'downloading-model', percent: download.percent }));let recognized;try {if (mixWav) {recognized = [];+ const inRegion = (window) => !windowed || (window.endSec > windowed.startSec && window.startSec < windowed.endSec);+ const total = windows.filter(inRegion).length;+ let done = 0;// The runner already slices and offsets each result onto the song clock.// Sequential calls bound memory/GPU use and release one runner per song.for (const [index, window] of windows.entries()) {- if (windowed && (window.endSec <= windowed.startSec || window.startSec >= windowed.endSec)) continue;+ if (!inRegion(window)) continue;+ checkCancel();+ onProgress({ stage: 'transcribing', current: done + 1, total, percent: Math.round((done / total) * 100) });+ done += 1;const startSec = Math.max(window.startSec, windowed?.startSec ?? 0);const endSec = Math.min(window.endSec, windowed?.endSec ?? Infinity);const words = await transcriber.transcribe(mixWav, { startSec, endSec, prompt });@@ -139,11 +152,14 @@ export async function alignProjectLyrics(projectId, options = {}) {}recognized = dropNonLyricWords(recognized);} else {+ checkCancel();+ onProgress({ stage: 'transcribing', current: 1, total: 1, percent: 0 });recognized = mergeTranscripts(await transcriber.transcribe(wav, { ...region, prompt }), [], promptCues.map((entry) => entry.text).join('\n'));}} finally {await Promise.resolve(transcriber.release?.()).catch((err) => console.error(`❌ Could not stop the alignment runner: ${err.message}`));}+ checkCancel();if (!mixWav && !windowed && recognized.length === 0) {throw new ServerError('Speech-to-text heard no words in this audio. Check the song has vocals, then try Align words again.',@@ -160,6 +176,7 @@ export async function alignProjectLyrics(projectId, options = {}) {throw new ServerError('The lyric lines changed while they were aligning. Run Align words again.', { status: 409, code: 'LYRIC_ALIGN_TEXT_CHANGED' });}+ onProgress({ stage: 'saving', percent: 100 });const align = (entries) => {const aligned = alignDirectorWords(entries, recognized, { phraseAnchored: Boolean(mixWav) });return mixWav ? snapLineStarts(aligned, phrases.map((phrase) => phrase.startSec), entries) : aligned;diff --git a/server/services/musicVideo/lyricAlign.test.js b/server/services/musicVideo/lyricAlign.test.jsindex 2b1859b808..e793ed014f 100644--- a/server/services/musicVideo/lyricAlign.test.js+++ b/server/services/musicVideo/lyricAlign.test.js@@ -300,6 +300,24 @@ describe('alignProjectLyrics', () => {expect(release).toHaveBeenCalledOnce();});+ it('reports stages and stops without saving when cancelled mid-run (#10155)', async () => {+ const stages = [];+ const transcribe = vi.fn(async () => [{ text: 'walking', startSec: 0.5, endSec: 1 }]);+ const done = harness(transcribe);+ await done.run({ onProgress: (frame) => stages.push(frame.stage) });+ expect(stages).toEqual(['decoding', 'loading-model', 'transcribing', 'saving']);++ const stopped = harness(vi.fn(async () => [{ text: 'walking', startSec: 0.5, endSec: 1 }]));+ let cancel = false;+ await expect(stopped.run({+ isCancelled: () => cancel,+ onProgress: (frame) => { if (frame.stage === 'loading-model') cancel = true; },+ })).rejects.toMatchObject({ canceled: true });+ expect(stopped.transcribe).not.toHaveBeenCalled();+ expect(stopped.updateProject).not.toHaveBeenCalled();+ expect(stopped.release).toHaveBeenCalledOnce();+ });+it('anchors a post-silence line to the stem while transcribing only sequential mix windows', async () => {const record = { ...project, lyricCues: [{ id: 'a', text: 'hello morning', startSec: null, endSec: null },diff --git a/server/services/musicVideo/lyricAlignJob.js b/server/services/musicVideo/lyricAlignJob.jsnew file mode 100644index 0000000000..cb79e73dc6--- /dev/null+++ b/server/services/musicVideo/lyricAlignJob.js@@ -0,0 +1,93 @@+/**+ * Lyric word alignment as a job (#10155).+ *+ * `alignProjectLyrics` can take minutes (audio decode, a ~1.6 GB first-use+ * model download, one whisper pass per phrase window), so the route starts it+ * here and returns a job id; stages stream over SSE with cancel. One job per+ * project at a time — a second request returns the running job, so a double+ * click or a reloaded page never starts a duplicate run.+ *+ * Terminal frames: `{ type: 'complete', project }`, `{ type: 'error', error,+ * code? }` or `{ type: 'canceled' }`. Runs only on an explicit request.+ */++import { randomUUID } from 'crypto';+import { shortId } from '../../lib/fileUtils.js';+import { broadcastSse, attachSseClient as attachSse, closeJobAfterDelay } from '../../lib/sseUtils.js';+import { ServerError } from '../../lib/errorHandler.js';+import { alignProjectLyrics } from './lyricAlign.js';+import { getProject } from './projects.js';++// jobId -> job; projectId -> running jobId+const alignJobs = new Map();+const activeByProject = new Map();++export const attachLyricAlignSseClient = (jobId, res) => attachSse(alignJobs, jobId, res);++/** The project's running alignment job id, or null. */+export function getActiveLyricAlignJobId(projectId) {+ const jobId = activeByProject.get(projectId);+ const job = jobId ? alignJobs.get(jobId) : null;+ return job && !job.settled ? jobId : null;+}++export function cancelLyricAlign(jobId) {+ const job = alignJobs.get(jobId);+ if (!job || job.settled) return false;+ job.cancelRequested = true;+ return true;+}++/**+ * Start aligning a project's lyrics. Resolves `{ jobId }` (plus `reused: true`+ * when one is already running for the project). A request for a different+ * line while one runs also reuses it: the client reattaches rather than+ * queueing a second whisper run over the same song.+ */+export async function startLyricAlign(projectId, { cueId = null, align = alignProjectLyrics } = {}) {+ const running = getActiveLyricAlignJobId(projectId);+ if (running) return { jobId: running, reused: true };+ // Fail with a real status before a job exists, as the blocking route did.+ const project = await getProject(projectId);+ if (!project) throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });+ const cues = Array.isArray(project.lyricCues) ? project.lyricCues : [];+ if (cues.length === 0) throw new ServerError('Add lyric lines before aligning words.', { status: 400, code: 'NO_LYRICS' });+ if (cueId && !cues.some((cue) => cue.id === cueId)) {+ throw new ServerError('That lyric line is no longer on the project.', { status: 404, code: 'NOT_FOUND' });+ }+ // Another request may have started a job while the project was read.+ const raced = getActiveLyricAlignJobId(projectId);+ if (raced) return { jobId: raced, reused: true };+ const jobId = randomUUID();+ const job = { id: jobId, clients: [], settled: false, cancelRequested: false };+ alignJobs.set(jobId, job);+ activeByProject.set(projectId, jobId);+ console.log(`🎤 Lyric alignment ${shortId(jobId)} started for ${projectId}${cueId ? ` (line ${cueId})` : ''}`);++ (async () => {+ try {+ broadcastSse(job, { type: 'progress', stage: 'preparing' });+ const project = await align(projectId, {+ cueId,+ isCancelled: () => job.cancelRequested,+ onProgress: (frame) => broadcastSse(job, { type: 'progress', ...frame }),+ });+ console.log(`✅ Lyric alignment ${shortId(jobId)} complete`);+ broadcastSse(job, { type: 'complete', project });+ } catch (err) {+ if (err?.canceled || job.cancelRequested) {+ console.log(`🛑 Lyric alignment ${shortId(jobId)} cancelled`);+ broadcastSse(job, { type: 'canceled' });+ } else {+ console.error(`❌ Lyric alignment ${shortId(jobId)} failed: ${err?.message || err}`);+ broadcastSse(job, { type: 'error', error: err?.message || String(err), ...(err?.code ? { code: err.code } : {}) });+ }+ } finally {+ job.settled = true;+ if (activeByProject.get(projectId) === jobId) activeByProject.delete(projectId);+ closeJobAfterDelay(alignJobs, jobId);+ }+ })();++ return { jobId };+}diff --git a/server/services/musicVideo/lyricTranscriber.js b/server/services/musicVideo/lyricTranscriber.jsindex 71a077c0c2..fdea0aca0a 100644--- a/server/services/musicVideo/lyricTranscriber.js+++ b/server/services/musicVideo/lyricTranscriber.js@@ -60,6 +60,8 @@ export const WHISPER_MISSING_MESSAGE = 'Aligning words needs whisper.cpp, and no+ 'or run scripts/setup-voice.sh), then click Align words again.';let modelDownload = null;+// Callers sharing the one in-flight download each watch its progress.+const modelDownloadListeners = new Set();async function downloadAlignmentModel(target, { download = streamResumableDownload } = {}) {console.log(`⬇️ Downloading whisper alignment model ${ALIGN_MODEL_FILE} (about 1.6 GB, first alignment only)`);@@ -69,6 +71,7 @@ async function downloadAlignmentModel(target, { download = streamResumableDownlodestPath: target,onBytes: (received, total) => {if (!(total > 0)) return;+ for (const listener of modelDownloadListeners) listener({ received, total, percent: Math.round((received / total) * 100) });const decile = Math.floor((received / total) * 10);if (decile === lastDecile) return;lastDecile = decile;@@ -83,7 +86,7 @@ async function downloadAlignmentModel(target, { download = streamResumableDownlo* use. A `large` model the voice settings already point at is used as is.* Concurrent callers share one download.*/-async function ensureAlignmentModel({ configuredModelPath = null, download } = {}) {+async function ensureAlignmentModel({ configuredModelPath = null, download, onDownloadProgress = null } = {}) {const target = join(alignModelDir(), ALIGN_MODEL_FILE);if (existsSync(target)) return target;if (configuredModelPath && /large/i.test(basename(configuredModelPath)) && existsSync(configuredModelPath)) {@@ -92,10 +95,15 @@ async function ensureAlignmentModel({ configuredModelPath = null, download } = {if (!modelDownload) {modelDownload = downloadAlignmentModel(target, { download }).finally(() => { modelDownload = null; });}- await modelDownload.catch((err) => {+ if (onDownloadProgress) modelDownloadListeners.add(onDownloadProgress);+ try {+ await modelDownload;+ } catch (err) {console.error(`❌ Whisper alignment model download failed: ${err.message}`);throw new ServerError(`Could not download the whisper alignment model: ${err.message}`, { status: 502, code: 'LYRIC_ALIGN_MODEL_DOWNLOAD_FAILED' });- });+ } finally {+ if (onDownloadProgress) modelDownloadListeners.delete(onDownloadProgress);+ }return target;}@@ -262,6 +270,7 @@ export async function resolveAlignmentTranscriber(deps = {}) {runCommand = runStreamingCommand,startServer = startTemporaryWhisperServer,transcribe = sttTranscribe,+ onDownloadProgress = null,} = deps;const cfg = await voiceConfig().catch(() => null);const language = cfg?.stt?.language || 'en';@@ -269,7 +278,7 @@ export async function resolveAlignmentTranscriber(deps = {}) {const cli = await firstOnPath(WHISPER_CLI_NAMES, which);if (cli) {- const modelPath = await ensureModel({ configuredModelPath });+ const modelPath = await ensureModel({ configuredModelPath, onDownloadProgress });return createCliTranscriber({ bin: cli, modelPath, language, run: runCommand });}const endpoint = cfg?.stt?.endpoint || null;@@ -278,7 +287,7 @@ export async function resolveAlignmentTranscriber(deps = {}) {}const serverBin = await which('whisper-server');if (serverBin) {- const modelPath = await ensureModel({ configuredModelPath });+ const modelPath = await ensureModel({ configuredModelPath, onDownloadProgress });const server = await startServer({ bin: serverBin, modelPath });return createEndpointTranscriber({ endpoint: server.endpoint, kind: 'whisper-server', transcribe, release: server.stop });}diff --git a/server/services/musicVideo/lyricTranscriber.test.js b/server/services/musicVideo/lyricTranscriber.test.jsindex a7c26bcd57..761b66148e 100644--- a/server/services/musicVideo/lyricTranscriber.test.js+++ b/server/services/musicVideo/lyricTranscriber.test.js@@ -53,7 +53,7 @@ describe('resolveAlignmentTranscriber', () => {});expect(transcriber.kind).toBe('whisper-cli');expect(probeEndpoint).not.toHaveBeenCalled();- expect(ensureModel).toHaveBeenCalledWith({ configuredModelPath: '/models/ggml-base.en.bin' });+ expect(ensureModel).toHaveBeenCalledWith({ configuredModelPath: '/models/ggml-base.en.bin', onDownloadProgress: null });// A windowed re-align slices the audio and shifts the words onto the song clock.const words = await transcriber.transcribe(encodePcm16Wav(16000 * 10), { startSec: 2, endSec: 8, prompt: 'walking home' });diff --git a/server/services/musicVideo/vocalSeparation.js b/server/services/musicVideo/vocalSeparation.jsindex e8e51916af..1967f32df1 100644--- a/server/services/musicVideo/vocalSeparation.js+++ b/server/services/musicVideo/vocalSeparation.js@@ -147,6 +147,12 @@ const activeByProject = new Map();export const attachVocalSeparationSseClient = (jobId, res) => attachSse(separationJobs, jobId, res);+/** The project's running separation job id, or null. */+export function getActiveVocalSeparationJobId(projectId) {+ const jobId = activeByProject.get(projectId);+ return jobId && separationJobs.get(jobId) && !separationJobs.get(jobId).settled ? jobId : null;+}+export function cancelVocalSeparation(jobId) {const job = separationJobs.get(jobId);if (!job || job.settled) return false;