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 master audio in music-video federation manifest (#1858)

[._.]/ Adam Eivydfc5dc74da14
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 3513cc821d..21972999b2 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -29,6 +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-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/peerSyncAssets.js b/server/services/sharing/peerSyncAssets.js
index 951ecb39c0..53cf7bbcaa 100644
--- a/server/services/sharing/peerSyncAssets.js
+++ b/server/services/sharing/peerSyncAssets.js
@@ -30,7 +30,7 @@ import { findCollectionBySeriesId } from '../mediaCollections.js';
import { headshotImageFilename } from '../authors/index.js';
import { portraitImageFilename } from '../artists/index.js';
import { coverImageFilename } from '../albums/index.js';
-import { trackAudioFilename } from '../tracks/index.js';
+import { trackAudioFilename, getTrack } from '../tracks/index.js';
import { startingImageFilename } from '../creativeDirector/local.js';
import { imageUrlToAppAsset } from '../moodBoard/index.js';
import { WRITERS_ROOM_DRAFT_ASSET_KIND } from '../writersRoom/syncLogic.js';
@@ -390,10 +390,17 @@ async function videoHistoryFilenamesById() {
* 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.
+ * - the master audio. A project stores EITHER an uploaded basename
+ * (`uploadedAudioFilename`) OR a `trackId` pointing at a music-library track
+ * whose `audioFilename` lives under the same PATHS.music dir; the create UI's
+ * normal path is the latter. We bundle whichever one carries the bytes (#1858)
+ * so a peer subscribed to `musicVideoProjects` ONLY — not the music/tracks
+ * category — still receives playable audio instead of `resolveMasterAudioPath()`
+ * later failing with `Linked track not found` / `AUDIO_MISSING`. When the
+ * linked track ALSO federates (the peer has the music category), dedup by
+ * `music:<filename>` ships it exactly once. The track is dynamic-resolved via
+ * `getTrack`; a deleted/missing track or a track with no `audioFilename` simply
+ * contributes nothing (a missing file is skipped, same as every other ref).
* - 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
@@ -411,8 +418,17 @@ async function videoHistoryFilenamesById() {
*/
export async function buildMusicVideoAssetManifest(project) {
const dedup = new Map();
- if (isStr(project?.uploadedAudioFilename)) {
- const audio = await hashSimpleAsset(project.uploadedAudioFilename, 'music', PATHS.music);
+ // Master audio: the uploaded basename and/or the linked track's audioFilename
+ // (the create-UI path stores trackId with uploadedAudioFilename: null, so a
+ // music-video-only subscriber gets no audio unless we resolve+bundle it here).
+ const audioNames = [];
+ if (isStr(project?.uploadedAudioFilename)) audioNames.push(project.uploadedAudioFilename);
+ if (isStr(project?.trackId)) {
+ const track = await getTrack(project.trackId).catch(() => null);
+ if (isStr(track?.audioFilename)) audioNames.push(track.audioFilename);
+ }
+ for (const name of [...new Set(audioNames)]) {
+ const audio = await hashSimpleAsset(name, 'music', PATHS.music);
if (audio) dedup.set(`${audio.kind}:${audio.filename}`, audio);
}
const scenes = Array.isArray(project?.scenes) ? project.scenes : [];
diff --git a/server/services/sharing/peerSyncAssets.test.js b/server/services/sharing/peerSyncAssets.test.js
new file mode 100644
index 0000000000..9a21ff0216
--- /dev/null
+++ b/server/services/sharing/peerSyncAssets.test.js
@@ -0,0 +1,97 @@
+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
+import { mkdtempSync, rmSync, writeFileSync, mkdirSync } from 'fs';
+import { tmpdir } from 'os';
+import { join } from 'path';
+import { createHash } from 'crypto';
+import { makePathsProxy } from '../../lib/mockPathsDataRoot.js';
+
+// Seed a root before the dynamic import below: peerSyncAssets transitively
+// pulls in modules that read PATHS.data at module-evaluation time, so the
+// proxy's dataRoot getter must already resolve to a string.
+let tempRoot = mkdtempSync(join(tmpdir(), 'portos-mv-assets-boot-'));
+
+vi.mock('../../lib/fileUtils.js', async () => {
+ const actual = await vi.importActual('../../lib/fileUtils.js');
+ return makePathsProxy(actual, {
+ dataRoot: () => tempRoot,
+ extraOverrides: (root) => ({ music: join(root, 'music') }),
+ });
+});
+
+// Tracks are db-primary; stub the dispatcher so the manifest builder never
+// touches Postgres. trackAudioFilename mirrors the real basename sanitizer.
+vi.mock('../tracks/index.js', async () => ({
+ getTrack: vi.fn(),
+ trackAudioFilename: vi.fn((name) =>
+ (typeof name === 'string' && name.trim() && !/[\\/]|\.\./.test(name) ? name.trim() : null)),
+}));
+
+const { getTrack } = await import('../tracks/index.js');
+const { buildMusicVideoAssetManifest } = await import('./peerSyncAssets.js');
+
+const sha = (buf) => createHash('sha256').update(buf).digest('hex');
+
+function writeMusic(filename, bytes) {
+ const dir = join(tempRoot, 'music');
+ mkdirSync(dir, { recursive: true });
+ writeFileSync(join(dir, filename), bytes);
+}
+
+describe('buildMusicVideoAssetManifest — master audio', () => {
+ beforeEach(() => {
+ tempRoot = mkdtempSync(join(tmpdir(), 'portos-mv-assets-'));
+ vi.mocked(getTrack).mockReset().mockResolvedValue(null);
+ });
+ afterEach(() => {
+ if (tempRoot) rmSync(tempRoot, { recursive: true, force: true });
+ });
+
+ it('bundles the uploaded audio basename (no track)', async () => {
+ const bytes = Buffer.from('uploaded-audio');
+ writeMusic('upload.mp3', bytes);
+ const manifest = await buildMusicVideoAssetManifest({
+ trackId: null, uploadedAudioFilename: 'upload.mp3', scenes: [],
+ });
+ expect(manifest).toContainEqual({ filename: 'upload.mp3', kind: 'music', sha256: sha(bytes) });
+ expect(getTrack).not.toHaveBeenCalled();
+ });
+
+ it('resolves and bundles the linked track audio when uploadedAudioFilename is null (#1858)', async () => {
+ const bytes = Buffer.from('track-audio');
+ writeMusic('track-1.wav', bytes);
+ vi.mocked(getTrack).mockResolvedValue({ id: 'trk-1', audioFilename: 'track-1.wav' });
+ const manifest = await buildMusicVideoAssetManifest({
+ trackId: 'trk-1', uploadedAudioFilename: null, scenes: [],
+ });
+ expect(getTrack).toHaveBeenCalledWith('trk-1');
+ expect(manifest).toContainEqual({ filename: 'track-1.wav', kind: 'music', sha256: sha(bytes) });
+ });
+
+ it('skips a missing/deleted track without throwing', async () => {
+ vi.mocked(getTrack).mockResolvedValue(null);
+ const manifest = await buildMusicVideoAssetManifest({
+ trackId: 'gone', uploadedAudioFilename: null, scenes: [],
+ });
+ expect(manifest).toEqual([]);
+ });
+
+ it('skips a track whose audio file is absent on disk (never ships a null hash)', async () => {
+ vi.mocked(getTrack).mockResolvedValue({ id: 'trk-2', audioFilename: 'nope.wav' });
+ const manifest = await buildMusicVideoAssetManifest({
+ trackId: 'trk-2', uploadedAudioFilename: null, scenes: [],
+ });
+ expect(manifest).toEqual([]);
+ });
+
+ it('dedups when the upload basename and the linked track point at the same file', async () => {
+ const bytes = Buffer.from('shared');
+ writeMusic('shared.mp3', bytes);
+ vi.mocked(getTrack).mockResolvedValue({ id: 'trk-3', audioFilename: 'shared.mp3' });
+ const manifest = await buildMusicVideoAssetManifest({
+ trackId: 'trk-3', uploadedAudioFilename: 'shared.mp3', scenes: [],
+ });
+ const audio = manifest.filter((m) => m.kind === 'music');
+ expect(audio).toHaveLength(1);
+ expect(audio[0]).toEqual({ filename: 'shared.mp3', kind: 'music', sha256: sha(bytes) });
+ });
+});