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
fix(sharing): don't surface self-authored shares as pending imports
[._.]/ Adam Eivyc94af9e7d4ec
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex e57584f776..ef8c3fed09 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -41,6 +41,21 @@## Fixed+- **Sharing inbox no longer prompts you to import your own shares.** When the+ local PortOS published a manifest into a share bucket (e.g. a Google Drive+ folder it also reads from), the importer treated the round-tripped file as+ an incoming share from "@you" and queued it as a pending import. The fix+ filters self-authored manifests at import time by comparing+ `manifest.senderInstanceId` against `getInstanceId()` and marks them+ processed so the watcher won't replay them. A backfill prunes any+ pre-existing self-authored items already in `data/sharing/inbox/*.json`+ on the next `processBacklog` pass (which runs on server startup per+ bucket): missing `senderInstanceId` fields are filled from the manifest+ file on disk, then any item matching the local instance id is dropped+ with an `inbox-updated` socket event so the UI clears immediately.+ Touches: `server/services/sharing/importer.js`,+ `server/services/sharing/integration.test.js`.+- **`adoptImportedSubscription` no longer mislabels deliberately-subscribedrecords as imported.** On the update branch, `sub.adoptedFromImport ?? true`flipped `undefined` (a deliberate `subscribe()` result) to `true` the nextdiff --git a/server/services/sharing/importer.js b/server/services/sharing/importer.jsindex 0a4ff03832..34ce4de568 100644--- a/server/services/sharing/importer.js+++ b/server/services/sharing/importer.js@@ -32,9 +32,19 @@ 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';import { adoptImportedSubscription, withReexportSuppressed } from './subscriptions.js';+import { getInstanceId } from '../instances.js';const isStr = (v) => typeof v === 'string';+const UNKNOWN_INSTANCE_ID = 'unknown';++function isSelfAuthored(senderInstanceId, localInstanceId) {+ return !!localInstanceId+ && !!senderInstanceId+ && senderInstanceId !== UNKNOWN_INSTANCE_ID+ && senderInstanceId === localInstanceId;+}+export const sharingEvents = new EventEmitter();const inboxPath = (bucketId) => join(PATHS.data, 'sharing', 'inbox', `${bucketId}.json`);@@ -328,6 +338,7 @@ async function applyInbox(bucket, manifest, manifestFilename, records) {subscription: sub || null,source: manifest.source,sourceBio: manifest.sourceBio,+ senderInstanceId: manifest.senderInstanceId || null,producedByVersion: manifest.producedByVersion || null,sharingSchemaVersion: manifest.sharingSchemaVersion ?? manifest.schemaVersion ?? null,createdAt: manifest.createdAt,@@ -370,6 +381,14 @@ export async function processManifest(bucketId, manifestFilename) {if (hasBeenProcessed(cursor, manifestFilename, manifest.id)) {return { skipped: true, reason: 'already-processed' };}+ // Re-importing our own shares would falsely surface them in the inbox+ // (or no-op merge into their own LWW state). Mark processed so the+ // watcher doesn't replay on every file event.+ const localInstanceId = await getInstanceId().catch(() => null);+ if (isSelfAuthored(manifest.senderInstanceId, localInstanceId)) {+ await markProcessed(bucketId, manifestFilename, manifest.id);+ return { skipped: true, reason: 'self-authored' };+ }// Read schemaVersion (also accepts the descriptive alias sharingSchemaVersion).const remoteVersion = Number.isFinite(manifest.sharingSchemaVersion)? manifest.sharingSchemaVersion@@ -417,9 +436,57 @@ export async function processManifest(bucketId, manifestFilename) {return { processed: true, manifest, outcome };}+/**+ * Drop any inbox items the local instance itself produced. Pre-fix releases+ * could surface self-shares as pending imports; this prunes those on the+ * next backlog pass. Items predating the senderInstanceId field are+ * backfilled by reading the underlying manifest, so the pruning works for+ * legacy inbox state too.+ */+async function pruneSelfAuthoredInbox(bucket, localInstanceId) {+ if (!localInstanceId) return { pruned: 0 };+ const inbox = await readInbox(bucket.id);+ const items = Array.isArray(inbox.items) ? inbox.items : [];+ if (items.length === 0) return { pruned: 0 };++ let changed = false;+ const kept = [];+ for (const it of items) {+ let sender = it.senderInstanceId || null;+ let backfilled = it;+ if (!sender) {+ const m = await readManifest(bucket.path, it.manifestFilename).catch(() => null);+ sender = m?.senderInstanceId || null;+ if (sender) {+ backfilled = { ...it, senderInstanceId: sender };+ changed = true;+ }+ }+ if (isSelfAuthored(sender, localInstanceId)) {+ changed = true;+ continue;+ }+ kept.push(backfilled);+ }+ const pruned = items.length - kept.length;+ if (changed) {+ inbox.items = kept;+ await writeInbox(bucket.id, inbox);+ if (pruned > 0) {+ sharingEvents.emit('inbox-updated', { bucketId: bucket.id });+ console.log(`🧹 sharing: bucket=${bucket.name} pruned ${pruned} self-authored inbox item(s)`);+ }+ }+ return { pruned };+}+/** On startup or registration, scan the manifests dir for unprocessed entries. */export async function processBacklog(bucketId) {const bucket = await getBucket(bucketId);+ const localInstanceId = await getInstanceId().catch(() => null);+ await pruneSelfAuthoredInbox(bucket, localInstanceId).catch((err) => {+ console.log(`⚠️ sharing.importer: pruneSelfAuthoredInbox failed: ${err.message}`);+ });const manifestsDir = join(bucket.path, 'manifests');if (!existsSync(manifestsDir)) return { processed: 0 };const filenames = (await readdir(manifestsDir).catch(() => []))diff --git a/server/services/sharing/integration.test.js b/server/services/sharing/integration.test.jsindex 386a1a7b20..ae8639e035 100644--- a/server/services/sharing/integration.test.js+++ b/server/services/sharing/integration.test.js@@ -53,6 +53,19 @@ const importer = await import('./importer.js');const series = await import('../pipeline/series.js');const issues = await import('../pipeline/issues.js');+// Rewrite a manifest's senderInstanceId on disk so the importer sees it as+// coming from a remote peer. The mocked `getInstanceId` returns the same+// id for both producer and consumer in these tests, but in production+// instance A publishes and instance B imports — `processManifest` now+// short-circuits self-authored manifests, so the round-trip tests must+// flip the sender to simulate a peer.+function simulateRemoteSender(bucketPath, filename, peerId = 'remote-peer-id') {+ const p = join(bucketPath, 'manifests', filename);+ const m = JSON.parse(readFileSync(p, 'utf-8'));+ m.senderInstanceId = peerId;+ writeFileSync(p, JSON.stringify(m, null, 2));+}+describe('sharing round-trip', () => {beforeEach(() => {// Wipe and re-seed the temp data dir + a fake asset for each test.@@ -92,6 +105,7 @@ describe('sharing round-trip', () => {// Process as inbox (the bucket mode is 'inbox'). The manifest should// queue, not auto-apply.+ simulateRemoteSender(tempBucket, exp.filename);const result = await importer.processManifest(bucket.id, exp.filename);expect(result.processed).toBe(true);expect(result.outcome.mode).toBe('inbox');@@ -137,6 +151,7 @@ describe('sharing round-trip', () => {// Drop the local series, then process — auto-merge inserts under preserved id.await series.deleteSeries(s.id);+ simulateRemoteSender(tempBucket, exp.filename);const r1 = await importer.processManifest(bucket.id, exp.filename);expect(r1.outcome.mode).toBe('auto-merge');expect(r1.outcome.applied).toBeGreaterThan(0);@@ -162,6 +177,7 @@ describe('sharing round-trip', () => {writeFileSync(statePath, JSON.stringify(state, null, 2));// Process the new manifest — should LWW-override.+ simulateRemoteSender(tempBucket, exp2.filename);const r2 = await importer.processManifest(bucket.id, exp2.filename);expect(r2.outcome.mode).toBe('auto-merge');expect(r2.outcome.overridden).toHaveLength(1);@@ -176,6 +192,7 @@ describe('sharing round-trip', () => {const s = await series.createSeries({ name: 'X' });const exp = await exporter.exportSeries(s.id, bucket.id);await series.deleteSeries(s.id);+ simulateRemoteSender(tempBucket, exp.filename);const r1 = await importer.processManifest(bucket.id, exp.filename);expect(r1.processed).toBe(true);@@ -219,6 +236,7 @@ describe('sharing round-trip', () => {await universeBuilder.deleteUniverse(u.id);expect((await mediaCollections.listCollections()).find((c) => c.universeId === u.id)).toBeUndefined();+ simulateRemoteSender(tempBucket, manifestFile);const r = await importer.processManifest(bucket.id, manifestFile);expect(r.processed).toBe(true);expect(r.outcome.collectionItemsAdded).toBe(2);@@ -253,6 +271,7 @@ describe('sharing round-trip', () => {await mediaCollections.deleteCollection(collection.id);await universeBuilder.deleteUniverse(u.id);+ simulateRemoteSender(tempBucket, exp.filename);const r = await importer.processManifest(bucket.id, exp.filename);expect(r.processed).toBe(true);expect(r.outcome.collectionItemsAdded).toBe(1);@@ -284,6 +303,7 @@ describe('sharing round-trip', () => {await mediaCollections.deleteCollection(collection.id);await universeBuilder.deleteUniverse(u.id);+ simulateRemoteSender(tempBucket, exp.filename);const first = await importer.processManifest(bucket.id, exp.filename);expect(first.pending).toBe(true);expect(first.outcome.pendingAssets).toEqual([{ kind: 'image', ref: 'late.png' }]);@@ -371,6 +391,7 @@ describe('sharing round-trip', () => {await universeBuilder.deleteUniverse(u.id);expect(await listSubscriptions({ recordKind: 'universe', recordId: u.id })).toEqual([]);+ simulateRemoteSender(tempBucket, exp.filename);const result = await importer.processManifest(bucket.id, exp.filename);expect(result.processed).toBe(true);expect(result.outcome.adoptedSubscription).toMatchObject({@@ -393,6 +414,57 @@ describe('sharing round-trip', () => {expect(subs[0].lastExportedAt).toBe(null);});+ it('skips self-authored manifests on import and prunes pre-existing self-authored inbox items', async () => {+ const { sharingEvents } = await import('./importer.js');+ const bucket = await buckets.createBucket({ name: 'SelfBucket', path: tempBucket, mode: 'inbox' });++ // Author + export a series locally — the manifest is dropped into our own bucket.+ const s = await series.createSeries({ name: 'Mine', logline: 'Local-only' });+ const exp = await exporter.exportSeries(s.id, bucket.id);+ expect(exp.manifestId).toBeTruthy();++ // The watcher would now pick the manifest up. Process it manually and+ // verify it never enters the inbox — `senderInstanceId === localInstanceId`.+ const res = await importer.processManifest(bucket.id, exp.filename);+ expect(res.skipped).toBe(true);+ expect(res.reason).toBe('self-authored');+ expect(await importer.listInbox(bucket.id)).toEqual([]);++ // Second pass is the cursor's already-processed branch.+ const replay = await importer.processManifest(bucket.id, exp.filename);+ expect(replay.skipped).toBe(true);+ expect(replay.reason).toBe('already-processed');++ // Pre-fix bug: simulate a stale inbox entry from before the filter existed+ // (no senderInstanceId field). processBacklog should backfill from the+ // manifest file on disk and prune it.+ const fs = await import('fs');+ const inboxFile = join(tempData, 'sharing', 'inbox', `${bucket.id}.json`);+ mkdirSync(join(tempData, 'sharing', 'inbox'), { recursive: true });+ fs.writeFileSync(inboxFile, JSON.stringify({ items: [{+ manifestId: exp.manifestId,+ manifestFilename: exp.filename,+ kind: 'series',+ subscription: null,+ source: 'antic',+ sourceBio: null,+ createdAt: new Date().toISOString(),+ receivedAt: new Date().toISOString(),+ recordIds: [s.id],+ assetCount: 0,+ }] }));++ const updates = [];+ const onUpdate = (p) => updates.push(p);+ sharingEvents.on('inbox-updated', onUpdate);+ await importer.processBacklog(bucket.id);+ sharingEvents.off('inbox-updated', onUpdate);++ expect(await importer.listInbox(bucket.id)).toEqual([]);+ expect(updates).toHaveLength(1);+ expect(updates[0]).toMatchObject({ bucketId: bucket.id });+ });+it('refuses a manifest with a sharingSchemaVersion newer than local + emits incompatible event', async () => {const { SHARING_SCHEMA_VERSION } = await import('./version.js');const { sharingEvents } = await import('./importer.js');