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: federate Music Video project media assets (#1772)

[._.]/ Adam Eivy81b7b44b2954
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 4c81e89193..d524b0626f 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -17,6 +17,7 @@
- **[issue-1760] Groundwork: offline beat/tempo/section analysis of an audio track (Phase 0 spike).** The first slice of the planned Music Video production mode proves the riskiest unknown — that a music track's BPM, beat grid, 4/4 downbeats, and a coarse section map can be extracted **fully offline with no new dependency**, using only ffmpeg (already required) plus a pure-JS DSP core (onset-strength envelope → tempo-weighted autocorrelation → beat-phase fit → energy-novelty sections). No Python, no ML model download, no network — so it runs the same in CI and on every install. There's no user-facing surface yet; this is the analyzer the upcoming director scene board and beat-snapped render build on. (`server/services/musicVideo/audioAnalysis.js`)
- **[issue-1760] Director scene board: create a Music Video project, analyze its track, and storyboard beat-aligned scenes (Phase 1).** Builds the first user-facing surface on top of the Phase 0 analyzer: a new **Create → Music Video** page (also reachable via `⌘K` and voice) where you pick an existing track (or name an uploaded audio file), create a project, and run the offline analyzer with one click — the detected BPM, beat/downbeat counts, and section map render inline. From there you storyboard the video as an ordered list of **scenes**, each with a label, a start/end time, a beat-aligned flag, and image/frame prompts; scenes can be added, edited (blur-to-save), reordered, and removed. Projects persist through a db-primary store (PostgreSQL `music_video_projects` with a file-backend fallback for dev/test), mirroring the creative-director pattern with soft-delete tombstones and LWW timestamps. Cross-machine federation of projects, per-scene reference-frame/image generation + image-to-video, and the beat-snapped render with a master audio bed are filed as follow-ups on #1760. (`server/services/musicVideo/`, `server/routes/musicVideo.js`, `server/lib/musicVideoValidation.js`, `client/src/pages/MusicVideo.jsx`, `client/src/services/apiMusicVideo.js`)
- **[issue-1770] Music Video projects now sync across your federated machines.** Phase 1 shipped the project store as local-only; it now federates over the same peer-sync pipeline your other creative records use. A new **Music Video** toggle on the Instances page enables it per peer — when on, creating, editing, reordering scenes on, or deleting a project on one machine propagates to the others, with newest-edit-wins conflict resolution and deletions that an out-of-date peer can't resurrect. Conflicting edits are surfaced in the Conflicts UI for restore. Referenced media (the uploaded audio track and rendered scene clips) is not bundled in this phase and is tracked as a follow-up. (Closes #1770)
+- **[issue-1772] Music Video project media now federates with the project.** #1770 synced the project record but shipped an empty asset manifest, so a peer that subscribed to just one project received the metadata and beat-aligned scenes but none of the bytes. The push now bundles the project's referenced media: the **uploaded audio track** (as a `music` asset) and each scene's **rendered clip** (resolved from its `videoHistoryId` through `video-history.json` to the file under `data/videos/`, with a `<id>.mp4` fallback when the metadata row hasn't synced yet). A track-linked project ships no audio here — the linked track federates its own. Tombstones still ship nothing, and missing files are skipped so a stale reference never forces a peer to re-request bytes the sender doesn't have. Scene reference-frame images (`referenceImageId`) wait on the unshipped Phase 1b render pipeline that populates them. (Closes #1772)
## Devtools
diff --git a/server/lib/peerSyncValidation.js b/server/lib/peerSyncValidation.js
index 4d8c8dc791..777fb9fe5e 100644
--- a/server/lib/peerSyncValidation.js
+++ b/server/lib/peerSyncValidation.js
@@ -239,11 +239,11 @@ const writersRoomExercisePushSchema = z.object({
...peerSyncPushBase,
}).strict();
// Music Video projects (#1770) push the bare record (metadata + beat-aligned
-// scenes[]) — no bundled children/linked collection, and referenced media
-// (uploaded audio, scene images/rendered videos) is NOT bundled in this phase,
-// so the base shape alone suffices and the sender always ships `assetManifest:
-// []` (`.strict()` rejects smuggled bundle keys, same posture as
-// creativeDirectorProject/writersRoomFolder).
+// scenes[]) — no bundled children/linked collection. #1772 bundles referenced
+// media (uploaded audio as a `music` entry, rendered scene clips as `video`
+// entries) via the base `assetManifest`, which already accepts both kinds; no
+// project-specific manifest field is needed (`.strict()` still rejects smuggled
+// bundle keys, same posture as creativeDirectorProject/writersRoomFolder).
const musicVideoProjectPushSchema = z.object({
kind: z.literal('musicVideoProject'),
...peerSyncPushBase,
diff --git a/server/services/sharing/peerSync.js b/server/services/sharing/peerSync.js
index 5970a2256b..d61ef02aed 100644
--- a/server/services/sharing/peerSync.js
+++ b/server/services/sharing/peerSync.js
@@ -842,10 +842,7 @@ async function buildIntegrityAssetManifest(kind, record) {
if (kind === 'album') return buildAlbumAssetManifest(record);
if (kind === 'track') return buildTrackAssetManifest(record);
if (kind === 'creativeDirectorProject') return buildProjectAssetManifest(record);
- // Music Video projects (#1770): the record federates but its referenced media
- // (uploaded audio, scene reference images / rendered videos) is NOT bundled in
- // this phase — empty manifest, mirroring the body-less Writers Room kinds.
- if (kind === 'musicVideoProject') return [];
+ if (kind === 'musicVideoProject') return buildMusicVideoAssetManifest(record);
if (kind === 'moodBoard') return buildBoardAssetManifest(record);
if (kind === 'series') {
const childIssues = await listIssues({ seriesId: record?.id, includeDeleted: true }).catch(() => []);
@@ -1689,15 +1686,14 @@ async function buildPushPayload(sub, sourceInstanceId) {
return { kind: 'writersRoomExercise', record: sanitized, assetManifest: [], sourceInstanceId, portosMeta };
}
if (sub.recordKind === 'musicVideoProject') {
- // #1770 — the record (metadata + beat-aligned scenes) is the LWW envelope.
- // Referenced media (uploaded audio, scene images/rendered videos) is NOT
- // bundled in this phase, so the asset manifest is empty (writersRoomFolder
- // pattern). Media-asset bundling is a follow-up.
+ // #1770 ships the record (metadata + beat-aligned scenes) as the LWW
+ // envelope; #1772 bundles its referenced media. A tombstone ships no bytes.
const record = await getMusicVideoProject(sub.recordId, { includeDeleted: true }).catch(() => null);
if (!record) return null;
const sanitized = sanitizeRecordForWire('musicVideoProject', record);
if (!sanitized) return null;
- return { kind: 'musicVideoProject', record: sanitized, assetManifest: [], sourceInstanceId, portosMeta };
+ const assetManifest = record.deleted === true ? [] : await buildMusicVideoAssetManifest(record);
+ return { kind: 'musicVideoProject', record: sanitized, assetManifest, sourceInstanceId, portosMeta };
}
return null;
}
@@ -1765,6 +1761,66 @@ async function buildProjectAssetManifest(project) {
return entry ? [entry] : [];
}
+// `data/video-history.json` is a FLAT array of video-generation rows
+// (`{ id, filename, ... }`). The same store dataSync's `videoHistory` category
+// federates as metadata; here we read it only to resolve a scene's
+// `videoHistoryId` to its on-disk basename under PATHS.videos. Mirrors
+// dataSync's direct readJSONFile (no videoGen import — that drags in
+// ffmpeg/spawn machinery we don't need on the manifest path).
+async function videoHistoryFilenamesById() {
+ const raw = await readJSONFile(join(PATHS.data, 'video-history.json'), []);
+ const map = new Map();
+ for (const row of Array.isArray(raw) ? raw : []) {
+ if (isStr(row?.id) && isStr(row?.filename)) map.set(row.id, row.filename);
+ }
+ return map;
+}
+
+/**
+ * Build a Music Video project's asset manifest (#1772). Unlike the Creative
+ * Director store, a music video project has NO auto-linked media collection, so
+ * its referenced media has no other federation channel — this manifest is the
+ * only way a selectively-subscribed peer receives the bytes. Covers the two
+ * media kinds a shipped project actually references:
+ * - the uploaded audio track (`uploadedAudioFilename`, a basename under
+ * PATHS.music — the same dir tracks use). A track-LINKED project stores
+ * `uploadedAudioFilename: null` (the route writes one or the other), so the
+ * linked track's own federation carries that audio and nothing double-ships.
+ * - per-scene rendered clips (`scene.videoHistoryId` → a video-history row →
+ * `<filename>` under PATHS.videos). The row METADATA union-merges via the
+ * `videoHistory` dataSync category; this adds the bytes. Falls back to the
+ * `<id>.mp4` convention (`collectionVideoRefToFilename`) when the row hasn't
+ * synced yet — a missing file is skipped, so a wrong guess never ships.
+ *
+ * Scene reference-frame images (`scene.referenceImageId`) are intentionally NOT
+ * hashed: the i2v render pipeline that populates them is Phase 1b (unshipped)
+ * and its reference-image store/dir convention isn't defined yet — federating
+ * them is a follow-up. Path-traversal-guarded + missing-file-skipped via
+ * hashSimpleAsset; dedup by `<kind>:<filename>` so two scenes pointing at the
+ * same render ship once.
+ */
+async function buildMusicVideoAssetManifest(project) {
+ const dedup = new Map();
+ if (isStr(project?.uploadedAudioFilename)) {
+ const audio = await hashSimpleAsset(project.uploadedAudioFilename, 'music', PATHS.music);
+ if (audio) dedup.set(`${audio.kind}:${audio.filename}`, audio);
+ }
+ const scenes = Array.isArray(project?.scenes) ? project.scenes : [];
+ const videoIds = [...new Set(
+ scenes.map((s) => (isStr(s?.videoHistoryId) ? s.videoHistoryId : null)).filter(Boolean),
+ )];
+ if (videoIds.length) {
+ const byId = await videoHistoryFilenamesById();
+ const entries = await Promise.all(videoIds.map((id) =>
+ hashSimpleAsset(byId.get(id) || collectionVideoRefToFilename(id), 'video', PATHS.videos),
+ ));
+ for (const entry of entries) {
+ if (entry) dedup.set(`${entry.kind}:${entry.filename}`, entry);
+ }
+ }
+ return [...dedup.values()];
+}
+
/**
* Hash the local image bytes a mood board's items reference so the receiver can
* pull them from `/data/{images,image-refs,videos}/`. An image item points at
diff --git a/server/services/sharing/peerSync.test.js b/server/services/sharing/peerSync.test.js
index ecf6b9c96f..6d07f1910c 100644
--- a/server/services/sharing/peerSync.test.js
+++ b/server/services/sharing/peerSync.test.js
@@ -2289,6 +2289,111 @@ describe('peerSync', () => {
expect(captured[1].assetManifest).toEqual([expect.objectContaining({ kind: 'image', filename: 'album.png' })]);
expect(captured[2].assetManifest).toEqual([expect.objectContaining({ kind: 'music', filename: 'song.mp3' })]);
});
+
+ // --- Music Video project media federation (#1772) ---
+ const enableMusicVideoPeer = () => {
+ vi.mocked(getPeers).mockResolvedValue([{
+ instanceId: 'peer-a', name: 'Peer A', host: null, address: '10.0.0.2', port: 5555,
+ enabled: true, syncEnabled: true, directions: ['outbound', 'inbound'],
+ syncCategories: { musicVideoProjects: true },
+ }]);
+ };
+
+ it('bundles uploaded audio + rendered scene clips for a music video project push', async () => {
+ // #1772: the project record federated but shipped an empty manifest, so a
+ // selectively-subscribed peer never received the referenced media. Audio
+ // rides as a `music` entry (PATHS.music); each scene's videoHistoryId
+ // resolves through video-history.json to its `<filename>` under PATHS.videos.
+ enableMusicVideoPeer();
+ PATHS.videos = join(tmp, 'videos');
+ await mkdir(PATHS.videos, { recursive: true });
+ await writeFile(join(PATHS.music, 'mv-song.mp3'), Buffer.from('audio bytes'));
+ await writeFile(join(PATHS.videos, 'scene-one.mp4'), Buffer.from('clip one'));
+ await writeFile(join(PATHS.videos, 'scene-two.webm'), Buffer.from('clip two'));
+ // video-history.json maps each videoHistoryId → its on-disk basename.
+ await writeFile(join(tmp, 'video-history.json'), JSON.stringify([
+ { id: 'vh-1', filename: 'scene-one.mp4' },
+ { id: 'vh-2', filename: 'scene-two.webm' },
+ ]));
+ vi.mocked(getMusicVideoProject).mockResolvedValue({
+ id: 'mv-1', name: 'My Video', mode: 'director', trackId: null,
+ uploadedAudioFilename: 'mv-song.mp3',
+ scenes: [
+ { sceneId: 's-1', order: 0, videoHistoryId: 'vh-1', referenceImageId: 'ref-x' },
+ { sceneId: 's-2', order: 1, videoHistoryId: 'vh-2', referenceImageId: null },
+ { sceneId: 's-3', order: 2, videoHistoryId: null, referenceImageId: null },
+ ],
+ updatedAt: '2026-06-28T00:00:00Z', deleted: false, deletedAt: null,
+ });
+ let captured = null;
+ vi.mocked(peerFetch).mockImplementation(async (_url, opts) => {
+ captured = JSON.parse(opts.body);
+ return { ok: true, json: async () => ({ missingAssets: [] }) };
+ });
+ await pushRecordToPeer({
+ id: 'sub-mv', peerId: 'peer-a', recordKind: 'musicVideoProject', recordId: 'mv-1',
+ });
+ expect(captured.kind).toBe('musicVideoProject');
+ expect(captured.record.id).toBe('mv-1');
+ const byKind = (k) => captured.assetManifest.filter(a => a.kind === k).map(a => a.filename).sort();
+ expect(byKind('music')).toEqual(['mv-song.mp3']);
+ expect(byKind('video')).toEqual(['scene-one.mp4', 'scene-two.webm']);
+ // referenceImageId is Phase 1b — no image entry ships yet.
+ expect(byKind('image')).toEqual([]);
+ });
+
+ it('falls back to the <id>.mp4 convention when a scene clip has no video-history row', async () => {
+ // The metadata row may not have synced yet; the bare-id + .mp4 convention
+ // (collectionVideoRefToFilename) still resolves the bytes. A wrong guess is
+ // harmless — a missing file is skipped, never shipped.
+ enableMusicVideoPeer();
+ PATHS.videos = join(tmp, 'videos');
+ await mkdir(PATHS.videos, { recursive: true });
+ await writeFile(join(PATHS.videos, 'vh-orphan.mp4'), Buffer.from('orphan clip'));
+ vi.mocked(getMusicVideoProject).mockResolvedValue({
+ id: 'mv-2', name: 'No Rows', mode: 'director', trackId: null,
+ uploadedAudioFilename: null,
+ scenes: [{ sceneId: 's-1', order: 0, videoHistoryId: 'vh-orphan', referenceImageId: null }],
+ updatedAt: '2026-06-28T00:00:00Z', deleted: false, deletedAt: null,
+ });
+ let captured = null;
+ vi.mocked(peerFetch).mockImplementation(async (_url, opts) => {
+ captured = JSON.parse(opts.body);
+ return { ok: true, json: async () => ({ missingAssets: [] }) };
+ });
+ await pushRecordToPeer({
+ id: 'sub-mv2', peerId: 'peer-a', recordKind: 'musicVideoProject', recordId: 'mv-2',
+ });
+ expect(captured.assetManifest).toEqual([expect.objectContaining({ kind: 'video', filename: 'vh-orphan.mp4' })]);
+ });
+
+ it('ships an empty asset manifest for a tombstone music video project push', async () => {
+ enableMusicVideoPeer();
+ PATHS.videos = join(tmp, 'videos');
+ await mkdir(PATHS.videos, { recursive: true });
+ // Real files on disk would otherwise hash in — the deleted gate must skip
+ // the manifest builder entirely.
+ await writeFile(join(PATHS.music, 'doomed.mp3'), Buffer.from('bytes'));
+ await writeFile(join(PATHS.videos, 'doomed.mp4'), Buffer.from('bytes'));
+ await writeFile(join(tmp, 'video-history.json'), JSON.stringify([{ id: 'vh-d', filename: 'doomed.mp4' }]));
+ vi.mocked(getMusicVideoProject).mockResolvedValue({
+ id: 'mv-tomb', name: 'Doomed', mode: 'director', trackId: null,
+ uploadedAudioFilename: 'doomed.mp3',
+ scenes: [{ sceneId: 's-1', order: 0, videoHistoryId: 'vh-d', referenceImageId: null }],
+ updatedAt: '2026-06-28T03:00:00Z', deleted: true, deletedAt: '2026-06-28T03:00:00Z',
+ });
+ let captured = null;
+ vi.mocked(peerFetch).mockImplementation(async (_url, opts) => {
+ captured = JSON.parse(opts.body);
+ return { ok: true, json: async () => ({}) };
+ });
+ await pushRecordToPeer({
+ id: 'sub-mvt', peerId: 'peer-a', recordKind: 'musicVideoProject', recordId: 'mv-tomb',
+ });
+ expect(captured.record.id).toBe('mv-tomb');
+ expect(captured.record.deleted).toBe(true);
+ expect(captured.assetManifest).toEqual([]);
+ });
});
describe('collectSubscriptionsForUpdate', () => {