Skip to content

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

fix(sync): federated collection reconciliation + Pull-from-peer + drawer resilience (#472)

[._.]/ Adam Eivya6ebed9e218f
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 1236c5db85..5a98160554 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -25,6 +25,7 @@
## Fixed
+- **Federated media-collection sync reconciliation + resolution UX.** Follow-up to the federated-media-collections feature, fixing issues found running it across two machines. (1) **Universe/series-linked collections now reconcile across peers.** Each machine used to mint a random UUID for its "Universe: X" / "Series: Y" collection, so per-record sync (keyed on `id`) treated each machine's copy as distinct — integrity reported both sides "local only" and the merge created a *duplicate* on every peer. Linked collections now derive a deterministic id (`uc-<universeId>` / `sc-<seriesId>`); create paths reclaim the id when a tombstone holds it (re-creating a deleted collection). Migration 038 canonicalizes existing ids on each machine, merging (union of items) any same-owner duplicates and rewriting `mediaCollection` subscription recordIds — idempotent; both machines converge independently. (2) **New "Pull from peer" action** (`GET /api/peer-sync/record` + `POST /api/peer-sync/pull-record`) lets a machine that is *behind* on a record fetch it and background-pull its asset bytes via `applyIncomingPush`, instead of "Sync to peer" being push-only; the Sync Details drawer is now direction-aware (Pull for peer-only, Sync for local-only, both for diverged/assets-missing). (3) **The Sync Details drawer can no longer hang on "Loading…"** — the record fetch gets a 12s timeout + explicit error state. (4) **Removed the unbounded "Live-pushed records" per-record list** from the Instances page (the Sync Details drawer covers per-record status). `mediaCollections` sync remains opt-in per peer — enable the "Media Collections" category on the Instances page for collections to sync.
- **[upcoming-tasks-widget-drop-catch-to-empty] Upcoming Tasks widget no longer blanks on a transient hiccup** — a momentary failure of the dashboard's Upcoming Tasks background refresh now keeps the last-loaded tasks on screen instead of clearing the list.
- **[propagate-runner-errorAnalysis-into-onRunFailed-context] Propagate `metadata.errorAnalysis` into the `onRunFailed` event context.** Runner-provided error analysis now rides the failed run result into `promptRunner`, so fallback provider marking reuses the category and wait-time already computed by the runner instead of analyzing the wrapper error again. The emitted `AI_PROVIDER_EXECUTION_FAILED` context also includes `errorAnalysis` for downstream auto-fix and diagnostics consumers.
- **`plan-task` agents now claim their own PLAN.md item instead of one the scheduler pre-picks.** The scheduled "plan-task" job used to reserve a PLAN.md slug at dispatch time and hand it to the agent as a hard constraint, but the actual lock (the `claim/<slug>` branch) isn't created until the agent runs — so two runs firing close together could both be handed the same first-available item, and one would waste its turn (the failure mode behind the 2026-05-21 duplicate-PR incident). The agent now picks the next unclaimed item itself at execution time and immediately creates the claim branch, exactly like the `/claim` command, so concurrent runs naturally land on different items. The dispatch-time scan is kept only as a gate that skips the run when nothing is claimable. Existing scheduled-task prompts auto-upgrade on next load (`plan-task` prompt v6 → v7); `feature-ideas` is unaffected.
diff --git a/client/src/components/sync/SyncDetailDrawer.jsx b/client/src/components/sync/SyncDetailDrawer.jsx
index 11a18a0b90..8c58a44104 100644
--- a/client/src/components/sync/SyncDetailDrawer.jsx
+++ b/client/src/components/sync/SyncDetailDrawer.jsx
@@ -18,7 +18,7 @@ import { X, RefreshCw, ArrowUpCircle, Download, CheckCircle2, AlertTriangle, Wif
import toast from '../ui/Toast';
import { useSyncIntegrity } from '../../hooks/useSyncIntegrity';
import { useAsyncAction } from '../../hooks/useAsyncAction';
-import { getMediaCollection, getUniverse, getPipelineSeries, syncRecordToPeer, pullMissingMetadata } from '../../services/api';
+import { getMediaCollection, getUniverse, getPipelineSeries, syncRecordToPeer, pullRecordFromPeer, pullMissingMetadata } from '../../services/api';
import MediaImage from '../MediaImage';
// ── Per-kind record fetcher ──────────────────────────────────────────────────
@@ -30,6 +30,10 @@ const KIND_FETCHER = {
series: getPipelineSeries,
};
+// Cap how long the drawer waits on the record fetch before surfacing an error
+// state — guarantees the "Loading…" spinner can't hang forever if a request stalls.
+const RECORD_LOAD_TIMEOUT_MS = 12000;
+
// ── Per-status display config ────────────────────────────────────────────────
const STATUS_CONFIG = {
'in-parity': {
@@ -75,7 +79,7 @@ function StatusPill({ status }) {
// Presentational only — the collection state is owned by the drawer (fetched
// once there) and passed down, so the "Pull missing metadata" action can read
// the same already-loaded record without a second fetch.
-function CollectionPreview({ collection, loading }) {
+function CollectionPreview({ collection, loading, error }) {
if (loading) {
return (
<div className="flex items-center gap-2 text-gray-500 text-sm py-2">
@@ -84,6 +88,14 @@ function CollectionPreview({ collection, loading }) {
</div>
);
}
+ if (error) {
+ return (
+ <div className="flex items-center gap-2 text-port-warning text-sm py-2">
+ <AlertTriangle className="w-4 h-4" />
+ Couldn’t load this collection — try Refresh.
+ </div>
+ );
+ }
if (!collection) {
return <p className="text-gray-500 text-sm">Collection not found.</p>;
}
@@ -132,10 +144,25 @@ const PUSH_SKIP_LABELS = {
network: 'network error reaching the peer',
};
+// Friendly labels for the `{ pulled:false, reason }` shapes pullRecordFromPeer
+// can return. Unmapped reasons (e.g. `http-500`) fall back to the raw string.
+const PULL_SKIP_LABELS = {
+ 'peer-not-found': 'peer not found',
+ 'peer-unreachable': 'peer offline or unreachable',
+ 'not-on-peer': 'record not on that peer (or peer on an older PortOS)',
+ 'invalid-payload': 'peer returned an unexpected response',
+};
+
// ── Peer row with per-peer sync action ───────────────────────────────────────
function PeerRow({ entry, kind, recordId, onRefresh }) {
const { peerId, peerName, status } = entry;
- const needsAction = status !== 'in-parity';
+ // Direction-aware actions. local-only → we have it, peer doesn't → PUSH.
+ // peer-only → peer has it, we don't → PULL. diverged / assets-missing are
+ // ambiguous (either side could be ahead) → offer BOTH so the fix is always
+ // reachable from the machine you're on. (Pre-fix, only push existed, which
+ // couldn't resolve a record the LOCAL side was behind on.)
+ const canPush = ['local-only', 'diverged', 'assets-missing'].includes(status);
+ const canPull = ['peer-only', 'diverged', 'assets-missing'].includes(status);
const [syncToPeer, syncing] = useAsyncAction(async () => {
// The endpoint returns 200 even when nothing was pushed ({ pushed:false,
@@ -151,25 +178,50 @@ function PeerRow({ entry, kind, recordId, onRefresh }) {
onRefresh();
}, { errorMessage: `Failed to sync to ${peerName}` });
+ const [pullFromPeer, pulling] = useAsyncAction(async () => {
+ const result = await pullRecordFromPeer(peerId, kind, recordId, { silent: true });
+ if (result?.pulled) {
+ const n = result?.missingAssets ?? 0;
+ toast.success(`Pulled from ${peerName}${n > 0 ? ` — fetching ${n} asset${n === 1 ? '' : 's'}` : ''}`);
+ } else {
+ const detail = result?.reason ? ` — ${PULL_SKIP_LABELS[result.reason] ?? result.reason}` : '';
+ toast.error(`Nothing pulled from ${peerName}${detail}`);
+ }
+ onRefresh();
+ }, { errorMessage: `Failed to pull from ${peerName}` });
+
return (
<div className="flex items-center justify-between gap-2 py-2 border-b border-port-border/60 last:border-0">
<div className="min-w-0">
<p className="text-sm text-white truncate">{peerName}</p>
<StatusPill status={status} />
</div>
- {needsAction && (
- <button
- type="button"
- onClick={() => syncToPeer()}
- disabled={syncing}
- className="flex-shrink-0 flex items-center gap-1 px-2 py-1 rounded text-xs bg-port-accent/20 hover:bg-port-accent/40 text-port-accent disabled:opacity-40"
- >
- {syncing
- ? <Loader2 className="w-3 h-3 animate-spin" />
- : <ArrowUpCircle className="w-3 h-3" />}
- Sync to peer
- </button>
- )}
+ <div className="flex-shrink-0 flex items-center gap-1.5">
+ {canPull && (
+ <button
+ type="button"
+ onClick={() => pullFromPeer()}
+ disabled={pulling || syncing}
+ className="flex items-center gap-1 px-2 py-1 rounded text-xs bg-port-success/15 hover:bg-port-success/30 text-port-success disabled:opacity-40"
+ title="Fetch this record + its assets from the peer (fixes when this machine is behind)"
+ >
+ {pulling ? <Loader2 className="w-3 h-3 animate-spin" /> : <Download className="w-3 h-3" />}
+ Pull from peer
+ </button>
+ )}
+ {canPush && (
+ <button
+ type="button"
+ onClick={() => syncToPeer()}
+ disabled={syncing || pulling}
+ className="flex items-center gap-1 px-2 py-1 rounded text-xs bg-port-accent/20 hover:bg-port-accent/40 text-port-accent disabled:opacity-40"
+ title="Push this record + its assets to the peer"
+ >
+ {syncing ? <Loader2 className="w-3 h-3 animate-spin" /> : <ArrowUpCircle className="w-3 h-3" />}
+ Sync to peer
+ </button>
+ )}
+ </div>
</div>
);
}
@@ -187,6 +239,10 @@ export default function SyncDetailDrawer({ kind, recordId, onClose }) {
const fetcher = KIND_FETCHER[kind] ?? null;
const [record, setRecord] = useState(null);
const [recordLoading, setRecordLoading] = useState(!!fetcher);
+ // True when the record fetch failed or timed out (distinct from "loaded but
+ // empty"). Drives an explicit error state so the drawer can never sit on a
+ // permanent "Loading…" spinner if the request hangs.
+ const [recordError, setRecordError] = useState(false);
// Drop async results that resolve after the drawer unmounts (fast route
// change / close while a fetch is in flight) to avoid setState-on-unmounted
@@ -198,28 +254,64 @@ export default function SyncDetailDrawer({ kind, recordId, onClose }) {
// that resolves afterward fails the equality check and is dropped, instead
// of overwriting the newer record with a stale name/preview.
const loadGenRef = useRef(0);
+ // Hold the in-flight load timeout so it can be cleared on unmount or on a
+ // rapid re-load — not only when the fetch settles. Without this, closing the
+ // drawer (or switching records) mid-fetch leaves the 12s timer scheduled.
+ const loadTimeoutRef = useRef(null);
+ // Last recordId we began loading — lets us clear stale metadata only when
+ // SWITCHING records (not on a same-id refresh, which should keep the current
+ // record visible while it reloads).
+ const lastRecordIdRef = useRef(null);
const loadRecord = useCallback(() => {
if (!fetcher) return;
const gen = ++loadGenRef.current; // invalidates any prior in-flight fetch
const fresh = () => mountedRef.current && gen === loadGenRef.current;
+ if (loadTimeoutRef.current) clearTimeout(loadTimeoutRef.current); // drop a prior timer on rapid re-load
+ // Switching to a DIFFERENT record: drop the old record up front so the
+ // header/preview never shows the prior record's name while the new one
+ // loads — and can't stay stuck on it if the new fetch errors/times out.
+ if (recordId !== lastRecordIdRef.current) {
+ setRecord(null);
+ lastRecordIdRef.current = recordId;
+ }
// An empty recordId (e.g. a param-less route mount) would fetch
// `/media/collections/` and 404/toast — skip the request, and clear any
// previously-loaded record so a stale name/preview can't linger.
- if (!recordId) { setRecord(null); setRecordLoading(false); return; }
+ if (!recordId) { setRecord(null); setRecordError(false); setRecordLoading(false); return; }
+ setRecordError(false);
setRecordLoading(true);
+ // Hard timeout so a hung request can never leave the drawer on a permanent
+ // "Loading…" spinner. Bumping the generation also drops a late response.
+ // Capture THIS invocation's timer locally: a later loadRecord() overwrites
+ // loadTimeoutRef.current, so clearing the ref here would kill the newer
+ // request's timeout. Clear only our own timer, and null the ref only while
+ // it still points at us (so unmount/rapid-reload cleanup stays correct).
+ const timeout = setTimeout(() => {
+ if (fresh()) { loadGenRef.current += 1; setRecordError(true); setRecordLoading(false); }
+ }, RECORD_LOAD_TIMEOUT_MS);
+ loadTimeoutRef.current = timeout;
fetcher(recordId)
- .then((data) => { if (fresh()) setRecord(data); })
- .catch(() => { if (fresh()) setRecord(null); })
- .finally(() => { if (fresh()) setRecordLoading(false); });
+ .then((data) => { if (fresh()) { setRecord(data); setRecordError(false); } })
+ .catch(() => { if (fresh()) { setRecord(null); setRecordError(true); } })
+ .finally(() => {
+ clearTimeout(timeout);
+ if (loadTimeoutRef.current === timeout) loadTimeoutRef.current = null;
+ if (fresh()) setRecordLoading(false);
+ });
}, [fetcher, recordId]);
- useEffect(() => { loadRecord(); }, [loadRecord]);
+ // Run on mount/recordId change; clear any pending load timer on unmount.
+ useEffect(() => {
+ loadRecord();
+ return () => { if (loadTimeoutRef.current) clearTimeout(loadTimeoutRef.current); };
+ }, [loadRecord]);
// Keep the mediaCollection-specific alias in scope so the pull action below
// can read it without changing its reference to `collection`.
const collection = kind === 'mediaCollection' ? record : null;
const collectionLoading = kind === 'mediaCollection' ? recordLoading : false;
+ const collectionError = kind === 'mediaCollection' ? recordError : false;
// Convenience alias so the header can show `record?.name` regardless of kind.
const recordName = record?.name ?? null;
@@ -306,7 +398,7 @@ export default function SyncDetailDrawer({ kind, recordId, onClose }) {
{kind === 'mediaCollection' && (
<section>
<h3 className="text-xs font-semibold text-gray-400 uppercase tracking-wide mb-2">Collection</h3>
- <CollectionPreview collection={collection} loading={collectionLoading} />
+ <CollectionPreview collection={collection} loading={collectionLoading} error={collectionError} />
</section>
)}
@@ -316,8 +408,8 @@ export default function SyncDetailDrawer({ kind, recordId, onClose }) {
<h3 className="text-xs font-semibold text-gray-400 uppercase tracking-wide">Peer Status</h3>
<button
type="button"
- onClick={refresh}
- title="Refresh sync status"
+ onClick={() => { refresh(); loadRecord(); }}
+ title="Refresh sync status + reload record"
className="p-1 text-gray-500 hover:text-gray-300 rounded"
>
<RefreshCw className="w-3.5 h-3.5" />
@@ -368,7 +460,7 @@ export default function SyncDetailDrawer({ kind, recordId, onClose }) {
entry={entry}
kind={kind}
recordId={recordId}
- onRefresh={refresh}
+ onRefresh={() => { refresh(); loadRecord(); }}
/>
))}
</div>
diff --git a/client/src/components/sync/SyncDetailDrawer.test.jsx b/client/src/components/sync/SyncDetailDrawer.test.jsx
index 4c6ae719a4..332798d7a0 100644
--- a/client/src/components/sync/SyncDetailDrawer.test.jsx
+++ b/client/src/components/sync/SyncDetailDrawer.test.jsx
@@ -13,6 +13,7 @@ const mockGetMediaCollection = vi.fn();
const mockGetUniverse = vi.fn();
const mockGetPipelineSeries = vi.fn();
const mockSyncRecordToPeer = vi.fn();
+const mockPullRecordFromPeer = vi.fn();
const mockPullMissingMetadata = vi.fn();
vi.mock('../../services/api', () => ({
@@ -20,6 +21,7 @@ vi.mock('../../services/api', () => ({
getUniverse: (...args) => mockGetUniverse(...args),
getPipelineSeries: (...args) => mockGetPipelineSeries(...args),
syncRecordToPeer: (...args) => mockSyncRecordToPeer(...args),
+ pullRecordFromPeer: (...args) => mockPullRecordFromPeer(...args),
pullMissingMetadata: (...args) => mockPullMissingMetadata(...args),
}));
@@ -84,6 +86,7 @@ beforeEach(() => {
mockGetUniverse.mockImplementation(pendingPromise);
mockGetPipelineSeries.mockImplementation(pendingPromise);
mockSyncRecordToPeer.mockResolvedValue({ pushed: true });
+ mockPullRecordFromPeer.mockResolvedValue({ pulled: true, missingAssets: 0 });
mockPullMissingMetadata.mockResolvedValue({ recovered: 2, attempted: 2 });
});
@@ -100,6 +103,29 @@ describe('SyncDetailDrawer', () => {
expect(mockGetMediaCollection).not.toHaveBeenCalled();
});
+ it('shows ONLY "Pull from peer" for a peer-only record and calls pullRecordFromPeer', async () => {
+ mockUseSyncIntegrity.mockReturnValue(defaultHookState({
+ byPeer: buildByPeer([{ peerId: 'peer-a', peerName: 'void', status: 'peer-only' }]),
+ }));
+ render(<SyncDetailDrawer kind="mediaCollection" recordId={RECORD_ID} onClose={() => {}} />);
+ expect(screen.queryByRole('button', { name: /sync to peer/i })).not.toBeInTheDocument();
+ const pullBtn = screen.getByRole('button', { name: /pull from peer/i });
+ fireEvent.click(pullBtn);
+ await waitFor(() => expect(mockPullRecordFromPeer).toHaveBeenCalledWith(
+ 'peer-a', 'mediaCollection', RECORD_ID, { silent: true },
+ ));
+ await waitFor(() => expect(mockRefresh).toHaveBeenCalled());
+ });
+
+ it('offers BOTH pull and push for an assets-missing record (ambiguous direction)', async () => {
+ mockUseSyncIntegrity.mockReturnValue(defaultHookState({
+ byPeer: buildByPeer([{ peerId: 'peer-a', peerName: 'void', status: 'assets-missing' }]),
+ }));
+ render(<SyncDetailDrawer kind="universe" recordId={RECORD_ID} onClose={() => {}} />);
+ expect(screen.getByRole('button', { name: /pull from peer/i })).toBeInTheDocument();
+ expect(screen.getByRole('button', { name: /sync to peer/i })).toBeInTheDocument();
+ });
+
it('drops a stale in-flight fetch when recordId changes mid-flight (latest wins)', async () => {
let resolveFirst;
mockGetMediaCollection
@@ -116,6 +142,20 @@ describe('SyncDetailDrawer', () => {
expect(screen.getAllByText('Beta Collection').length).toBeGreaterThan(0);
});
+ it('clears the prior record while switching to a different recordId (no stale metadata)', async () => {
+ let resolveB;
+ mockGetMediaCollection
+ .mockImplementationOnce(() => Promise.resolve({ id: 'col-A', name: 'Alpha Collection', items: [] }))
+ .mockImplementationOnce(() => new Promise((r) => { resolveB = () => r({ id: 'col-B', name: 'Beta Collection', items: [] }); }));
+ const { rerender } = render(<SyncDetailDrawer kind="mediaCollection" recordId="col-A" onClose={() => {}} />);
+ await waitFor(() => expect(screen.getAllByText('Alpha Collection').length).toBeGreaterThan(0));
+ // Switch to col-B (still loading) — Alpha must clear immediately, not linger.
+ rerender(<SyncDetailDrawer kind="mediaCollection" recordId="col-B" onClose={() => {}} />);
+ await waitFor(() => expect(screen.queryAllByText('Alpha Collection')).toHaveLength(0));
+ resolveB();
+ await waitFor(() => expect(screen.getAllByText('Beta Collection').length).toBeGreaterThan(0));
+ });
+
it('clears a previously-loaded record when recordId becomes empty (no stale name/preview)', async () => {
mockGetMediaCollection.mockResolvedValue(COLLECTION_DATA);
const { rerender } = render(<SyncDetailDrawer kind="mediaCollection" recordId={RECORD_ID} onClose={() => {}} />);
@@ -192,6 +232,45 @@ describe('SyncDetailDrawer', () => {
expect(thumbs.length).toBeGreaterThan(0);
});
+ it('shows an error state (not a stuck spinner) when the collection fetch rejects', async () => {
+ mockGetMediaCollection.mockRejectedValue(new Error('boom'));
+ render(<SyncDetailDrawer kind="mediaCollection" recordId={RECORD_ID} onClose={() => {}} />);
+ await waitFor(() => expect(screen.getByText(/couldn.t load this collection/i)).toBeInTheDocument());
+ });
+
+ it('times out a hung collection fetch into an error state (no permanent Loading…)', async () => {
+ vi.useFakeTimers();
+ try {
+ mockGetMediaCollection.mockImplementation(() => new Promise(() => {})); // never settles
+ render(<SyncDetailDrawer kind="mediaCollection" recordId={RECORD_ID} onClose={() => {}} />);
+ await vi.advanceTimersByTimeAsync(12001);
+ expect(screen.getByText(/couldn.t load this collection/i)).toBeInTheDocument();
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('keeps the latest load timeout armed when an earlier fetch settles after a re-load (no stuck Loading…)', async () => {
+ vi.useFakeTimers();
+ try {
+ let resolveA;
+ mockGetMediaCollection
+ .mockImplementationOnce(() => new Promise((r) => { resolveA = () => r({ id: 'col-A', name: 'Alpha Collection', items: [] }); }))
+ .mockImplementationOnce(() => new Promise(() => {})); // col-B hangs forever
+ const { rerender } = render(<SyncDetailDrawer kind="mediaCollection" recordId="col-A" onClose={() => {}} />);
+ // Switch to col-B (its fetch hangs) before col-A settles.
+ rerender(<SyncDetailDrawer kind="mediaCollection" recordId="col-B" onClose={() => {}} />);
+ // Now the stale col-A fetch settles — its cleanup must clear ONLY its own
+ // timer, NOT col-B's. If it cleared the ref blindly, col-B's hard timeout
+ // would be disabled and the drawer would hang on "Loading…" forever.
+ resolveA();
+ await vi.advanceTimersByTimeAsync(12001);
+ expect(screen.getByText(/couldn.t load this collection/i)).toBeInTheDocument();
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
it('calls pullMissingMetadata and refresh when "Pull missing metadata" is clicked', async () => {
mockGetMediaCollection.mockResolvedValue(COLLECTION_DATA);
render(<SyncDetailDrawer kind="mediaCollection" recordId={RECORD_ID} onClose={() => {}} />);
diff --git a/client/src/pages/Instances.jsx b/client/src/pages/Instances.jsx
index 0ace64677e..572d59135f 100644
--- a/client/src/pages/Instances.jsx
+++ b/client/src/pages/Instances.jsx
@@ -14,7 +14,7 @@ import socket from '../services/socket';
import {
getInstances, updateSelfInstance, addPeer, updatePeer,
removePeer, connectPeer, probePeer, getTailnetInfo, provisionTailnetCert,
- listPeerSubscriptions, unsubscribeFromPeer,
+ listPeerSubscriptions,
getTombstoneSweepStatus, sweepTombstonesNow,
} from '../services/api';
import PeerAppsList from '../components/instances/PeerAppsList';
@@ -515,7 +515,7 @@ function SyncCategoriesPanel({ peer, onRefresh }) {
);
}
-function SnapshotSyncBadge({ label, icon: Icon, cursorChecksum, remoteChecksum, livePushCovered }) {
+function SnapshotSyncBadge({ label, icon: Icon, cursorChecksum, remoteChecksum, livePushCovered, subsLoaded = true }) {
// `livePushCovered` is true when this peer has at least one per-record
// peer-sync subscription for a record kind that maps to this category
// (universe-subs → 'universe', series-subs → 'pipeline'). The orchestrator
@@ -525,7 +525,10 @@ function SnapshotSyncBadge({ label, icon: Icon, cursorChecksum, remoteChecksum,
// would always read "behind" even when the records are actually converged.
// Render a distinct "live-push" state instead so the badge stops lying.
const synced = cursorChecksum && remoteChecksum && cursorChecksum === remoteChecksum;
- const behind = cursorChecksum && remoteChecksum && cursorChecksum !== remoteChecksum;
+ // Suppress "behind" until peer subs have loaded — `livePushCovered` is derived
+ // from them, so before they resolve a live-push category would briefly mislabel
+ // itself "behind". Until then it falls through to the neutral "pending" state.
+ const behind = subsLoaded && cursorChecksum && remoteChecksum && cursorChecksum !== remoteChecksum;
return (
<div className="flex items-center gap-1.5 text-xs">
@@ -558,82 +561,7 @@ function SnapshotSyncBadge({ label, icon: Icon, cursorChecksum, remoteChecksum,
);
}
-/**
- * Per-record peer-sync subscriptions to / from this peer.
- *
- * Shows what universes and series are being live-pushed to the peer (outgoing
- * subscriptions we created via SyncToPeerButton) plus what they auto-subscribed
- * back from us (`adoptedFromReverse`). Each row carries an unsubscribe control
- * so the user can tear down a sync mistake without leaving the page.
- *
- * Inbound-only peers (configured with directions=['inbound'] in the peer
- * record) never get reverse subscriptions auto-created — see
- * services/sharing/peerSync.js `maybeCreateReverseSubscription`.
- */
-function PeerSyncSubscriptionsSection({ peer, peerSubs, peerSubsLoaded, setPeerSubs }) {
- const [busyId, setBusyId] = useState(null);
-
- if (!peer.instanceId) return null;
- if (!peerSubsLoaded) return null;
- if (peerSubs.length === 0) return null;
-
- const handleUnsubscribe = async (sub) => {
- setBusyId(sub.id);
- // silent:true — own toast in the catch, so suppress the apiCore default.
- const ok = await unsubscribeFromPeer(sub.id, { silent: true }).catch((err) => {
- toast.error(err.message || 'Unsubscribe failed');
- return null;
- });
- if (ok) {
- setPeerSubs((prev) => prev.filter((s) => s.id !== sub.id));
- toast.success(`Stopped syncing ${sub.recordKind} ${sub.recordId.slice(0, 8)} with ${peer.name}`);
- }
- setBusyId(null);
- };
-
- const universeSubs = peerSubs.filter((s) => s.recordKind === 'universe');
- const seriesSubs = peerSubs.filter((s) => s.recordKind === 'series');
-
- return (
- <div className="mt-2 pt-2 border-t border-port-border/50">
- <div className="flex items-center gap-1.5 mb-1.5">
- <ArrowLeftRight size={12} className="text-gray-500" />
- <span className="text-[10px] text-gray-500 uppercase tracking-wider font-medium">
- Live-pushed records ({peerSubs.length})
- </span>
- </div>
- <div className="space-y-1">
- {[...universeSubs, ...seriesSubs].map((sub) => (
- <div
- key={sub.id}
- className="flex items-center gap-2 text-[11px] text-gray-300 group"
- >
- <span className="text-gray-500 font-mono">{sub.recordKind}</span>
- <span className="text-gray-400 font-mono truncate flex-1" title={sub.recordId}>
- {sub.recordId.slice(0, 12)}…
- </span>
- {sub.adoptedFromReverse ? (
- <span className="text-[9px] text-port-accent/70" title="Auto-created when this peer pushed us first">
- ↩ reverse
- </span>
- ) : null}
- <button
- type="button"
- onClick={() => handleUnsubscribe(sub)}
- disabled={busyId === sub.id}
- className="text-gray-600 hover:text-port-error disabled:opacity-40"
- title="Stop syncing"
- >
- <X size={12} />
- </button>
- </div>
- ))}
- </div>
- </div>
- );
-}
-
-function SyncStatusSection({ peer, syncStatus, peerSubs = [] }) {
+function SyncStatusSection({ peer, syncStatus, peerSubs = [], peerSubsLoaded = true }) {
if (!syncStatus || !peer.instanceId) return null;
const cursor = syncStatus.cursors?.[peer.instanceId];
@@ -709,6 +637,7 @@ function SyncStatusSection({ peer, syncStatus, peerSubs = [] }) {
cursorChecksum={cursorChecksums[cat]}
remoteChecksum={remoteChecksums[cat]}
livePushCovered={livePushCovered.has(cat)}
+ subsLoaded={peerSubsLoaded}
/>
);
})}
@@ -827,23 +756,29 @@ function PeerCard({ peer, onRefresh, syncStatus, tailnetInfo }) {
const [probing, setProbing] = useState(false);
const [connecting, setConnecting] = useState(false);
const [confirmRemove, setConfirmRemove] = useState(false);
- // Peer subs are loaded once at this level and shared with both
- // PeerSyncSubscriptionsSection (renders the per-record list) and
- // SyncStatusSection (uses the sub set to decide which snapshot badges
- // should render as "live-push" instead of misleading "behind"). Without
- // sharing, every card would issue two identical /sharing/peer-subs
- // fetches.
+ // Peer subs are loaded once at this level and shared with SchemaGapBadge and
+ // SyncStatusSection (which uses the sub set to decide which snapshot badges
+ // render as "live-push" instead of a misleading "behind"). Without sharing,
+ // every card would issue duplicate /sharing/peer-subs fetches. (The verbose
+ // per-record "Live-pushed records" list that used to render these was removed
+ // — it grew unbounded and the Sync Details drawer covers per-record status.)
const [peerSubs, setPeerSubs] = useState([]);
+ // Track whether the first subs fetch has settled — until it has, `peerSubs`
+ // is [] and SyncStatusSection can't tell a live-push category from a behind
+ // one, so it would flash "behind". Gates the snapshot badges' "behind" state.
const [peerSubsLoaded, setPeerSubsLoaded] = useState(false);
useEffect(() => {
if (!peer.instanceId) {
setPeerSubs([]);
- setPeerSubsLoaded(true);
+ setPeerSubsLoaded(true); // no instanceId → nothing to load; don't suppress forever
return;
}
- let cancelled = false;
+ // instanceId just became available or changed — re-suppress "behind" until
+ // this peer's first fetch settles, otherwise the stale [] would mislabel a
+ // live-push category. Cleared in the .finally() below.
setPeerSubsLoaded(false);
+ let cancelled = false;
const refetch = () => listPeerSubscriptions({ peerId: peer.instanceId }, { silent: true })
.then((r) => {
if (!cancelled) setPeerSubs(r?.subscriptions || []);
@@ -1014,9 +949,7 @@ function PeerCard({ peer, onRefresh, syncStatus, tailnetInfo }) {
<SyncCategoriesPanel peer={peer} onRefresh={onRefresh} />
- <SyncStatusSection peer={peer} syncStatus={syncStatus} peerSubs={peerSubs} />
-
- <PeerSyncSubscriptionsSection peer={peer} peerSubs={peerSubs} peerSubsLoaded={peerSubsLoaded} setPeerSubs={setPeerSubs} />
+ <SyncStatusSection peer={peer} syncStatus={syncStatus} peerSubs={peerSubs} peerSubsLoaded={peerSubsLoaded} />
<PeerAppsList apps={peer.lastApps} peerAddress={peer.address} peerHost={peer.host} />
{peer.status === 'online' && (
diff --git a/client/src/services/apiPeerSync.js b/client/src/services/apiPeerSync.js
index 75fe66b0e0..151b0a1231 100644
--- a/client/src/services/apiPeerSync.js
+++ b/client/src/services/apiPeerSync.js
@@ -81,6 +81,18 @@ export const syncRecordToPeer = (peerId, recordKind, recordId, options = {}) =>
...options,
});
+/**
+ * Receiver-initiated PULL of a record (+ its assets) FROM a peer — the mirror of
+ * syncRecordToPeer, for when the LOCAL machine is the one behind. Returns
+ * `{ pulled, reason?, missingAssets? }`.
+ */
+export const pullRecordFromPeer = (peerId, recordKind, recordId, options = {}) =>
+ request('/peer-sync/pull-record', {
+ method: 'POST',
+ body: JSON.stringify({ peerId, recordKind, recordId }),
+ ...options,
+ });
+
/**
* Trigger a full sync-now for all subscribed records to a peer.
* Same silent-capable pattern as `syncRecordToPeer`.
diff --git a/client/src/services/apiPeerSync.test.js b/client/src/services/apiPeerSync.test.js
index 06891ce09c..c70356b9c6 100644
--- a/client/src/services/apiPeerSync.test.js
+++ b/client/src/services/apiPeerSync.test.js
@@ -10,6 +10,7 @@ let fetchSyncIntegrity;
let syncRecordToPeer;
let syncNowForPeer;
let pullMissingMetadata;
+let pullRecordFromPeer;
beforeEach(async () => {
vi.resetModules();
@@ -19,6 +20,7 @@ beforeEach(async () => {
syncRecordToPeer,
syncNowForPeer,
pullMissingMetadata,
+ pullRecordFromPeer,
} = await import('./apiPeerSync.js'));
request.mockReset();
request.mockResolvedValue({ ok: true });
@@ -81,6 +83,17 @@ describe('syncNowForPeer', () => {
});
});
+describe('pullRecordFromPeer', () => {
+ it('POSTs /peer-sync/pull-record with the record tuple', async () => {
+ await pullRecordFromPeer('peer-a', 'mediaCollection', 'uc-7', { silent: true });
+ expect(request).toHaveBeenCalledWith('/peer-sync/pull-record', {
+ method: 'POST',
+ body: JSON.stringify({ peerId: 'peer-a', recordKind: 'mediaCollection', recordId: 'uc-7' }),
+ silent: true,
+ });
+ });
+});
+
describe('pullMissingMetadata', () => {
it('calls POST /peer-sync/pull-metadata with filenames array', async () => {
await pullMissingMetadata(['a.json', 'b.json']);
diff --git a/scripts/migrations/038-canonicalize-linked-collection-ids.js b/scripts/migrations/038-canonicalize-linked-collection-ids.js
new file mode 100644
index 0000000000..612cc31297
--- /dev/null
+++ b/scripts/migrations/038-canonicalize-linked-collection-ids.js
@@ -0,0 +1,231 @@
+/**
+ * Canonicalize universe/series-LINKED media-collection ids to a deterministic
+ * scheme so federated peers converge instead of duplicating.
+ *
+ * Before this migration every machine minted a random UUID for its
+ * "Universe: X" / "Series: Y" collection via `findOrCreateUniverseCollection`
+ * (et al). Because per-record collection sync keys on `id`, two machines'
+ * copies of the SAME universe's collection had different ids — so integrity
+ * reported both as "local only" and the merge created a duplicate on every
+ * peer instead of reconciling.
+ *
+ * The live code now derives the id from the owner: `uc-<universeId>` /
+ * `sc-<seriesId>` (see `linkedCollectionId` in services/mediaCollections.js —
+ * KEEP THIS IN SYNC with that helper). This migration rewrites existing
+ * linked-collection ids to that scheme on each machine independently; once both
+ * have run, the same universe's collection carries the same id everywhere and
+ * the next sync cycle merges (union of items) instead of duplicating.
+ *
+ * If a machine already accumulated duplicates (e.g. it received a peer's
+ * differently-id'd copy before this shipped), every collection for the same
+ * owner collapses to the one canonical id, unioning their items — that's the
+ * "clean up duplicates" step.
+ *
+ * Tombstones are left untouched: `deleteCollection` nulls universeId/seriesId,
+ * so a deleted collection has no owner link to canonicalize; its old-id
+ * tombstone simply propagates as a delete for an id no live record uses and is
+ * pruned by tombstone GC.
+ *
+ * Also rewrites any `mediaCollection` peer subscriptions whose `recordId` was an
+ * old collection id (regenerating the derived subscription id and de-duping).
+ *
+ * Idempotent: a second run finds every linked id already canonical → no-op.
+ */
+
+import { mkdir, readFile, writeFile, rename, stat } from 'fs/promises';
+import { join } from 'path';
+
+// Inlined copies of services/mediaCollections.js — migrations stay
+// dependency-light (importing the service would pull its whole module graph +
+// side effects). Keep these identical to that module: UNIVERSE_ID_MAX /
+// SERIES_ID_MAX bound the owner id, and `findOrCreateUniverseCollection` slices
+// the owner id to that cap BEFORE deriving the deterministic id and before
+// storing it. The migration must slice the same way, or an overlong/hand-edited
+// owner id would yield a canonical id (and a stored universeId) that disagrees
+// with what the live service computes — the runtime couldn't re-find the row and
+// would mint a duplicate.
+const UNIVERSE_ID_MAX = 80;
+const SERIES_ID_MAX = 80;
+const linkedIdFor = (c) => {
+ if (c.universeId) return `uc-${String(c.universeId).slice(0, UNIVERSE_ID_MAX)}`;
+ if (c.seriesId) return `sc-${String(c.seriesId).slice(0, SERIES_ID_MAX)}`;
+ return null;
+};
+
+const itemKey = (it) => `${it?.kind}:${it?.ref}`;
+// Null-based timestamp parse (mirrors mediaCollections.js#parseTsMs): an
+// unparseable value returns null and LOSES every comparison, so a corrupted
+// timestamp can't win "earliest" or "newest". A -Infinity fallback would make
+// a bad timestamp win the earliest-wins comparisons below.
+const parseTsMs = (s) => { const n = typeof s === 'string' ? Date.parse(s) : NaN; return Number.isFinite(n) ? n : null; };
+// "Earliest wins": -1 if a is earlier (a wins), 1 if b is earlier, 0 on tie.
+// Unparseable side loses; both unparseable → tie (caller's incumbent wins).
+const compareEarlierWins = (a, b) => {
+ const aMs = parseTsMs(a); const bMs = parseTsMs(b);
+ if (aMs === null && bMs === null) return 0;
+ if (aMs === null) return 1;
+ if (bMs === null) return -1;
+ return aMs < bMs ? -1 : aMs > bMs ? 1 : 0;
+};
+// "Newer wins": true iff candidate is strictly newer than incumbent. Unparseable
+// candidate never overrides; unparseable incumbent loses to a valid candidate.
+const compareNewerWins = (candidate, incumbent) => {
+ const cMs = parseTsMs(candidate); const iMs = parseTsMs(incumbent);
+ if (cMs === null) return false;
+ if (iMs === null) return true;
+ return cMs > iMs;
+};
+
+// Union two collections' items: dedupe by kind:ref, keep the earliest addedAt
+// (a replay shouldn't bump an item's age). Mirrors mergeCollectionItems —
+// including the final sort by itemKey, so two installs with the same item set
+// persist the same order (else snapshot checksums churn until the next merge).
+const unionItems = (a = [], b = []) => {
+ const byKey = new Map();
+ for (const it of [...(a || []), ...(b || [])]) {
+ if (!it || typeof it.ref !== 'string') continue;
+ const k = itemKey(it);
+ const prev = byKey.get(k);
+ if (!prev) { byKey.set(k, it); continue; }
+ if (compareEarlierWins(it.addedAt, prev.addedAt) < 0) byKey.set(k, it);
+ }
+ return [...byKey.values()].sort((x, y) => itemKey(x).localeCompare(itemKey(y)));
+};
+
+/**
+ * Pure transform. Returns `{ collections, idMap, merged, renamed }`.
+ * - idMap: oldId -> newId for every rewritten linked collection.
+ * - merged: count of collections folded into an existing canonical id.
+ * - renamed: count of collections whose id changed (incl. merged).
+ */
+export function canonicalizeCollections(input) {
+ const list = Array.isArray(input) ? input : [];
+ const idMap = {};
+ let merged = 0;
+ let renamed = 0;
+
+ // Tombstones + standalone (no owner link) pass through unchanged.
+ const passthrough = [];
+ // Canonical-id -> merged live record.
+ const byCanon = new Map();
+
+ for (const raw of list) {
+ if (!raw || typeof raw !== 'object') continue;
+ // Slice owner ids to the runtime cap up front so the derived id, the stored
+ // universeId/seriesId, and the merge below all key on the same value the
+ // live service would compute. idMap stays keyed on the original `raw.id`.
+ const c = {
+ ...raw,
+ ...(typeof raw.universeId === 'string' ? { universeId: raw.universeId.slice(0, UNIVERSE_ID_MAX) } : {}),
+ ...(typeof raw.seriesId === 'string' ? { seriesId: raw.seriesId.slice(0, SERIES_ID_MAX) } : {}),
+ };
+ const canon = c.deleted === true ? null : linkedIdFor(c);
+ if (!canon) { passthrough.push(raw); continue; }
+ if (raw.id !== canon) { idMap[raw.id] = canon; renamed += 1; }
+ const existing = byCanon.get(canon);
+ if (!existing) {
+ byCanon.set(canon, { ...c, id: canon });
+ continue;
+ }
+ // Two records collapse to the same canonical id → merge (LWW scalars on the
+ // newer updatedAt; union items; earliest createdAt wins).
+ merged += 1;
+ const remoteWins = compareNewerWins(c.updatedAt, existing.updatedAt);
+ const scalar = remoteWins ? c : existing;
+ const items = unionItems(existing.items, c.items);
+ const presentKeys = new Set(items.map(itemKey));
+ byCanon.set(canon, {
+ ...existing,
+ id: canon,
+ name: scalar.name,
+ description: scalar.description,
+ coverKey: scalar.coverKey && presentKeys.has(scalar.coverKey) ? scalar.coverKey : null,
+ universeId: scalar.universeId ?? existing.universeId ?? null,
+ seriesId: scalar.seriesId ?? existing.seriesId ?? null,
+ items,
+ // Earliest createdAt wins; existing (incumbent) wins ties + unparseable.
+ createdAt: compareEarlierWins(c.createdAt, existing.createdAt) < 0 ? c.createdAt : existing.createdAt,
+ updatedAt: remoteWins ? c.updatedAt : existing.updatedAt,
+ });
+ }
+
+ return { collections: [...passthrough, ...byCanon.values()], idMap, merged, renamed };
+}
+
+/**
+ * Rewrite mediaCollection subscription recordIds via `idMap`, regenerating the
+ * derived subscription id (`peer-mediaCollection-<recordId>-<peerId>`) and
+ * de-duping collisions (keep the most-recently-pushed). Returns the new array.
+ */
+export function rewriteSubscriptions(subs, idMap) {
+ const list = Array.isArray(subs) ? subs : [];
+ const seen = new Map();
+ for (const s of list) {
+ if (!s || typeof s !== 'object') { continue; }
+ let next = s;
+ if (s.recordKind === 'mediaCollection' && idMap[s.recordId]) {
+ const recordId = idMap[s.recordId];
+ next = { ...s, recordId, id: `peer-mediaCollection-${recordId}-${s.peerId}` };
+ }
+ const existing = seen.get(next.id);
+ if (!existing) { seen.set(next.id, next); continue; }
+ // Collision after rewrite — keep whichever was pushed most recently
+ // (unparseable lastPushedAt loses; incumbent wins ties).
+ if (compareNewerWins(next.lastPushedAt, existing.lastPushedAt)) seen.set(next.id, next);
+ }
+ return [...seen.values()];
+}
+
+const fileExists = (p) => stat(p).then(() => true, (e) => { if (e.code === 'ENOENT') return false; throw e; });
+const readJson = async (p, fallback) => {
+ const raw = await readFile(p, 'utf-8').catch((e) => { if (e.code === 'ENOENT') return null; throw e; });
+ if (raw == null) return fallback;
+ try { return JSON.parse(raw); } catch { return fallback; }
+};
+const writeJsonAtomic = async (p, value) => {
+ const tmp = `${p}.tmp-038`;
+ await writeFile(tmp, JSON.stringify(value, null, 2) + '\n');
+ await rename(tmp, p);
+};
+
+export default {
+ async up({ rootDir }) {
+ const dataDir = join(rootDir, 'data');
+ const collectionsPath = join(dataDir, 'media-collections.json');
+ const subsPath = join(dataDir, 'sharing', 'peer_subscriptions.json');
+
+ if (!(await fileExists(collectionsPath))) {
+ console.log('📦 migration 038: no media-collections.json — fresh install, no-op');
+ return { ok: true, reason: 'no-collections' };
+ }
+
+ const doc = await readJson(collectionsPath, { collections: [] });
+ if (!doc || !Array.isArray(doc.collections)) {
+ console.log('📦 migration 038: media-collections.json has no collections array — no-op');
+ return { ok: true, reason: 'empty' };
+ }
+
+ const { collections, idMap, merged, renamed } = canonicalizeCollections(doc.collections);
+ if (renamed === 0) {
+ console.log('📦 migration 038: all linked-collection ids already canonical — no-op');
+ return { ok: true, reason: 'already-canonical' };
+ }
+
+ await mkdir(dataDir, { recursive: true });
+ await writeJsonAtomic(collectionsPath, { ...doc, collections });
+
+ let subsDeduped = 0;
+ if (await fileExists(subsPath)) {
+ const subsDoc = await readJson(subsPath, { subscriptions: [] });
+ if (subsDoc && Array.isArray(subsDoc.subscriptions)) {
+ const before = subsDoc.subscriptions.length;
+ const next = rewriteSubscriptions(subsDoc.subscriptions, idMap);
+ subsDeduped = before - next.length; // subscriptions collapsed by id-rewrite dedupe
+ await writeJsonAtomic(subsPath, { ...subsDoc, subscriptions: next });
+ }
+ }
+
+ console.log(`📦 migration 038: canonicalized ${renamed} linked-collection id(s), merged ${merged} duplicate(s), deduped ${subsDeduped} mediaCollection subscription(s)`);
+ return { ok: true, reason: 'migrated', renamed, merged, subsDeduped };
+ },
+};
diff --git a/scripts/migrations/038-canonicalize-linked-collection-ids.test.js b/scripts/migrations/038-canonicalize-linked-collection-ids.test.js
new file mode 100644
index 0000000000..3b14dc776f
--- /dev/null
+++ b/scripts/migrations/038-canonicalize-linked-collection-ids.test.js
@@ -0,0 +1,182 @@
+import { describe, it, expect, beforeEach, afterEach } from 'vitest';
+import { mkdtempSync, rmSync, mkdirSync, writeFileSync, readFileSync, existsSync } from 'fs';
+import { tmpdir } from 'os';
+import { join } from 'path';
+
+import migration, { canonicalizeCollections, rewriteSubscriptions } from './038-canonicalize-linked-collection-ids.js';
+
+const readJson = (p) => JSON.parse(readFileSync(p, 'utf-8'));
+const writeJson = (p, v) => writeFileSync(p, JSON.stringify(v, null, 2) + '\n');
+
+describe('canonicalizeCollections', () => {
+ it('rewrites a universe-linked collection id to uc-<universeId>', () => {
+ const { collections, idMap, renamed, merged } = canonicalizeCollections([
+ { id: 'rand-1', name: 'Universe: A', universeId: 'u1', items: [], updatedAt: '2026-05-01T00:00:00Z' },
+ ]);
+ expect(collections[0].id).toBe('uc-u1');
+ expect(idMap).toEqual({ 'rand-1': 'uc-u1' });
+ expect(renamed).toBe(1);
+ expect(merged).toBe(0);
+ });
+
+ it('rewrites a series-linked collection id to sc-<seriesId>', () => {
+ const { collections } = canonicalizeCollections([
+ { id: 'rand-2', name: 'Series: B', seriesId: 's1', items: [], updatedAt: '2026-05-01T00:00:00Z' },
+ ]);
+ expect(collections[0].id).toBe('sc-s1');
+ });
+
+ it('merges two collections for the same universe (the duplicate cleanup) — union items, newer scalars win', () => {
+ const { collections, merged, renamed } = canonicalizeCollections([
+ { id: 'local', name: 'Universe: A (old)', universeId: 'u1', updatedAt: '2026-05-01T00:00:00Z',
+ createdAt: '2026-04-01T00:00:00Z',
+ items: [{ kind: 'image', ref: 'a.png', addedAt: '2026-04-01T00:00:00Z' }] },
+ { id: 'from-peer', name: 'Universe: A (new)', universeId: 'u1', updatedAt: '2026-05-10T00:00:00Z',
+ createdAt: '2026-04-15T00:00:00Z',
+ items: [{ kind: 'image', ref: 'b.png', addedAt: '2026-04-15T00:00:00Z' }] },
+ ]);
+ expect(collections).toHaveLength(1);
+ const c = collections[0];
+ expect(c.id).toBe('uc-u1');
+ expect(c.name).toBe('Universe: A (new)'); // newer updatedAt wins scalars
+ expect(c.createdAt).toBe('2026-04-01T00:00:00Z'); // earliest createdAt
+ expect(c.items.map((i) => i.ref).sort()).toEqual(['a.png', 'b.png']); // union
+ expect(merged).toBe(1);
+ expect(renamed).toBe(2);
+ });
+
+ it('merge: a corrupted addedAt loses "earliest wins" (valid timestamp is preserved)', () => {
+ const { collections } = canonicalizeCollections([
+ { id: 'a', name: 'U', universeId: 'u1', updatedAt: '2026-05-01T00:00:00Z',
+ items: [{ kind: 'image', ref: 'x.png', addedAt: 'not-a-date' }] },
+ { id: 'b', name: 'U', universeId: 'u1', updatedAt: '2026-05-02T00:00:00Z',
+ items: [{ kind: 'image', ref: 'x.png', addedAt: '2026-04-01T00:00:00Z' }] },
+ ]);
+ const item = collections[0].items.find((i) => i.ref === 'x.png');
+ expect(item.addedAt).toBe('2026-04-01T00:00:00Z'); // valid beats unparseable, not -Infinity
+ });
+
+ it('merge: unioned items are sorted by itemKey (deterministic, matches runtime → no checksum churn)', () => {
+ const { collections } = canonicalizeCollections([
+ { id: 'a', name: 'U', universeId: 'u1', updatedAt: '2026-05-01T00:00:00Z',
+ items: [{ kind: 'video', ref: 'z.mp4' }, { kind: 'image', ref: 'm.png' }] },
+ { id: 'b', name: 'U', universeId: 'u1', updatedAt: '2026-05-02T00:00:00Z',
+ items: [{ kind: 'image', ref: 'a.png' }] },
+ ]);
+ const keys = collections[0].items.map((i) => `${i.kind}:${i.ref}`);
+ expect(keys).toEqual([...keys].sort((x, y) => x.localeCompare(y)));
+ expect(keys).toEqual(['image:a.png', 'image:m.png', 'video:z.mp4']);
+ });
+
+ it('leaves standalone (unlinked) collections untouched', () => {
+ const { collections, renamed } = canonicalizeCollections([
+ { id: 'standalone-uuid', name: 'My Bucket', universeId: null, seriesId: null, items: [] },
+ ]);
+ expect(collections[0].id).toBe('standalone-uuid');
+ expect(renamed).toBe(0);
+ });
+
+ it('leaves tombstones untouched (deleted records have no owner link)', () => {
+ const { collections, renamed } = canonicalizeCollections([
+ { id: 'gone-uuid', name: 'Universe: Dead', universeId: null, seriesId: null, deleted: true, items: [] },
+ ]);
+ expect(collections[0].id).toBe('gone-uuid');
+ expect(renamed).toBe(0);
+ });
+
+ it('is idempotent — already-canonical ids are not renamed', () => {
+ const { renamed } = canonicalizeCollections([
+ { id: 'uc-u1', name: 'Universe: A', universeId: 'u1', items: [] },
+ { id: 'sc-s1', name: 'Series: B', seriesId: 's1', items: [] },
+ ]);
+ expect(renamed).toBe(0);
+ });
+
+ it('slices an overlong owner id to the runtime cap for both the id and the stored field', () => {
+ const longId = 'u'.repeat(120); // > UNIVERSE_ID_MAX (80)
+ const sliced = longId.slice(0, 80);
+ const { collections } = canonicalizeCollections([
+ { id: 'rand-long', name: 'Universe: Long', universeId: longId, items: [], updatedAt: '2026-05-01T00:00:00Z' },
+ ]);
+ // Matches what findOrCreateUniverseCollection would compute (it slices first).
+ expect(collections[0].id).toBe(`uc-${sliced}`);
+ expect(collections[0].universeId).toBe(sliced);
+ });
+});
+
+describe('rewriteSubscriptions', () => {
+ it('rewrites recordId + regenerates the derived id for mediaCollection subs', () => {
+ const out = rewriteSubscriptions(
+ [{ id: 'peer-mediaCollection-rand-1-peerA', peerId: 'peerA', recordKind: 'mediaCollection', recordId: 'rand-1' }],
+ { 'rand-1': 'uc-u1' },
+ );
+ expect(out).toEqual([
+ { id: 'peer-mediaCollection-uc-u1-peerA', peerId: 'peerA', recordKind: 'mediaCollection', recordId: 'uc-u1' },
+ ]);
+ });
+
+ it('leaves non-mediaCollection subs and unmapped ids untouched', () => {
+ const subs = [
+ { id: 'peer-universe-u1-peerA', peerId: 'peerA', recordKind: 'universe', recordId: 'u1' },
+ { id: 'peer-mediaCollection-keepme-peerA', peerId: 'peerA', recordKind: 'mediaCollection', recordId: 'keepme' },
+ ];
+ expect(rewriteSubscriptions(subs, { 'rand-1': 'uc-u1' })).toEqual(subs);
+ });
+
+ it('de-dupes subs that collide after rewrite (keeps most-recently-pushed)', () => {
+ const out = rewriteSubscriptions(
+ [
+ { id: 'peer-mediaCollection-rand-1-peerA', peerId: 'peerA', recordKind: 'mediaCollection', recordId: 'rand-1', lastPushedAt: '2026-05-01T00:00:00Z' },
+ { id: 'peer-mediaCollection-uc-u1-peerA', peerId: 'peerA', recordKind: 'mediaCollection', recordId: 'uc-u1', lastPushedAt: '2026-05-09T00:00:00Z' },
+ ],
+ { 'rand-1': 'uc-u1' },
+ );
+ expect(out).toHaveLength(1);
+ expect(out[0].lastPushedAt).toBe('2026-05-09T00:00:00Z');
+ });
+});
+
+describe('migration 038 — up()', () => {
+ let rootDir;
+ let dataDir;
+ let collectionsPath;
+ let subsPath;
+
+ beforeEach(() => {
+ rootDir = mkdtempSync(join(tmpdir(), 'migration-038-'));
+ dataDir = join(rootDir, 'data');
+ mkdirSync(join(dataDir, 'sharing'), { recursive: true });
+ collectionsPath = join(dataDir, 'media-collections.json');
+ subsPath = join(dataDir, 'sharing', 'peer_subscriptions.json');
+ });
+
+ afterEach(() => rmSync(rootDir, { recursive: true, force: true }));
+
+ it('canonicalizes ids on disk and rewrites subscriptions, idempotently', async () => {
+ writeJson(collectionsPath, { collections: [
+ { id: 'rand-1', name: 'Universe: A', universeId: 'u1', items: [], updatedAt: '2026-05-01T00:00:00Z' },
+ { id: 'standalone', name: 'Loose', universeId: null, seriesId: null, items: [] },
+ ] });
+ writeJson(subsPath, { subscriptions: [
+ { id: 'peer-mediaCollection-rand-1-peerA', peerId: 'peerA', recordKind: 'mediaCollection', recordId: 'rand-1' },
+ ] });
+
+ const res = await migration.up({ rootDir });
+ expect(res).toMatchObject({ ok: true, reason: 'migrated', renamed: 1 });
+
+ const cols = readJson(collectionsPath).collections;
+ expect(cols.find((c) => c.universeId === 'u1').id).toBe('uc-u1');
+ expect(cols.find((c) => c.name === 'Loose').id).toBe('standalone');
+ expect(readJson(subsPath).subscriptions[0].recordId).toBe('uc-u1');
+
+ // Second run is a no-op.
+ const res2 = await migration.up({ rootDir });
+ expect(res2).toMatchObject({ ok: true, reason: 'already-canonical' });
+ });
+
+ it('no-ops on a fresh install (no media-collections.json)', async () => {
+ const res = await migration.up({ rootDir });
+ expect(res).toMatchObject({ ok: true, reason: 'no-collections' });
+ expect(existsSync(collectionsPath)).toBe(false);
+ });
+});
diff --git a/server/routes/peerSync.js b/server/routes/peerSync.js
index 1a19a52b8b..ef5557e9c2 100644
--- a/server/routes/peerSync.js
+++ b/server/routes/peerSync.js
@@ -38,6 +38,8 @@ import {
unsubscribePeer,
applyIncomingPush,
forcePushRecord,
+ getRecordPayloadForPeer,
+ pullRecordFromPeer,
syncNowForPeer,
ERR_NOT_FOUND,
ERR_VALIDATION,
@@ -144,6 +146,27 @@ router.get('/manifest', asyncHandler(async (req, res) => {
res.json({ records: await buildLocalManifest(kind) });
}));
+// --- 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 fetches
+// the payload here and applies it locally (POST /pull-record below). Same shape
+// buildPushPayload produces, so the puller reuses applyIncomingPush.
+router.get('/record', asyncHandler(async (req, res) => {
+ const kind = typeof req.query.kind === 'string' ? req.query.kind.trim() : '';
+ const id = typeof req.query.id === 'string' ? req.query.id.trim() : '';
+ if (!validKind(kind)) {
+ throw new ServerError('invalid kind', { status: 400, code: 'VALIDATION_ERROR' });
+ }
+ if (!id) {
+ throw new ServerError('id required', { status: 400, code: 'VALIDATION_ERROR' });
+ }
+ const payload = await getRecordPayloadForPeer(kind, id);
+ if (!payload) {
+ throw new ServerError('record not found', { status: 404, code: 'NOT_FOUND' });
+ }
+ res.json(payload);
+}));
+
// --- GET /integrity --- compare this instance's records against a peer's.
//
// Fetches the peer's /manifest, runs the pure diff, and returns
@@ -173,6 +196,14 @@ router.post('/sync-record', asyncHandler(async (req, res) => {
res.json(await forcePushRecord(peerId, recordKind, recordId).catch(mapAndRethrow));
}));
+// --- POST /pull-record --- receiver-initiated PULL of a record (+ assets) FROM
+// a peer. The mirror of /sync-record — fixes a record the LOCAL machine is
+// behind on, which a push can't resolve. Reuses peerSyncRecordSchema's shape.
+router.post('/pull-record', asyncHandler(async (req, res) => {
+ const { peerId, recordKind, recordId } = validateRequest(peerSyncRecordSchema, req.body || {});
+ res.json(await pullRecordFromPeer(peerId, recordKind, recordId).catch(mapAndRethrow));
+}));
+
// --- POST /sync-now --- trigger an immediate full-sync for a peer.
//
// Backfills subscriptions for every enabled category then retries all pending
diff --git a/server/routes/peerSync.test.js b/server/routes/peerSync.test.js
index eadc07177e..357272bb43 100644
--- a/server/routes/peerSync.test.js
+++ b/server/routes/peerSync.test.js
@@ -9,6 +9,8 @@ vi.mock('../services/sharing/peerSync.js', () => ({
unsubscribePeer: vi.fn(),
applyIncomingPush: vi.fn(),
forcePushRecord: vi.fn(),
+ getRecordPayloadForPeer: vi.fn(),
+ pullRecordFromPeer: vi.fn(),
syncNowForPeer: vi.fn(),
ERR_NOT_FOUND: 'PEER_SYNC_SUBSCRIPTION_NOT_FOUND',
ERR_VALIDATION: 'PEER_SYNC_SUBSCRIPTION_VALIDATION',
@@ -559,6 +561,53 @@ describe('peer-sync routes', () => {
});
});
+ describe('GET /api/peer-sync/record', () => {
+ it('200 with the record payload for a valid kind + id', async () => {
+ svc.getRecordPayloadForPeer.mockResolvedValue({ kind: 'universe', record: { id: 'u1' }, assetManifest: [], sourceInstanceId: 'me' });
+ const res = await request(buildApp()).get('/api/peer-sync/record?kind=universe&id=u1');
+ expect(res.status).toBe(200);
+ expect(res.body.record.id).toBe('u1');
+ expect(svc.getRecordPayloadForPeer).toHaveBeenCalledWith('universe', 'u1');
+ });
+
+ it('trims kind + id before the lookup', async () => {
+ svc.getRecordPayloadForPeer.mockResolvedValue({ kind: 'universe', record: { id: 'u1' }, assetManifest: [], sourceInstanceId: 'me' });
+ await request(buildApp()).get('/api/peer-sync/record?kind=%20universe%20&id=%20u1%20');
+ expect(svc.getRecordPayloadForPeer).toHaveBeenCalledWith('universe', 'u1');
+ });
+
+ it('404 when the record does not exist locally', async () => {
+ svc.getRecordPayloadForPeer.mockResolvedValue(null);
+ const res = await request(buildApp()).get('/api/peer-sync/record?kind=universe&id=ghost');
+ expect(res.status).toBe(404);
+ });
+
+ it('400 on invalid kind or missing id', async () => {
+ expect((await request(buildApp()).get('/api/peer-sync/record?kind=issue&id=x')).status).toBe(400);
+ expect((await request(buildApp()).get('/api/peer-sync/record?kind=universe&id=%20%20')).status).toBe(400);
+ expect(svc.getRecordPayloadForPeer).not.toHaveBeenCalled();
+ });
+ });
+
+ describe('POST /api/peer-sync/pull-record', () => {
+ it('200 with the pull result for a valid body', async () => {
+ svc.pullRecordFromPeer.mockResolvedValue({ pulled: true, missingAssets: 3 });
+ const res = await request(buildApp())
+ .post('/api/peer-sync/pull-record')
+ .send({ peerId: 'peer-a', recordKind: 'mediaCollection', recordId: 'uc-7' });
+ expect(res.status).toBe(200);
+ expect(res.body).toEqual({ pulled: true, missingAssets: 3 });
+ expect(svc.pullRecordFromPeer).toHaveBeenCalledWith('peer-a', 'mediaCollection', 'uc-7');
+ });
+
+ it('400 on invalid body (missing recordId / bad kind / missing peerId)', async () => {
+ expect((await request(buildApp()).post('/api/peer-sync/pull-record').send({ peerId: 'p', recordKind: 'universe' })).status).toBe(400);
+ expect((await request(buildApp()).post('/api/peer-sync/pull-record').send({ peerId: 'p', recordKind: 'issue', recordId: 'i' })).status).toBe(400);
+ expect((await request(buildApp()).post('/api/peer-sync/pull-record').send({ recordKind: 'universe', recordId: 'u1' })).status).toBe(400);
+ expect(svc.pullRecordFromPeer).not.toHaveBeenCalled();
+ });
+ });
+
describe('POST /api/peer-sync/sync-now', () => {
it('200 with {ok:true} for a valid peerId', async () => {
svc.syncNowForPeer.mockResolvedValue({ ok: true });
diff --git a/server/services/mediaCollections.js b/server/services/mediaCollections.js
index 4f39f5237f..6bf4c61ccf 100644
--- a/server/services/mediaCollections.js
+++ b/server/services/mediaCollections.js
@@ -232,6 +232,14 @@ export async function findOrCreateCollectionByName({ name, description = '', uni
const trimmedDescription = typeof description === 'string'
? description.trim().slice(0, DESCRIPTION_MAX_LENGTH)
: '';
+ // Normalize the universe id (trim whitespace, then cap length) so the
+ // presence guard and the stored/derived value operate on the SAME string —
+ // a padded id can't yield `uc- u1 ` while the guard saw a non-empty value.
+ // Whitespace-only is treated as "no universe". Keeps the derived deterministic
+ // id under the peer-sync id length cap.
+ const normalizedUniverseId = typeof universeId === 'string' && universeId.trim()
+ ? universeId.trim().slice(0, UNIVERSE_ID_MAX)
+ : null;
let createdId = null;
const result = await serializeFileWrite(async () => {
const all = await listCollections({ includeDeleted: true });
@@ -240,29 +248,47 @@ export async function findOrCreateCollectionByName({ name, description = '', uni
// should not be resurrected by name.
const existing = all.find((c) => !c.deleted && c.name.toLowerCase() === needle);
if (existing) {
- if (universeId && !existing.universeId) {
- // Lazy backfill so legacy "Universe: <name>" collections gain the
- // link the first time a universe-builder render references them.
- const idx = all.findIndex((c) => c.id === existing.id);
- all[idx] = { ...existing, universeId, updatedAt: new Date().toISOString() };
- await writeAll(all);
- return all[idx];
+ if (normalizedUniverseId && !existing.universeId) {
+ // Lazy backfill so legacy "Universe: <name>" collections gain the link
+ // the first time a universe-builder render references them. Adopt the
+ // DETERMINISTIC id at the same time — keeping the old random id would
+ // leave a universe-linked collection that can't converge across peers
+ // (the very bug deterministic ids fix).
+ const canonId = linkedCollectionId({ universeId: normalizedUniverseId });
+ // If the universe ALREADY has its canonical collection, don't promote a
+ // same-named orphan over it (that would clobber the canonical record's
+ // items) — return the canonical one; the orphan is a duplicate the merge
+ // / migration 038 reconciles.
+ const liveCanonical = all.find((c) => c.id === canonId && !c.deleted);
+ if (liveCanonical) return liveCanonical;
+ // No live canonical — rename the orphan to the deterministic id,
+ // reclaiming a tombstone at that id if one exists.
+ const linked = { ...existing, id: canonId, universeId: normalizedUniverseId, updatedAt: new Date().toISOString() };
+ await writeAll([...all.filter((c) => c.id !== existing.id && c.id !== canonId), linked]);
+ if (canonId !== existing.id) createdId = canonId; // announce the newly-linked record
+ return linked;
}
return existing;
}
const now = new Date().toISOString();
const next = {
- id: randomUUID(),
+ // Deterministic id when universe-linked (cross-machine convergence);
+ // standalone (no link) keeps a random id. See linkedCollectionId.
+ id: linkedCollectionId({ universeId: normalizedUniverseId }) || randomUUID(),
name: trimmed,
description: trimmedDescription,
coverKey: null,
- universeId: universeId || null,
+ universeId: normalizedUniverseId,
items: [],
createdAt: now,
updatedAt: now,
};
createdId = next.id;
- await writeAll([...all, next]);
+ // Reclaim the deterministic id if a tombstone already holds it (re-creating
+ // a previously-deleted universe/series collection). A plain append would
+ // leave two records at the same id and listCollections' dedup keeps the
+ // tombstone (it's first), silently dropping this fresh live record.
+ await writeAll([...all.filter((c) => c.id !== next.id), next]);
return next;
});
if (createdId) announceNewCollection(createdId);
@@ -277,6 +303,24 @@ export async function findOrCreateCollectionByName({ name, description = '', uni
export const universeCollectionNameFor = (universeName) =>
`Universe: ${typeof universeName === 'string' ? universeName : ''}`.slice(0, NAME_MAX_LENGTH);
+// Deterministic id for a universe/series-LINKED collection. Every federated
+// machine derives the SAME id from the same universe/series id — so per-record
+// collection sync (which keys on `id`) treats both machines' copies as ONE
+// record and converges, instead of each minting a random UUID and duplicating
+// the collection on every peer. Standalone (unlinked) collections keep a random
+// id — they have no stable cross-machine identity. Migration 038 canonicalizes
+// existing linked-collection ids to this scheme. Mirror any change here in that
+// migration. `uc-`/`sc-` prefixes keep linked ids visually distinct from the
+// random UUIDs of standalone collections. The owner id is sliced to the same cap
+// storage uses so the derived id is bounded by construction — callers can pass a
+// raw owner id without first slicing it and still converge on the canonical id
+// (and stay under the peer-sync id length cap).
+export const linkedCollectionId = ({ universeId = null, seriesId = null } = {}) => {
+ if (universeId) return `uc-${String(universeId).slice(0, UNIVERSE_ID_MAX)}`;
+ if (seriesId) return `sc-${String(seriesId).slice(0, SERIES_ID_MAX)}`;
+ return null;
+};
+
// Look up an existing collection by its universeId stamp. Returns null if no
// collection has ever been linked to this universe — callers fall back to
// `findOrCreateUniverseCollection` (the universeId-first upsert) to provision
@@ -351,7 +395,9 @@ export async function findOrCreateUniverseCollection({ universeId, universeName,
// migration belong to "ambiguous, leave it" rather than "auto-adopt."
const now = new Date().toISOString();
const next = {
- id: randomUUID(),
+ // Deterministic id so this universe's collection has the SAME id on every
+ // peer (per-record sync keys on id) — see linkedCollectionId.
+ id: linkedCollectionId({ universeId: normalizedUniverseId }),
name: desiredName,
description: trimmedDescription,
coverKey: null,
@@ -361,7 +407,11 @@ export async function findOrCreateUniverseCollection({ universeId, universeName,
updatedAt: now,
};
createdId = next.id;
- await writeAll([...all, next]);
+ // Reclaim the deterministic id if a tombstone already holds it (re-creating
+ // a previously-deleted universe/series collection). A plain append would
+ // leave two records at the same id and listCollections' dedup keeps the
+ // tombstone (it's first), silently dropping this fresh live record.
+ await writeAll([...all.filter((c) => c.id !== next.id), next]);
return next;
});
// Announce only when a NEW record was persisted (not a find-existing hit), so
@@ -406,7 +456,8 @@ export async function findOrCreateSeriesCollection({ seriesId, seriesName, descr
if (linked) return linked;
const now = new Date().toISOString();
const next = {
- id: randomUUID(),
+ // Deterministic id — same series collection id on every peer (see linkedCollectionId).
+ id: linkedCollectionId({ seriesId: normalizedSeriesId }),
name: desiredName,
description: trimmedDescription,
coverKey: null,
@@ -416,7 +467,11 @@ export async function findOrCreateSeriesCollection({ seriesId, seriesName, descr
updatedAt: now,
};
createdId = next.id;
- await writeAll([...all, next]);
+ // Reclaim the deterministic id if a tombstone already holds it (re-creating
+ // a previously-deleted universe/series collection). A plain append would
+ // leave two records at the same id and listCollections' dedup keeps the
+ // tombstone (it's first), silently dropping this fresh live record.
+ await writeAll([...all.filter((c) => c.id !== next.id), next]);
return next;
});
if (createdId) announceNewCollection(createdId);
diff --git a/server/services/mediaCollections.test.js b/server/services/mediaCollections.test.js
index 8fe3730e18..5497f542e8 100644
--- a/server/services/mediaCollections.test.js
+++ b/server/services/mediaCollections.test.js
@@ -417,6 +417,72 @@ describe('mediaCollections service', () => {
});
describe('findOrCreateUniverseCollection', () => {
+ it('mints a DETERMINISTIC id (uc-<universeId>) so federated peers converge, not a random UUID', async () => {
+ const c = await svc.findOrCreateUniverseCollection({ universeId: 'u-1', universeName: 'Foo' });
+ expect(c.id).toBe('uc-u-1');
+ expect(svc.linkedCollectionId({ universeId: 'u-1' })).toBe('uc-u-1');
+ // Series mirror.
+ const s = await svc.findOrCreateSeriesCollection({ seriesId: 's-9', seriesName: 'Bar' });
+ expect(s.id).toBe('sc-s-9');
+ });
+
+ it('findOrCreateCollectionByName canonicalizes the id when backfilling a universe link onto an orphan', async () => {
+ const orphan = await svc.findOrCreateCollectionByName({ name: 'Universe: Legacy' });
+ expect(orphan.id).not.toMatch(/^uc-/); // standalone → random id
+ // Referencing it WITH a universeId must adopt the deterministic id, not
+ // keep the random one (which couldn't converge across peers).
+ const linked = await svc.findOrCreateCollectionByName({ name: 'Universe: Legacy', universeId: 'u-legacy' });
+ expect(linked.id).toBe('uc-u-legacy');
+ expect(linked.universeId).toBe('u-legacy');
+ const all = await svc.listCollections();
+ expect(all.filter((c) => c.name === 'Universe: Legacy')).toHaveLength(1);
+ expect(all.some((c) => c.id === orphan.id)).toBe(false); // old random id gone
+ });
+
+ it('backfill prefers an existing live canonical collection over promoting a same-named orphan', async () => {
+ // Universe already has its canonical collection (with items)…
+ const canonical = await svc.findOrCreateUniverseCollection({ universeId: 'u-x', universeName: 'X' });
+ await svc.addItem(canonical.id, { kind: 'image', ref: 'keep.png' });
+ // …plus a same-named orphan. A name-first backfill must NOT clobber the
+ // canonical record's items — it returns the canonical one.
+ const result = await svc.findOrCreateCollectionByName({ name: 'Universe: X', universeId: 'u-x' });
+ expect(result.id).toBe('uc-u-x');
+ expect(result.items.map((i) => i.ref)).toContain('keep.png');
+ });
+
+ it('findOrCreateCollectionByName slices an overlong universeId for both the id and the stored field', async () => {
+ // An overlong owner id must yield the same canonical id the universeId-first
+ // path computes (it slices to UNIVERSE_ID_MAX=80) — otherwise the backfill/
+ // create here and findOrCreateUniverseCollection would diverge and duplicate.
+ const overlong = 'u-' + 'x'.repeat(200);
+ const sliced = overlong.slice(0, 80);
+ const c = await svc.findOrCreateCollectionByName({ name: 'Universe: Big', universeId: overlong });
+ expect(c.id).toBe(`uc-${sliced}`);
+ expect(c.universeId).toBe(sliced);
+ expect(svc.linkedCollectionId({ universeId: overlong })).toBe(`uc-${sliced}`);
+ });
+
+ it('findOrCreateCollectionByName trims a padded universeId so it converges (no uc- u1 -style ids)', async () => {
+ // A padded id must normalize to the same canonical id an unpadded caller
+ // gets — the presence guard and the slice operate on the trimmed value.
+ const c = await svc.findOrCreateCollectionByName({ name: 'Universe: Padded', universeId: ' u-pad ' });
+ expect(c.id).toBe('uc-u-pad');
+ expect(c.universeId).toBe('u-pad');
+ });
+
+ it('revives the deterministic id after delete instead of duplicating it (tombstone reclaim)', async () => {
+ const c = await svc.findOrCreateUniverseCollection({ universeId: 'u-1', universeName: 'Foo' });
+ await svc.addItem(c.id, { kind: 'image', ref: 'x.png' });
+ await svc.deleteCollection(c.id); // tombstone at uc-u-1
+ const revived = await svc.findOrCreateUniverseCollection({ universeId: 'u-1', universeName: 'Foo' });
+ expect(revived.id).toBe('uc-u-1');
+ expect(revived.deleted).toBeFalsy();
+ // Exactly one live collection at the deterministic id — the tombstone was
+ // reclaimed, not left to shadow the fresh record in listCollections' dedup.
+ const live = await svc.listCollections();
+ expect(live.filter((x) => x.id === 'uc-u-1')).toHaveLength(1);
+ });
+
it('returns the existing universeId-linked collection on second call', async () => {
const first = await svc.findOrCreateUniverseCollection({
universeId: 'u-1', universeName: 'Foo',
diff --git a/server/services/sharing/peerSync.js b/server/services/sharing/peerSync.js
index 055e567e55..85ef4ed5b6 100644
--- a/server/services/sharing/peerSync.js
+++ b/server/services/sharing/peerSync.js
@@ -57,6 +57,7 @@ import {
getPortosVersion,
} from '../../lib/schemaVersions.js';
import { getInstanceId, getPeers, UNKNOWN_INSTANCE_ID } from '../instances.js';
+import { peerSyncPushSchema } from '../../lib/validation.js';
import { instanceEvents } from '../instanceEvents.js';
import { getUniverse, mergeUniversesFromSync } from '../universeBuilder.js';
import { getSeries, mergeSeriesFromSync } from '../pipeline/series.js';
@@ -1447,6 +1448,10 @@ const ASSET_KIND_TO_URL_PREFIX = Object.freeze({
const ASSET_PULL_TIMEOUT_MS = 60000;
const ASSET_PULL_MAX_BYTES = 100 * 1024 * 1024; // 100MB hard cap per asset
+// A record pull returns JSON (the record + its asset *manifest* of hashes, not
+// the bytes). Even a large series+issues record is metadata, so 16MB is a
+// generous ceiling that still caps a buggy/runaway peer's response.
+const RECORD_PAYLOAD_MAX_BYTES = 16 * 1024 * 1024;
// In-flight pull dedup. A peer can push multiple records that reference the
// same asset in quick succession (universe edit → child collection re-link
@@ -1768,6 +1773,93 @@ export async function forcePushRecord(peerId, recordKind, recordId) {
return pushRecordToPeer({ ...sub, lastPushedHash: null }, { bypassSchemaCooldown: true });
}
+/**
+ * Build the push-payload for a single record WITHOUT a subscription — backs the
+ * peer-facing `GET /api/peer-sync/record` endpoint so a peer can PULL this
+ * record (and its assets) from us. Returns null when the record doesn't exist
+ * locally. Same shape `pushRecordToPeer` sends, so the puller reuses
+ * `applyIncomingPush` verbatim.
+ */
+export async function getRecordPayloadForPeer(recordKind, recordId) {
+ // Mirror pushRecordToPeer's identity guard: if our self-identity can't be read
+ // or isn't initialized yet, do NOT emit a payload — a missing/UNKNOWN
+ // sourceInstanceId would 500 here or poison the puller (applyIncomingPush
+ // rejects sourceInstanceId='unknown'). Return null → the route 404s.
+ const instanceId = await getInstanceId().catch(() => null);
+ if (!isNonEmptyStr(instanceId) || instanceId === UNKNOWN_INSTANCE_ID) return null;
+ return buildPushPayload({ recordKind, recordId }, instanceId);
+}
+
+/**
+ * Receiver-initiated PULL — the mirror of forcePushRecord. Fetch a record's
+ * push-payload from `peerId` and apply it locally (merging the record + its
+ * bundled collection and background-pulling missing asset bytes via
+ * applyIncomingPush). Lets a machine that is BEHIND on a record fix itself,
+ * instead of "Sync to peer" being the only (push-only) action — which can't
+ * help when the LOCAL side is the one missing data. Best-effort: returns
+ * `{ pulled, reason?, missingAssets? }`.
+ */
+export async function pullRecordFromPeer(peerId, recordKind, recordId) {
+ const peers = await getPeers().catch(() => []);
+ const peer = peers.find((p) => p.instanceId === peerId) || null;
+ if (!peer) return { pulled: false, reason: 'peer-not-found' };
+
+ const url = `${peerBaseUrl(peer)}/api/peer-sync/record?kind=${encodeURIComponent(recordKind)}&id=${encodeURIComponent(recordId)}`;
+ // Abort a hung peer after PUSH_TIMEOUT_MS — peerFetch has no built-in timeout,
+ // so without this a stalled peer would hang the pull (and the UI action)
+ // indefinitely. Mirrors the push path; an abort rejects → caught as null →
+ // 'peer-unreachable'.
+ const controller = new AbortController();
+ const timeoutId = setTimeout(() => controller.abort(), PUSH_TIMEOUT_MS);
+ // maxBytes caps the HTTPS shim's in-memory buffering (see lib/httpClient.js);
+ // a buggy/misbehaving peer streaming an oversized body is aborted mid-stream
+ // rather than buffered whole. The shim rejects with an "exceed" Error.
+ let tooLarge = false;
+ const res = await peerFetch(url, { signal: controller.signal, maxBytes: RECORD_PAYLOAD_MAX_BYTES })
+ .finally(() => clearTimeout(timeoutId))
+ .catch((err) => {
+ if (err?.message?.includes('exceed')) {
+ tooLarge = true; // HTTPS shim tripped the cap — same condition as the Content-Length check
+ console.log(`⚠️ peerSync: pull-record ${recordKind}/${recordId} exceeded payload cap — ${err.message}`);
+ }
+ return null;
+ });
+ if (tooLarge) return { pulled: false, reason: 'payload-too-large' };
+ if (!res) return { pulled: false, reason: 'peer-unreachable' };
+ if (res.status === 404) return { pulled: false, reason: 'not-on-peer' };
+ if (!res.ok) return { pulled: false, reason: `http-${res.status}` };
+ // Plain-HTTP path: Node's fetch ignores maxBytes, but Express sets
+ // Content-Length on JSON — reject an oversized declared body before buffering.
+ const declaredLen = Number(res.headers?.get?.('content-length'));
+ if (Number.isFinite(declaredLen) && declaredLen > RECORD_PAYLOAD_MAX_BYTES) {
+ console.log(`⚠️ peerSync: pull-record ${recordKind}/${recordId} declared ${declaredLen} bytes > cap`);
+ return { pulled: false, reason: 'payload-too-large' };
+ }
+
+ const body = await res.json().catch(() => null);
+ // The peer response is untrusted — validate with the SAME schema the inbound
+ // /push route uses before handing it to applyIncomingPush.
+ const parsed = peerSyncPushSchema.safeParse(body);
+ if (!parsed.success) return { pulled: false, reason: 'invalid-payload' };
+ // The payload self-reports its origin via `sourceInstanceId`; applyIncomingPush
+ // uses it to wire the reverse subscription + pull asset bytes. We fetched from
+ // `peer`, so the origin MUST be that peer — a record claiming to originate
+ // elsewhere (misconfigured/buggy peer returning the wrong record) would bind
+ // our subscription/asset-pull to a peer we never contacted. Reject the mismatch.
+ if (parsed.data.sourceInstanceId !== peer.instanceId) {
+ return { pulled: false, reason: 'invalid-payload' };
+ }
+ // Likewise, the payload must be the record we asked for — a buggy peer that
+ // returns a different kind/id would otherwise merge unexpected data locally.
+ if (parsed.data.kind !== recordKind || parsed.data.record?.id !== recordId) {
+ return { pulled: false, reason: 'invalid-payload' };
+ }
+
+ console.log(`🔄 peerSync: pull-record ${recordKind}/${recordId} ← ${peer.name || peerId}`);
+ const result = await applyIncomingPush(parsed.data);
+ return { pulled: true, missingAssets: result?.missingAssets?.length ?? 0 };
+}
+
/**
* Trigger an immediate full-sync for a single peer: backfill subscriptions for
* every enabled category and then retry all pending/stale pushes. Best-effort
diff --git a/server/services/sharing/peerSync.test.js b/server/services/sharing/peerSync.test.js
index 7b9e1c2bf5..bde782a9c8 100644
--- a/server/services/sharing/peerSync.test.js
+++ b/server/services/sharing/peerSync.test.js
@@ -68,6 +68,8 @@ import {
autoSubscribePeerToAllRecords,
retryPendingPushesForPeer,
forcePushRecord,
+ getRecordPayloadForPeer,
+ pullRecordFromPeer,
syncNowForPeer,
collectSubscriptionsForUpdate,
__resetForTests,
@@ -711,6 +713,111 @@ describe('peerSync', () => {
});
});
+ describe('getRecordPayloadForPeer', () => {
+ it('returns a push-payload for an existing universe', async () => {
+ vi.mocked(getUniverse).mockResolvedValue({ id: 'u1', name: 'Foo', updatedAt: '2026-01-01T00:00:00Z' });
+ const payload = await getRecordPayloadForPeer('universe', 'u1');
+ expect(payload).toMatchObject({ kind: 'universe', record: { id: 'u1' } });
+ expect(Array.isArray(payload.assetManifest)).toBe(true);
+ });
+
+ it('returns null when the record does not exist locally', async () => {
+ vi.mocked(getUniverse).mockResolvedValue(undefined);
+ expect(await getRecordPayloadForPeer('universe', 'ghost')).toBeNull();
+ });
+
+ it('returns null (no unknown-sourced payload) when self-identity is unknown', async () => {
+ // Without the guard this would emit a payload with sourceInstanceId='unknown'
+ // that the puller's applyIncomingPush rejects — or 500 on a read failure.
+ vi.mocked(getUniverse).mockResolvedValue({ id: 'u1', name: 'Foo', updatedAt: '2026-01-01T00:00:00Z' });
+ vi.mocked(getInstanceId).mockResolvedValueOnce('unknown');
+ expect(await getRecordPayloadForPeer('universe', 'u1')).toBeNull();
+ });
+
+ it('returns null when self-identity read fails', async () => {
+ vi.mocked(getUniverse).mockResolvedValue({ id: 'u1', name: 'Foo', updatedAt: '2026-01-01T00:00:00Z' });
+ vi.mocked(getInstanceId).mockRejectedValueOnce(new Error('instances.json unreadable'));
+ expect(await getRecordPayloadForPeer('universe', 'u1')).toBeNull();
+ });
+ });
+
+ describe('pullRecordFromPeer', () => {
+ it('peer-not-found when the peer is unknown', async () => {
+ vi.mocked(getPeers).mockResolvedValue([]);
+ expect(await pullRecordFromPeer('nope', 'universe', 'u1')).toEqual({ pulled: false, reason: 'peer-not-found' });
+ });
+
+ it('peer-unreachable when the fetch fails', async () => {
+ vi.mocked(peerFetch).mockRejectedValue(new Error('ECONNREFUSED'));
+ expect(await pullRecordFromPeer('peer-a', 'universe', 'u1')).toEqual({ pulled: false, reason: 'peer-unreachable' });
+ });
+
+ it('not-on-peer on a 404 from the peer', async () => {
+ vi.mocked(peerFetch).mockResolvedValue({ ok: false, status: 404 });
+ expect(await pullRecordFromPeer('peer-a', 'universe', 'u1')).toEqual({ pulled: false, reason: 'not-on-peer' });
+ });
+
+ it('invalid-payload when the peer returns a malformed body', async () => {
+ vi.mocked(peerFetch).mockResolvedValue({ ok: true, status: 200, json: async () => ({ junk: true }) });
+ expect(await pullRecordFromPeer('peer-a', 'universe', 'u1')).toEqual({ pulled: false, reason: 'invalid-payload' });
+ });
+
+ it('applies a valid payload and reports missingAssets count', async () => {
+ vi.mocked(peerFetch).mockResolvedValue({
+ ok: true,
+ status: 200,
+ json: async () => ({ kind: 'universe', record: { id: 'u-pull' }, assetManifest: [], sourceInstanceId: 'peer-a' }),
+ });
+ const result = await pullRecordFromPeer('peer-a', 'universe', 'u-pull');
+ expect(result.pulled).toBe(true);
+ expect(typeof result.missingAssets).toBe('number');
+ });
+
+ it('invalid-payload when sourceInstanceId does not match the contacted peer', async () => {
+ // We fetched from peer-a, but the payload claims to originate from someone
+ // else — applying it would bind our reverse-subscription/asset-pull to a
+ // peer we never contacted. Reject rather than trust the self-reported origin.
+ vi.mocked(peerFetch).mockResolvedValue({
+ ok: true,
+ status: 200,
+ json: async () => ({ kind: 'universe', record: { id: 'u-pull' }, assetManifest: [], sourceInstanceId: 'peer-b' }),
+ });
+ expect(await pullRecordFromPeer('peer-a', 'universe', 'u-pull'))
+ .toEqual({ pulled: false, reason: 'invalid-payload' });
+ });
+
+ it('payload-too-large when the peer declares a Content-Length over the cap', async () => {
+ vi.mocked(peerFetch).mockResolvedValue({
+ ok: true,
+ status: 200,
+ headers: { get: (h) => (h.toLowerCase() === 'content-length' ? String(64 * 1024 * 1024) : null) },
+ json: async () => ({ kind: 'universe', record: { id: 'u-pull' }, assetManifest: [], sourceInstanceId: 'peer-a' }),
+ });
+ expect(await pullRecordFromPeer('peer-a', 'universe', 'u-pull'))
+ .toEqual({ pulled: false, reason: 'payload-too-large' });
+ });
+
+ it('payload-too-large (not peer-unreachable) when the HTTPS shim trips the maxBytes cap', async () => {
+ // The shim rejects with an "exceed" Error — must map to payload-too-large,
+ // consistent with the Content-Length path, not be misread as offline.
+ vi.mocked(peerFetch).mockRejectedValue(new Error('Response body exceeded maxBytes 16777216 (got 99999999)'));
+ expect(await pullRecordFromPeer('peer-a', 'universe', 'u-pull'))
+ .toEqual({ pulled: false, reason: 'payload-too-large' });
+ });
+
+ it('invalid-payload when the returned record is not the one we requested', async () => {
+ // Asked for universe/u-pull but the peer returned a different record id —
+ // applying it would merge unexpected data under the requested key.
+ vi.mocked(peerFetch).mockResolvedValue({
+ ok: true,
+ status: 200,
+ json: async () => ({ kind: 'universe', record: { id: 'some-other-id' }, assetManifest: [], sourceInstanceId: 'peer-a' }),
+ });
+ expect(await pullRecordFromPeer('peer-a', 'universe', 'u-pull'))
+ .toEqual({ pulled: false, reason: 'invalid-payload' });
+ });
+ });
+
describe('syncNowForPeer', () => {
it('returns {ok:false} when the peer has no instanceId', async () => {
vi.mocked(getPeers).mockResolvedValue([