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(sharing): coalesce universe-builder per-image re-exports

[._.]/ Adam Eivy49329d6f2b2b
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index be8959ef07..993b4ebae2 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -12,6 +12,8 @@
## Fixed
+- **Universe Builder — coalesce per-image share re-exports during a batch render.** When a subscribed universe was rendering a large batch (e.g. 160 prompts), every completed image fired a per-item `emitRecordUpdated('universe', …)` → debounced re-export, walking every historical `imageJobId` in the linked collection and warning for any that aged out of the 24h in-memory media-job archive. The render route now registers each run's job count with `universeBuilderCollectionHook`, which wraps every per-item `addItem` in `withReexportSuppressed` while the run is active and emits a single `emitRecordUpdated` once the last terminal event (completed / failed / canceled) lands. A 160-image batch now schedules one debounced re-export at the end instead of ~one per completion, and the "imageJobId not found in live queue or archive" warnings collapse to a single sweep. Server restart mid-run drops the in-memory tracker entry — the hook falls back to the legacy per-image emits for the rest of that run.
+
- **Media annotations now sync across PortOS instances via shared Drive buckets, with per-author attribution.** Previously, a note or star added on one machine was invisible to peers sharing the same Drive bucket — `data/media-annotations.json` lived purely client-local. Storage is now per-author: each instance owns its own `instanceId` sub-entry under each `<kind>:<ref>` key (`{ authors: { [instanceId]: { authorName, starred, note, updatedAt } } }`), so my notes never clobber yours and vice versa. A new manifest kind (`media-annotations`) carries each instance's annotation snapshot into every auto-merge bucket via a stable filename (`annotations-<instanceId>.json`), debounced 2s after the last local edit. The export is per-bucket scoped to assets actually present in that bucket, so a private annotation can't leak into an unrelated share. On import, peer records merge per-author by `updatedAt` LWW and re-broadcast `media:annotation:updated` so open clients refresh without a reload. Stars are also per-author — "my favorites" remains my view, not a tug-of-war. The lightbox now shows my note in the editable textarea and "Notes from others" as labeled read-only blocks below (with the peer's display name + their star). Migration `012-attribute-existing-annotations.js` rewraps existing notes under the local instance's id on first run.
## Removed
diff --git a/server/routes/universeBuilder.js b/server/routes/universeBuilder.js
index 92bd2ff57c..6f5f550cbe 100644
--- a/server/routes/universeBuilder.js
+++ b/server/routes/universeBuilder.js
@@ -25,6 +25,7 @@ import { refineWorldPrompts } from '../services/universeBuilderRefine.js';
import { enqueueJob } from '../services/mediaJobQueue/index.js';
import { getSettings } from '../services/settings.js';
import { findOrCreateCollectionByName, NAME_MAX_LENGTH as COLLECTION_NAME_MAX } from '../services/mediaCollections.js';
+import { registerUniverseBuilderRun } from '../services/universeBuilderCollectionHook.js';
import { getImageModels, isFlux2, isZImage, isErnie } from '../lib/mediaModels.js';
const router = Router();
@@ -424,6 +425,10 @@ router.post('/:id/render', asyncHandler(async (req, res) => {
createdAt: new Date().toISOString(),
});
+ // Tell the completion hook how many jobs to expect so per-image
+ // emitRecordUpdated calls can be coalesced into one re-export at run end.
+ registerUniverseBuilderRun({ runId, universeId: universe.id, jobCount: jobIds.length });
+
console.log(`🌍 Universe Builder render — universe=${universe.name} prompts=${compiled.length} mode=${mode} runId=${runId.slice(0, 8)}`);
res.json({
diff --git a/server/services/universeBuilderCollectionHook.js b/server/services/universeBuilderCollectionHook.js
index 6a2aad3030..a692318b70 100644
--- a/server/services/universeBuilderCollectionHook.js
+++ b/server/services/universeBuilderCollectionHook.js
@@ -9,31 +9,64 @@
* the lifetime of the process. Failures here are logged but never thrown
* — a bookkeeping miss must not crash the server or fail the user's
* render.
+ *
+ * Re-export coalescing: when the route calls `registerUniverseBuilderRun`
+ * with a job count, every `addItem` for that run is wrapped in
+ * `withReexportSuppressed` so the per-image emits don't each schedule a
+ * debounced re-export of the whole universe. Once the last job in the run
+ * reaches a terminal state (completed/failed/canceled), the hook emits a
+ * single `emitRecordUpdated('universe', …)` and the subscription debounces
+ * one re-export. Server restart mid-run drops the tracker entry — the
+ * hook then falls back to per-image emits (current/legacy behavior) until
+ * the run finishes naturally.
*/
import { mediaJobEvents } from './mediaJobQueue/index.js';
import { addItem, ERR_DUPLICATE } from './mediaCollections.js';
+import { withReexportSuppressed, emitRecordUpdated } from './sharing/recordEvents.js';
+
+// runId → { universeId, pending }. Pure in-memory; lost on restart.
+const activeRuns = new Map();
-let registeredHandler = null;
+export function registerUniverseBuilderRun({ runId, universeId, jobCount }) {
+ if (!runId || !universeId || !Number.isFinite(jobCount) || jobCount <= 0) return;
+ activeRuns.set(runId, { universeId, pending: jobCount });
+}
+
+// Returns the run's universeId when this terminal closes the batch (pending → 0),
+// otherwise null. Callers use the return value as the "fire the final emit" signal.
+function noteTerminal(runId) {
+ const entry = activeRuns.get(runId);
+ if (!entry) return null;
+ entry.pending -= 1;
+ if (entry.pending > 0) return null;
+ activeRuns.delete(runId);
+ return entry.universeId;
+}
+
+let completedHandler = null;
+let terminalHandler = null;
export function initUniverseBuilderCollectionHook() {
// Idempotent: a stray double-init (test reload, future refactor) would
// otherwise register two listeners and double-file every completed image.
- if (registeredHandler) return;
+ if (completedHandler) return;
// EventEmitter does not await async listeners and does not catch their
// rejections — any throw here would surface as an unhandled promise
// rejection (process-killing on Node ≥15). Use a sync listener that
// launches an async IIFE with a top-level catch so this bookkeeping
// miss can never crash the server or fail the user's render.
- registeredHandler = (job) => {
+ completedHandler = (job) => {
void (async () => {
if (!job || job.kind !== 'image') return;
const tag = job.params?.universeRun;
if (!tag?.collectionId) return;
const filename = job.result?.filename;
if (!filename || typeof filename !== 'string') return;
- const status = await addItem(tag.collectionId, { kind: 'image', ref: filename })
+
+ const runActive = tag.runId ? activeRuns.has(tag.runId) : false;
+ const addItemCall = () => addItem(tag.collectionId, { kind: 'image', ref: filename })
.then(() => 'added')
.catch((err) => {
// A duplicate (same filename rendered twice in the same run) is
@@ -42,27 +75,66 @@ export function initUniverseBuilderCollectionHook() {
console.log(`⚠️ universe-builder collection hook failed for ${filename}: ${err?.message || String(err)}`);
return 'failed';
});
- if (status === 'added') {
- console.log(`🌍 universe-builder run=${tag.runId?.slice(0, 8)} category=${tag.category} → ${filename}`);
- } else if (status === 'duplicate') {
- console.log(`🌍 universe-builder run=${tag.runId?.slice(0, 8)} category=${tag.category} duplicate skipped: ${filename}`);
+
+ try {
+ // When the run is tracked, swallow the per-item emitRecordUpdated so a
+ // 160-image batch doesn't fan into 160 debounced re-exports. The final
+ // emit below fires once when pending hits zero.
+ const status = runActive && tag.universeId
+ ? await withReexportSuppressed('universe', tag.universeId, addItemCall)
+ : await addItemCall();
+
+ if (status === 'added') {
+ console.log(`🌍 universe-builder run=${tag.runId?.slice(0, 8)} category=${tag.category} → ${filename}`);
+ } else if (status === 'duplicate') {
+ console.log(`🌍 universe-builder run=${tag.runId?.slice(0, 8)} category=${tag.category} duplicate skipped: ${filename}`);
+ }
+ } finally {
+ // `finally` (not the happy path) so an unexpected throw still
+ // decrements pending — otherwise one anomaly stalls the run's
+ // coalesced emit forever.
+ if (tag.runId) {
+ const completedUniverseId = noteTerminal(tag.runId);
+ if (completedUniverseId) emitRecordUpdated('universe', completedUniverseId);
+ }
}
})().catch((err) => {
// Last-resort net for synchronous throws (unexpected job shape, etc).
console.log(`⚠️ universe-builder collection hook crashed: ${err?.message || err}`);
});
};
- mediaJobEvents.on('completed', registeredHandler);
+
+ // Failed/canceled jobs still count toward run completion — otherwise a
+ // single failure mid-batch would leave `pending > 0` forever and the
+ // final emit would never fire.
+ terminalHandler = (job) => {
+ if (!job || job.kind !== 'image') return;
+ const tag = job.params?.universeRun;
+ if (!tag?.runId) return;
+ const completedUniverseId = noteTerminal(tag.runId);
+ if (completedUniverseId) emitRecordUpdated('universe', completedUniverseId);
+ };
+
+ mediaJobEvents.on('completed', completedHandler);
+ mediaJobEvents.on('failed', terminalHandler);
+ mediaJobEvents.on('canceled', terminalHandler);
console.log('🌍 Universe Builder collection hook initialized');
}
// Test-only reset hook so suites that re-init can do so cleanly. Removes the
-// previously registered listener so re-init doesn't leak handlers.
+// previously registered listeners so re-init doesn't leak handlers.
export const __testing = {
reset: () => {
- if (registeredHandler) {
- mediaJobEvents.off('completed', registeredHandler);
- registeredHandler = null;
+ if (completedHandler) {
+ mediaJobEvents.off('completed', completedHandler);
+ completedHandler = null;
+ }
+ if (terminalHandler) {
+ mediaJobEvents.off('failed', terminalHandler);
+ mediaJobEvents.off('canceled', terminalHandler);
+ terminalHandler = null;
}
+ activeRuns.clear();
},
+ getActiveRuns: () => new Map(activeRuns),
};
diff --git a/server/services/universeBuilderCollectionHook.test.js b/server/services/universeBuilderCollectionHook.test.js
new file mode 100644
index 0000000000..ca92439093
--- /dev/null
+++ b/server/services/universeBuilderCollectionHook.test.js
@@ -0,0 +1,136 @@
+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
+import { mkdtempSync, rmSync, mkdirSync } from 'fs';
+import { tmpdir } from 'os';
+import { join } from 'path';
+
+const tempData = mkdtempSync(join(tmpdir(), 'portos-ubhook-test-data-'));
+
+vi.mock('../lib/fileUtils.js', async () => {
+ const actual = await vi.importActual('../lib/fileUtils.js');
+ return new Proxy(actual, {
+ get(target, prop) {
+ if (prop === 'PATHS') return {
+ ...actual.PATHS,
+ data: tempData,
+ images: join(tempData, 'images'),
+ videos: join(tempData, 'videos'),
+ };
+ return target[prop];
+ },
+ });
+});
+
+const { mediaJobEvents } = await import('./mediaJobQueue/index.js');
+const collections = await import('./mediaCollections.js');
+const recordEvents = await import('./sharing/recordEvents.js');
+const hook = await import('./universeBuilderCollectionHook.js');
+
+async function waitFor(predicate, { timeoutMs = 2000, intervalMs = 5 } = {}) {
+ const deadline = Date.now() + timeoutMs;
+ while (Date.now() < deadline) {
+ if (predicate()) return;
+ await new Promise((r) => setTimeout(r, intervalMs));
+ }
+ throw new Error('waitFor: predicate never became true');
+}
+
+describe('universeBuilderCollectionHook', () => {
+ let updates;
+ let recordListener;
+
+ beforeEach(() => {
+ rmSync(tempData, { recursive: true, force: true });
+ mkdirSync(tempData, { recursive: true });
+ hook.__testing.reset();
+ hook.initUniverseBuilderCollectionHook();
+ updates = [];
+ // Capture suppression state at emit time — that's the layer the coalesce
+ // actually changes. The recordEvents bus fires for every emit; what we
+ // care about is how many of those would *actually* trigger a re-export
+ // (i.e. how many fired without isReexportSuppressed gating them).
+ recordListener = (evt) => updates.push({
+ ...evt,
+ suppressed: recordEvents.isReexportSuppressed(evt.recordKind, evt.recordId),
+ });
+ recordEvents.recordEvents.on('updated', recordListener);
+ });
+
+ afterEach(() => {
+ recordEvents.recordEvents.off('updated', recordListener);
+ hook.__testing.reset();
+ });
+
+ async function makeCollection(universeId) {
+ return collections.findOrCreateCollectionByName({
+ name: `c-${Math.random().toString(36).slice(2, 8)}`,
+ universeId,
+ });
+ }
+
+ function emitCompletion({ runId, universeId, collectionId, filename, category = 'landscapes' }) {
+ mediaJobEvents.emit('completed', {
+ kind: 'image',
+ result: { filename },
+ params: {
+ universeRun: { runId, universeId, collectionId, category, label: 'l' },
+ },
+ });
+ }
+
+ function emitTerminal(eventName, { runId, universeId, collectionId, category = 'landscapes' }) {
+ mediaJobEvents.emit(eventName, {
+ kind: 'image',
+ params: {
+ universeRun: { runId, universeId, collectionId, category, label: 'l' },
+ },
+ });
+ }
+
+ it('coalesces per-image emits into a single update at run end', async () => {
+ const universeId = 'uni-1';
+ const c = await makeCollection(universeId);
+ hook.registerUniverseBuilderRun({ runId: 'r1', universeId, jobCount: 3 });
+
+ emitCompletion({ runId: 'r1', universeId, collectionId: c.id, filename: 'a.png' });
+ emitCompletion({ runId: 'r1', universeId, collectionId: c.id, filename: 'b.png' });
+ emitCompletion({ runId: 'r1', universeId, collectionId: c.id, filename: 'c.png' });
+
+ const forUniverse = () => updates.filter((u) => u.recordKind === 'universe' && u.recordId === universeId);
+ const unsuppressed = () => forUniverse().filter((u) => !u.suppressed);
+ await waitFor(() => hook.__testing.getActiveRuns().size === 0 && unsuppressed().length >= 1);
+ await new Promise((r) => setTimeout(r, 50));
+ expect(unsuppressed()).toHaveLength(1);
+ expect(hook.__testing.getActiveRuns().size).toBe(0);
+ });
+
+ it('counts failed/canceled jobs toward run completion', async () => {
+ const universeId = 'uni-2';
+ const c = await makeCollection(universeId);
+ hook.registerUniverseBuilderRun({ runId: 'r2', universeId, jobCount: 3 });
+
+ emitCompletion({ runId: 'r2', universeId, collectionId: c.id, filename: 'd.png' });
+ emitTerminal('failed', { runId: 'r2', universeId, collectionId: c.id });
+ emitTerminal('canceled', { runId: 'r2', universeId, collectionId: c.id });
+
+ const forUniverse = () => updates.filter((u) => u.recordKind === 'universe' && u.recordId === universeId);
+ const unsuppressed = () => forUniverse().filter((u) => !u.suppressed);
+ await waitFor(() => hook.__testing.getActiveRuns().size === 0 && unsuppressed().length >= 1);
+ await new Promise((r) => setTimeout(r, 50));
+ expect(unsuppressed()).toHaveLength(1);
+ expect(hook.__testing.getActiveRuns().size).toBe(0);
+ });
+
+ it('falls back to per-image emits when run is not registered', async () => {
+ const universeId = 'uni-3';
+ const c = await makeCollection(universeId);
+ // No registerUniverseBuilderRun — simulates a server restart mid-run.
+
+ emitCompletion({ runId: 'r3', universeId, collectionId: c.id, filename: 'e.png' });
+ emitCompletion({ runId: 'r3', universeId, collectionId: c.id, filename: 'f.png' });
+
+ const forUniverse = () => updates.filter((u) => u.recordKind === 'universe' && u.recordId === universeId);
+ const unsuppressed = () => forUniverse().filter((u) => !u.suppressed);
+ await waitFor(() => unsuppressed().length >= 2);
+ expect(unsuppressed()).toHaveLength(2);
+ });
+});