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
fix: keep ffmpeg decodes and encodes on open GET routes behind host control (#13156)
Adam Eivyba711f314706
diff --git a/client/src/components/media/MediaLightbox.jsx b/client/src/components/media/MediaLightbox.jsxindex 8d2653656b..446585a14f 100644--- a/client/src/components/media/MediaLightbox.jsx+++ b/client/src/components/media/MediaLightbox.jsx@@ -8,6 +8,7 @@ import VideoStartTrimControl from './VideoStartTrimControl';import PromptRefineModal from './PromptRefineModal';import { PromptFromMediaModal } from './PromptFromMedia';import AddToCollectionMenu from './AddToCollectionMenu';+import SharingDownloadButton from './SharingDownloadButton';import PinToMoodBoardMenu from './PinToMoodBoardMenu';import FilmLookEditor from './FilmLookEditor.jsx';import MediaImage from '../MediaImage';@@ -1039,8 +1040,7 @@ function SettingsPane({onTrim={(startSec) => onTrimStart(item, startSec)} />)}{isVideo && item.id && item.previewUrl && (- <a href={`/api/video-gen/history/${encodeURIComponent(item.id)}/sharing-download`} download- className="min-h-[44px] flex items-center px-2 rounded bg-port-border text-white">Download for sharing</a>+ <SharingDownloadButton itemId={item.id} />)}<AddToCollectionMenu item={item} size="md" /><PinToMoodBoardMenu item={item} size="md" />diff --git a/client/src/components/media/MediaLightbox.test.jsx b/client/src/components/media/MediaLightbox.test.jsxindex fa7a746160..3a25d3246e 100644--- a/client/src/components/media/MediaLightbox.test.jsx+++ b/client/src/components/media/MediaLightbox.test.jsx@@ -363,5 +363,5 @@ describe('MediaLightbox compact preview item', () => {await waitFor(() => expect(screen.getByRole('button', { name: 'Reset poster' })).not.toBeDisabled());fireEvent.click(screen.getByRole('button', { name: 'Reset poster' }));await waitFor(() => expect(onPosterChange).toHaveBeenCalledWith(videoItem, null));- expect(screen.getByRole('link', { name: 'Download for sharing' })).toHaveAttribute('href', '/api/video-gen/history/abc/sharing-download');+ expect(screen.getByRole('button', { name: 'Download for sharing' })).toBeInTheDocument();});diff --git a/client/src/components/media/SharingDownloadButton.jsx b/client/src/components/media/SharingDownloadButton.jsxnew file mode 100644index 0000000000..185b41b7b8--- /dev/null+++ b/client/src/components/media/SharingDownloadButton.jsx@@ -0,0 +1,35 @@+import { useState } from 'react';+import { downloadVideoSharingCopy } from '../../services/apiImageVideo';+import { downloadBlob } from '../../lib/downloadBlob';++// The sharing copy is an ffmpeg re-encode the server runs only for a caller+// with host control, so it is fetched (not linked) to show a refusal as an+// unavailable note instead of saving the error body as the download.+export default function SharingDownloadButton({ itemId }) {+ const [state, setState] = useState({ busy: false, note: null });+ const download = async () => {+ if (state.busy) return;+ setState({ busy: true, note: null });+ const blob = await downloadVideoSharingCopy(itemId).catch((err) => err);+ if (blob instanceof Blob) {+ downloadBlob(blob, `sharing-${itemId}.mp4`, 'video/mp4');+ setState({ busy: false, note: null });+ return;+ }+ setState({+ busy: false,+ note: blob?.code === 'HOST_CONTROL_FORBIDDEN'+ ? 'Download for sharing needs operator access.'+ : (blob?.message || 'Could not prepare the sharing download'),+ });+ };+ return (+ <>+ <button type="button" disabled={state.busy} onClick={download}+ className="min-h-[44px] flex items-center px-2 rounded bg-port-border text-white disabled:opacity-50">+ {state.busy ? 'Preparing…' : 'Download for sharing'}+ </button>+ {state.note && <p role="status" className="w-full text-xs text-port-text-muted">{state.note}</p>}+ </>+ );+}diff --git a/client/src/components/media/SharingDownloadButton.test.jsx b/client/src/components/media/SharingDownloadButton.test.jsxnew file mode 100644index 0000000000..123a7c9b1e--- /dev/null+++ b/client/src/components/media/SharingDownloadButton.test.jsx@@ -0,0 +1,37 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';+import { fireEvent, render, screen, waitFor } from '@testing-library/react';++const api = vi.hoisted(() => ({ downloadVideoSharingCopy: vi.fn() }));+const saved = vi.hoisted(() => ({ downloadBlob: vi.fn() }));+vi.mock('../../services/apiImageVideo', () => api);+vi.mock('../../lib/downloadBlob', () => saved);++import SharingDownloadButton from './SharingDownloadButton';++beforeEach(() => vi.clearAllMocks());++describe('SharingDownloadButton', () => {+ it('saves the re-encoded copy for a caller with host control', async () => {+ const blob = new Blob(['video'], { type: 'video/mp4' });+ api.downloadVideoSharingCopy.mockResolvedValue(blob);+ render(<SharingDownloadButton itemId="abc" />);+ fireEvent.click(screen.getByRole('button', { name: 'Download for sharing' }));+ await waitFor(() => expect(saved.downloadBlob).toHaveBeenCalledWith(blob, 'sharing-abc.mp4', 'video/mp4'));+ expect(screen.queryByRole('status')).toBeNull();+ });++ it('shows an unavailable note, not a saved error body, when host control refuses the encode', async () => {+ api.downloadVideoSharingCopy.mockRejectedValue(Object.assign(new Error('Host control requires an operator session'), { code: 'HOST_CONTROL_FORBIDDEN' }));+ render(<SharingDownloadButton itemId="abc" />);+ fireEvent.click(screen.getByRole('button', { name: 'Download for sharing' }));+ expect(await screen.findByRole('status')).toHaveTextContent('needs operator access');+ expect(saved.downloadBlob).not.toHaveBeenCalled();+ });++ it('reports any other failure with the server message', async () => {+ api.downloadVideoSharingCopy.mockRejectedValue(new Error('Set a poster before downloading for sharing'));+ render(<SharingDownloadButton itemId="abc" />);+ fireEvent.click(screen.getByRole('button', { name: 'Download for sharing' }));+ expect(await screen.findByRole('status')).toHaveTextContent('Set a poster before downloading for sharing');+ });+});diff --git a/client/src/services/apiCore.js b/client/src/services/apiCore.jsindex 1e8d1e044e..755dfd563b 100644--- a/client/src/services/apiCore.js+++ b/client/src/services/apiCore.js@@ -119,6 +119,9 @@ async function performRequest(endpoint, options = {}) {if (responseType === 'text') {return response.text();}+ if (responseType === 'blob') {+ return response.blob();+ }return response.json();}diff --git a/client/src/services/apiImageVideo.js b/client/src/services/apiImageVideo.jsindex 4e7c0f4acd..e96859f691 100644--- a/client/src/services/apiImageVideo.js+++ b/client/src/services/apiImageVideo.js@@ -682,3 +682,9 @@ export const requestMediaModelSupport = (input, options = {}) => request('/imageexport const updateVideoPoster = (id, atSec, options = {}) => request(`/video-gen/history/${encodeURIComponent(id)}/poster`, {method: 'PATCH', body: JSON.stringify({ atSec }), ...options,});++// Re-encodes the video with its poster as the first frame on every request, so+// the server refuses a caller without host control (HOST_CONTROL_FORBIDDEN).+export const downloadVideoSharingCopy = (id, options = {}) => request(`/video-gen/history/${encodeURIComponent(id)}/sharing-download`, {+ responseType: 'blob', silent: true, hostControlOptional: true, ...options,+});diff --git a/server/hostControlCoverage.test.js b/server/hostControlCoverage.test.jsindex 3f7994aa0f..be5a9616d0 100644--- a/server/hostControlCoverage.test.js+++ b/server/hostControlCoverage.test.js@@ -1466,7 +1466,8 @@ const TOOLKIT_INJECTED = 'Toolkit factory route (lib/aiToolkit/routes and theirconst TOOL_CATALOG = 'Lists a catalog whose entries carry executors (agent, voice and creative tools, MCP tool adapters, mind recipes); the handler returns metadata, and the executors run only through the gated tool dispatch.';const JOB_TABLE = "Reads media-job queue state or a job record; the traced encoders and generators sit in the queue's runtime table and run only from the queue worker after a gated enqueue.";const ACTIVE_WORK_READ = 'Reports in-flight work by reading the in-memory state of the runner, backup and media-job modules, loaded lazily, plus GPU telemetry; starts none of it.';-const STORED_MEDIA = 'Runs ffmpeg or ffprobe over media PortOS already stored (a generation history item, the song master, a music-library track, a sprite run) to probe it, decode it or write a derived cache file; the caller supplies no path or argument.';+const STORED_MEDIA_PROBE = 'Runs ffprobe over media PortOS already stored (a generation history item) to read its stream facts; no decode or encode, and the caller supplies no path or argument.';+const MUSIC_VIDEO_PLAN_READ = "Plans the render to report shot, look or cleanup state; the plan's performance-take review decodes the song master with ffmpeg only for a caller with host control (`requestHasHostControl`, #13156), and anyone else gets the plan with that take unchecked.";const MOLTBOOK_READ = 'Reads from the Moltbook API with the stored agent key; a response that demands verification is answered with the account\'s configured model and screened by the local abuse classifier, as on every Moltbook call.';const PEER_PAYLOAD = 'Peer endpoint in PEER_API_SURFACE that builds its payload from stored records; the executors the trace reaches come from whole-module namespace imports of the stores it reads.';const PEER_ADMIN_READ = 'Describes peer-administration state from stored grants and catalog reviews; the installer and execution adapters the trace reaches run only from the handler-gated execution and catalog-review writes.';@@ -1518,7 +1519,7 @@ const REVIEWED_PROCESS_GETS = [['GET /api/git/submodules/status', FORGE_READ],['GET /api/github/accounts/:id/status', FORGE_READ],['GET /api/harnesses', PROVIDER_STATUS],- ['GET /api/html-composition/beats', STORED_MEDIA],+ ['GET /api/html-composition/beats', 'Measures the beat grid of an existing Music-library track (the caller picks the track, never a path); the ffmpeg decode runs once per file modification time and every later read serves the cached grid (#13156).'],['GET /api/image-gen/status', RUNTIME_STATUS],['GET /api/image-to-3d/targets', 'Reports image-to-3D target install state with each adapter\'s fixed probes (Metal toolchain, module imports); the adapter table\'s install and generate functions run only from the gated install and generate routes.'],['GET /api/image-to-3d/targets/:targetId/install', 'Reports image-to-3D target install state with each adapter\'s fixed probes (Metal toolchain, module imports); the adapter table\'s install and generate functions run only from the gated install and generate routes.'],@@ -1548,13 +1549,13 @@ const REVIEWED_PROCESS_GETS = [['GET /api/models/performance/task-benchmark', TOOLKIT_INJECTED],['GET /api/music-video', JOB_TABLE],['GET /api/music-video/:id', JOB_TABLE],- ['GET /api/music-video/:id/film-looks', STORED_MEDIA],+ ['GET /api/music-video/:id/film-looks', MUSIC_VIDEO_PLAN_READ],['GET /api/music-video/:id/media-pool/library', 'Searches stored media for the pool; the trace reaches the local image backend whole through a namespace import, while the handler reads only its gallery records.'],['GET /api/music-video/:id/media-pool/search', 'Searches stored media for the pool; the trace reaches the local image backend whole through a namespace import, while the handler reads only its gallery records.'],['GET /api/music-video/:id/publish/drafts', 'Checks whether each publish draft the operator opened through the gated prepare route is still a tab in the managed browser (a CDP target lookup); opens, fills or submits nothing.'],- ['GET /api/music-video/:id/render-cleanup', STORED_MEDIA],- ['GET /api/music-video/:id/shot-renders', STORED_MEDIA],- ['GET /api/music-video/:id/shot-renders/:name', STORED_MEDIA],+ ['GET /api/music-video/:id/render-cleanup', MUSIC_VIDEO_PLAN_READ],+ ['GET /api/music-video/:id/shot-renders', MUSIC_VIDEO_PLAN_READ],+ ['GET /api/music-video/:id/shot-renders/:name', 'Streams an already-rendered shot segment file by its content-hash name; the ffmpeg the trace reaches through the shot-segment module renders only from the gated shot-render routes (#13156).'],['GET /api/music/supercollider/status', RUNTIME_STATUS],['GET /api/palette/manifest', TOOL_CATALOG],['GET /api/peer-administration/catalog-review', PEER_ADMIN_READ],@@ -1595,7 +1596,7 @@ const REVIEWED_PROCESS_GETS = [['GET /api/runs/:id/prompt', TOOLKIT_INJECTED],['GET /api/settings/ai-assignments', FORGE_READ],['GET /api/settings/media-share-candidates', 'Reports which local media generators this install offers peers, from readiness probes and the media-job queue\'s in-memory state; the encoders in the queue\'s runtime table run only from its worker.'],- ['GET /api/sprites/:id/walk/runs/:runId/source-frames', STORED_MEDIA],+ ['GET /api/sprites/:id/walk/runs/:runId/source-frames', 'Lists the raw frames already on disk for a walk run; the ffmpeg re-extraction the trace reaches runs only for `extract: true`, which only the gated POST .../source-frames/extract passes (#13156).'],['GET /api/system/activity', ACTIVE_WORK_READ],['GET /api/system/health/details', JOB_TABLE],['GET /api/system/processing', ACTIVE_WORK_READ],@@ -1605,9 +1606,8 @@ const REVIEWED_PROCESS_GETS = [['GET /api/usage/claude-code', PROVIDER_USAGE],['GET /api/usage/providers', PROVIDER_USAGE],['GET /api/video-gen/active', JOB_TABLE],- ['GET /api/video-gen/history/:id', STORED_MEDIA],- ['GET /api/video-gen/history/:id/sharing-download', STORED_MEDIA],- ['GET /api/video-gen/upscale/:id/plan', STORED_MEDIA],+ ['GET /api/video-gen/history/:id', STORED_MEDIA_PROBE],+ ['GET /api/video-gen/upscale/:id/plan', STORED_MEDIA_PROBE],['GET /api/voice/facetime/status', RUNTIME_STATUS],['GET /api/voice/public/voices', 'Lists TTS voices from the configured engines\' catalogs; the synthesize functions in the engine table run only from the speak and synthesis routes.'],['GET /api/voice/qwen3/status', RUNTIME_STATUS],diff --git a/server/lib/hostControlRoutes.js b/server/lib/hostControlRoutes.jsindex 926cd6dba6..4d618b8a0d 100644--- a/server/lib/hostControlRoutes.js+++ b/server/lib/hostControlRoutes.js@@ -15,7 +15,9 @@* A route belongs here when it runs a process, git, npm, gh or a CoS agent on* the host, or when it sets what one will run (a repo path, a start command, a* task prompt, a shell job), or accesses live camera/microphone streams.- * Ordinary read-only GETs stay open; raw backup archives require operator+ * Ordinary read-only GETs stay open (a GET that only decodes media for some+ * callers checks `requestHasHostControl` in its handler instead, as the Music+ * Video shot, look and cleanup reads do for the song-master decode, #13156); raw backup archives require operator* authority because they export private records and credentials, and so does* the directory picker (GET /api/scaffold/directories), which enumerates any* readable host directory rather than a PortOS record. Mutating routes in the@@ -1311,8 +1313,11 @@ export const HOST_CONTROL_ROUTES = Object.freeze([// GET routes the process-reach trace found starting host work (#13097): the// dependency-impact preview decodes the current song master with ffmpeg to// compare sung windows, and the YouTube setup check opens or reuses a tab in- // the signed-in managed browser and reads it (#12488 rule).+ // the signed-in managed browser and reads it (#12488 rule); the sharing+ // download re-encodes the video with ffmpeg on every request (it keeps no+ // cached copy, #13156).'GET /api/music-video/:id/dependency-impact',+ 'GET /api/video-gen/history/:id/sharing-download','GET /api/youtube/setup-check',]);diff --git a/server/routes/musicVideo.js b/server/routes/musicVideo.jsindex fa26882aa2..9cf3c709d1 100644--- a/server/routes/musicVideo.js+++ b/server/routes/musicVideo.js@@ -728,9 +728,18 @@ router.get('/:id/render', (req, res) => {res.json({ jobId: getActiveRenderJobId(req.params.id) });});+// The shot, look and cleanup reads plan the render, whose performance-take+// review decodes the song master with ffmpeg; only a caller with host control+// starts that decode (#13156). Others get the plan with the take unchecked.+let authGateModule;+const planOptions = async (req) => {+ const { requestHasHostControl } = await (authGateModule ??= import('../services/authGate.js'));+ return { decode: requestHasHostControl(req) };+};+router.get('/:id/render-cleanup', asyncHandler(async (req, res) => {const { getRenderCleanup } = await import('../services/musicVideo/renderCleanup.js');- res.json(await getRenderCleanup(req.params.id));+ res.json(await getRenderCleanup(req.params.id, await planOptions(req)));}));router.post('/:id/render-cleanup', asyncHandler(async (req, res) => {const input = validateRequest(musicVideoRenderCleanupSchema, req.body ?? {});@@ -742,7 +751,7 @@ router.post('/:id/render-cleanup', asyncHandler(async (req, res) => {// shot's render started or stopped, and a rendered shot's silent segment.router.get('/:id/shot-renders', asyncHandler(async (req, res) => {const { getShotRenderStatus } = await import('../services/musicVideo/shotSegments.js');- res.json(await getShotRenderStatus(req.params.id));+ res.json(await getShotRenderStatus(req.params.id, await planOptions(req)));}));router.post('/:id/shots/:sceneId/render', asyncHandler(async (req, res) => {const { startShotRender } = await import('../services/musicVideo/shotSegments.js');@@ -761,7 +770,7 @@ router.post('/:id/shot-renders/preview', asyncHandler(async (req, res) => {}));router.get('/:id/film-looks', asyncHandler(async (req, res) => {const { listFilmLooks } = await import('../services/musicVideo/shotSegments.js');- res.json(await listFilmLooks(req.params.id));+ res.json(await listFilmLooks(req.params.id, await planOptions(req)));}));router.delete('/:id/film-looks/:lookId', asyncHandler(async (req, res) => {const { deleteFilmLook } = await import('../services/musicVideo/shotSegments.js');@@ -902,7 +911,6 @@ router.post('/:id/code/sections/:sectionId/regenerate', asyncHandler(async (req,// this router is reached by many suites that mock settings. Both deferred// imports are memoized: overlapping first loads of one specifier can resolve// past a test's module mock.-let authGateModule;let overlayTextModule;const checkOverlayTextAfterImport = async (req, projectId) => {const { requestHasHostControl } = await (authGateModule ??= import('../services/authGate.js'));diff --git a/server/routes/musicVideoPlanDecodeGuard.test.js b/server/routes/musicVideoPlanDecodeGuard.test.jsnew file mode 100644index 0000000000..0db8b8b688--- /dev/null+++ b/server/routes/musicVideoPlanDecodeGuard.test.js@@ -0,0 +1,77 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';+import express from 'express';+import { request } from '../lib/testHelper.js';+import { errorMiddleware } from '../lib/errorHandler.js';++// The shot, look and cleanup reads plan the render, whose performance-take+// review decodes the song master with ffmpeg. The services are spies: the+// route must hand each one `decode: true` only to a caller with host control.+const auth = vi.hoisted(() => ({ enabled: false }));+const planners = vi.hoisted(() => ({+ getShotRenderStatus: vi.fn(async () => ({ available: false })),+ listFilmLooks: vi.fn(async () => ({ available: false })),+ getRenderCleanup: vi.fn(async () => ({ finals: [], segments: {} })),+}));++vi.mock('../services/auth.js', async (importOriginal) => ({+ ...await importOriginal(),+ isAuthEnabled: vi.fn(async () => auth.enabled),+}));+vi.mock('../services/settings.js', () => ({+ settingsEvents: { on: vi.fn(), off: vi.fn(), emit: vi.fn() },+ getSettings: vi.fn(async () => ({})),+ updateSettingsWith: vi.fn(async (mutate) => mutate({})),+}));+vi.mock('../services/musicVideo/shotSegments.js', async (importOriginal) => ({+ ...await importOriginal(),+ getShotRenderStatus: planners.getShotRenderStatus,+ listFilmLooks: planners.listFilmLooks,+}));+vi.mock('../services/musicVideo/renderCleanup.js', async (importOriginal) => ({+ ...await importOriginal(),+ getRenderCleanup: planners.getRenderCleanup,+}));++import { authGate, hostControlRouteGate } from '../services/authGate.js';+import musicVideoRoutes from './musicVideo.js';++const PROJECT = '/api/music-video/example-project';+const reads = [+ [`${PROJECT}/shot-renders`, planners.getShotRenderStatus],+ [`${PROJECT}/film-looks`, planners.listFilmLooks],+ [`${PROJECT}/render-cleanup`, planners.getRenderCleanup],+];++const appFor = (address) => {+ const app = express();+ app.use((req, _res, next) => {+ Object.defineProperty(req.socket, 'remoteAddress', { value: address });+ next();+ });+ app.use(authGate, hostControlRouteGate, express.json());+ app.use('/api/music-video', musicVideoRoutes);+ app.use(errorMiddleware);+ return app;+};++beforeEach(() => {+ vi.clearAllMocks();+ auth.enabled = false;+});++describe('Music Video plan reads and the song-master decode (#13156)', () => {+ it('serves a remote password-free caller without allowing the ffmpeg decode', async () => {+ for (const [path, service] of reads) {+ const response = await request(appFor('192.0.2.10')).get(path);+ expect(response.status, path).toBe(200);+ expect(service, path).toHaveBeenCalledWith('example-project', { decode: false });+ }+ });++ it('lets a local caller decode', async () => {+ for (const [path, service] of reads) {+ expect((await request(appFor('127.0.0.1')).get(path)).status, path).toBe(200);+ expect(service, path).toHaveBeenCalledWith('example-project', { decode: true });+ }+ });+});diff --git a/server/routes/videoGenSharingDownloadGuard.test.js b/server/routes/videoGenSharingDownloadGuard.test.jsnew file mode 100644index 0000000000..0019fe2454--- /dev/null+++ b/server/routes/videoGenSharingDownloadGuard.test.js@@ -0,0 +1,56 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';+import express from 'express';+import { request } from '../lib/testHelper.js';+import { errorMiddleware } from '../lib/errorHandler.js';++// The sharing download re-encodes the video with ffmpeg on every request and+// keeps no cached copy (#13156), so a caller without host control must not+// reach the encoder.+const auth = vi.hoisted(() => ({ enabled: false }));+const createSharingCopy = vi.hoisted(() => vi.fn());+vi.mock('../services/auth.js', async (importOriginal) => ({+ ...await importOriginal(),+ isAuthEnabled: vi.fn(async () => auth.enabled),+}));+vi.mock('../services/settings.js', () => ({+ settingsEvents: { on: vi.fn(), off: vi.fn(), emit: vi.fn() },+ getSettings: vi.fn(async () => ({})),+ updateSettingsWith: vi.fn(async (mutate) => mutate({})),+}));+vi.mock('../services/videoGen/poster.js', () => ({ updateVideoPoster: vi.fn(), createSharingCopy }));++import { authGate, hostControlRouteGate } from '../services/authGate.js';+import videoGenRoutes from './videoGen.js';++const PATH = '/api/video-gen/history/11111111-1111-4111-8111-111111111111/sharing-download';+const appFor = (address) => {+ const app = express();+ app.use((req, _res, next) => {+ Object.defineProperty(req.socket, 'remoteAddress', { value: address });+ next();+ });+ app.use(authGate, hostControlRouteGate, express.json());+ app.use('/api/video-gen', videoGenRoutes);+ app.use(errorMiddleware);+ return app;+};++beforeEach(() => {+ vi.clearAllMocks();+ auth.enabled = false;+});++describe('GET /api/video-gen/history/:id/sharing-download host control (#13156)', () => {+ it('refuses a remote password-free caller before the ffmpeg encode', async () => {+ const response = await request(appFor('192.0.2.10')).get(PATH);+ expect([response.status, response.body.code]).toEqual([403, 'HOST_CONTROL_FORBIDDEN']);+ expect(createSharingCopy).not.toHaveBeenCalled();+ });++ it('still encodes for a local caller', async () => {+ createSharingCopy.mockRejectedValue(Object.assign(new Error('Set a poster before downloading for sharing'), { status: 422 }));+ const response = await request(appFor('127.0.0.1')).get(PATH);+ expect(response.status).toBe(422);+ expect(createSharingCopy).toHaveBeenCalledTimes(1);+ });+});diff --git a/server/services/musicVideo/performanceShot.js b/server/services/musicVideo/performanceShot.jsindex 4d5678ae8e..1c3501cc62 100644--- a/server/services/musicVideo/performanceShot.js+++ b/server/services/musicVideo/performanceShot.js@@ -173,9 +173,11 @@ function legacyMasterLookup(project, masterPath) {* of its old master when that file is still in the track's render history)* is compared with the new master. With neither, a changed master is stale.* The master is hashed only when there is a performance take to check, and- * decoded only when its hash changed.+ * decoded only when its hash changed. `decode: false` (a read-only caller+ * without host control) never starts that ffmpeg decode: a rehashed master's+ * window is taken as unchanged, and the renders that follow re-check it.*/-async function reviewPerformanceTakes(project, masterPath) {+async function reviewPerformanceTakes(project, masterPath, { decode = true } = {}) {const results = [];const selected = [];let sha256 = null;@@ -197,6 +199,7 @@ async function reviewPerformanceTakes(project, masterPath) {let currentEnvelope = null;const oldEnvelope = legacyMasterLookup(project, masterPath);const windowUnchanged = async (instruction) => {+ if (!decode) return true;let fingerprint = instruction.audio?.windowFingerprint;if (!fingerprint) {const envelope = await oldEnvelope(instruction.audio?.sha256);@@ -223,8 +226,8 @@ async function reviewPerformanceTakes(project, masterPath) {}/** The stale entries of `reviewPerformanceTakes`: `[{ sceneId, reason }]`. */-export async function findStalePerformanceTakes(project, masterPath) {- return (await reviewPerformanceTakes(project, masterPath))+export async function findStalePerformanceTakes(project, masterPath, options) {+ return (await reviewPerformanceTakes(project, masterPath, options)).filter((r) => r.stale).map(({ sceneId, reason }) => ({ sceneId, reason }));}@@ -235,8 +238,8 @@ export async function findStalePerformanceTakes(project, masterPath) {* its newest cutaway clip (a video take with no performance or song-audio* instruction), else its still. Final renders keep the strict gate below.*/-export async function withDraftPerformanceFallbacks(project, masterPath) {- const stale = new Set((await findStalePerformanceTakes(project, masterPath)).map(({ sceneId }) => sceneId));+export async function withDraftPerformanceFallbacks(project, masterPath, options) {+ const stale = new Set((await findStalePerformanceTakes(project, masterPath, options)).map(({ sceneId }) => sceneId));if (!stale.size) return project;return { ...project, scenes: project.scenes.map((scene) => {if (!stale.has(scene.sceneId)) return scene;@@ -259,8 +262,8 @@ export async function withDraftPerformanceFallbacks(project, masterPath) {* Cutaway fixes: those with no lip-sync take. A lip-sync take switched to* Cutaway loses its in-point and plays from its first frame, out of sync.*/-export async function assertCurrentPerformanceTakes(project, masterPath) {- const reviewed = await reviewPerformanceTakes(project, masterPath);+export async function assertCurrentPerformanceTakes(project, masterPath, options) {+ const reviewed = await reviewPerformanceTakes(project, masterPath, options);const rehashed = reviewed.filter((r) => r.reason === 'audio-rehashed').length;if (rehashed > 0) console.log(`🎵 Music Video: ${rehashed} lip-sync take${rehashed === 1 ? '' : 's'} still match${rehashed === 1 ? 'es' : ''} the re-mastered song in ${rehashed === 1 ? 'its' : 'their'} sung window`);const locks = clipLocks(project);diff --git a/server/services/musicVideo/performanceShot.test.js b/server/services/musicVideo/performanceShot.test.jsindex 2a6ab05e01..e1be86cf69 100644--- a/server/services/musicVideo/performanceShot.test.js+++ b/server/services/musicVideo/performanceShot.test.js@@ -246,6 +246,9 @@ describe.skipIf(!ffmpeg)('music-video performance shot through the fal lip-syncawait writeFile(songPath, resung);expect(await findStalePerformanceTakes({ scenes: [withTake] }, songPath)).toEqual([{ sceneId: 'mvs-1', reason: 'audio-changed' }]);+ // A read-only caller without host control never starts that decode (#13156):+ // the re-sung window goes unchecked rather than stale.+ expect(await findStalePerformanceTakes({ scenes: [withTake] }, songPath, { decode: false })).toEqual([]);// A take made before window fingerprints existed is compared against its// old master when the track's render history still holds it, and is stalediff --git a/server/services/musicVideo/render.js b/server/services/musicVideo/render.jsindex be013c79bd..53099ff23a 100644--- a/server/services/musicVideo/render.js+++ b/server/services/musicVideo/render.js@@ -835,7 +835,9 @@ function lockedShotIds(project) {return Object.keys(shots).filter((id) => (clips[id] ?? shots[id]) === 'locked');}-export async function planMusicVideoRender(project, { draft = false } = {}) {+// `decode: false` plans for a read-only caller without host control: the+// performance-take review skips its ffmpeg decode of the song master.+export async function planMusicVideoRender(project, { draft = false, decode = true } = {}) {assertMusicVideoMediaSelections(project);assertCurrentClipDependencies(project);const ffmpeg = await findFfmpeg();@@ -844,8 +846,8 @@ export async function planMusicVideoRender(project, { draft = false } = {}) {const audioPath = await resolveMasterAudioPath(project);// #8977/#9266: refuse a performance take whose scene was re-timed or whose// sung window changed in the current master. A draft shows a cutaway instead.- if (draft) project = await withDraftPerformanceFallbacks(project, audioPath);- await assertCurrentPerformanceTakes(project, audioPath);+ if (draft) project = await withDraftPerformanceFallbacks(project, audioPath, { decode });+ await assertCurrentPerformanceTakes(project, audioPath, { decode });// #8985: a composed render cuts still and card sections into the same// timebase as the footage; plain concat renders footage only, as before.const composed = project.composition?.mode === 'composed';diff --git a/server/services/musicVideo/renderCleanup.js b/server/services/musicVideo/renderCleanup.jsindex 2385f119ce..7571bed3b7 100644--- a/server/services/musicVideo/renderCleanup.js+++ b/server/services/musicVideo/renderCleanup.js@@ -135,11 +135,11 @@ export async function cleanupSupersededFinals(projectId, { replacementId = null,return reserved ? retire() : withRenderCleanupReservation(projectId, retire);}-export async function getRenderCleanup(projectId) {+export async function getRenderCleanup(projectId, options) {const [history, pending] = await Promise.all([loadHistory(), readPending()]);const { finals } = await finalInventory(projectId, history, pending);const { getSegmentCleanup } = await import('./shotSegments.js');- return { finals, segments: await getSegmentCleanup(projectId) };+ return { finals, segments: await getSegmentCleanup(projectId, options) };}export async function cleanupRenders(projectId, { unusedLooks = false } = {}) {diff --git a/server/services/musicVideo/shotSegments.js b/server/services/musicVideo/shotSegments.jsindex a2498155bc..69543d3f38 100644--- a/server/services/musicVideo/shotSegments.js+++ b/server/services/musicVideo/shotSegments.js@@ -118,12 +118,13 @@ async function fingerprintArgs(args) {* Plan a composed project's segments: the same preflight and clip plan as the* final render, then each section's keys and cache paths. Throws the render's* own refusals (each names its shots and the fix). Reads files, writes nothing.+ * `options.decode: false` skips the performance-take review's ffmpeg decode.*/-export async function planShotSegments(project) {+export async function planShotSegments(project, options) {if (project?.composition?.mode !== 'composed') {throw new ServerError('Shot renders need the composed render style', { status: 409, code: 'SHOT_RENDER_NEEDS_COMPOSED' });}- const { ffmpeg, audioPath, clips, audioDurationSec, soundBed, aspect } = await planMusicVideoRender(project);+ const { ffmpeg, audioPath, clips, audioDurationSec, soundBed, aspect } = await planMusicVideoRender(project, options);const grade = project.composition?.grade;const beats = project.audioAnalysis?.beats;const common = { audioDurationSec, frameGrid: true, grade, beats, aspect };@@ -488,8 +489,8 @@ export function assertSegmentCleanupIdle(projectId) {}}-export async function getSegmentCleanup(projectId) {- const { project, plan: planned } = await planForLooks(projectId);+export async function getSegmentCleanup(projectId, options) {+ const { project, plan: planned } = await planForLooks(projectId, options);const plan = planned || { project, dir: shotSegmentDir(projectId), segments: [], outro: null };if (plan.error) return { available: true, error: plan.error, stale: [], unusedLooks: [] };const stale = await staleSegmentFiles(plan, { previews: true });@@ -578,10 +579,10 @@ async function loadProjectScene(projectId, sceneId) {* final render would refuse reports that refusal (it names the shots and the* fix) instead of shot states, since no segment can be placed until it plans.*/-export async function getShotRenderStatus(projectId) {+export async function getShotRenderStatus(projectId, options) {const project = await requireProject(projectId);if (project.composition?.mode !== 'composed') return { available: false, shots: [], outro: null, ready: 0, total: 0 };- const plan = await planShotSegments(project).catch((err) => {+ const plan = await planShotSegments(project, options).catch((err) => {if (!err?.status || err.status >= 500) throw err;return { error: { message: err.message, code: err.code || null } };});@@ -709,10 +710,10 @@ const rememberFilmLook = (dir, look) => updateFilmLooks(dir, (looks) => {const videoLookSegments = (plan) => [...plan.segments.filter((s) => !s.ownLook), ...(plan.outro ? [plan.outro] : [])];-async function planForLooks(projectId) {+async function planForLooks(projectId, options) {const project = await requireProject(projectId);if (project.composition?.mode !== 'composed') return { project, plan: null };- const plan = await planShotSegments(project).catch((err) => {+ const plan = await planShotSegments(project, options).catch((err) => {if (!err?.status || err.status >= 500) throw err;return { error: { message: err.message, code: err.code || null } };});@@ -724,8 +725,8 @@ async function planForLooks(projectId) {* settings, how many of the shots that use the video's look have it rendered,* and the disk it holds. The look in use comes first.*/-export async function listFilmLooks(projectId) {- const { project, plan } = await planForLooks(projectId);+export async function listFilmLooks(projectId, options) {+ const { project, plan } = await planForLooks(projectId, options);if (!plan) return { available: false, looks: [], total: 0 };if (plan.error) return { available: true, error: plan.error, looks: [], total: 0 };const stored = await readFilmLooks(plan.dir);