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([sharing-v2-per-sender-subscription-filenames]): include senderInstanceId in subscription filenames
[._.]/ Adam Eivye46d55a88b80
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 8131add2a9..326985bdfc 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -20,6 +20,10 @@- **Removed duplicate Universe Builder tab.** The MediaGen tab strip no longer shows a Universe Builder entry — the Create sidebar already links straight to `/universe-builder`. Legacy `/media/universe-builder/*` URLs redirect to the top-level routes so bookmarks keep working.+### Sharing++- **Per-sender subscription filenames.** `subscriptionFilename()` now includes the sender's instance id in the bucket-side filename (`sub-<kind>-<recordId>-<senderInstanceId>.json`) so two peers subscribed to the same series/universe don't clobber each other's deterministic share files. Inbox dedup keys on `(recordKind, recordId, senderInstanceId)` so a peer's update no longer wipes the other peer's inbox row. `unsubscribe` best-effort cleans up the pre-v2 sender-less filename when its `senderInstanceId` matches this instance, leaving any other peer's pre-upgrade file intact. New `legacySubscriptionFilename` export for the legacy name. Touched `server/services/sharing/{manifest,subscriptions,importer,exporter}.js` + tests.+## Changed- **Universe Builder — starter idea is no longer capped at 4000 chars.** The starter idea is whatever the user wants to type, from a one-line pitch to a full treatment. The Zod-backed `STARTER_PROMPT_MAX` is raised to 200,000 chars (a sanity ceiling, not an artificial brevity constraint) and the textarea's `maxLength={4000}` attribute is removed.diff --git a/server/services/sharing/exporter.js b/server/services/sharing/exporter.jsindex 5830bfb371..764a940b18 100644--- a/server/services/sharing/exporter.js+++ b/server/services/sharing/exporter.js@@ -288,8 +288,9 @@ function stampOrigin(record, { bucket, source, sourceBio, manifestId }) {** `opts.subscription` (optional): when set to `{ recordKind, recordId }` the* manifest is marked as a subscription — bucket-side filename becomes- * deterministic (`sub-series-<id>.json`) so re-exports overwrite in place- * instead of accumulating. Omit for one-shot legacy shares.+ * deterministic (`sub-series-<id>-<senderInstanceId>.json`) so re-exports+ * overwrite in place instead of accumulating, and two peers sharing the same+ * series don't collide on the bucket file. Omit for one-shot legacy shares.*/export async function exportSeries(seriesId, bucketId, opts = {}) {const bucket = await getBucket(bucketId);diff --git a/server/services/sharing/importer.js b/server/services/sharing/importer.jsindex dfd9679c87..2b546b4101 100644--- a/server/services/sharing/importer.js+++ b/server/services/sharing/importer.js@@ -391,8 +391,10 @@ const INBOX_MAX = 1000;* Inbox mode: write the manifest + record refs to the bucket's inbox for review.** For subscription manifests we replace any prior inbox entry for the same- * (recordKind, recordId) so a sender's repeated edits don't pile up as N- * inbox items — the user always sees the latest snapshot. One-shot manifests+ * (recordKind, recordId, senderInstanceId) so a sender's repeated edits don't+ * pile up as N inbox items — the user always sees that sender's latest+ * snapshot. Two peers sharing the same record produce two distinct inbox rows+ * (the per-sender filenames keep them apart on disk). One-shot manifests* dedup by manifest id.*/async function applyInbox(bucket, manifest, manifestFilename, records) {@@ -400,9 +402,11 @@ async function applyInbox(bucket, manifest, manifestFilename, records) {inbox.items = Array.isArray(inbox.items) ? inbox.items : [];const sub = manifest.subscription;if (sub?.recordKind && sub?.recordId) {+ const senderId = manifest.senderInstanceId || null;inbox.items = inbox.items.filter((it) => !(it.subscription&& it.subscription.recordKind === sub.recordKind- && it.subscription.recordId === sub.recordId));+ && it.subscription.recordId === sub.recordId+ && (it.senderInstanceId || null) === senderId));} else if (inbox.items.some((it) => it.manifestId === manifest.id)) {return { queued: false, reason: 'already-in-inbox' };}diff --git a/server/services/sharing/integration.test.js b/server/services/sharing/integration.test.jsindex 6c97e38bbe..373474c051 100644--- a/server/services/sharing/integration.test.js+++ b/server/services/sharing/integration.test.js@@ -437,7 +437,7 @@ describe('sharing round-trip', () => {// Subscribe — first export writes a deterministic-named file.const sub = await subscribe({ bucketId: bucket.id, recordKind: 'universe', recordId: u.id });- const filename = subscriptionFilename(sub);+ const filename = subscriptionFilename({ ...sub, senderInstanceId: 'test-instance-id' });const filePath = join(tempBucket, 'manifests', filename);const fs = await import('fs');expect(fs.existsSync(filePath)).toBe(true);@@ -487,7 +487,9 @@ describe('sharing round-trip', () => {const exp = await exporter.exportUniverse(u.id, bucket.id, {subscription: { recordKind: 'universe', recordId: u.id },});- expect(exp.filename).toBe(subscriptionFilename({ recordKind: 'universe', recordId: u.id }));+ expect(exp.filename).toBe(subscriptionFilename({+ recordKind: 'universe', recordId: u.id, senderInstanceId: 'test-instance-id',+ }));await universeBuilder.deleteUniverse(u.id);expect(await listSubscriptions({ recordKind: 'universe', recordId: u.id })).toEqual([]);diff --git a/server/services/sharing/manifest.js b/server/services/sharing/manifest.jsindex f262de69f2..1f5225387d 100644--- a/server/services/sharing/manifest.js+++ b/server/services/sharing/manifest.js@@ -181,17 +181,33 @@ export function buildManifest({* Filename a manifest lives under inside `<bucket>/manifests/`.** For subscription manifests we use a deterministic name keyed on the- * (recordKind, recordId, bucketId) tuple so re-exports overwrite the same- * file — bucket recipients see updates via chokidar `change` events, not as- * accumulating new files. For one-shot manifests we use the legacy+ * (recordKind, recordId, senderInstanceId) tuple so re-exports overwrite the+ * same file — bucket recipients see updates via chokidar `change` events, not+ * as accumulating new files. Including the senderInstanceId means two peers+ * each subscribed to the same record write to distinct files instead of+ * clobbering each other. For one-shot manifests we use the legacy* `<iso-ts>-<source>-<uuid>.json` naming so the watcher's add-order remains* lexicographically deterministic.*/+/** Filename prefix shared by every subscription manifest, regardless of+ * schema version. The prune filter at `pruneBucketManifests` uses this same+ * prefix to exempt subscription manifests from archive cleanup. */+export const SUBSCRIPTION_FILE_PREFIX = 'sub-';+/** Filename for a subscription manifest. Used by both the writer (exporter)* and the reader (subscriptions service, watcher) so the formula stays in- * one place. */-export function subscriptionFilename({ recordKind, recordId }) {- return `sub-${recordKind}-${recordId}.json`;+ * one place. The `senderInstanceId` segment keeps two peers' shares of the+ * same record from colliding; absent senderInstanceId falls back to+ * `'unknown'` so the filename is always valid. */+export function subscriptionFilename({ recordKind, recordId, senderInstanceId }) {+ const sender = (isStr(senderInstanceId) ? senderInstanceId.trim() : '') || 'unknown';+ return `${SUBSCRIPTION_FILE_PREFIX}${recordKind}-${recordId}-${sender}.json`;+}++/** Legacy pre-sharing-v2 subscription filename — kept so we can clean up the+ * old file when a peer upgrades and switches to the per-sender name. */+export function legacySubscriptionFilename({ recordKind, recordId }) {+ return `${SUBSCRIPTION_FILE_PREFIX}${recordKind}-${recordId}.json`;}export function manifestFilename(manifest) {@@ -199,7 +215,11 @@ export function manifestFilename(manifest) {return annotationManifestFilename(manifest.senderInstanceId);}if (manifest.subscription?.recordKind && manifest.subscription?.recordId) {- return subscriptionFilename(manifest.subscription);+ return subscriptionFilename({+ recordKind: manifest.subscription.recordKind,+ recordId: manifest.subscription.recordId,+ senderInstanceId: manifest.senderInstanceId,+ });}const ts = manifest.createdAt.replace(/[:.]/g, '-');const senderSlug = (manifest.source || manifest.senderInstanceId || 'unknown')@@ -303,7 +323,7 @@ export async function pruneBucketManifests(bucket, opts = {}) {const manifestsDir = join(bucket.path, 'manifests');const entries = await readdir(manifestsDir).catch(() => []);const candidates = entries- .filter((f) => f.endsWith('.json') && !f.startsWith('sub-') && !f.startsWith('annotations-'))+ .filter((f) => f.endsWith('.json') && !f.startsWith(SUBSCRIPTION_FILE_PREFIX) && !f.startsWith('annotations-')).sort();// Fast path: if the total candidate count is at or below the cap, no read// of any manifest is necessary — owned count cannot exceed total.diff --git a/server/services/sharing/manifest.test.js b/server/services/sharing/manifest.test.jsindex 578402e5ee..b91f4078f4 100644--- a/server/services/sharing/manifest.test.js+++ b/server/services/sharing/manifest.test.js@@ -236,19 +236,42 @@ describe('sharing/manifest', () => {});});- it('manifestFilename is deterministic when subscription is set', () => {+ it('manifestFilename is deterministic per-sender when subscription is set', () => {const m = manifest.buildManifest({- kind: 'universe', source: 'me', bucketId: 'b1', bucketName: 'c',+ kind: 'universe', source: 'me', senderInstanceId: 'inst-A',+ bucketId: 'b1', bucketName: 'c',recordIds: [], assetRefs: [],subscription: { recordKind: 'universe', recordId: 'uni-abc-123' },});- expect(manifest.manifestFilename(m)).toBe('sub-universe-uni-abc-123.json');- // Same record → same filename regardless of timestamp.+ expect(manifest.manifestFilename(m)).toBe('sub-universe-uni-abc-123-inst-A.json');+ // Same record + same sender → same filename regardless of timestamp.const m2 = manifest.buildManifest({- kind: 'universe', source: 'me', bucketId: 'b1', bucketName: 'c',+ kind: 'universe', source: 'me', senderInstanceId: 'inst-A',+ bucketId: 'b1', bucketName: 'c',recordIds: [], assetRefs: [],subscription: { recordKind: 'universe', recordId: 'uni-abc-123' },});expect(manifest.manifestFilename(m2)).toBe(manifest.manifestFilename(m));});++ it('manifestFilename produces distinct names for two peers sharing the same record', () => {+ const peerA = manifest.buildManifest({+ kind: 'universe', source: 'A', senderInstanceId: 'inst-A',+ bucketId: 'b1', bucketName: 'c', recordIds: [], assetRefs: [],+ subscription: { recordKind: 'universe', recordId: 'uni-shared' },+ });+ const peerB = manifest.buildManifest({+ kind: 'universe', source: 'B', senderInstanceId: 'inst-B',+ bucketId: 'b1', bucketName: 'c', recordIds: [], assetRefs: [],+ subscription: { recordKind: 'universe', recordId: 'uni-shared' },+ });+ expect(manifest.manifestFilename(peerA)).not.toBe(manifest.manifestFilename(peerB));+ expect(manifest.manifestFilename(peerA)).toBe('sub-universe-uni-shared-inst-A.json');+ expect(manifest.manifestFilename(peerB)).toBe('sub-universe-uni-shared-inst-B.json');+ });++ it('legacySubscriptionFilename returns the pre-v2 sender-less name', () => {+ expect(manifest.legacySubscriptionFilename({ recordKind: 'series', recordId: 'ser-1' }))+ .toBe('sub-series-ser-1.json');+ });});diff --git a/server/services/sharing/subscriptions.js b/server/services/sharing/subscriptions.jsindex be4fbdaf43..c0a182fcfc 100644--- a/server/services/sharing/subscriptions.js+++ b/server/services/sharing/subscriptions.js@@ -15,7 +15,8 @@* Subscriptions are local-only state (data/sharing/subscriptions.json) — the* bucket itself only holds the deterministic manifest file. Multiple peers* may both be subscribing the same bucket; each writes their own- * sub-<kind>-<recordId>.json with their own source attribution.+ * sub-<kind>-<recordId>-<senderInstanceId>.json with their own source+ * attribution, so two peers sharing the same record don't collide.*/import { join } from 'path';@@ -35,7 +36,8 @@ import {// Re-export so existing callers (importer.js etc.) keep their import path// stable; the canonical implementation now lives in recordEvents.js.export { withReexportSuppressed };-import { subscriptionFilename } from './manifest.js';+import { subscriptionFilename, legacySubscriptionFilename } from './manifest.js';+import { getInstanceId } from '../instances.js';// Re-export from the canonical source so other modules can import the// filename helper from either side without forcing a manifest.js import.@@ -185,15 +187,32 @@ export async function unsubscribe(id) {// path may be unmounted; the subscription record removal still wins so the// user's "I want to stop sharing" intent is honored regardless. Importers// on other peers see the file vanish via chokidar `unlink`.+ //+ // Also clean up the pre-sharing-v2 legacy filename (`sub-<kind>-<id>.json`)+ // if it exists AND was authored by THIS instance — a peer that subscribed+ // pre-upgrade and unsubscribed post-upgrade would otherwise leave a phantom+ // file in the bucket. Read the file's `senderInstanceId` before unlinking+ // so we don't stomp on a different peer's pre-upgrade share.const bucket = await getBucket(sub.bucketId).catch(() => null);if (bucket) {- const filename = subscriptionFilename(sub);+ const myInstanceId = await getInstanceId().catch(() => null);+ const filename = subscriptionFilename({ ...sub, senderInstanceId: myInstanceId });const filePath = join(bucket.path, 'manifests', filename);if (existsSync(filePath)) {await unlink(filePath).catch((err) => {console.log(`⚠️ sharing.subscriptions: failed to remove ${filePath}: ${err.message}`);});}+ const legacyName = legacySubscriptionFilename(sub);+ const legacyPath = join(bucket.path, 'manifests', legacyName);+ if (existsSync(legacyPath)) {+ const legacy = await readJSONFile(legacyPath, null, { logError: false });+ if (legacy && (!legacy.senderInstanceId || legacy.senderInstanceId === myInstanceId)) {+ await unlink(legacyPath).catch((err) => {+ console.log(`⚠️ sharing.subscriptions: failed to remove legacy ${legacyPath}: ${err.message}`);+ });+ }+ }}state.subscriptions.splice(idx, 1);diff --git a/server/services/sharing/subscriptions.test.js b/server/services/sharing/subscriptions.test.jsindex bc13ef9c88..cd70e9d43a 100644--- a/server/services/sharing/subscriptions.test.js+++ b/server/services/sharing/subscriptions.test.js@@ -54,11 +54,16 @@ describe('sharing/subscriptions', () => {expect(sub.lastManifestId).toBeTruthy();const fs = await import('fs');- const filename = subs.subscriptionFilename({ recordKind: 'universe', recordId: u.id });- expect(filename).toBe(`sub-universe-${u.id}.json`);+ const filename = subs.subscriptionFilename({ recordKind: 'universe', recordId: u.id, senderInstanceId: 'inst-test' });+ expect(filename).toBe(`sub-universe-${u.id}-inst-test.json`);expect(fs.existsSync(join(tempBucket, 'manifests', filename))).toBe(true);});+ it('subscriptionFilename falls back to "unknown" sender when missing', async () => {+ const filename = subs.subscriptionFilename({ recordKind: 'series', recordId: 'ser-x' });+ expect(filename).toBe('sub-series-ser-x-unknown.json');+ });+it('subscribe is idempotent — second call re-exports onto the same file with a new manifestId', async () => {const bucket = await buckets.createBucket({ name: 'B', path: tempBucket });const u = await universeBuilder.createUniverse({ name: 'U2' });@@ -75,7 +80,7 @@ describe('sharing/subscriptions', () => {const bucket = await buckets.createBucket({ name: 'B', path: tempBucket });const u = await universeBuilder.createUniverse({ name: 'U3' });const sub = await subs.subscribe({ bucketId: bucket.id, recordKind: 'universe', recordId: u.id });- const filename = subs.subscriptionFilename(sub);+ const filename = subs.subscriptionFilename({ ...sub, senderInstanceId: 'inst-test' });const filePath = join(tempBucket, 'manifests', filename);const fs = await import('fs');expect(fs.existsSync(filePath)).toBe(true);@@ -85,6 +90,32 @@ describe('sharing/subscriptions', () => {expect(await subs.listSubscriptions()).toEqual([]);});+ it('unsubscribe also cleans up the pre-sharing-v2 legacy filename when authored by this instance', async () => {+ const bucket = await buckets.createBucket({ name: 'B', path: tempBucket });+ const u = await universeBuilder.createUniverse({ name: 'U-legacy' });+ const fs = await import('fs');++ const sub = await subs.subscribe({ bucketId: bucket.id, recordKind: 'universe', recordId: u.id });+ const legacyPath = join(tempBucket, 'manifests', `sub-universe-${u.id}.json`);+ fs.writeFileSync(legacyPath, JSON.stringify({ senderInstanceId: 'inst-test' }));++ await subs.unsubscribe(sub.id);+ expect(fs.existsSync(legacyPath)).toBe(false);+ });++ it('unsubscribe preserves a legacy filename authored by a DIFFERENT peer', async () => {+ const bucket = await buckets.createBucket({ name: 'B', path: tempBucket });+ const u = await universeBuilder.createUniverse({ name: 'U-legacy-other' });+ const fs = await import('fs');++ const sub = await subs.subscribe({ bucketId: bucket.id, recordKind: 'universe', recordId: u.id });+ const legacyPath = join(tempBucket, 'manifests', `sub-universe-${u.id}.json`);+ fs.writeFileSync(legacyPath, JSON.stringify({ senderInstanceId: 'some-other-peer' }));++ await subs.unsubscribe(sub.id);+ expect(fs.existsSync(legacyPath)).toBe(true);+ });+it('listSubscriptions filters by bucketId / recordKind / recordId', async () => {const bucket1 = await buckets.createBucket({ name: 'A', path: tempBucket });const bucket2Path = mkdtempSync(join(tmpdir(), 'portos-subs-b2-'));