Skip to content

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

fix: a share refused because this PortOS is too old now says so and imports after the upgrade

Adam Eivy035841444019
diff --git a/client/src/components/NotificationDropdown.jsx b/client/src/components/NotificationDropdown.jsx
index ce8d781ce8..86a3ba45cc 100644
--- a/client/src/components/NotificationDropdown.jsx
+++ b/client/src/components/NotificationDropdown.jsx
@@ -1,7 +1,7 @@
import { useState, useRef, useEffect } from 'react';
import { createPortal } from 'react-dom';
import { useNavigate } from 'react-router';
-import { Bell, X, CheckCheck, Trash2, Brain, ListTodo, AlertTriangle, Code, HelpCircle, BellRing, Film, Sparkles, AlarmClock } from 'lucide-react';
+import { Bell, X, CheckCheck, Trash2, Brain, ListTodo, AlertTriangle, Code, HelpCircle, BellRing, Film, Sparkles, AlarmClock, Share2 } from 'lucide-react';
import { timeAgo, formatCount } from '../utils/formatters';
import { useActionQueue } from '../hooks/useActionQueue';
import ActionQueuePreview from './ActionQueuePreview';
@@ -60,6 +60,11 @@ const NOTIFICATION_TYPE_CONFIG = {
icon: AlarmClock,
color: 'text-port-accent',
bgColor: 'bg-port-accent/20'
+ },
+ share_blocked: {
+ icon: Share2,
+ color: 'text-orange-400',
+ bgColor: 'bg-orange-500/20'
}
};
diff --git a/client/src/hooks/useSharingNotifications.js b/client/src/hooks/useSharingNotifications.js
index 685a744181..699ef73550 100644
--- a/client/src/hooks/useSharingNotifications.js
+++ b/client/src/hooks/useSharingNotifications.js
@@ -2,6 +2,13 @@ import { useEffect } from 'react';
import socket from '../services/socket';
import toast from '../components/ui/Toast';
+const shareSender = (payload) => {
+ const source = payload.source || 'a peer';
+ return payload.producedByVersion && payload.producedByVersion !== 'unknown'
+ ? `${source} (PortOS ${payload.producedByVersion})`
+ : source;
+};
+
/**
* Global subscriber for share-bucket notifications. Mirrors useErrorNotifications:
* mounts once in Layout.jsx so any open page hears about auto-merge updates
@@ -28,20 +35,26 @@ export function useSharingNotifications() {
};
const onIncompatibleManifest = (payload) => {
if (!payload) return;
- const source = payload.source || 'a peer';
- const producedBy = payload.producedByVersion && payload.producedByVersion !== 'unknown'
- ? ` (PortOS ${payload.producedByVersion})`
- : '';
toast.error(
- `Can't import share from ${source}${producedBy} — protocol v${payload.remoteVersion} requires upgrading PortOS (local v${payload.localVersion}).`,
+ `Can't import share from ${shareSender(payload)} — protocol v${payload.remoteVersion} requires upgrading PortOS (local v${payload.localVersion}).`,
+ { duration: 12000 },
+ );
+ };
+ const onSchemaAhead = (payload) => {
+ if (!payload) return;
+ const categories = (payload.ahead || []).map((gap) => gap.category).join(', ') || 'storage';
+ toast.error(
+ `Can't import share from ${shareSender(payload)} yet — it uses a newer ${categories} format. Update PortOS and it imports automatically.`,
{ duration: 12000 },
);
};
socket.on('sharing:manifest-processed', onManifestProcessed);
socket.on('sharing:incompatible-manifest', onIncompatibleManifest);
+ socket.on('sharing:portos-schema-ahead', onSchemaAhead);
return () => {
socket.off('sharing:manifest-processed', onManifestProcessed);
socket.off('sharing:incompatible-manifest', onIncompatibleManifest);
+ socket.off('sharing:portos-schema-ahead', onSchemaAhead);
};
}, []);
}
diff --git a/server/lib/notificationTypes.js b/server/lib/notificationTypes.js
index 70f6dc91ea..34afd3fd02 100644
--- a/server/lib/notificationTypes.js
+++ b/server/lib/notificationTypes.js
@@ -12,7 +12,8 @@ export const NOTIFICATION_CATALOG = {
DAILY_POST_REMINDER: { key: 'daily_post_reminder', label: 'POST Reminders' },
CREATIVE_COMMISSION: { key: 'creative_commission', label: 'Creative Commissions' },
MUSIC_VIDEO_ATTENTION: { key: 'music_video_attention', label: 'Music Video Attention' },
- ACTION_DUE: { key: 'action_due', label: 'Scheduled Actions Due' }
+ ACTION_DUE: { key: 'action_due', label: 'Scheduled Actions Due' },
+ SHARE_BLOCKED: { key: 'share_blocked', label: 'Blocked Shares' }
};
export const NOTIFICATION_TYPES = Object.fromEntries(
diff --git a/server/services/sharing/importer.js b/server/services/sharing/importer.js
index b551cf9d8d..faf30084cb 100644
--- a/server/services/sharing/importer.js
+++ b/server/services/sharing/importer.js
@@ -23,6 +23,7 @@
import { createKeyCachedQueue } from '../../lib/createKeyCachedQueue.js';
import { join, basename } from 'path';
+import { createHash } from 'crypto';
import { readdir } from 'fs/promises';
import { existsSync } from 'fs';
import { EventEmitter } from 'events';
@@ -31,7 +32,7 @@ import { PATHS, copyFileGuarded, ensureDir, atomicWrite, readJSONFile } from '..
import { isSafeRecordId } from '../../lib/validation.js';
import { logFailureWithStack } from '../../lib/failureLogging.js';
import { getBucket, bucketBlobPath, bucketBlobSidecarPath, bucketRecordsDir, bucketRecordPath, imageSidecarName, isHexHash } from './buckets.js';
-import { readManifest, markProcessed, readCursor, hasBeenProcessed, forgetProcessed } from './manifest.js';
+import { readManifest, markProcessed, markRefused, readCursor, hasBeenProcessed, isRefusalCurrent, forgetProcessed } from './manifest.js';
import { SHARING_SCHEMA_VERSION, isManifestCompatible } from './version.js';
import { PORTOS_SCHEMA_VERSIONS, RECORD_KIND_SCHEMA_CATEGORIES, compareSchemaVersions, scopeVersionDiff, formatVersionGap } from '../../lib/schemaVersions.js';
import { insertSeriesWithId, updateSeries, getSeries } from '../pipeline/series.js';
@@ -63,6 +64,18 @@ function isSelfAuthored(senderInstanceId, localInstanceId) {
export const sharingEvents = new EventEmitter();
+// Everything on the receiving side that the two compatibility gates in
+// `processManifest` read. A refusal recorded under this fingerprint stays quiet
+// until an upgrade changes one of them.
+const LOCAL_SCHEMA_FINGERPRINT = createHash('sha256')
+ .update(JSON.stringify({
+ sharing: SHARING_SCHEMA_VERSION,
+ portos: PORTOS_SCHEMA_VERSIONS,
+ categories: RECORD_KIND_SCHEMA_CATEGORIES,
+ }))
+ .digest('hex')
+ .slice(0, 16);
+
const queueInboxWrite = createKeyCachedQueue();
const inboxPath = (bucketId) => join(PATHS.data, 'sharing', 'inbox', `${bucketId}.json`);
@@ -954,6 +967,9 @@ export async function processManifest(bucketId, manifestFilename) {
if (hasBeenProcessed(cursor, manifestFilename, manifest.id)) {
return { skipped: true, reason: 'already-processed' };
}
+ if (isRefusalCurrent(cursor, manifestFilename, manifest.id, LOCAL_SCHEMA_FINGERPRINT)) {
+ return { skipped: true, reason: 'already-refused' };
+ }
// 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.
@@ -967,10 +983,11 @@ export async function processManifest(bucketId, manifestFilename) {
? manifest.sharingSchemaVersion
: (Number.isFinite(manifest.schemaVersion) ? manifest.schemaVersion : null);
if (remoteVersion !== null && !isManifestCompatible(remoteVersion)) {
- // Mark processed so the watcher doesn't replay it on every file event,
- // but emit a clear signal to the UI so the user knows a peer is on a
- // newer protocol and they should upgrade PortOS to consume their shares.
- await markProcessed(bucketId, manifestFilename, manifest.id);
+ // Record the refusal so the watcher doesn't replay it on every file event,
+ // and emit a clear signal so the user knows a peer is on a newer protocol.
+ // The refusal lapses when an upgrade changes this install's schema, so
+ // the share imports on the next backlog walk.
+ await markRefused(bucketId, manifestFilename, manifest.id, LOCAL_SCHEMA_FINGERPRINT);
sharingEvents.emit('incompatible-manifest', {
bucketId, manifestId: manifest.id, manifestFilename,
remoteVersion, localVersion: SHARING_SCHEMA_VERSION,
@@ -983,11 +1000,11 @@ export async function processManifest(bucketId, manifestFilename) {
// PORTOS SCHEMA-VERSION GATE — even when the share-protocol schemaVersion
// is compatible, the manifest's per-category storage layout versions
// (`portosSchemaVersions`, e.g. `{ universes: 5 }`) may exceed what this
- // PortOS can apply. We refuse the import AND mark it processed (see the
- // dedup rationale in the branch below) — so retry-after-upgrade is NOT
- // automatic; the user clears the bucket cursor (or unshare/reshares) once
- // they've upgraded. Emits a `portos-schema-ahead` event the UI uses to
- // render a persistent "Update PortOS to import this share" badge.
+ // PortOS can apply. We refuse the import and record the refusal against
+ // this install's schema (see the dedup rationale in the branch below), so
+ // the first backlog walk after an upgrade retries it. Emits a
+ // `portos-schema-ahead` event; `shareRefusalNotifier.js` turns it into a
+ // persistent "Update PortOS to import this share" bell card.
const senderSchemaVersions = isPlainObject(manifest.portosSchemaVersions)
? manifest.portosSchemaVersions
: {};
@@ -997,14 +1014,13 @@ export async function processManifest(bucketId, manifestFilename) {
const portosFullDiff = compareSchemaVersions(senderSchemaVersions, PORTOS_SCHEMA_VERSIONS);
const portosDiff = scopeVersionDiff(portosFullDiff, relevantSchemaCategoriesForManifest(manifest));
if (portosDiff.ahead.length > 0) {
- // Mark processed so subsequent chokidar fan-outs (every asset/record
+ // Record the refusal so subsequent chokidar fan-outs (every asset/record
// file landing under the bucket triggers a backlog scan that re-walks
// every manifest) don't re-fire this event 100× per bundle. Mirrors
- // the sibling `incompatible-version` branch above. Trade-off: when the
- // user upgrades PortOS, they must clear the cursor entry to retry the
- // import (or unshare/reshare from the sender side). Without this dedup,
- // the event spams logs + the socket channel on every receive cycle.
- await markProcessed(bucketId, manifestFilename, manifest.id);
+ // the sibling `incompatible-version` branch above. The record is bound to
+ // this install's schema fingerprint, so an upgrade lifts it and the
+ // boot backlog walk imports the share without cursor surgery.
+ await markRefused(bucketId, manifestFilename, manifest.id, LOCAL_SCHEMA_FINGERPRINT);
sharingEvents.emit('portos-schema-ahead', {
bucketId, manifestId: manifest.id, manifestFilename,
ahead: portosDiff.ahead,
@@ -1014,7 +1030,7 @@ export async function processManifest(bucketId, manifestFilename) {
});
console.log(
`⚠️ sharing: bucket=${bucket.name} manifest=${manifest.id} — ${formatVersionGap(portosDiff)} ` +
- `(producedBy=${manifest.producedByVersion || 'unknown'}). Update PortOS to import; clear the bucket cursor after upgrade to retry.`,
+ `(producedBy=${manifest.producedByVersion || 'unknown'}). Update PortOS to import — it retries after the upgrade.`,
);
return {
skipped: true,
@@ -1329,6 +1345,7 @@ export async function promoteInboxItem(bucketId, manifestId) {
export async function handleUnshare(bucketId, manifestFilename) {
const cursor = await readCursor(bucketId);
const wasTracked = manifestFilename in (cursor.processedById || {})
+ || manifestFilename in (cursor.refusedById || {})
|| (Array.isArray(cursor.processed) && cursor.processed.includes(manifestFilename));
const inboxHit = await queueInboxWrite(bucketId, async () => {
const inbox = await readInbox(bucketId);
diff --git a/server/services/sharing/index.js b/server/services/sharing/index.js
index bbd8157eb4..22ca479522 100644
--- a/server/services/sharing/index.js
+++ b/server/services/sharing/index.js
@@ -15,6 +15,7 @@ import { installSubscriptionListener } from './subscriptions.js';
import { installPeerSyncListener, uninstallPeerSyncListener, peerSyncEvents, syncMediaLibraryWithAllPeers, syncCosHistoryWithAllPeers, syncCosTasksWithAllPeers, syncEidoverseFoundationsWithAllPeers } from './peerSync.js';
import { hasSubscriptionAdapter } from './recordEvents.js';
import { initAnnotationsSync } from './annotationsSync.js';
+import { installShareRefusalNotifier } from './shareRefusalNotifier.js';
export { sharingEvents } from './importer.js';
export { attachWatcher, detachWatcher, listAttachedWatchers };
@@ -94,6 +95,10 @@ export async function initSharing({ io: socketIo } = {}) {
await ensureDir(join(PATHS.data, 'sharing', 'cursors'));
await ensureDir(join(PATHS.data, 'sharing', 'inbox'));
+ // A share refused because this install is behind reaches the bell even when
+ // no browser is open while the bucket fills.
+ installShareRefusalNotifier(sharingEvents);
+
// Wire socket events for the client UI.
if (io) {
sharingEvents.on('manifest-processed', (payload) => {
diff --git a/server/services/sharing/integration.test.js b/server/services/sharing/integration.test.js
index a788394fad..a473ea63ba 100644
--- a/server/services/sharing/integration.test.js
+++ b/server/services/sharing/integration.test.js
@@ -2186,11 +2186,15 @@ describe('sharing round-trip', () => {
producedByVersion: '9.99.0',
});
- // A second process is dedup'd via the cursor (we marked it processed to
- // prevent the watcher replay loop).
+ // A second process is dedup'd via the cursor's refusal record (prevents the
+ // watcher replay loop) without re-announcing — and without marking it
+ // processed, so an upgraded install can still import it.
const replay = await importer.processManifest(bucket.id, filename);
expect(replay.skipped).toBe(true);
- expect(replay.reason).toBe('already-processed');
+ expect(replay.reason).toBe('already-refused');
+ expect(events).toHaveLength(1);
+ const { readCursor, hasBeenProcessed } = await import('./manifest.js');
+ expect(hasBeenProcessed(await readCursor(bucket.id), filename, futureManifest.id)).toBe(false);
});
it('annotation manifest round-trip: peer record merges into local annotations without touching pipeline records', async () => {
@@ -2439,6 +2443,47 @@ describe('sharing round-trip', () => {
await expect(series.getSeries(s.id)).rejects.toThrow();
});
+ it('a refused manifest stays quiet on replay, then imports once this install is upgraded', async () => {
+ const { sharingEvents } = await import('./importer.js');
+ const { markRefused, readCursor, hasBeenProcessed } = await import('./manifest.js');
+ const bucket = await buckets.createBucket({ name: 'RetryAfterUpgradeBucket', path: tempBucket, mode: 'auto-merge' });
+ const s = await series.createSeries({ name: 'Arrives Early', logline: 'x' });
+ const exp = await exporter.exportSeries(s.id, bucket.id);
+ await series.deleteSeries(s.id);
+ simulateRemoteSender(tempBucket, exp.filename);
+ const manifestPath = join(tempBucket, 'manifests', exp.filename);
+ const manifest = JSON.parse(readFileSync(manifestPath, 'utf-8'));
+ const compatibleVersions = manifest.portosSchemaVersions;
+ manifest.portosSchemaVersions = { ...compatibleVersions, pipelineSeries: 99 };
+ writeFileSync(manifestPath, JSON.stringify(manifest, null, 2));
+
+ const announced = [];
+ const onAhead = (p) => announced.push(p);
+ sharingEvents.on('portos-schema-ahead', onAhead);
+ try {
+ expect((await importer.processManifest(bucket.id, exp.filename)).reason).toBe('portos-schema-ahead');
+ // Every bundle file landing re-walks the backlog: the replay must not
+ // re-announce the same refusal.
+ expect((await importer.processManifest(bucket.id, exp.filename)).reason).toBe('already-refused');
+ expect(announced).toHaveLength(1);
+ } finally {
+ sharingEvents.off('portos-schema-ahead', onAhead);
+ }
+
+ // Upgrade: the refusal was recorded by the previous build's schema, and
+ // the new build reads the sender's layout. The boot backlog re-walk then
+ // imports the share with no manual cursor surgery.
+ await markRefused(bucket.id, exp.filename, manifest.id, 'previous-build-schema');
+ manifest.portosSchemaVersions = compatibleVersions;
+ writeFileSync(manifestPath, JSON.stringify(manifest, null, 2));
+ await importer.processBacklog(bucket.id);
+
+ expect((await series.getSeries(s.id)).id).toBe(s.id);
+ const cursor = await readCursor(bucket.id);
+ expect(hasBeenProcessed(cursor, exp.filename, manifest.id)).toBe(true);
+ expect(cursor.refusedById[exp.filename]).toBeUndefined();
+ });
+
it('importer IMPORTS a manifest when the sender is ahead only on a category the manifest does NOT carry', async () => {
// Per-category gate: a universeless series manifest carries only
// pipelineSeries (+ pipelineIssues for bundled issues). A sender ahead on
diff --git a/server/services/sharing/manifest.js b/server/services/sharing/manifest.js
index 639d51faf5..89c524105e 100644
--- a/server/services/sharing/manifest.js
+++ b/server/services/sharing/manifest.js
@@ -47,6 +47,7 @@ const cursorPath = (bucketId) => join(PATHS.data, 'sharing', 'cursors', `${bucke
* {
* processedById: { '<filename>': '<lastSeenManifestId>' },
* processed: ['<filename>', ...], // legacy: pre-content-aware cursor entries
+ * refusedById: { '<filename>': { manifestId, localSchema } },
* lastProcessedAt: ISO
* }
*
@@ -63,6 +64,7 @@ export async function readCursor(bucketId) {
return {
processedById: (raw.processedById && typeof raw.processedById === 'object') ? raw.processedById : {},
processed: Array.isArray(raw.processed) ? raw.processed : [],
+ refusedById: isPlainObject(raw.refusedById) ? raw.refusedById : {},
lastProcessedAt: raw.lastProcessedAt || null,
};
}
@@ -84,6 +86,7 @@ export async function markProcessed(bucketId, manifestFilename, manifestId = nul
if (cursor.processed.includes(manifestFilename)) {
cursor.processed = cursor.processed.filter((f) => f !== manifestFilename);
}
+ delete cursor.refusedById[manifestFilename];
const keys = Object.keys(cursor.processedById);
if (keys.length > 5000) {
// Drop the lexicographically-smallest 1000 — for timestamp-prefixed
@@ -110,14 +113,38 @@ export async function forgetProcessed(bucketId, manifestFilename) {
const cursor = await readCursor(bucketId);
const inMap = cursor.processedById && manifestFilename in cursor.processedById;
const inLegacy = cursor.processed.includes(manifestFilename);
- if (!inMap && !inLegacy) return cursor;
+ const inRefused = manifestFilename in cursor.refusedById;
+ if (!inMap && !inLegacy && !inRefused) return cursor;
if (inMap) delete cursor.processedById[manifestFilename];
if (inLegacy) cursor.processed = cursor.processed.filter((f) => f !== manifestFilename);
+ if (inRefused) delete cursor.refusedById[manifestFilename];
await writeCursor(bucketId, cursor);
return cursor;
});
}
+/**
+ * Record a manifest this install refused because its own schema is behind the
+ * sender's. Unlike `markProcessed`, the entry is bound to `localSchema` — a
+ * fingerprint of the versions that refused it — so it suppresses the watcher's
+ * replays only until this install's schema changes. The first backlog walk
+ * after an upgrade re-evaluates the manifest and imports it.
+ */
+export async function markRefused(bucketId, manifestFilename, manifestId, localSchema) {
+ return queueCursorWrite(bucketId, async () => {
+ const cursor = await readCursor(bucketId);
+ cursor.refusedById[manifestFilename] = { manifestId: manifestId || '', localSchema };
+ await writeCursor(bucketId, cursor);
+ return cursor;
+ });
+}
+
+/** True when this exact manifest was already refused under the current local schema. */
+export function isRefusalCurrent(cursor, manifestFilename, manifestId, localSchema) {
+ const refusal = cursor?.refusedById?.[manifestFilename];
+ return Boolean(refusal) && refusal.manifestId === (manifestId || '') && refusal.localSchema === localSchema;
+}
+
/**
* Returns true when we've already imported THIS specific version of the
* manifest. For subscription manifests, content-aware: a new manifestId on
diff --git a/server/services/sharing/manifest.test.js b/server/services/sharing/manifest.test.js
index 0e208be8ff..b1266ac050 100644
--- a/server/services/sharing/manifest.test.js
+++ b/server/services/sharing/manifest.test.js
@@ -145,6 +145,27 @@ describe('sharing/manifest', () => {
expect(manifest.hasBeenProcessed(c, 'sub-universe-abc.json', 'mfst-1')).toBe(false);
});
+ it('a refusal is current only for the same manifest under the same local schema, and survives other cursor writes', async () => {
+ await manifest.markRefused('b1', 'ahead.json', 'mfst-1', 'schema-a');
+ // Every import rewrites the cursor; the refusal must survive that rewrite
+ // or each backlog walk re-announces it.
+ await manifest.markProcessed('b1', 'other.json', 'mfst-9');
+ const c = await manifest.readCursor('b1');
+ expect(manifest.isRefusalCurrent(c, 'ahead.json', 'mfst-1', 'schema-a')).toBe(true);
+ expect(manifest.isRefusalCurrent(c, 'ahead.json', 'mfst-1', 'schema-b')).toBe(false);
+ expect(manifest.isRefusalCurrent(c, 'ahead.json', 'mfst-2', 'schema-a')).toBe(false);
+ expect(manifest.hasBeenProcessed(c, 'ahead.json', 'mfst-1')).toBe(false);
+ });
+
+ it('importing or unsharing a refused manifest clears its refusal', async () => {
+ await manifest.markRefused('b1', 'imported.json', 'mfst-1', 'schema-a');
+ await manifest.markRefused('b1', 'unshared.json', 'mfst-2', 'schema-a');
+ await manifest.markProcessed('b1', 'imported.json', 'mfst-1');
+ await manifest.forgetProcessed('b1', 'unshared.json');
+ const c = await manifest.readCursor('b1');
+ expect(c.refusedById).toEqual({});
+ });
+
describe('pruneBucketManifests', () => {
let bucketRoot;
diff --git a/server/services/sharing/shareRefusalNotifier.js b/server/services/sharing/shareRefusalNotifier.js
new file mode 100644
index 0000000000..efaabc6319
--- /dev/null
+++ b/server/services/sharing/shareRefusalNotifier.js
@@ -0,0 +1,64 @@
+/**
+ * Share-refusal notifier.
+ *
+ * The importer refuses a manifest this install is too old to apply — a newer
+ * share protocol (`incompatible-manifest`) or a storage layout ahead of ours on
+ * a category the share carries (`portos-schema-ahead`). Share buckets fill
+ * while nobody is watching, so a socket toast alone is missed: this turns each
+ * refusal into a persistent bell card, one per manifest, retracted once that
+ * manifest imports (after the upgrade) or the sender withdraws it.
+ * Machine-local — `data/notifications.json` is never federated.
+ */
+
+import { addNotification, exists, removeByMetadata, NOTIFICATION_TYPES, PRIORITY_LEVELS } from '../notifications.js';
+
+const KEY_FIELD = 'shareRefusalKey';
+
+const refusalKey = ({ bucketId, manifestFilename }) => `${bucketId}/${manifestFilename}`;
+
+const describeSender = ({ source, producedByVersion }) => {
+ const name = source && source !== 'unknown' ? source : 'A peer';
+ return producedByVersion && producedByVersion !== 'unknown' ? `${name} (PortOS ${producedByVersion})` : name;
+};
+
+const describeGap = (kind, payload) => (kind === 'incompatible-manifest'
+ ? `uses share protocol v${payload.remoteVersion}; this install reads v${payload.localVersion}`
+ : `uses a newer ${(payload.ahead || []).map((gap) => gap.category).join(', ') || 'storage'} format than this install`);
+
+async function notifyShareRefused(kind, payload) {
+ if (!payload?.bucketId || !payload.manifestFilename) return false;
+ const key = refusalKey(payload);
+ if (await exists(NOTIFICATION_TYPES.SHARE_BLOCKED, KEY_FIELD, key)) return false;
+ await addNotification({
+ type: NOTIFICATION_TYPES.SHARE_BLOCKED,
+ title: 'Share needs a PortOS update',
+ description: `A share from ${describeSender(payload)} ${describeGap(kind, payload)}. Update PortOS — it imports it automatically after the update.`,
+ priority: PRIORITY_LEVELS.HIGH,
+ link: `/sharing/buckets/${encodeURIComponent(payload.bucketId)}?tab=activity`,
+ metadata: { [KEY_FIELD]: key, bucketId: payload.bucketId },
+ });
+ return true;
+}
+
+async function clearShareRefusal(payload) {
+ if (!payload?.bucketId || !payload.manifestFilename) return;
+ await removeByMetadata(KEY_FIELD, refusalKey(payload));
+}
+
+/** Wire the importer's refusal and resolution events to the bell. */
+export function installShareRefusalNotifier(sharingEvents) {
+ // EventEmitter listeners run outside any request lifecycle: a rejection here
+ // would be unhandled, so each one is caught and logged.
+ for (const kind of ['incompatible-manifest', 'portos-schema-ahead']) {
+ sharingEvents.on(kind, (payload) => {
+ notifyShareRefused(kind, payload)
+ .catch((err) => console.error(`❌ sharing: refused-share notification failed: ${err.message}`));
+ });
+ }
+ for (const resolved of ['manifest-processed', 'unshared']) {
+ sharingEvents.on(resolved, (payload) => {
+ clearShareRefusal(payload)
+ .catch((err) => console.error(`❌ sharing: refused-share notification cleanup failed: ${err.message}`));
+ });
+ }
+}
diff --git a/server/services/sharing/shareRefusalNotifier.test.js b/server/services/sharing/shareRefusalNotifier.test.js
new file mode 100644
index 0000000000..4dda3db7c7
--- /dev/null
+++ b/server/services/sharing/shareRefusalNotifier.test.js
@@ -0,0 +1,71 @@
+/**
+ * Contract: a share this install refuses because it is behind the sender raises
+ * one persistent bell card per manifest, and the card goes away once that
+ * manifest imports or the sender withdraws it.
+ */
+import { EventEmitter } from 'events';
+import { describe, it, expect, beforeEach, vi } from 'vitest';
+
+vi.mock('../notifications.js', () => ({
+ addNotification: vi.fn().mockResolvedValue({}),
+ exists: vi.fn().mockResolvedValue(false),
+ removeByMetadata: vi.fn().mockResolvedValue({ success: true, removed: 0 }),
+ NOTIFICATION_TYPES: { SHARE_BLOCKED: 'share_blocked' },
+ PRIORITY_LEVELS: { HIGH: 'high' },
+}));
+
+import { installShareRefusalNotifier } from './shareRefusalNotifier.js';
+import { addNotification, exists, removeByMetadata } from '../notifications.js';
+
+const flush = () => new Promise((resolve) => setImmediate(resolve));
+
+let events;
+beforeEach(() => {
+ vi.clearAllMocks();
+ exists.mockResolvedValue(false);
+ events = new EventEmitter();
+ installShareRefusalNotifier(events);
+});
+
+describe('installShareRefusalNotifier', () => {
+ it('raises a card for a share whose storage layout is ahead of this install', async () => {
+ events.emit('portos-schema-ahead', {
+ bucketId: 'bkt-1', manifestId: 'mfst-1', manifestFilename: 'a.json',
+ ahead: [{ category: 'pipelineSeries', senderV: 9, receiverV: 8 }],
+ producedByVersion: '9.1.0', source: 'Example Studio',
+ });
+ await flush();
+ const card = addNotification.mock.calls[0][0];
+ expect(card).toMatchObject({ type: 'share_blocked', link: '/sharing/buckets/bkt-1?tab=activity' });
+ expect(card.description).toContain('Example Studio (PortOS 9.1.0)');
+ expect(card.description).toContain('pipelineSeries');
+ expect(card.description).toContain('imports it automatically');
+ });
+
+ it('raises a card for a share on a newer share protocol', async () => {
+ events.emit('incompatible-manifest', {
+ bucketId: 'bkt-1', manifestId: 'mfst-2', manifestFilename: 'b.json',
+ remoteVersion: 3, localVersion: 2, producedByVersion: 'unknown', source: 'Example Studio',
+ });
+ await flush();
+ const card = addNotification.mock.calls[0][0];
+ expect(card.description).toContain('share protocol v3');
+ expect(card.description).not.toContain('PortOS unknown');
+ });
+
+ it('stays silent when the same manifest is already announced', async () => {
+ exists.mockResolvedValue(true);
+ events.emit('portos-schema-ahead', { bucketId: 'bkt-1', manifestFilename: 'a.json', ahead: [] });
+ await flush();
+ expect(exists).toHaveBeenCalledWith('share_blocked', 'shareRefusalKey', 'bkt-1/a.json');
+ expect(addNotification).not.toHaveBeenCalled();
+ });
+
+ it('retracts the card when the manifest imports or the sender withdraws it', async () => {
+ events.emit('manifest-processed', { bucketId: 'bkt-1', manifestFilename: 'a.json' });
+ events.emit('unshared', { bucketId: 'bkt-1', manifestFilename: 'b.json' });
+ await flush();
+ expect(removeByMetadata).toHaveBeenCalledWith('shareRefusalKey', 'bkt-1/a.json');
+ expect(removeByMetadata).toHaveBeenCalledWith('shareRefusalKey', 'bkt-1/b.json');
+ });
+});