Skip to content

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

feat(sharing): universe shares include the linked collection + auto-flow on new images

[._.]/ Adam Eivy2ccb8833777c
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 1df2f8993c..4e526c029d 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -2,6 +2,44 @@
## Added
+- **Sharing v1.4 — universe shares include the collection + new peer images flow in.**
+ Sharing a universe now bundles the linked media collection ("Universe:
+ <name>" — the bucket of images the user generated via Universe Builder),
+ so recipients see those images alongside the universe instead of an
+ empty canon. Two pieces:
+ - **Explicit `universeId` field on `mediaCollections`.** The universe-
+ builder route now stamps the link at create time
+ (`findOrCreateCollectionByName({ ..., universeId })`); legacy
+ "Universe: <name>" collections get lazy-backfilled when the route
+ re-uses them. Replaces the prior name-only convention so subsequent
+ universe renames don't break the link.
+ - **Exporter bundles the collection.** `exportUniverse` (and
+ `exportSeries` when its series links a universe) finds the linked
+ collection, includes a `manifest.collection` payload
+ `{ name, universeId, items }`, and walks every item's asset
+ filename + associated media-job record into the bucket. Recipients'
+ importer find-or-creates a local collection by `universeId` and
+ unions the items in (existing `ERR_DUPLICATE` semantics dedup so
+ repeated processing is a no-op).
+ - **Mutation triggers re-export.** `mediaCollections.addItem` /
+ `removeItem` now emit `recordEvents('updated', 'universe',
+ universeId)` when the collection carries a `universeId`. The
+ subscription listener picks this up with the same 3-second debounce
+ as record edits, so new images generated locally for a subscribed
+ universe auto-flow to the bucket without the user re-clicking
+ Share.
+ - **Inbox UI shows the count.** Inbox entries now display
+ "+ N collection items (Universe: <name>)" alongside the asset
+ count so the user knows what they're accepting on promote.
+
+ **Files:** `mediaCollections.js` (universeId field + emits on
+ add/remove), `routes/universeBuilder.js` (pass universeId on create),
+ `sharing/exporter.js` (linked-collection lookup + bundle helper),
+ `sharing/manifest.js` (manifest.collection field), `sharing/importer.js`
+ (mergeCollectionPayload + inbox surfacing), `Sharing.jsx` (inbox UI).
+ Test: new integration round-trip covers export → delete locally →
+ import → collection + items + assets all restored.
+
- **Sharing v1.3 — subscriptions: toggle on/off, updates auto-flow.**
Rewrote the share-bucket model from one-shot manifests to persistent
subscriptions, addressing two real UX gaps:
diff --git a/PLAN.md b/PLAN.md
index c4e252d518..ee66718668 100644
--- a/PLAN.md
+++ b/PLAN.md
@@ -6,15 +6,18 @@ For project goals, see [GOALS.md](./GOALS.md). For completed work, see [DONE.md]
## Next Up
-### Cross-network sharing via cloud-synced folders ("Share Buckets") — v1.3 shipped
+### Cross-network sharing via cloud-synced folders ("Share Buckets") — v1.4 shipped
-V1 landed: buckets, ShareToButton on Pipeline + UniverseBuilder + MediaCollection, OriginBadge, exporter with full gen-metadata fidelity, importer with `auto-merge` + `inbox` modes, chokidar watcher, configurable `sharingDisplayName` source attribution, nav-manifest registration. V1.1: id-preserving inserts (`insertSeriesWithId` / `insertIssueWithId` / `insertUniverseWithId`) so re-shares LWW-merge instead of duplicating; `overridden[]` outcome surfaced via socket → global `useSharingNotifications` toast; round-trip integration tests. V1.2: schema versioning — `SHARING_SCHEMA_VERSION` stamped on every manifest + bucket.json, `producedByVersion` (PortOS app version) on every manifest, importer refuses future-version manifests with a clear toast + cursor-mark, bucket cards warn when remote schema > local. V1.3: subscription model for series + universe — toggle on/off in ShareToButton with real state indicators, persistent (bucket, record) tuples in `data/sharing/subscriptions.json`, deterministic-filename manifests that overwrite on re-export, auto-re-export on edit via `recordEvents` (debounced 3s), `unlink` → `handleUnshare` flow that propagates "stop sharing" to recipients without reverting their local copies, content-aware cursor (`processedById` map). See `~/.claude/plans/new-high-priority-task-valiant-wall.md` for design. Remaining follow-ups:
+V1 landed: buckets, ShareToButton on Pipeline + UniverseBuilder + MediaCollection, OriginBadge, exporter with full gen-metadata fidelity, importer with `auto-merge` + `inbox` modes, chokidar watcher, configurable `sharingDisplayName` source attribution, nav-manifest registration. V1.1: id-preserving inserts (`insertSeriesWithId` / `insertIssueWithId` / `insertUniverseWithId`) so re-shares LWW-merge instead of duplicating; `overridden[]` outcome surfaced via socket → global `useSharingNotifications` toast; round-trip integration tests. V1.2: schema versioning — `SHARING_SCHEMA_VERSION` stamped on every manifest + bucket.json, `producedByVersion` (PortOS app version) on every manifest, importer refuses future-version manifests with a clear toast + cursor-mark, bucket cards warn when remote schema > local. V1.3: subscription model for series + universe — toggle on/off in ShareToButton with real state indicators, persistent (bucket, record) tuples in `data/sharing/subscriptions.json`, deterministic-filename manifests that overwrite on re-export, auto-re-export on edit via `recordEvents` (debounced 3s), `unlink` → `handleUnshare` flow that propagates "stop sharing" to recipients without reverting their local copies, content-aware cursor (`processedById` map). V1.4: collection-aware universe shares — `mediaCollections.universeId` field links a collection to its parent universe, exporter bundles the collection (record + items + assets + media-job records) when a universe is shared, importer find-or-creates the local collection and unions the items in, item-add/remove emits `recordEvents` on the linked universe so subscriptions auto-re-export when peer adds new images. See `~/.claude/plans/new-high-priority-task-valiant-wall.md` for design. Remaining follow-ups:
- [ ] **Per-instance display-name fallback inside the Sharing page.** Settings save flow currently lives on the Sharing page top strip; mirror it into the existing Settings tab structure (`client/src/components/settings/`) so the field is discoverable from both surfaces.
- [ ] **Manifest archive pruning.** A bucket lived long enough accumulates thousands of manifests under `<bucket>/manifests/`. Add a per-bucket retention policy (e.g. keep last 500 manifests, archive the rest into `manifests/.archive/` or drop entirely once cursor advances past them).
- [ ] **Route-level tests for `server/routes/sharing.js`.** Bucket CRUD + export + inbox actions + subscriptions are exercised through the service layer in integration.test.js + subscriptions.test.js, but the HTTP surface (Zod rejection, error mapping) is uncovered. Add a `server/routes/sharing.test.js` to lock the JSON contract.
- [ ] **Auto-unsubscribe on local record delete.** Today if the user deletes a subscribed series/universe, the subscription in `data/sharing/subscriptions.json` becomes an orphan — next re-export attempt logs an error but the entry persists. Hook `deleteSeries` / `deleteUniverse` to call `unsubscribe()` for every subscription where `recordId === id`. Surface the unshare in the UI so the user sees "Removed from N bucket(s)" alongside the deletion toast.
- [ ] **Inbox UI: visually mark subscription items.** New inbox entries already carry `subscription: { recordKind, recordId }` when applicable, but the Sharing page renders them identically to one-shot manifest items. Add a small "🔄 live" badge to subscription rows so the user sees "this is the latest snapshot of a live share" vs "this is a one-time snapshot."
+- [ ] **Per-peer subscription filenames for bidirectional collaboration.** Today both peers writing to the same subscription clobber each other's manifest because the filename is `sub-<kind>-<recordId>.json`. Change to `sub-<kind>-<recordId>-<senderInstanceId>.json` so each peer owns their own file; the recipient's importer merges every peer's payload into local state. Without this, peers receive each other's items via the import path but cannot push their own contributions back unless only one peer is the "owner."
+- [ ] **Item-removal semantics across peers.** Collection items are unioned via `addItem` (additive only — `ERR_DUPLICATE` swallowed). When a peer removes an item from their local collection their re-exported manifest no longer lists it; for single-owner the recipient's collection still contains the item because no one tells it to drop. Decide whether to model removals as tombstones in the manifest, or treat the local collection as union-of-all-peer-sets. Probably tombstones — simpler mental model.
+- [ ] **Same collection-export pattern for pipeline series with auto-collections.** Series renders that get auto-filed into a per-series collection (if/when that exists) should also flow through `manifest.collection`. Today only the universe → collection link is bundled.
- [ ] **Content-addressed asset dedup.** Today asset copies skip-if-filename-exists. Hash-based dedup would let multiple manifests share the same blob even when filenames differ.
- [ ] **Extend `syncOrchestrator` to cover pipeline/universe over Tailscale.** Separate ticket from buckets — same-network peers on Tailscale should be able to sync these categories without going through a bucket.
- [ ] **Multi-hop provenance chains.** Re-share authors a fresh `origin` block; chain[] would preserve full attribution. Defer until users ask.
diff --git a/client/src/pages/Sharing.jsx b/client/src/pages/Sharing.jsx
index dd36ac0d40..1f63271772 100644
--- a/client/src/pages/Sharing.jsx
+++ b/client/src/pages/Sharing.jsx
@@ -503,7 +503,12 @@ function Inboxlist({ bucket, items, onPromote, onDismiss }) {
))}
</ul>
) : null}
- {item.assetCount ? <div className="text-[11px] text-gray-500 mt-1">{item.assetCount} asset{item.assetCount === 1 ? '' : 's'}</div> : null}
+ <div className="text-[11px] text-gray-500 mt-1 flex flex-wrap gap-3">
+ {item.assetCount ? <span>{item.assetCount} asset{item.assetCount === 1 ? '' : 's'}</span> : null}
+ {item.collectionItemCount ? (
+ <span>+ {item.collectionItemCount} collection item{item.collectionItemCount === 1 ? '' : 's'}{item.collectionName ? ` (${item.collectionName})` : ''}</span>
+ ) : null}
+ </div>
</div>
<div className="flex flex-col gap-1">
<button
diff --git a/server/routes/universeBuilder.js b/server/routes/universeBuilder.js
index b4a8705edc..8b98d57e34 100644
--- a/server/routes/universeBuilder.js
+++ b/server/routes/universeBuilder.js
@@ -315,6 +315,7 @@ router.post('/:id/render', asyncHandler(async (req, res) => {
const collection = await findOrCreateCollectionByName({
name: collectionName.slice(0, COLLECTION_NAME_MAX),
description: `Universe Builder renders for "${universe.name}"`,
+ universeId: universe.id,
});
const runId = randomUUID();
diff --git a/server/services/mediaCollections.js b/server/services/mediaCollections.js
index 16eff5712e..b36c7af852 100644
--- a/server/services/mediaCollections.js
+++ b/server/services/mediaCollections.js
@@ -15,6 +15,7 @@ import { randomUUID } from 'crypto';
import { PATHS, atomicWrite, readJSONFile, ensureDir } from '../lib/fileUtils.js';
import { ITEM_KIND, REF_MAX_LENGTH, itemKey } from '../lib/mediaItemKey.js';
import { sanitizeOrigin } from '../lib/sharingOrigin.js';
+import { emitRecordUpdated } from './sharing/recordEvents.js';
const STATE_PATH = join(PATHS.data, 'media-collections.json');
@@ -52,6 +53,8 @@ const sanitizeItem = (raw) => {
return out;
};
+const UNIVERSE_ID_MAX = 80;
+
const sanitizeCollection = (raw) => {
if (!raw || typeof raw !== 'object') return null;
if (typeof raw.id !== 'string' || !raw.id) return null;
@@ -80,9 +83,15 @@ const sanitizeCollection = (raw) => {
const coverKey = typeof raw.coverKey === 'string' && seen.has(raw.coverKey)
? raw.coverKey
: null;
+ // Optional link to a universe — used by share-bucket subscriptions to
+ // know which universe-record's subscription should re-export when this
+ // collection's items change.
+ const universeId = typeof raw.universeId === 'string' && raw.universeId
+ ? raw.universeId.slice(0, UNIVERSE_ID_MAX)
+ : null;
const createdAt = typeof raw.createdAt === 'string' ? raw.createdAt : new Date().toISOString();
const updatedAt = typeof raw.updatedAt === 'string' ? raw.updatedAt : createdAt;
- return { id: raw.id, name, description, coverKey, items, createdAt, updatedAt };
+ return { id: raw.id, name, description, coverKey, universeId, items, createdAt, updatedAt };
};
export async function listCollections() {
@@ -141,7 +150,12 @@ export async function createCollection({ name, description = '' }) {
// Find an existing collection by case-insensitive trimmed name, else create
// a fresh one. Lets repeat-render callers (Universe Builder) append into a
// single per-world bucket without growing a new collection on every run.
-export async function findOrCreateCollectionByName({ name, description = '' }) {
+//
+// `universeId`, when provided, stamps the collection so share-bucket
+// subscriptions know which universe-record to notify when items change.
+// If the matched existing collection lacks `universeId`, it's backfilled
+// from the caller's value so the link is established on next access.
+export async function findOrCreateCollectionByName({ name, description = '', universeId = null }) {
const trimmed = typeof name === 'string' ? name.trim() : '';
if (!trimmed || trimmed.length > NAME_MAX_LENGTH) {
throw makeErr('Collection name is required (1..' + NAME_MAX_LENGTH + ' chars)', ERR_VALIDATION);
@@ -152,13 +166,24 @@ export async function findOrCreateCollectionByName({ name, description = '' }) {
const all = await listCollections();
const needle = trimmed.toLowerCase();
const existing = all.find((c) => c.name.toLowerCase() === needle);
- if (existing) return existing;
+ 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];
+ }
+ return existing;
+ }
const now = new Date().toISOString();
const next = {
id: randomUUID(),
name: trimmed,
description: trimmedDescription,
coverKey: null,
+ universeId: universeId || null,
items: [],
createdAt: now,
updatedAt: now,
@@ -227,6 +252,7 @@ export async function addItem(id, item) {
const next = [...all];
next[idx] = merged;
await writeAll(next);
+ if (merged.universeId) emitRecordUpdated('universe', merged.universeId);
return merged;
}
@@ -250,5 +276,6 @@ export async function removeItem(id, key) {
const next = [...all];
next[idx] = merged;
await writeAll(next);
+ if (merged.universeId) emitRecordUpdated('universe', merged.universeId);
return merged;
}
diff --git a/server/services/sharing/exporter.js b/server/services/sharing/exporter.js
index 30f48ac6d1..1dab82c5b7 100644
--- a/server/services/sharing/exporter.js
+++ b/server/services/sharing/exporter.js
@@ -22,6 +22,7 @@ import { buildManifest, writeManifest } from './manifest.js';
import { listSeries, getSeries } from '../pipeline/series.js';
import { listIssues } from '../pipeline/issues.js';
import { getUniverse } from '../universeBuilder.js';
+import { listCollections } from '../mediaCollections.js';
import { getJob } from '../mediaJobQueue/index.js';
import { getInstanceId } from '../instances.js';
import { getSettings } from '../settings.js';
@@ -164,6 +165,48 @@ function collectAssetReferences(record) {
};
}
+/**
+ * Find the media collection linked to a universe. Prefers the explicit
+ * `universeId` field on the collection (added by the universe-builder
+ * route); falls back to matching the conventional `Universe: <name>`
+ * name. Returns null when nothing's linked.
+ */
+async function findCollectionForUniverse(universe) {
+ if (!universe?.id) return null;
+ const all = await listCollections().catch(() => []);
+ const direct = all.find((c) => c.universeId === universe.id);
+ if (direct) return direct;
+ const conventional = `universe: ${(universe.name || '').toLowerCase()}`;
+ return all.find((c) => (c.name || '').toLowerCase() === conventional) || null;
+}
+
+/**
+ * Walk a collection's items and return:
+ * - assetFilenames: every {kind, ref} pair to copy into the bucket
+ * - jobIds: every media-job record the items resolve to (for re-render
+ * metadata fidelity on the recipient side — same logic as imageJobId
+ * resolution on canon entries)
+ *
+ * The serialized `collection` payload in the manifest carries the raw
+ * items + the linked universeId + the canonical name; the recipient's
+ * importer reuses these to find-or-create a local collection of the
+ * same name and add the items.
+ */
+function collectCollectionAssets(collection) {
+ const assetFilenames = [];
+ const jobIds = new Set();
+ if (!collection) return { assetFilenames, jobIds: [] };
+ for (const it of collection.items || []) {
+ if (!it?.ref || typeof it.ref !== 'string') continue;
+ assetFilenames.push({ kind: it.kind, ref: it.ref });
+ // Strip extension to recover the media-job id (matches the convention
+ // used in exportMedia's lookup path: filenames are `<jobId>.<ext>`).
+ const baseId = it.ref.replace(/\.[a-z0-9]+$/i, '');
+ if (baseId && baseId !== it.ref) jobIds.add(baseId);
+ }
+ return { assetFilenames, jobIds: [...jobIds] };
+}
+
/** Stamp the outgoing record with origin metadata. */
function stampOrigin(record, { bucket, source, sourceBio, manifestId }) {
return {
@@ -193,8 +236,10 @@ export async function exportSeries(seriesId, bucketId, opts = {}) {
const series = await getSeries(seriesId);
const issues = await listIssues({ seriesId });
let universe = null;
+ let linkedCollection = null;
if (series.universeId) {
universe = await getUniverse(series.universeId).catch(() => null);
+ if (universe) linkedCollection = await findCollectionForUniverse(universe);
}
const [source, sourceBio, senderInstanceId, producedByVersion] = await Promise.all([
@@ -211,6 +256,7 @@ export async function exportSeries(seriesId, bucketId, opts = {}) {
source, sourceBio,
producedByVersion,
subscription: opts.subscription || null,
+ collection: linkedCollection,
bucketId: bucket.id,
bucketName: bucket.name,
recordIds: [],
@@ -235,7 +281,9 @@ export async function exportSeries(seriesId, bucketId, opts = {}) {
await atomicWrite(join(bucket.path, 'records', 'universes', `${universe.id}.json`), stampedUni);
}
- // Gather asset refs across every record.
+ // Gather asset refs across every record, plus the universe's linked
+ // collection items (if any) so universe-render output ships alongside
+ // the series.
const allJobIds = new Set();
const allImageFiles = new Set();
const allVideoFiles = new Set();
@@ -245,6 +293,13 @@ export async function exportSeries(seriesId, bucketId, opts = {}) {
refs.directImageFilenames.forEach((f) => allImageFiles.add(f));
refs.directVideoFilenames.forEach((f) => allVideoFiles.add(f));
}
+ if (linkedCollection) {
+ const collAssets = collectCollectionAssets(linkedCollection);
+ collAssets.jobIds.forEach((j) => allJobIds.add(j));
+ for (const a of collAssets.assetFilenames) {
+ if (a.kind === 'video') allVideoFiles.add(a.ref); else allImageFiles.add(a.ref);
+ }
+ }
// Copy media-job records + their assets — run all three groups in parallel.
const mediaRecordsDir = join(bucket.path, 'records', 'media');
@@ -265,6 +320,7 @@ export async function exportUniverse(universeId, bucketId, opts = {}) {
const bucket = await getBucket(bucketId);
await ensureBucketLayout(bucket);
const universe = await getUniverse(universeId);
+ const linkedCollection = await findCollectionForUniverse(universe);
const [source, sourceBio, senderInstanceId, producedByVersion] = await Promise.all([
resolveSourceName(bucket),
@@ -279,6 +335,7 @@ export async function exportUniverse(universeId, bucketId, opts = {}) {
source, sourceBio,
producedByVersion,
subscription: opts.subscription || null,
+ collection: linkedCollection,
bucketId: bucket.id,
bucketName: bucket.name,
recordIds: [],
@@ -289,13 +346,26 @@ export async function exportUniverse(universeId, bucketId, opts = {}) {
const stamped = stampOrigin(universe, { bucket, source, sourceBio, manifestId });
await atomicWrite(join(bucket.path, 'records', 'universes', `${universe.id}.json`), stamped);
- const refs = collectAssetReferences(universe);
+ // Combine universe-record asset refs with the linked collection's assets
+ // so a single export pass pulls everything the universe needs.
+ const universeRefs = collectAssetReferences(universe);
+ const collectionAssets = collectCollectionAssets(linkedCollection);
+ const allJobIds = new Set([...universeRefs.jobIds, ...collectionAssets.jobIds]);
+ const allImageFiles = new Set([
+ ...universeRefs.directImageFilenames,
+ ...collectionAssets.assetFilenames.filter((a) => a.kind === 'image').map((a) => a.ref),
+ ]);
+ const allVideoFiles = new Set(
+ collectionAssets.assetFilenames.filter((a) => a.kind === 'video').map((a) => a.ref),
+ );
+
const mediaRecordsDir = join(bucket.path, 'records', 'media');
- const [jobRefGroups, imageRefs] = await Promise.all([
- Promise.all(refs.jobIds.map((jobId) => exportMediaJobAndAsset(jobId, bucket.path, mediaRecordsDir))),
- Promise.all(refs.directImageFilenames.map((f) => copyAssetIfPresent(f, 'image', bucket.path))),
+ const [jobRefGroups, imageRefs, videoRefs] = await Promise.all([
+ Promise.all([...allJobIds].map((jobId) => exportMediaJobAndAsset(jobId, bucket.path, mediaRecordsDir))),
+ Promise.all([...allImageFiles].map((f) => copyAssetIfPresent(f, 'image', bucket.path))),
+ Promise.all([...allVideoFiles].map((f) => copyAssetIfPresent(f, 'video', bucket.path))),
]);
- const assetRefs = [...jobRefGroups.flat(), ...imageRefs.filter(Boolean)];
+ const assetRefs = [...jobRefGroups.flat(), ...imageRefs.filter(Boolean), ...videoRefs.filter(Boolean)];
const manifest = { ...manifestStub, recordIds: [universe.id], assetRefs };
const filename = await writeManifest(bucket.path, manifest);
diff --git a/server/services/sharing/importer.js b/server/services/sharing/importer.js
index 2489169c72..1148b42e6e 100644
--- a/server/services/sharing/importer.js
+++ b/server/services/sharing/importer.js
@@ -28,6 +28,7 @@ import { SHARING_SCHEMA_VERSION, isManifestCompatible } from './version.js';
import { insertSeriesWithId, updateSeries, getSeries } from '../pipeline/series.js';
import { insertIssueWithId, updateIssue, getIssue } from '../pipeline/issues.js';
import { insertUniverseWithId, updateUniverse, getUniverse } from '../universeBuilder.js';
+import { findOrCreateCollectionByName, addItem as addCollectionItem, ERR_DUPLICATE as COLLECTION_ERR_DUPLICATE } from '../mediaCollections.js';
const isStr = (v) => typeof v === 'string';
@@ -50,6 +51,41 @@ function remoteWins(localTs, remoteTs) {
return (remoteTs || '') > (localTs || '');
}
+/**
+ * Merge a manifest's `collection` payload into local state. Find-or-create
+ * the collection by `universeId` (with name as a fallback), then add each
+ * remote item via `addItem` — `ERR_DUPLICATE` errors are expected and
+ * swallowed (the item already exists locally; nothing to do).
+ *
+ * The asset blobs are NOT copied here — `copyAssetsLocally` (called in
+ * `processManifest`) already pulled every `assetRefs[]` entry, which
+ * includes the collection items. This function only persists the local
+ * collection record so the items show up in the user's UI.
+ */
+async function mergeCollectionPayload(payload) {
+ if (!payload?.universeId || !Array.isArray(payload.items)) return { itemsAdded: 0 };
+ const collection = await findOrCreateCollectionByName({
+ name: payload.name || `Universe: ${payload.universeId}`,
+ description: payload.description || '',
+ universeId: payload.universeId,
+ }).catch((err) => {
+ console.log(`⚠️ sharing.importer: findOrCreateCollectionByName failed: ${err.message}`);
+ return null;
+ });
+ if (!collection) return { itemsAdded: 0 };
+ let added = 0;
+ for (const item of payload.items) {
+ if (!item?.kind || !item?.ref) continue;
+ const result = await addCollectionItem(collection.id, item).catch((err) => {
+ if (err?.code === COLLECTION_ERR_DUPLICATE) return null;
+ console.log(`⚠️ sharing.importer: addCollectionItem failed for ${item.ref}: ${err.message}`);
+ return null;
+ });
+ if (result) added += 1;
+ }
+ return { itemsAdded: added };
+}
+
/** Copy bundled assets from the bucket into local data dirs. Runs in parallel. */
async function copyAssetsLocally(bucketPath, assetRefs) {
await ensureDir(PATHS.images);
@@ -184,7 +220,17 @@ async function applyAutoMerge(bucket, manifest, records) {
});
}
- return { applied, overridden };
+ // Universe shares can carry a linked media collection payload. Items
+ // are unioned into a local "Universe: <name>" collection so peer-
+ // generated images appear alongside the universe in the recipient's UI.
+ let itemsAdded = 0;
+ if (manifest.collection) {
+ const r = await mergeCollectionPayload(manifest.collection);
+ itemsAdded = r.itemsAdded;
+ if (itemsAdded > 0) applied += itemsAdded;
+ }
+
+ return { applied, overridden, collectionItemsAdded: itemsAdded };
}
const INBOX_MAX = 1000;
@@ -221,6 +267,8 @@ async function applyInbox(bucket, manifest, manifestFilename, records) {
receivedAt: new Date().toISOString(),
recordIds: manifest.recordIds,
assetCount: (manifest.assetRefs || []).length,
+ collectionItemCount: manifest.collection?.items?.length || 0,
+ collectionName: manifest.collection?.name || null,
note: manifest.note,
summary: summarizeRecords(records),
});
diff --git a/server/services/sharing/integration.test.js b/server/services/sharing/integration.test.js
index 4b97d5259f..891d0b5127 100644
--- a/server/services/sharing/integration.test.js
+++ b/server/services/sharing/integration.test.js
@@ -185,6 +185,52 @@ describe('sharing round-trip', () => {
expect(r2.reason).toBe('already-processed');
});
+ it('universe export bundles the linked collection — recipient gains the items', async () => {
+ const bucket = await buckets.createBucket({ name: 'CollabBucket', path: tempBucket, mode: 'auto-merge' });
+ const universeBuilder = await import('../universeBuilder.js');
+ const mediaCollections = await import('../mediaCollections.js');
+ const u = await universeBuilder.createUniverse({ name: 'Linked Universe' });
+
+ // Pretend universe-builder rendered two images and filed them into a
+ // collection. Each item.ref points at a real file in tempData/images
+ // (we seeded 'fakeasset.png' in beforeEach, but for variety, add another).
+ const fs = await import('fs');
+ fs.writeFileSync(join(tempData, 'images', 'second.png'), 'PNG2');
+ const collection = await mediaCollections.findOrCreateCollectionByName({
+ name: `Universe: ${u.name}`, description: 'Linked', universeId: u.id,
+ });
+ await mediaCollections.addItem(collection.id, { kind: 'image', ref: 'fakeasset.png' });
+ await mediaCollections.addItem(collection.id, { kind: 'image', ref: 'second.png' });
+
+ // Export the universe — manifest should carry the collection payload
+ // and assets should land in the bucket.
+ const exp = await exporter.exportUniverse(u.id, bucket.id);
+ expect(exp.assetCount).toBeGreaterThanOrEqual(2);
+ const manifestFile = exp.filename;
+ const manifest = JSON.parse(fs.readFileSync(join(tempBucket, 'manifests', manifestFile), 'utf-8'));
+ expect(manifest.collection).toMatchObject({ universeId: u.id });
+ expect(manifest.collection.items).toHaveLength(2);
+ expect(fs.existsSync(join(tempBucket, 'assets', 'images', 'second.png'))).toBe(true);
+
+ // Drop the local collection + universe, then re-process: the importer
+ // should recreate both, find-or-create the local collection by
+ // universeId, and merge the items in.
+ await mediaCollections.deleteCollection(collection.id);
+ await universeBuilder.deleteUniverse(u.id);
+ expect((await mediaCollections.listCollections()).find((c) => c.universeId === u.id)).toBeUndefined();
+
+ const r = await importer.processManifest(bucket.id, manifestFile);
+ expect(r.processed).toBe(true);
+ expect(r.outcome.collectionItemsAdded).toBe(2);
+
+ const localCollections = await mediaCollections.listCollections();
+ const restoredCollection = localCollections.find((c) => c.universeId === u.id);
+ expect(restoredCollection).toBeTruthy();
+ expect(restoredCollection.items.map((i) => i.ref).sort()).toEqual(['fakeasset.png', 'second.png']);
+ // Asset blobs are back in the local data/images pool.
+ expect(fs.existsSync(join(tempData, 'images', 'second.png'))).toBe(true);
+ });
+
it('subscription round-trip: subscribe → mutate → re-export onto same filename → unsubscribe → unshared event', async () => {
const { subscribe, unsubscribe, subscriptionFilename, __resetForTests } = await import('./subscriptions.js');
const { sharingEvents } = await import('./importer.js');
diff --git a/server/services/sharing/manifest.js b/server/services/sharing/manifest.js
index 833e860212..476324ff3b 100644
--- a/server/services/sharing/manifest.js
+++ b/server/services/sharing/manifest.js
@@ -135,7 +135,7 @@ export function hasBeenProcessed(cursor, manifestFilename, manifestId = null) {
*/
export function buildManifest({
kind, senderInstanceId, source, sourceBio, recordIds, assetRefs,
- bucketId, bucketName, note, producedByVersion, subscription,
+ bucketId, bucketName, note, producedByVersion, subscription, collection,
}) {
if (!MANIFEST_KIND.includes(kind)) throw new Error(`buildManifest: invalid kind '${kind}'`);
return {
@@ -155,6 +155,17 @@ export function buildManifest({
bucketName: bucketName || bucketId,
recordIds: Array.isArray(recordIds) ? recordIds : [],
assetRefs: Array.isArray(assetRefs) ? assetRefs : [],
+ // Optional payload for universe shares — the linked media collection so
+ // recipients gain the same set of generated images and the link is
+ // restored on their side.
+ collection: collection && collection.universeId && Array.isArray(collection.items)
+ ? {
+ name: collection.name || `Universe: ${collection.universeId}`,
+ universeId: collection.universeId,
+ description: collection.description || '',
+ items: collection.items.map((it) => ({ kind: it.kind, ref: it.ref, addedAt: it.addedAt || null })),
+ }
+ : null,
note: isStr(note) ? note.slice(0, 1000) : null,
};
}