Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat(peer-sync): Stage 4 — UI components + receiver asset pull (#436)
[._.]/ Adam Eivy4cfccf69b404
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex ea406aab21..cac113bbfb 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -1,6 +1,7 @@# Unreleased Changes## Added+- Federated peer-sync UI + receiver-side asset pull (Stage 4 of 5). New `SyncToPeerButton` (`client/src/components/sharing/SyncToPeerButton.jsx`) appears next to the existing `ShareToButton` on Universe and Series pages — a dropdown of every enabled peer with a check/circle toggle to subscribe/unsubscribe. New `MediaImage` component (`client/src/components/MediaImage.jsx`) wraps `<img>` and renders a "Syncing" placeholder when the asset 404s (peer-pushed records reference UUIDs that haven't been pulled yet); a `peerSync:asset-arrived` socket event swaps the placeholder for the live bytes the moment the receiver's worker lands them. The Instances page now shows a per-peer "Live-pushed records" section listing every active sync subscription with a one-click unsubscribe and a `↩ reverse` badge for subs that were auto-created by an inbound push. New receiver-side `pullMissingAssetsFromPeer` worker in `server/services/sharing/peerSync.js` background-fetches each missing asset from the sender's `/data/{kind-dir}/<filename>` static mount and writes it locally (capped at 100MB per asset, filenames re-validated against path traversal even after the diff already sanitized them). `peerSyncEvents` is wired through `sharing/index.js` to socket clients so the UI updates in real time.- Federated peer-sync HTTP routes and orchestrator wiring (Stage 3 of 5). New `server/routes/peerSync.js` mounts at `/api/peer-sync` with `POST /push` (receiver-side; wraps `applyIncomingPush` with Zod-validated payload + asset-manifest size cap of 2000), `GET/POST /subscriptions` (list + create local outgoing subs), and `DELETE /subscriptions/:id`. `installPeerSyncListener()` now runs alongside `installSubscriptionListener` in `initSharing` so one `recordEvents 'updated'` fan-out drives both the share-bucket and peer-sync transports. `syncOrchestrator` now consults `listPeerSubscriptions(peerId)` per cycle and skips the snapshot category for any `(peer, kind)` pair where a per-record peer subscription exists (universe-sub → skip 'universe' snapshot; series-sub → skip 'pipeline' snapshot) so the push pipeline owns the wire for subscribed pairs and the 60s loop stops re-applying the same records. Asset static mounts under `/data/{images,image-refs,videos,video-thumbnails}` now pass `acceptRanges: true` explicitly so the receiver's background asset-pull can resume partial downloads over flaky Tailnet links (default of serve-static, now encoded as a contract so it can't accidentally regress).- Federated peer-sync pipeline modules (Stage 2 of 5). New `server/services/sharing/peerSync.js` holds the per-record subscription store (`data/sharing/peer_subscriptions.json`), the asset-manifest builder, the push pipeline that serializes a record + its child issues + the SHA-manifest to a peer's `/api/peer-sync/push` endpoint, and the receiver-side `applyIncomingPush` that merges via the existing `merge*FromSync` LWW path, computes the asset-diff response, and best-effort auto-creates a reverse subscription back to the sender (honoring per-peer `directions: ['inbound']` to skip when explicitly inbound-only). New `server/services/sharing/peerTombstoneCursors.js` holds per-peer `lastAckedDeleteAt` water-marks so a tombstone is only GC'd once every subscribed peer has acked it (with a `subscribedSince` horizon so late-joining peers don't have to ingest every historical deletion). State writes serialize through a module-level `writeTail` so a fire-and-forget push can't clobber a concurrent subscribe write on the same JSON. The actual HTTP routes and orchestrator wiring land in Stage 3.- Foundation for federated peer sync of Universes, Series, and Issues (Stage 1 of 5). Soft-delete (`deleted` + `deletedAt` tombstone fields) is now part of the on-disk record for universes, series, and issues — so a delete propagates to other PortOS instances via the existing LWW snapshot merge instead of vanishing locally and resurrecting from a peer. `listUniverses` / `listSeries` / `listIssues` (and their per-id getters) filter tombstones by default; pass `{ includeDeleted: true }` to see them. `mergeUniversesFromSync` / `mergeSeriesFromSync` / `mergeIssuesFromSync` detect delete-transitions and fire the same orphan-cleanup cascades as a local delete (media-collection unlink, slot-map clear, issue renumber). New `server/lib/syncWire.js` is the single source of truth for what fields cross the peer wire (today it strips `runs[]` from universe state — shared by the 60s snapshot loop and the upcoming per-record push). New `server/lib/assetHash.js` persists SHA-256 hashes in each `data/images/{uuid}.metadata.json` sidecar so both the share-bucket exporter and the upcoming peer-sync push pipeline reuse the same value (no per-bucket recomputation, no per-transport cache). `insertUniverseWithId` / `insertSeriesWithId` / `insertIssueWithId` now overwrite a tombstoned record (re-import undeletes) but still reject DUPLICATE on a live record.diff --git a/client/src/components/MediaImage.jsx b/client/src/components/MediaImage.jsxnew file mode 100644index 0000000000..6b6b970161--- /dev/null+++ b/client/src/components/MediaImage.jsx@@ -0,0 +1,121 @@+/**+ * <MediaImage> — wraps <img> with graceful handling for assets that haven't+ * arrived yet from a federated peer.+ *+ * When a peer pushes us a universe / series, we accept the record immediately+ * but background-pull the referenced assets via HTTP from the sender's static+ * mount (see server/services/sharing/peerSync.js `pullMissingAssetsFromPeer`).+ * Until each asset lands, `<img src="/data/images/uuid.png">` 404s. This+ * component intercepts that 404 and shows a "syncing" placeholder instead of+ * the browser's broken-image icon, then auto-swaps to the live image the+ * moment the receiver's worker reports it arrived (via the+ * `peerSync:asset-arrived` socket event).+ *+ * Props:+ * src: string — same as <img>; expected to be `/data/...`+ * alt: string — same as <img>+ * className?: string — applies to BOTH the live <img> and the placeholder wrapper+ * placeholderClassName?: string — extra classes for the placeholder only+ * ...rest — forwarded to <img>+ *+ * The component renders the "Syncing" placeholder on ANY image load failure+ * — the browser's <img onError> doesn't expose the HTTP status, so we can't+ * actually distinguish a 404 from a network drop. That's intentional: the+ * placeholder accurately describes the user-visible state ("this asset is+ * not loadable right now") whether the cause is "peer hasn't pushed it yet"+ * or "network is down." The `peerSync:asset-arrived` listener still gates+ * the swap-back, so a permanent network error doesn't lock the placeholder+ * on forever — the live image returns whenever the path is reachable again+ * (e.g. on the next push that triggers a re-fetch via the socket event).+ */++import { useEffect, useRef, useState } from 'react';+import { Cloud } from 'lucide-react';+import socket from '../services/socket';++function basenameOf(src) {+ if (typeof src !== 'string') return null;+ const last = src.split('/').pop();+ if (!last) return null;+ return last.split('?')[0] || null;+}++export default function MediaImage({+ src,+ alt = '',+ className = '',+ placeholderClassName = '',+ ...rest+}) {+ const [errored, setErrored] = useState(false);+ // Bumping `nonce` forces the <img> to re-fetch (cache-busted) when the+ // socket says our asset arrived — without it the browser would serve the+ // cached 404 forever.+ const [nonce, setNonce] = useState(0);+ const filename = basenameOf(src);+ const filenameRef = useRef(filename);+ filenameRef.current = filename;++ // Reset the error flag when `src` changes — a new record may reference a+ // different filename that we DO have locally.+ useEffect(() => {+ setErrored(false);+ setNonce(0);+ }, [src]);++ // Listen for the receiver's asset-arrived event. Match on filename only+ // (kind is implicit from the directory in the src URL) so the listener+ // doesn't need to know which `/data/{images,image-refs,videos}/` slot the+ // src belongs to.+ useEffect(() => {+ if (!filename) return;+ const handler = (payload) => {+ if (payload?.filename === filenameRef.current) {+ setErrored(false);+ setNonce((n) => n + 1);+ }+ };+ socket.on('peerSync:asset-arrived', handler);+ return () => socket.off('peerSync:asset-arrived', handler);+ }, [filename]);++ if (errored) {+ return (+ <div+ className={`flex items-center justify-center bg-port-bg border border-port-border/40 rounded text-gray-500 ${className} ${placeholderClassName}`}+ title={`Asset pending: ${filename || src}`}+ >+ <Cloud size={16} className="opacity-50" />+ <span className="ml-2 text-[10px] uppercase tracking-wider">Syncing</span>+ </div>+ );+ }++ // The cache-buster appears only after the first arrival event; the very+ // first load (before any 404) uses the bare src so HTTP caching still+ // works the way the rest of the UI expects.+ const cacheBustedSrc = nonce > 0 ? `${src}${src.includes('?') ? '&' : '?'}_t=${nonce}` : src;+ // Spread `rest` FIRST so the explicit `onError` below wins over a caller-+ // provided one — we still forward the event by capturing the caller's+ // handler before composing. Putting {...rest} last would silently override+ // setErrored and the placeholder would never appear.+ const callerOnError = rest.onError;+ const { onError: _ignore, ...passthrough } = rest;+ return (+ <img+ {...passthrough}+ src={cacheBustedSrc}+ alt={alt}+ className={className}+ onError={(e) => {+ // The browser doesn't expose the HTTP status to onError, so any load+ // failure flips into the placeholder. The `peerSync:asset-arrived`+ // listener still gates the swap-back, so a permanent network error+ // doesn't lock the placeholder on forever — user-visible state then+ // accurately reflects "asset not loadable right now."+ setErrored(true);+ callerOnError?.(e);+ }}+ />+ );+}diff --git a/client/src/components/MediaImage.test.jsx b/client/src/components/MediaImage.test.jsxnew file mode 100644index 0000000000..7c601d4461--- /dev/null+++ b/client/src/components/MediaImage.test.jsx@@ -0,0 +1,83 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';+import { render, screen, fireEvent, act } from '@testing-library/react';++// Mock the socket module so we can drive `peerSync:asset-arrived` events+// without a real Socket.IO connection.+const socketHandlers = new Map();+vi.mock('../services/socket', () => ({+ default: {+ on: vi.fn((event, fn) => {+ if (!socketHandlers.has(event)) socketHandlers.set(event, new Set());+ socketHandlers.get(event).add(fn);+ }),+ off: vi.fn((event, fn) => {+ socketHandlers.get(event)?.delete(fn);+ }),+ },+}));++import MediaImage from './MediaImage';++function emitAssetArrived(payload) {+ for (const fn of socketHandlers.get('peerSync:asset-arrived') ?? []) fn(payload);+}++beforeEach(() => {+ socketHandlers.clear();+});++describe('MediaImage', () => {+ it('renders the underlying <img> with the original src by default', () => {+ render(<MediaImage src="/data/images/foo.png" alt="character" />);+ const img = screen.getByAltText('character');+ expect(img.tagName).toBe('IMG');+ expect(img.getAttribute('src')).toBe('/data/images/foo.png');+ });++ it('shows the "Syncing" placeholder after an onError fires (asset 404s before pull lands)', () => {+ render(<MediaImage src="/data/images/missing.png" alt="ghost" />);+ fireEvent.error(screen.getByAltText('ghost'));+ expect(screen.getByText(/Syncing/i)).toBeTruthy();+ });++ it('swaps back to the image when the peerSync:asset-arrived event matches the filename', () => {+ render(<MediaImage src="/data/images/late.png" alt="late" />);+ fireEvent.error(screen.getByAltText('late'));+ expect(screen.getByText(/Syncing/i)).toBeTruthy();+ act(() => {+ emitAssetArrived({ filename: 'late.png', kind: 'image', peerId: 'peer-a' });+ });+ // Placeholder gone, image is back (with a cache-buster nonce).+ expect(screen.queryByText(/Syncing/i)).toBeNull();+ const img = screen.getByAltText('late');+ expect(img.getAttribute('src')).toMatch(/^\/data\/images\/late\.png\?_t=/);+ });++ it('ignores arrival events for a different filename (no spurious reset)', () => {+ render(<MediaImage src="/data/images/foo.png" alt="foo" />);+ fireEvent.error(screen.getByAltText('foo'));+ expect(screen.getByText(/Syncing/i)).toBeTruthy();+ act(() => {+ emitAssetArrived({ filename: 'bar.png', kind: 'image', peerId: 'peer-a' });+ });+ // Still syncing — different filename means our asset is still missing.+ expect(screen.getByText(/Syncing/i)).toBeTruthy();+ });++ it('resets the error state when src changes (new record may reference an asset we have)', () => {+ const { rerender } = render(<MediaImage src="/data/images/a.png" alt="a" />);+ fireEvent.error(screen.getByAltText('a'));+ expect(screen.getByText(/Syncing/i)).toBeTruthy();+ rerender(<MediaImage src="/data/images/b.png" alt="a" />);+ expect(screen.queryByText(/Syncing/i)).toBeNull();+ });++ it('forwards onError to the caller in addition to setting errored state', () => {+ const onError = vi.fn();+ render(<MediaImage src="/data/images/x.png" alt="x" onError={onError} />);+ fireEvent.error(screen.getByAltText('x'));+ expect(onError).toHaveBeenCalled();+ // Placeholder visible regardless.+ expect(screen.getByText(/Syncing/i)).toBeTruthy();+ });+});diff --git a/client/src/components/sharing/SyncToPeerButton.jsx b/client/src/components/sharing/SyncToPeerButton.jsxnew file mode 100644index 0000000000..28f5fb71d3--- /dev/null+++ b/client/src/components/sharing/SyncToPeerButton.jsx@@ -0,0 +1,182 @@+/**+ * SyncToPeerButton — dropdown of federated PortOS peers that toggles per-record+ * peer-sync subscriptions for universes + series.+ *+ * Sibling of `ShareToButton` (which targets cloud-synced share buckets); this+ * targets *other PortOS instances over Tailnet*. The contract is the same:+ * - Filled CheckCircle when (recordKind, recordId) is subscribed to that peer.+ * - Empty Circle otherwise.+ * - Clicking checked → unsubscribe; clicking unchecked → subscribe (which+ * triggers an initial push and then auto-pushes on every subsequent edit).+ *+ * Bidirectional sync: when this peer subscribes to a record on our end, the+ * receiver-side `applyIncomingPush` on the peer auto-creates a *reverse*+ * subscription (when their `directions` config allows it). The button doesn't+ * expose the reverse state — the user only manages the *outbound* direction+ * from this UI; the Instances page shows the bidirectional picture.+ *+ * Props:+ * recordKind: 'universe' | 'series'+ * recordId: string (required — the record's id)+ * label?: string+ * compact?: boolean+ */++import { useEffect, useRef, useState } from 'react';+import { Cloud, Circle, CheckCircle2, Loader2 } from 'lucide-react';+import toast from '../ui/Toast';+import {+ getInstances,+ listPeerSubscriptions,+ subscribeToPeer,+ unsubscribeFromPeer,+} from '../../services/api';++export default function SyncToPeerButton({+ recordKind,+ recordId,+ label = 'Sync',+ compact = false,+ className = '',+}) {+ const [open, setOpen] = useState(false);+ const [peers, setPeers] = useState([]);+ const [subscriptions, setSubscriptions] = useState([]); // [{id, peerId, ...}]+ const [loading, setLoading] = useState(false);+ const [busyPeerId, setBusyPeerId] = useState(null);+ const wrapperRef = useRef(null);++ const refresh = async () => {+ setLoading(true);+ const [instances, subs] = await Promise.all([+ getInstances({ silent: true }).catch(() => null),+ listPeerSubscriptions({ recordKind, recordId }, { silent: true })+ .then((r) => r?.subscriptions || [])+ .catch(() => []),+ ]);+ // Only show enabled, online-or-connectable peers — Tailnet peers that are+ // marked enabled but currently offline are still listed so the user can+ // create the subscription now and let the push pipeline retry on reconnect.+ const visiblePeers = (instances?.peers || []).filter((p) => p.enabled && p.instanceId);+ setPeers(visiblePeers);+ setSubscriptions(subs);+ setLoading(false);+ };++ useEffect(() => {+ if (open) refresh();+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [open]);++ useEffect(() => {+ if (!open) return;+ const handler = (e) => {+ if (wrapperRef.current && !wrapperRef.current.contains(e.target)) setOpen(false);+ };+ window.addEventListener('mousedown', handler);+ return () => window.removeEventListener('mousedown', handler);+ }, [open]);++ const subscriptionForPeer = (peerInstanceId) =>+ subscriptions.find((s) => s.peerId === peerInstanceId) || null;++ const handleToggle = async (peer) => {+ setBusyPeerId(peer.instanceId);+ const existing = subscriptionForPeer(peer.instanceId);+ if (existing) {+ const ok = await unsubscribeFromPeer(existing.id).catch((err) => {+ toast.error(err.message || `Unsync from ${peer.name} failed`);+ return null;+ });+ if (ok) {+ setSubscriptions((prev) => prev.filter((s) => s.id !== existing.id));+ toast.success(`Stopped syncing to ${peer.name}`);+ }+ } else {+ const result = await subscribeToPeer({+ peerId: peer.instanceId,+ recordKind,+ recordId,+ }).catch((err) => {+ toast.error(err.message || `Sync to ${peer.name} failed`);+ return null;+ });+ if (result?.subscription) {+ setSubscriptions((prev) => [...prev, result.subscription]);+ toast.success(`Syncing to ${peer.name} — edits will push automatically`);+ }+ }+ setBusyPeerId(null);+ };++ const nothingToSync = !recordId;++ return (+ <div ref={wrapperRef} className={`relative inline-block ${className}`}>+ <button+ type="button"+ onClick={() => setOpen((v) => !v)}+ disabled={nothingToSync}+ className={`inline-flex items-center gap-1.5 px-2.5 py-1.5 rounded text-xs border border-port-border hover:border-port-accent/40 text-gray-300 hover:text-white disabled:opacity-40 disabled:cursor-not-allowed transition-colors ${compact ? 'p-1.5' : ''}`}+ title={nothingToSync ? 'Nothing to sync' : 'Sync to a peer instance'}+ >+ <Cloud size={12} />+ {!compact && <span>{label}</span>}+ </button>++ {open && (+ <div className="absolute right-0 z-30 mt-1 w-72 bg-port-card border border-port-border rounded-lg shadow-lg overflow-hidden">+ <div className="px-3 py-2 text-[10px] uppercase tracking-wider text-gray-500 border-b border-port-border">+ Subscribe to peer+ </div>+ {loading ? (+ <div className="px-3 py-3 text-xs text-gray-500 flex items-center gap-2">+ <Loader2 size={12} className="animate-spin" /> Loading peers…+ </div>+ ) : peers.length === 0 ? (+ <div className="px-3 py-3 text-xs text-gray-500">+ No peers configured. <a href="/instances" className="text-port-accent hover:underline">Add one</a>.+ </div>+ ) : (+ <ul className="max-h-72 overflow-y-auto">+ {peers.map((p) => {+ const subscribed = !!subscriptionForPeer(p.instanceId);+ const busy = busyPeerId === p.instanceId;+ return (+ <li key={p.instanceId}>+ <button+ type="button"+ onClick={() => handleToggle(p)}+ disabled={busy}+ className="w-full text-left px-3 py-2 hover:bg-port-bg disabled:opacity-50 flex items-start gap-2"+ >+ <span className="mt-0.5 shrink-0">+ {busy+ ? <Loader2 size={14} className="animate-spin text-port-accent" />+ : subscribed+ ? <CheckCircle2 size={14} className="text-port-success" />+ : <Circle size={14} className="text-gray-600" />}+ </span>+ <div className="flex-1 min-w-0">+ <div className="text-sm text-white truncate">{p.name}</div>+ <div className="text-[10px] text-gray-500 truncate">+ {p.status === 'online' ? 'online' : p.status || 'offline'}+ {p.host ? ` · ${p.host}` : p.address ? ` · ${p.address}` : ''}+ </div>+ </div>+ </button>+ </li>+ );+ })}+ </ul>+ )}+ {subscriptions.length > 0 && (+ <div className="px-3 py-2 text-[10px] text-gray-500 border-t border-port-border">+ Subscribed peers receive your edits automatically; their edits flow back if their config allows.+ </div>+ )}+ </div>+ )}+ </div>+ );+}diff --git a/client/src/components/sharing/SyncToPeerButton.test.jsx b/client/src/components/sharing/SyncToPeerButton.test.jsxnew file mode 100644index 0000000000..2722b1aa48--- /dev/null+++ b/client/src/components/sharing/SyncToPeerButton.test.jsx@@ -0,0 +1,109 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';+import { render, screen, waitFor } from '@testing-library/react';+import userEvent from '@testing-library/user-event';++vi.mock('../../services/api', () => ({+ getInstances: vi.fn(),+ listPeerSubscriptions: vi.fn(),+ subscribeToPeer: vi.fn(),+ unsubscribeFromPeer: vi.fn(),+}));+vi.mock('../ui/Toast', () => ({+ default: { success: vi.fn(), error: vi.fn() },+}));++import * as api from '../../services/api';+import SyncToPeerButton from './SyncToPeerButton';++beforeEach(() => {+ vi.clearAllMocks();+ api.getInstances.mockResolvedValue({+ peers: [+ { instanceId: 'peer-a', name: 'Peer A', enabled: true, status: 'online', host: 'host-a.tail.net' },+ { instanceId: 'peer-b', name: 'Peer B', enabled: true, status: 'offline', address: '10.0.0.3' },+ { instanceId: 'peer-c', name: 'Peer C disabled', enabled: false, status: 'offline' },+ { instanceId: '', name: 'No-id peer', enabled: true },+ ],+ });+ api.listPeerSubscriptions.mockResolvedValue({ subscriptions: [] });+});++describe('SyncToPeerButton', () => {+ it('does not open the dropdown when there is no recordId', async () => {+ const user = userEvent.setup();+ render(<SyncToPeerButton recordKind="universe" recordId={null} />);+ const button = screen.getByRole('button', { name: /Sync/i });+ expect(button).toBeDisabled();+ await user.click(button);+ expect(screen.queryByText(/Subscribe to peer/i)).toBeNull();+ });++ it('lists only enabled peers with an instanceId on open', async () => {+ const user = userEvent.setup();+ render(<SyncToPeerButton recordKind="universe" recordId="u1" />);+ await user.click(screen.getByRole('button', { name: /Sync/i }));+ await waitFor(() => expect(api.getInstances).toHaveBeenCalled());+ expect(await screen.findByText('Peer A')).toBeTruthy();+ expect(screen.getByText('Peer B')).toBeTruthy();+ // disabled peer + no-id peer hidden.+ expect(screen.queryByText(/Peer C disabled/i)).toBeNull();+ expect(screen.queryByText(/No-id peer/i)).toBeNull();+ });++ it('shows a filled check when already subscribed to that peer', async () => {+ api.listPeerSubscriptions.mockResolvedValue({+ subscriptions: [{+ id: 'peer-universe-u1-peer-a',+ peerId: 'peer-a',+ recordKind: 'universe',+ recordId: 'u1',+ }],+ });+ const user = userEvent.setup();+ render(<SyncToPeerButton recordKind="universe" recordId="u1" />);+ await user.click(screen.getByRole('button', { name: /Sync/i }));+ await waitFor(() => expect(api.listPeerSubscriptions).toHaveBeenCalled());+ // We can't easily assert on the icon shape; assert via the row count + that+ // the peer's name renders alongside an enabled-looking button.+ expect(await screen.findByText('Peer A')).toBeTruthy();+ });++ it('subscribes when an unchecked peer row is clicked', async () => {+ api.subscribeToPeer.mockResolvedValue({+ subscription: {+ id: 'peer-universe-u1-peer-a',+ peerId: 'peer-a',+ recordKind: 'universe',+ recordId: 'u1',+ },+ });+ const user = userEvent.setup();+ render(<SyncToPeerButton recordKind="universe" recordId="u1" />);+ await user.click(screen.getByRole('button', { name: /Sync/i }));+ await screen.findByText('Peer A');+ await user.click(screen.getByText('Peer A'));+ expect(api.subscribeToPeer).toHaveBeenCalledWith({+ peerId: 'peer-a',+ recordKind: 'universe',+ recordId: 'u1',+ });+ });++ it('unsubscribes when a checked peer row is clicked', async () => {+ api.listPeerSubscriptions.mockResolvedValue({+ subscriptions: [{+ id: 'peer-universe-u1-peer-a',+ peerId: 'peer-a',+ recordKind: 'universe',+ recordId: 'u1',+ }],+ });+ api.unsubscribeFromPeer.mockResolvedValue({ id: 'peer-universe-u1-peer-a', removed: true });+ const user = userEvent.setup();+ render(<SyncToPeerButton recordKind="universe" recordId="u1" />);+ await user.click(screen.getByRole('button', { name: /Sync/i }));+ await screen.findByText('Peer A');+ await user.click(screen.getByText('Peer A'));+ expect(api.unsubscribeFromPeer).toHaveBeenCalledWith('peer-universe-u1-peer-a');+ });+});diff --git a/client/src/components/universe/CharacterReferenceSheetPanel.jsx b/client/src/components/universe/CharacterReferenceSheetPanel.jsxindex e7a11e3983..653aefe159 100644--- a/client/src/components/universe/CharacterReferenceSheetPanel.jsx+++ b/client/src/components/universe/CharacterReferenceSheetPanel.jsx@@ -24,6 +24,7 @@ import useMediaJobProgress from '../../hooks/useMediaJobProgress';import useMounted from '../../hooks/useMounted';import { readSheetPointer, LEGACY_SHEET_VARIANT_ID } from '../../lib/sheetPointers';import toast from '../ui/Toast';+import MediaImage from '../MediaImage';// HEAD-poll for the rendered sheet at its destination URL, with backoff. The// server-side onSheetComplete listener copies the gallery PNG into@@ -214,10 +215,14 @@ function VariantRow({className="mt-2 block w-full bg-port-bg rounded overflow-hidden border border-port-border hover:border-port-accent/60 cursor-zoom-in p-0"title="Open sheet at full size">- <img+ {/* MediaImage handles the "this asset was peer-pushed but hasn't been+ pulled yet" case — without it, this would show a broken-image icon+ until the receiver's background pull finishes. */}+ <MediaImagesrc={`/data/image-refs/${existing}`}alt={`${entry.name} ${variant.label}`}className="w-full h-auto block"+ placeholderClassName="w-full h-32"loading="lazy"/><span className="flex items-center justify-center gap-1 px-2 py-1 text-[10px] text-gray-500 border-t border-port-border">diff --git a/client/src/pages/Instances.jsx b/client/src/pages/Instances.jsxindex d34c5529d6..cb6d8e12e4 100644--- a/client/src/pages/Instances.jsx+++ b/client/src/pages/Instances.jsx@@ -13,7 +13,8 @@ import toast from '../components/ui/Toast';import socket from '../services/socket';import {getInstances, updateSelfInstance, addPeer, updatePeer,- removePeer, connectPeer, probePeer, getTailnetInfo, provisionTailnetCert+ removePeer, connectPeer, probePeer, getTailnetInfo, provisionTailnetCert,+ listPeerSubscriptions, unsubscribeFromPeer,} from '../services/api';import PeerAppsList from '../components/instances/PeerAppsList';import PeerAgentsSection from '../components/instances/PeerAgentsSection';@@ -533,6 +534,103 @@ 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 }) {+ const [subs, setSubs] = useState([]);+ const [loading, setLoading] = useState(true);+ const [busyId, setBusyId] = useState(null);++ useEffect(() => {+ if (!peer.instanceId) {+ setSubs([]);+ setLoading(false);+ return;+ }+ let cancelled = false;+ setLoading(true);+ listPeerSubscriptions({ peerId: peer.instanceId }, { silent: true })+ .then((r) => {+ if (!cancelled) setSubs(r?.subscriptions || []);+ })+ .catch(() => {+ if (!cancelled) setSubs([]);+ })+ .finally(() => {+ if (!cancelled) setLoading(false);+ });+ return () => { cancelled = true; };+ }, [peer.instanceId]);++ if (!peer.instanceId) return null;+ if (loading) return null;+ if (subs.length === 0) return null;++ const handleUnsubscribe = async (sub) => {+ setBusyId(sub.id);+ const ok = await unsubscribeFromPeer(sub.id).catch((err) => {+ toast.error(err.message || 'Unsubscribe failed');+ return null;+ });+ if (ok) {+ setSubs((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 = subs.filter((s) => s.recordKind === 'universe');+ const seriesSubs = subs.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 ({subs.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 }) {if (!syncStatus || !peer.instanceId) return null;@@ -851,6 +949,8 @@ function PeerCard({ peer, onRefresh, syncStatus, tailnetInfo }) {<SyncStatusSection peer={peer} syncStatus={syncStatus} />+ <PeerSyncSubscriptionsSection peer={peer} />+<PeerAppsList apps={peer.lastApps} peerAddress={peer.address} peerHost={peer.host} />{peer.status === 'online' && (<PeerAgentsSection peerId={peer.id} peerName={peer.name} />diff --git a/client/src/pages/Pipeline.jsx b/client/src/pages/Pipeline.jsxindex 39136ab189..1130957183 100644--- a/client/src/pages/Pipeline.jsx+++ b/client/src/pages/Pipeline.jsx@@ -12,6 +12,7 @@ import { Link } from 'react-router-dom';import { Plus, Workflow as WorkflowIcon, Trash2, Loader2, Globe2 } from 'lucide-react';import toast from '../components/ui/Toast';import ShareToButton from '../components/sharing/ShareToButton';+import SyncToPeerButton from '../components/sharing/SyncToPeerButton';import OriginBadge from '../components/sharing/OriginBadge';import {listPipelineSeries,@@ -354,6 +355,7 @@ export default function Pipeline() {) : null}</Link><ShareToButton kind="series" ids={[s.id]} compact />+ <SyncToPeerButton recordKind="series" recordId={s.id} compact /><buttontype="button"onClick={() => handleDelete(s)}diff --git a/client/src/pages/UniverseBuilder.jsx b/client/src/pages/UniverseBuilder.jsxindex effcb2449b..e55c912172 100644--- a/client/src/pages/UniverseBuilder.jsx+++ b/client/src/pages/UniverseBuilder.jsx@@ -33,6 +33,7 @@ import InfluenceChipsInput from '../components/universeBuilder/InfluenceChipsInpimport ImageGenSettingsForm from '../components/imageGen/ImageGenSettingsForm';import { RUNNER_FAMILIES } from '../lib/runnerFamilies';import ShareToButton from '../components/sharing/ShareToButton';+import SyncToPeerButton from '../components/sharing/SyncToPeerButton';import OriginBadge from '../components/sharing/OriginBadge';import UniverseCanonSection from '../components/universe/UniverseCanonSection';import EntryCard from '../components/universe/EntryCard';@@ -1780,6 +1781,7 @@ export default function UniverseBuilder() {{selectedId && (<><ShareToButton kind="universe" ids={[selectedId]} label="Share" />+ <SyncToPeerButton recordKind="universe" recordId={selectedId} label="Sync" />{draft.origin ? <OriginBadge origin={draft.origin} /> : null}<buttononClick={handleDelete}diff --git a/client/src/services/README.md b/client/src/services/README.mdindex b0ea5a30c8..a7f771be67 100644--- a/client/src/services/README.md+++ b/client/src/services/README.md@@ -83,6 +83,7 @@ toasts on throw). **Custom catch ⇒ `silent: true`** — otherwise toasts fire| `apiUniverseBuilder.js` | Universe Builder (generate + edit + commit). || `apiWritersRoom.js` | Writers Room (folders + works + drafts). || `apiSharing.js` | Share buckets + federation sync. |+| `apiPeerSync.js` | Per-record peer sync subscriptions (universe + series → other PortOS instances over Tailnet). |## Tools / integrationsdiff --git a/client/src/services/api.js b/client/src/services/api.jsindex 97e2a5f583..655619a83b 100644--- a/client/src/services/api.js+++ b/client/src/services/api.js@@ -42,6 +42,7 @@ export * from './apiWritersRoom.js';export * from './apiUniverseBuilder.js';export * from './apiPipeline.js';export * from './apiSharing.js';+export * from './apiPeerSync.js';export * from './apiCreativeDirector.js';export * from './apiImporter.js';export * from './apiVoice.js';diff --git a/client/src/services/apiPeerSync.js b/client/src/services/apiPeerSync.jsnew file mode 100644index 0000000000..423ed783a4--- /dev/null+++ b/client/src/services/apiPeerSync.js@@ -0,0 +1,41 @@+/**+ * Federated peer-sync API wrappers.+ *+ * Sibling of `apiSharing.js` (which targets cloud-synced share buckets); this+ * module targets *other PortOS instances over Tailnet*. The route surface is+ * a thin wrapper over `server/routes/peerSync.js`:+ *+ * GET /peer-sync/subscriptions[?peerId=…&recordKind=…&recordId=…]+ * POST /peer-sync/subscriptions → { peerId, recordKind, recordId }+ * DELETE /peer-sync/subscriptions/:id+ *+ * The receiver-side `POST /peer-sync/push` endpoint exists only for peer-to-+ * peer traffic — the browser never calls it — so it's intentionally absent+ * from this client wrapper.+ */++import { request } from './apiCore.js';++export const PEER_SUBSCRIBABLE_KINDS = Object.freeze(['universe', 'series']);++export const listPeerSubscriptions = (filter = {}, options) => {+ const qs = new URLSearchParams();+ if (filter.peerId) qs.set('peerId', filter.peerId);+ if (filter.recordKind) qs.set('recordKind', filter.recordKind);+ if (filter.recordId) qs.set('recordId', filter.recordId);+ const query = qs.toString();+ return request(`/peer-sync/subscriptions${query ? `?${query}` : ''}`, options);+};++export const subscribeToPeer = ({ peerId, recordKind, recordId }, options) =>+ request('/peer-sync/subscriptions', {+ method: 'POST',+ body: JSON.stringify({ peerId, recordKind, recordId }),+ ...options,+ });++export const unsubscribeFromPeer = (subscriptionId, options) =>+ request(`/peer-sync/subscriptions/${encodeURIComponent(subscriptionId)}`, {+ method: 'DELETE',+ ...options,+ });diff --git a/server/lib/httpClient.js b/server/lib/httpClient.jsindex bc9e0226b7..7b9aef0c2e 100644--- a/server/lib/httpClient.js+++ b/server/lib/httpClient.js@@ -27,13 +27,25 @@ export function insecureFetch(agent) {res.on('data', c => chunks.push(c));res.on('end', () => {cleanup();- const text = Buffer.concat(chunks).toString('utf-8');+ // Concat as a raw Buffer so the response can be projected to text+ // (UTF-8 decode), JSON (parse), or arrayBuffer (binary). Pre-+ // decoding to a UTF-8 string up-front would corrupt binary+ // responses — the peer-sync asset-pull worker uses this shim to+ // download images / videos over HTTPS, and `Buffer.toString('utf-8')`+ // silently replaces invalid byte sequences with U+FFFD.+ const buffer = Buffer.concat(chunks);resolve({ok: res.statusCode >= 200 && res.statusCode < 300,status: res.statusCode,headers: { get: n => res.headers[n.toLowerCase()] ?? null },- text: () => Promise.resolve(text),- json: () => Promise.resolve(JSON.parse(text))+ text: () => Promise.resolve(buffer.toString('utf-8')),+ json: () => Promise.resolve(JSON.parse(buffer.toString('utf-8'))),+ // ArrayBuffer view matching Fetch's Response so call sites can+ // `Buffer.from(await res.arrayBuffer())` without branching on+ // transport.+ arrayBuffer: () => Promise.resolve(+ buffer.buffer.slice(buffer.byteOffset, buffer.byteOffset + buffer.byteLength),+ ),});});res.on('error', (err) => { cleanup(); reject(err); });diff --git a/server/services/sharing/index.js b/server/services/sharing/index.jsindex fd1090f6f3..37245a5779 100644--- a/server/services/sharing/index.js+++ b/server/services/sharing/index.js@@ -12,7 +12,7 @@ import { join } from 'path';import { attachAllWatchers, attachWatcher, detachWatcher, shutdownAllWatchers, listAttachedWatchers } from './watcher.js';import { sharingEvents } from './importer.js';import { installSubscriptionListener } from './subscriptions.js';-import { installPeerSyncListener } from './peerSync.js';+import { installPeerSyncListener, peerSyncEvents } from './peerSync.js';import { initAnnotationsSync } from './annotationsSync.js';export { sharingEvents } from './importer.js';@@ -58,6 +58,12 @@ export async function initSharing({ io: socketIo } = {}) {sharingEvents.on('annotation-updated', (payload) => {io.emit('media:annotation:updated', payload);});+ // Peer-sync asset arrivals → broadcast so the UI can swap the+ // <MediaImage> "syncing" placeholder for the live bytes the moment+ // the receiver's background pull lands them on disk.+ peerSyncEvents.on('asset-arrived', (payload) => {+ io.emit('peerSync:asset-arrived', payload);+ });}installSubscriptionListener();@@ -74,6 +80,7 @@ export async function initSharing({ io: socketIo } = {}) {export async function shutdownSharing() {await shutdownAllWatchers();sharingEvents.removeAllListeners();+ peerSyncEvents.removeAllListeners();initialized = false;io = null;}diff --git a/server/services/sharing/peerSync.js b/server/services/sharing/peerSync.jsindex 0366358f6e..dd32964e1e 100644--- a/server/services/sharing/peerSync.js+++ b/server/services/sharing/peerSync.js@@ -33,6 +33,7 @@import { join, basename } from 'path';import { existsSync } from 'fs';+import { EventEmitter } from 'events';import { PATHS, atomicWrite, readJSONFile, ensureDir, sha256File } from '../../lib/fileUtils.js';import { isStr } from '../../lib/storyBible.js';import { isPlainObject } from '../../lib/objects.js';@@ -54,6 +55,16 @@ import {export const PEER_SUBSCRIBABLE_KINDS = Object.freeze(['universe', 'series']);+/**+ * Cross-cutting event bus for the peer-sync receiver. The asset-pull worker+ * emits `asset-arrived` ({ filename, kind, peerId }) when a previously-missing+ * file lands locally; `sharing/index.js` wires that to a socket emission so+ * the client's MediaImage component can swap its "syncing" placeholder for+ * the real bytes without polling.+ */+export const peerSyncEvents = new EventEmitter();+peerSyncEvents.setMaxListeners(100);+export const ERR_NOT_FOUND = 'PEER_SYNC_SUBSCRIPTION_NOT_FOUND';export const ERR_VALIDATION = 'PEER_SYNC_SUBSCRIPTION_VALIDATION';const makeErr = (message, code) => Object.assign(new Error(message), { code });@@ -590,6 +601,18 @@ export async function applyIncomingPush(payload) {recordId: record.id,}).catch(() => false);+ // Schedule background pulls for every asset we're missing. The sender just+ // told us they have these files — fetch them via their `/data/{kind-dir}/`+ // static mount (acceptRanges enabled so resumes work over flaky Tailnet).+ // Fire-and-forget so the push response isn't blocked on a slow pull; the+ // worker emits a socket event when each asset lands so the UI can swap+ // the MediaImage placeholder for the real bytes.+ if (missingAssets.length > 0) {+ pullMissingAssetsFromPeer(sourceInstanceId, missingAssets).catch((err) => {+ console.log(`⚠️ peerSync: asset pull from ${sourceInstanceId} failed: ${err.message}`);+ });+ }+return {missingAssets,reverseSubscriptionCreated,@@ -626,6 +649,144 @@ async function maybeCreateReverseSubscription({ peerId, recordKind, recordId })return true;}+// --- Receiver-side asset pull worker ------------------------------------++const ASSET_KIND_TO_URL_PREFIX = Object.freeze({+ image: '/data/images',+ 'image-ref': '/data/image-refs',+ video: '/data/videos',+});++const ASSET_PULL_TIMEOUT_MS = 60000;+const ASSET_PULL_MAX_BYTES = 100 * 1024 * 1024; // 100MB hard cap per asset++// In-flight pull dedup. A peer can push multiple records that reference the+// same asset in quick succession (universe edit → child collection re-link+// → series under that universe), and without this guard we'd kick off+// duplicate downloads of the same UUID-named PNG — wasting bandwidth,+// doubling the 100MB memory ceiling per asset, and racing on the same+// destination filename. Key on (peerId, kind, filename) so concurrent+// pushes from DIFFERENT peers for the same filename are still allowed+// (e.g. peer-A re-renders and peer-B caches the old bytes — we want the+// newer-pushing peer to win, and the snapshot-sync safety net catches+// any divergence).+const inflightPulls = new Set();+function inflightKey(peerId, kind, filename) {+ return `${peerId}:${kind}:${filename}`;+}++/**+ * Background-fetch every asset in `missingAssets` from the named peer's+ * static `/data/{kind-dir}/` mount, writing each to the local PATHS dir for+ * that kind. Emits `peerSyncEvents 'asset-arrived'` per file so the client's+ * MediaImage placeholder can swap to the live asset.+ *+ * Each fetch is best-effort: a single failure does NOT abort the others, and+ * the asset will be retried on the next push cycle (since the receiver will+ * still report it as missing). The 60s loop's snapshot path also catches+ * up if push-driven pulls keep failing — defense in depth.+ *+ * Stage 4 keeps this simple — sequential per-asset fetches, no parallelism+ * cap. A future enhancement could pool 2-4 concurrent fetches if individual+ * universes routinely ship hundreds of assets.+ */+async function pullMissingAssetsFromPeer(senderInstanceId, missingAssets) {+ if (!isStr(senderInstanceId) || !Array.isArray(missingAssets) || missingAssets.length === 0) return;+ // Trust posture: `senderInstanceId` arrives in the push payload (the route+ // is Tailnet-only per the project's documented threat model — see+ // CLAUDE.md "Security Model"). We DON'T derive it from the TCP origin+ // because Express behind Tailscale loses that fidelity to the SO_REUSEADDR+ // socket. The guard below means even a payload that *spoofs* a different+ // peer's id can only redirect the asset pull at one of our OWN registered+ // peers — `findPeerById` returns null for any unknown id, aborting the+ // pull. So the worst case is fetching from peer-B when peer-A actually+ // pushed; both are trusted Tailnet peers, the fetch either succeeds (we+ // get the bytes peer-A wanted us to have) or 404s (we re-request next+ // push cycle). Outside the Tailnet trust boundary, the right answer is+ // mutual TLS or an HMAC over the payload — explicitly out of scope for+ // PortOS's stated security model.+ const peer = await findPeerById(senderInstanceId);+ if (!peer) {+ console.log(`⚠️ peerSync: can't pull assets — peer ${senderInstanceId} not in registry`);+ return;+ }+ const base = peerBaseUrl(peer);+ for (const entry of missingAssets) {+ await pullOneAsset(peer, base, entry).catch((err) => {+ console.log(`⚠️ peerSync: asset pull ${entry.filename} from ${peer.name || senderInstanceId} failed: ${err.message}`);+ });+ }+}++async function pullOneAsset(peer, base, entry) {+ const urlPrefix = ASSET_KIND_TO_URL_PREFIX[entry.kind];+ const localDir = directoryForAssetKind(entry.kind);+ // Re-validate the filename here even though the receiver already+ // sanitized it in diffAssetManifestAgainstLocal — belt-and-suspenders+ // against any future refactor that bypasses the diff path.+ const safeName = sanitizeAssetFilename(entry.filename);+ if (!urlPrefix || !localDir || !safeName) return;+ // Dedup in-flight pulls — if the same (peer, kind, filename) is already+ // being downloaded, skip rather than starting a second concurrent pull.+ // The first pull's `asset-arrived` event will resolve the UI for both+ // the original triggering push AND any subsequent push that wanted the+ // same bytes.+ const key = inflightKey(peer.instanceId, entry.kind, safeName);+ if (inflightPulls.has(key)) return;+ inflightPulls.add(key);+ try {+ await doPullOneAsset(peer, base, entry, urlPrefix, localDir, safeName);+ } finally {+ inflightPulls.delete(key);+ }+}++async function doPullOneAsset(peer, base, entry, urlPrefix, localDir, safeName) {+ const url = `${base}${urlPrefix}/${encodeURIComponent(safeName)}`;+ const controller = new AbortController();+ const timeoutId = setTimeout(() => controller.abort(), ASSET_PULL_TIMEOUT_MS);+ const res = await peerFetch(url, { signal: controller.signal })+ .finally(() => clearTimeout(timeoutId));+ if (!res || !res.ok) return;+ // Size-cap enforcement: REQUIRE a trustworthy content-length header up+ // front and refuse the pull if missing or over-cap. Without the header+ // we'd have to buffer the whole response before checking buffer.length,+ // which defeats the cap (a hostile peer could ship a 10GB file under a+ // small filename and OOM the receiver before the check runs). Express's+ // `serve-static` always sets content-length for static files (verified+ // by the `acceptRanges: true` mount config in server/index.js), so this+ // is enforceable in the real deployment path.+ const contentLength = Number(res.headers.get('content-length'));+ if (!Number.isFinite(contentLength) || contentLength < 0) {+ console.log(`⚠️ peerSync: asset ${safeName} has no content-length — refusing pull`);+ return;+ }+ if (contentLength > ASSET_PULL_MAX_BYTES) {+ console.log(`⚠️ peerSync: asset ${safeName} too large (${contentLength}) — refusing pull`);+ return;+ }+ const buffer = Buffer.from(await res.arrayBuffer());+ // Defense in depth: the server claimed length X but actually sent more+ // (shouldn't happen with serve-static, but content-length is just a+ // header). Refuse to write the partial / over-cap result.+ if (buffer.length > ASSET_PULL_MAX_BYTES || buffer.length !== contentLength) {+ console.log(`⚠️ peerSync: asset ${safeName} length mismatch (header=${contentLength}, body=${buffer.length}) — refusing pull`);+ return;+ }+ await ensureDir(localDir);+ const fullPath = join(localDir, safeName);+ // atomicWrite (temp + rename) so a crash mid-write doesn't leave a+ // half-written file that subsequent `diffAssetManifestAgainstLocal`+ // calls would see as "present" and stop re-requesting.+ await atomicWrite(fullPath, buffer);+ peerSyncEvents.emit('asset-arrived', {+ filename: safeName,+ kind: entry.kind,+ peerId: peer.instanceId,+ });+ console.log(`📥 peerSync: pulled ${entry.kind}/${safeName} from ${peer.name || peer.instanceId} (${buffer.length} bytes)`);+}+// --- Listener install + debounced trigger -------------------------------const pendingTimers = new Map(); // subId → Timeout