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: reattach to a running music-video publishing kit build after reload (#9942)

Adam Eivye0327be8dead
diff --git a/client/src/hooks/useMusicVideoPublishKit.js b/client/src/hooks/useMusicVideoPublishKit.js
index 8421bdaeec..bbf3ae9e1e 100644
--- a/client/src/hooks/useMusicVideoPublishKit.js
+++ b/client/src/hooks/useMusicVideoPublishKit.js
@@ -1,4 +1,4 @@
-import { useState } from 'react';
+import { useEffect, useRef, useState } from 'react';
import toast from '../components/ui/Toast';
import {
getMusicVideoProject,
@@ -29,6 +29,8 @@ export default function useMusicVideoPublishKit({ project, replaceProject } = {}
getMusicVideoProject(id, { silent: true }).then(replaceProject).catch(() => {});
};
+ const attachedJobs = useRef(new Set());
+
const job = useSseJobSlot({
startRequest: () => buildMusicVideoPublishKit(projectId, { silent: true }),
eventsUrl: musicVideoPublishKitEventsUrl,
@@ -36,6 +38,11 @@ export default function useMusicVideoPublishKit({ project, replaceProject } = {}
readPercent,
onComplete: (_frame, id) => reload(id),
onKickoffError: (err) => {
+ // A build is already running (another tab, or this one before a reload): adopt it.
+ if (err?.code === 'PUBLISH_KIT_BUILD_IN_PROGRESS' && err.context?.jobId) {
+ job.attach(err.context.jobId, projectId);
+ return true;
+ }
if (err?.status === 409) { toast.error(err.message || 'The publishing kit cannot be built yet'); return true; }
return false;
},
@@ -46,6 +53,14 @@ export default function useMusicVideoPublishKit({ project, replaceProject } = {}
startErrorFallback: 'Failed to start the publishing kit build',
});
+ // Reload or second tab: adopt the build the server says is running. Each jobId is
+ // adopted once, so the stale record can't re-adopt a build that already finished.
+ const runningJobId = project?.activePublishKitBuild?.jobId || null;
+ useEffect(() => {
+ if (!runningJobId || !projectId || attachedJobs.current.has(runningJobId)) return;
+ if (job.attach(runningJobId, projectId)) attachedJobs.current.add(runningJobId);
+ }, [runningJobId, projectId]);
+
const apply = (res) => { if (res?.project) replaceProject(res.project); return res?.project || null; };
const draftCopy = (body) => {
diff --git a/client/src/hooks/useMusicVideoPublishKit.test.jsx b/client/src/hooks/useMusicVideoPublishKit.test.jsx
new file mode 100644
index 0000000000..d854572d73
--- /dev/null
+++ b/client/src/hooks/useMusicVideoPublishKit.test.jsx
@@ -0,0 +1,37 @@
+import { afterEach, beforeEach, expect, it, vi } from 'vitest';
+import { act, renderHook } from '@testing-library/react';
+import useMusicVideoPublishKit from './useMusicVideoPublishKit.js';
+import { MockEventSource, lastEventSource } from '../test/mockEventSource';
+import { buildMusicVideoPublishKit, cancelMusicVideoPublishKit } from '../services/apiMusicVideo.js';
+
+vi.mock('../services/apiMusicVideo.js', () => ({
+ getMusicVideoProject: vi.fn(() => Promise.resolve({ id: 'mv-example' })),
+ buildMusicVideoPublishKit: vi.fn(),
+ musicVideoPublishKitEventsUrl: id => `/events/${id}`,
+ cancelMusicVideoPublishKit: vi.fn(() => Promise.resolve({ ok: true })),
+ draftMusicVideoPublishCopy: vi.fn(),
+ updateMusicVideoPublishCopy: vi.fn(),
+ selectMusicVideoPublishThumbnail: 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('reattaches to a build already running on load, shows progress, and cancels it', async () => {
+ const project = { id: 'mv-example', activePublishKitBuild: { jobId: 'mvpk-running', status: 'running' } };
+ const { result } = renderHook(() => useMusicVideoPublishKit({ project, replaceProject: vi.fn() }));
+ expect(result.current.building).toBe(true);
+ expect(lastEventSource().url).toBe('/events/mvpk-running');
+ act(() => lastEventSource().emit({ type: 'progress', progress: 0.5 }));
+ expect(result.current.progress).toBe(50);
+ act(() => result.current.cancelBuild());
+ expect(cancelMusicVideoPublishKit).toHaveBeenCalledWith('mvpk-running', { silent: true });
+});
+
+it('adopts the running job when Build answers 409 with its jobId', async () => {
+ buildMusicVideoPublishKit.mockRejectedValue(Object.assign(new Error('already running'), { status: 409, code: 'PUBLISH_KIT_BUILD_IN_PROGRESS', context: { jobId: 'mvpk-other' } }));
+ const { result } = renderHook(() => useMusicVideoPublishKit({ project: { id: 'mv-example' }, replaceProject: vi.fn() }));
+ await act(async () => result.current.build());
+ expect(result.current.building).toBe(true);
+ expect(lastEventSource().url).toBe('/events/mvpk-other');
+});
diff --git a/server/routes/musicVideo.js b/server/routes/musicVideo.js
index fe9f6eea87..286a6d7a57 100644
--- a/server/routes/musicVideo.js
+++ b/server/routes/musicVideo.js
@@ -117,7 +117,7 @@ import { generateMusicVideoCode, regenerateMusicVideoCodeSection } from '../serv
import { startExcerptRender, attachExcerptRenderSseClient, cancelExcerptRender } from '../services/musicVideo/excerptRender.js';
import { deleteExcerpt, addReviewNote, editReviewNote, deleteReviewNote } from '../services/musicVideo/excerptService.js';
import { suggestSocialCuts } from '../services/musicVideo/socialCuts.js';
-import { startPublishKitBuild, attachPublishKitSseClient, cancelPublishKitBuild, draftPublishKitCopy, updatePublishKitCopy, selectPublishKitThumbnail } from '../services/musicVideo/publishKit.js';
+import { getActivePublishKitBuild, startPublishKitBuild, attachPublishKitSseClient, cancelPublishKitBuild, draftPublishKitCopy, updatePublishKitCopy, selectPublishKitThumbnail } from '../services/musicVideo/publishKit.js';
import { preparePublishDraft, submitPublishDraft, discardPublishDraft, recordPublishPost } from '../services/musicVideo/publish/index.js';
import { getPublishPlatforms, updatePublishPlatforms, publishHistory } from '../services/musicVideo/publish/platforms.js';
import {
@@ -210,7 +210,9 @@ router.get('/', asyncHandler(async (req, res) => {
router.get('/:id', asyncHandler(async (req, res) => {
const p = await getProject(req.params.id);
if (!p) throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });
- res.json(p);
+ // Transient (never persisted): lets a reloaded page reattach to a running publishing-kit build.
+ const activePublishKitBuild = getActivePublishKitBuild(p.id);
+ res.json(activePublishKitBuild ? { ...p, activePublishKitBuild } : p);
}));
router.post('/', asyncHandler(async (req, res) => {
diff --git a/server/routes/musicVideoPublishKitReattach.test.js b/server/routes/musicVideoPublishKitReattach.test.js
new file mode 100644
index 0000000000..d63d2cc00e
--- /dev/null
+++ b/server/routes/musicVideoPublishKitReattach.test.js
@@ -0,0 +1,58 @@
+/**
+ * Publishing kit reattach (#9942), through the real router: a second build
+ * request answers 409 carrying the running job's id, and the project read
+ * exposes that in-flight build so a reloaded page can reattach.
+ */
+import { describe, it, expect, vi, afterAll } from 'vitest';
+import express from 'express';
+import { request } from '../lib/testHelper.js';
+import { errorMiddleware } from '../lib/errorHandler.js';
+import { makePathsProxy, lazyTempDataRoot, cleanupTempDataRoots } from '../lib/mockPathsDataRoot.js';
+
+vi.mock('../lib/paths.js', async (importOriginal) => makePathsProxy(await importOriginal(), { dataRoot: () => lazyTempDataRoot('mv-publish-kit-reattach-') }));
+vi.mock('../services/settings.js', () => ({ getSettings: vi.fn(async () => ({})) }));
+
+const { default: musicVideoRoutes } = await import('./musicVideo.js');
+const projects = await import('../services/musicVideo/projects.js');
+const ffmpegLib = await import('../lib/ffmpeg.js');
+const { saveHistory } = await import('../services/videoGen/history.js');
+const { PATHS } = await import('../lib/paths.js');
+const { mkdir, writeFile } = await import('node:fs/promises');
+const { join } = await import('node:path');
+
+const app = express();
+app.use(express.json());
+app.use('/api/music-video', musicVideoRoutes);
+app.use(errorMiddleware);
+
+afterAll(() => cleanupTempDataRoots());
+
+describe('publishing kit build reattach (#9942)', () => {
+ it('returns the running jobId on a second build and on the project read', async () => {
+ const { id } = await projects.createProject({ name: 'Example Song' });
+ await mkdir(PATHS.videos, { recursive: true });
+ await writeFile(join(PATHS.videos, 'reattach-master.mp4'), 'placeholder; never encoded');
+ await saveHistory([{ id: 'reattach-render', filename: 'reattach-master.mp4', durationSec: 30 }]);
+ await projects.mutateProjectRecord(id, (current) => ({ project: { ...current, renderHistoryId: 'reattach-render' } }));
+ let release;
+ const gate = new Promise((resolve) => { release = resolve; });
+ const probe = vi.spyOn(ffmpegLib, 'findFfmpeg').mockReturnValue(gate);
+ try {
+ const first = request(app).post(`/api/music-video/${id}/publish-kit/build`).then((r) => r);
+ await vi.waitFor(() => expect(probe).toHaveBeenCalled());
+ const second = await request(app).post(`/api/music-video/${id}/publish-kit/build`);
+ expect(second.status).toBe(409);
+ expect(second.body.code).toBe('PUBLISH_KIT_BUILD_IN_PROGRESS');
+ expect(second.body.context).toMatchObject({ status: 'running', jobId: expect.stringMatching(/^mvpk-/) });
+ const read = await request(app).get(`/api/music-video/${id}`);
+ expect(read.body.activePublishKitBuild).toEqual(second.body.context);
+ release(null);
+ await first;
+ const after = await request(app).get(`/api/music-video/${id}`);
+ expect(after.body.activePublishKitBuild).toBeUndefined();
+ } finally {
+ release(null);
+ probe.mockRestore();
+ }
+ });
+});
diff --git a/server/services/musicVideo/publishKit.js b/server/services/musicVideo/publishKit.js
index 2e4702efa2..a24a51628c 100644
--- a/server/services/musicVideo/publishKit.js
+++ b/server/services/musicVideo/publishKit.js
@@ -34,7 +34,13 @@ const AUDIO_ARGS = ['-c:a', 'aac', '-b:a', '192k', '-movflags', '+faststart'];
export const attachPublishKitSseClient = (jobId, res) => attachSse(jobs, jobId, res);
export const projectPublishKit = (project) => (project?.publishKit && typeof project.publishKit === 'object' ? project.publishKit : {});
-const kitError = (status, code, message) => new ServerError(message, { status, code });
+const kitError = (status, code, message, context) => new ServerError(message, { status, code, ...(context ? { context } : {}) });
+
+/** The build currently running for a project (`{ jobId, status }`), so a reloaded page can reattach. */
+export const getActivePublishKitBuild = (projectId) => {
+ const jobId = projectBuilds.get(projectId);
+ return jobId ? { jobId, status: 'running' } : null;
+};
async function requireProject(projectId) {
const project = await getProject(projectId);
@@ -85,7 +91,8 @@ async function releaseKitFiles(filenames, keep) {
* record carries the result.
*/
export async function startPublishKitBuild(projectId) {
- if (projectBuilds.has(projectId)) throw kitError(409, 'PUBLISH_KIT_BUILD_IN_PROGRESS', 'A publishing kit build is already running for this project');
+ const running = getActivePublishKitBuild(projectId);
+ if (running) throw kitError(409, 'PUBLISH_KIT_BUILD_IN_PROGRESS', 'A publishing kit build is already running for this project', running);
const jobId = `mvpk-${randomUUID()}`;
// Reserve synchronously: final-render lookup and ffmpeg probing can overlap
// another request before there is a background job to put in the registry.
diff --git a/server/services/musicVideo/publishKit.test.js b/server/services/musicVideo/publishKit.test.js
index 808f533fbd..0f0022639a 100644
--- a/server/services/musicVideo/publishKit.test.js
+++ b/server/services/musicVideo/publishKit.test.js
@@ -68,7 +68,8 @@ describe('publishing kit build (#9281)', () => {
await vi.waitFor(() => expect(probe).toHaveBeenCalledTimes(1));
const overlap = kit.startPublishKitBuild(id);
releasePrerequisite(null);
- await expect(overlap).rejects.toMatchObject({ status: 409, code: 'PUBLISH_KIT_BUILD_IN_PROGRESS' });
+ expect(kit.getActivePublishKitBuild(id)).toMatchObject({ status: 'running', jobId: expect.stringMatching(/^mvpk-/) });
+ await expect(overlap).rejects.toMatchObject({ status: 409, code: 'PUBLISH_KIT_BUILD_IN_PROGRESS', context: { jobId: kit.getActivePublishKitBuild(id).jobId, status: 'running' } });
expect(await firstFailure).toMatchObject({ code: 'FFMPEG_MISSING' });
expect(probe).toHaveBeenCalledTimes(1);
// A failed setup must leave the project available for the next attempt.