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

simplify(sharing): fix subscription leaks, missing emits, listener overreach

[._.]/ Adam Eivy1ebb65a7d72d
diff --git a/client/src/components/sharing/ShareToButton.jsx b/client/src/components/sharing/ShareToButton.jsx
index 4bc514e757..8ce882b218 100644
--- a/client/src/components/sharing/ShareToButton.jsx
+++ b/client/src/components/sharing/ShareToButton.jsx
@@ -35,6 +35,14 @@ import {
const SUBSCRIBABLE_KINDS = new Set(['series', 'universe']);
+function renderRowIcon({ busy, subscribable, subscribed }) {
+ if (busy) return <Loader2 size={14} className="animate-spin text-port-accent" />;
+ if (!subscribable) return <Check size={14} className="text-gray-600" />;
+ return subscribed
+ ? <CheckCircle2 size={14} className="text-port-success" />
+ : <Circle size={14} className="text-gray-600" />;
+}
+
export default function ShareToButton({ kind, ids, items, label = 'Share', compact = false, className = '' }) {
const [open, setOpen] = useState(false);
const [buckets, setBuckets] = useState([]);
@@ -179,15 +187,7 @@ export default function ShareToButton({ kind, ids, items, label = 'Share', compa
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" />
- ) : isSubscribable ? (
- subscribed
- ? <CheckCircle2 size={14} className="text-port-success" />
- : <Circle size={14} className="text-gray-600" />
- ) : (
- <Check size={14} className="text-gray-600" />
- )}
+ {renderRowIcon({ busy, subscribable: isSubscribable, subscribed })}
</span>
<div className="flex-1 min-w-0">
<div className="text-sm text-white truncate">{b.name}</div>
diff --git a/server/services/pipeline/issues.js b/server/services/pipeline/issues.js
index 31b81d79f2..54df65991b 100644
--- a/server/services/pipeline/issues.js
+++ b/server/services/pipeline/issues.js
@@ -444,10 +444,14 @@ export function updateStage(issueId, stageId, patch = {}) {
export function deleteIssue(id) {
return queueIssueWrite(id, async () => {
const state = await readState();
- const before = state.issues.length;
- state.issues = state.issues.filter((i) => i.id !== id);
- if (state.issues.length === before) throw makeErr(`Issue not found: ${id}`, ERR_NOT_FOUND);
+ const idx = state.issues.findIndex((i) => i.id === id);
+ if (idx < 0) throw makeErr(`Issue not found: ${id}`, ERR_NOT_FOUND);
+ const seriesId = state.issues[idx].seriesId;
+ state.issues.splice(idx, 1);
await writeState(state);
+ // Series export bundles every issue, so a deletion is an update on the
+ // parent series for any active share-bucket subscription.
+ emitRecordUpdated('series', seriesId);
return { id };
}); // end queueIssueWrite
}
diff --git a/server/services/pipeline/series.js b/server/services/pipeline/series.js
index 012626c239..c458a300b2 100644
--- a/server/services/pipeline/series.js
+++ b/server/services/pipeline/series.js
@@ -21,7 +21,7 @@ import {
import { sanitizeArc, sanitizeSeasonList } from '../../lib/storyArc.js';
import { extractBible } from '../../lib/bibleExtractor.js';
import { sanitizeOrigin } from '../../lib/sharingOrigin.js';
-import { emitRecordUpdated } from '../sharing/recordEvents.js';
+import { emitRecordUpdated, emitRecordDeleted } from '../sharing/recordEvents.js';
// Lazy resolution — PATHS.data may not be available at module-load time
// (e.g. tests that swap it through a Proxy mock).
@@ -220,6 +220,7 @@ export async function purgeImageRefFromAllSeries(filename) {
if (!filename || typeof filename !== 'string') return { removed: 0 };
const state = await readState();
let removed = 0;
+ const touchedIds = [];
const nextSeries = state.series.map((s) => {
let touched = false;
const patched = { ...s };
@@ -236,9 +237,15 @@ export async function purgeImageRefFromAllSeries(filename) {
});
if (touched) patched[key] = nextList;
}
+ if (touched) touchedIds.push(s.id);
return touched ? { ...patched, updatedAt: new Date().toISOString() } : s;
});
- if (removed > 0) await writeState({ series: nextSeries });
+ if (removed > 0) {
+ await writeState({ series: nextSeries });
+ // Each touched series is a mutation any active subscription should
+ // propagate to its bucket; otherwise recipients keep stale imageRefs.
+ for (const id of touchedIds) emitRecordUpdated('series', id);
+ }
return { removed };
}
@@ -322,5 +329,8 @@ export async function deleteSeries(id) {
state.series = state.series.filter((s) => s.id !== id);
if (state.series.length === before) throw makeErr(`Series not found: ${id}`, ERR_NOT_FOUND);
await writeState(state);
+ // Any live share-bucket subscription for this series tears itself down via
+ // the recordEvents listener instead of orphaning.
+ emitRecordDeleted('series', id);
return { id };
}
diff --git a/server/services/sharing/importer.js b/server/services/sharing/importer.js
index d323873bbd..2489169c72 100644
--- a/server/services/sharing/importer.js
+++ b/server/services/sharing/importer.js
@@ -345,19 +345,20 @@ export async function handleUnshare(bucketId, manifestFilename) {
const cursor = await readCursor(bucketId);
const wasTracked = manifestFilename in (cursor.processedById || {})
|| (Array.isArray(cursor.processed) && cursor.processed.includes(manifestFilename));
- await forgetProcessed(bucketId, manifestFilename);
-
- // Drop matching inbox entry by manifest filename (subscriptions have stable
- // filenames; one-shot manifests do too, just timestamped — both work).
const inbox = await readInbox(bucketId);
- const before = (inbox.items || []).length;
- inbox.items = (inbox.items || []).filter((it) => it.manifestFilename !== manifestFilename);
- if (inbox.items.length !== before) await writeInbox(bucketId, inbox);
+ const inboxHit = (inbox.items || []).some((it) => it.manifestFilename === manifestFilename);
+ // chokidar fires `unlink` for any file under the watched dir. If we never
+ // saw the filename as a manifest, treat the unlink as noise — no cursor
+ // write, no inbox write, no socket emit.
+ if (!wasTracked && !inboxHit) return { handled: true, wasTracked: false };
- sharingEvents.emit('unshared', { bucketId, manifestFilename });
- if (wasTracked) {
- console.log(`📤 sharing: bucket=${bucketId} manifest=${manifestFilename} unshared by peer`);
+ await forgetProcessed(bucketId, manifestFilename);
+ if (inboxHit) {
+ inbox.items = inbox.items.filter((it) => it.manifestFilename !== manifestFilename);
+ await writeInbox(bucketId, inbox);
}
+ sharingEvents.emit('unshared', { bucketId, manifestFilename });
+ console.log(`📤 sharing: bucket=${bucketId} manifest=${manifestFilename} unshared by peer`);
return { handled: true, wasTracked };
}
diff --git a/server/services/sharing/manifest.js b/server/services/sharing/manifest.js
index 783e14829c..833e860212 100644
--- a/server/services/sharing/manifest.js
+++ b/server/services/sharing/manifest.js
@@ -87,13 +87,16 @@ export async function markProcessed(bucketId, manifestFilename, manifestId = nul
/**
* Remove a filename from the cursor entirely (used on `unlink` so a future
* re-share of the same record under the same filename re-imports cleanly).
+ * No-op short-circuit when the filename isn't tracked — chokidar fires
+ * `unlink` for arbitrary files in the watched dir, not just our manifests.
*/
export async function forgetProcessed(bucketId, manifestFilename) {
const cursor = await readCursor(bucketId);
- if (cursor.processedById[manifestFilename] !== undefined) {
- delete cursor.processedById[manifestFilename];
- }
- cursor.processed = cursor.processed.filter((f) => f !== manifestFilename);
+ const inMap = cursor.processedById && manifestFilename in cursor.processedById;
+ const inLegacy = cursor.processed.includes(manifestFilename);
+ if (!inMap && !inLegacy) return cursor;
+ if (inMap) delete cursor.processedById[manifestFilename];
+ if (inLegacy) cursor.processed = cursor.processed.filter((f) => f !== manifestFilename);
await writeCursor(bucketId, cursor);
return cursor;
}
@@ -166,9 +169,16 @@ export function buildManifest({
* `<iso-ts>-<source>-<uuid>.json` naming so the watcher's add-order remains
* lexicographically deterministic.
*/
+/** 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`;
+}
+
export function manifestFilename(manifest) {
if (manifest.subscription?.recordKind && manifest.subscription?.recordId) {
- return `sub-${manifest.subscription.recordKind}-${manifest.subscription.recordId}.json`;
+ return subscriptionFilename(manifest.subscription);
}
const ts = manifest.createdAt.replace(/[:.]/g, '-');
const senderSlug = (manifest.source || manifest.senderInstanceId || 'unknown')
diff --git a/server/services/sharing/recordEvents.js b/server/services/sharing/recordEvents.js
index 9d7b5b0813..2462e52f08 100644
--- a/server/services/sharing/recordEvents.js
+++ b/server/services/sharing/recordEvents.js
@@ -21,3 +21,9 @@ export function emitRecordUpdated(recordKind, recordId) {
if (!recordKind || !recordId) return;
recordEvents.emit('updated', { recordKind, recordId });
}
+
+/** Local deletion of a subscribed record auto-unsubscribes via the listener. */
+export function emitRecordDeleted(recordKind, recordId) {
+ if (!recordKind || !recordId) return;
+ recordEvents.emit('deleted', { recordKind, recordId });
+}
diff --git a/server/services/sharing/subscriptions.js b/server/services/sharing/subscriptions.js
index 0f337232ef..fa942f2ca1 100644
--- a/server/services/sharing/subscriptions.js
+++ b/server/services/sharing/subscriptions.js
@@ -26,6 +26,11 @@ import { isStr } from '../../lib/storyBible.js';
import { getBucket } from './buckets.js';
import { exportSeries, exportUniverse } from './exporter.js';
import { recordEvents } from './recordEvents.js';
+import { subscriptionFilename } from './manifest.js';
+
+// Re-export from the canonical source so other modules can import the
+// filename helper from either side without forcing a manifest.js import.
+export { subscriptionFilename };
export const SUBSCRIBABLE_KINDS = Object.freeze(['series', 'universe']);
@@ -40,11 +45,6 @@ function subId({ bucketId, recordKind, recordId }) {
return `sub-${recordKind}-${recordId}-${bucketId}`;
}
-/** Deterministic file name in `<bucket>/manifests/` for a subscription. */
-export function subscriptionFilename({ recordKind, recordId }) {
- return `sub-${recordKind}-${recordId}.json`;
-}
-
async function readState() {
await ensureDir(join(PATHS.data, 'sharing'));
const raw = await readJSONFile(STATE_PATH(), { subscriptions: [] }, { logError: false });
@@ -126,6 +126,16 @@ export async function unsubscribe(id) {
if (idx < 0) throw makeErr(`Subscription not found: ${id}`, ERR_NOT_FOUND);
const sub = state.subscriptions[idx];
+ // Cancel any pending debounced re-export — otherwise the timer fires ~3s
+ // later, the sub is gone, and reexportNow no-ops, but the timer + the
+ // reference to its closure linger in the pendingTimers Map until the
+ // setTimeout callback runs.
+ const pending = pendingTimers.get(sub.id);
+ if (pending) {
+ clearTimeout(pending);
+ pendingTimers.delete(sub.id);
+ }
+
// Delete the deterministic file from the bucket. Best-effort: the bucket
// path may be unmounted; the subscription record removal still wins so the
// user's "I want to stop sharing" intent is honored regardless. Importers
@@ -146,6 +156,24 @@ export async function unsubscribe(id) {
return { id, removed: true };
}
+/**
+ * Drop every subscription that targets a given (recordKind, recordId). Used
+ * by the `deleted` recordEvents listener so deleting a series/universe
+ * automatically tears down its outgoing subscriptions instead of leaving
+ * orphaned entries that fail every re-export.
+ */
+export async function unsubscribeAllForRecord(recordKind, recordId) {
+ const matching = await listSubscriptions({ recordKind, recordId });
+ const removed = [];
+ for (const sub of matching) {
+ await unsubscribe(sub.id).catch((err) => {
+ console.log(`⚠️ sharing.subscriptions: auto-unsubscribe failed for ${sub.id}: ${err.message}`);
+ });
+ removed.push(sub.id);
+ }
+ return { removed };
+}
+
/**
* Re-export every subscription for a given (recordKind, recordId). Called by
* the recordEvents listener. Debounced per subscription so a flurry of edits
@@ -184,23 +212,35 @@ export async function reexportSubscribedRecord(recordKind, recordId) {
}
}
-let listenerInstalled = false;
+// Track the listener handles we install so __resetForTests can remove just
+// ours — `removeAllListeners('updated')` would also kill listeners installed
+// by neighboring test files that share the recordEvents bus.
+let onUpdated = null;
+let onDeleted = null;
-/** Attach the recordEvents listener — call once during sharing init. */
+/** Attach the recordEvents listeners — call once during sharing init. */
export function installSubscriptionListener() {
- if (listenerInstalled) return;
- listenerInstalled = true;
- recordEvents.on('updated', ({ recordKind, recordId }) => {
+ if (onUpdated || onDeleted) return;
+ onUpdated = ({ recordKind, recordId }) => {
reexportSubscribedRecord(recordKind, recordId).catch((err) => {
console.log(`⚠️ sharing.subscriptions: listener error for ${recordKind}/${recordId}: ${err.message}`);
});
- });
+ };
+ onDeleted = ({ recordKind, recordId }) => {
+ unsubscribeAllForRecord(recordKind, recordId).catch((err) => {
+ console.log(`⚠️ sharing.subscriptions: delete-listener error for ${recordKind}/${recordId}: ${err.message}`);
+ });
+ };
+ recordEvents.on('updated', onUpdated);
+ recordEvents.on('deleted', onDeleted);
}
-/** Test-only: clear pending debounces and detach the listener so suites can isolate. */
+/** Test-only: clear pending debounces and detach our own listeners. */
export function __resetForTests() {
for (const t of pendingTimers.values()) clearTimeout(t);
pendingTimers.clear();
- recordEvents.removeAllListeners('updated');
- listenerInstalled = false;
+ if (onUpdated) recordEvents.off('updated', onUpdated);
+ if (onDeleted) recordEvents.off('deleted', onDeleted);
+ onUpdated = null;
+ onDeleted = null;
}
diff --git a/server/services/sharing/subscriptions.test.js b/server/services/sharing/subscriptions.test.js
index d068fd086e..f162bfee72 100644
--- a/server/services/sharing/subscriptions.test.js
+++ b/server/services/sharing/subscriptions.test.js
@@ -118,4 +118,33 @@ describe('sharing/subscriptions', () => {
const bucket = await buckets.createBucket({ name: 'B', path: tempBucket });
expect(await subs.findSubscription(bucket.id, 'universe', 'no-such-id')).toBeNull();
});
+
+ it('unsubscribeAllForRecord drops every matching subscription', async () => {
+ const bucket1 = await buckets.createBucket({ name: 'A', path: tempBucket });
+ const bucket2Path = mkdtempSync(join(tmpdir(), 'portos-subs-b2-'));
+ const bucket2 = await buckets.createBucket({ name: 'B', path: bucket2Path });
+ const u = await universeBuilder.createUniverse({ name: 'shared-uni' });
+ await subs.subscribe({ bucketId: bucket1.id, recordKind: 'universe', recordId: u.id });
+ await subs.subscribe({ bucketId: bucket2.id, recordKind: 'universe', recordId: u.id });
+ expect(await subs.listSubscriptions({ recordId: u.id })).toHaveLength(2);
+
+ const result = await subs.unsubscribeAllForRecord('universe', u.id);
+ expect(result.removed).toHaveLength(2);
+ expect(await subs.listSubscriptions({ recordId: u.id })).toEqual([]);
+ rmSync(bucket2Path, { recursive: true, force: true });
+ });
+
+ it('deleting the local record auto-unsubscribes via the deleted recordEvent', async () => {
+ subs.installSubscriptionListener();
+ const bucket = await buckets.createBucket({ name: 'D', path: tempBucket });
+ const u = await universeBuilder.createUniverse({ name: 'to-delete' });
+ await subs.subscribe({ bucketId: bucket.id, recordKind: 'universe', recordId: u.id });
+ expect((await subs.listSubscriptions({ recordId: u.id }))).toHaveLength(1);
+
+ await universeBuilder.deleteUniverse(u.id);
+ // Listener fans out async (readState → unsubscribe → unlink → writeState);
+ // wait one event-loop tick + a small slack for the I/O chain to settle.
+ await new Promise((r) => setTimeout(r, 50));
+ expect(await subs.listSubscriptions({ recordId: u.id })).toEqual([]);
+ });
});
diff --git a/server/services/universeBuilder.js b/server/services/universeBuilder.js
index 9b622ec769..a870590b0e 100644
--- a/server/services/universeBuilder.js
+++ b/server/services/universeBuilder.js
@@ -31,7 +31,7 @@ import {
normalizeBibleName,
} from '../lib/storyBible.js';
import { sanitizeOrigin } from '../lib/sharingOrigin.js';
-import { emitRecordUpdated } from './sharing/recordEvents.js';
+import { emitRecordUpdated, emitRecordDeleted } from './sharing/recordEvents.js';
// Bumped when a sanitizer-time backfill changes how on-disk universes are
// shaped, so future migrations can gate on the prior version.
@@ -636,6 +636,7 @@ export async function deleteUniverse(id) {
// Drop runs referencing the deleted universe — they're useless without it.
state.runs = state.runs.filter((r) => r.universeId !== id);
await writeState(state);
+ emitRecordDeleted('universe', id);
return { id };
}