Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

fix: bundle linked track record in music-video federation push (#1858)

[._.]/ Adam Eivyd07f5ca33e0e
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 21972999b2..ab4e8d3473 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -29,7 +29,7 @@
## Fixed
-- **[issue-1858] Music-video federation now ships the linked track's master audio** — a music-video project created the normal way stores a `trackId` with `uploadedAudioFilename: null`, so its push manifest carried no master audio. A peer subscribed to the **Music Videos** category only (not Music/Tracks) received the project and scene clips but never the linked track, so its render later failed with `Linked track not found` / `AUDIO_MISSING`. `buildMusicVideoAssetManifest` now resolves the linked track via `getTrack` and bundles its `audioFilename` bytes alongside any uploaded audio (dedup-by-`music:<filename>` so a track that *also* federates ships once; a deleted/missing track or absent file contributes nothing). (#1858)
+- **[issue-1858] Music-video federation now ships the linked track to a Music-Videos-only subscriber** — a music-video project created the normal way stores a `trackId` with `uploadedAudioFilename: null`, so a peer subscribed to the **Music Videos** category only (not Music/Tracks) received the project and scene clips but no master audio, and its render failed with `Linked track not found` / `AUDIO_MISSING`. Because the receiver's `resolveMasterAudioPath()` looks the track up by id *before* touching any file, shipping the bytes alone wasn't enough — the push now bundles the linked **track record** itself (`linkedTrack`, merged via `mergeTracksFromSync` and gated by the same tombstone/opt-out rules as `linkedCollection`) *and* its `audioFilename` bytes in the music-video asset manifest. Additive optional payload key, so no schema-version bump and older peers ignore it; dedup-by-`music:<filename>` keeps a separately-federated track from double-shipping. (#1858)
- **[issue-1845] Client fetch hygiene — effect fetches now abort on cleanup and `window` is read lazily** — `StagePromptModelPicker` fired two effect `fetch`es guarded only by a `cancelled` flag, so rapid `stageName` changes wasted in-flight round-trips; it now passes an `AbortController` `signal` to both and aborts on cleanup. `LocalSetupPanel`'s `/setup/check` fetch had no abort and its `setChecking(false)` `finally` could fire after unmount; it now aborts the prior/in-flight check (so a stale response can't clobber a newer one) and guards every state set behind a `mountedRef`. `VoiceCapture` read `window.SpeechRecognition` at module scope — a `ReferenceError` when the file is imported in an SSR/Node test context — now resolved lazily via a `useState` initializer that only runs in the browser. And `useArmedAction`'s `fire` is wrapped in `useCallback` so memoized children stay stable. (#1845)
- **`useEscapeKey`/`useClickOutside` no longer thrash their global listener on every render** — both hooks kept the caller's `handler`/`onOutside` in the effect dep array, so the `window` keydown/mousedown listener was removed and re-added on every parent render while open. Since most call sites pass a fresh inline arrow (`() => setOpenCommentId(null)`), that meant a full detach+reattach on *every keystroke* in editors like `PipelineManuscriptEditor`/`AnnotatedManuscriptSection` and on every render of `SceneCard`/`WorkEditor`/`UniverseBuilder`. Both hooks now read the handler through a ref (the same pattern `useKeyboardShortcuts` already uses), so the listener subscribes only when `active` (and, for `useClickOutside`, `ref`) changes while still always invoking the latest handler. Behavior-preserving; covered by new hook tests. (#1844)
- **Blocking sync I/O removed from request/completion hot paths** — several syscalls ran synchronously on paths that serve live SSE/socket traffic, freezing the event loop for their duration. `checkForTaskCommit` (`agentRunTracking.js`) ran a `spawnSync('git', ['log', …])` on the completion path of every failed CoS run (100ms–2s on a large repo); it now uses the async, hard-timeout `bufferedSpawn`. `buildId.js` `statSync`'d `client/dist/index.html` on every SPA navigation; the freshness check is now throttled to at most once per second (the hot path between checks is a clock comparison, no syscall), so a rebuild re-syncs the served HTML with the on-disk chunks within the throttle window instead of paying a stat per navigation. The avatar (`routes/avatar.js`) and attachment (`routes/attachments.js`) routes swapped `existsSync`/`statSync` for async `fs.access`/`fs.stat` (via a new canonical `pathExists` helper in `fileUtils.js`), and uploads now call the idempotent `ensureDir` directly. Separately, the tombstone-prune paths for authors/tracks/creative-director projects (DB + file backends) wrapped their per-record `deleteSyncBaseHash` loops in `withBaseHashFlushBatch`, collapsing N `sync_base_hashes.json` rewrites into one. (#1828)
diff --git a/server/services/sharing/peerSync.test.js b/server/services/sharing/peerSync.test.js
index 59da026b4f..6baf2b2114 100644
--- a/server/services/sharing/peerSync.test.js
+++ b/server/services/sharing/peerSync.test.js
@@ -2369,6 +2369,54 @@ describe('peerSync', () => {
expect(byKind('image')).toEqual(['ref-x.png']);
});
+ it('bundles the linked track record + its master audio for a track-linked project (#1858)', async () => {
+ // The create-UI path stores trackId with uploadedAudioFilename: null. A
+ // peer subscribed to musicVideoProjects ONLY (no Tracks category) needs
+ // both the audio BYTES (manifest) and the track RECORD (linkedTrack) — the
+ // receiver's resolveMasterAudioPath() looks the track up by id first.
+ enableMusicVideoPeer();
+ await writeFile(join(PATHS.music, 'linked.mp3'), Buffer.from('linked track audio'));
+ vi.mocked(getTrack).mockResolvedValue({
+ id: 'track-7', title: 'Anthem', audioFilename: 'linked.mp3',
+ updatedAt: '2026-06-28T00:00:00Z', deleted: false, deletedAt: null,
+ });
+ vi.mocked(getMusicVideoProject).mockResolvedValue({
+ id: 'mv-3', name: 'Linked', mode: 'director', trackId: 'track-7',
+ uploadedAudioFilename: null, scenes: [],
+ 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-mv3', peerId: 'peer-a', recordKind: 'musicVideoProject', recordId: 'mv-3',
+ });
+ expect(captured.assetManifest.filter(a => a.kind === 'music').map(a => a.filename)).toEqual(['linked.mp3']);
+ expect(captured.linkedTrack?.id).toBe('track-7');
+ expect(captured.linkedTrack?.audioFilename).toBe('linked.mp3');
+ });
+
+ it('omits linkedTrack when the project has no linked track', async () => {
+ enableMusicVideoPeer();
+ vi.mocked(getMusicVideoProject).mockResolvedValue({
+ id: 'mv-4', name: 'Upload only', mode: 'director', trackId: null,
+ uploadedAudioFilename: null, scenes: [],
+ 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-mv4', peerId: 'peer-a', recordKind: 'musicVideoProject', recordId: 'mv-4',
+ });
+ expect(captured.kind).toBe('musicVideoProject');
+ expect('linkedTrack' in captured).toBe(false);
+ });
+
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
@@ -2555,6 +2603,46 @@ describe('peerSync', () => {
expect(mergeMediaCollectionsFromSync).not.toHaveBeenCalled();
});
+ it('routes a bundled linkedTrack through mergeTracksFromSync on a music-video push (#1858)', async () => {
+ const linkedTrack = {
+ id: 'track-9', title: 'Anthem', audioFilename: 'linked.mp3',
+ updatedAt: '2026-06-28T00:00:00Z', deleted: false, deletedAt: null,
+ };
+ await applyIncomingPush({
+ kind: 'musicVideoProject',
+ record: { id: 'mv-1', name: 'Linked', trackId: 'track-9', deleted: false, deletedAt: null },
+ linkedTrack,
+ assetManifest: [],
+ sourceInstanceId: 'peer-a',
+ });
+ expect(mergeMusicVideoProjectsFromSync).toHaveBeenCalledWith(
+ [expect.objectContaining({ id: 'mv-1' })],
+ { source: { via: 'peer-push', peerId: 'peer-a' } },
+ );
+ expect(mergeTracksFromSync).toHaveBeenCalledWith(
+ [linkedTrack],
+ { source: { via: 'peer-push', peerId: 'peer-a' } },
+ );
+ });
+
+ it('skips linkedTrack merge when none is bundled or the project is a tombstone', async () => {
+ await applyIncomingPush({
+ kind: 'musicVideoProject',
+ record: { id: 'mv-2', trackId: 'track-9', deleted: false, deletedAt: null },
+ assetManifest: [],
+ sourceInstanceId: 'peer-a',
+ });
+ expect(mergeTracksFromSync).not.toHaveBeenCalled();
+ await applyIncomingPush({
+ kind: 'musicVideoProject',
+ record: { id: 'mv-3', trackId: 'track-9', deleted: true, deletedAt: '2026-06-29T00:00:00Z' },
+ linkedTrack: { id: 'track-9', audioFilename: 'linked.mp3' },
+ assetManifest: [],
+ sourceInstanceId: 'peer-a',
+ });
+ expect(mergeTracksFromSync).not.toHaveBeenCalled();
+ });
+
it('routes a bundled manuscriptReview through mergeReviewFromSync on a series push', async () => {
const manuscriptReview = {
schemaVersion: 1,
diff --git a/server/services/sharing/peerSyncPush.js b/server/services/sharing/peerSyncPush.js
index 3ce149e562..c79e326898 100644
--- a/server/services/sharing/peerSyncPush.js
+++ b/server/services/sharing/peerSyncPush.js
@@ -753,7 +753,22 @@ export async function buildPushPayload(sub, sourceInstanceId) {
const sanitized = sanitizeRecordForWire('musicVideoProject', record);
if (!sanitized) return null;
const assetManifest = record.deleted === true ? [] : await buildMusicVideoAssetManifest(record);
- return { kind: 'musicVideoProject', record: sanitized, assetManifest, sourceInstanceId, portosMeta };
+ // #1858: bundle the LINKED TRACK RECORD (create-UI projects store `trackId`,
+ // not `uploadedAudioFilename`). The audio BYTES ride `assetManifest` above,
+ // but the receiver's `resolveMasterAudioPath()` looks the track up by id
+ // FIRST and throws "Linked track not found" without the record — so a peer
+ // subscribed to `musicVideoProjects` only (no Tracks category) needs the
+ // record itself to render. Additive optional key: an older receiver ignores
+ // it (same as before), so no schema-version bump (mirrors `linkedCollection`).
+ let linkedTrack = null;
+ if (record.deleted !== true && isStr(record.trackId)) {
+ const track = await getTrack(record.trackId, { includeDeleted: true }).catch(() => null);
+ if (track && track.deleted !== true) linkedTrack = sanitizeRecordForWire('track', track);
+ }
+ return {
+ kind: 'musicVideoProject', record: sanitized, assetManifest, sourceInstanceId, portosMeta,
+ ...(linkedTrack ? { linkedTrack } : {}),
+ };
}
return null;
}
diff --git a/server/services/sharing/peerSyncReceive.js b/server/services/sharing/peerSyncReceive.js
index d458953318..13d7c203e4 100644
--- a/server/services/sharing/peerSyncReceive.js
+++ b/server/services/sharing/peerSyncReceive.js
@@ -109,7 +109,7 @@ export async function applyIncomingPush(payload) {
if (!isPlainObject(payload)) {
throw makeErr('payload must be an object', ERR_VALIDATION);
}
- const { kind, record, issues, linkedCollection, catalogBundle, manuscriptReview, reverseOutline, assetManifest, draftBodyManifest, sourceInstanceId, portosMeta } = payload;
+ const { kind, record, issues, linkedCollection, linkedTrack, catalogBundle, manuscriptReview, reverseOutline, assetManifest, draftBodyManifest, sourceInstanceId, portosMeta } = payload;
if (!PEER_SUBSCRIBABLE_KINDS.includes(kind)) {
throw makeErr(`unknown kind: ${kind}`, ERR_VALIDATION);
}
@@ -225,6 +225,12 @@ export async function applyIncomingPush(payload) {
} else if (kind === 'series') {
const local = await getSeries(record.id, { includeDeleted: true }).catch(() => null);
localEphemeral = local?.ephemeral === true;
+ } else if (kind === 'musicVideoProject') {
+ // #1858: the music-video push now carries a secondary `linkedTrack` bundle,
+ // so it needs the same opt-out gate — a stale peer push must not plant a
+ // track record for a project the user marked ephemeral.
+ const local = await getMusicVideoProject(record.id, { includeDeleted: true }).catch(() => null);
+ localEphemeral = local?.ephemeral === true;
}
// Merge into local state via the existing LWW path. The merge functions
@@ -311,6 +317,16 @@ export async function applyIncomingPush(payload) {
await mergeExercisesFromSync([record], { source });
} else if (kind === 'musicVideoProject') {
await mergeMusicVideoProjectsFromSync([record], { source });
+ // #1858: merge the bundled linked track record so a receiver WITHOUT the
+ // Tracks category can still resolve `project.trackId` (getTrack) at render
+ // time. The audio bytes already pulled via assetManifest. Non-fatal: the
+ // project itself is merged; skip on a tombstone push, a local-ephemeral
+ // (opted-out) project, or a missing bundle — same contract as linkedCollection.
+ if (!localEphemeral && record.deleted !== true && isPlainObject(linkedTrack)) {
+ await mergeTracksFromSync([linkedTrack], { source }).catch((err) => {
+ console.log(`⚠️ peerSync: linkedTrack merge failed: ${err.message}`);
+ });
+ }
}
// Apply the bundled collection (if any) — same LWW + union-of-items