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
feat([issue-1566]): federate the standalone media library across full-sync peers
[._.]/ Adam Eivybb0809560040
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 998b3a6a86..a795a5e695 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -98,6 +98,8 @@- **[issue-1564] Mood Boards now federate across peers (completing #1564).** Mood boards (the pinned image + text reference canvas) were `db-primary` but local-only, so a node pair couldn't mirror them. Boards now ride the same per-record peer-sync push pipeline as Creative Director projects: there's a new **Mood Boards** sync category on the Instances page (and it's covered automatically by Full mirror peers), creating a board auto-subscribes it to every board-enabled peer, edits propagate as last-write-wins (newer `updatedAt` wins, with a Conflicts-tab entry archived — restorable down to the board's `items[]` — when both sides diverged from a common base), and a delete becomes a tombstone the merge keeps an out-of-date peer from resurrecting. Image bytes a board's items reference (gallery media-keys or `/data/images/...` URLs) replicate as pulled assets; external image URLs resolve on the receiver. Cross-version pushes are version-gated (`moodBoards` schema v1) so a newer peer can't corrupt an older one. (`server/services/moodBoard/`, `server/services/sharing/peerSync.js`, `server/services/sharing/tombstoneGc.js`, `server/services/conflictJournalResolver.js`, `server/lib/schemaVersions.js`, `server/lib/syncWire.js`, `server/lib/conflictJournal.js`, `server/lib/peerSyncValidation.js`, `client/src/pages/Instances.jsx`)+- **[issue-1566] Your whole media library now mirrors across full-mirror peers — not just media attached to a synced story.** Until now a node pair only replicated image/video bytes that were *referenced by a synced creative record* (a universe, series, mood board, …); images and videos you generated standalone, pipeline-rendered audio, and uploaded music never crossed, so each machine's **Media** tab showed a different library. Full-mirror peers now also replicate the **standalone media library** — generated images (with their gen-params sidecars), generated videos, pipeline audio, and uploaded music. Each machine periodically asks its full-mirror peers for a library manifest (filename + SHA-256 per asset), pulls only the bytes it's missing (integrity-checked, resumable, capped per file), regenerates video thumbnails locally, and rebuilds its media index so the new media appears in the gallery automatically. Video generation *history* already converged; now the underlying `.mp4`/image bytes do too, so a peer pair's Media tab truly matches. Byte replication is gated to full-mirror peers (it can move a lot of data) and honors your backup exclusions — a media folder you've excluded from backup isn't federated either. Regular (non-full-mirror) peers are unchanged. (`server/services/sharing/peerSync.js`, `server/services/sharing/index.js`, `server/routes/peerSync.js`, `server/lib/schemaVersions.js`, `server/lib/peerSyncValidation.js`)+- **Comic-page proof/final render buttons no longer get stuck "loading"/disabled on already-rendered pages.** Navigating into an issue's Comic tab — for example right after kicking off an unrelated render like a volume cover — could leave a page's **Proof**/**Final** buttons spinning and disabled even though that page's render finished long ago. The in-flight check re-armed an "unknown" status on every navigation and only cleared it once a job-status fetch (or a 5-second grace timer) resolved, ignoring that the slot already carried a rendered image. It now treats a slot that already has a rendered filename as settled immediately (the server clears the filename when a re-render is queued, so a present filename is an authoritative "done" signal), so the buttons are clickable right away and you can queue the next render without waiting. (`client/src/hooks/useSlotInFlight.js`)- **The Volume covers section on a series page is now expanded by default** instead of starting collapsed, so the front/back cover editors and render buttons are visible without an extra click. (`client/src/components/pipeline/ArcCanvas.jsx`)- **Claude Code TUI agents now reliably wait for the input prompt before sending their task (and no longer wedge the shell on startup hiccups).** TUI-provider CoS agents (e.g. `claude-code-tui`) run their CLI as a *child* of a persistent PTY shell, and the old prompt-delivery gate fired on a crude "saw output, then went idle" heuristic. During Claude Code's startup that lull happens *before* the input box exists — and on a folder it hasn't seen, claude shows a **"trust this folder?" gate** that `--dangerously-skip-permissions` does not bypass (common because agents start in fresh worktrees). The gate would paste the task into the banner / trust menu, or — if claude had already exited — into the returned shell prompt, leaving a frozen, un-typeable session showing a literal `^[[200~ …` and a silently-failed run. The spawner now (1) **waits until the shell can actually run commands** before injecting the CLI command — a fixed 200 ms delay raced a heavy interactive shell (powerlevel10k / async plugins / nvm-PATH setup), so the command ran before the env was ready and the launched TUI fell straight back to the prompt. Heuristic timing watches (a prompt-marker, or settle-on-output-quiet) are *both* fooled by powerlevel10k's *instant prompt* (it renders a fake-ready prompt — and enables bracketed-paste mode — before `.zshrc` finishes) and by slow mid-load quiet gaps (nvm/plugins) that trip a settle timer just as easily, sending the command into a half-loaded shell where the instant-prompt→real-prompt redraw swallows it (the command sits echoed-but-unexecuted at a bare prompt — the intermittent wedge). It now **proves the shell is executing commands with a round-trip probe**: it prints a unique nonce and waits to *see that nonce in the output* before injecting the command. The nonce is split in the probe source (`'PORTOSRDY' '<nonce>'`) so the command echo never contains the assembled string — only the executed output matches — and instant-prompt keystroke buffering replays the probe into the real shell, so the gate is theme- and shell-agnostic with a bounded fallback if the probe never round-trips, (2) gates the paste on claude **re-enabling bracketed-paste mode** (`ESC[?2004h`, after the shell turned it off to run the command) as the input-ready signal — this is what makes the paste's leading `ESC` read as a paste rather than as Escape (which cancels claude's input — the intermittent "something other than Enter canceled it" failure); the visible footer text (`bypass permissions on (shift+tab to cycle)`) is deliberately NOT used because claude renders it with inter-glyph cursor moves that strip its spaces after ANSI-stripping, making it unmatchable, (3) **auto-confirms the folder-trust prompt** (Enter on the default "Yes, I trust") so claims run in fresh worktrees, (4) probes that the CLI is still a live child of the shell before pasting, and (5) **never blind-pastes** — if the input prompt never appears within 45 s (or the CLI exited), it finalizes the run as a failure carrying the CLI's captured output (`tui-not-ready` / `tui-exited-early`) instead of dumping into the shell. Non-claude TUI providers keep their existing handshake. (`server/services/agentTuiSpawning.js`, `server/lib/tuiHandshake.js`, `server/services/shell.js`)diff --git a/docs/STORAGE.md b/docs/STORAGE.mdindex 68fc6911e4..f510858086 100644--- a/docs/STORAGE.md+++ b/docs/STORAGE.md@@ -70,6 +70,8 @@ PostgreSQL is a **required** install/runtime dependency (see [Backup & Restore](**Media asset index (`media_assets`, #1000).** One row per generated image/video: `media_key` (`<kind>:<ref>`) PK, `kind`/`ref`/`created_at` mirror columns for queries, the full metadata record in `data` JSONB. It is a **derived index** — the on-disk sidecars + `video-history.json` stay authoritative — reconciled from disk at boot (upsert every asset, prune rows whose file is gone) and kept warm by a generation-`completed` hook. Local-only (rebuilt from disk), so no sync cursor/tombstone. Adapter: `server/services/mediaAssetIndex/{logic,db,index}.js`.+**Standalone media-library federation (`mediaLibrary`, #1566).** For **full-sync peers**, the standalone media-library *bytes* (generated images + sidecars, videos, pipeline audio, uploaded music) mirror across the pair — not just bytes referenced by a synced creative record. The sender advertises a library-level manifest at `GET /api/peer-sync/library-manifest` (`{ schemaVersion, manifestHash, assets:[{kind,filename,sha256,sidecarSha256?}] }`); the receiver's periodic sweep (`syncMediaLibraryFromPeer`, driven from `initSharing`) diffs it against local disk, receiver-pulls missing bytes through the SAME `diffAssetManifestAgainstLocal` + `pullOneAsset` machinery as the per-record path, then rebuilds the derived `media_assets` index. Video thumbnails are regenerated locally on video pull (not byte-federated); `video-history.json` metadata already union-merges via the `videoHistory` dataSync category; the generic `data/history.jsonl` action log is machine-local and never federated. Byte replication is gated to `peer.fullSync` and honors backup `DEFAULT_EXCLUDES` (a media dir excluded from backup isn't federated). Manifest envelope versioned by `PORTOS_SCHEMA_VERSIONS.mediaLibrary` (a non-record category — see `NON_RECORD_SCHEMA_CATEGORIES`); the receiver gently skips a sender ahead of its version.+**Postgres-First target (remaining).** `data/history.jsonl` (action log) and the durable portions of `data/media-jobs.json` (job history / lineage) are still file-backed — follow-up slices. Do **not** move generated image/video/audio bytes into PostgreSQL.---diff --git a/docs/plans/2026-06-24-media-library-federation.md b/docs/plans/2026-06-24-media-library-federation.mdnew file mode 100644index 0000000000..037f7583a0--- /dev/null+++ b/docs/plans/2026-06-24-media-library-federation.md@@ -0,0 +1,72 @@+# Media-library federation (#1566)++**Approved:** 2026-06-24 · **Issue:** #1566 (child of #1561 full-sync tracking) · **Branch:** `next/issue-1566`++## Goal++For a declared **full-sync** peer pair, mirror the *standalone* media library — generated+images/videos/thumbnails/audio plus user-uploaded music — and their bytes, so each peer's+Media tab is a complete replica. Today only assets *referenced by a synced creative record*+get receiver-pulled; the standalone library + its bytes do not federate.++## Key finding — most of the machinery already exists++- **Byte transport** is fully reusable: static mounts for `/data/{images,image-refs,videos,+ video-thumbnails,audio,music}` all exist (`server/index.js`), and `fetchCappedAssetBuffer`+ + the receiver-pull diff are generic.+- **Video history metadata already union-merges** via the `videoHistory` dataSync category+ (union by `id`, LWW) for *all* peers — what's missing is the backing `.mp4`/thumbnail bytes.+- **`media_assets` is a derived index** rebuilt from disk by `reconcileMediaAssets()`+ (idempotent) — the receiver just re-runs it after bytes land.++So #1566 reduces to: a **library-level manifest** (vs per-record), a **fullSync-gated+receiver sweep**, two small kind-map extensions (audio + video-thumbnail), and a post-pull+reconcile.++## Decisions (locked 2026-06-24)++1. **`data/history.jsonl` is NOT federated.** It is the generic app action-audit log+ (`logAction`, 500-entry cap), machine-local activity — not media gen history. "Generation+ history converges" is satisfied by `video-history.json` (already union-merges) + image+ sidecars (ride with image bytes).+2. **All five media kinds mirror**, including user-uploaded `data/music`. `image-refs` is+ excluded (ephemeral FLUX multi-ref scratch).+3. **Byte replication is gated to `peer.fullSync === true`.** Non-fullSync peers are+ unchanged (today's record-referenced-only behavior).++## Implementation++### Sender — advertise the whole library+- `buildMediaLibraryManifest()` walks `PATHS.{images,videos,videoThumbnails,audio,music}`,+ hashes each file (reuse `hashSimpleAsset` / `getOrComputeImageSha256` / `sidecarGenParamsHash`),+ honors backup `DEFAULT_EXCLUDES`. Returns `{ schemaVersion, manifestHash, assets:+ [{ kind, filename, sha256, sidecarSha256? }] }`. Logged cap on entry count (pagination = follow-up if ever hit).+- `GET /api/peer-sync/library-manifest` in `server/routes/peerSync.js`.++### Receiver — fullSync-gated sweep+- New `server/services/sharing/mediaLibrarySync.js`: per online `fullSync` peer, fetch+ manifest (short-circuit on unchanged `manifestHash`), diff vs local disk, pull missing+ bytes via `fetchCappedAssetBuffer` (image sidecars ride alongside). Per-peer re-entrancy+ lock + cooldown. Debounced `reconcileMediaAssets()` + emit existing `peerSync:asset-arrived`.+- Hook into the existing 30s `probeAllPeers()` success path (`server/services/instances.js`).++### Shared extensions+- `assetDirForKind` (`peerSync.js:~979`) + `diffAssetManifestAgainstLocal` + per-kind byte+ caps: add `audio` → `PATHS.audio`, `video-thumbnail` → `PATHS.videoThumbnails`.+- `PORTOS_SCHEMA_VERSIONS.mediaLibrary = 1`; Zod manifest-response schema in+ `peerSyncValidation.js`; add `audio` + `video-thumbnail` to the kind enum. Receiver gently+ **skips** (not rejects) a sender whose manifest schema is newer.++### Tests+manifest build/excludes · diff across kinds (incl audio/thumbnail) · fullSync gate (non-fullSync+= no-op) · schema-skip · `history.jsonl` untouched · reconcile-after-pull called · re-entrancy lock.++## Acceptance (from #1566)+- [x] Library asset bytes replicate to full-sync peers via manifest+pull with SHA256 integrity.+- [x] Generation history union-merges across peers without duplicates (video-history + sidecars).+- [x] `media_assets` index rebuilds on the receiver after bytes arrive.+- [x] Byte replication gated to full-sync peers and respects backup exclusions.++## Test plan+Verify on this instance ↔ the `void` peer: enable fullSync A↔B, generate media on A not+attached to any synced record, confirm B's Media tab converges (and vice-versa).diff --git a/server/lib/peerSyncValidation.js b/server/lib/peerSyncValidation.jsindex 6d7358810a..fed3f5f3fb 100644--- a/server/lib/peerSyncValidation.js+++ b/server/lib/peerSyncValidation.js@@ -38,7 +38,12 @@ const peerAssetManifestEntrySchema = z.discriminatedUnion('kind', [}).strict(),z.object({filename: z.string().trim().min(1).max(255),- kind: z.enum(['image-ref', 'video', 'music']),+ // `audio` (#1566) joins the per-record kinds (image-ref/video/music) for the+ // standalone media-library manifest. Like video/music it carries no gen-params+ // sidecar, so it rides the non-image branch (`.strict()` rejects a stray+ // sidecarSha256). The per-record push pipeline never emits `audio`; accepting+ // it here is harmless and keeps one shared entry schema across both manifests.+ kind: z.enum(['image-ref', 'video', 'music', 'audio']),sha256: hex64.optional(),}).strict(),]);@@ -245,6 +250,23 @@ export const peerSyncNowSchema = z.object({peerId: z.string().trim().min(1).max(120),}).strict();+// Standalone media-library manifest the SENDER advertises at+// GET /api/peer-sync/library-manifest (#1566). A full-sync receiver fetches it,+// validates it through this schema, then diffs `assets` vs local disk and+// receiver-pulls the missing bytes. Reuses `peerAssetManifestEntrySchema` (now+// incl. `audio`) so the wire shape stays identical to the per-record manifest.+//+// `assets` is capped well above the per-record manifest (a whole library is far+// larger than one record's refs); the sender logs + truncates beyond the cap+// rather than shipping an unbounded list. `manifestHash` lets the receiver+// short-circuit an unchanged library without diffing every entry. `.strict()`+// so a malformed envelope is rejected at the boundary.+export const peerLibraryManifestSchema = z.object({+ schemaVersion: z.number().int().min(0).max(1_000_000),+ manifestHash: hex64,+ assets: z.array(peerAssetManifestEntrySchema).max(100_000),+}).strict();+export const peerPullMetadataSchema = z.object({// Backfill tries every online peer; no per-peer scoping field today.// .trim() so a stray-whitespace filename (' a.png ') normalizes to the realdiff --git a/server/lib/schemaVersions.js b/server/lib/schemaVersions.jsindex c8a7b339d4..8185311bfc 100644--- a/server/lib/schemaVersions.js+++ b/server/lib/schemaVersions.js@@ -309,6 +309,20 @@ export const PORTOS_SCHEMA_VERSIONS = Object.freeze({// diff + receiver-pull), never round-tripped through the record. Folders +// exercises are NOT federated yet (they lack soft-delete columns).writersRoomWorks: 1,+ // v1 = standalone media-library federation (#1566). NOT a record kind — it's+ // the wire contract for the library-level asset manifest a full-sync peer+ // advertises at GET /api/peer-sync/library-manifest. The receiver-pull sweep+ // (syncMediaLibraryFromPeer) reads the sender's advertised `schemaVersion` and+ // GENTLY SKIPS (logs, no reject) a sender ahead of its local `mediaLibrary` —+ // unlike the push gate's hard 412, because a library sweep is best-effort+ // background convergence, not an authoritative record transfer. The asset+ // BYTES themselves are version-agnostic (an image is an image); only the+ // MANIFEST envelope shape is gated, so the FIRST incompatible manifest-shape+ // change (new required field, kind semantics) MUST bump this to 2. Adding a+ // new media KIND to the manifest is additive — the receiver ignores kinds it+ // can't route (directoryForAssetKind returns null) — and does NOT require a+ // bump on its own.+ mediaLibrary: 1,// NOTE: `videoHistory` is intentionally NOT listed here. The version gate// rejects the ENTIRE snapshot/push payload on ANY ahead-mismatch (the// comparator walks the union of keys), so declaring a brand-new key would@@ -357,6 +371,25 @@ export const RECORD_KIND_SCHEMA_CATEGORIES = Object.freeze({writersRoomWork: Object.freeze(['writersRoomWorks']),});+/**+ * Schema-version categories that are versioned but NOT reachable from a record+ * push — they ride their OWN transport with their OWN compatibility gate, not the+ * per-record push gate that `RECORD_KIND_SCHEMA_CATEGORIES` drives. Listing one+ * here is the explicit, reviewed way to say "this version is gated elsewhere, so+ * the gate-map-completeness guard should not require a record-kind mapping."+ *+ * - `mediaLibrary` (#1566): the standalone media-library manifest a full-sync+ * peer advertises at GET /api/peer-sync/library-manifest. The RECEIVER pulls+ * it and GENTLY SKIPS a sender ahead of its local version (see+ * syncMediaLibraryFromPeer) — there is no push to gate, so it has no entry in+ * RECORD_KIND_SCHEMA_CATEGORIES by design.+ *+ * Do NOT add a real record-push category here to silence the guard — that would+ * leave its push transfers ungated (silent cross-install corruption). Only+ * genuinely non-push categories belong.+ */+export const NON_RECORD_SCHEMA_CATEGORIES = Object.freeze(new Set(['mediaLibrary']));+/*** Lazy-read the current PortOS version from the ROOT package.json so a* pull-and-restart picks it up without a process-relative cache.diff --git a/server/routes/peerSync.js b/server/routes/peerSync.jsindex ef5557e9c2..baee66dba6 100644--- a/server/routes/peerSync.js+++ b/server/routes/peerSync.js@@ -41,6 +41,7 @@ import {getRecordPayloadForPeer,pullRecordFromPeer,syncNowForPeer,+ buildMediaLibraryManifest,ERR_NOT_FOUND,ERR_VALIDATION,ERR_SCHEMA_VERSION_AHEAD,@@ -146,6 +147,19 @@ router.get('/manifest', asyncHandler(async (req, res) => {res.json({ records: await buildLocalManifest(kind) });}));+// --- GET /library-manifest --- advertise this instance's STANDALONE media+// library (#1566) so a full-sync peer can diff + receiver-pull missing bytes.+//+// Returns `{ schemaVersion, manifestHash, assets: [{ kind, filename, sha256,+// sidecarSha256? }] }` covering generated images/videos, pipeline audio, and+// user-uploaded music. Unauthenticated like every peer-sync route (Tailnet-only+// per the threat model); the receiver gates the PULL on its own `fullSync` flag,+// so advertising the manifest to any tailnet peer is safe (it's read-only and+// the bytes are already served by the /data/* static mounts).+router.get('/library-manifest', asyncHandler(async (_req, res) => {+ res.json(await buildMediaLibraryManifest());+}));+// --- GET /record --- return ONE record's push payload so a peer can PULL it.//// The mirror of the sender's /push: a peer that's behind on this record fetchesdiff --git a/server/routes/peerSync.test.js b/server/routes/peerSync.test.jsindex 08c4e80962..f53d857f04 100644--- a/server/routes/peerSync.test.js+++ b/server/routes/peerSync.test.js@@ -12,6 +12,7 @@ vi.mock('../services/sharing/peerSync.js', () => ({getRecordPayloadForPeer: vi.fn(),pullRecordFromPeer: vi.fn(),syncNowForPeer: vi.fn(),+ buildMediaLibraryManifest: vi.fn(),ERR_NOT_FOUND: 'PEER_SYNC_SUBSCRIPTION_NOT_FOUND',ERR_VALIDATION: 'PEER_SYNC_SUBSCRIPTION_VALIDATION',ERR_SCHEMA_VERSION_AHEAD: 'PEER_SYNC_SCHEMA_VERSION_AHEAD',@@ -512,6 +513,22 @@ describe('peer-sync routes', () => {});});+ describe('GET /api/peer-sync/library-manifest', () => {+ it('200 with the standalone media-library manifest (#1566)', async () => {+ const manifest = {+ schemaVersion: 1,+ manifestHash: 'a'.repeat(64),+ assets: [{ filename: 'x.png', kind: 'image', sha256: 'b'.repeat(64) }],+ };+ svc.buildMediaLibraryManifest.mockResolvedValue(manifest);++ const res = await request(buildApp()).get('/api/peer-sync/library-manifest');+ expect(res.status).toBe(200);+ expect(res.body).toEqual(manifest);+ expect(svc.buildMediaLibraryManifest).toHaveBeenCalled();+ });+ });+describe('GET /api/peer-sync/integrity', () => {it('200 with available:false when peer is not found', async () => {integritySvc.getPeerIntegrity.mockResolvedValue({diff --git a/server/services/sharing/index.js b/server/services/sharing/index.jsindex eef5360e02..38fcc3bb3b 100644--- a/server/services/sharing/index.js+++ b/server/services/sharing/index.js@@ -12,7 +12,7 @@ import { join } from 'path';import { attachAllWatchers, attachWatcher, detachWatcher, shutdownAllWatchers, listAttachedWatchers } from './watcher.js';import { sharingEvents } from './importer.js';import { installSubscriptionListener } from './subscriptions.js';-import { installPeerSyncListener, uninstallPeerSyncListener, peerSyncEvents } from './peerSync.js';+import { installPeerSyncListener, uninstallPeerSyncListener, peerSyncEvents, syncMediaLibraryWithAllPeers } from './peerSync.js';import { hasSubscriptionAdapter } from './recordEvents.js';import { initAnnotationsSync } from './annotationsSync.js';@@ -23,6 +23,43 @@ export { pullSidecarForImage, backfillMissingSidecars } from './sidecarSync.js';let initialized = false;let io = null;+// Standalone media-library federation sweep (#1566). A low-frequency timer pulls+// each full-sync peer's library bytes; an unchanged library short-circuits on the+// manifestHash, so the steady-state tick is one cheap manifest fetch per peer.+// Period is deliberately slower than the 30s peer health probe — media changes+// less often and a sweep can move large bytes.+const MEDIA_LIBRARY_SWEEP_INTERVAL_MS = 60_000;+const MEDIA_LIBRARY_SWEEP_INITIAL_DELAY_MS = 20_000; // let boot settle before the first sweep+let mediaLibraryTimer = null;+let mediaLibraryKickoff = null;++function startMediaLibrarySweep() {+ // Timer callbacks run OUTSIDE the request lifecycle — an uncaught throw here+ // crashes the process (CLAUDE.md). syncMediaLibraryWithAllPeers already catches+ // per-peer; this guards a synchronous throw before the awaits begin.+ const tick = () => {+ try {+ syncMediaLibraryWithAllPeers().catch((err) => {+ console.error(`❌ sharing: media-library sweep failed: ${err.message}`);+ });+ } catch (err) {+ console.error(`❌ sharing: media-library sweep threw synchronously: ${err.message}`);+ }+ };+ mediaLibraryKickoff = setTimeout(() => {+ mediaLibraryKickoff = null;+ tick();+ mediaLibraryTimer = setInterval(tick, MEDIA_LIBRARY_SWEEP_INTERVAL_MS);+ if (typeof mediaLibraryTimer.unref === 'function') mediaLibraryTimer.unref();+ }, MEDIA_LIBRARY_SWEEP_INITIAL_DELAY_MS);+ if (typeof mediaLibraryKickoff.unref === 'function') mediaLibraryKickoff.unref();+}++function stopMediaLibrarySweep() {+ if (mediaLibraryKickoff) { clearTimeout(mediaLibraryKickoff); mediaLibraryKickoff = null; }+ if (mediaLibraryTimer) { clearInterval(mediaLibraryTimer); mediaLibraryTimer = null; }+}+export async function initSharing({ io: socketIo } = {}) {if (initialized) return;initialized = true;@@ -103,6 +140,8 @@ export async function initSharing({ io: socketIo } = {}) {// subscription listener so a single recordEvents `updated` fan-out drives// both transports. No state until at least one peer subscription exists.installPeerSyncListener();+ // #1566 — periodic standalone media-library mirror for full-sync peers.+ startMediaLibrarySweep();initAnnotationsSync();const result = await attachAllWatchers();console.log(`📡 sharing: initialized, watchers attached for ${result.attached} bucket(s)`);@@ -111,6 +150,7 @@ export async function initSharing({ io: socketIo } = {}) {export async function shutdownSharing() {await shutdownAllWatchers();+ stopMediaLibrarySweep();sharingEvents.removeAllListeners();// Detach the recordEvents + instanceEvents listeners that// installPeerSyncListener attached. Without this, the peer-sync servicediff --git a/server/services/sharing/peerSync.js b/server/services/sharing/peerSync.jsindex be7019cc06..ff246aa317 100644--- a/server/services/sharing/peerSync.js+++ b/server/services/sharing/peerSync.js@@ -37,6 +37,7 @@import { join } from 'path';import { existsSync } from 'fs';+import { readdir, stat } from 'fs/promises';import { EventEmitter } from 'events';import { createHash } from 'crypto';import { PATHS, atomicWrite, readJSONFile, ensureDir, sha256File } from '../../lib/fileUtils.js';@@ -62,7 +63,7 @@ import {getPortosVersion,} from '../../lib/schemaVersions.js';import { getInstanceId, getPeers, enqueueReciprocalSync, UNKNOWN_INSTANCE_ID } from '../instances.js';-import { peerSyncPushSchema } from '../../lib/validation.js';+import { peerSyncPushSchema, peerLibraryManifestSchema } from '../../lib/validation.js';import { instanceEvents } from '../instanceEvents.js';import { getUniverse, mergeUniversesFromSync } from '../universeBuilder.js';import { getSeries, mergeSeriesFromSync } from '../pipeline/series.js';@@ -980,6 +981,7 @@ function directoryForAssetKind(kind) {if (kind === 'image-ref') return PATHS.imageRefs;if (kind === 'video') return PATHS.videos;if (kind === 'music') return PATHS.music;+ if (kind === 'audio') return PATHS.audio; // #1566 standalone media-library sweepreturn null;}@@ -2403,6 +2405,10 @@ const ASSET_KIND_TO_URL_PREFIX = Object.freeze({'image-ref': '/data/image-refs',video: '/data/videos',music: '/data/music',+ // `audio` (#1566) — pipeline TTS / generated audio under data/audio, pulled by+ // the standalone media-library sweep. (video-thumbnails are NOT pulled: a video+ // pull regenerates its thumbnail locally — see doPullOneAsset's video branch.)+ audio: '/data/audio',});const ASSET_PULL_TIMEOUT_MS = 60000;@@ -2669,6 +2675,262 @@ async function doPullOneAsset(peer, base, entry, urlPrefix, localDir, safeName)}}+// --- Standalone media-library federation (#1566) ------------------------+//+// The per-record pipeline above replicates only the bytes a SYNCED creative+// record references. For a declared full-sync peer pair we ALSO mirror the+// STANDALONE media library — every generated image/video, pipeline audio, and+// user-uploaded music — so each peer's Media tab is a complete replica.+//+// Shape: the sender advertises a library-level manifest (filename + sha256 per+// asset) at GET /api/peer-sync/library-manifest; a receiver (only for peers it+// has flagged fullSync) fetches it, diffs vs local disk via the SAME+// diffAssetManifestAgainstLocal + pullOneAsset machinery the per-record path+// uses, and rebuilds the derived media_assets index once bytes land. Notably:+// - video THUMBNAILS are regenerated locally on each video pull+// (doPullOneAsset's video branch), not byte-federated;+// - video-history METADATA already union-merges via the `videoHistory`+// dataSync category — the bytes are what this adds;+// - the generic data/history.jsonl action log is machine-local and never+// federated (it's app activity, not media gen history).++// The on-disk media kinds the library manifest covers, resolved at CALL TIME+// (not frozen at module load) so a redirected PATHS — the test-suite tmpdir+// pattern, and consistent with directoryForAssetKind reading PATHS live — is+// honored. `image` carries a gen-params sidecar (rides via hashImageForManifest);+// the rest are flat bytes. image-refs are EXCLUDED (ephemeral FLUX multi-ref+// scratch); video-thumbnails are EXCLUDED (regenerated locally on video pull).+function mediaLibraryDirs() {+ return [+ { kind: 'image', dir: PATHS.images },+ { kind: 'video', dir: PATHS.videos },+ { kind: 'audio', dir: PATHS.audio },+ { kind: 'music', dir: PATHS.music },+ ];+}++// Stable data-root-relative basename per kind, used only to match backup+// exclude patterns. Independent of PATHS so a redirected path can't change which+// exclude pattern applies.+const MEDIA_LIBRARY_KIND_DIRNAMES = Object.freeze({+ image: 'images', video: 'videos', audio: 'audio', music: 'music',+});++// Cap so a pathologically large library can't build an unbounded manifest. 100k+// assets is far beyond any realistic single-user library; when exceeded we LOG+// and truncate (per CLAUDE.md "no silent caps") rather than ship an open-ended+// list. Pagination is a clean follow-up if ever hit. Kept in sync with the+// `assets` array cap in peerLibraryManifestSchema.+const MEDIA_LIBRARY_MANIFEST_CAP = 100_000;++/**+ * Pure matcher: given a list of effective rsync exclude patterns, return the Set+ * of media-library KINDS the user has excluded from backup (and therefore from+ * federation, per the #1566 acceptance criterion). Checked at DIRECTORY+ * granularity — recognizes a whole-dir exclude (`/videos`, `/videos/`,+ * `/videos/**`, or the bare `videos/` form). Per-file glob granularity is out of+ * scope: none of the media dirs are excluded by DEFAULT_EXCLUDES, so this only+ * fires on a custom user exclude like `/music/`, and excluding individual files+ * from federation isn't a supported control.+ *+ * Exported for unit testing without mocking the settings/backup IO.+ */+export function libraryKindsExcludedByPatterns(effectiveExcludes) {+ const excluded = new Set();+ const patterns = Array.isArray(effectiveExcludes) ? effectiveExcludes : [];+ // Normalize each pattern to its bare anchored segment in one pass: strip+ // leading slashes, a trailing `/**`/`/*`, or a trailing slash → `/videos/**`+ // and `videos/` both collapse to `videos`.+ const normalized = patterns.map((p) => String(p).replace(/^\/+|\/+\*+$|\/+$/g, ''));+ for (const [kind, name] of Object.entries(MEDIA_LIBRARY_KIND_DIRNAMES)) {+ if (normalized.includes(name)) excluded.add(kind);+ }+ return excluded;+}++// Honor the backup exclusion contract (#1566 acceptance). Best-effort: a+// settings/backup read failure federates everything (the prior behavior), never+// throws. Composes the IO (read settings, compute effective excludes) with the+// pure `libraryKindsExcludedByPatterns` matcher above.+async function excludedLibraryKinds() {+ const settingsMod = await import('../settings.js').catch(() => null);+ const backupMod = await import('../backup.js').catch(() => null);+ if (!settingsMod?.getSettings || !backupMod?.computeEffectiveExcludes) return new Set();+ const settings = await settingsMod.getSettings().catch(() => null);+ const excludePaths = Array.isArray(settings?.backup?.excludePaths) ? settings.backup.excludePaths : [];+ const disabledDefaultExcludes = Array.isArray(settings?.backup?.disabledDefaultExcludes) ? settings.backup.disabledDefaultExcludes : [];+ const effective = backupMod.computeEffectiveExcludes({ excludePaths, disabledDefaultExcludes });+ return libraryKindsExcludedByPatterns(effective);+}++// In-memory hash cache for the flat (non-image) library kinds, keyed by full+// path → { mtimeMs, size, entry }. The manifest is rebuilt on every poll (each+// full-sync peer fetches it ~every 60s), and video/music files can be large —+// re-`sha256File`-ing a multi-GB library every poll is real, avoidable disk I/O.+// Images already cache their sha in the sidecar (getOrComputeImageSha256), so+// this only covers video/audio/music. Invalidated on (mtimeMs, size) change —+// the same cheap signal the image sidecar cache uses; a re-render writes a new+// file (new mtime), so staleness isn't a concern.+const libraryFlatHashCache = new Map(); // fullPath → { mtimeMs, size, entry }++async function hashCachedLibraryAsset(name, kind, dir) {+ const safeName = sanitizeAssetFilename(name);+ if (!safeName) return null;+ const fullPath = join(dir, safeName);+ const st = await stat(fullPath).catch(() => null);+ if (!st || !st.isFile()) return null;+ const cached = libraryFlatHashCache.get(fullPath);+ if (cached && cached.mtimeMs === st.mtimeMs && cached.size === st.size) return cached.entry;+ const entry = await hashSimpleAsset(safeName, kind, dir);+ if (entry) libraryFlatHashCache.set(fullPath, { mtimeMs: st.mtimeMs, size: st.size, entry });+ return entry;+}++/**+ * Build the standalone media-library manifest this instance advertises to+ * full-sync peers. Walks each media dir, hashes every file (reusing the+ * per-record hashers so the wire shape is identical), and stamps a `manifestHash`+ * over the sorted entries so a receiver can short-circuit an unchanged library.+ *+ * @returns {Promise<{ schemaVersion:number, manifestHash:string, assets:Array }>}+ */+export async function buildMediaLibraryManifest() {+ const excluded = await excludedLibraryKinds();+ const assets = [];+ let truncated = false;+ for (const { kind, dir } of mediaLibraryDirs()) {+ if (truncated) break;+ if (excluded.has(kind)) continue;+ const names = await readdir(dir).catch(() => []); // missing dir → empty (nothing of that kind yet)+ for (const name of names) {+ // Image sidecars are metadata, not standalone assets — they ride the image+ // entry's sidecarSha256 + the receiver's pullSidecarForImage, so skip the+ // `.json` files in the images dir.+ if (kind === 'image' && name.endsWith('.json')) continue;+ const entry = kind === 'image'+ ? await hashImageForManifest(name) // sidecar-cached+ : await hashCachedLibraryAsset(name, kind, dir); // (mtime,size)-cached+ if (!entry) continue;+ if (assets.length >= MEDIA_LIBRARY_MANIFEST_CAP) { truncated = true; break; }+ assets.push(entry);+ }+ }+ if (truncated) {+ console.log(`⚠️ peerSync: media-library manifest hit the ${MEDIA_LIBRARY_MANIFEST_CAP}-asset cap — truncating (some assets won't federate; pagination is a follow-up)`);+ }+ // Deterministic order (sort by filename) so the manifestHash converges across+ // machines regardless of readdir order / filesystem.+ const sorted = assets.sort((a, b) => (a.filename < b.filename ? -1 : a.filename > b.filename ? 1 : 0));+ const manifestHash = createHash('sha256')+ .update(sorted.map((e) => `${e.kind}:${e.filename}:${e.sha256 || ''}:${e.sidecarSha256 || ''}`).join('\n'))+ .digest('hex');+ return { schemaVersion: PORTOS_SCHEMA_VERSIONS.mediaLibrary, manifestHash, assets: sorted };+}++// Receiver-side: last manifestHash fully processed per peer, so an unchanged+// library skips the diff entirely. In-memory (rebuilt on restart — the first+// post-boot sweep just re-confirms disk, cheap because the diff finds everything+// present and pulls nothing).+const lastLibraryManifestHash = new Map(); // peerInstanceId → manifestHash+// Per-peer re-entrancy guard so a slow sweep (large pull) can't overlap itself+// when the periodic tick fires again before it finishes.+const librarySweepInFlight = new Set(); // peerInstanceId+// The manifest JSON itself (not the bytes — those ride the per-asset 100MB cap).+const MEDIA_LIBRARY_MANIFEST_MAX_BYTES = 32 * 1024 * 1024;++async function reconcileMediaLibraryIndex() {+ // Dynamic import keeps the DB-backed index module out of peerSync's static+ // graph (it no-ops under the file/test backend). image+video rows are rebuilt+ // from disk; audio/music aren't indexed (served from disk directly).+ const mod = await import('../mediaAssetIndex/index.js').catch(() => null);+ if (!mod?.reconcileMediaAssets) return;+ await mod.reconcileMediaAssets().catch((err) => {+ console.log(`⚠️ peerSync: media_assets reconcile after library sweep failed: ${err.message}`);+ });+}++/**+ * Receiver-pull the standalone media library from ONE full-sync peer: fetch its+ * manifest, gate on schema version, diff vs local disk, pull missing bytes, then+ * rebuild the derived media_assets index. No-op for a non-full-sync peer.+ *+ * Best-effort + idempotent: every guard returns rather than throws so a periodic+ * caller can fire it unconditionally.+ *+ * @param {object} peer a peer entry from getPeers()+ * @returns {Promise<{ pulled:number, skipped?:string }>}+ */+export async function syncMediaLibraryFromPeer(peer) {+ if (!isPlainObject(peer) || peer.fullSync !== true || !isStr(peer.instanceId)) {+ return { pulled: 0, skipped: 'not-fullsync' };+ }+ if (librarySweepInFlight.has(peer.instanceId)) return { pulled: 0, skipped: 'in-flight' };+ librarySweepInFlight.add(peer.instanceId);+ try {+ const url = `${peerBaseUrl(peer)}/api/peer-sync/library-manifest`;+ const controller = new AbortController();+ const timeoutId = setTimeout(() => controller.abort(), ASSET_PULL_TIMEOUT_MS);+ const res = await peerFetch(url, { signal: controller.signal, maxBytes: MEDIA_LIBRARY_MANIFEST_MAX_BYTES }, peer)+ .finally(() => clearTimeout(timeoutId))+ .catch(() => null);+ if (!res || !res.ok) return { pulled: 0, skipped: 'unreachable' };+ const body = await res.json().catch(() => null);+ const parsed = peerLibraryManifestSchema.safeParse(body);+ if (!parsed.success) {+ console.log(`⚠️ peerSync: media-library manifest from ${peer.name || peer.instanceId} failed validation — skipping`);+ return { pulled: 0, skipped: 'invalid' };+ }+ const manifest = parsed.data;+ // Schema gate — GENTLE skip (not reject): the sender's manifest envelope is+ // newer than this instance understands. Wait for the local PortOS to upgrade+ // rather than mis-pull against a contract we can't read. (Bytes are+ // version-agnostic, but a manifest-SHAPE bump means a new field we'd mishandle.)+ if (manifest.schemaVersion > PORTOS_SCHEMA_VERSIONS.mediaLibrary) {+ console.log(`⏸️ peerSync: ${peer.name || peer.instanceId} media-library manifest is schema v${manifest.schemaVersion} > local v${PORTOS_SCHEMA_VERSIONS.mediaLibrary} — skipping until this instance updates`);+ return { pulled: 0, skipped: 'schema-ahead' };+ }+ // Unchanged-library short-circuit.+ if (lastLibraryManifestHash.get(peer.instanceId) === manifest.manifestHash) {+ return { pulled: 0, skipped: 'unchanged' };+ }+ const missing = await diffAssetManifestAgainstLocal(manifest.assets);+ if (missing.length === 0) {+ lastLibraryManifestHash.set(peer.instanceId, manifest.manifestHash);+ return { pulled: 0 };+ }+ const requested = missing.length;+ // Reuse the per-record pull worker (in-flight dedup, image-sidecar fetch,+ // video-thumbnail regen).+ await pullMissingAssetsFromPeer(peer.instanceId, missing);+ // Rebuild the derived media_assets index so the gallery/Media tab reflects+ // the new image+video bytes. Idempotent; best-effort.+ await reconcileMediaLibraryIndex();+ // Record the hash only AFTER a full sweep so a partial pull (peer dropped+ // mid-transfer) re-attempts next tick instead of being marked done.+ lastLibraryManifestHash.set(peer.instanceId, manifest.manifestHash);+ console.log(`📥 peerSync: media-library sweep from ${peer.name || peer.instanceId} — requested ${requested} missing asset(s)`);+ return { pulled: requested };+ } finally {+ librarySweepInFlight.delete(peer.instanceId);+ }+}++/**+ * Periodic driver: sweep the standalone media library from every full-sync peer.+ * Called on a timer from initSharing. Each peer's sweep is independent and+ * best-effort; the per-peer re-entrancy guard + manifestHash short-circuit keep+ * an unchanged library cheap.+ */+export async function syncMediaLibraryWithAllPeers() {+ const peers = await getPeers().catch(() => []);+ const fullSyncPeers = peers.filter((p) => p?.fullSync === true && p?.enabled !== false && isStr(p.instanceId));+ for (const peer of fullSyncPeers) {+ await syncMediaLibraryFromPeer(peer).catch((err) => {+ console.log(`⚠️ peerSync: media-library sweep for ${peer.name || peer.instanceId} failed: ${err.message}`);+ });+ }+}+// --- Listener install + debounced trigger -------------------------------const pendingTimers = new Map(); // subId → Timeoutdiff --git a/server/services/sharing/peerSync.test.js b/server/services/sharing/peerSync.test.jsindex 0fecd1960d..cee2efafd0 100644--- a/server/services/sharing/peerSync.test.js+++ b/server/services/sharing/peerSync.test.js@@ -11,7 +11,7 @@ import { tmpdir } from 'os';// runs against the real on-disk paths via the tmpdir-redirect pattern below.import { PATHS } from '../../lib/fileUtils.js';-import { RECORD_KIND_SCHEMA_CATEGORIES, PORTOS_SCHEMA_VERSIONS } from '../../lib/schemaVersions.js';+import { RECORD_KIND_SCHEMA_CATEGORIES, PORTOS_SCHEMA_VERSIONS, NON_RECORD_SCHEMA_CATEGORIES } from '../../lib/schemaVersions.js';// instances.js mock: aligns with mockNoPeers() contract (getPeers → [], getInstanceId// → 'test-instance' by default) while keeping vi.fn() wrappers so per-test@@ -66,6 +66,13 @@ vi.mock('../mediaCollections.js', async () => ({mergeMediaCollectionsFromSync: vi.fn(),}));+// #1566 — the media-library sweep dynamic-imports this to rebuild the derived+// media_assets index after bytes land. Mock it to a no-op spy so the sweep tests+// don't touch Postgres and can assert the reconcile fired.+vi.mock('../mediaAssetIndex/index.js', () => ({+ reconcileMediaAssets: vi.fn().mockResolvedValue(undefined),+}));+vi.mock('../artists/index.js', async () => {const imageBasename = (url) => {if (typeof url !== 'string' || !url.trim()) return null;@@ -155,6 +162,10 @@ import {pullRecordFromPeer,syncNowForPeer,collectSubscriptionsForUpdate,+ buildMediaLibraryManifest,+ libraryKindsExcludedByPatterns,+ syncMediaLibraryFromPeer,+ syncMediaLibraryWithAllPeers,peerSyncEvents,__resetForTests,__drainForTests,@@ -177,6 +188,7 @@ import { getArtist, listArtists, mergeArtistsFromSync } from '../artists/index.jimport { getAlbum, listAlbums, mergeAlbumsFromSync } from '../albums/index.js';import { getTrack, listTracks, mergeTracksFromSync } from '../tracks/index.js';import { peerFetch } from '../../lib/peerHttpClient.js';+import { reconcileMediaAssets } from '../mediaAssetIndex/index.js';import { getBackendName } from '../memoryBackend.js';import { getCatalogBundleForRef } from '../catalogDB.js';import { applyRemoteChanges as applyCatalogRemoteChanges } from '../catalogSync.js';@@ -3117,9 +3129,12 @@ describe('peerSync', () => {it('every versioned PORTOS_SCHEMA_VERSIONS key is reachable from a record kind', () => {// So a newly-versioned category can't ship without being wired into the- // per-category gate (which would leave its transfers ungated).+ // per-category gate (which would leave its transfers ungated). The only+ // exemptions are categories explicitly declared as non-record (pull-gated+ // elsewhere) via NON_RECORD_SCHEMA_CATEGORIES — e.g. mediaLibrary (#1566).const covered = new Set(Object.values(RECORD_KIND_SCHEMA_CATEGORIES).flat());for (const key of Object.keys(PORTOS_SCHEMA_VERSIONS)) {+ if (NON_RECORD_SCHEMA_CATEGORIES.has(key)) continue;expect(covered.has(key)).toBe(true);}});@@ -3690,3 +3705,174 @@ describe('peerSync', () => {});});});++describe('media-library federation (#1566)', () => {+ let origAudio;+ let origVideos;++ beforeEach(async () => {+ // The suite beforeEach redirects PATHS.data/images/music to `tmp` and+ // restores videos in its afterEach; redirect videos + audio (not created+ // there) into the same per-test tmpdir so manifest builds see ONLY fixtures.+ origAudio = PATHS.audio;+ origVideos = PATHS.videos;+ PATHS.videos = join(tmp, 'videos');+ PATHS.audio = join(tmp, 'audio');+ await mkdir(PATHS.videos, { recursive: true });+ await mkdir(PATHS.audio, { recursive: true });+ vi.mocked(reconcileMediaAssets).mockClear();+ });++ afterEach(() => {+ PATHS.audio = origAudio;+ PATHS.videos = origVideos;+ });++ describe('libraryKindsExcludedByPatterns (honors backup excludes)', () => {+ it('flags a kind whose whole dir is excluded — anchored, trailing-slash, and glob forms', () => {+ expect([...libraryKindsExcludedByPatterns(['/music/'])]).toEqual(['music']);+ expect([...libraryKindsExcludedByPatterns(['/videos/**'])]).toEqual(['video']);+ expect([...libraryKindsExcludedByPatterns(['images'])]).toEqual(['image']);+ expect([...libraryKindsExcludedByPatterns(['/audio'])]).toEqual(['audio']);+ });++ it('ignores excludes that do not name a whole media dir', () => {+ expect(libraryKindsExcludedByPatterns(['/loras/*.safetensors', '/repos/']).size).toBe(0);+ expect(libraryKindsExcludedByPatterns([]).size).toBe(0);+ expect(libraryKindsExcludedByPatterns(undefined).size).toBe(0);+ });+ });++ describe('buildMediaLibraryManifest', () => {+ it('walks all media dirs, hashes files, skips image sidecars, and is deterministic', async () => {+ await writeFile(join(PATHS.images, 'a.png'), 'img-a');+ await writeFile(join(PATHS.images, 'a.png.metadata.json'), JSON.stringify({ prompt: 'x' }));+ await writeFile(join(PATHS.videos, 'v.mp4'), 'vid');+ await writeFile(join(PATHS.audio, 's.wav'), 'aud');+ await writeFile(join(PATHS.music, 'm.mp3'), 'mus');++ const m1 = await buildMediaLibraryManifest();+ const kinds = m1.assets.map((e) => `${e.kind}:${e.filename}`).sort();+ expect(kinds).toEqual(['audio:s.wav', 'image:a.png', 'music:m.mp3', 'video:v.mp4']);+ // sidecar json is metadata, not advertised as its own asset+ expect(m1.assets.find((e) => e.filename.endsWith('.json'))).toBeUndefined();+ // every entry carries a 64-hex sha256+ expect(m1.assets.every((e) => /^[a-f0-9]{64}$/.test(e.sha256))).toBe(true);+ expect(m1.schemaVersion).toBe(PORTOS_SCHEMA_VERSIONS.mediaLibrary);+ expect(/^[a-f0-9]{64}$/.test(m1.manifestHash)).toBe(true);+ // deterministic hash across rebuilds of the same library+ const m2 = await buildMediaLibraryManifest();+ expect(m2.manifestHash).toBe(m1.manifestHash);+ });++ it('changes manifestHash when the library changes', async () => {+ await writeFile(join(PATHS.audio, 's.wav'), 'aud');+ const before = (await buildMediaLibraryManifest()).manifestHash;+ await writeFile(join(PATHS.audio, 't.wav'), 'aud2');+ const after = (await buildMediaLibraryManifest()).manifestHash;+ expect(after).not.toBe(before);+ });++ it('returns an empty manifest when the library is empty', async () => {+ const m = await buildMediaLibraryManifest();+ expect(m.assets).toEqual([]);+ });++ it('re-hash cache invalidates when a flat asset changes in place (size differs)', async () => {+ const p = join(PATHS.audio, 's.wav');+ await writeFile(p, 'short');+ const first = (await buildMediaLibraryManifest()).assets.find((e) => e.filename === 's.wav').sha256;+ // Overwrite with different-length content → (mtime,size) cache key changes.+ await writeFile(p, 'a much longer payload than before');+ const second = (await buildMediaLibraryManifest()).assets.find((e) => e.filename === 's.wav').sha256;+ expect(second).not.toBe(first);+ });+ });++ describe('syncMediaLibraryFromPeer', () => {+ const mkPeer = (id, extra = {}) => ({+ instanceId: id, name: id, host: null, address: '10.0.0.9', port: 5555,+ enabled: true, fullSync: true, ...extra,+ });++ it('no-ops for a non-full-sync peer and never hits the network', async () => {+ const res = await syncMediaLibraryFromPeer(mkPeer('fs-nofs', { fullSync: false }));+ expect(res.skipped).toBe('not-fullsync');+ expect(peerFetch).not.toHaveBeenCalled();+ });++ it('gently skips a peer whose manifest schema is ahead of local (no pull, no reconcile)', async () => {+ vi.mocked(peerFetch).mockResolvedValue({ ok: true, json: async () => ({+ schemaVersion: PORTOS_SCHEMA_VERSIONS.mediaLibrary + 1,+ manifestHash: 'a'.repeat(64), assets: [],+ }) });+ const res = await syncMediaLibraryFromPeer(mkPeer('fs-ahead'));+ expect(res.skipped).toBe('schema-ahead');+ expect(reconcileMediaAssets).not.toHaveBeenCalled();+ });++ it('skips an unreachable peer and an invalid manifest', async () => {+ vi.mocked(peerFetch).mockResolvedValue({ ok: false });+ expect((await syncMediaLibraryFromPeer(mkPeer('fs-down'))).skipped).toBe('unreachable');+ vi.mocked(peerFetch).mockResolvedValue({ ok: true, json: async () => ({ bogus: true }) });+ expect((await syncMediaLibraryFromPeer(mkPeer('fs-bad'))).skipped).toBe('invalid');+ });++ it('pulls nothing when assets already exist locally, then short-circuits on unchanged hash', async () => {+ // The peer's manifest == our OWN library (write files, build manifest, feed+ // it back) so diffAssetManifestAgainstLocal finds everything present.+ await writeFile(join(PATHS.audio, 's.wav'), 'aud');+ await writeFile(join(PATHS.images, 'a.png'), 'img');+ const localManifest = await buildMediaLibraryManifest();+ vi.mocked(peerFetch).mockResolvedValue({ ok: true, json: async () => localManifest });++ const peer = mkPeer('fs-present');+ const res1 = await syncMediaLibraryFromPeer(peer);+ expect(res1.pulled).toBe(0);+ expect(res1.skipped).toBeUndefined();+ expect(reconcileMediaAssets).not.toHaveBeenCalled(); // nothing pulled → no reconcile++ const res2 = await syncMediaLibraryFromPeer(peer);+ expect(res2.skipped).toBe('unchanged');+ });++ it('requests missing bytes and reconciles the index when the library diverges', async () => {+ const peer = mkPeer('fs-diverge');+ // pullMissingAssetsFromPeer re-resolves the peer via getPeers — include it.+ vi.mocked(getPeers).mockResolvedValue([peer]);+ const manifest = {+ schemaVersion: PORTOS_SCHEMA_VERSIONS.mediaLibrary,+ manifestHash: 'b'.repeat(64),+ assets: [{ filename: 'remote.wav', kind: 'audio', sha256: 'c'.repeat(64) }],+ };+ vi.mocked(peerFetch).mockImplementation(async (url) => {+ if (String(url).endsWith('/library-manifest')) return { ok: true, json: async () => manifest };+ return { ok: false }; // byte pull fails gracefully — mechanics tested elsewhere+ });+ const res = await syncMediaLibraryFromPeer(peer);+ expect(res.pulled).toBe(1);+ const urls = vi.mocked(peerFetch).mock.calls.map((c) => String(c[0]));+ expect(urls.some((u) => u.includes('/data/audio/remote.wav'))).toBe(true);+ expect(reconcileMediaAssets).toHaveBeenCalled();+ });+ });++ describe('syncMediaLibraryWithAllPeers', () => {+ it('sweeps only full-sync, enabled peers that have an instanceId', async () => {+ vi.mocked(getPeers).mockResolvedValue([+ { instanceId: 'fs1', address: '10.0.0.4', port: 5555, enabled: true, fullSync: true },+ { instanceId: 'partial', address: '10.0.0.5', port: 5555, enabled: true, fullSync: false },+ { instanceId: 'disabled', address: '10.0.0.6', port: 5555, enabled: false, fullSync: true },+ { instanceId: null, address: '10.0.0.7', port: 5555, enabled: true, fullSync: true },+ ]);+ vi.mocked(peerFetch).mockResolvedValue({ ok: true, json: async () => ({+ schemaVersion: PORTOS_SCHEMA_VERSIONS.mediaLibrary, manifestHash: 'd'.repeat(64), assets: [],+ }) });+ await syncMediaLibraryWithAllPeers();+ const manifestUrls = vi.mocked(peerFetch).mock.calls+ .map((c) => String(c[0])).filter((u) => u.endsWith('/library-manifest'));+ expect(manifestUrls).toHaveLength(1);+ expect(manifestUrls[0]).toContain('10.0.0.4');+ });+ });+});