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

feat: add private music video sharing downloads under 100 MB (#10287)

[._.]/a80e5ab73c2f
diff --git a/client/src/components/musicVideo/SharingCopyPanel.jsx b/client/src/components/musicVideo/SharingCopyPanel.jsx
new file mode 100644
index 0000000000..ee53949449
--- /dev/null
+++ b/client/src/components/musicVideo/SharingCopyPanel.jsx
@@ -0,0 +1,64 @@
+import { useEffect, useState } from 'react';
+import { Download, Loader2 } from 'lucide-react';
+import { getMusicVideoSharingCopy, prepareMusicVideoSharingCopy, musicVideoSharingCopyDownloadUrl } from '../../services/apiMusicVideo.js';
+import { cancelMediaJob } from '../../services/apiMediaJobs.js';
+import useSseJobSlot from '../../hooks/useSseJobSlot.js';
+import useAsyncAction from '../../hooks/useAsyncAction.js';
+import { formatCount } from '../../utils/formatters.js';
+
+/** Keyed by the exact selected final render in ReviewStage. */
+export default function SharingCopyPanel({ projectId }) {
+ const [copy, setCopy] = useState(null);
+ const [error, setError] = useState(null);
+ const [canceling, setCanceling] = useState(false);
+ const [loading, setLoading] = useState(true);
+ const slot = useSseJobSlot({
+ eventsUrl: jobId => `/api/video-gen/${encodeURIComponent(jobId)}/events`,
+ cancelRequest: (jobId, options) => {
+ setCanceling(true);
+ return cancelMediaJob(jobId, options).catch(err => { setCanceling(false); setError(err.message); throw err; });
+ },
+ onSettled: () => setCanceling(false),
+ onComplete: frame => { setCopy(frame.result); setError(null); },
+ onErrorFrame: frame => { setError(frame.error || 'Sharing export failed'); },
+ lostConnectionMessage: 'Sharing export connection lost — use Check export to reconnect',
+ canceledMessage: 'Sharing export cancelled',
+ });
+ const [check, checking] = useAsyncAction(async () => {
+ const state = await getMusicVideoSharingCopy(projectId, { silent: true });
+ setCopy(state.copy);
+ setError(null);
+ if (state.jobId && !slot.active) slot.attach(state.jobId, projectId);
+ });
+ useEffect(() => {
+ let active = true;
+ getMusicVideoSharingCopy(projectId, { silent: true }).then(state => {
+ if (!active) return;
+ setCopy(state.copy);
+ if (state.jobId) slot.attach(state.jobId, projectId);
+ }).catch(err => { if (active) setError(err.message); })
+ .finally(() => { if (active) setLoading(false); });
+ return () => { active = false; };
+ }, [projectId]);
+ const [prepare, preparing] = useAsyncAction(async () => {
+ setError(null);
+ const state = await prepareMusicVideoSharingCopy(projectId, { silent: true });
+ if (state.copy) setCopy(state.copy);
+ else if (state.jobId) slot.attach(state.jobId, projectId);
+ });
+ const busy = loading || preparing || checking;
+ return <div className="mt-3 border-t border-port-border pt-3 space-y-2">
+ <p className="text-xs text-port-text-muted">Private sharing copy · H.264 MP4 · up to 720p · under 100 MB (100,000,000 bytes). Full-quality MP4 remains available above.</p>
+ {copy && <p className="text-xs text-port-text-muted">{formatCount(copy.width)} × {formatCount(copy.height)} · {formatCount(copy.fps)} fps · {formatCount(copy.bytes)} bytes · under 100 MB</p>}
+ <div className="flex flex-wrap items-center gap-2 text-xs">
+ {copy ? <a href={musicVideoSharingCopyDownloadUrl(projectId)} download className="min-h-[44px] inline-flex items-center gap-1 rounded border border-port-border bg-port-bg px-3 py-2 text-port-accent"><Download size={14} /> Download sharing copy</a>
+ : <button type="button" onClick={prepare} disabled={busy || slot.active} className="min-h-[44px] inline-flex items-center gap-1 rounded border border-port-border bg-port-bg px-3 py-2 disabled:opacity-50">
+ {(busy || slot.active) && <Loader2 size={14} className="animate-spin" />}{loading ? 'Checking sharing copy…' : preparing ? 'Preparing sharing copy…' : slot.active ? 'Creating sharing copy…' : 'Prepare sharing copy'}
+ </button>}
+ {slot.active && <button type="button" onClick={slot.cancel} disabled={canceling} className="min-h-[44px] px-2 text-port-warning">{canceling ? 'Cancelling…' : 'Cancel export'}</button>}
+ {!slot.active && <button type="button" onClick={check} disabled={busy} className="min-h-[44px] px-2 text-port-text-muted">Check export</button>}
+ </div>
+ {slot.active && <p role="status" className="text-xs text-port-text-muted">{slot.latest?.message || slot.stage || 'Queued or starting sharing export…'}</p>}
+ {error && <p role="alert" className="text-xs text-port-error break-words">{error}</p>}
+ </div>;
+}
diff --git a/client/src/components/musicVideo/SharingCopyPanel.test.jsx b/client/src/components/musicVideo/SharingCopyPanel.test.jsx
new file mode 100644
index 0000000000..ca8b7cc235
--- /dev/null
+++ b/client/src/components/musicVideo/SharingCopyPanel.test.jsx
@@ -0,0 +1,65 @@
+import { afterEach, beforeEach, expect, it, vi } from 'vitest';
+import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
+import SharingCopyPanel from './SharingCopyPanel.jsx';
+
+const { api, sse } = vi.hoisted(() => ({ api: {
+ get: vi.fn(), prepare: vi.fn(), cancel: vi.fn(),
+}, sse: { latest: null, latestUrl: null, closed: false, isOpen: true } }));
+vi.mock('../../services/apiMusicVideo.js', () => ({
+ getMusicVideoSharingCopy: api.get, prepareMusicVideoSharingCopy: api.prepare,
+ musicVideoSharingCopyDownloadUrl: id => `/api/music-video/${id}/sharing-copy/download`,
+}));
+vi.mock('../../services/apiMediaJobs.js', () => ({ cancelMediaJob: api.cancel }));
+vi.mock('../../hooks/useSseProgress.js', () => ({ useSseProgress: () => sse, isTerminalSseFrame: frame => ['complete', 'error', 'canceled'].includes(frame?.type) }));
+vi.mock('../ui/Toast', () => ({ default: { error: vi.fn(), info: vi.fn(), success: vi.fn() } }));
+beforeEach(() => {
+ vi.clearAllMocks();
+ Object.assign(sse, { latest: null, latestUrl: null, closed: false, isOpen: true });
+ api.get.mockResolvedValue({ copy: null, jobId: null });
+ api.prepare.mockResolvedValue({ jobId: 'job-example' });
+ api.cancel.mockResolvedValue({ ok: true });
+});
+afterEach(cleanup);
+
+it('prepares once, reports the encode stage, and exposes a private download with measured size', async () => {
+ const view = render(<SharingCopyPanel projectId="mv-example" />);
+ await waitFor(() => expect(screen.getByRole('button', { name: 'Prepare sharing copy' })).toBeEnabled());
+ fireEvent.click(screen.getByRole('button', { name: 'Prepare sharing copy' }));
+ await screen.findByRole('button', { name: 'Creating sharing copy…' });
+ expect(api.prepare).toHaveBeenCalledTimes(1);
+ expect(screen.getByRole('button', { name: 'Creating sharing copy…' })).toBeDisabled();
+ sse.latest = { type: 'status', message: 'Encoding sharing copy (pass 2 of 2)' };
+ view.rerender(<SharingCopyPanel projectId="mv-example" />);
+ await screen.findByText('Encoding sharing copy (pass 2 of 2)');
+ sse.latest = { type: 'complete', result: { width: 1280, height: 720, fps: 60, bytes: 90_000_000 } };
+ view.rerender(<SharingCopyPanel projectId="mv-example" />);
+ const download = await screen.findByRole('link', { name: 'Download sharing copy' });
+ expect(download).toHaveAttribute('href', '/api/music-video/mv-example/sharing-copy/download');
+ expect(screen.getByText(/1,280 × 720.*90,000,000 bytes/)).toBeInTheDocument();
+});
+
+it('reattaches after reload, keeps cancellation pending until settlement, and shows cancellation refusal', async () => {
+ api.get.mockResolvedValue({ copy: null, jobId: 'job-recovered' });
+ api.cancel.mockRejectedValueOnce(new Error('Job is already finishing'));
+ const view = render(<SharingCopyPanel projectId="mv-example" />);
+ fireEvent.click(await screen.findByRole('button', { name: 'Cancel export' }));
+ expect(await screen.findByRole('alert')).toHaveTextContent('already finishing');
+ expect(api.cancel).toHaveBeenCalledWith('job-recovered', { silent: true });
+ fireEvent.click(screen.getByRole('button', { name: 'Cancel export' }));
+ expect(await screen.findByRole('button', { name: 'Cancelling…' })).toBeDisabled();
+ expect(screen.queryByRole('link', { name: 'Download sharing copy' })).not.toBeInTheDocument();
+ sse.latest = { type: 'canceled' };
+ view.rerender(<SharingCopyPanel projectId="mv-example" />);
+ expect(await screen.findByRole('button', { name: 'Prepare sharing copy' })).toBeEnabled();
+});
+
+it('isolates a delayed lookup when navigating to another final render', async () => {
+ let resolveOld;
+ api.get.mockImplementationOnce(() => new Promise(resolve => { resolveOld = resolve; }));
+ const view = render(<SharingCopyPanel key="old" projectId="mv-old" />);
+ view.rerender(<SharingCopyPanel key="new" projectId="mv-new" />);
+ await screen.findByRole('button', { name: 'Prepare sharing copy' });
+ resolveOld({ copy: { bytes: 10, width: 10, height: 10, fps: 10 }, jobId: 'old-job' });
+ await waitFor(() => expect(screen.queryByRole('link', { name: 'Download sharing copy' })).not.toBeInTheDocument());
+ expect(screen.queryByRole('button', { name: 'Cancel export' })).not.toBeInTheDocument();
+});
diff --git a/client/src/components/musicVideo/stages/ReviewStage.jsx b/client/src/components/musicVideo/stages/ReviewStage.jsx
index 895f6161da..7a9d88ae81 100644
--- a/client/src/components/musicVideo/stages/ReviewStage.jsx
+++ b/client/src/components/musicVideo/stages/ReviewStage.jsx
@@ -1,3 +1,4 @@
+import SharingCopyPanel from '../SharingCopyPanel.jsx';
import DependencyImpactPanel from '../DependencyImpactPanel.jsx';
import RenderStatusPanel, { RenderFailure } from '../RenderStatusPanel.jsx';
import ExcerptPanel from '../ExcerptPanel.jsx';
@@ -37,6 +38,7 @@ export default function ReviewStage({ board }) {
finalVideo={finalVideo}
onOpenPreview={board.openPreview}
/>
+ {project.renderHistoryId && <SharingCopyPanel key={`${project.id}:${project.renderHistoryId}`} projectId={project.id} />}
</StageSection>
<StageSection title="Excerpt and revision tools" defaultOpen={!hasDraft || excerpts.rendering}>
diff --git a/client/src/pages/MusicVideo.test.jsx b/client/src/pages/MusicVideo.test.jsx
index 08f4d4ba27..582bc9e496 100644
--- a/client/src/pages/MusicVideo.test.jsx
+++ b/client/src/pages/MusicVideo.test.jsx
@@ -77,6 +77,9 @@ vi.mock('../services/apiMusicVideo.js', () => ({
musicVideoVocalSeparationEventsUrl: (jobId) => `/api/music-video/vocal-stem/separate/${jobId}/events`,
cancelMusicVideoVocalSeparation: vi.fn(async () => ({ ok: true })),
getMusicVideoActiveRender: vi.fn(async () => ({ jobId: null })),
+ getMusicVideoSharingCopy: vi.fn(async () => ({ copy: null, jobId: null })),
+ prepareMusicVideoSharingCopy: vi.fn(async () => ({ jobId: 'sharing-example' })),
+ musicVideoSharingCopyDownloadUrl: id => `/api/music-video/${id}/sharing-copy/download`,
getMusicVideoSceneJobs: vi.fn(async () => ({ jobs: [] })),
renderMusicVideoProject: vi.fn(async () => ({ jobId: 'job-1' })),
musicVideoRenderEventsUrl: (jobId) => `/api/music-video/render/${jobId}/events`,
@@ -715,9 +718,14 @@ describe('MusicVideo render control (#1760)', () => {
expect(renderBtn).toHaveProperty('disabled', true);
});
- it('shows the rendered-video link once a project carries a renderHistoryId', async () => {
+ it('keeps full-quality and sharing controls together in the compact native-final disclosure', async () => {
await openProject({ ...PROJECT_WITH_CLIP, renderHistoryId: 'rh-9' }, 'review');
- await screen.findByText(/Download MP4/i);
+ const fullQuality = await screen.findByRole('link', { name: /Download MP4/i });
+ const sharing = await screen.findByRole('button', { name: 'Prepare sharing copy' });
+ const disclosure = fullQuality.closest('details');
+ expect(disclosure).toHaveAttribute('id', 'mv-final-video');
+ expect(disclosure).toContainElement(sharing);
+ expect(sharing).toHaveClass('min-h-[44px]');
const link = await screen.findByText(/Open in Media History/i);
// Media History matches video items by their `video:<id>` key via ?preview=.
expect(link.closest('a').getAttribute('href')).toContain('preview=video%3Arh-9');
diff --git a/client/src/services/apiMusicVideo.js b/client/src/services/apiMusicVideo.js
index c93308365c..a67e6d45b3 100644
--- a/client/src/services/apiMusicVideo.js
+++ b/client/src/services/apiMusicVideo.js
@@ -500,3 +500,8 @@ export const actOnMusicVideoSongRevision = (id, action, data, options = {}) => {
};
export const importMusicVideoDocumentShots = (id, body, options = {}) => request(`/music-video/${encodeURIComponent(id)}/production-review/document-shots`, { method: 'POST', body: JSON.stringify(body), ...options });
+
+// Source-bound private sharing export; the server rejects stale download URLs.
+export const getMusicVideoSharingCopy = (id, options = {}) => request(`/music-video/${encodeURIComponent(id)}/sharing-copy`, options);
+export const prepareMusicVideoSharingCopy = (id, options = {}) => request(`/music-video/${encodeURIComponent(id)}/sharing-copy`, { method: 'POST', ...options });
+export const musicVideoSharingCopyDownloadUrl = (id) => `/api/music-video/${encodeURIComponent(id)}/sharing-copy/download`;
diff --git a/docs/README.md b/docs/README.md
index cc72b7bd06..a4350f15fa 100644
--- a/docs/README.md
+++ b/docs/README.md
@@ -51,6 +51,7 @@ Index of everything under `docs/`. Start with the [root README](../README.md) fo
## Feature deep dives (`features/`)
+- [Music Video private sharing copy](./features/music-video-sharing-copy.md) — source-bound 720p downloads strictly under 100 MB, private local export and media queue lifecycle
- [Music Video making-of export](./features/music-video-making-of.md) — local multi-variant planning packages, inventory previews, source planning retention and publication boundaries
Start with the [product surface map](./features/product-surfaces.md) for a complete, user-facing inventory of the application. The focused guides below explain the features with their own operating contracts.
diff --git a/docs/features/music-video-sharing-copy.md b/docs/features/music-video-sharing-copy.md
new file mode 100644
index 0000000000..4c6c0c693b
--- /dev/null
+++ b/docs/features/music-video-sharing-copy.md
@@ -0,0 +1,53 @@
+# Music Video private sharing copy
+
+Music Video → Review & Export → Final render offers **Prepare sharing copy**.
+When ready, **Download sharing copy** shows the measured dimensions, frame rate
+and byte size. The existing full-quality MP4 download remains available.
+This action downloads locally; it does not send messages or publish anything.
+
+The local `video-sharing` media job uses the existing durable queue, maintenance
+admission, supervised child processes, SSE status, cancellation and boot cleanup.
+Reloading reattaches to an active job. After a connection failure, **Check export**
+recovers the saved result or reconnects. Repeated requests reuse the active job
+or verified saved copy. Cancellation remains pending until process settlement;
+once file publication starts it is refused as already finishing.
+
+The export uses two-pass H.264 with AAC at 128 kbps, at most 1280×720, preserves
+aspect ratio and frame rates up to 60 fps, and never upscales. A duration-based
+95 MB stream budget reserves room for container overhead. An oversized result
+gets one retry at a lower bitrate. Only a full-length file strictly below
+100,000,000 bytes is offered; failed or cancelled work removes partial files.
+Encoding uses two threads and a 30-minute timeout per pass. Sources over one
+hour, unreadable sources and duration budgets below the minimum usable bitrate
+are refused with an actionable error.
+An observer error with a live process retains ownership until physical exit.
+If owned-file cleanup fails, maintenance retains a recovery blocker instead of
+claiming that the export has fully drained.
+
+The server resolves only the project's selected final history entry, refuses
+symlinks and unsafe filenames, and binds the copy to its history ID and SHA-256.
+The copy's own hash and size are verified before reuse/download. Selecting a
+new final or changing the existing final's bytes invalidates it. No original
+file or history entry is overwritten. Publishing-kit metadata stores the result
+on the existing project record; missing files on another machine are cache misses.
+Downloads retain and stream the exact descriptor used to verify the copy rather
+than reopening its pathname. It closes after completion, refusal, disconnect or
+stream error. GET/HEAD, single byte ranges (including suffix ranges), If-Range,
+If-Match, If-Unmodified-Since and freshness conditions are supported; malformed
+or multipart ranges fall back to the full response. Unsatisfiable ranges return
+416, failed preconditions 412 and fresh conditional requests 304.
+
+API:
+
+- `GET /api/music-video/:id/sharing-copy` — verified `copy` or null, plus active
+ `jobId`/`status` when present.
+- `POST /api/music-video/:id/sharing-copy` — return a cached copy, reuse an active
+ job or enqueue a new job. No arbitrary path, codec or process arguments are accepted.
+- `GET /api/music-video/:id/sharing-copy/download` — source-validated attachment;
+ stale/missing copies return a conflict requiring a new preparation.
+- Existing `/api/video-gen/:jobId/events` and `/api/media-jobs/:jobId/cancel`
+ provide the media queue's SSE and cancellation contracts.
+
+There is no native cache-registration endpoint for externally prepared MP4s.
+Development-file uploads retain their existing media policy and do not register
+a sharing derivative or replace the canonical final.
diff --git a/server/lib/backupAssetOwners.js b/server/lib/backupAssetOwners.js
index 0560820a13..18bf8c7656 100644
--- a/server/lib/backupAssetOwners.js
+++ b/server/lib/backupAssetOwners.js
@@ -120,6 +120,7 @@ export const BACKUP_ASSET_OWNERS = Object.freeze([
modules: [
'services/musicVideo/render.js', 'services/musicVideo/excerptRender.js',
'services/musicVideo/publishKit.js', 'services/musicVideo/compositionDocument.js',
+ 'services/musicVideo/sharingCopy.js',
],
},
{
diff --git a/server/routes/musicVideo.js b/server/routes/musicVideo.js
index 776e21bb50..8d8ab373b1 100644
--- a/server/routes/musicVideo.js
+++ b/server/routes/musicVideo.js
@@ -10,6 +10,7 @@
import { existsSync } from 'fs';
import { unlink } from 'fs/promises';
+import { pipeline } from 'stream/promises';
import { Router } from 'express';
import { musicVideoProjectListQuerySchema, musicVideoProductionDraftSchema, musicVideoProductionApprovalSchema, musicVideoProductionProofSchema, musicVideoProductionImportSchema, musicVideoProductionFeedbackSchema, musicVideoProductionFeedbackResolutionSchema, musicVideoProductionReviseSchema, musicVideoProductionRevertSchema } from '../lib/musicVideoValidation.js';
import { productionReadiness } from '../services/musicVideo/productionReview.js';
@@ -114,6 +115,7 @@ import {
import { analyzeAudioFileManual, buildManualAnalysisFromCached } from '../services/musicVideo/audioAnalysis.js';
import { analyzeProjectSong, resolveProjectAudioPath } from '../services/musicVideo/projectAudio.js';
import { listInFlightSceneJobs } from '../services/musicVideo/sceneJobs.js';
+import { getSharingCopy, prepareSharingCopy, sharingCopyDownload } from '../services/musicVideo/sharingCopy.js';
import { renderMusicVideo, attachRenderSseClient, cancelRender, getActiveRenderJobId } from '../services/musicVideo/render.js';
import { prepareCodeRender } from '../services/musicVideo/codeRender.js';
import { generateMusicVideoCode, regenerateMusicVideoCodeSection } from '../services/musicVideo/codeGeneration.js';
@@ -577,6 +579,54 @@ router.post('/transcribe-midi/:jobId/cancel', (req, res) => {
});
// --- Render (#1760, Phase 2) ---
+// Private local export; no publication or provider submission.
+router.get('/:id/sharing-copy', asyncHandler(async (req, res) => {
+ res.json(await getSharingCopy(req.params.id));
+}));
+router.post('/:id/sharing-copy', asyncHandler(async (req, res) => {
+ res.status(202).json(await prepareSharingCopy(req.params.id));
+}));
+router.get('/:id/sharing-copy/download', asyncHandler(async (req, res) => {
+ const { file, copy, modifiedAt } = await sharingCopyDownload(req.params.id);
+ let stream;
+ const abort = () => { if (!res.writableFinished) stream?.destroy(); };
+ try {
+ if (req.aborted || res.destroyed) return;
+ const etag = `"${copy.hash}"`;
+ res.attachment(copy.filename).type('video/mp4');
+ res.set({ 'Cache-Control': 'private, no-store', 'Accept-Ranges': 'bytes', ETag: etag, 'Last-Modified': modifiedAt.toUTCString() });
+ const matches = value => value === '*' || value?.split(',').some(tag => tag.trim() === etag);
+ const unmodified = Date.parse(req.get('If-Unmodified-Since'));
+ if ((req.get('If-Match') && !matches(req.get('If-Match'))) || (!req.get('If-Match') && Number.isFinite(unmodified) && Math.floor(modifiedAt.getTime() / 1000) > Math.floor(unmodified / 1000))) {
+ res.status(412).end(); return;
+ }
+ if (req.fresh) { res.status(304).end(); return; }
+ let start = 0; let end = copy.bytes - 1;
+ const ifRange = req.get('If-Range');
+ const rangeCurrent = !ifRange || ifRange === etag || (!ifRange.includes('"') && Number.isFinite(Date.parse(ifRange)) && modifiedAt.getTime() <= Date.parse(ifRange) + 999);
+ if (req.get('Range') && rangeCurrent) {
+ const ranges = req.range(copy.bytes, { combine: true });
+ if (ranges === -1) { res.set('Content-Range', `bytes */${copy.bytes}`); res.status(416).end(); return; }
+ // Like res.download, malformed/non-byte/multipart ranges fall back to 200.
+ if (Array.isArray(ranges) && ranges.type === 'bytes' && ranges.length === 1) {
+ ({ start, end } = ranges[0]);
+ res.status(206).set('Content-Range', `bytes ${start}-${end}/${copy.bytes}`);
+ }
+ }
+ res.set('Content-Length', String(end - start + 1));
+ if (req.method === 'HEAD') { res.end(); return; }
+ stream = file.createReadStream({ start, end, autoClose: false });
+ res.once('close', abort);
+ req.once('aborted', abort);
+ await pipeline(stream, res);
+ } finally {
+ res.off('close', abort);
+ req.off('aborted', abort);
+ stream?.destroy();
+ await file.close();
+ }
+}));
+
// Assemble the scenes' i2v clips into one MP4 over the track as the master audio
// bed. Kickoff returns { jobId }; progress streams over SSE (mirrors
// videoTimeline). Per-project mutex returns 409 with the live jobId for re-attach.
diff --git a/server/routes/musicVideo.test.js b/server/routes/musicVideo.test.js
index c6bb1cebcc..179d0e848c 100644
--- a/server/routes/musicVideo.test.js
+++ b/server/routes/musicVideo.test.js
@@ -2,6 +2,15 @@ import { describe, it, expect, vi, beforeEach } from 'vitest';
import express from 'express';
import { request } from '../lib/testHelper.js';
import { ServerError } from '../lib/errorHandler.js';
+import { mkdtemp, open, rename, rm, symlink, writeFile } from 'fs/promises';
+import { join } from 'path';
+import { tmpdir } from 'os';
+import { request as httpRequest } from 'http';
+import { Readable } from 'stream';
+import { startLoopbackServer, closeLoopbackServer } from '../lib/testHelper.js';
+
+vi.mock('../services/musicVideo/sharingCopy.js', () => ({ getSharingCopy: vi.fn(), prepareSharingCopy: vi.fn(), sharingCopyDownload: vi.fn() }));
+import { sharingCopyDownload } from '../services/musicVideo/sharingCopy.js';
vi.mock('../services/musicVideo/projects.js', () => ({
listProjects: vi.fn(async () => [{ id: 'mv-1', name: 'A' }]),
@@ -916,3 +925,91 @@ it('validates a project moodboard as up to eight bounded gallery images', async
expect((await request(app).patch('/api/music-video/mv-1').send({ styleReferences: refs })).status).toBe(400);
}
});
+
+describe('sharing downloads retain verified descriptor ownership', () => {
+ const url = '/api/music-video/example/sharing-copy/download';
+ async function fixture(run, size = 32) {
+ const root = await mkdtemp(join(tmpdir(), 'sharing-http-'));
+ const path = join(root, 'copy.mp4');
+ await writeFile(path, Buffer.from('0123456789abcdef'.repeat(Math.ceil(size / 16)).slice(0, size)));
+ const file = await open(path, 'r');
+ const modifiedAt = new Date('2026-01-01T00:00:00Z');
+ const copy = { filename: 'sharing.mp4', bytes: size, hash: 'a'.repeat(64) };
+ const app = express();
+ app.use('/api/music-video', musicVideoRoutes);
+ sharingCopyDownload.mockResolvedValue({ file, copy, modifiedAt });
+ try { await run({ app, file, path, root, etag: `"${copy.hash}"` }); }
+ finally { await file.close(); await rm(root, { recursive: true, force: true }); }
+ }
+
+ it.each(['replacement', 'symlink'])('streams the verified descriptor after a %s pathname swap', async swap => fixture(async ({ app, file, path, root }) => {
+ await rename(path, `${path}.old`);
+ const different = join(root, 'different.mp4');
+ await writeFile(different, 'replacement bytes');
+ if (swap === 'symlink') await symlink(different, path);
+ else await writeFile(path, 'replacement bytes');
+ const response = await request(app).get(url);
+ expect(response.status).toBe(200);
+ expect(response.text).toBe('0123456789abcdef0123456789abcdef');
+ expect(response.headers['content-disposition']).toContain('attachment; filename="sharing.mp4"');
+ expect(response.headers['content-type']).toContain('video/mp4');
+ expect(response.headers['cache-control']).toBe('private, no-store');
+ await vi.waitFor(() => expect(file.fd).toBe(-1));
+ }));
+
+ it.each([
+ ['HEAD', {}, 200, ''],
+ ['GET', { Range: 'bytes=2-5' }, 206, '2345'],
+ ['GET', { Range: 'bytes=-4' }, 206, 'cdef'],
+ ['GET', { Range: 'bytes=999-' }, 416, ''],
+ ['GET', { Range: 'invalid' }, 200, '0123456789abcdef0123456789abcdef'],
+ ['GET', { Range: 'bytes=0-1,4-5' }, 200, '0123456789abcdef0123456789abcdef'],
+ ['GET', { Range: 'bytes=2-5', 'If-Range': '"outdated"' }, 200, '0123456789abcdef0123456789abcdef'],
+ ['GET', { 'If-Match': '"outdated"' }, 412, ''],
+ ['GET', { 'If-Unmodified-Since': 'Wed, 01 Jan 2025 00:00:00 GMT' }, 412, ''],
+ ])('supports %s %j with status %i and closes the descriptor', async (method, headers, status, text) => fixture(async ({ app, file }) => {
+ let query = method === 'HEAD' ? request(app).head(url) : request(app).get(url);
+ for (const [key, value] of Object.entries(headers)) query = query.set(key, value);
+ const response = await query;
+ expect(response.status).toBe(status);
+ expect(response.text).toBe(text);
+ if (status === 206) expect(response.headers['content-range']).toMatch(/^bytes \d+-\d+\/32$/);
+ if (status === 416) expect(response.headers['content-range']).toBe('bytes */32');
+ await vi.waitFor(() => expect(file.fd).toBe(-1));
+ }));
+
+ it('supports conditional 304 and a current If-Range without reopening the path', async () => {
+ await fixture(async ({ app, file, etag }) => {
+ const response = await request(app).get(url).set('If-None-Match', etag).set('Cache-Control', 'max-age=0');
+ expect(response.status).toBe(304);
+ expect(response.text).toBe('');
+ await vi.waitFor(() => expect(file.fd).toBe(-1));
+ });
+ await fixture(async ({ app, file, etag }) => {
+ const response = await request(app).get(url).set('Range', 'bytes=0-3').set('If-Range', etag);
+ expect(response.status).toBe(206);
+ expect(response.text).toBe('0123');
+ await vi.waitFor(() => expect(file.fd).toBe(-1));
+ });
+ });
+
+ it('closes the descriptor on client disconnect and stream error', async () => {
+ await fixture(async ({ app, file }) => {
+ const server = await startLoopbackServer(app);
+ try {
+ await new Promise((resolve, reject) => {
+ const req = httpRequest(`http://127.0.0.1:${server.address().port}${url}`, response => {
+ response.once('data', () => { req.destroy(); response.destroy(); resolve(); });
+ });
+ req.once('error', reject); req.end();
+ });
+ await vi.waitFor(() => expect(file.fd).toBe(-1));
+ } finally { server.closeAllConnections(); await closeLoopbackServer(server); }
+ }, 5_000_000);
+ await fixture(async ({ app, file }) => {
+ vi.spyOn(file, 'createReadStream').mockImplementation(() => new Readable({ read() { this.destroy(new Error('Synthetic read failure')); } }));
+ await expect(request(app).get(url)).rejects.toThrow();
+ await vi.waitFor(() => expect(file.fd).toBe(-1));
+ });
+ });
+});
diff --git a/server/services/README.md b/server/services/README.md
index 59cdf009fe..856be1a669 100644
--- a/server/services/README.md
+++ b/server/services/README.md
@@ -11,6 +11,7 @@ image-generation paths below are useful entry points when tracing render jobs.
| `databaseMaintenanceProducers.js` | Internal one-use coordinator stage: retain producer identity, stop this install's PM2 CoS/server, and verify fresh readback while admission remains fenced. |
| `databaseMaintenanceQuiescence.js` | Internal coordinator stage after producer shutdown: terminate verified running detached-writer groups, prove every registry record quiescent from process-table evidence, archive it with the operation, and refuse pending, legacy, orphaned, ambiguous or unregistered writers. |
| `imageGen/prepareParams.js` | Shared image request preparation and the canonical local image model selector. Use `selectLocalImageModelFromSettings()` for model identity and `resolveLocalImageModel()` when the caller must also enforce local runtime, hardware, and edit-image requirements. |
+| `musicVideo/sharingCopy.js` | Source-hashed private sharing MP4s: queued 720p H.264/AAC export, strict decimal 100 MB cap, supervised cancellation, verified download and owned-file cleanup. |
| `mediaJobQueue/index.js` | Owns admission, lanes, durability and terminal effects; `videoHolds.js` returns local-video cohort preparation results and owns circuit breakers, while `videoGen/modelSelection.js` owns model-selection policy. |
| `imageGen/index.js` | Mode-aware image backend dispatcher and shared image-generation helpers. Direct queue consumers still resolve local model identity before enqueueing. |
| `superColliderRuntime.js` | Managed SuperCollider runtime I/O (#9412): Docker probe, recipe-hash-stamped image build, `runSuperColliderContainer` (contained `sclang` run with forced container removal), the synthetic render probe and its cached evidence, `getSuperColliderStatus` and idempotent `setupSuperColliderRuntime`. Never runs at boot. |
diff --git a/server/services/mediaJobQueue/index.js b/server/services/mediaJobQueue/index.js
index 510387459a..e1d9ab2697 100644
--- a/server/services/mediaJobQueue/index.js
+++ b/server/services/mediaJobQueue/index.js
@@ -174,7 +174,7 @@ async function safeUnlinkUpload(path) {
// edit to one of them rather than a mode string slipping through.
// 'supercollider' (#9413) is likewise local-only: it executes untrusted source
// inside this machine's verified container, so no peer map names it.
-export const JOB_KINDS = Object.freeze(['video', 'video-upscale', 'html-composition', 'image', 'training', 'audio', 'supercollider']);
+export const JOB_KINDS = Object.freeze(['video', 'video-upscale', 'video-sharing', 'html-composition', 'image', 'training', 'audio', 'supercollider']);
export const JOB_STATUSES = Object.freeze(['queued', 'running', 'completed', 'failed', 'canceled']);
// Returns a Promise that resolves to the gen module for the given job's
@@ -189,6 +189,7 @@ function getGenModuleForJob(job) {
if (isRemoteMediaJob(job)) return REMOTE_MEDIA_MODULES[job.kind]();
if (job.kind === 'html-composition') return import('../htmlComposition/index.js');
if (job.kind === 'video-upscale') return import('../videoGen/upscaleJob.js');
+ if (job.kind === 'video-sharing') return import('../musicVideo/sharingCopy.js');
if (job.kind === 'video' && job.params?.mode === IMAGE_GEN_MODE.GROK) return import('../videoGen/grok.js');
if (job.kind === 'video' && job.params?.mode === VIDEO_GEN_MODE.FAL) return import('../videoGen/fal.js');
if (job.kind === 'video' && job.params?.mode === VIDEO_GEN_MODE.REACTOR) return import('../videoGen/reactor.js');
@@ -702,6 +703,10 @@ export async function initMediaJobQueue() {
error: 'interrupted by restart',
completedAt: new Date().toISOString(),
};
+ if (j.kind === 'video-sharing') {
+ const { cleanupInterruptedSharingCopy } = await import('../musicVideo/sharingCopy.js');
+ await cleanupInterruptedSharingCopy(j.id).catch(err => console.error(`❌ Interrupted sharing copy cleanup failed: ${err.message}`));
+ }
archive.push(failed);
restartedFailedIds.push(failed.id);
// The failed job will never reach the worker's cleanup, so any
@@ -1408,7 +1413,7 @@ async function runJobLifecycle(job, markDispatched, permit) {
await resolveLiveParams(job, safeParams);
- const emitter = job.kind === 'video' || job.kind === 'video-upscale' || job.kind === 'html-composition' ? videoGenEvents
+ const emitter = job.kind === 'video' || job.kind === 'video-upscale' || job.kind === 'video-sharing' || job.kind === 'html-composition' ? videoGenEvents
: job.kind === 'training' ? trainingEvents
: job.kind === 'audio' || job.kind === 'supercollider' ? audioGenEvents
: imageGenEvents;
@@ -1446,7 +1451,7 @@ async function runJobLifecycle(job, markDispatched, permit) {
if (isCloudImageJob(job)) return WATCHDOG_CODEX_MS;
// An upscale is a single GPU render with no chunking, so it takes the
// video idle window flat rather than the chunk-scaled one.
- if (job.kind === 'video-upscale') return WATCHDOG_VIDEO_MS;
+ if (job.kind === 'video-upscale' || job.kind === 'video-sharing') return WATCHDOG_VIDEO_MS;
if (job.kind === 'video') return WATCHDOG_VIDEO_MS * Math.max(1, Number(safeParams.chunks) || 1);
if (job.kind === 'training') return WATCHDOG_TRAINING_MS;
if (job.kind === 'audio') return WATCHDOG_AUDIO_MS;
@@ -1552,6 +1557,7 @@ async function runJobLifecycle(job, markDispatched, permit) {
: job.kind === 'video' ? mod.generateVideo(request)
: job.kind === 'html-composition' ? mod.renderComposition(request)
: job.kind === 'video-upscale' ? mod.runVideoUpscale(request)
+ : job.kind === 'video-sharing' ? mod.runSharingCopy(request)
: job.kind === 'training' ? mod.runTraining(request)
: job.kind === 'audio' ? mod.generateAudio(request)
: job.kind === 'supercollider' ? mod.renderSuperCollider(request)
diff --git a/server/services/mediaJobQueue/index.test.js b/server/services/mediaJobQueue/index.test.js
index 51244dac11..3346d0aea2 100644
--- a/server/services/mediaJobQueue/index.test.js
+++ b/server/services/mediaJobQueue/index.test.js
@@ -84,6 +84,8 @@ const stubs = {
hasSurvivingTrainer: vi.fn(async () => false),
runVideoUpscale: vi.fn(() => new Promise(() => {})),
cancelVideoUpscale: vi.fn(),
+ runSharingCopy: vi.fn(async () => ({})),
+ cancelSharingCopy: vi.fn(() => true),
renderComposition: vi.fn(async () => ({})),
cancelComposition: vi.fn(),
renderSuperCollider: vi.fn(() => new Promise(() => {})),
@@ -103,6 +105,12 @@ vi.mock('../videoGen/local.js', () => ({
cancel: (...args) => stubs.cancelVideo(...args),
}));
+vi.mock('../musicVideo/sharingCopy.js', () => ({
+ runSharingCopy: (...args) => stubs.runSharingCopy(...args),
+ cancel: (...args) => stubs.cancelSharingCopy(...args),
+ cleanupInterruptedSharingCopy: vi.fn(async () => {}),
+}));
+
vi.mock('../htmlComposition/index.js', () => ({
renderComposition: (...args) => stubs.renderComposition(...args),
cancel: (...args) => stubs.cancelComposition(...args),
@@ -390,6 +398,50 @@ describe('mediaJobQueue', () => {
await waitFor(() => mediaJobQueue.getJob(jobId)?.status === 'canceled');
});
+ it('dispatches private sharing copies through the serialized lane and preserves physical cancellation settlement', async () => {
+ stubs.runSharingCopy.mockImplementation(() => new Promise(() => {}));
+ stubs.cancelSharingCopy.mockReturnValue(true);
+ const params = { sharingProjectId: 'mv-example', renderHistoryId: 'final-example', sourceHash: 'a'.repeat(64) };
+ const { jobId } = await mediaJobQueue.enqueueJob({ kind: 'video-sharing', params });
+ await waitFor(() => stubs.runSharingCopy.mock.calls.length === 1);
+ expect(stubs.runSharingCopy).toHaveBeenCalledWith(expect.objectContaining({ ...params, jobId }));
+ expect(mediaJobQueue.isRemoteMediaJob(mediaJobQueue.getJob(jobId))).toBe(false);
+ expect(mediaJobQueue.laneConcurrencyFor(mediaJobQueue.getJob(jobId))).toBe(1);
+ videoGenEvents.emit('status', { generationId: jobId, message: 'Encoding sharing copy' });
+ expect(mediaJobQueue.getJob(jobId).statusMsg).toBe('Encoding sharing copy');
+ expect(await mediaJobQueue.cancelJob(jobId)).toMatchObject({ ok: true, status: 'canceling' });
+ expect(stubs.cancelSharingCopy).toHaveBeenCalledWith(jobId);
+ expect(mediaJobQueue.getJob(jobId).status).toBe('running');
+ videoGenEvents.emit('failed', { generationId: jobId, error: 'Sharing export cancelled' });
+ await waitFor(() => mediaJobQueue.getJob(jobId)?.status === 'canceled');
+ });
+
+ it('keeps sharing exports queued during maintenance and draining until process settlement', async () => {
+ const { maintenance } = await import('../../lib/maintenanceAdmission.js');
+ let releaseProcess;
+ stubs.runSharingCopy.mockImplementation(() => new Promise(resolve => { releaseProcess = resolve; }));
+ stubs.cancelSharingCopy.mockReturnValue(true);
+ const params = { sharingProjectId: 'mv-example', renderHistoryId: 'final-example', sourceHash: 'a'.repeat(64) };
+ const first = await mediaJobQueue.enqueueJob({ kind: 'video-sharing', params });
+ await waitFor(() => stubs.runSharingCopy.mock.calls.length === 1);
+ const { hold } = maintenance.begin({ reason: 'Sharing fixture drain', owner: 'Operator' });
+ try {
+ const second = await mediaJobQueue.enqueueJob({ kind: 'video-sharing', params: { ...params, sharingProjectId: 'mv-other' } });
+ await mediaJobQueue.cancelJob(first.jobId);
+ expect(maintenance.status().state).toBe('draining');
+ expect(stubs.runSharingCopy).toHaveBeenCalledTimes(1);
+ expect(mediaJobQueue.getJob(second.jobId).status).toBe('queued');
+ videoGenEvents.emit('failed', { generationId: first.jobId, error: 'Sharing export cancelled' });
+ await waitFor(() => mediaJobQueue.getJob(first.jobId).status === 'canceled');
+ expect(maintenance.status().state).toBe('draining');
+ releaseProcess();
+ await waitFor(() => maintenance.status().state === 'ready');
+ expect(stubs.runSharingCopy).toHaveBeenCalledTimes(1);
+ expect(mediaJobQueue.getJob(first.jobId).status).toBe('canceled');
+ await mediaJobQueue.cancelJob(second.jobId);
+ } finally { releaseProcess?.(); maintenance.resume({ id: hold.id, revision: hold.revision }); }
+ });
+
// SuperCollider renders (#9413) are local-only audio jobs: progress rides the
// audio bus, and a cancel reaches the render module so it can remove the container.
it('dispatches SuperCollider renders locally with their frozen source and cancels through the render module', async () => {
diff --git a/server/services/musicVideo/sharingCopy.js b/server/services/musicVideo/sharingCopy.js
new file mode 100644
index 0000000000..03f969fc70
--- /dev/null
+++ b/server/services/musicVideo/sharingCopy.js
@@ -0,0 +1,286 @@
+/** Private, source-bound sharing exports run through the existing media queue. */
+import { createHash } from 'crypto';
+import { constants } from 'fs';
+import { lstat, realpath, mkdtemp, rm, stat, link, unlink, open } from 'fs/promises';
+import { join, sep } from 'path';
+import { spawnDetached } from '../../lib/detachedSpawn.js';
+import { PATHS, ensureDir } from '../../lib/fileUtils.js';
+import { safeUnder, findFfmpeg, probeVideoDuration, probeVideoStreamInfo } from '../../lib/ffmpeg.js';
+import { safeChildProcessEnv } from '../../lib/processEnv.js';
+import { killWithEscalation } from '../../lib/killWithEscalation.js';
+import { withBackupAssetPublication } from '../../lib/backupSnapshotBoundary.js';
+import { maintenance } from '../../lib/maintenanceAdmission.js';
+import { ServerError } from '../../lib/errorHandler.js';
+import { getProject, listProjects, mutateProjectRecord } from './projects.js';
+import { getHistoryItem } from '../videoGen/history.js';
+import { videoGenEvents } from '../videoGen/events.js';
+
+export const SHARING_COPY_MAX_BYTES = 100_000_000;
+const KIND = 'video-sharing';
+const pending = new Map();
+const running = new Map();
+const fail = (message) => new ServerError(message, { status: 409, code: 'SHARING_COPY_UNAVAILABLE' });
+
+const missingFile = error => {
+ if (error.code === 'ENOENT' || error.code === 'ELOOP') throw fail('The video file is missing or unsafe — check the final render and prepare again');
+ throw error;
+};
+const fileVersion = info => [info.dev, info.ino, info.size, info.mtimeMs, info.ctimeMs].join(':');
+
+async function ownedVideo(filename) {
+ const path = safeUnder(PATHS.videos, filename);
+ if (!path || !(await lstat(path).catch(missingFile)).isFile()) throw fail('The video file is missing or unsafe');
+ const [root, actual] = await Promise.all([realpath(PATHS.videos), realpath(path).catch(missingFile)]);
+ if (!actual.startsWith(root + sep)) throw fail('The video file is outside the media directory');
+ return actual;
+}
+
+async function fileHash(path, retainedFile = null) {
+ // Do not follow a leaf symlink installed after the ownership lookup.
+ const file = retainedFile || await open(path, constants.O_RDONLY | (constants.O_NOFOLLOW || 0)).catch(missingFile);
+ try {
+ const before = await file.stat();
+ if (!before.isFile()) throw fail('Unsafe video file');
+ const hash = createHash('sha256');
+ for await (const chunk of file.createReadStream({ autoClose: false, start: 0 })) hash.update(chunk);
+ const after = await lstat(path).catch(missingFile);
+ if (!after.isFile() || fileVersion(before) !== fileVersion(after)) throw fail('The video file changed during verification; prepare again');
+ return { hash: hash.digest('hex'), version: fileVersion(after) };
+ } finally { if (!retainedFile) await file.close(); }
+}
+
+async function assertSourceSelected(source) {
+ const project = await getProject(source.project.id);
+ const entry = project?.renderHistoryId === source.renderHistoryId ? await getHistoryItem(source.renderHistoryId) : null;
+ const info = await lstat(source.path).catch(missingFile);
+ if (!entry || entry.filename !== source.filename || !info.isFile() || fileVersion(info) !== source.fileVersion) throw fail('The final render changed during verification; prepare a new sharing copy');
+ return project;
+}
+
+async function finalSource(projectId) {
+ const project = await getProject(projectId);
+ if (!project) throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });
+ if (!project.renderHistoryId) throw fail('Render the final video before preparing a sharing copy');
+ const entry = await getHistoryItem(project.renderHistoryId);
+ if (!entry?.filename) throw fail('The final render is missing');
+ const path = await ownedVideo(entry.filename);
+ const digest = await fileHash(path);
+ const source = { project, path, filename: entry.filename, sourceHash: digest.hash, fileVersion: digest.version, renderHistoryId: project.renderHistoryId };
+ source.project = await assertSourceSelected(source);
+ return source;
+}
+
+function sameSource(source, expected) {
+ return source.renderHistoryId === expected.renderHistoryId && source.sourceHash === expected.sourceHash;
+}
+
+async function cachedCopy(source) {
+ const copy = source.project.publishKit?.sharingCopy;
+ if (!copy || copy.version !== 1 || !sameSource(source, copy)) return null;
+ try {
+ const path = await ownedVideo(copy.filename);
+ const digest = await fileHash(path);
+ const info = await stat(path).catch(missingFile);
+ if (digest.version !== fileVersion(info) || info.size !== copy.bytes || !info.size || info.size >= SHARING_COPY_MAX_BYTES || digest.hash !== copy.hash) return null;
+ return copy;
+ } catch (error) {
+ if (error.code === 'SHARING_COPY_UNAVAILABLE') return null;
+ throw error;
+ }
+}
+
+async function sharingState(source) {
+ const projectId = source.project.id;
+ const { listJobs } = await import('../mediaJobQueue/index.js');
+ const job = listJobs({ kind: KIND }).find((job) => ['queued', 'running'].includes(job.status)
+ && job.params?.sharingProjectId === projectId && sameSource(source, job.params));
+ source.project = await assertSourceSelected(source);
+ const copy = await cachedCopy(source);
+ await assertSourceSelected(source);
+ return { copy, jobId: job?.id || null, status: job?.status || null };
+}
+
+export async function getSharingCopy(projectId) {
+ return sharingState(await finalSource(projectId));
+}
+
+/** Reserve before any async lookup; repeated clicks reuse the exact same request/job. */
+export function prepareSharingCopy(projectId) {
+ if (pending.has(projectId)) return pending.get(projectId);
+ const request = (async () => {
+ const source = await finalSource(projectId);
+ const state = await sharingState(source);
+ if (state.copy || state.jobId) return state;
+ const { enqueueJob } = await import('../mediaJobQueue/index.js');
+ return enqueueJob({ kind: KIND, owner: `music-video:${projectId}`, params: {
+ sharingProjectId: projectId, renderHistoryId: source.renderHistoryId, sourceHash: source.sourceHash,
+ } });
+ })().finally(() => pending.delete(projectId));
+ pending.set(projectId, request);
+ return request;
+}
+
+export async function sharingCopyDownload(projectId) {
+ const source = await finalSource(projectId);
+ const copy = source.project.publishKit?.sharingCopy;
+ if (!copy || copy.version !== 1 || !sameSource(source, copy)) throw fail('Prepare a sharing copy of the current final render first');
+ const path = await ownedVideo(copy.filename);
+ const file = await open(path, constants.O_RDONLY | (constants.O_NOFOLLOW || 0)).catch(missingFile);
+ try {
+ const digest = await fileHash(path, file);
+ const info = await file.stat();
+ if (digest.version !== fileVersion(info) || info.size !== copy.bytes || !info.size || info.size >= SHARING_COPY_MAX_BYTES || digest.hash !== copy.hash) throw fail('Prepare a sharing copy of the current final render first');
+ await assertSourceSelected(source);
+ // The caller owns this exact verified descriptor; never reopen the pathname.
+ return { copy, file, modifiedAt: info.mtime };
+ } catch (error) {
+ await file.close();
+ throw error;
+ }
+}
+
+export function cancel(jobId) {
+ const run = running.get(jobId);
+ if (!run || run.committing) return false;
+ run.aborted = true;
+ const proc = run.proc;
+ if (proc) killWithEscalation(proc, { label: 'sharing export', stillRunning: () => run.proc === proc });
+ return true;
+}
+
+async function encode(bin, args, run) {
+ if (run.aborted) throw fail('Sharing export cancelled');
+ const proc = await spawnDetached(bin, args, {
+ controlDir: join(PATHS.videos, '.detached', `sharing-${run.jobId}-${run.pass++}`),
+ env: safeChildProcessEnv(), cleanup: true,
+ });
+ run.proc = proc;
+ if (run.aborted) killWithEscalation(proc, { label: 'sharing export', stillRunning: () => run.proc === proc });
+ return new Promise((resolve, reject) => {
+ let tail = '';
+ let processError;
+ proc.stderr.on('data', chunk => {
+ tail = (tail + chunk.toString()).slice(-2000);
+ videoGenEvents.emit('activity', { generationId: run.jobId });
+ });
+ const timer = setTimeout(() => {
+ run.aborted = true;
+ killWithEscalation(proc, { label: 'sharing export timeout', stillRunning: () => run.proc === proc });
+ }, 30 * 60_000);
+ timer.unref?.();
+ const cleanup = () => { clearTimeout(timer); run.proc = null; };
+ proc.on('error', error => {
+ processError = error;
+ // An observer error with a live PID does not prove physical settlement.
+ // Retain the lane and scratch until close; cancellation still escalates.
+ if (proc.pid) killWithEscalation(proc, { label: 'sharing export observer failure', stillRunning: () => run.proc === proc });
+ else { cleanup(); reject(error); }
+ });
+ proc.once('close', code => {
+ cleanup();
+ if (processError) reject(processError);
+ else if (run.aborted) reject(fail('Sharing export cancelled or timed out'));
+ else if (code !== 0) reject(new Error(`Sharing encode failed (${code}): ${tail}`));
+ else resolve();
+ });
+ });
+}
+
+/** Queue worker: fixed two-pass H.264/AAC, at most 720p/60fps and strictly <100 MB. */
+export async function runSharingCopy({ jobId, sharingProjectId, renderHistoryId, sourceHash }) {
+ if (!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(jobId)) throw fail('Invalid sharing job identity');
+ const run = { jobId, proc: null, aborted: false, committing: false, pass: 0 };
+ running.set(jobId, run);
+ let scratch;
+ let output;
+ let published = false;
+ let result;
+ let error;
+ const reportStage = message => videoGenEvents.emit('status', { generationId: jobId, message });
+ try {
+ const source = await finalSource(sharingProjectId);
+ if (!sameSource(source, { renderHistoryId, sourceHash })) throw fail('The final render changed; prepare a new sharing copy');
+ const [duration, stream, bin] = await Promise.all([probeVideoDuration(source.path), probeVideoStreamInfo(source.path), findFfmpeg()]);
+ if (!bin || !Number.isFinite(duration) || duration <= 0 || duration > 3600 || !stream.width || !stream.height || !Number.isFinite(stream.fps) || stream.fps <= 0) throw fail('Cannot export this final render (supported duration: up to one hour)');
+ await ensureDir(PATHS.videos);
+ await ensureDir(join(PATHS.videos, '.detached'));
+ if (!(await lstat(join(PATHS.videos, '.detached'))).isDirectory()) throw fail('Unsafe render scratch directory');
+ scratch = await mkdtemp(join(PATHS.videos, '.detached', 'sharing-work-'));
+ const encoded = join(scratch, 'copy.mp4');
+ const passlog = join(scratch, 'pass');
+ // Budget 95 MB for streams; the remaining 5 MB protects against mux overhead.
+ let bitrate = Math.min(8_000_000, Math.floor(95_000_000 * 8 / duration) - 128_000);
+ if (bitrate < 100_000) throw fail('The video is too long for a usable sharing copy');
+ for (let attempt = 0; attempt < 2; attempt++) {
+ const video = ['-vf', "scale=w='min(1280,iw)':h='min(720,ih)':force_original_aspect_ratio=decrease:force_divisible_by=2", '-r', String(Math.min(60, stream.fps)), '-c:v', 'libx264', '-preset', 'medium', '-threads', '2', '-b:v', String(bitrate), '-pix_fmt', 'yuv420p', '-passlogfile', passlog];
+ const input = ['-hide_banner', '-nostdin', '-loglevel', 'info', '-filter_threads', '2', '-protocol_whitelist', 'file,pipe', '-f', 'mov', '-i', source.path, '-map', '0:v:0'];
+ reportStage('Analyzing sharing encode (pass 1 of 2)');
+ await encode(bin, [...input, ...video, '-pass', '1', '-an', '-f', 'null', '-y', process.platform === 'win32' ? 'NUL' : '/dev/null'], run);
+ reportStage('Encoding sharing copy (pass 2 of 2)');
+ await encode(bin, [...input, '-map', '0:a:0?', ...video, '-pass', '2', '-c:a', 'aac', '-b:a', '128k', '-map_metadata', '-1', '-fs', '104000000', '-movflags', '+faststart', '-y', encoded], run);
+ const bytes = (await stat(encoded)).size;
+ if (bytes < SHARING_COPY_MAX_BYTES) break;
+ bitrate = Math.floor(bitrate * 90_000_000 / bytes);
+ }
+ reportStage('Verifying file size and current final render');
+ const [info, measured, copyDuration, fresh] = await Promise.all([stat(encoded), probeVideoStreamInfo(encoded), probeVideoDuration(encoded), finalSource(sharingProjectId)]);
+ if (run.aborted) throw fail('Sharing export cancelled');
+ if (!sameSource(fresh, source)) throw fail('The final render changed during export; prepare a new sharing copy');
+ if (!info.size || info.size >= SHARING_COPY_MAX_BYTES || !measured.width || !measured.height || measured.width > 1280 || measured.height > 720 || !Number.isFinite(measured.fps) || measured.fps <= 0 || measured.fps > 60 || !Number.isFinite(copyDuration) || Math.abs(copyDuration - duration) > Math.max(0.25, 2 / stream.fps)) throw fail('Sharing copy failed size, resolution or full-length verification');
+ const filename = `music-video-sharing-${jobId}.mp4`;
+ result = { version: 1, filename, bytes: info.size, width: measured.width, height: measured.height, fps: measured.fps,
+ durationSec: copyDuration, renderHistoryId, sourceHash, hash: (await fileHash(encoded)).hash, createdAt: new Date().toISOString() };
+ if (run.aborted) throw fail('Sharing export cancelled');
+ // Once publication starts, cancellation is refused rather than reporting cancelled for a saved result.
+ run.committing = true;
+ await withBackupAssetPublication(async () => {
+ await assertSourceSelected(source);
+ const destination = join(PATHS.videos, filename);
+ // An exclusive hard link publishes atomically without overwriting an existing file.
+ await link(encoded, destination);
+ output = destination;
+ await mutateProjectRecord(sharingProjectId, current => {
+ if (current.renderHistoryId !== renderHistoryId) throw fail('The final render changed during export');
+ return { project: { ...current, publishKit: { ...current.publishKit, sharingCopy: result } } };
+ });
+ published = true;
+ });
+ const previous = source.project.publishKit?.sharingCopy?.filename;
+ if (previous && previous !== filename) await releaseUnusedSharingCopy(previous).catch(err => cleanupFailed(jobId, err));
+ } catch (err) {
+ error = err.message || 'Sharing export failed';
+ } finally {
+ if (output && !published) await unlink(output).catch(err => {
+ if (err.code !== 'ENOENT') { cleanupFailed(jobId, err); error ||= 'Sharing export cleanup needs recovery'; }
+ });
+ if (scratch) await rm(scratch, { recursive: true, force: true }).catch(err => {
+ cleanupFailed(jobId, err); error ||= 'Sharing export cleanup needs recovery';
+ });
+ running.delete(jobId);
+ }
+ if (error) videoGenEvents.emit('failed', { generationId: jobId, error });
+ else videoGenEvents.emit('completed', { generationId: jobId, ...result });
+}
+
+function cleanupFailed(jobId, error) {
+ maintenance.markCurrentUnsettled();
+ maintenance.markResourceUnsettled('media', jobId);
+ console.error(`❌ Sharing copy cleanup needs recovery [${jobId.slice(0, 8)}]: ${error.message}`);
+}
+
+async function releaseUnusedSharingCopy(filename) {
+ if (!/^music-video-sharing-[0-9a-f-]{36}\.mp4$/i.test(filename)) return;
+ const projects = await listProjects();
+ if (projects.some(project => project.publishKit?.sharingCopy?.filename === filename)) return;
+ const path = await ownedVideo(filename).catch(error => {
+ if (error.code === 'SHARING_COPY_UNAVAILABLE') return null;
+ throw error;
+ });
+ if (path) await withBackupAssetPublication(() => unlink(path));
+}
+
+/** Boot reconciliation removes only this job's unpublished output, never a saved copy. */
+export async function cleanupInterruptedSharingCopy(jobId) {
+ if (!/^[0-9a-f-]{36}$/i.test(jobId)) return;
+ await releaseUnusedSharingCopy(`music-video-sharing-${jobId}.mp4`);
+}
diff --git a/server/services/musicVideo/sharingCopy.test.js b/server/services/musicVideo/sharingCopy.test.js
new file mode 100644
index 0000000000..3becb1e5f4
--- /dev/null
+++ b/server/services/musicVideo/sharingCopy.test.js
@@ -0,0 +1,293 @@
+import { afterAll, beforeEach, describe, expect, it, vi } from 'vitest';
+import { EventEmitter } from 'events';
+import { mkdir, readFile, readdir, rename, symlink, truncate, unlink, writeFile } from 'fs/promises';
+import { join } from 'path';
+import { cleanupTempDataRoots, lazyTempDataRoot, makePathsProxy } from '../../lib/mockPathsDataRoot.js';
+
+const state = vi.hoisted(() => ({ project: null, jobs: [], spawns: [], outputSizes: [], duringPass: null, failPass: null, realEncode: false, saveError: null, missingFfmpeg: false, cleanupError: false, observerError: null, openedFiles: [] }));
+vi.mock('fs/promises', async original => {
+ const actual = await original();
+ return { ...actual, open: async (...args) => { const file = await actual.open(...args); state.openedFiles.push(file); return file; }, rm: async (path, options) => {
+ if (state.cleanupError && String(path).includes('sharing-work-')) throw new Error('Synthetic cleanup I/O error');
+ return actual.rm(path, options);
+ } };
+});
+vi.mock('../../lib/maintenanceAdmission.js', () => ({ maintenance: { markCurrentUnsettled: vi.fn(), markResourceUnsettled: vi.fn() } }));
+vi.mock('../../lib/paths.js', async original => makePathsProxy(await original(), { dataRoot: () => lazyTempDataRoot('sharing-copy-test-') }));
+vi.mock('./projects.js', () => ({
+ getProject: vi.fn(async () => state.project),
+ listProjects: async () => [state.project],
+ mutateProjectRecord: async (_id, transform) => { if (state.saveError) throw state.saveError; const out = transform(state.project); state.project = out.project; return out; },
+}));
+vi.mock('../videoGen/history.js', () => ({ getHistoryItem: async id => ({ id, filename: `${id}.mp4` }) }));
+vi.mock('../mediaJobQueue/index.js', () => ({
+ listJobs: () => state.jobs,
+ enqueueJob: vi.fn(async job => { state.jobs.push({ ...job, id: 'queued-example', status: 'queued' }); return { jobId: 'queued-example', status: 'queued' }; }),
+}));
+vi.mock('../../lib/backupSnapshotBoundary.js', () => ({ withBackupAssetPublication: async fn => fn() }));
+vi.mock('../../lib/ffmpeg.js', async original => {
+ const actual = await original();
+ return { ...actual,
+ findFfmpeg: async () => state.missingFfmpeg ? null : state.realEncode ? actual.findFfmpeg() : 'ffmpeg',
+ probeVideoDuration: async path => state.realEncode ? actual.probeVideoDuration(path) : 120,
+ probeVideoStreamInfo: async path => state.realEncode ? actual.probeVideoStreamInfo(path) : ({ width: 1280, height: 720, fps: 60 }),
+ };
+});
+vi.mock('../../lib/detachedSpawn.js', async original => ({ spawnDetached: vi.fn(async (bin, args, options) => {
+ if (state.realEncode) return (await original()).spawnDetached(bin, args, options);
+ state.spawns.push(args);
+ const proc = new EventEmitter();
+ proc.stderr = new EventEmitter();
+ proc.kill = () => { queueMicrotask(() => proc.emit('close', null, 'SIGTERM')); return true; };
+ proc.exitCode = null;
+ proc.signalCode = null;
+ if (state.observerError) {
+ proc.pid = 123;
+ setImmediate(() => { proc.emit('error', new Error('Synthetic observer I/O error')); state.observerError(proc); });
+ // This test controls physical exit rather than the ordinary pass fixture.
+ proc.kill = vi.fn(() => true);
+ return proc;
+ }
+ setImmediate(async () => {
+ try {
+ await state.duringPass?.(args);
+ if (state.failPass) { proc.emit('close', 1); return; }
+ if (args[args.indexOf('-pass') + 1] === '2') {
+ const file = args.at(-1);
+ await writeFile(file, 'sharing fixture');
+ if (state.outputSizes.length) await truncate(file, state.outputSizes.shift());
+ }
+ proc.exitCode = 0;
+ proc.emit('close', 0);
+ } catch (err) { proc.emit('error', err); }
+ });
+ return proc;
+}) }));
+
+const { PATHS } = await import('../../lib/fileUtils.js');
+const sharing = await import('./sharingCopy.js');
+const { videoGenEvents } = await import('../videoGen/events.js');
+const { enqueueJob } = await import('../mediaJobQueue/index.js');
+
+beforeEach(async () => {
+ state.project = { id: 'mv-example', renderHistoryId: 'final-example' };
+ state.jobs = []; state.spawns = []; state.outputSizes = []; state.duringPass = null; state.failPass = null; state.realEncode = false; state.saveError = null; state.missingFfmpeg = false; state.cleanupError = false; state.observerError = null; state.openedFiles = [];
+ vi.clearAllMocks();
+ const { getProject } = await import('./projects.js');
+ getProject.mockImplementation(async () => state.project);
+ await mkdir(PATHS.videos, { recursive: true });
+ await writeFile(join(PATHS.videos, 'final-example.mp4'), 'original final fixture');
+});
+afterAll(cleanupTempDataRoots);
+
+async function runExport(jobId = '00000000-0000-4000-8000-000000000001') {
+ const queued = await sharing.prepareSharingCopy('mv-example');
+ const params = state.jobs.find(j => j.id === queued.jobId).params;
+ const completed = vi.fn(); const failed = vi.fn();
+ videoGenEvents.once('completed', completed); videoGenEvents.once('failed', failed);
+ await sharing.runSharingCopy({ ...params, jobId });
+ videoGenEvents.removeListener('completed', completed); videoGenEvents.removeListener('failed', failed);
+ return { completed, failed };
+}
+
+describe('private sharing export workflow', () => {
+ it('retains process ownership after an observer error until physical close', async () => {
+ let reportError;
+ const observed = new Promise(resolve => { reportError = resolve; });
+ state.observerError = reportError;
+ let settled = false;
+ const outcome = runExport('00000000-0000-4000-8000-000000000066').then(result => { settled = true; return result; });
+ const proc = await observed;
+ expect(proc.kill).toHaveBeenCalledWith('SIGTERM');
+ await new Promise(resolve => setImmediate(resolve));
+ expect(settled).toBe(false);
+ expect((await readdir(join(PATHS.videos, '.detached'))).some(name => name.startsWith('sharing-work-'))).toBe(true);
+ proc.exitCode = 1;
+ proc.emit('close', 1);
+ expect((await outcome).failed).toHaveBeenCalledWith(expect.objectContaining({ error: 'Synthetic observer I/O error' }));
+ expect(await readdir(join(PATHS.videos, '.detached'))).toEqual([]);
+ });
+
+ it('preserves a maintenance blocker when owned scratch cleanup cannot finish', async () => {
+ state.failPass = true;
+ state.cleanupError = true;
+ const { failed } = await runExport('00000000-0000-4000-8000-000000000067');
+ expect(failed).toHaveBeenCalled();
+ const { maintenance } = await import('../../lib/maintenanceAdmission.js');
+ expect(maintenance.markCurrentUnsettled).toHaveBeenCalled();
+ expect(maintenance.markResourceUnsettled).toHaveBeenCalledWith('media', '00000000-0000-4000-8000-000000000067');
+ expect(state.project.publishKit).toBeUndefined();
+ state.cleanupError = false;
+ const actualFs = await vi.importActual('fs/promises');
+ for (const name of await readdir(join(PATHS.videos, '.detached'))) {
+ if (name.startsWith('sharing-work-')) await actualFs.rm(join(PATHS.videos, '.detached', name), { recursive: true, force: true });
+ }
+ });
+
+ it('coalesces repeated clicks, preserves the final, and caches only the exact final bytes', async () => {
+ const requests = await Promise.all([sharing.prepareSharingCopy('mv-example'), sharing.prepareSharingCopy('mv-example')]);
+ expect(requests[0]).toEqual(requests[1]);
+ expect(enqueueJob).toHaveBeenCalledTimes(1);
+ const { completed, failed } = await runExport();
+ expect(failed).not.toHaveBeenCalled();
+ expect(completed).toHaveBeenCalledWith(expect.objectContaining({ bytes: 15, width: 1280, fps: 60 }));
+ expect(await readFile(join(PATHS.videos, 'final-example.mp4'), 'utf8')).toBe('original final fixture');
+ state.jobs = [];
+ const cached = await sharing.prepareSharingCopy('mv-example');
+ expect(cached.copy.filename).toBe('music-video-sharing-00000000-0000-4000-8000-000000000001.mp4');
+ expect(enqueueJob).toHaveBeenCalledTimes(1);
+ const download = await sharing.sharingCopyDownload('mv-example');
+ try { expect(download.copy).toEqual(cached.copy); } finally { await download.file.close(); }
+ await writeFile(join(PATHS.videos, 'final-example.mp4'), 'changed final fixture');
+ expect((await sharing.getSharingCopy('mv-example')).copy).toBeNull();
+ await expect(sharing.sharingCopyDownload('mv-example')).rejects.toThrow('current final render');
+ await sharing.prepareSharingCopy('mv-example');
+ expect(enqueueJob).toHaveBeenCalledTimes(2);
+ const firstArgs = state.spawns[0];
+ expect(firstArgs).toEqual(expect.arrayContaining(['-threads', '2', '-r', '60', '-protocol_whitelist', 'file,pipe', '-f', 'mov']));
+ });
+
+ it('retries an oversized encode with a smaller budget and refuses any still oversized result', async () => {
+ state.outputSizes = [100_000_000, 100_000_001];
+ const { failed, completed } = await runExport('00000000-0000-4000-8000-000000000002');
+ expect(state.spawns).toHaveLength(4);
+ const rate = args => Number(args[args.indexOf('-b:v') + 1]);
+ expect(rate(state.spawns[2])).toBeLessThan(rate(state.spawns[0]));
+ expect(completed).not.toHaveBeenCalled();
+ expect(failed).toHaveBeenCalledWith(expect.objectContaining({ error: expect.stringContaining('verification') }));
+ expect(state.project.publishKit).toBeUndefined();
+ expect(await readdir(join(PATHS.videos, '.detached'))).toEqual([]);
+ });
+
+ it('cancels between passes and removes partial output before reporting failure', async () => {
+ state.duringPass = args => { if (args[args.indexOf('-pass') + 1] === '1') sharing.cancel('00000000-0000-4000-8000-000000000003'); };
+ const { failed, completed } = await runExport('00000000-0000-4000-8000-000000000003');
+ expect(failed).toHaveBeenCalledWith(expect.objectContaining({ error: expect.stringContaining('cancelled') }));
+ expect(completed).not.toHaveBeenCalled();
+ expect(state.spawns).toHaveLength(1);
+ expect(await readdir(join(PATHS.videos, '.detached'))).toEqual([]);
+ });
+
+ it('refuses a final changed during encode and leaves its source untouched', async () => {
+ state.duringPass = async args => { if (args[args.indexOf('-pass') + 1] === '2') await writeFile(join(PATHS.videos, 'final-example.mp4'), 'replacement final'); };
+ const { failed, completed } = await runExport('00000000-0000-4000-8000-000000000004');
+ expect(completed).not.toHaveBeenCalled();
+ expect(failed).toHaveBeenCalledWith(expect.objectContaining({ error: expect.stringContaining('changed during export') }));
+ expect(await readFile(join(PATHS.videos, 'final-example.mp4'), 'utf8')).toBe('replacement final');
+ expect(state.project.publishKit).toBeUndefined();
+ });
+
+ it('refuses a removed source before delivery and a final selection changed during verification', async () => {
+ await runExport('00000000-0000-4000-8000-000000000061');
+ await unlink(join(PATHS.videos, 'final-example.mp4'));
+ await expect(sharing.sharingCopyDownload('mv-example')).rejects.toMatchObject({ status: 409, code: 'SHARING_COPY_UNAVAILABLE' });
+ await writeFile(join(PATHS.videos, 'final-example.mp4'), 'original final fixture');
+ const { getProject } = await import('./projects.js');
+ getProject.mockImplementationOnce(async () => ({ ...state.project }));
+ getProject.mockImplementationOnce(async () => ({ ...state.project, renderHistoryId: 'replacement-example' }));
+ await expect(sharing.getSharingCopy('mv-example')).rejects.toThrow('final render changed');
+ });
+
+ it('removes partial files when ffmpeg fails, the source disappears, or the record write fails', async () => {
+ state.failPass = true;
+ let outcome = await runExport('00000000-0000-4000-8000-000000000062');
+ expect(outcome.failed).toHaveBeenCalledWith(expect.objectContaining({ error: expect.stringContaining('Sharing encode failed') }));
+ state.failPass = null;
+ state.duringPass = async args => { if (args[args.indexOf('-pass') + 1] === '2') await unlink(join(PATHS.videos, 'final-example.mp4')); };
+ outcome = await runExport('00000000-0000-4000-8000-000000000063');
+ expect(outcome.completed).not.toHaveBeenCalled();
+ expect(outcome.failed).toHaveBeenCalledWith(expect.objectContaining({ error: expect.stringContaining('missing or unsafe') }));
+ await writeFile(join(PATHS.videos, 'final-example.mp4'), 'original final fixture');
+ state.duringPass = null;
+ state.saveError = new Error('Synthetic storage full');
+ outcome = await runExport('00000000-0000-4000-8000-000000000064');
+ expect(outcome.failed).toHaveBeenCalledWith(expect.objectContaining({ error: 'Synthetic storage full' }));
+ expect(state.project.publishKit).toBeUndefined();
+ expect(await readdir(PATHS.videos)).not.toContain('music-video-sharing-00000000-0000-4000-8000-000000000064.mp4');
+ expect(await readdir(join(PATHS.videos, '.detached'))).toEqual([]);
+ expect(await readFile(join(PATHS.videos, 'final-example.mp4'), 'utf8')).toBe('original final fixture');
+ });
+
+ it('fails before spawning if ffmpeg is unavailable and rejects a corrupted job identity', async () => {
+ state.missingFfmpeg = true;
+ const { failed } = await runExport('00000000-0000-4000-8000-000000000065');
+ expect(failed).toHaveBeenCalled();
+ expect(state.spawns).toHaveLength(0);
+ await expect(sharing.runSharingCopy({ jobId: '../unowned', sharingProjectId: 'mv-example' })).rejects.toThrow('Invalid sharing job identity');
+ expect(state.project.publishKit).toBeUndefined();
+ });
+
+ it('refuses an output-name collision without overwriting or deleting the existing file', async () => {
+ const jobId = '00000000-0000-4000-8000-000000000088';
+ const destination = join(PATHS.videos, `music-video-sharing-${jobId}.mp4`);
+ await writeFile(destination, 'existing owned video');
+ const { failed, completed } = await runExport(jobId);
+ expect(completed).not.toHaveBeenCalled();
+ expect(failed).toHaveBeenCalled();
+ expect(await readFile(destination, 'utf8')).toBe('existing owned video');
+ expect(state.project.publishKit).toBeUndefined();
+ });
+
+ it('rejects symlinked sources and detects a changed sharing file before download', async () => {
+ await runExport('00000000-0000-4000-8000-000000000005');
+ await writeFile(join(PATHS.videos, state.project.publishKit.sharingCopy.filename), 'tampered bytes!');
+ await expect(sharing.sharingCopyDownload('mv-example')).rejects.toThrow('current final render');
+ await symlink(join(PATHS.videos, 'final-example.mp4'), join(PATHS.videos, 'linked-example.mp4'));
+ state.project.renderHistoryId = 'linked-example';
+ await expect(sharing.prepareSharingCopy('mv-example')).rejects.toThrow('unsafe');
+ });
+
+ it.each(['replacement', 'symlink'])('retains the certified inode across a %s swap during final validation', async swap => {
+ await runExport(swap === 'replacement' ? '00000000-0000-4000-8000-000000000071' : '00000000-0000-4000-8000-000000000072');
+ const copyPath = join(PATHS.videos, state.project.publishKit.sharingCopy.filename);
+ const { getProject } = await import('./projects.js');
+ let lookups = 0;
+ getProject.mockImplementation(async () => {
+ if (++lookups === 3) {
+ await rename(copyPath, `${copyPath}.old`);
+ if (swap === 'symlink') await symlink(join(PATHS.videos, 'final-example.mp4'), copyPath);
+ else await writeFile(copyPath, 'replacement bytes must not be delivered');
+ }
+ return state.project;
+ });
+ const { file } = await sharing.sharingCopyDownload('mv-example');
+ try {
+ const chunks = [];
+ for await (const chunk of file.createReadStream({ start: 0, autoClose: false })) chunks.push(chunk);
+ expect(Buffer.concat(chunks).toString()).toBe('sharing fixture');
+ } finally { await file.close(); }
+ });
+
+ it('closes the retained descriptor when source validation refuses delivery', async () => {
+ await runExport('00000000-0000-4000-8000-000000000073');
+ const { getProject } = await import('./projects.js');
+ let lookups = 0;
+ getProject.mockImplementation(async () => ++lookups === 3 ? { ...state.project, renderHistoryId: 'replacement-final' } : state.project);
+ await expect(sharing.sharingCopyDownload('mv-example')).rejects.toThrow('final render changed');
+ expect(state.openedFiles.every(file => file.fd === -1)).toBe(true);
+ });
+});
+
+// Two seconds only: catches ffmpeg argument/container/pass-log mistakes that stubs cannot.
+const actualFfmpeg = await vi.importActual('../../lib/ffmpeg.js');
+const realBinary = await actualFfmpeg.findFfmpeg();
+it.skipIf(!realBinary)('exports a bounded real MP4 fixture through the supervised process runner', async () => {
+ state.realEncode = true;
+ const { execFile } = await import('../../lib/childProcess.js');
+ const { promisify } = await import('util');
+ const { safeChildProcessOptions } = await import('../../lib/processEnv.js');
+ const sourcePath = join(PATHS.videos, 'final-example.mp4');
+ await promisify(execFile)(realBinary, ['-hide_banner', '-loglevel', 'error', '-f', 'lavfi', '-i', 'testsrc2=size=1440x810:rate=60', '-f', 'lavfi', '-i', 'sine=frequency=440:sample_rate=48000', '-t', '2', '-c:v', 'libx264', '-threads', '2', '-preset', 'ultrafast', '-c:a', 'aac', '-y', sourcePath], safeChildProcessOptions({ timeout: 20_000 }));
+ const original = await readFile(sourcePath);
+ const { completed, failed } = await runExport('00000000-0000-4000-8000-000000000099');
+ expect(failed).not.toHaveBeenCalled();
+ expect(completed).toHaveBeenCalledWith(expect.objectContaining({ width: 1280, height: 720, fps: 60 }));
+ const { file, copy } = await sharing.sharingCopyDownload('mv-example');
+ await file.close();
+ const path = join(PATHS.videos, copy.filename);
+ expect(copy.bytes).toBeLessThan(sharing.SHARING_COPY_MAX_BYTES);
+ expect(copy.durationSec).toBeCloseTo(2, 1);
+ expect(await readFile(sourcePath)).toEqual(original);
+ // A complete decode is cheap for this fixture and proves a playable full copy.
+ await promisify(execFile)(realBinary, ['-v', 'error', '-i', path, '-f', 'null', '-'], safeChildProcessOptions({ timeout: 20_000 }));
+}, 30_000);