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

feat(universe-builder): per-item render history with avatar thumbnails (#315)

[._.]/ Adam Eivy15c8dc075d79
diff --git a/client/src/components/pipeline/CanonCard.jsx b/client/src/components/pipeline/CanonCard.jsx
index ec493e6ab5..08099df680 100644
--- a/client/src/components/pipeline/CanonCard.jsx
+++ b/client/src/components/pipeline/CanonCard.jsx
@@ -293,11 +293,13 @@ export default function CanonCard({
const blockedByLock = locked;
// Visual at-a-glance without scrolling to the footer ref grid. Falls back
- // to the first ref when nothing is pinned so a freshly-rendered entry isn't
- // thumbnail-less just because the user hasn't picked a primary yet.
+ // to the MOST RECENT ref when nothing is pinned so a freshly-rendered entry
+ // isn't thumbnail-less just because the user hasn't picked a primary yet,
+ // and a re-render lands as the avatar instead of being buried behind older
+ // takes. `imageRefs` is chronological (renders append to the end).
const thumbnailRef = (entry.primaryImageRef && refs.includes(entry.primaryImageRef))
? entry.primaryImageRef
- : (refs[0] || null);
+ : (refs[refs.length - 1] || null);
// settledRef prevents duplicate completion callbacks under React 18
// StrictMode's mount→cleanup→mount double-fire in dev. MediaJobThumb
@@ -539,12 +541,19 @@ export default function CanonCard({
</>
);
+ // `fallbackRefs` lets EntryCardThumbnail walk back through prior renders
+ // when the chosen primary file no longer exists on disk — so a deleted
+ // gallery image gracefully degrades to the next existing render rather
+ // than producing a broken thumbnail. `onClick` receives the currently
+ // displayed filename (which may be a fallback) so the lightbox previews
+ // what the user actually sees rather than the absent primary.
const thumbnail = thumbnailRef
? {
filename: thumbnailRef,
alt: `${entry.name} reference`,
- onClick: () => onPreview?.(thumbnailRef),
+ onClick: (visibleFilename) => onPreview?.(visibleFilename || thumbnailRef),
isPrimary: !!entry.primaryImageRef && entry.primaryImageRef === thumbnailRef,
+ fallbackRefs: refs,
}
: null;
diff --git a/client/src/components/universe/EntryCard.jsx b/client/src/components/universe/EntryCard.jsx
index 826efb6b4a..4fd2dc21ab 100644
--- a/client/src/components/universe/EntryCard.jsx
+++ b/client/src/components/universe/EntryCard.jsx
@@ -6,10 +6,15 @@
* Slot contract:
* - `title`, `body`, `actions`, `footer` — ReactNode. Consumers own internal
* layout (e.g. column vs. row for `actions`) so EntryCard stays unopinionated.
- * - `thumbnail` — descriptor object `{ filename, alt?, onClick?, isPrimary? }`
- * (NOT a ReactNode). Spread into the internal `EntryCardThumbnail` renderer
- * so the 12x12 frame, primary-star badge, and zoom-in button styling stay
- * consistent across consumers. Pass `null`/omit to skip the thumbnail column.
+ * - `thumbnail` — descriptor object `{ filename, alt?, onClick?, isPrimary?,
+ * fallbackRefs? }` (NOT a ReactNode). Spread into the internal
+ * `EntryCardThumbnail` renderer so the 12x12 frame, primary-star badge, and
+ * zoom-in button styling stay consistent across consumers. Pass `null`/omit
+ * to skip the thumbnail column. `fallbackRefs` is an optional chronological
+ * list of older filenames — when the primary one fails to load (file
+ * deleted), the thumbnail walks back through this list to the next existing
+ * render rather than producing a broken image; if none load, the column
+ * collapses to nothing.
* - `selectable` — descriptor `{ selected, onToggle, label? }`. Turns the row
* into a checkbox-driven selection card (used by the Importer review for
* pre-commit canon picks). Selected accent matches `locked`'s family;
@@ -20,7 +25,7 @@
* overlay so they remain independently clickable without nesting interactive
* controls inside a `<label>` (invalid HTML).
*/
-import { useId } from 'react';
+import { useId, useState, useEffect } from 'react';
import { Star } from 'lucide-react';
export default function EntryCard({
@@ -63,9 +68,7 @@ export default function EntryCard({
/>
) : null}
{thumbnail ? (
- <div className={thumbnail.onClick ? 'relative z-10' : undefined}>
- <EntryCardThumbnail {...thumbnail} />
- </div>
+ <EntryCardThumbnail {...thumbnail} />
) : null}
<div className="flex-1 min-w-0">
{title}
@@ -78,13 +81,40 @@ export default function EntryCard({
);
}
-function EntryCardThumbnail({ filename, alt, onClick, isPrimary = false }) {
+function EntryCardThumbnail({ filename, alt, onClick, isPrimary = false, fallbackRefs = null }) {
+ // Build a walk-back list: primary first, then any older filenames (most
+ // recent of the fallbacks first since the consumer passes chronological,
+ // newest last — reverse so we step back through history). `filename` is
+ // de-duplicated from `fallbackRefs` so it isn't tried twice.
+ const candidates = [];
+ if (filename) candidates.push(filename);
+ if (Array.isArray(fallbackRefs)) {
+ for (let i = fallbackRefs.length - 1; i >= 0; i -= 1) {
+ const f = fallbackRefs[i];
+ if (typeof f === 'string' && f && f !== filename && !candidates.includes(f)) {
+ candidates.push(f);
+ }
+ }
+ }
+ // Reset the walk-back when the candidates list changes (new render landed,
+ // entry swapped, etc.). Keyed on the joined list so React rebuilds local
+ // state when the input genuinely changes vs. a parent re-render.
+ const candidateKey = candidates.join('|');
+ const [idx, setIdx] = useState(0);
+ useEffect(() => { setIdx(0); }, [candidateKey]);
+ // Walked past the end → all files are missing on disk. Collapse rather than
+ // render a broken `<img>`; matches the contract that no avatar shows when
+ // there are no resolvable renders.
+ if (!candidates.length || idx >= candidates.length) return null;
+ const currentFilename = candidates[idx];
+
const img = (
<img
- src={`/data/images/${filename}`}
- alt={alt || filename}
+ src={`/data/images/${currentFilename}`}
+ alt={alt || currentFilename}
className="w-full h-full object-cover"
loading="lazy"
+ onError={() => setIdx((n) => n + 1)}
/>
);
const frame = (
@@ -106,10 +136,10 @@ function EntryCardThumbnail({ filename, alt, onClick, isPrimary = false }) {
return (
<button
type="button"
- onClick={onClick}
- title={`Preview ${alt || filename}`}
- aria-label={`Preview ${alt || filename}`}
- className="p-0 bg-transparent border-0 cursor-zoom-in"
+ onClick={() => onClick(currentFilename)}
+ title={`Preview ${alt || currentFilename}`}
+ aria-label={`Preview ${alt || currentFilename}`}
+ className="p-0 bg-transparent border-0 cursor-zoom-in relative z-10"
>
{frame}
</button>
diff --git a/client/src/components/universe/EntryCard.test.jsx b/client/src/components/universe/EntryCard.test.jsx
index 8605f3e493..0374b3c439 100644
--- a/client/src/components/universe/EntryCard.test.jsx
+++ b/client/src/components/universe/EntryCard.test.jsx
@@ -115,3 +115,72 @@ describe('EntryCard — selectable mode', () => {
expect(li.className).toMatch(/(^|\s)p-3(\s|$)/);
});
});
+
+describe('EntryCard — thumbnail fallback', () => {
+ it('renders the primary filename when present', () => {
+ const { container } = render(wrapInList(
+ <EntryCard
+ title={<div>L1</div>}
+ thumbnail={{ filename: 'render-3.png', alt: 'avatar' }}
+ />,
+ ));
+ const img = container.querySelector('img');
+ expect(img.getAttribute('src')).toBe('/data/images/render-3.png');
+ });
+
+ it('walks back through fallbackRefs on image error', () => {
+ const { container } = render(wrapInList(
+ <EntryCard
+ title={<div>L1</div>}
+ thumbnail={{
+ filename: 'newest.png',
+ alt: 'avatar',
+ // chronological: oldest first, newest last. The `filename` field
+ // already holds the newest, so the walk-back order is
+ // newest → middle → oldest.
+ fallbackRefs: ['oldest.png', 'middle.png', 'newest.png'],
+ }}
+ />,
+ ));
+ const img = container.querySelector('img');
+ expect(img.getAttribute('src')).toBe('/data/images/newest.png');
+ fireEvent.error(img);
+ expect(container.querySelector('img').getAttribute('src')).toBe('/data/images/middle.png');
+ fireEvent.error(container.querySelector('img'));
+ expect(container.querySelector('img').getAttribute('src')).toBe('/data/images/oldest.png');
+ });
+
+ it('collapses to nothing when every candidate fails to load', () => {
+ const { container } = render(wrapInList(
+ <EntryCard
+ title={<div>L1</div>}
+ thumbnail={{ filename: 'only.png', alt: 'avatar', fallbackRefs: [] }}
+ />,
+ ));
+ const img = container.querySelector('img');
+ fireEvent.error(img);
+ expect(container.querySelector('img')).toBeNull();
+ });
+
+ it('passes the currently displayed filename to onClick', () => {
+ const onClick = vi.fn();
+ const { container } = render(wrapInList(
+ <EntryCard
+ title={<div>L1</div>}
+ thumbnail={{
+ filename: 'newest.png',
+ alt: 'avatar',
+ fallbackRefs: ['old.png', 'newest.png'],
+ onClick,
+ }}
+ />,
+ ));
+ // Initial click previews the newest visible filename.
+ fireEvent.click(container.querySelector('button'));
+ expect(onClick).toHaveBeenLastCalledWith('newest.png');
+ // After the newest fails, the click should preview the now-visible fallback.
+ fireEvent.error(container.querySelector('img'));
+ fireEvent.click(container.querySelector('button'));
+ expect(onClick).toHaveBeenLastCalledWith('old.png');
+ });
+});
diff --git a/client/src/pages/UniverseBuilder.jsx b/client/src/pages/UniverseBuilder.jsx
index 98ab1076ec..ef6bf3ef3d 100644
--- a/client/src/pages/UniverseBuilder.jsx
+++ b/client/src/pages/UniverseBuilder.jsx
@@ -2028,7 +2028,14 @@ function CompositeSheetsEditor({ sheets, onChange, canRender = false, onRender =
const prompt = editPrompt.trim();
if (!label || !prompt) return;
const next = [...sheets];
- next[editIdx] = { kind: editKind, label: label.slice(0, 120), prompt: prompt.slice(0, COMPOSITE_PROMPT_MAX) };
+ // Preserve `id`, `locked`, `imageRefs` — see VariationCard.saveEdit for
+ // the rationale. The editor only owns kind/label/prompt.
+ next[editIdx] = {
+ ...next[editIdx],
+ kind: editKind,
+ label: label.slice(0, 120),
+ prompt: prompt.slice(0, COMPOSITE_PROMPT_MAX),
+ };
onChange(next);
setEditIdx(null);
};
@@ -2302,7 +2309,19 @@ export function CategoryEditor({
// the user can't see why they vanished.
if (!label || !prompt) return;
const next = [...variations];
- next[editIdx] = { label: label.slice(0, 120), prompt: prompt.slice(0, 2000) };
+ // Preserve `id`, `locked`, and `imageRefs` — only label + prompt are
+ // editable in this row. A naive replacement would re-mint the variation's
+ // id (breaking the link to its render history) and drop accrued imageRefs.
+ // The server's stale-PATCH guard catches some of this via length + tail
+ // comparison (variations with NEW renders in cur survive an empty patch),
+ // but a stale variation whose history hasn't grown server-side since the
+ // client loaded would still get its imageRefs cleared if we sent an empty
+ // array. Echoing cur's array verbatim avoids relying on the guard.
+ next[editIdx] = {
+ ...next[editIdx],
+ label: label.slice(0, 120),
+ prompt: prompt.slice(0, 2000),
+ };
onChange(next);
setEditIdx(null);
};
@@ -2547,6 +2566,21 @@ function VariationCard({
? 'Promote to canon — pick a trunk'
: 'Promote to canon — LLM expands this variation into a full canon entry';
+ // Show the most recent render as an avatar. `imageRefs` is chronological
+ // (renders append to the end). EntryCardThumbnail falls back through the
+ // history on `onError` so a deleted gallery file degrades gracefully. The
+ // thumbnail column collapses when there are no renders yet — matching the
+ // contract that nothing shows until at least one image has been generated.
+ const renders = Array.isArray(v.imageRefs) ? v.imageRefs : [];
+ const latestRender = renders[renders.length - 1] || null;
+ const thumbnail = latestRender
+ ? {
+ filename: latestRender,
+ alt: `${v.label} render`,
+ fallbackRefs: renders,
+ }
+ : null;
+
const title = <div className="text-sm text-white font-medium truncate">{v.label}</div>;
const body = <div className="text-xs text-gray-400 line-clamp-2 mt-1">{v.prompt}</div>;
const actions = (
@@ -2628,7 +2662,7 @@ function VariationCard({
</div>
);
- return <EntryCard locked={locked} title={title} body={body} actions={actions} />;
+ return <EntryCard locked={locked} thumbnail={thumbnail} title={title} body={body} actions={actions} />;
}
function BibleTab({
diff --git a/server/routes/universeBuilder.js b/server/routes/universeBuilder.js
index 97b44f47ad..3aee87ca55 100644
--- a/server/routes/universeBuilder.js
+++ b/server/routes/universeBuilder.js
@@ -47,19 +47,34 @@ const mapServiceError = (err) => {
};
// ---- shared zod fragments ----
+// `id` is optional on input — the service-layer sanitizer mints one with a
+// `var-`/`sheet-` prefix when absent. Existing non-empty ids are normalized
+// on read/write (trimmed + capped to 80 chars) so renames + bucket-moves
+// preserve the link to imageRefs[]; callers should treat the normalized
+// form as the canonical id rather than the raw value they supplied.
+const entryIdField = z.string().trim().min(1).max(80).optional();
+const entryImageRefField = z.string().trim().min(1).max(svc.IMAGE_REF_FILENAME_MAX);
+const entryImageRefsField = z.array(entryImageRefField).max(svc.IMAGE_REFS_PER_ENTRY_MAX).optional();
const variationSchema = z.object({
+ id: entryIdField,
label: z.string().trim().min(1).max(svc.VARIATION_LABEL_MAX),
prompt: z.string().trim().min(1).max(svc.PROMPT_FRAGMENT_MAX),
// Per-item lock — when true, expand preserves this variation across
// re-runs instead of letting the LLM regenerate it.
locked: z.boolean().optional(),
+ // Render history (newest last). Server stamps this via the collection hook
+ // when a render completes; clients echo it back on PATCH-the-whole-list flows
+ // so the sanitizer can preserve it across rename/bucket-move.
+ imageRefs: entryImageRefsField,
});
const compositeSheetSchema = z.object({
+ id: entryIdField,
kind: z.enum(svc.COMPOSITE_SHEET_KINDS).optional(),
label: z.string().trim().min(1).max(svc.VARIATION_LABEL_MAX),
prompt: z.string().trim().min(1).max(svc.COMPOSITE_PROMPT_MAX),
// Per-item lock for composite boards (same semantics as variations).
locked: z.boolean().optional(),
+ imageRefs: entryImageRefsField,
});
const categoryShape = z.object({
// Tags this bucket to one of the 3 canon trunks (or 'other' as the
@@ -385,6 +400,20 @@ router.get('/:id/runs', asyncHandler(async (req, res) => {
router.post('/:id/render', asyncHandler(async (req, res) => {
const body = validateRequest(renderSchema, req.body ?? {});
+ // Legacy universes carry no variation/sheet ids on disk. sanitizeTemplate
+ // mints fresh UUIDs on every read but readState() intentionally does not
+ // persist them (race against concurrent writers). The render route needs
+ // ids that are stable across the read→queue→completion lifecycle so the
+ // collection hook can find the source entry by `entryRef.id`. Gate the
+ // one-time no-op write on the raw-disk inspection: fully-migrated
+ // universes skip the write so `updatedAt` doesn't bump on every render
+ // (which would interfere with LWW sync + trigger spurious re-export).
+ // Skip entirely for canon-only renders — canon entries already carry
+ // stable ids (storyBible.js sanitizer), so the raw-disk read + write
+ // would be pure overhead.
+ if (body.promptMode !== 'canon' && await svc.needsEntryIdPersist(req.params.id)) {
+ await svc.updateUniverse(req.params.id, () => ({})).catch((err) => { throw mapServiceError(err); });
+ }
const universe = await svc.getUniverse(req.params.id).catch((err) => { throw mapServiceError(err); });
// Resolve a style preset (server-side authoritative list) so the embrace
@@ -497,13 +526,19 @@ router.post('/:id/render', asyncHandler(async (req, res) => {
negativePrompt: item.negativePrompt || undefined,
// Tag every job so the completion hook can route the result back
// into the run's collection without us having to thread additional
- // arguments through the queue.
+ // arguments through the queue. `entryRef` (when present — variations
+ // and composite sheets gain it once the universe has been written
+ // through the current sanitizer) lets the hook also append the
+ // rendered filename to the source variation/sheet/canon entry's
+ // `imageRefs[]` so the Universe Builder can show the latest render
+ // as an avatar next to each item.
universeRun: {
runId,
universeId: universe.id,
collectionId: collection.id,
category: item.category,
label: item.label,
+ ...(item.entryRef ? { entryRef: item.entryRef } : {}),
},
};
if (mode === 'codex') {
diff --git a/server/services/universeBuilder.js b/server/services/universeBuilder.js
index 713d4427fa..afe68312db 100644
--- a/server/services/universeBuilder.js
+++ b/server/services/universeBuilder.js
@@ -25,7 +25,7 @@
* other name the user picks at kickoff).
*/
-import { join } from 'path';
+import { join, basename } from 'path';
import { randomUUID } from 'crypto';
import { PATHS, atomicWrite, readJSONFile, ensureDir, resolveImageRef } from '../lib/fileUtils.js';
import { createFileWriteQueue } from '../lib/fileWriteQueue.js';
@@ -98,6 +98,17 @@ export const COMPOSITE_SHEET_KINDS = Object.freeze([
]);
export const WORLD_CATEGORY_KEY_MAX = 64;
export const WORLD_CATEGORY_COUNT_MAX = 30;
+// Per-entry render history caps reuse the bible's existing limits so a
+// variation/sheet entry can't accrue more refs than canon already allows.
+export const IMAGE_REFS_PER_ENTRY_MAX = BIBLE_LIMITS.IMAGE_REFS_PER_ENTRY_MAX;
+export const IMAGE_REF_FILENAME_MAX = BIBLE_LIMITS.IMAGE_REF_MAX;
+// `entryRef.kind` discriminator — the kind tag that universeRun job tags carry
+// so the collection hook knows which list to append the rendered filename to.
+export const ENTRY_REF_KIND = Object.freeze({
+ VARIATION: 'variation',
+ SHEET: 'sheet',
+ CANON: 'canon',
+});
// Influences — structured token lists that ARE the universe's style + negative
// prompts. Surfaced in the UI as "Style prompt" (embrace) and "Negative prompt"
@@ -215,6 +226,60 @@ export const normalizeCategoryKey = (raw) => {
// ("character_variations", "Characters", etc.) after key normalization.
const isCharactersBucket = (k) => /^characters?(_|$)/i.test(normalizeCategoryKey(k));
+// Mint a stable id when raw is missing/blank. Variations and composite sheets
+// historically had no id (just label+prompt); ensuring one now means rename and
+// bucket-move preserve the linkage to the entry's rendered imageRefs[]. Existing
+// non-empty ids are normalized (whitespace-trimmed and capped to 80 chars) on
+// every read/write, so callers controlling ids (sync importer) should supply
+// already-normalized values to ensure verbatim round-trip — any leading/trailing
+// whitespace or excess length will be silently truncated.
+//
+// WARNING: minted ids are NOT persisted by readState() — every read of a
+// legacy record mints a fresh UUID. Callers that queue async work referencing
+// the id (e.g. an `entryRef` on a render job that a completion hook will
+// resolve later) must force a write first via `needsEntryIdPersist(id)` +
+// `updateUniverse(id, () => ({}))` so the queued id matches the next read.
+const ensureEntryId = (raw, prefix) => {
+ if (isStr(raw) && raw.trim()) return raw.trim().slice(0, 80);
+ return `${prefix}${randomUUID()}`;
+};
+
+// Sanitize a filename-only image reference. Basename strip + traversal guards
+// mirror server/lib/fileUtils.js#resolveGalleryImage — no FS check here because
+// sanitize runs on every read. Stale-file collapse happens in the UI via the
+// thumbnail's onError fallback.
+const sanitizeImageRefFilename = (raw) => {
+ if (!isStr(raw)) return '';
+ const trimmed = raw.trim().slice(0, IMAGE_REF_FILENAME_MAX);
+ if (!trimmed) return '';
+ // Reject any path separator before basename() — POSIX basename() doesn't
+ // treat `\` as a separator, so a Windows-style traversal like `..\foo.png`
+ // would otherwise pass through as a single token.
+ if (/[/\\]/.test(trimmed)) return '';
+ const safe = basename(trimmed);
+ if (!safe || safe === '.' || safe === '..') return '';
+ return safe;
+};
+
+// Render history for variations + composite sheets. Newest last. Deduped so a
+// re-render that produced the same gallery filename doesn't bloat the list.
+const sanitizeEntryImageRefs = (raw) => {
+ if (!Array.isArray(raw)) return [];
+ const out = [];
+ const seen = new Set();
+ for (const v of raw) {
+ const safe = sanitizeImageRefFilename(v);
+ if (!safe || seen.has(safe)) continue;
+ seen.add(safe);
+ out.push(safe);
+ }
+ // Keep the most recent `IMAGE_REFS_PER_ENTRY_MAX` entries — older ones drop
+ // off the front so the cap doesn't strand new renders.
+ return out.length > IMAGE_REFS_PER_ENTRY_MAX
+ ? out.slice(-IMAGE_REFS_PER_ENTRY_MAX)
+ : out;
+};
+
const sanitizeVariation = (raw) => {
if (!raw || typeof raw !== 'object') return null;
const label = trimTo(raw.label, VARIATION_LABEL_MAX);
@@ -223,7 +288,12 @@ const sanitizeVariation = (raw) => {
// Per-item lock — when true, expand merges preserve this entry instead of
// letting the LLM regenerate it. Only `true` is recorded; missing/false
// collapses to undefined so the on-disk shape stays minimal.
- const out = { label, prompt };
+ const out = {
+ id: ensureEntryId(raw.id, 'var-'),
+ label,
+ prompt,
+ imageRefs: sanitizeEntryImageRefs(raw.imageRefs),
+ };
if (raw.locked === true) out.locked = true;
return out;
};
@@ -234,7 +304,13 @@ const sanitizeCompositeSheet = (raw) => {
const prompt = trimTo(raw.prompt, COMPOSITE_PROMPT_MAX);
if (!label || !prompt) return null;
const kind = COMPOSITE_SHEET_KINDS.includes(raw.kind) ? raw.kind : 'reference_sheet';
- const out = { kind, label, prompt };
+ const out = {
+ id: ensureEntryId(raw.id, 'sheet-'),
+ kind,
+ label,
+ prompt,
+ imageRefs: sanitizeEntryImageRefs(raw.imageRefs),
+ };
if (raw.locked === true) out.locked = true;
return out;
};
@@ -715,6 +791,34 @@ export async function getUniverse(id) {
return w;
}
+// Returns true when the raw on-disk universe carries variations or composite
+// sheets that are missing a stable `id` field — i.e. sanitizeTemplate would
+// mint fresh UUIDs (and those UUIDs would differ on every read until the
+// migration is persisted). The render route uses this to gate a one-time
+// no-op write before queueing jobs whose `entryRef.id` must match the on-disk
+// record at completion time. Reads raw JSON without sanitizing, so callers
+// can skip the write entirely when the universe is already fully migrated —
+// avoiding unwanted `updatedAt` bumps that would otherwise interfere with
+// LWW sync and trigger spurious re-export/notification emits.
+export async function needsEntryIdPersist(id) {
+ await ensureDir(PATHS.data);
+ const raw = await readJSONFile(statePath(), DEFAULT_STATE, { logError: false });
+ const rec = Array.isArray(raw.universes) ? raw.universes.find((u) => u?.id === id) : null;
+ if (!rec) return false;
+ const cats = rec.categories && typeof rec.categories === 'object' ? rec.categories : {};
+ for (const cat of Object.values(cats)) {
+ const vars = Array.isArray(cat?.variations) ? cat.variations : [];
+ for (const v of vars) {
+ if (!isStr(v?.id) || !v.id.trim()) return true;
+ }
+ }
+ const sheets = Array.isArray(rec.compositeSheets) ? rec.compositeSheets : [];
+ for (const s of sheets) {
+ if (!isStr(s?.id) || !s.id.trim()) return true;
+ }
+ return false;
+}
+
export async function createUniverse(input = {}) {
const name = trimTo(input.name, NAME_MAX_LENGTH);
if (!name) throw makeErr(`Universe name is required (1..${NAME_MAX_LENGTH} chars)`, ERR_VALIDATION);
@@ -897,6 +1001,36 @@ export async function updateUniverse(id, patchOrMutator = {}) {
});
}
+ // Server-stamped render history on variations + composite sheets. The
+ // collection hook is the sole writer (via the mutator-form of
+ // updateUniverse, which bypasses this guard). A literal-object PATCH that
+ // round-trips the variation body the client loaded before a render
+ // completed would otherwise clobber the freshly-appended filename. Match
+ // by `id` and preserve cur's `imageRefs` when it has more entries than
+ // the patch OR when their tails differ (the at-cap rotation case, where
+ // an append drops the oldest and lengths stay equal). Same-length +
+ // same-tail means the client is current and the patch survives — note
+ // that as a corollary, an empty patched list against a non-empty cur is
+ // treated as stale and cur's history is preserved (the current UI has
+ // no explicit-clear control, so this is the safer default).
+ if (!isMutator && 'categories' in patch && patch.categories && typeof patch.categories === 'object') {
+ for (const [catKey, catVal] of Object.entries(mergedCategories)) {
+ if (!catVal || !Array.isArray(catVal.variations)) continue;
+ const curCat = cur.categories?.[catKey];
+ if (!curCat || !Array.isArray(curCat.variations)) continue;
+ // Only run preservation against categories the patch actually sent —
+ // categories preserved verbatim from cur already have the right imageRefs.
+ if (!(catKey in patch.categories)) continue;
+ mergedCategories[catKey] = {
+ ...catVal,
+ variations: preserveImageRefsById(catVal.variations, curCat.variations),
+ };
+ }
+ }
+ if (!isMutator && Array.isArray(scalarPatch.compositeSheets) && Array.isArray(cur.compositeSheets)) {
+ scalarPatch.compositeSheets = preserveImageRefsById(scalarPatch.compositeSheets, cur.compositeSheets);
+ }
+
const mergedRecord = sanitizeTemplate({
...cur,
...scalarPatch,
@@ -1030,6 +1164,88 @@ export async function listRuns(universeId = null) {
return [...filtered].sort((a, b) => (b.createdAt || '').localeCompare(a.createdAt || ''));
}
+// Append a rendered gallery filename to the imageRefs[] of the entry the job
+// targeted. `entryRef` shape mirrors what `compilePrompts` stamps onto each
+// job (see `universeRun.entryRef`); the mutator branches on `kind`:
+// - 'variation' → `universe.categories[categoryKey].variations[id]`
+// - 'sheet' → `universe.compositeSheets[id]`
+// - 'canon' → `universe[kindKey][id]` (characters/places/objects)
+// Dedupes against the existing list so a re-render that produces the same
+// filename doesn't bloat the history. Runs through `updateUniverse`'s mutator
+// form so the read→modify→write window is serialized against concurrent edits
+// on the same universe.
+export async function appendEntryImageRef(universeId, entryRef, filename) {
+ if (!isStr(universeId) || !entryRef || typeof entryRef !== 'object') return null;
+ // Apply the same filename guard the sanitizer uses on round-trip so a
+ // pathy or traversal-laden filename is rejected up-front rather than
+ // entering the queued write and triggering a no-op `updatedAt` bump
+ // when sanitizeTemplate strips it on the way out.
+ const safe = sanitizeImageRefFilename(filename);
+ if (!safe) return null;
+ return updateUniverse(universeId, (cur) => {
+ if (entryRef.kind === ENTRY_REF_KIND.VARIATION && isStr(entryRef.categoryKey) && isStr(entryRef.id)) {
+ const cat = cur.categories?.[entryRef.categoryKey];
+ const variations = mapAppendImageRef(cat?.variations, entryRef.id, safe);
+ if (!variations) return null;
+ return { categories: { [entryRef.categoryKey]: { ...cat, variations } } };
+ }
+ if (entryRef.kind === ENTRY_REF_KIND.SHEET && isStr(entryRef.id)) {
+ const sheets = mapAppendImageRef(cur.compositeSheets, entryRef.id, safe);
+ if (!sheets) return null;
+ return { compositeSheets: sheets };
+ }
+ if (entryRef.kind === ENTRY_REF_KIND.CANON && isStr(entryRef.kindKey) && isStr(entryRef.id)) {
+ const list = mapAppendImageRef(cur[entryRef.kindKey], entryRef.id, safe);
+ if (!list) return null;
+ return { [entryRef.kindKey]: list };
+ }
+ return null;
+ });
+}
+
+// Preserve cur's `imageRefs` on entries the patch round-tripped from a stale
+// load. Match by `id`; we consider the patch stale (and restore cur's history)
+// when EITHER cur's list has more entries than the patch's OR the newest entry
+// (tail) differs between cur and patch. The tail check catches the at-cap case:
+// once imageRefs is at IMAGE_REFS_PER_ENTRY_MAX (12), a server-side append
+// rotates the list — pushing the new filename and dropping the oldest — so
+// lengths stay equal even though cur is strictly newer. Comparing tails
+// detects this; a stale client PATCH (with the pre-rotation list) has a
+// different last element than the freshly-appended cur. Used by both the
+// variations and composite-sheets preservation paths in updateUniverse.
+function preserveImageRefsById(next, prev) {
+ if (!Array.isArray(next) || !Array.isArray(prev)) return next;
+ const prevById = new Map(prev.filter((p) => p?.id).map((p) => [p.id, p]));
+ return next.map((n) => {
+ const p = n?.id ? prevById.get(n.id) : null;
+ if (!p) return n;
+ const prevRefs = Array.isArray(p.imageRefs) ? p.imageRefs : [];
+ const nextRefs = Array.isArray(n.imageRefs) ? n.imageRefs : [];
+ if (prevRefs.length === 0) return n;
+ // Restore when cur has strictly more refs (patch dropped some) OR cur has
+ // a different newest entry than the patch (server-side rotation at cap).
+ // Equal-length + same tail means the patch is current and survives.
+ const isStale =
+ prevRefs.length > nextRefs.length ||
+ (prevRefs.length > 0 && prevRefs[prevRefs.length - 1] !== nextRefs[nextRefs.length - 1]);
+ return isStale ? { ...n, imageRefs: prevRefs } : n;
+ });
+}
+
+// Append `filename` (deduped + capped to IMAGE_REFS_PER_ENTRY_MAX) to the
+// imageRefs[] of the entry in `list` matched by `id`. Returns the new list,
+// or `null` when the id isn't present so the caller can short-circuit.
+function mapAppendImageRef(list, id, filename) {
+ if (!Array.isArray(list) || !list.some((e) => e?.id === id)) return null;
+ return list.map((e) => {
+ if (e?.id !== id) return e;
+ const refs = Array.isArray(e.imageRefs) ? e.imageRefs : [];
+ if (refs.includes(filename)) return e;
+ const next = [...refs, filename];
+ return { ...e, imageRefs: next.length > IMAGE_REFS_PER_ENTRY_MAX ? next.slice(-IMAGE_REFS_PER_ENTRY_MAX) : next };
+ });
+}
+
// Join an influence list (embrace or avoid) into the comma-separated string
// shape the renderer's `composeStyledPrompt` consumes. Tokens have already
// been deduped + capped by `sanitizeInfluenceList` at write time, so this is
@@ -1199,6 +1415,13 @@ export function compilePrompts(universe, options = {}) {
prompt,
negativePrompt,
batchIndex: i,
+ // `entryRef` lets the collection hook stamp the rendered filename
+ // back onto this exact variation regardless of subsequent label
+ // edits or bucket moves. Older universes can be missing `id` until
+ // the next write through sanitizeTemplate — fall through silently
+ // when that happens; the variation just won't accrue a render
+ // history until it next gets persisted.
+ ...(variation.id ? { entryRef: { kind: ENTRY_REF_KIND.VARIATION, categoryKey: category, id: variation.id } } : {}),
});
}
}
@@ -1223,6 +1446,7 @@ export function compilePrompts(universe, options = {}) {
prompt,
negativePrompt,
batchIndex: i,
+ ...(sheet.id ? { entryRef: { kind: ENTRY_REF_KIND.SHEET, id: sheet.id } } : {}),
});
}
}
@@ -1265,6 +1489,7 @@ export function compilePrompts(universe, options = {}) {
prompt,
negativePrompt,
batchIndex: i,
+ ...(entry.id ? { entryRef: { kind: ENTRY_REF_KIND.CANON, kindKey: trunk.key, id: entry.id } } : {}),
});
}
}
diff --git a/server/services/universeBuilder.test.js b/server/services/universeBuilder.test.js
index 36dd342294..8c0502082c 100644
--- a/server/services/universeBuilder.test.js
+++ b/server/services/universeBuilder.test.js
@@ -123,8 +123,10 @@ describe("universeBuilder service", () => {
});
expect(w.categories.clothing_styles.variations).toEqual([
{
+ id: expect.stringMatching(/^var-/),
label: "Rib-Cage Nomads",
prompt: "reference sheet, layered sailcloth, bone toggles",
+ imageRefs: [],
},
]);
expect(w.categories.factions.variations).toHaveLength(1);
@@ -143,10 +145,12 @@ describe("universeBuilder service", () => {
});
expect(w.compositeSheets).toEqual([
{
+ id: expect.stringMatching(/^sheet-/),
kind: "reference_sheet",
label: "Gas-Giant Drifters costume sheet",
prompt:
"Create a clean illustrated costume reference sheet with five figures, materials swatches, fasteners, accessories, and color palette strip.",
+ imageRefs: [],
},
]);
});
@@ -164,10 +168,12 @@ describe("universeBuilder service", () => {
});
expect(w.compositeSheets).toEqual([
{
+ id: expect.stringMatching(/^sheet-/),
kind: "world_pitch_poster",
label: "Universe summary concept pitch poster",
prompt:
"Create a cinematic universe summary concept pitch poster with hero panorama, inset environments, cultures, creatures, visual language, color palette, materials, light atmosphere, and theme icons.",
+ imageRefs: [],
},
]);
});
@@ -1411,6 +1417,317 @@ describe("universeBuilder service", () => {
});
});
+ describe("entry ids + render history", () => {
+ it("sanitizeTemplate mints stable ids for variations + composite sheets", async () => {
+ const u = await svc.createUniverse({
+ name: "Avatars",
+ categories: {
+ landscapes: { variations: [{ label: "L1", prompt: "p1" }] },
+ },
+ compositeSheets: [{ kind: "reference_sheet", label: "S1", prompt: "sp" }],
+ });
+ const v = u.categories.landscapes.variations[0];
+ expect(v.id).toMatch(/^var-/);
+ expect(v.imageRefs).toEqual([]);
+ const sheet = u.compositeSheets[0];
+ expect(sheet.id).toMatch(/^sheet-/);
+ expect(sheet.imageRefs).toEqual([]);
+ });
+
+ it("sanitizeTemplate round-trips existing variation + sheet ids verbatim", async () => {
+ fileStore.set("/mock/data/universe-builder.json", {
+ universes: [
+ {
+ id: "w1",
+ name: "X",
+ schemaVersion: svc.CURRENT_SCHEMA_VERSION,
+ categories: {
+ landscapes: {
+ kind: "places",
+ variations: [{ id: "var-keep-me", label: "V1", prompt: "p1" }],
+ },
+ },
+ compositeSheets: [{ id: "sheet-keep-me", kind: "reference_sheet", label: "S1", prompt: "sp" }],
+ createdAt: "2024-01-01T00:00:00Z",
+ },
+ ],
+ runs: [],
+ });
+ const list = await svc.listUniverses();
+ expect(list[0].categories.landscapes.variations[0].id).toBe("var-keep-me");
+ expect(list[0].compositeSheets[0].id).toBe("sheet-keep-me");
+ });
+
+ it("legacy universe (no variation ids on disk) gets unstable in-memory ids until persisted, then stable after a write", async () => {
+ // Plant a pre-PR universe shape with no variation/sheet ids. Reads
+ // through readState() mint fresh UUIDs each call because the migration
+ // is not persisted there (race-safety against concurrent writers — see
+ // readState() docstring). After a no-op updateUniverse() forces a write,
+ // ids land on disk and every subsequent read returns the same ones.
+ fileStore.set("/mock/data/universe-builder.json", {
+ universes: [
+ {
+ id: "legacy-universe",
+ name: "Legacy",
+ schemaVersion: svc.CURRENT_SCHEMA_VERSION,
+ categories: {
+ landscapes: { kind: "places", variations: [{ label: "L1", prompt: "p1" }] },
+ },
+ compositeSheets: [],
+ createdAt: "2024-01-01T00:00:00Z",
+ },
+ ],
+ runs: [],
+ });
+ const a = await svc.getUniverse("legacy-universe");
+ const b = await svc.getUniverse("legacy-universe");
+ expect(a.categories.landscapes.variations[0].id).not.toBe(b.categories.landscapes.variations[0].id);
+ // No-op mutator persists the in-memory sanitized shape (the render
+ // route uses this to lock in entryRef.id before queueing jobs).
+ const persisted = await svc.updateUniverse("legacy-universe", () => ({}));
+ const variationIdPersisted = persisted.categories.landscapes.variations[0].id;
+ const c = await svc.getUniverse("legacy-universe");
+ expect(c.categories.landscapes.variations[0].id).toBe(variationIdPersisted);
+ // appendEntryImageRef against the persisted id now succeeds.
+ await svc.appendEntryImageRef("legacy-universe", { kind: "variation", categoryKey: "landscapes", id: variationIdPersisted }, "after-persist.png");
+ const d = await svc.getUniverse("legacy-universe");
+ expect(d.categories.landscapes.variations[0].imageRefs).toEqual(["after-persist.png"]);
+ });
+
+ it("needsEntryIdPersist returns true only when raw-disk variations or sheets lack ids", async () => {
+ // Mixed fixture: one universe has ids on disk, the other doesn't.
+ // The render route uses this helper to skip the no-op write when the
+ // universe is already migrated — so already-upgraded records don't
+ // bump updatedAt (which would interfere with LWW sync + spuriously
+ // emit recordUpdated on every render).
+ fileStore.set("/mock/data/universe-builder.json", {
+ universes: [
+ {
+ id: "fresh",
+ name: "Fresh",
+ schemaVersion: svc.CURRENT_SCHEMA_VERSION,
+ categories: {
+ landscapes: { kind: "places", variations: [{ id: "var-on-disk", label: "L", prompt: "p" }] },
+ },
+ compositeSheets: [{ id: "sheet-on-disk", kind: "reference_sheet", label: "S", prompt: "sp" }],
+ createdAt: "2024-01-01T00:00:00Z",
+ },
+ {
+ id: "legacy",
+ name: "Legacy",
+ schemaVersion: svc.CURRENT_SCHEMA_VERSION,
+ categories: {
+ landscapes: { kind: "places", variations: [{ label: "L", prompt: "p" }] },
+ },
+ compositeSheets: [],
+ createdAt: "2024-01-01T00:00:00Z",
+ },
+ {
+ id: "legacy-sheet",
+ name: "LegacySheet",
+ schemaVersion: svc.CURRENT_SCHEMA_VERSION,
+ categories: {},
+ compositeSheets: [{ kind: "reference_sheet", label: "S", prompt: "sp" }],
+ createdAt: "2024-01-01T00:00:00Z",
+ },
+ ],
+ runs: [],
+ });
+ expect(await svc.needsEntryIdPersist("fresh")).toBe(false);
+ expect(await svc.needsEntryIdPersist("legacy")).toBe(true);
+ expect(await svc.needsEntryIdPersist("legacy-sheet")).toBe(true);
+ expect(await svc.needsEntryIdPersist("does-not-exist")).toBe(false);
+ });
+
+ it("appendEntryImageRef appends to a variation's imageRefs by id", async () => {
+ const u = await svc.createUniverse({
+ name: "Bucket",
+ categories: { landscapes: { variations: [{ label: "L1", prompt: "p1" }] } },
+ });
+ const variationId = u.categories.landscapes.variations[0].id;
+ await svc.appendEntryImageRef(u.id, { kind: "variation", categoryKey: "landscapes", id: variationId }, "rendered-1.png");
+ await svc.appendEntryImageRef(u.id, { kind: "variation", categoryKey: "landscapes", id: variationId }, "rendered-2.png");
+ const updated = await svc.getUniverse(u.id);
+ expect(updated.categories.landscapes.variations[0].imageRefs).toEqual(["rendered-1.png", "rendered-2.png"]);
+ });
+
+ it("appendEntryImageRef rejects pathy filenames up-front (no queued write)", async () => {
+ // A renderer that ever returns a path-laden filename should be
+ // rejected at the helper boundary — letting it through would trigger
+ // a no-op write (sanitizer strips it later) and pointlessly bump
+ // updatedAt + emit recordUpdated.
+ const u = await svc.createUniverse({
+ name: "PathReject",
+ categories: { landscapes: { variations: [{ label: "L1", prompt: "p1" }] } },
+ });
+ const variationId = u.categories.landscapes.variations[0].id;
+ const before = (await svc.getUniverse(u.id)).updatedAt;
+ const result1 = await svc.appendEntryImageRef(u.id, { kind: "variation", categoryKey: "landscapes", id: variationId }, "../escape.png");
+ const result2 = await svc.appendEntryImageRef(u.id, { kind: "variation", categoryKey: "landscapes", id: variationId }, "sub/file.png");
+ const result3 = await svc.appendEntryImageRef(u.id, { kind: "variation", categoryKey: "landscapes", id: variationId }, "..\\windows.png");
+ expect(result1).toBe(null);
+ expect(result2).toBe(null);
+ expect(result3).toBe(null);
+ const after = (await svc.getUniverse(u.id)).updatedAt;
+ expect(after).toBe(before);
+ });
+
+ it("appendEntryImageRef dedupes a same-filename repeat render", async () => {
+ const u = await svc.createUniverse({
+ name: "Dedupe",
+ compositeSheets: [{ kind: "reference_sheet", label: "S1", prompt: "sp" }],
+ });
+ const sheetId = u.compositeSheets[0].id;
+ await svc.appendEntryImageRef(u.id, { kind: "sheet", id: sheetId }, "x.png");
+ await svc.appendEntryImageRef(u.id, { kind: "sheet", id: sheetId }, "x.png");
+ const updated = await svc.getUniverse(u.id);
+ expect(updated.compositeSheets[0].imageRefs).toEqual(["x.png"]);
+ });
+
+ it("appendEntryImageRef appends to a canon entry's imageRefs by id", async () => {
+ const u = await svc.createUniverse({
+ name: "Canon",
+ places: [{ id: "set-abc", name: "Library" }],
+ });
+ await svc.appendEntryImageRef(u.id, { kind: "canon", kindKey: "places", id: "set-abc" }, "place-render.png");
+ const updated = await svc.getUniverse(u.id);
+ expect(updated.places[0].imageRefs).toContain("place-render.png");
+ });
+
+ it("appendEntryImageRef is a no-op when entry id no longer exists", async () => {
+ const u = await svc.createUniverse({ name: "Gone" });
+ const result = await svc.appendEntryImageRef(u.id, { kind: "variation", categoryKey: "landscapes", id: "var-missing" }, "x.png");
+ // The mutator returns null → updateUniverse skips the write and resolves
+ // with the unchanged record. Either shape is fine; we just want no throw.
+ expect(result).toBeTruthy();
+ });
+
+ it("stale literal-object PATCH does not clobber server-stamped imageRefs (variations)", async () => {
+ const u = await svc.createUniverse({
+ name: "Stale",
+ categories: { landscapes: { variations: [{ label: "L1", prompt: "p1" }] } },
+ });
+ const variationId = u.categories.landscapes.variations[0].id;
+ // Server stamps a render history while the client is editing.
+ await svc.appendEntryImageRef(u.id, { kind: "variation", categoryKey: "landscapes", id: variationId }, "fresh.png");
+ // Client (loaded BEFORE the render landed) PATCHes a label edit with
+ // an empty imageRefs list. The stale-guard must preserve the freshly
+ // appended filename.
+ await svc.updateUniverse(u.id, {
+ categories: {
+ landscapes: {
+ kind: "places",
+ variations: [{ id: variationId, label: "L1 renamed", prompt: "p1", imageRefs: [] }],
+ },
+ },
+ });
+ const final = await svc.getUniverse(u.id);
+ const v = final.categories.landscapes.variations[0];
+ expect(v.label).toBe("L1 renamed");
+ expect(v.imageRefs).toEqual(["fresh.png"]);
+ });
+
+ it("stale literal-object PATCH does not clobber server-stamped imageRefs (composite sheets)", async () => {
+ const u = await svc.createUniverse({
+ name: "StaleSheet",
+ compositeSheets: [{ kind: "reference_sheet", label: "S1", prompt: "sp" }],
+ });
+ const sheetId = u.compositeSheets[0].id;
+ await svc.appendEntryImageRef(u.id, { kind: "sheet", id: sheetId }, "sheet.png");
+ await svc.updateUniverse(u.id, {
+ compositeSheets: [{ id: sheetId, kind: "reference_sheet", label: "S1 renamed", prompt: "sp" }],
+ });
+ const final = await svc.getUniverse(u.id);
+ expect(final.compositeSheets[0].label).toBe("S1 renamed");
+ expect(final.compositeSheets[0].imageRefs).toEqual(["sheet.png"]);
+ });
+
+ it("stale at-cap PATCH detects rotation via tail mismatch (variations)", async () => {
+ // Seed a variation whose imageRefs is already at the cap. A server-side
+ // append rotates the list (drops oldest, pushes newest) — lengths stay
+ // equal, so the stale-PATCH guard must compare the tail element, not
+ // just the length.
+ const cap = svc.IMAGE_REFS_PER_ENTRY_MAX;
+ const capRefs = Array.from({ length: cap }, (_, i) => `r${i}.png`);
+ const u = await svc.createUniverse({
+ name: "Capped",
+ categories: { landscapes: { variations: [{ label: "L1", prompt: "p1", imageRefs: capRefs }] } },
+ });
+ const variationId = u.categories.landscapes.variations[0].id;
+ // Server appends a new render — list rotates (r0.png drops off, fresh.png appended).
+ await svc.appendEntryImageRef(u.id, { kind: "variation", categoryKey: "landscapes", id: variationId }, "fresh.png");
+ // Stale client (loaded BEFORE the rotation) PATCHes with the
+ // pre-rotation list — same length, but tail is r{cap-1}.png instead of
+ // fresh.png. Without the tail check, the stale list would clobber the
+ // server-stamped fresh.png.
+ await svc.updateUniverse(u.id, {
+ categories: {
+ landscapes: {
+ kind: "places",
+ variations: [{ id: variationId, label: "L1 renamed", prompt: "p1", imageRefs: capRefs }],
+ },
+ },
+ });
+ const final = await svc.getUniverse(u.id);
+ const v = final.categories.landscapes.variations[0];
+ expect(v.label).toBe("L1 renamed");
+ // Tail should still be fresh.png (the server-stamped newest), not the
+ // pre-rotation r{cap-1}.png from the stale patch.
+ expect(v.imageRefs[v.imageRefs.length - 1]).toBe("fresh.png");
+ });
+
+ it("compilePrompts stamps entryRef on each compiled prompt", () => {
+ const universe = {
+ id: "w1",
+ influences: { embrace: [], avoid: [] },
+ categories: {
+ landscapes: { kind: "places", variations: [{ id: "var-1", label: "L1", prompt: "p1" }] },
+ },
+ compositeSheets: [{ id: "sheet-1", kind: "reference_sheet", label: "S1", prompt: "sp" }],
+ characters: [],
+ places: [{ id: "set-abc", name: "Library" }],
+ objects: [],
+ };
+ const variationCompiled = svc.compilePrompts(universe, { promptMode: "variations" });
+ expect(variationCompiled).toHaveLength(1);
+ expect(variationCompiled[0].entryRef).toEqual({ kind: "variation", categoryKey: "landscapes", id: "var-1" });
+
+ const sheetCompiled = svc.compilePrompts(universe, { promptMode: "sheets" });
+ expect(sheetCompiled).toHaveLength(1);
+ expect(sheetCompiled[0].entryRef).toEqual({ kind: "sheet", id: "sheet-1" });
+
+ const canonCompiled = svc.compilePrompts(universe, {
+ promptMode: "canon",
+ canonSelection: { places: "all" },
+ });
+ expect(canonCompiled).toHaveLength(1);
+ expect(canonCompiled[0].entryRef).toEqual({ kind: "canon", kindKey: "places", id: "set-abc" });
+ });
+
+ it("imageRefs basename guard rejects path-separator filenames", async () => {
+ fileStore.set("/mock/data/universe-builder.json", {
+ universes: [
+ {
+ id: "w1",
+ name: "Guard",
+ schemaVersion: svc.CURRENT_SCHEMA_VERSION,
+ categories: {
+ landscapes: {
+ kind: "places",
+ variations: [{ id: "var-1", label: "L", prompt: "p", imageRefs: ["../escape.png", "normal.png", "/abs/path.png", "..\\windows.png", "sub\\dir.png", "ok.png"] }],
+ },
+ },
+ compositeSheets: [],
+ createdAt: "2024-01-01T00:00:00Z",
+ },
+ ],
+ runs: [],
+ });
+ const list = await svc.listUniverses();
+ expect(list[0].categories.landscapes.variations[0].imageRefs).toEqual(["normal.png", "ok.png"]);
+ });
+ });
+
describe("sanitizers", () => {
it("drops malformed variations on read", async () => {
// Manually plant invalid state — sanitizeTemplate strips it on read.
diff --git a/server/services/universeBuilderCollectionHook.js b/server/services/universeBuilderCollectionHook.js
index a692318b70..07a02aa661 100644
--- a/server/services/universeBuilderCollectionHook.js
+++ b/server/services/universeBuilderCollectionHook.js
@@ -24,6 +24,7 @@
import { mediaJobEvents } from './mediaJobQueue/index.js';
import { addItem, ERR_DUPLICATE } from './mediaCollections.js';
import { withReexportSuppressed, emitRecordUpdated } from './sharing/recordEvents.js';
+import { appendEntryImageRef } from './universeBuilder.js';
// runId → { universeId, pending }. Pure in-memory; lost on restart.
const activeRuns = new Map();
@@ -76,13 +77,34 @@ export function initUniverseBuilderCollectionHook() {
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
+ // alongside `addItem` under the same re-export-suppression scope, so a
+ // single coalesced emit fires when the run finishes. Best-effort —
+ // 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;
+ });
+ };
+
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.
+ // The two writes touch independent files (media-collections.json vs
+ // universe-builder.json) and have no ordering dependency — fire them
+ // in parallel so a 160-image batch run doesn't pay double the
+ // per-completion serialization cost.
+ const work = async () => {
+ const [s] = await Promise.all([addItemCall(), appendEntryRefCall()]);
+ return s;
+ };
const status = runActive && tag.universeId
- ? await withReexportSuppressed('universe', tag.universeId, addItemCall)
- : await addItemCall();
+ ? await withReexportSuppressed('universe', tag.universeId, work)
+ : await work();
if (status === 'added') {
console.log(`🌍 universe-builder run=${tag.runId?.slice(0, 8)} category=${tag.category} → ${filename}`);
diff --git a/server/services/universeBuilderExpand.test.js b/server/services/universeBuilderExpand.test.js
index 2fde0a65f6..55552da2eb 100644
--- a/server/services/universeBuilderExpand.test.js
+++ b/server/services/universeBuilderExpand.test.js
@@ -159,8 +159,8 @@ describe("universeBuilderExpand.normalizeCategories", () => {
landscapes: ["Crystalline canyon basin", "Salt flat ruins"],
});
expect(out.landscapes.variations).toEqual([
- { label: "Crystalline canyon basin", prompt: "Crystalline canyon basin" },
- { label: "Salt flat ruins", prompt: "Salt flat ruins" },
+ { id: expect.stringMatching(/^var-/), label: "Crystalline canyon basin", prompt: "Crystalline canyon basin", imageRefs: [] },
+ { id: expect.stringMatching(/^var-/), label: "Salt flat ruins", prompt: "Salt flat ruins", imageRefs: [] },
]);
});
@@ -183,7 +183,7 @@ describe("universeBuilderExpand.normalizeCategories", () => {
},
});
expect(out.vehicles.variations).toEqual([
- { label: "Walker mech", prompt: "rusted six-leg walker mech" },
+ { id: expect.stringMatching(/^var-/), label: "Walker mech", prompt: "rusted six-leg walker mech", imageRefs: [] },
]);
});
@@ -200,7 +200,7 @@ describe("universeBuilderExpand.normalizeCategories", () => {
},
});
expect(out.structures.variations).toEqual([
- { label: "Tower", prompt: "spire of obsidian" },
+ { id: expect.stringMatching(/^var-/), label: "Tower", prompt: "spire of obsidian", imageRefs: [] },
]);
});
@@ -215,7 +215,7 @@ describe("universeBuilderExpand.normalizeCategories", () => {
});
expect(out.landscapes.variations).toHaveLength(1);
expect(out.raider_pirate_clans.variations).toEqual([
- { label: "Wake Jackals", prompt: "spare moebius scavenger raiders" },
+ { id: expect.stringMatching(/^var-/), label: "Wake Jackals", prompt: "spare moebius scavenger raiders", imageRefs: [] },
]);
});
@@ -258,10 +258,12 @@ describe("universeBuilderExpand.normalizeCompositeSheets", () => {
]);
expect(out).toEqual([
{
+ id: expect.stringMatching(/^sheet-/),
kind: "reference_sheet",
label: "Gas-Giant Drifters costume sheet",
prompt:
"Create a clean illustrated costume reference sheet with five figures, material swatches, fasteners, accessories, color palette strip, and simple floating-platform background.",
+ imageRefs: [],
},
]);
});
@@ -270,9 +272,11 @@ describe("universeBuilderExpand.normalizeCompositeSheets", () => {
const out = normalizeCompositeSheets(["Canopy Symbiotes reference board"]);
expect(out).toEqual([
{
+ id: expect.stringMatching(/^sheet-/),
kind: "reference_sheet",
label: "Canopy Symbiotes reference board",
prompt: "Canopy Symbiotes reference board",
+ imageRefs: [],
},
]);
});
@@ -288,10 +292,12 @@ describe("universeBuilderExpand.normalizeCompositeSheets", () => {
]);
expect(out).toEqual([
{
+ id: expect.stringMatching(/^sheet-/),
kind: "world_pitch_poster",
label: "Universe summary concept pitch poster",
prompt:
"Create a cinematic universe summary concept pitch poster with hero panorama, inset environments, culture callouts, palette, materials, light atmosphere, and theme icons.",
+ imageRefs: [],
},
]);
});