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: host-or-copy sync mode for federated Media Collections, with local/remote state

Adam Eivy73a02c161c24
diff --git a/client/src/pages/Instances.jsx b/client/src/pages/Instances.jsx
index 0ae8cfe1b9..bdaf4bc7b0 100644
--- a/client/src/pages/Instances.jsx
+++ b/client/src/pages/Instances.jsx
@@ -564,8 +564,7 @@ const SYNC_CATEGORY_META = [
{ key: 'meatspace', label: 'Meatspace', icon: HeartPulse, description: 'Daily logs, blood tests, body metrics, eyes' },
{ key: 'universe', label: 'Universe', icon: Sparkles, description: 'Universe Builder canon: characters, places, objects' },
{ key: 'pipeline', label: 'Pipeline', icon: Film, description: 'Series + issues record state (no image/video blobs)' },
- { key: 'mediaCollections', label: 'Media Collections', icon: Images, description: 'Per-universe/series image + video buckets' },
- { key: 'videoHistory', label: 'Video History', icon: Film, description: 'Generated-video metadata rows (so synced collection videos render)' },
+ { key: 'mediaCollections', label: 'Media Collections', icon: Images, description: 'Per-universe/series image + video buckets, including the video metadata they need to render' },
{ key: 'storyBuilder', label: 'Story Builder', icon: BookOpen, description: 'Resumable Story Builder sessions you marked for cross-machine sync' },
{ key: 'usage', label: 'AI Usage Metrics', icon: Gauge, description: 'On by default. Aggregate AI usage counters — providers, models, token counts, estimated spend — so the Usage page totals your whole federation. No prompts, transcripts, or record contents. Turning it off stops PULLING this peer\u2019s usage; disable the peer to stop every direction.' },
{ key: 'fableLoom', label: 'FableLoom', icon: Waypoints, description: 'Branching stories, series plans, episode graphs, and rendered scene references' },
@@ -591,6 +590,22 @@ const SYNC_CATEGORY_META = [
const NON_SNAPSHOT_KEYS = new Set(['brain', 'memory', 'catalog', 'authors', 'artists', 'albums', 'tracks', 'creativeDirectorProjects', 'moodBoards', 'fableLoom', 'writersRoomWorks', 'writersRoomFolders', 'writersRoomExercises', 'musicVideoProjects', 'commissionFeedback', 'creativeCommissions', 'decks']);
const SNAPSHOT_CATEGORIES = SYNC_CATEGORY_META.filter(m => !NON_SNAPSHOT_KEYS.has(m.key));
+// Video-history rows have no toggle of their own: they are the metadata half of
+// Media Collections, so that one switch drives both keys (server-side
+// `mediaCollections` already implies `videoHistory`; a legacy peer with only
+// `videoHistory` on reads as on here, and turning the row off clears both).
+const MEDIA_COLLECTION_KEYS = ['mediaCollections', 'videoHistory'];
+const isCategoryOn = (categories, key) => (key === 'mediaCollections'
+ ? MEDIA_COLLECTION_KEYS.some(k => categories[k])
+ : Boolean(categories[key]));
+
+// How bytes for a synced Media Collection reach this machine. Mirrors the
+// server's MEDIA_SYNC_MODES (services/instances.js).
+const MEDIA_SYNC_MODE_OPTIONS = [
+ { value: 'copy', label: 'Copy', description: 'Download every image/video onto this machine (uses local disk, works offline)' },
+ { value: 'host', label: 'Host on peer', description: 'Keep references only and stream files from the peer on demand (no local copy)' },
+];
+
// Indicator backed by REAL coverage diffing (record IDs vs confirmed pushes),
// not the BIGSERIAL cursors — so "fully mirrored" never lies. Refetches on mount
// and whenever `refreshKey` changes; the caller passes peer.lastSeen, so it
@@ -642,7 +657,8 @@ function SyncCategoriesPanel({ peer, onRefresh }) {
const categories = peer.syncCategories || {};
const fullSync = peer.fullSync === true;
// A full-sync peer mirrors every category — present them as locked-on.
- const enabledCount = fullSync ? SYNC_CATEGORY_META.length : Object.values(categories).filter(Boolean).length;
+ const enabledCount = fullSync ? SYNC_CATEGORY_META.length : SYNC_CATEGORY_META.filter(({ key }) => isCategoryOn(categories, key)).length;
+ const mediaSyncMode = peer.mediaSyncMode === 'host' ? 'host' : 'copy';
const toggleFullSync = async () => {
await updatePeer(peer.id, { fullSync: !fullSync }).catch(() => null);
@@ -654,7 +670,15 @@ function SyncCategoriesPanel({ peer, onRefresh }) {
// as "something is enabled" and widen the peer's outbound push consent.
const toggleCategory = async (key) => {
if (fullSync) return; // categories are locked-on under full mirror
- await updatePeer(peer.id, { syncCategories: { [key]: !categories[key] } }).catch(() => null);
+ const next = !isCategoryOn(categories, key);
+ const keys = key === 'mediaCollections' ? MEDIA_COLLECTION_KEYS : [key];
+ await updatePeer(peer.id, { syncCategories: Object.fromEntries(keys.map(k => [k, next])) }).catch(() => null);
+ onRefresh();
+ };
+
+ const changeMediaSyncMode = async (mode) => {
+ if (mode === mediaSyncMode) return;
+ await updatePeer(peer.id, { mediaSyncMode: mode }).catch(() => null);
onRefresh();
};
@@ -663,6 +687,7 @@ function SyncCategoriesPanel({ peer, onRefresh }) {
for (const { key } of SYNC_CATEGORY_META) {
updated[key] = enable;
}
+ updated.videoHistory = enable;
await updatePeer(peer.id, { syncCategories: updated }).catch(() => null);
onRefresh();
};
@@ -765,10 +790,10 @@ function SyncCategoriesPanel({ peer, onRefresh }) {
</div>
{SYNC_CATEGORY_META.map(({ key, label, icon: Icon, description }) => {
// Under full mirror every category reads as on and is non-interactive.
- const on = fullSync || categories[key];
+ const on = fullSync || isCategoryOn(categories, key);
return (
+ <div key={key}>
<button
- key={key}
onClick={() => toggleCategory(key)}
disabled={fullSync}
title={fullSync ? 'Locked on by full mirror' : undefined}
@@ -787,6 +812,34 @@ function SyncCategoriesPanel({ peer, onRefresh }) {
<p className="text-[10px] text-gray-600 truncate">{description}</p>
</div>
</button>
+ {key === 'mediaCollections' && on && (
+ <fieldset className="ml-7 mt-1 mb-1.5" aria-label="Media Collections sync method">
+ <legend className="sr-only">Media Collections sync method</legend>
+ <div className="flex flex-wrap gap-1.5">
+ {MEDIA_SYNC_MODE_OPTIONS.map(option => (
+ <button
+ key={option.value}
+ type="button"
+ onClick={() => changeMediaSyncMode(option.value)}
+ aria-pressed={mediaSyncMode === option.value}
+ title={option.description}
+ className={`px-2 py-1 min-h-[28px] rounded text-[10px] border transition-colors ${
+ mediaSyncMode === option.value
+ ? 'border-port-accent bg-port-accent/20 text-port-accent'
+ : 'border-port-border text-gray-400 hover:bg-port-bg/50'
+ }`}
+ >
+ {option.label}
+ </button>
+ ))}
+ </div>
+ <p className="text-[10px] text-gray-600 mt-1">
+ {MEDIA_SYNC_MODE_OPTIONS.find(o => o.value === mediaSyncMode).description}
+ {fullSync ? '. Full mirror still copies the whole media library.' : '.'}
+ </p>
+ </fieldset>
+ )}
+ </div>
);
})}
</div>
diff --git a/client/src/pages/MediaCollectionDetail.jsx b/client/src/pages/MediaCollectionDetail.jsx
index db60c41bd7..15395fe162 100644
--- a/client/src/pages/MediaCollectionDetail.jsx
+++ b/client/src/pages/MediaCollectionDetail.jsx
@@ -1,6 +1,6 @@
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { useParams, Link, useNavigate } from 'react-router';
-import { ArrowLeft, CheckSquare, Copy, DatabaseZap, FolderInput, Inbox, Lock, Pencil, Star, StarOff, Trash2, X } from 'lucide-react';
+import { ArrowLeft, Cloud, CloudOff, CheckSquare, Copy, DatabaseZap, FolderInput, HardDriveDownload, Inbox, Lock, Pencil, Star, StarOff, Trash2, X } from 'lucide-react';
import ShareToButton from '../components/sharing/ShareToButton';
import PageSkeleton from '../components/ui/PageSkeleton';
import toast from '../components/ui/Toast';
@@ -17,12 +17,40 @@ import {
listMediaCollections,
addMediaCollectionItem, removeMediaCollectionItem,
deleteImage, deleteVideoHistoryItem,
- pullMissingMetadata,
+ pullMissingMetadata, localizeMediaCollection,
} from '../services/api';
+import socket from '../services/socket';
import useMediaPreviewActions from '../hooks/useMediaPreviewActions';
import usePreviewRoute from '../hooks/usePreviewRoute';
import { useGalleryPage } from '../hooks/useGalleryPage';
+// Local-vs-remote state of one collection item. Local files (the normal case)
+// carry no badge; the header summarizes the peer-hosted count.
+function LocationBadge({ entry }) {
+ if (entry?.location === 'remote') {
+ const host = entry.hostPeerName || 'peer';
+ return (
+ <span
+ className="absolute top-1.5 left-1.5 z-10 px-1.5 py-0.5 rounded bg-black/70 text-port-accent text-[10px] flex items-center gap-1 pointer-events-none"
+ title={`Hosted by ${host} — streamed on demand, not stored on this machine`}
+ >
+ <Cloud className="w-3 h-3" /> {host}
+ </span>
+ );
+ }
+ if (entry?.location === 'missing') {
+ return (
+ <span
+ className="absolute top-1.5 left-1.5 z-10 px-1.5 py-0.5 rounded bg-black/70 text-port-warning text-[10px] flex items-center gap-1 pointer-events-none"
+ title="The file is not on this machine and no peer is known to host it"
+ >
+ <CloudOff className="w-3 h-3" /> Not here
+ </span>
+ );
+ }
+ return null;
+}
+
export default function MediaCollectionDetail() {
const { id } = useParams();
const navigate = useNavigate();
@@ -58,8 +86,45 @@ export default function MediaCollectionDetail() {
setCollection(c); setAllCollections(cols); setNameDraft(c?.name || ''); setLoading(false);
}, [id, isUnsorted, page.refresh]);
useEffect(() => { refresh(); }, [refresh]);
- const items = useMemo(() => page.items.filter(row => isUnsorted || collection?.items?.some(ref => ref.kind === row.kind && ref.ref === (row.kind === 'image' ? row.data.filename : row.data.id)))
- .map(normalizeMediaRow), [page.items, collection, isUnsorted]);
+ // Where each item's bytes live (server-annotated): 'local' | 'remote' (hosted
+ // by a peer and streamed on demand) | 'missing'. Items without an annotation
+ // (older server, unsorted view) read as local.
+ const locationByKey = useMemo(() => new Map((collection?.items || []).map(item => [`${item.kind}:${item.ref}`, item])), [collection]);
+ // The gallery index is built from local disk, so a peer-hosted image never
+ // appears in `page.items`. Append a stub row for each so it still renders
+ // (its /data/images URL falls through to the peer server-side). Videos need
+ // no stub: their rows arrive with the synced video history.
+ const galleryRows = useMemo(() => {
+ if (isUnsorted || page.hasMore) return page.items;
+ const present = new Set(page.items.filter(row => row.kind === 'image').map(row => row.data.filename));
+ const remoteStubs = (collection?.items || [])
+ .filter(item => item.kind === 'image' && item.location === 'remote' && !present.has(item.ref))
+ .map(item => ({ kind: 'image', data: { filename: item.ref, prompt: '', createdAt: item.addedAt } }));
+ return remoteStubs.length ? [...page.items, ...remoteStubs] : page.items;
+ }, [page.items, page.hasMore, collection, isUnsorted]);
+ const items = useMemo(() => galleryRows.filter(row => isUnsorted || collection?.items?.some(ref => ref.kind === row.kind && ref.ref === (row.kind === 'image' ? row.data.filename : row.data.id)))
+ .map(normalizeMediaRow), [galleryRows, collection, isUnsorted]);
+ const remoteKeys = useMemo(() => (collection?.items || []).filter(item => item.location === 'remote').map(item => `${item.kind}:${item.ref}`), [collection]);
+ const [runLocalize, localizing] = useAsyncAction(async () => {
+ const result = await localizeMediaCollection(id, remoteKeys, { silent: true });
+ toast.success(`Copying ${result?.started ?? remoteKeys.length} hosted item(s) to this machine…`);
+ });
+ // A copied file lands as `peerSync:asset-arrived`; re-read the annotations
+ // (and gallery rows) instead of polling. Debounced — a batch fires many.
+ useEffect(() => {
+ if (isUnsorted) return undefined;
+ let active = true;
+ let timer = null;
+ const onArrived = () => {
+ clearTimeout(timer);
+ timer = setTimeout(() => {
+ getMediaCollection(id, { silent: true }).then((c) => { if (active) setCollection(c); }).catch(() => {});
+ page.refresh();
+ }, 500);
+ };
+ socket.on('peerSync:asset-arrived', onArrived);
+ return () => { active = false; clearTimeout(timer); socket.off('peerSync:asset-arrived', onArrived); };
+ }, [id, isUnsorted, page.refresh]);
const resolvePreview = useGalleryPreviewResolver({ collectionId: id });
const [preview, setPreview] = usePreviewRoute(items, { resolveItem: resolvePreview });
@@ -349,6 +414,11 @@ export default function MediaCollectionDetail() {
</Link>
{renderTitle()}
<span className="text-xs text-gray-500">{page.total} item{page.total === 1 ? '' : 's'}</span>
+ {remoteKeys.length > 0 && (
+ <span className="text-xs text-port-accent flex items-center gap-1" title="Hosted by a peer and streamed on demand — not stored on this machine">
+ <Cloud className="w-3.5 h-3.5" /> {remoteKeys.length} on peer
+ </span>
+ )}
{!selectMode && (
<div className="ml-auto flex items-center gap-2">
{isUnsorted && (
@@ -365,6 +435,18 @@ export default function MediaCollectionDetail() {
{pullingPrompts ? 'Pulling…' : 'Pull missing prompts'}
</button>
)}
+ {remoteKeys.length > 0 && (
+ <button
+ type="button"
+ onClick={runLocalize}
+ disabled={localizing}
+ className="px-2.5 py-1 text-xs bg-port-accent/20 hover:bg-port-accent/40 text-port-accent rounded flex items-center gap-1.5 disabled:opacity-40"
+ title="Download the peer-hosted items so they are stored on this machine"
+ >
+ <HardDriveDownload className="w-3.5 h-3.5" />
+ {localizing ? 'Copying…' : `Copy ${remoteKeys.length} to this machine`}
+ </button>
+ )}
{items.length > 0 && (
<button
type="button"
@@ -511,6 +593,7 @@ export default function MediaCollectionDetail() {
onToggleStar={!selectMode ? toggleStar : undefined}
onAnnotate={!selectMode && item.kind === 'image' ? handleAnnotate : undefined}
/>
+ <LocationBadge entry={locationByKey.get(key)} />
{!selectMode && !isUnsorted && (
<button
type="button"
diff --git a/client/src/pages/MediaCollectionDetail.test.jsx b/client/src/pages/MediaCollectionDetail.test.jsx
index c168a34c52..3e1a9dd000 100644
--- a/client/src/pages/MediaCollectionDetail.test.jsx
+++ b/client/src/pages/MediaCollectionDetail.test.jsx
@@ -12,6 +12,7 @@ const mockListMediaCollections = vi.fn();
const mockGetMediaCollection = vi.fn();
const mockAddMediaCollectionItem = vi.fn();
const mockRemoveMediaCollectionItem = vi.fn();
+const mockLocalizeMediaCollection = vi.fn();
vi.mock('../services/api', () => ({
listImageGallery: (...args) => mockListImageGallery(...args),
@@ -24,8 +25,11 @@ vi.mock('../services/api', () => ({
deleteImage: vi.fn(),
deleteVideoHistoryItem: vi.fn(),
pullMissingMetadata: (...args) => mockPullMissingMetadata(...args),
+ localizeMediaCollection: (...args) => mockLocalizeMediaCollection(...args),
}));
+vi.mock('../services/socket', () => ({ default: { on: vi.fn(), off: vi.fn() } }));
+
vi.mock('../services/apiImageVideo', () => ({
listMediaGalleryPage: async ({ collectionId, limit, offset }) => {
const [images, videos, collections, collection] = await Promise.all([
@@ -457,4 +461,23 @@ describe('MediaCollectionDetail — bulkMoveOrCopy move/remove failures', () =>
await waitFor(() => expect(screen.getByText(/of 2 selected/)).toBeInTheDocument());
expect(screen.queryByText(IMAGE_B.filename)).toBeNull();
});
+ it('renders a peer-hosted image the gallery index cannot see, badges it, and copies it locally', async () => {
+ mockListImageGallery.mockResolvedValue([IMAGE_A]);
+ mockListVideoHistory.mockResolvedValue([]);
+ mockGetMediaCollection.mockResolvedValue({
+ ...REAL_COLLECTION,
+ items: [
+ { kind: 'image', ref: IMAGE_A.filename, location: 'local' },
+ { kind: 'image', ref: 'hosted-on-peer.png', location: 'remote', hostPeerId: 'peer-1', hostPeerName: 'Studio Mac' },
+ ],
+ });
+ mockLocalizeMediaCollection.mockResolvedValue({ requested: 1, started: 1 });
+ const user = userEvent.setup();
+ renderReal();
+ // The stub row exists only because the collection annotates it as remote.
+ expect(await screen.findByText('hosted-on-peer.png')).toBeInTheDocument();
+ expect(screen.getByTitle(/Hosted by Studio Mac/)).toBeInTheDocument();
+ await user.click(screen.getByRole('button', { name: /copy 1 to this machine/i }));
+ await waitFor(() => expect(mockLocalizeMediaCollection).toHaveBeenCalledWith(REAL_COLLECTION.id, ['image:hosted-on-peer.png'], { silent: true }));
+ });
});
diff --git a/client/src/services/apiImageVideo.js b/client/src/services/apiImageVideo.js
index 7b81ee6f93..1cfdfe661a 100644
--- a/client/src/services/apiImageVideo.js
+++ b/client/src/services/apiImageVideo.js
@@ -369,6 +369,13 @@ export const renderTimelineProject = (id, options = {}) => request(`/video-timel
// "video:<uuid>"); cover keys use the same format.
export const listMediaCollections = ({ silent = false } = {}) => request('/media/collections', { silent });
export const getMediaCollection = (id, options = {}) => request(`/media/collections/${encodeURIComponent(id)}`, options);
+// Copy a collection's peer-hosted items onto this machine (all, or just `keys`).
+// The pulls run server-side; each landed file arrives as `peerSync:asset-arrived`.
+export const localizeMediaCollection = (id, keys, options = {}) => request(`/media/collections/${encodeURIComponent(id)}/localize`, {
+ method: 'POST',
+ body: JSON.stringify(keys ? { keys } : {}),
+ ...options,
+});
export const createMediaCollection = ({ name, description = '' }, options = {}) => request('/media/collections', {
method: 'POST',
body: JSON.stringify({ name, description }),
diff --git a/docs/STORAGE.md b/docs/STORAGE.md
index 8998374a7d..44d236d1b7 100644
--- a/docs/STORAGE.md
+++ b/docs/STORAGE.md
@@ -207,6 +207,8 @@ goal data together; interrupted intents remain retryable after restore.
**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.
+**Media Collections sync method — `copy` vs `host`.** Each peer carries `mediaSyncMode` (`copy` default | `host`, set per peer in Instances → Sync Categories → Media Collections). `copy` downloads collection image/video bytes into local `data/` (the historical behavior). `host` keeps references only: `applyIncomingPush` (and the `mediaCollections` snapshot apply) records each absent collection-owned file in `data/peer-hosted-media.json` (`{ version, entries: { "<kind>:<filename>": { peerId, at } } }`) instead of pulling it, and the `/data/images`, `/data/videos`, `/data/video-thumbnails` and `/data/image-thumbnails` mounts fall back to streaming the file from that peer when the local copy is absent (`services/peerHostedMedia.js`, Range forwarded). A universe/series' own art and every non-collection asset still copy; a local file always wins over an index entry; full-mirror peers still copy the whole library. `GET /api/media/collections/:id` annotates each item with `location` (`local` | `remote` + `hostPeerId`/`hostPeerName` | `missing`) and `POST /api/media/collections/:id/localize` copies hosted items onto this machine. `data/peer-hosted-media.json` is `file-primary`, a bounded machine-local index of where THIS machine fetches bytes from — **never federated**, rsync-backed-up, no seed or migration (an absent file is an empty index; a peer with no `mediaSyncMode` reads as `copy`). Video-history rows have no separate toggle: `mediaCollections` implies the `videoHistory` snapshot category (`resolveEffectiveCategories`), and a legacy `videoHistory`-only peer keeps syncing.
+
**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/server/lib/peerHttpClient.js b/server/lib/peerHttpClient.js
index 6b6ddeaa5f..7a5ff8aaef 100644
--- a/server/lib/peerHttpClient.js
+++ b/server/lib/peerHttpClient.js
@@ -1,4 +1,5 @@
// Federation HTTP/Socket.IO client — TLS validation off (Tailnet is the trust boundary).
+import http from 'node:http';
import https from 'node:https';
import { createHmac } from 'node:crypto';
import { insecureFetch, RESPONSE_TOO_LARGE } from './httpClient.js';
@@ -104,14 +105,14 @@ export function __resetSelfInstanceIdForTests() {
* `options.headers` still win over the injected headers. The `peer` arg is optional so existing two-arg callers
* keep working.
*/
-export async function peerFetch(url, options = {}, peer = null) {
+async function peerRequestOptions(url, options, peer) {
const callerHeaders = normalizeHeaders(options.headers);
const selfId = await selfInstanceId();
// Scope the pair credential to the record-push endpoint; never disclose it
// to general peer queries, redirects, assets, or announcement responses.
const syncHeaders = peer?.syncSecret && new URL(url).pathname === '/api/peer-sync/push'
? { 'X-PortOS-Peer-Sync-Token': peer.syncSecret } : {};
- const finalOptions = {
+ return {
...options,
// Peer credentials and sender identity must stay at the configured destination.
redirect: 'error',
@@ -124,9 +125,40 @@ export async function peerFetch(url, options = {}, peer = null) {
...callerHeaders,
},
};
+}
+
+export async function peerFetch(url, options = {}, peer = null) {
+ const finalOptions = await peerRequestOptions(url, options, peer);
return url.startsWith('https://') ? httpsFetch(url, finalOptions) : fetch(url, finalOptions);
}
+/**
+ * GET a peer URL WITHOUT buffering the body: resolves once response headers
+ * arrive with `{ status, headers, stream }` (`headers` is Node's lowercase
+ * object, `stream` the raw IncomingMessage). `peerFetch` is unsuitable for
+ * large media — its HTTPS shim collects the entire body before resolving —
+ * so a peer-hosted video would otherwise sit whole in memory per viewer.
+ * Same credential/identity headers and no-redirect posture as `peerFetch`.
+ */
+export async function peerStreamRequest(url, options = {}, peer = null) {
+ const { headers, signal } = await peerRequestOptions(url, options, peer);
+ const u = new URL(url);
+ const secure = u.protocol === 'https:';
+ return new Promise((resolve, reject) => {
+ const req = (secure ? https : http).request({
+ hostname: u.hostname,
+ port: u.port || (secure ? 443 : 80),
+ path: u.pathname + u.search,
+ method: 'GET',
+ headers,
+ signal,
+ ...(secure ? { agent: peerHttpsAgent } : {}),
+ }, (res) => resolve({ status: res.statusCode, headers: res.headers, stream: res }));
+ req.on('error', reject);
+ req.end();
+ });
+}
+
export const PEER_BODY_IDLE_TIMEOUT = 'PEER_BODY_IDLE_TIMEOUT';
// Well above any legitimate snapshot; a body past it is a broken or hostile peer.
export const PEER_BODY_DEFAULT_MAX_BYTES = 256 * 1024 * 1024;
diff --git a/server/routes/instances.js b/server/routes/instances.js
index 984827f302..fce68095f7 100644
--- a/server/routes/instances.js
+++ b/server/routes/instances.js
@@ -84,6 +84,10 @@ const updatePeerSchema = z.object({
// category and back-subscribes all subscribable records to this peer.
fullSync: z.boolean().optional(),
syncCategories: syncCategoriesSchema,
+ // How Media Collection bytes arrive from this peer (mirrors MEDIA_SYNC_MODES
+ // in services/instances.js): copied locally or hosted
+ // by the peer and streamed on demand.
+ mediaSyncMode: z.enum(['copy', 'host']).optional(),
// Accept empty string to clear; any other string is validated/normalized in the service
host: z.string().optional().nullable(),
auth: peerAuthSchema,
diff --git a/server/routes/mediaCollections.js b/server/routes/mediaCollections.js
index bd7502e22b..64b10982fe 100644
--- a/server/routes/mediaCollections.js
+++ b/server/routes/mediaCollections.js
@@ -3,6 +3,10 @@
* `{ items, total, limit, offset }`)
* POST /api/media/collections → Collection (body: { name, description? })
* GET /api/media/collections/:id → Collection
+ * Each item carries `location` ('local' | 'remote' | 'missing')
+ * and, when remote, `hostPeerId`/`hostPeerName` (peer-hosted media)
+ * POST /api/media/collections/:id/localize → { requested, started } (body: { keys?: ["<kind>:<ref>"] };
+ * copies peer-hosted items onto this machine)
* PATCH /api/media/collections/:id → Collection (body: { name?, description?, coverKey?, source? })
* DELETE /api/media/collections/:id → { id }
* POST /api/media/collections/:id/items → Collection (body: { kind, ref })
@@ -16,6 +20,8 @@ import { z } from 'zod';
import { asyncHandler, ServerError, createServiceErrorMapper } from '../lib/errorHandler.js';
import { validateRequest, mediaCollectionBulkItemsSchema, isPaginationRequested, paginateArray } from '../lib/validation.js';
import * as svc from '../services/mediaCollections.js';
+import { resolveMediaLocations, unmarkHosted } from '../services/peerHostedMedia.js';
+import { pullMissingAssetsFromPeer, collectionVideoRefToFilename } from '../services/sharing/peerSyncAssets.js';
const router = Router();
@@ -73,7 +79,35 @@ router.post('/', asyncHandler(async (req, res) => {
router.get('/:id', asyncHandler(async (req, res) => {
const c = await svc.getCollection(req.params.id).catch((err) => { throw mapServiceError(err); });
- res.json(c);
+ const locations = await resolveMediaLocations(c.items);
+ res.json({ ...c, items: c.items.map((item, i) => ({ ...item, ...locations[i] })) });
+}));
+
+const localizeSchema = z.object({ keys: z.array(z.string().min(1).max(svc.REF_MAX_LENGTH + 8)).max(svc.ITEMS_MAX).optional() });
+
+// Copy peer-hosted items onto this machine. Pulls run in the background (a video
+// can be large); each landed file emits `peerSync:asset-arrived`, which the
+// collection page listens for, so there is nothing to poll.
+router.post('/:id/localize', asyncHandler(async (req, res) => {
+ const { keys } = validateRequest(localizeSchema, req.body ?? {});
+ const c = await svc.getCollection(req.params.id).catch((err) => { throw mapServiceError(err); });
+ const wanted = keys ? new Set(keys) : null;
+ const items = c.items.filter((item) => !wanted || wanted.has(svc.itemKey(item)));
+ const locations = await resolveMediaLocations(items);
+ const byPeer = new Map();
+ items.forEach((item, i) => {
+ if (locations[i].location !== 'remote') return;
+ const filename = item.kind === 'video' ? collectionVideoRefToFilename(item.ref) : item.ref;
+ const list = byPeer.get(locations[i].hostPeerId) ?? [];
+ list.push({ kind: item.kind, filename });
+ byPeer.set(locations[i].hostPeerId, list);
+ });
+ const started = [...byPeer.values()].reduce((n, list) => n + list.length, 0);
+ Promise.all([...byPeer.entries()].map(async ([peerId, list]) => {
+ await pullMissingAssetsFromPeer(peerId, list, { includeMismatched: false });
+ await Promise.all(list.map((entry) => unmarkHosted(entry.kind, entry.filename)));
+ })).catch((err) => console.error(`❌ localize collection media failed: ${err.message}`));
+ res.status(202).json({ requested: items.length, started });
}));
router.patch('/:id', asyncHandler(async (req, res) => {
diff --git a/server/services/assetMounts.js b/server/services/assetMounts.js
index 0ec2d7a5ba..0e150c4578 100644
--- a/server/services/assetMounts.js
+++ b/server/services/assetMounts.js
@@ -22,6 +22,7 @@ import { ASSET_ROUTE_PREFIXES, SERVER_OWNED_PREFIXES } from '../lib/assetRoutePr
import { wrWorksDir, WORK_ID_RE } from './writersRoom/_shared.js';
import { escapeRegExp } from '../lib/textUtils.js';
import { ensureImageThumbnail } from '../lib/imageThumbnail.js';
+import { hostedAssetFallback } from './peerHostedMedia.js';
// `acceptRanges: true` is the serve-static default already, but we set it
// explicitly because the federated peer-sync receiver
@@ -115,11 +116,15 @@ const imageThumbnailGate = async (req, res, next) => {
if (!/^\/[A-Za-z0-9][A-Za-z0-9._-]*\.webp$/i.test(req.path)) return res.status(404).end();
const filename = req.path.slice(1);
const ready = await ensureImageThumbnail(filename);
- if (!ready) return res.status(404).end();
+ // No local source PNG: a peer hosting the collection image serves its own thumbnail.
+ if (!ready) return hostedAssetFallback('/data/image-thumbnails')(req, res, () => res.status(404).end());
res.setHeader('Cache-Control', 'public, max-age=86400');
next();
};
+// Mounts whose files a peer may host instead of copying (peerHostedMedia.js).
+const HOSTED_FALLBACK_ROUTES = new Set(['/data/images', '/data/videos', '/data/video-thumbnails']);
+
const ASSET_GATES = {
'/data/image-thumbnails': imageThumbnailGate,
'/data/writers-room/works': writersRoomAssetsOnly,
@@ -178,6 +183,8 @@ export function mountAssetRoutes(app, ownedPrefixes = SERVER_OWNED_PREFIXES) {
ASSET_MOUNTS.forEach(({ route, dir, gate }) => {
const options = route === '/data/image-thumbnails' ? IMAGE_THUMBNAIL_STATIC_OPTS : ASSET_STATIC_OPTS;
app.use(route, ...(gate ? [gate] : []), express.static(dir(), options));
+ // Media a `host`-mode peer keeps: local file absent → stream from the peer.
+ if (HOSTED_FALLBACK_ROUTES.has(route)) app.use(route, hostedAssetFallback(route));
});
ownedPrefixes.forEach(({ prefix, spaPaths }) => {
const spaMatchers = spaPaths.map(toRouteMatcher);
diff --git a/server/services/dataSync.js b/server/services/dataSync.js
index 5e7b56f61e..f2f5f9650e 100644
--- a/server/services/dataSync.js
+++ b/server/services/dataSync.js
@@ -33,6 +33,9 @@ import { getUniverseMutationEpoch } from './universeBuilder/store.js';
import { getPipelineMutationEpoch } from './pipeline/syncEpoch.js';
import { mergeSeriesFromSync, listSeries } from './pipeline/series.js';
import { mergeIssuesFromSync, listAllIssues } from './pipeline/issues.js';
+import { getPeers } from './instances.js';
+import { markHosted } from './peerHostedMedia.js';
+import { referenceCollectionAssetManifest } from './sharing/peerSyncAssets.js';
import { mergeMediaCollectionsFromSync, listCollections, itemKey } from './mediaCollections.js';
import { listSyncableSessionsForWire, mergeStorySessionsFromSync } from './storyBuilder.js';
import { getStoryBuilderMutationEpoch } from './storyBuilderStore/store.js';
@@ -815,6 +818,16 @@ async function applyMediaCollectionsRemote(remoteData, source) {
// bulkUpdateCollectionItems) — a sync-driven write can't interleave with a
// concurrent local mutation on the same JSON file.
const result = await mergeMediaCollectionsFromSync(filtered, { source });
+ // `host`-mode peers keep the bytes: index this snapshot's items as peer-hosted
+ // so the collection renders them via the static-mount fallback. Covers items
+ // that only ever arrive through this snapshot path (no per-record push).
+ if (source?.peerId) {
+ const senderPeer = (await getPeers().catch(() => [])).find((p) => p.instanceId === source.peerId);
+ if (senderPeer?.mediaSyncMode === 'host') {
+ const live = filtered.filter((c) => c?.deleted !== true);
+ await markHosted(source.peerId, live.flatMap((c) => referenceCollectionAssetManifest(c)));
+ }
+ }
if (result.applied) {
console.log(`🔄 MediaCollections sync: merged ${result.count} collection(s)`);
}
diff --git a/server/services/instances.js b/server/services/instances.js
index 49d69d39c3..dc2a5d45f1 100644
--- a/server/services/instances.js
+++ b/server/services/instances.js
@@ -281,6 +281,14 @@ const DEFAULT_SYNC_CATEGORIES = {
export { DEFAULT_SYNC_CATEGORIES };
+// How this install obtains the image/video BYTES behind a synced Media
+// Collection from a peer: `copy` downloads them into local `data/` (default —
+// the historical behavior), `host` keeps only the references and streams each
+// file from the peer on demand (see services/peerHostedMedia.js).
+export const MEDIA_SYNC_MODES = Object.freeze(['copy', 'host']);
+export const DEFAULT_MEDIA_SYNC_MODE = 'copy';
+export const peerMediaSyncMode = (peer) => (MEDIA_SYNC_MODES.includes(peer?.mediaSyncMode) ? peer.mediaSyncMode : DEFAULT_MEDIA_SYNC_MODE);
+
// Categories that stay on for a peer even when the user's master `syncEnabled`
// switch is off — that switch predates them and means "don't replicate my
// content to this peer", so it must not silently retract a default-ON one.
@@ -348,11 +356,17 @@ export function resolveEffectiveCategories(peer, { masterSwitch = true } = {}) {
if (!peerUserEstablished(peer)) {
for (const key of DEFAULT_ON_SYNC_CATEGORIES) defaults[key] = false;
}
- const stored = peer?.syncCategories
+ const storedRaw = peer?.syncCategories
? { ...defaults, ...peer.syncCategories }
// Legacy fallback: a peer with no stored map but sync on gets brain+memory,
// the pre-per-category behavior.
: { ...defaults, ...(peer?.syncEnabled !== false ? { brain: true, memory: true } : {}) };
+ // Video-history rows are the metadata half of Media Collections: a synced
+ // collection's `{ kind:'video' }` items only render once the matching row
+ // exists. There is no separate user-facing toggle, so `mediaCollections`
+ // implies `videoHistory`; a legacy peer that only had `videoHistory` on keeps
+ // it (OR, never AND), so upgrading stops nothing that was flowing.
+ const stored = storedRaw.mediaCollections ? { ...storedRaw, videoHistory: true } : storedRaw;
if (!masterSwitch || peer?.syncEnabled !== false) return stored;
return Object.fromEntries(DEFAULT_ON_SYNC_CATEGORIES.map((key) => [key, stored[key] === true]));
}
@@ -540,6 +554,9 @@ export async function updatePeer(id, updates, { probe = true } = {}) {
}
}
if (updates.name !== undefined) peer.name = validName(updates.name, peer.name);
+ if (updates.mediaSyncMode !== undefined && MEDIA_SYNC_MODES.includes(updates.mediaSyncMode)) {
+ peer.mediaSyncMode = updates.mediaSyncMode;
+ }
if (updates.enabled !== undefined) peer.enabled = updates.enabled;
if (updates.syncEnabled !== undefined) peer.syncEnabled = updates.syncEnabled;
// Full-sync ("mirror everything") toggle. A false→true flip implies every
diff --git a/server/services/instances.test.js b/server/services/instances.test.js
index 104e51023f..b7bb87d531 100644
--- a/server/services/instances.test.js
+++ b/server/services/instances.test.js
@@ -425,6 +425,21 @@ describe('instances.js', () => {
});
});
+ // Video-history rows are the metadata half of Media Collections — one toggle.
+ describe('resolveEffectiveCategories — videoHistory folded into mediaCollections', () => {
+ it('implies videoHistory whenever mediaCollections is on', () => {
+ const peer = { id: 'p1', syncCategories: { mediaCollections: true, videoHistory: false } };
+ expect(resolveEffectiveCategories(peer)).toMatchObject({ mediaCollections: true, videoHistory: true });
+ });
+
+ it('keeps a legacy videoHistory-only peer syncing, and adds nothing when both are off', () => {
+ expect(resolveEffectiveCategories({ id: 'p1', syncCategories: { videoHistory: true } }))
+ .toMatchObject({ mediaCollections: false, videoHistory: true });
+ expect(resolveEffectiveCategories({ id: 'p2', syncCategories: {} }))
+ .toMatchObject({ mediaCollections: false, videoHistory: false });
+ });
+ });
+
describe('sanitizePeerForClient', () => {
it('never exposes a legacy tailcat capability on either wire surface', () => {
const peer = { id: 'peer-example', tcAddress: 'tcEXAMPLE' + 'A'.repeat(40) };
@@ -488,6 +503,13 @@ describe('instances.js', () => {
expect(result.name).toBe('new-name');
});
+ it('stores the media sync mode and ignores an unknown one', async () => {
+ readJSONFile.mockResolvedValue({ self: null, peers: [{ id: 'peer-1', name: 'host', enabled: true }] });
+ expect((await updatePeer('peer-1', { mediaSyncMode: 'host' })).mediaSyncMode).toBe('host');
+ readJSONFile.mockResolvedValue({ self: null, peers: [{ id: 'peer-1', name: 'host', enabled: true, mediaSyncMode: 'host' }] });
+ expect((await updatePeer('peer-1', { mediaSyncMode: 'stream-everything' })).mediaSyncMode).toBe('host');
+ });
+
it('should update peer enabled state', async () => {
const peers = [{ id: 'peer-1', name: 'host', enabled: true }];
readJSONFile.mockResolvedValue({ self: null, peers });
diff --git a/server/services/peerHostedMedia.js b/server/services/peerHostedMedia.js
new file mode 100644
index 0000000000..b3c605a5ab
--- /dev/null
+++ b/server/services/peerHostedMedia.js
@@ -0,0 +1,226 @@
+/**
+ * Peer-hosted media index — the "host" half of the Media Collections sync mode.
+ *
+ * A peer whose `mediaSyncMode` is `host` never has its collection image/video
+ * bytes copied into this install's `data/`. Instead the receiver records, per
+ * `<kind>:<filename>`, WHICH peer hosts the file, and the local static mounts
+ * (`/data/images`, `/data/videos`, `/data/video-thumbnails`,
+ * `/data/image-thumbnails`) fall back to streaming that file from the peer when
+ * the local copy is absent (`streamHostedAsset`, wired in assetMounts.js). Every
+ * existing `<img src="/data/images/x.png">` therefore renders unchanged.
+ *
+ * Machine-local (`file-primary`, docs/STORAGE.md): it describes where THIS
+ * machine fetches bytes from, so it never federates. A local file always wins —
+ * once bytes exist on disk (copied, generated, or "Copy locally") the entry is
+ * ignored and pruned lazily.
+ */
+import { join, extname, basename } from 'path';
+import { existsSync } from 'fs';
+import { pipeline } from 'stream/promises';
+import { PATHS, readJSONFile, atomicWrite } from '../lib/fileUtils.js';
+import { createFileWriteQueue } from '../lib/fileWriteQueue.js';
+import { isPlainObject } from '../lib/objects.js';
+import { isStr } from '../lib/textUtils.js';
+import { peerBaseUrl } from '../lib/peerUrl.js';
+import { peerStreamRequest } from '../lib/peerHttpClient.js';
+import { withAbortTimeout } from '../lib/abortTimeout.js';
+import { sanitizeAssetFilename } from './sharing/buckets.js';
+import { getPeers } from './instances.js';
+
+const HOSTED_FILE = () => join(PATHS.data, 'peer-hosted-media.json');
+const SCHEMA_VERSION = 1;
+const queueWrite = createFileWriteQueue();
+const STREAM_TIMEOUT_MS = 30000;
+
+// kind → { local dir thunk, peer static-mount prefix }. Only kinds a collection
+// can hold. Thumbnails are derived views of these two, resolved below.
+const KIND_DIRS = {
+ image: () => PATHS.images,
+ video: () => PATHS.videos,
+};
+const KIND_PREFIX = { image: '/data/images', video: '/data/videos' };
+const VIDEO_EXTS = ['.mp4', '.webm', '.mov', '.m4v', '.ogv'];
+
+export const hostedKey = (kind, filename) => `${kind}:${filename}`;
+
+// STRICT: an unreadable index must never be written back as an empty one that
+// wipes every entry (absent file → real empty). Rendering-side readers use
+// `readEntriesOrEmpty` — an unreadable index just means "nothing is hosted".
+async function readEntries() {
+ const raw = await readJSONFile(HOSTED_FILE(), null, { strict: true });
+ return isPlainObject(raw) && isPlainObject(raw.entries) ? raw.entries : {};
+}
+const readEntriesOrEmpty = () => readEntries().catch(() => ({}));
+
+const writeEntries = (entries) => atomicWrite(HOSTED_FILE(), { version: SCHEMA_VERSION, entries });
+
+/**
+ * Record that `peerInstanceId` hosts these `{ kind, filename }` files. A file
+ * already on local disk is never recorded (local copy wins). Returns the number
+ * of entries added or re-pointed.
+ */
+export function markHosted(peerInstanceId, assets) {
+ if (!isStr(peerInstanceId) || !Array.isArray(assets) || assets.length === 0) return Promise.resolve(0);
+ return queueWrite(async () => {
+ const entries = await readEntries();
+ let changed = 0;
+ const at = new Date().toISOString();
+ for (const asset of assets) {
+ const dir = KIND_DIRS[asset?.kind]?.();
+ const filename = isStr(asset?.filename) ? sanitizeAssetFilename(asset.filename) : null;
+ if (!dir || !filename) continue;
+ if (existsSync(join(dir, filename))) continue;
+ const key = hostedKey(asset.kind, filename);
+ if (entries[key]?.peerId === peerInstanceId) continue;
+ entries[key] = { peerId: peerInstanceId, at };
+ changed++;
+ }
+ if (changed > 0) await writeEntries(entries);
+ return changed;
+ });
+}
+
+/**
+ * Host-mode split of a push's missing-asset list. Collection-owned entries whose
+ * bytes are ABSENT locally are recorded as hosted by `peerInstanceId` and
+ * dropped from the pull list; everything else (non-collection assets, or a file
+ * that exists locally but differs) still flows through the normal copy path.
+ * `collectionKeys` is a Set of `<kind>:<filename>`. Returns the assets to pull.
+ */
+export async function takeHostedAssets(peerInstanceId, missingAssets, collectionKeys) {
+ const hosted = [];
+ const remaining = [];
+ for (const entry of missingAssets) {
+ const dir = KIND_DIRS[entry?.kind]?.();
+ const owned = dir && collectionKeys.has(hostedKey(entry.kind, entry.filename));
+ if (owned && !existsSync(join(dir, entry.filename))) hosted.push(entry);
+ else remaining.push(entry);
+ }
+ if (hosted.length > 0) await markHosted(peerInstanceId, hosted);
+ return remaining;
+}
+
+/** Drop a hosted entry once its bytes are local; a still-absent file keeps its entry. */
+export function unmarkHosted(kind, filename) {
+ return queueWrite(async () => {
+ const dir = KIND_DIRS[kind]?.();
+ if (!dir || !existsSync(join(dir, filename))) return false;
+ const entries = await readEntries();
+ const key = hostedKey(kind, filename);
+ if (!(key in entries)) return false;
+ delete entries[key];
+ await writeEntries(entries);
+ return true;
+ });
+}
+
+/** Where does this media file live? `local` | `remote` (hosted by a peer) | `missing`. */
+export async function resolveMediaLocations(items) {
+ const entries = await readEntriesOrEmpty();
+ const peers = await getPeers().catch(() => []);
+ const peerName = new Map(peers.map((p) => [p.instanceId, p.name || null]));
+ return (Array.isArray(items) ? items : []).map((item) => {
+ const kind = item?.kind === 'video' ? 'video' : 'image';
+ const filename = kind === 'video' ? videoRefToFilename(item.ref) : item?.ref;
+ const safe = isStr(filename) ? sanitizeAssetFilename(filename) : null;
+ if (!safe) return { location: 'missing' };
+ if (existsSync(join(KIND_DIRS[kind](), safe))) return { location: 'local' };
+ const hosted = entries[hostedKey(kind, safe)];
+ if (!hosted) return { location: 'missing' };
+ return { location: 'remote', hostPeerId: hosted.peerId, hostPeerName: peerName.get(hosted.peerId) ?? null };
+ });
+}
+
+// Collection video refs are bare ids; on disk they are `<id>.<ext>` (mp4 today).
+// Mirrors collectionVideoRefToFilename in sharing/peerSyncAssets.js without
+// importing it (that module would drag the whole peer-sync graph in here).
+const videoRefToFilename = (ref) => (isStr(ref) ? (/\.[a-z0-9]+$/i.test(ref) ? ref : `${ref}.mp4`) : null);
+
+async function lookupHosted(kind, filename) {
+ const entries = await readEntriesOrEmpty();
+ return entries[hostedKey(kind, filename)] || null;
+}
+
+/**
+ * Resolve a request for a local static path to `{ peerId, url }`
+ * when a peer hosts it and the local file is absent; otherwise null.
+ * `mount` is the static route the request arrived on.
+ */
+async function resolveHostedRequest(mount, filename) {
+ const safe = sanitizeAssetFilename(filename);
+ if (!safe) return null;
+ if (mount === '/data/images') {
+ const hosted = await lookupHosted('image', safe);
+ return hosted && { peerId: hosted.peerId, url: `${KIND_PREFIX.image}/${encodeURIComponent(safe)}` };
+ }
+ if (mount === '/data/videos') {
+ const hosted = await lookupHosted('video', safe);
+ return hosted && { peerId: hosted.peerId, url: `${KIND_PREFIX.video}/${encodeURIComponent(safe)}` };
+ }
+ if (mount === '/data/image-thumbnails') {
+ // `<stem>.webp` is derived from `<stem>.png`; the peer serves its own
+ // thumbnail from the same path, so ask it for the thumbnail directly.
+ const hosted = await lookupHosted('image', `${safe.replace(/\.webp$/i, '')}.png`);
+ return hosted && { peerId: hosted.peerId, url: `/data/image-thumbnails/${encodeURIComponent(safe)}` };
+ }
+ if (mount === '/data/video-thumbnails') {
+ const stem = basename(safe, extname(safe));
+ for (const ext of VIDEO_EXTS) {
+ const hosted = await lookupHosted('video', `${stem}${ext}`);
+ if (hosted) return { peerId: hosted.peerId, url: `/data/video-thumbnails/${encodeURIComponent(safe)}` };
+ }
+ }
+ return null;
+}
+
+/**
+ * Express fallback mounted AFTER a static mount: when the local file is absent
+ * and a peer hosts it, stream it from the peer (Range forwarded so video
+ * scrubbing works). Anything else falls through to the mount's 404.
+ */
+export function hostedAssetFallback(mount) {
+ return async (req, res, next) => {
+ if (req.method !== 'GET' && req.method !== 'HEAD') return next();
+ let filename;
+ try { filename = decodeURIComponent(req.path.replace(/^\//, '')); } catch { return next(); }
+ // Fast reject: only flat basenames are ever hosted.
+ if (!filename || filename.includes('/')) return next();
+ const target = await resolveHostedRequest(mount, filename).catch(() => null);
+ if (!target) return next();
+ const peers = await getPeers().catch(() => []);
+ const peer = peers.find((p) => p.instanceId === target.peerId);
+ if (!peer) return next();
+ await streamFromPeer(peer, target.url, req, res).catch((err) => {
+ console.warn(`⚠️ peerHostedMedia: stream ${mount} from ${peer.name || 'peer'} failed: ${err.message}`);
+ if (!res.headersSent) res.status(502).end();
+ else res.destroy();
+ });
+ };
+}
+
+async function streamFromPeer(peer, path, req, res) {
+ const headers = {};
+ if (isStr(req.headers.range)) headers.Range = req.headers.range;
+ const upstream = await withAbortTimeout(STREAM_TIMEOUT_MS, (signal) =>
+ peerStreamRequest(`${peerBaseUrl(peer)}${path}`, { signal, headers }, peer));
+ if (upstream.status !== 200 && upstream.status !== 206) {
+ upstream.stream.resume();
+ res.status(upstream.status === 404 ? 404 : 502).end();
+ return;
+ }
+ res.status(upstream.status);
+ for (const name of ['content-type', 'content-length', 'content-range', 'accept-ranges', 'last-modified', 'etag']) {
+ const value = upstream.headers[name];
+ if (value) res.setHeader(name, value);
+ }
+ // Same hardening as the local static mounts: peer bytes must never execute
+ // with the PortOS origin's privileges.
+ res.setHeader('X-Content-Type-Options', 'nosniff');
+ res.setHeader('Content-Security-Policy', "sandbox; default-src 'none'; img-src 'self' data: blob:; media-src 'self'; style-src 'unsafe-inline'");
+ res.setHeader('X-PortOS-Media-Location', 'remote');
+ if (req.method === 'HEAD') {
+ upstream.stream.destroy();
+ return res.end();
+ }
+ await pipeline(upstream.stream, res);
+}
diff --git a/server/services/peerHostedMedia.test.js b/server/services/peerHostedMedia.test.js
new file mode 100644
index 0000000000..3aaf6250bc
--- /dev/null
+++ b/server/services/peerHostedMedia.test.js
@@ -0,0 +1,140 @@
+/**
+ * Host-mode media: the index, the location resolver, and the static-mount
+ * fallback that renders a peer-hosted file through an unchanged local URL.
+ * Real files under a temp data root; only the peer transport is faked.
+ */
+import { describe, it, expect, beforeAll, afterAll, beforeEach, vi } from 'vitest';
+import express from 'express';
+import { Readable } from 'stream';
+import { mkdirSync, rmSync, writeFileSync } from 'fs';
+import { join } from 'path';
+import { request } from '../lib/testHelper.js';
+import { createTempDataRoot, makePathsProxy } from '../lib/mockPathsDataRoot.js';
+
+const tempRoot = createTempDataRoot('portos-peer-hosted-media-');
+vi.mock('../lib/fileUtils.js', async (importOriginal) => (
+ makePathsProxy(await importOriginal(), { dataRoot: tempRoot })
+));
+afterAll(() => rmSync(tempRoot, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 }));
+
+const PEER = { id: 'p1', instanceId: 'peer-instance-1', name: 'Studio Mac', host: 'peer.example.com', port: 5555 };
+vi.mock('./instances.js', () => ({ getPeers: vi.fn(async () => [PEER]) }));
+
+const streamRequest = vi.fn();
+vi.mock('../lib/peerHttpClient.js', () => ({ peerStreamRequest: (...args) => streamRequest(...args) }));
+
+const { markHosted, unmarkHosted, takeHostedAssets, resolveMediaLocations } = await import('./peerHostedMedia.js');
+const { mountAssetRoutes } = await import('./assetMounts.js');
+
+let app;
+beforeAll(() => {
+ mkdirSync(join(tempRoot, 'images'), { recursive: true });
+ mkdirSync(join(tempRoot, 'videos'), { recursive: true });
+ writeFileSync(join(tempRoot, 'images', 'local.png'), 'LOCALBYTES');
+ app = express();
+ mountAssetRoutes(app);
+});
+
+beforeEach(async () => {
+ streamRequest.mockReset();
+ rmSync(join(tempRoot, 'peer-hosted-media.json'), { force: true });
+});
+
+const upstream = (body, status = 200, headers = {}) => ({
+ status,
+ headers: { 'content-type': 'image/png', 'content-length': String(body.length), ...headers },
+ stream: Readable.from([Buffer.from(body)]),
+});
+
+describe('resolveMediaLocations', () => {
+ it('reports local, peer-hosted (with the host name) and missing files', async () => {
+ await markHosted(PEER.instanceId, [{ kind: 'image', filename: 'remote.png' }, { kind: 'video', filename: 'v1.mp4' }]);
+ const result = await resolveMediaLocations([
+ { kind: 'image', ref: 'local.png' },
+ { kind: 'image', ref: 'remote.png' },
+ { kind: 'video', ref: 'v1' }, // bare video id → v1.mp4
+ { kind: 'image', ref: 'nobody-has-this.png' },
+ ]);
+ expect(result).toEqual([
+ { location: 'local' },
+ { location: 'remote', hostPeerId: PEER.instanceId, hostPeerName: 'Studio Mac' },
+ { location: 'remote', hostPeerId: PEER.instanceId, hostPeerName: 'Studio Mac' },
+ { location: 'missing' },
+ ]);
+ });
+
+ it('never marks a file that already exists locally as hosted', async () => {
+ expect(await markHosted(PEER.instanceId, [{ kind: 'image', filename: 'local.png' }])).toBe(0);
+ });
+
+ it('drops the entry only once the bytes are actually local', async () => {
+ await markHosted(PEER.instanceId, [{ kind: 'image', filename: 'arriving.png' }]);
+ expect(await unmarkHosted('image', 'arriving.png')).toBe(false); // pull failed: keep host entry
+ writeFileSync(join(tempRoot, 'images', 'arriving.png'), 'BYTES');
+ expect(await unmarkHosted('image', 'arriving.png')).toBe(true);
+ });
+});
+
+describe('takeHostedAssets', () => {
+ it('hosts absent collection-owned files and leaves everything else to the copy path', async () => {
+ const missing = [
+ { kind: 'image', filename: 'coll-only.png' },
+ { kind: 'image', filename: 'universe-art.png' }, // not collection-owned → still copied
+ { kind: 'image', filename: 'local.png' }, // exists locally with a different hash → still copied
+ ];
+ const keys = new Set(['image:coll-only.png', 'image:local.png']);
+ const remaining = await takeHostedAssets(PEER.instanceId, missing, keys);
+ expect(remaining.map((a) => a.filename)).toEqual(['universe-art.png', 'local.png']);
+ expect((await resolveMediaLocations([{ kind: 'image', ref: 'coll-only.png' }]))[0].location).toBe('remote');
+ });
+});
+
+describe('static-mount fallback', () => {
+ it('streams a peer-hosted image through the unchanged local URL', async () => {
+ await markHosted(PEER.instanceId, [{ kind: 'image', filename: 'remote.png' }]);
+ streamRequest.mockResolvedValue(upstream('REMOTEBYTES'));
+ const res = await request(app).get('/data/images/remote.png');
+ expect(res.status).toBe(200);
+ expect(res.headers['x-portos-media-location']).toBe('remote');
+ expect(res.headers['x-content-type-options']).toBe('nosniff');
+ expect(streamRequest.mock.calls[0][0]).toBe('https://peer.example.com:5555/data/images/remote.png');
+ });
+
+ it('prefers the local copy over a recorded host', async () => {
+ await markHosted(PEER.instanceId, [{ kind: 'image', filename: 'shadowed.png' }]);
+ writeFileSync(join(tempRoot, 'images', 'shadowed.png'), 'LOCALWINS');
+ const res = await request(app).get('/data/images/shadowed.png');
+ expect(res.status).toBe(200);
+ expect(res.text).toBe('LOCALWINS');
+ expect(streamRequest).not.toHaveBeenCalled();
+ });
+
+ it('forwards Range so a hosted video can be scrubbed', async () => {
+ await markHosted(PEER.instanceId, [{ kind: 'video', filename: 'clip.mp4' }]);
+ streamRequest.mockResolvedValue(upstream('PART', 206, { 'content-type': 'video/mp4', 'content-range': 'bytes 0-3/100' }));
+ const res = await request(app).get('/data/videos/clip.mp4').set('Range', 'bytes=0-3');
+ expect(res.status).toBe(206);
+ expect(streamRequest.mock.calls[0][1].headers.Range).toBe('bytes=0-3');
+ });
+
+ it('serves a hosted video poster from the peer (stem lookup)', async () => {
+ await markHosted(PEER.instanceId, [{ kind: 'video', filename: 'clip2.mp4' }]);
+ streamRequest.mockResolvedValue(upstream('JPEG', 200, { 'content-type': 'image/jpeg' }));
+ const res = await request(app).get('/data/video-thumbnails/clip2.jpg');
+ expect(res.status).toBe(200);
+ expect(streamRequest.mock.calls[0][0]).toBe('https://peer.example.com:5555/data/video-thumbnails/clip2.jpg');
+ });
+
+ it('404s a file nobody hosts', async () => {
+ const res = await request(app).get('/data/images/unknown.png');
+ expect(res.status).toBe(404);
+ expect(streamRequest).not.toHaveBeenCalled();
+ });
+
+ it('answers 502 when the host peer is unreachable', async () => {
+ await markHosted(PEER.instanceId, [{ kind: 'image', filename: 'offline.png' }]);
+ streamRequest.mockRejectedValue(new Error('ECONNREFUSED'));
+ const res = await request(app).get('/data/images/offline.png');
+ expect(res.status).toBe(502);
+ });
+});
diff --git a/server/services/sharing/peerSync.test.js b/server/services/sharing/peerSync.test.js
index cb71f0765a..5d0bfec690 100644
--- a/server/services/sharing/peerSync.test.js
+++ b/server/services/sharing/peerSync.test.js
@@ -4951,6 +4951,34 @@ describe('peerSync', () => {
expect(found.name).toBe('Synced');
});
+ it('host-mode peer: indexes collection bytes as peer-hosted instead of pulling them', async () => {
+ vi.mocked(getPeers).mockResolvedValue([{ id: 'p-host', instanceId: 'peer-host', name: 'Host', mediaSyncMode: 'host' }]);
+ const record = { id: 'col-h', name: 'Hosted', items: [{ kind: 'image', ref: 'hosted-only.png' }], updatedAt: '2026-05-23T00:00:00.000Z' };
+ const result = await applyIncomingPush({
+ kind: 'mediaCollection',
+ record,
+ assetManifest: [{ kind: 'image', filename: 'hosted-only.png', sha256: 'a'.repeat(64) }],
+ sourceInstanceId: 'peer-host',
+ });
+ // Nothing left to copy → the sender is not told bytes are "still syncing".
+ expect(result.missingAssets).toEqual([]);
+ expect(peerFetch).not.toHaveBeenCalledWith(expect.stringContaining('/data/images/hosted-only.png'), expect.anything(), expect.anything());
+ const { resolveMediaLocations } = await import('../peerHostedMedia.js');
+ expect((await resolveMediaLocations([{ kind: 'image', ref: 'hosted-only.png' }]))[0])
+ .toMatchObject({ location: 'remote', hostPeerId: 'peer-host' });
+ });
+
+ it('copy-mode peer (default): the same push still reports the asset as missing to copy', async () => {
+ vi.mocked(getPeers).mockResolvedValue([{ id: 'p-copy', instanceId: 'peer-copy', name: 'Copy' }]);
+ const result = await applyIncomingPush({
+ kind: 'mediaCollection',
+ record: { id: 'col-c', name: 'Copied', items: [{ kind: 'image', ref: 'copied.png' }], updatedAt: '2026-05-23T00:00:00.000Z' },
+ assetManifest: [{ kind: 'image', filename: 'copied.png', sha256: 'b'.repeat(64) }],
+ sourceInstanceId: 'peer-copy',
+ });
+ expect(result.missingAssets).toHaveLength(1);
+ });
+
it('routes a mediaCollection push through mergeMediaCollectionsFromSync (mock assertion)', async () => {
await applyIncomingPush({
kind: 'mediaCollection',
diff --git a/server/services/sharing/peerSyncReceive.js b/server/services/sharing/peerSyncReceive.js
index 52c9ba8251..6e63508b5a 100644
--- a/server/services/sharing/peerSyncReceive.js
+++ b/server/services/sharing/peerSyncReceive.js
@@ -29,11 +29,13 @@ import {
} from './peerTombstoneCursors.js';
import {
diffAssetManifestAgainstLocal,
+ referenceCollectionAssetManifest,
pullMissingAssetsFromPeer,
pullMissingWorkBodies,
pullMissingWorkBibles,
} from './peerSyncAssets.js';
import { RECORD_KINDS } from './recordKinds.js';
+import { takeHostedAssets } from '../peerHostedMedia.js';
import { findPeerSubscription, subscribePeer } from './peerSubscriptions.js';
import {
makeErr,
@@ -393,7 +395,26 @@ export async function applyIncomingPush(payload, authorization) {
if (ownAssets.length < incomingAssets.length) {
console.warn(`⚠️ peerSync: ignored ${incomingAssets.length - ownAssets.length} unreferenced push assets`);
}
- const missingAssets = await diffAssetManifestAgainstLocal(ownAssets, { includeMismatched: mergeResult?.applied === true });
+ let missingAssets = await diffAssetManifestAgainstLocal(ownAssets, { includeMismatched: mergeResult?.applied === true });
+
+ // Media Collections `host` mode: this peer keeps the collection's image/video
+ // bytes, so record them as peer-hosted (rendered on demand via the static-mount
+ // fallback) instead of copying. Only collection-owned assets qualify — a
+ // universe/series' own art still copies.
+ if (missingAssets.length > 0 && !localEphemeral && record.deleted !== true) {
+ const senderPeer = await findPeerById(sourceInstanceId);
+ if (senderPeer?.mediaSyncMode === 'host') {
+ const collection = kind === 'mediaCollection' ? record : linkedCollection;
+ const assetKey = (entry) => `${entry.kind}:${entry.filename}`;
+ const collectionKeys = new Set(isPlainObject(collection) ? referenceCollectionAssetManifest(collection).map(assetKey) : []);
+ if (kind !== 'mediaCollection' && desc.referencedAssets) {
+ // Assets the record itself references stay copies even when the linked
+ // collection also holds them.
+ for (const entry of await desc.referencedAssets(record, { issues, linkedTrack })) collectionKeys.delete(assetKey(entry));
+ }
+ if (collectionKeys.size > 0) missingAssets = await takeHostedAssets(sourceInstanceId, missingAssets, collectionKeys);
+ }
+ }
// Compute the deletedAt water-mark we can ack. Use the maximum across the
// record + its issues + a bundled linkedTrack tombstone (#1858 bundles the