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: durably persist universe canon section-local renders via the appendEntryImageRef hook (#1395)

Adam Eivy24edb22c0274
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 250d170e9a..588f6e03fc 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -136,3 +136,5 @@
- **The "Verify arc" hover tooltip on the series arc page no longer renders clipped behind the nav and other cards.** The `VerifyScopeTooltip` panel sat in the arc-header's button row as an `absolute`-positioned child. That row scrolls horizontally (the "Derive from manuscript" button overflows on narrow widths), so its `overflow` clipped the popover and trapped it in an ancestor stacking context — no `z-index` could lift it above the sidebar nav or the cards below. Rewrote it as a portal-rendered (`createPortal` to `<body>`), `position: fixed` popover anchored below-right of its trigger via the live `getBoundingClientRect()`, so it floats above everything and is clamped on-screen on narrow viewports. (A prior pass bumped the z-index to `z-[60]`, which didn't help because the clip was an `overflow`/stacking-context problem, not a layering one.) `aria-describedby` wiring is preserved. (`client/src/components/pipeline/ArcCanvas.jsx`)
- **[issue-1383] Chunked LLM editorial checks now carry cross-chapter continuity between chunks.** When a manuscript is too long for the provider's context window, the manuscript-consuming LLM checks review it chunk-by-chunk and merge findings first-wins (#1340). But a per-chunk view is blind to problems that span chapters: `style.conformance` couldn't see that chapter 1 established past-tense when judging chapter 3, and `objects.unmotivated-interaction` could flag a "missing setup" for an object that an earlier chunk already accounted for. Those two checks now opt into a rolling **prior-findings digest** (`editorialPriorFindingsDigest`) — each chunk after the first is prefixed with a capped, first-wins summary of the findings gathered so far, riding INSIDE the manuscript var so no stage-prompt template changes (mirrors the completeness pass's `priorFindingsDigest`). The digest instructs the model not to repeat prior findings and to flag only new problems plus cross-chapter continuity issues the earlier findings reveal; exact repeats are still deduped by `editorialFindingKey`. The chunk planner reserves `EDITORIAL_PRIOR_DIGEST_TOKENS` so prepending the digest can't overrun the window, and `prose.info-dumping` deliberately stays per-chunk (its problems are localized). The shared chunk loop is factored into one `runChunkedManuscriptCheck` helper used by both the staged and custom-check paths. (`server/lib/editorial/checkRegistry.js`, #1383)
+
+- **[issue-1395] Universe canon section-local renders now persist durably even if the page unmounts mid-render.** A single reference/clean-plate render fired from the Universe canon section round-tripped a client `updateUniverse` PATCH to append the new filename onto the entry's `imageRefs[]` — so a render that completed *after* the user navigated away, refreshed, or switched universes silently lost its attachment (the image reached the media library, but no `imageRefs[]` row was ever written). These renders now carry the same durable `universeRun.entryRef` job tag the batch path uses, so the server-side completion hook (`universeBuilderCollectionHook`) appends `imageRefs[]` independent of any mounted client — converging the section-local and batch surfaces onto one durable path (mirrors the catalog hook from #1359). The hook fires the `appendEntryImageRef` even when the render carries no collection (and the route preserves `entryRef` through a gallery-collection provisioning failure, so the imageRefs append never depends on the collection existing). The client `handleRefCompleted` keeps its optimistic/immediate-refresh role (no PATCH); the hook is idempotent against it (`mapAppendImageRef` dedupes by filename). (`server/services/universeBuilderCollectionHook.js`, `server/routes/imageGen.js`, `client/src/components/universe/UniverseCanonSection.jsx`, #1395)
diff --git a/client/src/components/universe/UniverseCanonSection.jsx b/client/src/components/universe/UniverseCanonSection.jsx
index 2b51f18397..b3252bd297 100644
--- a/client/src/components/universe/UniverseCanonSection.jsx
+++ b/client/src/components/universe/UniverseCanonSection.jsx
@@ -53,6 +53,26 @@ const capImageRefs = (refs) => (
// record; normalize to [] so callers can spread/map without a guard each time.
const getKindList = (u, kindKey) => (Array.isArray(u?.[kindKey]) ? u[kindKey] : []);
+// Durable section-local render tag (#1395). Carries the canon `entryRef` so the
+// server-side completion hook (universeBuilderCollectionHook) appends the
+// finished render to the entry's `imageRefs[]` even after this page unmounts —
+// converging these renders onto the same durable path batch renders use, so the
+// client no longer needs to PATCH the universe on completion. `universeName`
+// lets the route resolve the universe gallery collection (renders also land
+// there, matching the base-style probe + batch paths). Returns null when the
+// universe/entry identity isn't resolvable yet (render still proceeds untagged).
+const buildSectionRenderTag = (universe, kindKey, entry) => (
+ universe?.id && universe?.name && entry?.id
+ ? {
+ universeId: universe.id,
+ universeName: universe.name,
+ entryRef: { kind: 'canon', kindKey, id: entry.id },
+ label: entry.name || kindKey,
+ category: kindKey,
+ }
+ : null
+);
+
// Build an embedded canon entry from a picked catalog ingredient. The
// ingredient's `payload` already carries the same field names the universe
// canon sanitizer whitelists (name / physicalDescription / description / …),
@@ -406,10 +426,12 @@ export default function UniverseCanonSection({
universe,
baseNegative: baseOpts.negativePrompt,
});
+ const universeRun = buildSectionRenderTag(universe, kind.key, entry);
const queued = await generateImage({
...baseOpts,
prompt: styled.prompt,
negativePrompt: styled.negativePrompt || undefined,
+ ...(universeRun ? { universeRun } : {}),
}).catch((err) => { toast.error(err.message || 'Render failed'); return null; });
if (!queued?.jobId || !mountedRef.current) return;
setRenderingJobs((prev) => ({ ...prev, [entry.id]: queued.jobId }));
@@ -446,7 +468,7 @@ export default function UniverseCanonSection({
}
};
- const handleRenderCleanPlate = async (entry) => {
+ const handleRenderCleanPlate = async (kind, entry) => {
// Match CanonCard's button-enable predicate (descFor includes palette +
// recurringDetails for places) — composeCleanPlatePrompt builds a valid
// prompt from any of {description, palette, recurringDetails}, so gating
@@ -466,52 +488,34 @@ export default function UniverseCanonSection({
plate.negativePrompt,
universe ? universeStylePreset(universe) : null,
);
+ const universeRun = buildSectionRenderTag(universe, kind.key, entry);
const queued = await generateImage({
...baseOpts,
prompt: styled.prompt,
negativePrompt: styled.negativePrompt || undefined,
+ ...(universeRun ? { universeRun } : {}),
}).catch((err) => { toast.error(err.message || 'Clean plate render failed'); return null; });
if (!queued?.jobId || !mountedRef.current) return;
setRenderingJobs((prev) => ({ ...prev, [entry.id]: queued.jobId }));
toast.success(`Rendering clean plate for ${entry.name}`);
};
- // Section-local renders go through `generateImage` directly with no
- // `universeRun` tag, so the server-side `appendEntryImageRef` collection
- // hook never fires — the client MUST round-trip a PATCH to persist the
- // new filename onto the canon entry. The list shape passed in is built
- // from `universe`, but section-local renders are user-driven one-at-a-
- // time so the read-modify-write window is small and tolerable.
- const handleRefCompleted = useCallback(async (kindKey, entryId, filename) => {
- if (!filename || !universe) return;
- setRenderingJobs((prev) => {
- if (!prev[entryId]) return prev;
- const next = { ...prev };
- delete next[entryId];
- return next;
- });
- const capturedId = universeId;
- const list = (universe[kindKey] || []).map((e) =>
- e.id === entryId ? { ...e, imageRefs: [...(e.imageRefs || []), filename] } : e
- );
- const updated = await updateUniverse(universeId, { [kindKey]: list })
- .catch((err) => { toast.error(`Save failed: ${err.message}`); return null; });
- if (updated && mountedRef.current && currentUniverseIdRef.current === capturedId) onUniverseChange(updated);
- }, [universe, universeId, onUniverseChange, mountedRef]);
-
- // External (batch-render) canon completions follow a different path:
- // (a) the server's `appendEntryImageRef` collection hook has ALREADY
- // stamped the filename onto the persisted record, so a client-side
- // `updateUniverse` here is redundant and would clobber concurrent
- // sibling appends with a stale full-array patch built from the
- // `universe` snapshot the parent re-rendered with.
- // (b) the parent's draft is the source of truth for UI display, so we
- // update it through `onUniverseChange` only — dedupe on `includes`
- // so duplicate completion events don't double-stamp the same ref.
- // (c) `latestUniverseRef` (not the closed-over `universe` prop) is used
- // so back-to-back sibling completions all see the freshest state
- // and chain their appends instead of clobbering each other.
- const handleExternalCanonRefCompleted = useCallback((kindKey, entryId, filename) => {
+ // Optimistically stamp a completed render's filename onto a canon entry's
+ // `imageRefs[]` in the parent draft. Used by BOTH section-local and external
+ // batch completions, because as of #1395 BOTH are persisted server-side by
+ // the `appendEntryImageRef` completion hook — so the client never PATCHes
+ // here; it only mirrors the durable write into the visible draft for an
+ // immediate refresh. Notes:
+ // (a) the server hook is the source of truth, so a client `updateUniverse`
+ // would be redundant and could clobber concurrent sibling appends with a
+ // stale full-array patch.
+ // (b) `latestUniverseRef` (not the closed-over `universe` prop) is read so
+ // back-to-back sibling completions all see the freshest state and chain
+ // their appends instead of clobbering each other.
+ // (c) dedupe on `includes` so a duplicate completion event (or the optimistic
+ // path racing the hook) doesn't double-stamp the same ref; `capImageRefs`
+ // mirrors the server-side last-N cap.
+ const applyOptimisticCanonRef = useCallback((kindKey, entryId, filename) => {
if (!filename) return;
const latest = latestUniverseRef.current;
if (!latest) return;
@@ -520,15 +524,31 @@ export default function UniverseCanonSection({
if (e?.id !== entryId) return e;
const refs = Array.isArray(e.imageRefs) ? e.imageRefs : [];
if (refs.includes(filename)) return e;
- // Mirror the server-side appendEntryImageRef cap (last N wins) so
- // an external batch completion arriving at a full row doesn't leave
- // the optimistic state holding an overlong array that a subsequent
- // save would have to trim.
return { ...e, imageRefs: capImageRefs([...refs, filename]) };
});
onUniverseChange({ ...latest, [kindKey]: nextList });
}, [onUniverseChange]);
+ // Section-local renders now carry a durable `universeRun.entryRef` tag
+ // (buildSectionRenderTag), so the server-side `appendEntryImageRef` hook
+ // persists the new filename even if this page unmounts mid-render — the
+ // client just clears the spinner and mirrors the ref into the draft (no
+ // PATCH). The durable hook is idempotent against this optimistic stamp.
+ const handleRefCompleted = useCallback((kindKey, entryId, filename) => {
+ setRenderingJobs((prev) => {
+ if (!prev[entryId]) return prev;
+ const next = { ...prev };
+ delete next[entryId];
+ return next;
+ });
+ applyOptimisticCanonRef(kindKey, entryId, filename);
+ }, [applyOptimisticCanonRef]);
+
+ // External (batch-render) canon completions share the same optimistic-only
+ // path: the server collection hook already stamped the persisted record, so
+ // the client only updates the parent draft.
+ const handleExternalCanonRefCompleted = applyOptimisticCanonRef;
+
const handleRefFailed = useCallback((entryId, errMsg) => {
setRenderingJobs((prev) => {
if (!prev[entryId]) return prev;
@@ -769,15 +789,17 @@ export default function UniverseCanonSection({
renderingJobs={renderingJobs}
onRender={(entry) => handleRenderRef(kind, entry)}
onJobCompleted={(entryId, filename, completedJobId) => {
- // Discriminate by which pending map owns the completed jobId:
+ // Discriminate by which pending map owns the completed jobId.
+ // As of #1395 BOTH paths are persisted server-side by the
+ // `appendEntryImageRef` completion hook (section-local renders now
+ // carry a durable `universeRun.entryRef` tag too), so neither
+ // client path PATCHes — they only mirror the ref into the draft:
// - section-local renders (`generateImage`) populate
- // `renderingJobs[entryId]`; their server side has no
- // `appendEntryImageRef` hook so the client must persist
- // via `handleRefCompleted`.
+ // `renderingJobs[entryId]`; `handleRefCompleted` clears the
+ // spinner + stamps the draft optimistically.
// - external batch renders flow through the page-level
- // `externalPendingByEntryId`; the server collection hook
- // already stamped imageRefs, so the client only needs to
- // update local state + clear the pending queue.
+ // `externalPendingByEntryId`; `handleExternalCanonRefCompleted`
+ // stamps the draft + clears the pending queue.
const isExternal = completedJobId
&& externalPendingByEntryId?.[entryId] === completedJobId;
if (isExternal) {
@@ -807,7 +829,7 @@ export default function UniverseCanonSection({
onToggleLock={(entryId, nextLocked) => handleToggleLock(kind, entryId, nextLocked)}
togglingLockId={togglingLockId}
onPatchEntry={(entryId, patch) => handlePatchEntry(kind, entryId, patch)}
- onRenderCleanPlate={handleRenderCleanPlate}
+ onRenderCleanPlate={(entry) => handleRenderCleanPlate(kind, entry)}
onDescribeImages={(entry) => setDescribeTarget({ kind, entry })}
seriesNameMap={usage?.seriesNameMap || null}
onBulkLock={(nextLocked) => handleBulkLockKind(kind, nextLocked)}
diff --git a/server/routes/imageGen.js b/server/routes/imageGen.js
index ca3ee24631..a71a3be1c8 100644
--- a/server/routes/imageGen.js
+++ b/server/routes/imageGen.js
@@ -107,13 +107,25 @@ const generateSchema = z.object({
// collection — the same auto-filing path batch renders and character
// reference sheets use. The client passes only the universe identity (never
// a collectionId — that's server-resolved), so the front-end does no
- // collection bookkeeping. The base-style probe (StyleProbeImage) is the sole
- // caller today; JSON-only (the multipart ImageGen page never sends it).
+ // collection bookkeeping. The base-style probe (StyleProbeImage) and the
+ // Universe canon section-local renders (#1395) are the callers; JSON-only
+ // (the multipart ImageGen page never sends it).
universeRun: z.object({
universeId: z.string().min(1).max(200),
universeName: z.string().min(1).max(200),
label: z.string().max(200).optional(),
category: z.string().max(64).optional(),
+ // Section-local canon renders (#1395) tag the target entry so the
+ // completion hook durably appends the render to its `imageRefs[]` even
+ // after the originating page unmounts — converging these renders onto the
+ // same durable path batch renders use. Shape mirrors the batch path's
+ // entryRef (server/services/universeBuilder.js `ENTRY_REF_KIND`).
+ entryRef: z.object({
+ kind: z.enum(['canon', 'variation', 'sheet']),
+ kindKey: z.string().min(1).max(64).optional(),
+ categoryKey: z.string().min(1).max(64).optional(),
+ id: z.string().min(1).max(200),
+ }).optional(),
}).optional(),
// Durable catalog attach (#1359). When present, the mediaJobQueue completion
// hook (catalogImageAttachHook) files the finished render onto this catalog
@@ -280,7 +292,7 @@ router.post('/generate', imageGenUploads, asyncHandler(async (req, res) => {
// failure drops the tag and the render still proceeds (it just won't
// auto-file) rather than failing the user's generation over a side-effect.
if (params.universeRun?.universeId) {
- const { universeId, universeName, label, category } = params.universeRun;
+ const { universeId, universeName, label, category, entryRef } = params.universeRun;
const collection = await findOrCreateUniverseCollection({
universeId,
universeName,
@@ -289,8 +301,18 @@ router.post('/generate', imageGenUploads, asyncHandler(async (req, res) => {
console.error(`❌ image-gen → universe collection provision failed: ${err?.message || err}`);
return null;
});
- params.universeRun = collection
- ? { runId: randomUUID(), universeId, collectionId: collection.id, label, category }
+ // Preserve `entryRef` even when collection provisioning fails — the durable
+ // `imageRefs[]` append (#1395) must not depend on the gallery collection
+ // existing. Drop the tag entirely only when there's nothing left to do
+ // (no collection to file into AND no entry to append to).
+ params.universeRun = (collection || entryRef)
+ ? {
+ universeId,
+ ...(collection ? { runId: randomUUID(), collectionId: collection.id } : {}),
+ ...(label ? { label } : {}),
+ ...(category ? { category } : {}),
+ ...(entryRef ? { entryRef } : {}),
+ }
: undefined;
}
diff --git a/server/routes/imageGen.test.js b/server/routes/imageGen.test.js
index c945ef018a..640a71ccae 100644
--- a/server/routes/imageGen.test.js
+++ b/server/routes/imageGen.test.js
@@ -366,6 +366,60 @@ describe('Image Gen Routes', () => {
const [call] = mediaJobQueue.enqueueJob.mock.calls;
expect(call[0].params.universeRun).toBeUndefined();
});
+
+ // #1395 — section-local canon renders carry an `entryRef` so the
+ // completion hook durably appends the render to the entry's imageRefs[].
+ it('carries the section-local entryRef into the queued job tag', async () => {
+ getSettings.mockResolvedValueOnce({ imageGen: { mode: 'local', local: { pythonPath: '/usr/bin/python3' } } });
+ mediaJobQueue.enqueueJob.mockReturnValueOnce({ jobId: 'queued-section', position: 1, status: 'queued' });
+
+ const response = await request(app)
+ .post('/api/image-gen/generate')
+ .send({
+ prompt: 'a confident pyromancer',
+ universeRun: {
+ universeId: 'uni-3',
+ universeName: 'CanonVerse',
+ label: 'Ash',
+ category: 'characters',
+ entryRef: { kind: 'canon', kindKey: 'characters', id: 'char-ash' },
+ },
+ });
+
+ expect(response.status).toBe(200);
+ const [call] = mediaJobQueue.enqueueJob.mock.calls;
+ expect(call[0].params.universeRun).toEqual(expect.objectContaining({
+ universeId: 'uni-3',
+ collectionId: 'col-uni-3',
+ entryRef: { kind: 'canon', kindKey: 'characters', id: 'char-ash' },
+ }));
+ });
+
+ it('preserves the entryRef even when collection provisioning fails', async () => {
+ getSettings.mockResolvedValueOnce({ imageGen: { mode: 'local', local: { pythonPath: '/usr/bin/python3' } } });
+ mediaJobQueue.enqueueJob.mockReturnValueOnce({ jobId: 'queued-section-2', position: 1, status: 'queued' });
+ findOrCreateUniverseCollection.mockRejectedValueOnce(new Error('db down'));
+
+ const response = await request(app)
+ .post('/api/image-gen/generate')
+ .send({
+ prompt: 'a confident pyromancer',
+ universeRun: {
+ universeId: 'uni-4',
+ universeName: 'CanonVerse',
+ entryRef: { kind: 'canon', kindKey: 'characters', id: 'char-ash' },
+ },
+ });
+
+ expect(response.status).toBe(200);
+ const [call] = mediaJobQueue.enqueueJob.mock.calls;
+ // The durable imageRefs[] append must not depend on the gallery
+ // collection existing — entryRef survives, collectionId/runId don't.
+ expect(call[0].params.universeRun).toEqual({
+ universeId: 'uni-4',
+ entryRef: { kind: 'canon', kindKey: 'characters', id: 'char-ash' },
+ });
+ });
});
// Durable catalog attach (#1359): the Catalog ingredient editor's Generate
diff --git a/server/services/universeBuilderCollectionHook.js b/server/services/universeBuilderCollectionHook.js
index d4a3ce939f..6d609d7807 100644
--- a/server/services/universeBuilderCollectionHook.js
+++ b/server/services/universeBuilderCollectionHook.js
@@ -136,20 +136,34 @@ export function initUniverseBuilderCollectionHook() {
void (async () => {
if (!job || job.kind !== 'image') return;
const tag = job.params?.universeRun;
- if (!tag?.collectionId) return;
+ if (!tag) return;
+ const hasCollection = typeof tag.collectionId === 'string' && tag.collectionId.length > 0;
+ const hasEntryAppend = !!(tag.entryRef && tag.universeId);
+ // Section-local canon renders (#1395) carry an `entryRef` + `universeId`
+ // but no `collectionId` — they durably append the render to the entry's
+ // `imageRefs[]` without filing into a gallery collection. Batch + base-
+ // style-probe renders carry a `collectionId`. Bail only when neither
+ // piece of work is requested.
+ if (!hasCollection && !hasEntryAppend) return;
const filename = job.result?.filename;
if (!filename || typeof filename !== 'string') return;
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
- // expected when batchPerVariation > 1 and the gen output collides.
- if (err?.code === ERR_DUPLICATE) return 'duplicate';
- console.log(`⚠️ universe-builder collection hook failed for ${filename}: ${err?.message || String(err)}`);
- return 'failed';
- });
+ // Collection filing only when a collection target is present — section-
+ // local renders skip it (no gallery membership, just the entry-ref
+ // append below).
+ const addItemCall = () => {
+ if (!hasCollection) return Promise.resolve(null);
+ return addItem(tag.collectionId, { kind: 'image', ref: filename })
+ .then(() => 'added')
+ .catch((err) => {
+ // A duplicate (same filename rendered twice in the same run) is
+ // expected when batchPerVariation > 1 and the gen output collides.
+ if (err?.code === ERR_DUPLICATE) return 'duplicate';
+ console.log(`⚠️ universe-builder collection hook failed for ${filename}: ${err?.message || String(err)}`);
+ return 'failed';
+ });
+ };
// Append the rendered filename to the source entry's `imageRefs[]` so
// the Universe Builder can show the latest render as an avatar. Wrapped
@@ -158,10 +172,12 @@ export function initUniverseBuilderCollectionHook() {
// bookkeeping must never crash the server or fail the user's render.
const appendEntryRefCall = () => {
if (!tag.entryRef || !tag.universeId) return Promise.resolve(null);
- return appendEntryImageRef(tag.universeId, tag.entryRef, filename).catch((err) => {
- console.log(`⚠️ universe-builder entry-ref append failed for ${filename}: ${err?.message || String(err)}`);
- return null;
- });
+ return appendEntryImageRef(tag.universeId, tag.entryRef, filename)
+ .then((res) => (res ? 'appended' : null))
+ .catch((err) => {
+ console.log(`⚠️ universe-builder entry-ref append failed for ${filename}: ${err?.message || String(err)}`);
+ return null;
+ });
};
// Enrich the image's sidecar with universe + entity context so
@@ -195,17 +211,21 @@ export function initUniverseBuilderCollectionHook() {
// dependency — fire them in parallel so a large batch doesn't pay
// the per-completion serialization cost on every job.
const work = async () => {
- const [s] = await Promise.all([addItemCall(), appendEntryRefCall(), enrichSidecarCall()]);
- return s;
+ const [filed, appended] = await Promise.all([addItemCall(), appendEntryRefCall(), enrichSidecarCall()]);
+ return { filed, appended };
};
- const status = runActive && tag.universeId
+ const { filed, appended } = runActive && tag.universeId
? await withReexportSuppressed('universe', tag.universeId, work)
: await work();
- if (status === 'added') {
+ if (filed === 'added') {
console.log(`🌍 universe-builder run=${tag.runId?.slice(0, 8)} category=${tag.category} → ${filename}`);
- } else if (status === 'duplicate') {
+ } else if (filed === 'duplicate') {
console.log(`🌍 universe-builder run=${tag.runId?.slice(0, 8)} category=${tag.category} duplicate skipped: ${filename}`);
+ } else if (!hasCollection && appended === 'appended') {
+ // Section-local render: no collection filing, just the durable
+ // imageRefs[] append onto the canon entry.
+ console.log(`🌍 universe section-local render → entry ${tag.entryRef?.id?.slice(0, 8)} ← ${filename}`);
}
} finally {
// `finally` (not the happy path) so an unexpected throw still
diff --git a/server/services/universeBuilderCollectionHook.test.js b/server/services/universeBuilderCollectionHook.test.js
index 7a09565af0..f8f3a24d61 100644
--- a/server/services/universeBuilderCollectionHook.test.js
+++ b/server/services/universeBuilderCollectionHook.test.js
@@ -44,7 +44,10 @@ const readSidecar = (filename) => JSON.parse(readFileSync(sidecarPath(filename),
async function waitFor(predicate, { timeoutMs = 2000, intervalMs = 5 } = {}) {
const deadline = Date.now() + timeoutMs;
while (Date.now() < deadline) {
- if (predicate()) return;
+ // `await` so async predicates (e.g. getUniverse reads) resolve to a real
+ // boolean — a bare Promise is always truthy and would short-circuit. Sync
+ // boolean predicates pass through `await` unchanged.
+ if (await predicate()) return;
await new Promise((r) => setTimeout(r, intervalMs));
}
throw new Error('waitFor: predicate never became true');
@@ -390,4 +393,91 @@ describe('universeBuilderCollectionHook', () => {
expect(sc.prompt).toBe('a moody noir skyline');
expect(sc.seed).toBe(7);
});
+
+ // #1395 — section-local canon renders carry an entryRef + universeId but NO
+ // collectionId. The hook must still durably append the render to the entry's
+ // imageRefs[] (and enrich the sidecar) without filing into any collection.
+ it('appends a section-local render (entryRef, no collectionId) to the canon entry imageRefs[]', async () => {
+ const characterId = 'char-solo';
+ const seeded = await seedUniverse({
+ name: 'SoloVerse',
+ characters: [{ id: characterId, name: 'Solo', physicalDescription: 'lone wanderer' }],
+ });
+ const filename = 'section-local.png';
+ writeSidecar(filename, { id: 'section-local', prompt: 'a lone wanderer', seed: 11 });
+
+ // Route shape for a section-local render: universeId + entryRef, but the
+ // route resolves no collection (or provisioning failed), so collectionId is
+ // absent. No registerUniverseBuilderRun — these are one-off renders.
+ mediaJobEvents.emit('completed', {
+ kind: 'image',
+ result: { filename },
+ params: {
+ universeRun: {
+ universeId: seeded.id,
+ category: 'characters',
+ label: 'Solo',
+ entryRef: { kind: 'canon', kindKey: 'characters', id: characterId },
+ },
+ },
+ });
+
+ await waitFor(async () => {
+ const u = await universeBuilder.getUniverse(seeded.id);
+ return u?.characters?.[0]?.imageRefs?.includes(filename);
+ });
+ const u = await universeBuilder.getUniverse(seeded.id);
+ expect(u.characters[0].imageRefs).toEqual([filename]);
+ // No collection was created or filed (the hook skipped addItem).
+ expect(hook.__testing.getActiveRuns().size).toBe(0);
+ // Sidecar still gets universe/entity context.
+ const sc = readSidecar(filename);
+ expect(sc.entryId).toBe(characterId);
+ expect(sc.entryName).toBe('Solo');
+ expect(sc.prompt).toBe('a lone wanderer'); // original metadata preserved
+ });
+
+ it('is idempotent — the same section-local filename is appended only once', async () => {
+ const characterId = 'char-dupe';
+ const seeded = await seedUniverse({
+ name: 'DupeVerse',
+ characters: [{ id: characterId, name: 'Dupe' }],
+ });
+ const filename = 'dupe.png';
+ writeSidecar(filename, { id: 'dupe', prompt: 'p' });
+
+ const emit = () => mediaJobEvents.emit('completed', {
+ kind: 'image',
+ result: { filename },
+ params: {
+ universeRun: {
+ universeId: seeded.id,
+ entryRef: { kind: 'canon', kindKey: 'characters', id: characterId },
+ },
+ },
+ });
+ emit();
+ await waitFor(async () => {
+ const u = await universeBuilder.getUniverse(seeded.id);
+ return u?.characters?.[0]?.imageRefs?.includes(filename);
+ });
+ emit(); // duplicate completion (e.g. a re-emit) must not double-stamp
+ await new Promise((r) => setTimeout(r, 50));
+ const u = await universeBuilder.getUniverse(seeded.id);
+ expect(u.characters[0].imageRefs).toEqual([filename]);
+ });
+
+ it('ignores a universeRun tag with neither collectionId nor an entryRef append', async () => {
+ const filename = 'noop.png';
+ writeSidecar(filename, { id: 'noop', prompt: 'just pixels' });
+ mediaJobEvents.emit('completed', {
+ kind: 'image',
+ result: { filename },
+ // universeId present but no collectionId AND no entryRef → nothing to do.
+ params: { universeRun: { universeId: 'uni-noop', category: 'style' } },
+ });
+ await new Promise((r) => setTimeout(r, 50));
+ // Sidecar untouched — the hook bailed before enrich.
+ expect(readSidecar(filename)).toEqual({ id: 'noop', prompt: 'just pixels' });
+ });
});