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: fan track edits out to linked music-video projects + id-match the bundle (#1858)

[._.]/ Adam Eivy7d3a30ab8cf0
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index ab4e8d3473..deb0d970c2 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -29,7 +29,7 @@
## Fixed
-- **[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-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. A linked-track edit now also fans a push out to every music-video project that links it (so the bundled audio stays fresh on a Music-Videos-only peer), the receiver requires the bundle's id to match the project's `trackId` (no smuggling an unrelated track), and the bundle rides the push hash + schema gate + delivery-pending ack exactly like the existing `linkedCollection`/`manuscriptReview` bundles. (#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.js b/server/services/sharing/peerSync.js
index 3c48b80e9e..523cb72e5c 100644
--- a/server/services/sharing/peerSync.js
+++ b/server/services/sharing/peerSync.js
@@ -652,7 +652,20 @@ export async function collectSubscriptionsForUpdate(recordKind, recordId) {
// collection edits would only reach peers via initial subscribe / manual
// force-push, never on subsequent edits.
if (PEER_SUBSCRIBABLE_KINDS.includes(recordKind)) {
- return listPeerSubscriptions({ recordKind, recordId });
+ const direct = await listPeerSubscriptions({ recordKind, recordId });
+ // #1858: a track edit must ALSO re-push every music-video project that links
+ // it. The linked track's record + master-audio bytes ride the project's push
+ // (a `musicVideoProjects`-only subscriber has no direct `track` sub), so
+ // without this fan-out the project's audio would go stale on that peer until
+ // the project itself is edited. Mirrors the issue→series resolution below.
+ if (recordKind === 'track') {
+ const projectSubs = await collectMusicVideoSubsForTrack(recordId);
+ if (projectSubs.length === 0) return direct;
+ const byId = new Map(direct.map((s) => [s.id, s]));
+ for (const s of projectSubs) byId.set(s.id, s);
+ return [...byId.values()];
+ }
+ return direct;
}
if (recordKind === 'issue') {
const seriesId = await getIssueSeriesId(recordId);
@@ -662,6 +675,22 @@ export async function collectSubscriptionsForUpdate(recordKind, recordId) {
return [];
}
+// #1858: every music-video-project subscription whose project links `trackId`.
+// Backs the track→project push fan-out in collectSubscriptionsForUpdate so a
+// linked-track edit reaches a `musicVideoProjects`-only subscriber. The project
+// list is small (per-install), so a full scan on the debounce path is fine —
+// same posture as getIssueSeriesId's issue scan below.
+async function collectMusicVideoSubsForTrack(trackId) {
+ if (!isNonEmptyStr(trackId)) return [];
+ const projects = await listMusicVideoProjects({ includeDeleted: false }).catch(() => []);
+ const linked = projects.filter((p) => p?.trackId === trackId && isNonEmptyStr(p?.id));
+ if (linked.length === 0) return [];
+ const subLists = await Promise.all(
+ linked.map((p) => listPeerSubscriptions({ recordKind: 'musicVideoProject', recordId: p.id })),
+ );
+ return subLists.flat();
+}
+
async function getIssueSeriesId(issueId) {
// Avoid pulling in `getIssue` directly (cyclic risk during init): list
// the cohort of issues and pick the matching id. The issues file is
diff --git a/server/services/sharing/peerSync.test.js b/server/services/sharing/peerSync.test.js
index 760d897054..85065c4d4e 100644
--- a/server/services/sharing/peerSync.test.js
+++ b/server/services/sharing/peerSync.test.js
@@ -2497,6 +2497,31 @@ describe('peerSync', () => {
expect(subs.every((s) => s.recordKind === 'mediaCollection')).toBe(true);
});
+ it('fans a track update out to music-video projects that link it (#1858)', async () => {
+ 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 },
+ }]);
+ vi.mocked(getMusicVideoProject).mockResolvedValue({
+ id: 'mv-link', name: 'Linked', mode: 'director', trackId: 'track-7',
+ uploadedAudioFilename: null, scenes: [],
+ updatedAt: '2026-06-28T00:00:00Z', deleted: false, deletedAt: null,
+ });
+ vi.mocked(listMusicVideoProjects).mockResolvedValue([
+ { id: 'mv-link', trackId: 'track-7' },
+ { id: 'mv-other', trackId: 'track-99' },
+ ]);
+ vi.mocked(peerFetch).mockResolvedValue({ ok: true, json: async () => ({ missingAssets: [] }) });
+ await subscribePeer({ peerId: 'peer-a', recordKind: 'musicVideoProject', recordId: 'mv-link' });
+ await __drainForTests();
+
+ const subs = await collectSubscriptionsForUpdate('track', 'track-7');
+ expect(subs.some((s) => s.recordKind === 'musicVideoProject' && s.recordId === 'mv-link')).toBe(true);
+ // A project linking a DIFFERENT track is not fanned out.
+ expect(subs.some((s) => s.recordId === 'mv-other')).toBe(false);
+ });
+
it('returns [] for a kind with no direct/parent subscription path', async () => {
expect(await collectSubscriptionsForUpdate('image', 'whatever')).toEqual([]);
});
@@ -2643,6 +2668,17 @@ describe('peerSync', () => {
expect(mergeTracksFromSync).not.toHaveBeenCalled();
});
+ it('refuses a linkedTrack whose id does not match the project trackId (#1858)', async () => {
+ await applyIncomingPush({
+ kind: 'musicVideoProject',
+ record: { id: 'mv-5', trackId: 'track-A', deleted: false, deletedAt: null },
+ linkedTrack: { id: 'track-SMUGGLED', audioFilename: 'x.mp3' },
+ assetManifest: [],
+ sourceInstanceId: 'peer-a',
+ });
+ expect(mergeTracksFromSync).not.toHaveBeenCalled();
+ });
+
it('signals trackSyncPending when the bundled linkedTrack merge fails (#1858)', async () => {
// The linked track has no independent reconciliation cycle for a
// musicVideoProjects-only subscriber, so a swallowed failure must surface
diff --git a/server/services/sharing/peerSyncReceive.js b/server/services/sharing/peerSyncReceive.js
index c9041557a1..439ce73c78 100644
--- a/server/services/sharing/peerSyncReceive.js
+++ b/server/services/sharing/peerSyncReceive.js
@@ -191,7 +191,8 @@ export async function applyIncomingPush(payload) {
// forward-shaped track row past the gate via a music-video push (same reasoning
// as the linkedCollection gate above). Skip the gate for a tombstone track —
// id+deleted+deletedAt+updatedAt is schema-safe at every version.
- if (record.deleted !== true && isPlainObject(linkedTrack) && linkedTrack.deleted !== true) {
+ if (record.deleted !== true && isPlainObject(linkedTrack) && linkedTrack.deleted !== true
+ && linkedTrack.id === record.trackId) {
for (const c of RECORD_KIND_SCHEMA_CATEGORIES.track) relevantCategories.add(c);
}
const fullDiff = compareSchemaVersions(senderSchemaVersions, PORTOS_SCHEMA_VERSIONS);
@@ -335,7 +336,11 @@ export async function applyIncomingPush(payload) {
// 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)) {
+ // Require the bundle's id to MATCH the project's `trackId` so a malformed/
+ // malicious sender can't smuggle an unrelated track record through the
+ // music-video push (the project only needs the track it actually links).
+ if (!localEphemeral && record.deleted !== true && isPlainObject(linkedTrack)
+ && linkedTrack.id === record.trackId) {
await mergeTracksFromSync([linkedTrack], { source }).catch((err) => {
console.log(`⚠️ peerSync: linkedTrack merge failed: ${err.message}`);
trackSyncPending = true;