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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat(universe-builder): lock-by-default canon + per-row render thumbnails
[._.]/ Adam Eivye506e600be8d
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex e231e24cab..9bbb20520b 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -14,6 +14,7 @@### Universe Builder+- **Lock-by-default for canon, variations, and composite sheets + per-row render thumbnails.** Universe canon entries (characters / places / objects), category-bucket variations, and composite sheets are now locked on creation so AI rewrite paths (refine, differentiate, expand-merge) skip them until the user explicitly unlocks. Lock guards prompt-data rewrites only — render paths stay open on locked entries (rendering an image doesn't mutate the prompt; it just appends to `imageRefs[]`). Server-side: `sanitizeVariation` + `sanitizeCompositeSheet` default `locked: true`, `applyCanonExtras` in `storyBible.js` now persists both `locked: true` and `locked: false` (the writers-room legacy "absent = unlocked" shape stays for callers that never set the flag), `sanitizeTemplate` runs a `defaultLockCanon` pass on universe canon arrays so existing on-disk records read locked, and `extractCanonFromProse` defaults `autoLock: true` (with explicit `autoLock: false` opt-out that stamps `locked: false` on new inserts to survive the universe-side default). `promoteVariationToCanon` stamps `locked: true` on the promoted entry. Two new bulk endpoints: `PATCH /api/universe-builder/:id/canon/:kind/lock-all` and `PATCH /api/universe-builder/:id/variations/lock-all` (the latter accepts `{ category, includeSheets }`). Client adds a single icon-only **lock-all toggle** to every section header (canon Characters / Places / Objects sections, each category variation bucket, composite-boards section) that mirrors the per-item lock-toggle visual: Lock icon when everything is locked → click unlocks all, Unlock icon for the all-unlocked + mixed cases → click locks all so the toggle always normalizes upward. Per-item lock toggles now write explicit `locked: false` on unlock so the bit survives the next read. **Per-row render thumbnails** in every variation and canon card: `EntryThumbSlot` is a three-state slot (pending / empty / completed) that swaps in a `MediaJobThumb` spinner during a render, a portrait placeholder box with a Sparkles render button when no images exist yet, or the rendered avatar once complete. Pending state is driven by a new `entryJobs: [{ jobId, entryRef }]` field on the `/render` route response + a `pendingByEntryId` map on the universe-builder page; completion fires through `useMediaJobProgress` and optimistically appends the rendered filename to the row's `imageRefs[]`. New `xs` size on `MediaJobThumb` (48x80, 3:5 portrait) matches the 2:3 aspect of typical 1024x1536 universe renders so all three states share a footprint and the row doesn't jump mid-render. Clicking any variation thumb opens the page-level `MediaPreview` lightbox (same modal the gallery uses), built from a `previewItems` array spanning every variation + composite-sheet `imageRefs[]` on the draft; canon entries continue to route through `UniverseCanonSection`'s own `MediaPreview` (which carries the character reference-sheet `image-refs/` prefix). Canon cards switched from labeled pill buttons to an icon-only horizontal action strip (Render reference + Clean plate + AI: differentiate + Lock toggle) matching the variation cards. Migration `024-lock-canon-and-variations.js` materializes the locked-by-default state to disk: stamps `locked: true` on every existing canon entry / variation / composite sheet (skips entries with explicit `locked: false`), mints stable `id`s for the historically id-less variations + sheets (so future renders can attach `imageRefs` via the `entryRef` collection hook), and best-effort back-fills `imageRefs[]` on variations from surviving completed jobs in `media-jobs.json` via `params.universeRun.{universeId, category, label}` matching — historical renders whose jobs have aged out of the queue file aren't recoverable.- **Character bible / reference-sheet `/simplify` follow-ups.** Nine cleanups bundled from the simplify review during the character bible expansion PR. (1) `CanonCard`'s four character-only props collapsed into a single `characterExtensions` object so non-character call sites skip them entirely. (2) New `client/src/lib/bibleLimits.js` mirrors `server/lib/storyBible.js` `BIBLE_LIMITS` so client-side `max:` literals can't drift from the server caps. (3) Single-field `useFieldDraft` hook shared by `CharacterDetailEditor#DraftField` and a new per-row `WardrobeRow` sub-component (replaces the indexed `${idx}:${field}` drafts map). (4) `runPromptRefine` split into a lower-level `runPromptRefineRaw` so multi-field merges (`universeCharacterExpand`) can reuse the empty-guard + rationale-trim + log-tag scaffold. (5) `resolveGalleryImage` / `resolveImageRef` / `resolveTemplateAsset` collapsed onto a `makePathResolver(getRoot, { extensions, cache })` factory — thunk-only API (throws on non-function `getRoot`) so test-time mutations of `PATHS.x` at mock-eval time still steer the resolver; `rootAbsPrefix` is cached lazily on first call. (6) New `shortId(id, n=8)` helper in `fileUtils.js` replaces inline `String(x).slice(0, 8)` across the universe character family. (7) New `createImageGenWaiter` extracts the shared `imageGenEvents` completion-waiter pattern used by `sdapi.js#createCompletionWaiter` and `voice/tools.js#image_gen`. (8) `flattenStats`/`flattenPalette`/`flattenWardrobes`/`flattenProps`/`flattenNamedList` moved from `universeCharacterSheet.js` to `canonPrompt.js` alongside `RICH_SPEC`. (9) `CharacterReferenceSheetPanel#waitForImageRef` accepts an `AbortSignal` so unmount aborts the 3 s HEAD-poll loop instead of letting it issue requests against a dead component. Three sub-bullets deferred to dedicated PLAN entries: `[purge-reference-sheet-image-ref-on-sheet-delete]` and `[clear-pending-sheet-slot-on-entry-delete]` gate on character/universe-delete routes that don't exist yet; `[characterdetaileditor-listrow-row-draft-hook]` carves off the `ListRow` half of item 3 — the multi-column ride-along race protection can't survive a per-field split, so a `useRowDraft` hook for multi-column row state is the right successor.- **Character bible expansion + artist reference sheet.** Universe canon characters now carry novelist + graphic-novelist depth and can render a single dense artist reference sheet styled to match the universe. `sanitizeCharacter` in `server/lib/storyBible.js` gains 15 prose fields (pronouns, age, coreTheme, speechAccent, visualNotes, silhouetteNotes, postureNotes, specialTraits, visualIdentity, motivations, likes, dislikes, mannerisms, relationships, skills) + 5 structured lists (stats, colorPalette, props, expressions, handGestures) + 1 operational pointer (`referenceSheetImageRef`). Stats are an open `[{label, value}]` list so non-human characters (ghosts, spiders, clouds, AIs) aren't shoehorned into human anatomy. Two new endpoints: `POST /api/universe-builder/:id/characters/:entryId/expand` runs one LLM call (new `universe-character-expand` stage) that fills BLANK extended fields without clobbering populated content; `POST /api/universe-builder/:id/characters/:entryId/render-reference-sheet` enqueues a media-job render driven by a rich TEXT prompt (no init image required) that works equally well across codex and local image-gen backends. The renderer emits a multi-paragraph layout-prescriptive prompt (turnaround, expression progression, color palette swatches, wardrobe + prop cards, hand gestures), routes through `mediaJobQueue` with the active `imageGen.mode` (codex → codex lane, local → GPU lane; external SD-API returns `UNIVERSE_CHARACTER_SHEET_UNSUPPORTED_MODE` rather than a silently-degraded render), and on `mediaJobEvents` completion copies the result into `data/image-refs/` then stamps `character.referenceSheetImageRef`. Completed renders are also filed into the universe's media collection (`Universe: <name>` bucket) via `universeBuilderCollectionHook` by attaching a `universeRun` tag to the enqueued job, alongside the rest of the universe's concept art. `/data/image-refs/` is now exposed as a static route so the UI can render the sheet inline. New UI: `CharacterDetailEditor.jsx` (sectioned collapsible editor for the extended fields) + `CharacterReferenceSheetPanel.jsx` (Generate / Regenerate / lightbox) embedded in `CanonCard.jsx` behind a single "Character details + reference sheet" toggle that only renders when the caller passes the universe wiring — the per-series NounsStage stays focused on naming + visual refs. New migration `022-character-extended-fields.js` is record-only (sanitizer fills defaults on next read). 18+ new server tests (storyBible extensions + universeCharacterSheet prompt builder + universeCharacterExpand merge semantics + route mocks).diff --git a/client/src/components/pipeline/CanonCard.jsx b/client/src/components/pipeline/CanonCard.jsxindex 2a38613cc1..83d9d25886 100644--- a/client/src/components/pipeline/CanonCard.jsx+++ b/client/src/components/pipeline/CanonCard.jsx@@ -16,6 +16,7 @@ import useMediaJobProgress from '../../hooks/useMediaJobProgress';import useFieldDraft from '../../hooks/useFieldDraft';import MediaJobThumb from './MediaJobThumb';import EntryCard from '../universe/EntryCard';+import EntryThumbSlot from '../universe/EntryThumbSlot';import CharacterDetailEditor from '../universe/CharacterDetailEditor';import CharacterReferenceSheetPanel from '../universe/CharacterReferenceSheetPanel';import { BIBLE_LIMITS } from '../../lib/bibleLimits';@@ -282,15 +283,13 @@ export default function CanonCard({const refs = Array.isArray(entry.imageRefs) ? entry.imageRefs : [];const locked = entry.locked === true;const tags = Array.isArray(entry.tags) ? entry.tags.filter(Boolean) : [];- // Refine + Render guarded against locked entries — locks signal "frozen- // identity"; both AI rewrite (refine/differentiate) and new visual refs are- // gated so the user explicitly unlocks before reshaping the entry.- // Gate on `locked` alone, NOT on `!!onToggleLock` — consumers like- // NounsStage embed CanonCard without passing a toggle, but the underlying- // entry's `locked` flag still represents frozen-identity semantics on the- // server (Refine → 409 `UNIVERSE_CANON_LOCKED`, Render persists a new- // visual ref through bypass). The unlock UX lives in Universe Builder; the- // pipeline view just needs to respect it.+ // Lock guards prompt-data rewrites only — `refineUniverseCharacter`+ // returns 409 `UNIVERSE_CANON_LOCKED` on a locked target, and the cast-wide+ // differentiate skips locked entries at apply time. Render paths do NOT+ // consult the lock: rendering a new reference image (or a clean plate for+ // places) doesn't mutate the entry's prompt/description, just appends to+ // `imageRefs[]`. The pipeline view (NounsStage) inherits the same UX —+ // locked entries are still renderable, just not LLM-rewritable.const blockedByLock = locked;// Visual at-a-glance without scrolling to the footer ref grid. Falls back@@ -408,20 +407,37 @@ export default function CanonCard({</>);+ // Icon-only action strip — same visual contract as the variation cards+ // (`VariationCard` in `pages/UniverseBuilder.jsx`): `p-1` icon button per+ // action, horizontal row, 14px icons, accent hover for primary actions,+ // accent-on-locked styling for the lock toggle. Keeps the canon section+ // visually consistent with the bucket cards above it.const actions = (- <div className="flex flex-col gap-1 items-stretch">- {onToggleLock ? (+ <div className="flex items-center gap-1">+ <button+ type="button"+ onClick={onRender}+ disabled={!description.trim() || !!inFlightJobId}+ className="p-1 text-gray-400 hover:text-port-accent disabled:opacity-30 disabled:cursor-not-allowed rounded"+ title={description.trim()+ ? `Render a canonical reference image for ${entry.name}`+ : 'Add a description first'}+ aria-label={`Render reference for ${entry.name}`}+ >+ {inFlightJobId ? <Loader2 size={14} className="animate-spin" /> : <ImagePlus size={14} />}+ </button>+ {kind.key === 'places' && onRenderCleanPlate ? (<buttontype="button"- onClick={() => onToggleLock(entry.id, !locked)}- disabled={togglingLock}- className="inline-flex items-center justify-center gap-1 px-2 py-1 text-[10px] rounded border border-port-border text-gray-300 hover:bg-port-border/40 hover:text-white disabled:opacity-40"- title={locked- ? `Unlock ${entry.name} so refine / differentiate / re-extract can modify it`- : `Lock ${entry.name} so AI passes don't rewrite it`}+ onClick={() => onRenderCleanPlate(entry)}+ disabled={!description.trim() || !!inFlightJobId}+ className="p-1 text-gray-400 hover:text-port-accent disabled:opacity-30 disabled:cursor-not-allowed rounded"+ title={description.trim()+ ? `Render an empty-location plate for ${entry.name} — no people, edge-to-edge`+ : 'Add a description first'}+ aria-label={`Render clean plate for ${entry.name}`}>- {togglingLock ? <Loader2 size={10} className="animate-spin" /> : (locked ? <Unlock size={10} /> : <Lock size={10} />)}- {locked ? 'Unlock' : 'Lock'}+ {inFlightJobId ? <Loader2 size={14} className="animate-spin" /> : <Square size={14} />}</button>) : null}{kind.key === 'characters' && onRefine ? (@@ -429,41 +445,27 @@ export default function CanonCard({type="button"onClick={() => onRefine(entry.id)}disabled={refining || refineDisabled || blockedByLock}- className="inline-flex items-center justify-center gap-1 px-2 py-1 text-[10px] rounded border border-port-border text-gray-300 hover:bg-port-border/40 hover:text-white disabled:opacity-40"+ className="p-1 text-gray-400 hover:text-port-accent disabled:opacity-30 disabled:cursor-not-allowed rounded"title={blockedByLock? `Unlock ${entry.name} to refine`- : `Rewrite ${entry.name}'s description so they render distinct from every other character`}+ : `AI: rewrite ${entry.name}'s description so they render distinct from every other character`}+ aria-label={`AI differentiate ${entry.name}`}>- {refining ? <Loader2 size={10} className="animate-spin" /> : <WandSparkles size={10} />}- AI: differentiate+ {refining ? <Loader2 size={14} className="animate-spin" /> : <WandSparkles size={14} />}</button>) : null}- <button- type="button"- onClick={onRender}- disabled={!description.trim() || !!inFlightJobId || blockedByLock}- className="inline-flex items-center justify-center gap-1 px-2 py-1 text-[10px] rounded border border-port-border text-gray-300 hover:bg-port-border/40 hover:text-white disabled:opacity-40"- title={blockedByLock- ? `Unlock ${entry.name} to render a new reference`- : (description.trim() ? `Render a canonical reference image for ${entry.name}` : 'Add a description first')}- >- {inFlightJobId ? <Loader2 size={10} className="animate-spin" /> : <ImagePlus size={10} />}- Render reference- </button>- {kind.key === 'places' && onRenderCleanPlate ? (+ {onToggleLock ? (<buttontype="button"- onClick={() => onRenderCleanPlate(entry)}- disabled={!description.trim() || !!inFlightJobId || blockedByLock}- className="inline-flex items-center justify-center gap-1 px-2 py-1 text-[10px] rounded border border-port-border text-gray-300 hover:bg-port-border/40 hover:text-white disabled:opacity-40"- title={blockedByLock- ? `Unlock ${entry.name} to render a clean plate`- : (description.trim()- ? `Render an empty-location plate for ${entry.name} — no people, edge-to-edge`- : 'Add a description first')}+ onClick={() => onToggleLock(entry.id, !locked)}+ disabled={togglingLock}+ className={`p-1 rounded ${locked ? 'text-port-accent hover:bg-port-accent/20' : 'text-gray-500 hover:text-gray-300'}`}+ title={locked+ ? `Unlock ${entry.name} so refine / differentiate / re-extract can modify it`+ : `Lock ${entry.name} so AI passes don't rewrite it`}+ aria-pressed={locked}>- {inFlightJobId ? <Loader2 size={10} className="animate-spin" /> : <Square size={10} />}- Clean plate+ {togglingLock ? <Loader2 size={14} className="animate-spin" /> : (locked ? <Lock size={14} /> : <Unlock size={14} />)}</button>) : null}</div>@@ -542,21 +544,27 @@ 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: (visibleFilename) => onPreview?.(visibleFilename || thumbnailRef),- isPrimary: !!entry.primaryImageRef && entry.primaryImageRef === thumbnailRef,- fallbackRefs: refs,- }- : null;+ // Three-state thumbnail slot (pending / empty / completed). Empty state+ // shows a placeholder box with a Render button that fires the same handler+ // as the actions-column Image button — surfaces a one-click affordance for+ // canon entries that haven't been visualized yet. Pending shows the live+ // diffusion spinner from MediaJobThumb (also mirrored in the footer's+ // ref-grid for live-progress detail).+ // Lock no longer gates rendering — see the `blockedByLock` comment above.+ // Render still requires a description (the prompt source) + an actual+ // handler from the parent. Pending state is checked inside EntryThumbSlot.+ const canRender = !!onRender && !!description.trim();+ const thumbnail = (+ <EntryThumbSlot+ inFlightJobId={inFlightJobId || null}+ imageRefs={refs}+ primaryImageRef={entry.primaryImageRef || null}+ alt={`${entry.name} reference`}+ onPreview={onPreview ? (visibleFilename) => onPreview(visibleFilename || thumbnailRef) : null}+ onRender={onRender}+ canRender={canRender}+ />+ );return (<EntryCarddiff --git a/client/src/components/pipeline/MediaJobThumb.jsx b/client/src/components/pipeline/MediaJobThumb.jsxindex f1e6ed8670..aafd2d19c5 100644--- a/client/src/components/pipeline/MediaJobThumb.jsx+++ b/client/src/components/pipeline/MediaJobThumb.jsx@@ -53,11 +53,17 @@ export default function MediaJobThumb({// `fill` fills the parent container's width with the image's natural// aspect (object-contain). State-only branches (spinner, missing, failed)// keep a fixed footprint so the row doesn't collapse mid-render.+ // `xs` (48x80, 3:5 portrait) matches the universe-builder avatar slot used+ // by variation and canon rows — portrait shape so the typical 1024x1536+ // universe render shows the full subject without aggressive center-crop.+ // The larger square sizes (`sm`/`md`/`lg`) are used by the pipeline+ // comic-pages / storyboard stages where 1:1 still reads best.const isFill = size === 'fill';const dims = isFill? 'w-full': size === 'lg' ? 'w-32 h-32'- : size === 'md' ? 'w-24 h-24' : 'w-16 h-16';+ : size === 'md' ? 'w-24 h-24'+ : size === 'xs' ? 'w-12 h-20' : 'w-16 h-16';const stateDims = isFill ? 'w-full min-h-[200px]' : dims;const imgFit = isFill ? 'w-full h-auto max-h-[640px] object-contain' : 'w-full h-full object-cover';diff --git a/client/src/components/universe/EntryCard.jsx b/client/src/components/universe/EntryCard.jsxindex 4fd2dc21ab..aa6328b8a2 100644--- a/client/src/components/universe/EntryCard.jsx+++ b/client/src/components/universe/EntryCard.jsx@@ -6,15 +6,18 @@* 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?,- * 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.+ * - `thumbnail` — either a descriptor object `{ filename, alt?, onClick?,+ * isPrimary?, fallbackRefs? }` OR a React element. The descriptor flows+ * through `EntryCardThumbnail` (12x12 frame, primary-star badge, walk-back+ * on 404) so the existing image case stays consistent across consumers.+ * A React element is rendered as-is — used by variation/canon rows that+ * need to drop in a `MediaJobThumb` (in-flight render spinner) or an+ * empty-state "Render" placeholder box in the thumbnail slot. Pass+ * `null`/omit to skip the thumbnail column entirely. `fallbackRefs` (on+ * the descriptor) is an optional chronological list of older filenames —+ * when the primary file no longer resolves, the thumbnail walks back+ * through this list 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;@@ -25,7 +28,7 @@* overlay so they remain independently clickable without nesting interactive* controls inside a `<label>` (invalid HTML).*/-import { useId, useState, useEffect } from 'react';+import { useId, useState, useEffect, isValidElement } from 'react';import { Star } from 'lucide-react';export default function EntryCard({@@ -68,7 +71,9 @@ export default function EntryCard({/>) : null}{thumbnail ? (- <EntryCardThumbnail {...thumbnail} />+ isValidElement(thumbnail)+ ? <div className="shrink-0">{thumbnail}</div>+ : <EntryCardThumbnail {...thumbnail} />) : null}<div className="flex-1 min-w-0">{title}diff --git a/client/src/components/universe/EntryThumbSlot.jsx b/client/src/components/universe/EntryThumbSlot.jsxnew file mode 100644index 0000000000..ddf7e8fd40--- /dev/null+++ b/client/src/components/universe/EntryThumbSlot.jsx@@ -0,0 +1,149 @@+/**+ * Three-state thumbnail slot for universe canon entries and category variations.+ *+ * Mirrors the comic-page render thumb pattern from+ * `client/src/components/pipeline/MediaJobThumb.jsx`:+ *+ * 1. Pending — `inFlightJobId` set → render `MediaJobThumb` so the user+ * sees the diffusion spinner / step counter / preview latent.+ * 2. Completed — `imageRefs[]` non-empty → walk-back thumbnail (the existing+ * `EntryCardThumbnail` behavior, extracted here to keep both paths in+ * lock-step).+ * 3. Empty — no jobId, no images → 48x48 placeholder box with a centered+ * Sparkles button that fires `onRender()`. Keeps row heights consistent+ * across freshly-extracted entries (no images yet) and rendered ones,+ * and surfaces a one-click render affordance without scrolling to the+ * row's action column.+ *+ * The fixed footprint avoids row-height jitter between empty / pending /+ * rendered states. Disabled when `canRender` is false (no backend selected,+ * save pending, etc.) so the button shape is still visible but inert.+ */+import { useState, useEffect } from 'react';+import { Sparkles, Loader2, Star } from 'lucide-react';+import MediaJobThumb from '../pipeline/MediaJobThumb';++export default function EntryThumbSlot({+ inFlightJobId = null,+ imageRefs = null,+ primaryImageRef = null,+ onRender = null,+ onPreview = null,+ canRender = true,+ alt = 'Render',+ // When true, render the empty-state box with an even bigger Sparkles+ // affordance (used by canon rows that ride a wider card). Defaults to the+ // compact 48x48 footprint shared with variations.+ size = 'sm',+}) {+ if (inFlightJobId) {+ // `xs` (48x48) matches the empty + completed states below so all three+ // states share a footprint and the row doesn't jump mid-render. `lg`+ // upgrades the pending box to 64x64 when the slot is configured for the+ // larger size (kept available for parity with the empty placeholder).+ return (+ <MediaJobThumb+ jobId={inFlightJobId}+ label={alt}+ size={size === 'lg' ? 'sm' : 'xs'}+ onPreview={onPreview}+ />+ );+ }+ const refs = Array.isArray(imageRefs) ? imageRefs : [];+ const hasImage = refs.length > 0 || !!primaryImageRef;+ if (hasImage) {+ const chosen = (primaryImageRef && refs.includes(primaryImageRef))+ ? primaryImageRef+ : refs[refs.length - 1];+ return (+ <WalkBackThumb+ filename={chosen}+ alt={alt}+ fallbackRefs={refs}+ isPrimary={!!primaryImageRef && primaryImageRef === chosen}+ onClick={onPreview}+ />+ );+ }+ // Empty state — placeholder box with render button. Portrait footprint+ // (48x80 / 64x96) matches the 2:3 aspect of typical universe renders so+ // the row reserves the same vertical space as WalkBackThumb's completed+ // image, and the pending MediaJobThumb (xs / sm), eliminating row jitter+ // across the three states.+ const dim = size === 'lg' ? 'w-16 h-24' : 'w-12 h-20';+ return (+ <button+ type="button"+ onClick={() => onRender?.()}+ disabled={!onRender || !canRender}+ title={canRender ? 'Render image for this item' : 'Save the universe first to enable render'}+ className={`${dim} shrink-0 flex items-center justify-center rounded border border-dashed border-port-border bg-port-bg/40 text-gray-500 hover:border-port-accent/50 hover:text-port-accent hover:bg-port-accent/5 disabled:opacity-40 disabled:cursor-not-allowed disabled:hover:border-port-border disabled:hover:text-gray-500 disabled:hover:bg-port-bg/40 transition-colors`}+ >+ <Sparkles size={size === 'lg' ? 18 : 14} />+ </button>+ );+}++// Walk-back thumbnail extracted from EntryCard's internal renderer so the+// has-image branch of EntryThumbSlot reuses the same on-error fallback chain+// (stale gallery file → walk back through prior renders → collapse). Mirrors+// `EntryCardThumbnail` in `EntryCard.jsx`; intentionally kept in sync — visual+// drift would defeat the point of a shared slot.+function WalkBackThumb({ filename, alt, onClick, isPrimary = false, fallbackRefs = null }) {+ 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);+ }+ }+ }+ const candidateKey = candidates.join('|');+ const [idx, setIdx] = useState(0);+ useEffect(() => { setIdx(0); }, [candidateKey]);+ if (!candidates.length || idx >= candidates.length) {+ // All candidates failed to load — collapse to empty (no render button+ // here; the user can re-render from the action column).+ return <div className="w-12 h-20 shrink-0 rounded border border-port-border bg-port-bg/40" />;+ }+ const currentFilename = candidates[idx];+ const img = (+ <img+ src={`/data/images/${currentFilename}`}+ alt={alt || currentFilename}+ className="w-full h-full object-cover"+ loading="lazy"+ onError={() => setIdx((n) => n + 1)}+ />+ );+ const frame = (+ <div className={`relative w-12 h-20 shrink-0 rounded overflow-hidden border ${+ isPrimary ? 'border-port-accent' : 'border-port-border'+ }`}>+ {img}+ {isPrimary ? (+ <span+ title="Primary reference image"+ className="absolute top-0.5 right-0.5 p-0.5 rounded bg-port-accent text-white"+ >+ <Star size={8} fill="currentColor" />+ </span>+ ) : null}+ </div>+ );+ if (!onClick) return frame;+ return (+ <button+ type="button"+ onClick={() => onClick(currentFilename)}+ title={`Preview ${alt || currentFilename}`}+ aria-label={`Preview ${alt || currentFilename}`}+ className="p-0 bg-transparent border-0 cursor-zoom-in"+ >+ {frame}+ </button>+ );+}diff --git a/client/src/components/universe/EntryThumbSlot.test.jsx b/client/src/components/universe/EntryThumbSlot.test.jsxnew file mode 100644index 0000000000..85a03d2fcd--- /dev/null+++ b/client/src/components/universe/EntryThumbSlot.test.jsx@@ -0,0 +1,56 @@+import { describe, it, expect, vi } from 'vitest';+import { render, screen, fireEvent } from '@testing-library/react';+import EntryThumbSlot from './EntryThumbSlot';++// MediaJobThumb subscribes to a socket via useMediaJobProgress. Stub the hook+// so the test doesn't need a live socket / fetch; the empty + completed+// branches don't invoke it (no jobId), so this only affects the pending case.+vi.mock('../../hooks/useMediaJobProgress', () => ({+ default: () => ({ status: 'queued', progress: 0, step: 0, totalSteps: 0, currentImage: null, filename: null, error: null }),+}));++describe('EntryThumbSlot — three-state thumbnail', () => {+ it('renders an empty placeholder with a Render button when nothing else is set', () => {+ const onRender = vi.fn();+ render(<EntryThumbSlot onRender={onRender} canRender alt="Var A render" />);+ const btn = screen.getByRole('button', { name: /render image for this item/i });+ expect(btn).toBeInTheDocument();+ fireEvent.click(btn);+ expect(onRender).toHaveBeenCalledTimes(1);+ });++ it('disables the empty-state button when canRender is false', () => {+ const onRender = vi.fn();+ render(<EntryThumbSlot onRender={onRender} canRender={false} />);+ const btn = screen.getByRole('button');+ expect(btn).toBeDisabled();+ fireEvent.click(btn);+ expect(onRender).not.toHaveBeenCalled();+ });++ it('renders an <img> when imageRefs are present', () => {+ render(+ <EntryThumbSlot+ imageRefs={['render-aaa.png']}+ alt="Var B render"+ canRender={false}+ />,+ );+ const img = screen.getByRole('img', { name: 'Var B render' });+ expect(img).toHaveAttribute('src', '/data/images/render-aaa.png');+ });++ it('shows MediaJobThumb (spinner / step counter) when inFlightJobId is set', () => {+ const { container } = render(+ <EntryThumbSlot+ inFlightJobId="job-pending"+ imageRefs={[]}+ canRender={false}+ />,+ );+ // MediaJobThumb in queued/running with no preview renders a Loader2 svg —+ // assert on the spinner classname so we don't have to grep through icon+ // implementation details.+ expect(container.querySelector('.animate-spin')).toBeInTheDocument();+ });+});diff --git a/client/src/components/universe/UniverseCanonSection.jsx b/client/src/components/universe/UniverseCanonSection.jsxindex c9002543a8..a8c8010e4c 100644--- a/client/src/components/universe/UniverseCanonSection.jsx+++ b/client/src/components/universe/UniverseCanonSection.jsx@@ -14,7 +14,7 @@import { useCallback, useEffect, useMemo, useRef, useState } from 'react';import { useSearchParams } from 'react-router-dom';import {- Library, Loader2, Users, MapPin, Package, Wand2, Filter,+ Library, Loader2, Users, MapPin, Package, Wand2, Filter, Lock, Unlock,} from 'lucide-react';import toast from '../ui/Toast';import {@@ -24,6 +24,7 @@ import {updateUniverse,getUniverseCanonUsage,setUniverseCanonLock,+ setUniverseCanonLockAll,expandUniverseCharacter,} from '../../services/apiUniverseBuilder';import { generateImage } from '../../services/apiSystem';@@ -251,6 +252,27 @@ export default function UniverseCanonSection({ universe, universeId, onUniverseCtoast.success(`Differentiated ${result.touched}/${result.touched + result.skipped} characters — ${(result.rationale || '').slice(0, 140)}`);};+ // Track which kind has a bulk-lock in flight so we can disable its buttons+ // and show a spinner. Keyed by `kind.key` (characters / places / objects)+ // because the action is scoped to that section.+ const [bulkLockingKindKey, setBulkLockingKindKey] = useState(null);++ const handleBulkLockKind = useCallback(async (kind, nextLocked) => {+ if (bulkLockingKindKey) return;+ setBulkLockingKindKey(kind.key);+ const capturedId = universeId;+ const result = await setUniverseCanonLockAll(universeId, kind.apiKind, nextLocked)+ .catch((err) => { toast.error(err.message || `Bulk ${nextLocked ? 'lock' : 'unlock'} failed`); return null; });+ if (mountedRef.current) setBulkLockingKindKey(null);+ if (!result || !mountedRef.current || currentUniverseIdRef.current !== capturedId) return;+ if (result.universe) onUniverseChange(result.universe);+ if (result.changed === 0) {+ toast.success(`All ${kind.label.toLowerCase()} already ${nextLocked ? 'locked' : 'unlocked'}`);+ } else {+ toast.success(`${nextLocked ? 'Locked' : 'Unlocked'} ${result.changed} ${kind.label.toLowerCase()}`);+ }+ }, [universeId, onUniverseChange, mountedRef, bulkLockingKindKey]);+const handleToggleLock = useCallback(async (kind, entryId, nextLocked) => {if (togglingLockRef.current) return;togglingLockRef.current = entryId;@@ -549,6 +571,9 @@ export default function UniverseCanonSection({ universe, universeId, onUniverseConPatchEntry={(entryId, patch) => handlePatchEntry(kind, entryId, patch)}onRenderCleanPlate={handleRenderCleanPlate}seriesNameMap={usage?.seriesNameMap || null}+ onBulkLock={(nextLocked) => handleBulkLockKind(kind, nextLocked)}+ bulkLocking={bulkLockingKindKey === kind.key}+ fullList={Array.isArray(universe[kind.key]) ? universe[kind.key] : []}/>))}@@ -557,7 +582,7 @@ export default function UniverseCanonSection({ universe, universeId, onUniverseC);}-function KindSection({ kind, universeId, all, totalCount, filtered, usage, renderingJobs, onRender, onJobCompleted, onJobFailed, onPreview, onRefine, refiningId, onExpandCharacter, expandingId, onSheetCompleted, onToggleLock, togglingLockId, onPatchEntry, onRenderCleanPlate, seriesNameMap }) {+function KindSection({ kind, universeId, all, totalCount, filtered, usage, renderingJobs, onRender, onJobCompleted, onJobFailed, onPreview, onRefine, refiningId, onExpandCharacter, expandingId, onSheetCompleted, onToggleLock, togglingLockId, onPatchEntry, onRenderCleanPlate, seriesNameMap, onBulkLock, bulkLocking, fullList }) {// Universe-only character wiring — `null` for non-character kinds so// CanonCard's gate stays `kind === 'characters' && characterExtensions`.// Memoized so the BASE object is stable across re-renders that aren't@@ -571,6 +596,16 @@ function KindSection({ kind, universeId, all, totalCount, filtered, usage, rende[kind.key, universeId, onExpandCharacter, onSheetCompleted],);const Icon = kind.icon;+ // Bulk lock-state summary computed off the FULL list (not the series-filtered+ // view) so the buttons reflect the universe-wide state the bulk action will+ // change. A mixed list (some locked, some not) enables BOTH buttons so the+ // user can pick a direction without first having to inspect.+ const lockedCount = fullList.filter((e) => e?.locked === true).length;+ // "All locked" gates the toggle button's icon + action direction. A mixed+ // list (some locked, some not) falls into the same bucket as all-unlocked+ // so the next click locks the remaining holdouts.+ const allLocked = fullList.length > 0 && lockedCount === fullList.length;+ const bulkDisabled = !onBulkLock || bulkLocking || fullList.length === 0;return (<section className="rounded border border-port-border bg-port-bg/60"><div className="flex items-center gap-2 px-3 py-2 border-b border-port-border">@@ -579,6 +614,31 @@ function KindSection({ kind, universeId, all, totalCount, filtered, usage, rende<span className="text-[10px] text-gray-500">{filtered ? `${all.length} / ${totalCount}` : all.length}</span>+ {fullList.length > 0 && onBulkLock ? (+ // Single toggle button — mirrors the per-item lock-toggle visual.+ // Lock icon when every entry is already locked (click unlocks all);+ // Unlock icon for the all-unlocked + mixed cases (click locks all)+ // so "the next click locks the holdouts" is always the action.+ <button+ type="button"+ onClick={() => onBulkLock(!allLocked)}+ disabled={bulkDisabled}+ title={allLocked+ ? `Unlock all ${kind.label.toLowerCase()} — AI refine / differentiate may overwrite them`+ : `Lock all ${kind.label.toLowerCase()} — AI refine / differentiate will skip them`}+ aria-label={allLocked ? `Unlock all ${kind.label}` : `Lock all ${kind.label}`}+ aria-pressed={allLocked}+ className={`ml-auto p-1 rounded disabled:opacity-30 disabled:cursor-not-allowed ${+ allLocked+ ? 'text-port-accent hover:bg-port-accent/20'+ : 'text-gray-500 hover:text-gray-300'+ }`}+ >+ {bulkLocking+ ? <Loader2 size={14} className="animate-spin" />+ : allLocked ? <Lock size={14} /> : <Unlock size={14} />}+ </button>+ ) : null}</div><div className="p-3">{all.length === 0 ? (diff --git a/client/src/pages/UniverseBuilder.jsx b/client/src/pages/UniverseBuilder.jsxindex ef6bf3ef3d..e5e45be48f 100644--- a/client/src/pages/UniverseBuilder.jsx+++ b/client/src/pages/UniverseBuilder.jsx@@ -35,6 +35,9 @@ import ShareToButton from '../components/sharing/ShareToButton';import OriginBadge from '../components/sharing/OriginBadge';import UniverseCanonSection from '../components/universe/UniverseCanonSection';import EntryCard from '../components/universe/EntryCard';+import EntryThumbSlot from '../components/universe/EntryThumbSlot';+import useMediaJobProgress from '../hooks/useMediaJobProgress';+import MediaPreview from '../components/media/MediaPreview';import TabPills from '../components/ui/TabPills';import { deriveAvailableBackends, IMAGE_GEN_MODE } from '../lib/imageGenBackends';import { PIPELINE_IMAGE_DEFAULTS, readPipelineImageSettings } from '../lib/pipelineImageDefaults';@@ -551,6 +554,21 @@ export default function UniverseBuilder() {const [saving, setSaving] = useState(false);const [expanding, setExpanding] = useState(false);const [rendering, setRendering] = useState(false);+ // entryId → jobId map for variation / composite-sheet rows that have an+ // in-flight render. Populated from /render's `entryJobs` response and+ // cleared when MediaJobThumb fires a terminal status (completed / failed /+ // canceled). Canon entries have their own pending map in UniverseCanonSection+ // (`renderingJobs`) so they aren't included here.+ const [pendingByEntryId, setPendingByEntryId] = useState({});+ const clearPendingForEntry = useCallback((entryId) => {+ if (!entryId) return;+ setPendingByEntryId((prev) => {+ if (!(entryId in prev)) return prev;+ const next = { ...prev };+ delete next[entryId];+ return next;+ });+ }, []);const [providers, setProviders] = useState([]);const [activeProviderId, setActiveProviderId] = useState(null);// Image-gen plumbing for the batch-render form (reused from Image Gen).@@ -637,6 +655,47 @@ export default function UniverseBuilder() {);const [runs, setRuns] = useState([]);+ // Page-level lightbox state for variation + composite-sheet thumbs. Canon+ // entries route through `UniverseCanonSection`'s own MediaPreview; this+ // one covers the category-bucket rows so clicking a variation thumb opens+ // the same full-detail modal the gallery / history uses.+ const [preview, setPreview] = useState(null);+ const previewItems = useMemo(() => {+ const out = [];+ const seen = new Set();+ const pushFilename = (filename, label) => {+ if (typeof filename !== 'string' || !filename) return;+ if (seen.has(filename)) return;+ seen.add(filename);+ out.push({+ key: `universe-thumb:${filename}`,+ kind: 'image',+ filename,+ previewUrl: `/data/images/${filename}`,+ downloadUrl: `/data/images/${filename}`,+ prompt: label || filename,+ });+ };+ const cats = draft?.categories && typeof draft.categories === 'object' ? draft.categories : {};+ for (const [bucketKey, bucket] of Object.entries(cats)) {+ const variations = Array.isArray(bucket?.variations) ? bucket.variations : [];+ for (const v of variations) {+ const refs = Array.isArray(v?.imageRefs) ? v.imageRefs : [];+ for (const f of refs) pushFilename(f, `${bucketKey} · ${v.label}`);+ }+ }+ const sheets = Array.isArray(draft?.compositeSheets) ? draft.compositeSheets : [];+ for (const s of sheets) {+ const refs = Array.isArray(s?.imageRefs) ? s.imageRefs : [];+ for (const f of refs) pushFilename(f, `Composite · ${s.label}`);+ }+ return out;+ }, [draft]);+ const openVariationPreview = useCallback((filename) => {+ if (!filename) return;+ const match = previewItems.find((i) => i.filename === filename);+ if (match) setPreview(match);+ }, [previewItems]);// Two-click delete: first click flips this to the world id; a second// click within the live render confirms. Avoids window.confirm per@@ -1312,6 +1371,21 @@ export default function UniverseBuilder() {}).catch((e) => { toast.error(`Render failed: ${e.message}`); return null; });setRendering(false);if (!result) return;+ // Stamp per-entry pending state so each variation / composite sheet row can+ // swap its thumbnail for a MediaJobThumb spinner. Canon entries take a+ // different render path (UniverseCanonSection's `generateImage`) so+ // entryJobs entries with `kind: 'canon'` are intentionally ignored here.+ if (Array.isArray(result.entryJobs) && result.entryJobs.length > 0) {+ setPendingByEntryId((prev) => {+ const next = { ...prev };+ for (const { jobId, entryRef } of result.entryJobs) {+ if (!jobId || !entryRef?.id) continue;+ if (entryRef.kind === 'canon') continue;+ next[entryRef.id] = jobId;+ }+ return next;+ });+ }toast.success(`Queued ${result.promptCount} renders → "${result.collectionName}"`);const updated = await listWorldRuns(selectedId).catch(() => runs);setRuns(updated);@@ -1783,6 +1857,31 @@ export default function UniverseBuilder() {onPromoteVariation={(bucket, v) => handlePromoteVariation(bucket, v)}onBulkRenderBucket={(bucket) => runRender({ promptMode: 'variations', selection: { [bucket]: 'all' } })}onRenderVariation={(bucket, v) => runRender({ promptMode: 'variations', selection: { [bucket]: [v.label] } })}+ onPreviewVariation={openVariationPreview}+ pendingByEntryId={pendingByEntryId}+ onPendingCleared={clearPendingForEntry}+ onJobCompletedForEntry={(entryId, filename, bucket) => {+ if (!filename || !bucket) {+ clearPendingForEntry(entryId);+ return;+ }+ // Optimistically append the new filename to the variation's+ // imageRefs[] so the row swaps from spinner → rendered image+ // without a roundtrip. Server already stamped this via the+ // collection hook; the next universe refetch will agree.+ setDraft((d) => {+ const cat = d.categories?.[bucket];+ if (!cat?.variations) return d;+ const variations = cat.variations.map((v) => {+ if (v.id !== entryId) return v;+ const refs = Array.isArray(v.imageRefs) ? v.imageRefs : [];+ if (refs.includes(filename)) return v;+ return { ...v, imageRefs: [...refs, filename] };+ });+ return { ...d, categories: { ...d.categories, [bucket]: { ...cat, variations } } };+ });+ clearPendingForEntry(entryId);+ }}onBulkRenderTrunk={() => {const selection = Object.fromEntries((bucketsByKind[trunk.kind] || []).map((b) => [b, 'all']),@@ -1818,9 +1917,30 @@ export default function UniverseBuilder() {onPromoteVariation={(bucket, v, opts) => handlePromoteVariation(bucket, v, opts)}onBulkRenderBucket={(bucket) => runRender({ promptMode: 'variations', selection: { [bucket]: 'all' } })}onRenderVariation={(bucket, v) => runRender({ promptMode: 'variations', selection: { [bucket]: [v.label] } })}+ onPreviewVariation={openVariationPreview}onAssignBucketKind={assignBucketKind}onAutoSort={handleAutoSort}autoSorting={autoSorting}+ pendingByEntryId={pendingByEntryId}+ onPendingCleared={clearPendingForEntry}+ onJobCompletedForEntry={(entryId, filename, bucket) => {+ if (!filename || !bucket) {+ clearPendingForEntry(entryId);+ return;+ }+ setDraft((d) => {+ const cat = d.categories?.[bucket];+ if (!cat?.variations) return d;+ const variations = cat.variations.map((v) => {+ if (v.id !== entryId) return v;+ const refs = Array.isArray(v.imageRefs) ? v.imageRefs : [];+ if (refs.includes(filename)) return v;+ return { ...v, imageRefs: [...refs, filename] };+ });+ return { ...d, categories: { ...d.categories, [bucket]: { ...cat, variations } } };+ });+ clearPendingForEntry(entryId);+ }}/>)}@@ -2008,12 +2128,11 @@ function CompositeSheetsEditor({ sheets, onChange, canRender = false, onRender =const removeAt = (idx) => onChange(sheets.filter((_, i) => i !== idx));+ // Sheets default to locked at the sanitizer (locked-by-default contract);+ // persist an unlock as explicit `false` so it survives the next read.const toggleLockAt = (idx) => onChange(sheets.map((s, i) => {if (i !== idx) return s;- const next = { ...s };- if (next.locked) delete next.locked;- else next.locked = true;- return next;+ return { ...s, locked: !s.locked };}));const startEdit = (idx, sheet) => {@@ -2040,6 +2159,11 @@ function CompositeSheetsEditor({ sheets, onChange, canRender = false, onRender =setEditIdx(null);};+ const setAllSheetsLocked = (nextLocked) =>+ onChange(sheets.map((s) => (s?.locked === nextLocked ? s : { ...s, locked: nextLocked })));+ const sheetsLockedCount = sheets.filter((s) => s?.locked === true).length;+ const allSheetsLocked = sheets.length > 0 && sheetsLockedCount === sheets.length;+return (<section className="bg-port-card border border-port-border rounded p-4 flex flex-col gap-3"><div className="flex items-center justify-between gap-2">@@ -2047,12 +2171,31 @@ function CompositeSheetsEditor({ sheets, onChange, canRender = false, onRender =Composite boards<span className="ml-2 text-xs text-gray-500">{sheets.length}</span></h2>- <button- onClick={() => setAdding((v) => !v)}- className="text-xs px-2 py-1 bg-port-accent/15 hover:bg-port-accent/25 text-port-accent rounded flex items-center gap-1 min-h-[40px] sm:min-h-0"- >- <Plus size={12} /> Add- </button>+ <div className="flex items-center gap-1">+ {sheets.length > 0 && (+ <button+ onClick={() => setAllSheetsLocked(!allSheetsLocked)}+ title={allSheetsLocked+ ? 'Unlock all composite boards — Expand may overwrite them'+ : 'Lock all composite boards — Expand will preserve them'}+ aria-label={allSheetsLocked ? 'Unlock all composite boards' : 'Lock all composite boards'}+ aria-pressed={allSheetsLocked}+ className={`p-1 rounded ${+ allSheetsLocked+ ? 'text-port-accent hover:bg-port-accent/20'+ : 'text-gray-500 hover:text-gray-300'+ }`}+ >+ {allSheetsLocked ? <Lock size={14} /> : <Unlock size={14} />}+ </button>+ )}+ <button+ onClick={() => setAdding((v) => !v)}+ className="text-xs px-2 py-1 bg-port-accent/15 hover:bg-port-accent/25 text-port-accent rounded flex items-center gap-1 min-h-[40px] sm:min-h-0"+ >+ <Plus size={12} /> Add+ </button>+ </div></div>{adding && (<div className="bg-port-bg border border-port-border rounded p-2 flex flex-col gap-2">@@ -2209,6 +2352,15 @@ export function CategoryEditor({// Only set by OtherTab — clicking opens a picker that retags the bucket's// `kind` to a canon trunk. Variations stay in place; bucket moves tabs.onAssignBucketKind = null,+ // Clicking the row's thumbnail opens the page-level MediaPreview lightbox+ // (same modal that the history / gallery uses). Receives the visible+ // filename so the modal lands on the exact ref the user saw, not a stale+ // primary that may have walked-back on a 404.+ onPreviewVariation = null,+ // Per-row render-pending plumbing — `pendingByEntryId[v.id]` returns the+ // in-flight jobId (or undefined). Completion / failure callbacks fire when+ // the row's MediaJobThumb settles.+ pendingByEntryId = {}, onJobCompleted = null, onJobFailed = null,}) {const requiresTargetKind = !TRUNK_BY_KIND[bucketKind];const [adding, setAdding] = useState(false);@@ -2287,14 +2439,21 @@ export function CategoryEditor({const removeAt = (idx) => onChange(variations.filter((_, i) => i !== idx));+ // Variations default to locked at the sanitizer (locked-by-default contract),+ // so an unlock must persist as explicit `false` — not as an absent key —+ // otherwise the next read would re-lock the entry the user just unlocked.const toggleLockAt = (idx) => onChange(variations.map((v, i) => {if (i !== idx) return v;- const next = { ...v };- if (next.locked) delete next.locked;- else next.locked = true;- return next;+ return { ...v, locked: !v.locked };}));+ // Bulk lock/unlock everything in this bucket. Same persistence contract:+ // unlock writes explicit `false` so it survives the round-trip.+ const setAllLocked = (nextLocked) =>+ onChange(variations.map((v) => (v?.locked === nextLocked ? v : { ...v, locked: nextLocked })));+ const lockedCount = variations.filter((v) => v?.locked === true).length;+ const allLocked = variations.length > 0 && lockedCount === variations.length;+const startEdit = (idx, v) => {setEditIdx(idx);setEditLabel(v.label);@@ -2432,6 +2591,27 @@ export function CategoryEditor({)}</div>)}+ {variations.length > 0 && (+ // Single toggle — mirrors the per-row lock button. Lock icon when+ // every variation is locked (click unlocks all); Unlock icon for+ // the all-unlocked + mixed cases so a click always locks the+ // holdouts.+ <button+ onClick={() => setAllLocked(!allLocked)}+ title={allLocked+ ? 'Unlock all variations — Expand / Generate may overwrite them'+ : 'Lock all variations — Expand / Generate will preserve them'}+ aria-label={allLocked ? 'Unlock all variations' : 'Lock all variations'}+ aria-pressed={allLocked}+ className={`p-1 rounded ${+ allLocked+ ? 'text-port-accent hover:bg-port-accent/20'+ : 'text-gray-500 hover:text-gray-300'+ }`}+ >+ {allLocked ? <Lock size={14} /> : <Unlock size={14} />}+ </button>+ )}{canRemove && (<buttononClick={onRemove}@@ -2512,6 +2692,10 @@ export function CategoryEditor({runPromote={runPromote}onRenderVariation={onRenderVariation}canRender={canRender}+ onPreviewVariation={onPreviewVariation}+ inFlightJobId={pendingByEntryId[v.id] || null}+ onJobCompleted={onJobCompleted}+ onJobFailed={onJobFailed}/>))}</ul>@@ -2529,6 +2713,8 @@ function VariationCard({onPromote, canPromote, requiresTargetKind, promotingIdx,pickerIdx, setPickerIdx, pickerWrapRef, runPromote,onRenderVariation, canRender,+ onPreviewVariation = null,+ inFlightJobId = null, onJobCompleted = null, onJobFailed = null,}) {const locked = !!v.locked;if (editMode) {@@ -2566,20 +2752,36 @@ 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.+ // Thumbnail slot is now three-state (pending / empty / completed) — see+ // `EntryThumbSlot`. Subscribe to the row's in-flight job so we can fire the+ // completion / failure callbacks back up to the parent (which clears+ // pending state + appends the new filename to the variation's imageRefs[]+ // optimistically). settledRef prevents duplicate fires under React 18+ // StrictMode's mount → cleanup → mount dev double-fire.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,+ const { status: jobStatus, filename: jobFilename, error: jobError } = useMediaJobProgress(inFlightJobId);+ const settledRef = useRef(null);+ useEffect(() => {+ if (!inFlightJobId) { settledRef.current = null; return; }+ if (settledRef.current === inFlightJobId) return;+ if (jobStatus === 'completed' && jobFilename) {+ settledRef.current = inFlightJobId;+ onJobCompleted?.(v.id, jobFilename);+ } else if (jobStatus === 'failed' || jobStatus === 'canceled') {+ settledRef.current = inFlightJobId;+ onJobFailed?.(v.id, jobError || jobStatus);}- : null;+ }, [inFlightJobId, jobStatus, jobFilename, jobError, v.id, onJobCompleted, onJobFailed]);+ const thumbnail = (+ <EntryThumbSlot+ inFlightJobId={inFlightJobId}+ imageRefs={renders}+ alt={`${v.label} render`}+ canRender={!!onRenderVariation && canRender}+ onRender={onRenderVariation ? () => onRenderVariation(v) : null}+ onPreview={onPreviewVariation || 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>;@@ -2931,6 +3133,8 @@ export function TrunkView({onRemoveBucket, onUpdateBucket, onGenerateInBucket, onPromoteVariation,onBulkRenderBucket, onRenderVariation, onBulkRenderTrunk,onAddBucket,+ onPreviewVariation = null,+ pendingByEntryId = {}, onPendingCleared = null, onJobCompletedForEntry = null,}) {const canonList = Array.isArray(draft[trunk.kind]) ? draft[trunk.kind] : [];// Only count canon entries the server will actually compile — mirror the@@ -3064,6 +3268,10 @@ export function TrunkView({canPromote={canPromote}bucketKind={draft.categories?.[cat]?.kind ?? trunk.kind}onPromote={onPromoteVariation ? (v) => onPromoteVariation(cat, v) : null}+ onPreviewVariation={onPreviewVariation}+ pendingByEntryId={pendingByEntryId}+ onJobCompleted={(entryId, filename) => onJobCompletedForEntry?.(entryId, filename, cat)}+ onJobFailed={(entryId) => onPendingCleared?.(entryId)}/>))}</section>@@ -3082,6 +3290,8 @@ export function OtherTab({onUpdateBucket, onRemoveBucket, onGenerateInBucket, onPromoteVariation,onBulkRenderBucket, onRenderVariation, onAssignBucketKind, onAutoSort,autoSorting = false,+ onPreviewVariation = null,+ pendingByEntryId = {}, onPendingCleared = null, onJobCompletedForEntry = null,}) {return (<>@@ -3127,6 +3337,10 @@ export function OtherTab({bucketKind={draft.categories?.[cat]?.kind}onPromote={onPromoteVariation ? (v, opts) => onPromoteVariation(cat, v, opts) : null}onAssignBucketKind={onAssignBucketKind ? (targetKind) => onAssignBucketKind(cat, targetKind) : null}+ onPreviewVariation={onPreviewVariation}+ pendingByEntryId={pendingByEntryId}+ onJobCompleted={(entryId, filename) => onJobCompletedForEntry?.(entryId, filename, cat)}+ onJobFailed={(entryId) => onPendingCleared?.(entryId)}/>))}</section>@@ -3405,6 +3619,13 @@ function RenderTab({</ul></section>)}++ {/* Page-level lightbox for variation + composite-sheet thumb clicks.+ UniverseCanonSection owns its own MediaPreview for canon entries+ (which routes character reference sheets through a different+ static prefix), so we deliberately don't include canon refs in+ `previewItems` above — they're handled there. */}+ <MediaPreview preview={preview} setPreview={setPreview} items={previewItems} /></>);}diff --git a/client/src/services/apiUniverseBuilder.js b/client/src/services/apiUniverseBuilder.jsindex 1c831b1925..0360d19aec 100644--- a/client/src/services/apiUniverseBuilder.js+++ b/client/src/services/apiUniverseBuilder.js@@ -224,6 +224,23 @@ export const setUniverseCanonLock = (universeId, kind, entryId, locked) =>body: JSON.stringify({ locked }),});+// Bulk lock/unlock every canon entry of a single kind. Returns+// `{ universe, kind, locked, changed, total }`.+export const setUniverseCanonLockAll = (universeId, kind, locked) =>+ request(`/universe-builder/${encodeURIComponent(universeId)}/canon/${encodeURIComponent(kind)}/lock-all`, {+ method: 'PATCH',+ body: JSON.stringify({ locked }),+ });++// Bulk lock/unlock variations across one bucket (`category`) or every bucket+// (`category: null`). Pass `includeSheets: true` to also flip composite+// sheets in the same call.+export const setUniverseVariationsLockAll = (universeId, { locked, category = null, includeSheets = false } = {}) =>+ request(`/universe-builder/${encodeURIComponent(universeId)}/variations/lock-all`, {+ method: 'PATCH',+ body: JSON.stringify({ locked, category, includeSheets }),+ });+// Promote a category variation into a full canon entry. `targetKind` is// required only when the source bucket's `kind` is 'other' (otherwise the// server derives it from the bucket). Pass `{ silent: true }` in `options`diff --git a/scripts/migrations/024-lock-canon-and-variations.js b/scripts/migrations/024-lock-canon-and-variations.jsnew file mode 100644index 0000000000..6b53341160--- /dev/null+++ b/scripts/migrations/024-lock-canon-and-variations.js@@ -0,0 +1,240 @@+/**+ * Universe Builder — lock canon + variations by default, back-fill historical+ * render thumbnails on variations.+ *+ * Why:+ * PR shipped lock-on-create defaults for canon entries (characters / places /+ * objects) and category variations + composite sheets. New writes inherit+ * the lock through the sanitizer; pre-existing records on disk have no+ * `locked` field. The on-read sanitizer (`sanitizeTemplate` →+ * `defaultLockCanon` + `sanitizeVariation`) treats absent as locked, so the+ * UI displays them locked starting on the next read. This script+ * materializes that state to disk so callers that bypass the sanitizer+ * (sharing/export, raw JSON diff tools, future migrations) see the locked+ * shape too. It also gives each variation a stable `id` — historically only+ * minted on read — so going-forward `entryRef` render jobs can attach+ * imageRefs back to the right row.+ *+ * The second pass back-fills `imageRefs` on variations from surviving+ * `media-jobs.json` entries: completed image jobs tagged+ * `params.universeRun.{category, label}` are matched to the corresponding+ * variation and their `result.filename` is appended to `imageRefs[]`. Best-+ * effort — most historical jobs have already been purged from the queue+ * file, so this only resurrects a handful of thumbnails. New renders+ * continue to attach via the `appendEntryImageRef` collection hook.+ *+ * What this does to each universe in data/universe-builder.json:+ * - Stamp `locked: true` on every `characters[]` / `places[]` / `objects[]`+ * entry that has no `locked` field. Explicit `locked: false` is preserved+ * so a user who already unlocked an entry stays unlocked.+ * - Stamp `locked: true` on every variation in every+ * `categories[bucket].variations[]` that has no `locked` field. Mint a+ * UUID `id` for any variation that lacks one (key for future entryRef+ * stamping). Same for `compositeSheets[]`.+ * - For each completed media job in data/media-jobs.json whose+ * `params.universeRun.{universeId, category, label}` matches a variation+ * in this universe, append `result.filename` to that variation's+ * `imageRefs[]` (deduped, oldest-first preserved, capped at 12 — mirrors+ * the runtime cap in `appendEntryImageRef`).+ *+ * Idempotent: re-runs skip entries that already have an explicit `locked`+ * field AND already include the candidate filename in `imageRefs[]`.+ */++import { readFile, writeFile } from 'fs/promises';+import { join } from 'path';+import { randomUUID } from 'crypto';++// Mirrors sanitizeImageRefs cap in server/services/universeBuilder.js+const IMAGE_REFS_PER_ENTRY_MAX = 12;++const readJson = async (path) => {+ const raw = await readFile(path, 'utf-8').catch((err) => {+ if (err.code === 'ENOENT') return null;+ throw err;+ });+ if (raw == null) return null;+ return JSON.parse(raw);+};++const writeJson = (path, value) =>+ writeFile(path, JSON.stringify(value, null, 2) + '\n');++// Same normalization the runtime `normalizeCategoryKey` produces. Inlined so+// this migration's contract is frozen against future renames.+const normalizeCategoryKey = (raw) => {+ if (typeof raw !== 'string') return '';+ return raw+ .trim()+ .toLowerCase()+ .replace(/&/g, ' and ')+ .replace(/[^a-z0-9]+/g, '_')+ .replace(/^_+|_+$/g, '')+ .replace(/_{2,}/g, '_')+ .slice(0, 64);+};++const labelKey = (label) =>+ typeof label === 'string' ? label.trim().toLowerCase() : '';++const ensureLocked = (entry) => {+ if (!entry || typeof entry !== 'object') return entry;+ if (entry.locked === true || entry.locked === false) return entry;+ return { ...entry, locked: true };+};++const ensureIdOnVariation = (entry, prefix) => {+ if (!entry || typeof entry !== 'object') return entry;+ if (typeof entry.id === 'string' && entry.id.trim()) return entry;+ return { ...entry, id: `${prefix}${randomUUID()}` };+};++const appendUniqueRef = (entry, filename) => {+ if (!entry || typeof entry !== 'object' || !filename) return { entry, added: false };+ const refs = Array.isArray(entry.imageRefs) ? entry.imageRefs : [];+ if (refs.includes(filename)) return { entry, added: false };+ const next = [...refs, filename];+ const capped = next.length > IMAGE_REFS_PER_ENTRY_MAX+ ? next.slice(-IMAGE_REFS_PER_ENTRY_MAX)+ : next;+ return { entry: { ...entry, imageRefs: capped }, added: true };+};++export default {+ async up({ rootDir }) {+ const universesPath = join(rootDir, 'data', 'universe-builder.json');+ const jobsPath = join(rootDir, 'data', 'media-jobs.json');++ const universesDoc = await readJson(universesPath);+ if (!universesDoc || !Array.isArray(universesDoc.universes)) {+ return { reason: 'no-universes' };+ }++ let lockedCanon = 0;+ let lockedVariations = 0;+ let lockedSheets = 0;+ let mintedVariationIds = 0;+ let mintedSheetIds = 0;++ for (const universe of universesDoc.universes) {+ for (const kindKey of ['characters', 'places', 'objects']) {+ const list = Array.isArray(universe[kindKey]) ? universe[kindKey] : [];+ const before = list.filter((e) => e?.locked === true).length;+ universe[kindKey] = list.map(ensureLocked);+ const after = universe[kindKey].filter((e) => e?.locked === true).length;+ lockedCanon += Math.max(0, after - before);+ }++ const categories = universe.categories && typeof universe.categories === 'object'+ ? universe.categories+ : null;+ if (categories) {+ for (const [bucketKey, bucket] of Object.entries(categories)) {+ if (!bucket || !Array.isArray(bucket.variations)) continue;+ bucket.variations = bucket.variations.map((v) => {+ if (!v || typeof v !== 'object') return v;+ let next = v;+ if (typeof next.id !== 'string' || !next.id.trim()) {+ next = ensureIdOnVariation(next, 'var-');+ mintedVariationIds += 1;+ }+ if (next.locked !== true && next.locked !== false) {+ next = { ...next, locked: true };+ lockedVariations += 1;+ }+ return next;+ });+ categories[bucketKey] = bucket;+ }+ }++ if (Array.isArray(universe.compositeSheets)) {+ universe.compositeSheets = universe.compositeSheets.map((s) => {+ if (!s || typeof s !== 'object') return s;+ let next = s;+ if (typeof next.id !== 'string' || !next.id.trim()) {+ next = ensureIdOnVariation(next, 'sheet-');+ mintedSheetIds += 1;+ }+ if (next.locked !== true && next.locked !== false) {+ next = { ...next, locked: true };+ lockedSheets += 1;+ }+ return next;+ });+ }+ }++ // Best-effort imageRefs back-fill from surviving media jobs. Index variations+ // by `${universeId}|${normalizedCategoryKey}|${lowercaseLabel}` so the+ // lookup is one hash hit per matching job.+ let appendedRefs = 0;+ const jobsDoc = await readJson(jobsPath);+ const jobs = Array.isArray(jobsDoc?.jobs) ? jobsDoc.jobs : [];+ if (jobs.length > 0) {+ const variationIndex = new Map();+ for (const universe of universesDoc.universes) {+ const categories = universe.categories && typeof universe.categories === 'object'+ ? universe.categories+ : null;+ if (!categories) continue;+ for (const [bucketKey, bucket] of Object.entries(categories)) {+ if (!bucket || !Array.isArray(bucket.variations)) continue;+ const catKey = normalizeCategoryKey(bucketKey);+ bucket.variations.forEach((v, idx) => {+ if (!v || typeof v.label !== 'string') return;+ const key = `${universe.id}|${catKey}|${labelKey(v.label)}`;+ const existing = variationIndex.get(key);+ // If two variations in the same bucket share a label, prefer+ // the first — matches the dedupe behavior in sanitizeCategories.+ if (!existing) variationIndex.set(key, { universe, bucketKey, idx });+ });+ }+ }++ for (const job of jobs) {+ if (!job || job.kind !== 'image' || job.status !== 'completed') continue;+ const tag = job.params?.universeRun;+ const filename = job.result?.filename;+ if (!tag || !filename || typeof filename !== 'string') continue;+ const universeId = tag.universeId;+ const category = normalizeCategoryKey(tag.category);+ const label = labelKey(tag.label);+ if (!universeId || !category || !label) continue;+ const hit = variationIndex.get(`${universeId}|${category}|${label}`);+ if (!hit) continue;+ const bucket = hit.universe.categories[hit.bucketKey];+ const variations = Array.isArray(bucket.variations) ? bucket.variations : [];+ const current = variations[hit.idx];+ const { entry: nextEntry, added } = appendUniqueRef(current, filename);+ if (added) {+ variations[hit.idx] = nextEntry;+ bucket.variations = variations;+ hit.universe.categories[hit.bucketKey] = bucket;+ appendedRefs += 1;+ }+ }+ }++ await writeJson(universesPath, universesDoc);+ console.log(+ `🔒 migration 024: locked ${lockedCanon} canon entr${lockedCanon === 1 ? 'y' : 'ies'}, `+ + `${lockedVariations} variation${lockedVariations === 1 ? '' : 's'}, `+ + `${lockedSheets} composite sheet${lockedSheets === 1 ? '' : 's'}.`,+ );+ if (mintedVariationIds > 0 || mintedSheetIds > 0) {+ console.log(+ `🆔 migration 024: minted stable ids for ${mintedVariationIds} variation${mintedVariationIds === 1 ? '' : 's'} `+ + `and ${mintedSheetIds} composite sheet${mintedSheetIds === 1 ? '' : 's'} `+ + '(future renders can now attach imageRefs by id).',+ );+ }+ if (appendedRefs > 0) {+ console.log(+ `🖼️ migration 024: back-filled ${appendedRefs} historical render thumbnail${appendedRefs === 1 ? '' : 's'} `+ + 'on variations from surviving media-jobs.json entries.',+ );+ }+ return { lockedCanon, lockedVariations, lockedSheets, mintedVariationIds, mintedSheetIds, appendedRefs };+ },+};diff --git a/server/lib/storyBible.js b/server/lib/storyBible.jsindex aa8b032c20..48c9d41145 100644--- a/server/lib/storyBible.js+++ b/server/lib/storyBible.js@@ -456,9 +456,10 @@ function sanitizeHandGesture(raw) {return { id: ensureId(raw.id, 'gesture-'), name, description: trimTo(raw.description, BIBLE_LIMITS.GESTURE_DESC_MAX) };}-// Shared canon extras applied to every kind. `locked` follows the on-disk-// minimization pattern from universe-builder variations: only `true` is-// persisted, missing/false collapses to absent.+// Shared canon extras applied to every kind. Persists explicit `locked: true`+// AND `locked: false` so a Universe-Builder caller can flip the bit and have+// the change survive round-trips. Missing `locked` still collapses to absent+// — writers-room callers that never set the flag stay on the legacy shape.function applyCanonExtras(raw) {const out = {prompt: trimTo(raw.prompt, BIBLE_LIMITS.PROMPT_MAX),@@ -467,6 +468,7 @@ function applyCanonExtras(raw) {sourceSeriesId: trimTo(raw.sourceSeriesId, BIBLE_LIMITS.SOURCE_SERIES_ID_MAX) || null,};if (raw.locked === true) out.locked = true;+ else if (raw.locked === false) out.locked = false;return out;}diff --git a/server/lib/storyBible.test.js b/server/lib/storyBible.test.jsindex b7ffde1a30..1b6f6e213c 100644--- a/server/lib/storyBible.test.js+++ b/server/lib/storyBible.test.js@@ -120,8 +120,12 @@ describe('storyBible — sanitizeCharacter', () => {expect(out.source).toBe('series-extract');});- it('omits locked when not strictly true (mirrors variation pattern)', () => {- expect(sanitizeCharacter({ name: 'A', locked: false }).locked).toBeUndefined();+ it('preserves explicit true/false on locked and omits other shapes', () => {+ // applyCanonExtras now persists explicit `locked: false` so the+ // universe-builder lock-by-default contract can round-trip an unlock.+ // Anything else (truthy non-bool, missing) still collapses to absent so+ // writers-room callers that never set the flag stay on the legacy shape.+ expect(sanitizeCharacter({ name: 'A', locked: false }).locked).toBe(false);expect(sanitizeCharacter({ name: 'A', locked: 'yes' }).locked).toBeUndefined();expect(sanitizeCharacter({ name: 'A', locked: 1 }).locked).toBeUndefined();expect(sanitizeCharacter({ name: 'A' }).locked).toBeUndefined();diff --git a/server/routes/universeBuilder.js b/server/routes/universeBuilder.jsindex 3aee87ca55..23daa5ccd4 100644--- a/server/routes/universeBuilder.js+++ b/server/routes/universeBuilder.js@@ -519,6 +519,12 @@ router.post('/:id/render', asyncHandler(async (req, res) => {loraScales,};+ // Parallel-indexed mapping from jobId → entryRef so the client can show a+ // per-entry pending loader (MediaJobThumb-style) on the variation / sheet /+ // canon row that owns this render. Only entries with a stable `id` carry an+ // entryRef in `compiled` (the sanitizer mints ids on every write now, so+ // legacy id-less records are the only gap).+ const entryJobs = [];for (const item of compiled) {const params = {...baseParams,@@ -541,22 +547,23 @@ router.post('/:id/render', asyncHandler(async (req, res) => {...(item.entryRef ? { entryRef: item.entryRef } : {}),},};+ let queued;if (mode === 'codex') {const c = settings.imageGen?.codex || {};- const queued = enqueueJob({+ queued = enqueueJob({kind: 'image',params: { mode: 'codex', codexPath: c.codexPath, model: c.model, ...params },});- jobIds.push(queued.jobId);- continue;+ } else {+ // mode === 'local' (validated upfront).+ const py = settings.imageGen?.local?.pythonPath || null;+ queued = enqueueJob({+ kind: 'image',+ params: { pythonPath: py, modelId: body.modelId, ...params },+ });}- // mode === 'local' (validated upfront).- const py = settings.imageGen?.local?.pythonPath || null;- const queued = enqueueJob({- kind: 'image',- params: { pythonPath: py, modelId: body.modelId, ...params },- });jobIds.push(queued.jobId);+ if (item.entryRef) entryJobs.push({ jobId: queued.jobId, entryRef: item.entryRef });}const run = await svc.recordRun({@@ -580,6 +587,9 @@ router.post('/:id/render', asyncHandler(async (req, res) => {collectionName: collection.name,promptCount: compiled.length,jobIds,+ // Per-entry mapping for client-side pending-state UI. Empty when the+ // batch only contains entries without stable ids (legacy fallback).+ entryJobs,mode,});}));@@ -716,4 +726,33 @@ router.patch('/:id/canon/:kind/:entryId/lock', asyncHandler(async (req, res) =>res.json(result);}));+// Bulk lock/unlock every canon entry of a single kind. Powers the+// "Lock all / Unlock all" buttons in the Universe Builder canon section.+router.patch('/:id/canon/:kind/lock-all', asyncHandler(async (req, res) => {+ const { kind } = validateRequest(lockParamsSchema, req.params);+ const body = validateRequest(setLockSchema, req.body ?? {});+ const result = await canonSvc.setCanonKindLockAll(req.params.id, kind, body.locked)+ .catch((err) => { throw mapServiceError(err); });+ res.json(result);+}));++// Bulk lock/unlock every variation in a category bucket. Powers the+// per-bucket "Lock all / Unlock all" affordance on the variations grid.+// Omit `category` in the body to apply to every variation in every bucket;+// pass `includeSheets: true` to also flip composite sheets in the same call.+const setVariationsLockAllSchema = z.object({+ locked: z.boolean(),+ category: z.string().trim().min(1).max(svc.WORLD_CATEGORY_KEY_MAX).nullable().optional(),+ includeSheets: z.boolean().optional(),+});+router.patch('/:id/variations/lock-all', asyncHandler(async (req, res) => {+ const body = validateRequest(setVariationsLockAllSchema, req.body ?? {});+ const result = await svc.setVariationsLockAll(req.params.id, {+ categoryKey: body.category || null,+ locked: body.locked,+ includeSheets: body.includeSheets === true,+ }).catch((err) => { throw mapServiceError(err); });+ res.json(result);+}));+export default router;diff --git a/server/services/universeBuilder.js b/server/services/universeBuilder.jsindex afe68312db..376b9efb75 100644--- a/server/services/universeBuilder.js+++ b/server/services/universeBuilder.js@@ -286,15 +286,17 @@ const sanitizeVariation = (raw) => {const prompt = trimTo(raw.prompt, PROMPT_FRAGMENT_MAX);if (!label || !prompt) return null;// 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.+ // letting the LLM regenerate it. Default is `true` (locked) so newly-arriving+ // variations from extract / generate / manual add are protected by default;+ // only explicit `locked: false` records the user's unlock so it survives+ // round-trips through the sanitizer.const out = {id: ensureEntryId(raw.id, 'var-'),label,prompt,imageRefs: sanitizeEntryImageRefs(raw.imageRefs),+ locked: raw.locked === false ? false : true,};- if (raw.locked === true) out.locked = true;return out;};@@ -304,14 +306,16 @@ 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';+ // Default to locked — same rationale as sanitizeVariation; user explicitly+ // unlocks via `locked: false` and that survives round-trips.const out = {id: ensureEntryId(raw.id, 'sheet-'),kind,label,prompt,imageRefs: sanitizeEntryImageRefs(raw.imageRefs),+ locked: raw.locked === false ? false : true,};- if (raw.locked === true) out.locked = true;return out;};@@ -702,7 +706,18 @@ const sanitizeTemplate = (raw) => {objects: raw.objects,});const canonBackfill = backfillCanonFromCategories(raw, foldedCanon);- const { characters, places, objects, schemaVersion } = canonBackfill;+ const { schemaVersion } = canonBackfill;+ // Default-lock universe canon entries. Existing records on disk that pre-+ // date the lock-by-default contract have no `locked` field; stamp `true`+ // here so reads return a locked view. Explicit `locked: false` is preserved+ // verbatim so a user-unlock survives round-trips (applyCanonExtras now+ // persists both true and false).+ const defaultLockCanon = (list) => (Array.isArray(list) ? list : []).map((e) =>+ e && typeof e === 'object' && e.locked === undefined ? { ...e, locked: true } : e+ );+ const characters = defaultLockCanon(canonBackfill.characters);+ const places = defaultLockCanon(canonBackfill.places);+ const objects = defaultLockCanon(canonBackfill.objects);const llm = raw.llm && typeof raw.llm === 'object'? {provider: trimTo(raw.llm.provider, 80) || null,@@ -1174,6 +1189,63 @@ export async function listRuns(universeId = null) {// 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.+/**+ * Bulk-set `locked` on every variation in a category bucket. When+ * `categoryKey` is null, every variation in every bucket of the universe is+ * affected. Composite sheets are included in the universe-wide path (caller+ * intent for "lock everything" is consistent across both lists). Returns the+ * updated universe plus the count of variations whose state actually changed+ * — entries already at the target state are no-ops so the toast can read+ * "Locked N variations".+ */+export async function setVariationsLockAll(universeId, { categoryKey = null, locked, includeSheets = false } = {}) {+ const target = locked === true;+ let changed = 0;+ let total = 0;+ const updated = await updateUniverse(universeId, (cur) => {+ const patch = {};+ const categories = cur.categories || {};+ const nextCategories = {};+ let touchedCategories = false;+ for (const [key, bucket] of Object.entries(categories)) {+ const variations = Array.isArray(bucket?.variations) ? bucket.variations : [];+ total += variations.length;+ if (categoryKey && key !== categoryKey) {+ nextCategories[key] = bucket;+ continue;+ }+ let bucketTouched = false;+ const nextVariations = variations.map((v) => {+ if (!v || typeof v !== 'object') return v;+ if ((v.locked === true) === target) return v;+ changed += 1;+ bucketTouched = true;+ return { ...v, locked: target };+ });+ nextCategories[key] = bucketTouched ? { ...bucket, variations: nextVariations } : bucket;+ if (bucketTouched) touchedCategories = true;+ }+ if (touchedCategories) patch.categories = nextCategories;++ if (!categoryKey && includeSheets && Array.isArray(cur.compositeSheets)) {+ total += cur.compositeSheets.length;+ let sheetsTouched = false;+ const nextSheets = cur.compositeSheets.map((s) => {+ if (!s || typeof s !== 'object') return s;+ if ((s.locked === true) === target) return s;+ changed += 1;+ sheetsTouched = true;+ return { ...s, locked: target };+ });+ if (sheetsTouched) patch.compositeSheets = nextSheets;+ }++ if (!Object.keys(patch).length) return null;+ return patch;+ });+ return { universe: updated, locked: target, changed, total, categoryKey: categoryKey || null };+}+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 adiff --git a/server/services/universeBuilder.test.js b/server/services/universeBuilder.test.jsindex 8c0502082c..911771645f 100644--- a/server/services/universeBuilder.test.js+++ b/server/services/universeBuilder.test.js@@ -127,6 +127,9 @@ describe("universeBuilder service", () => {label: "Rib-Cage Nomads",prompt: "reference sheet, layered sailcloth, bone toggles",imageRefs: [],+ // Variations now lock-by-default — see sanitizeVariation in+ // services/universeBuilder.js for the contract.+ locked: true,},]);expect(w.categories.factions.variations).toHaveLength(1);@@ -151,6 +154,8 @@ describe("universeBuilder service", () => {prompt:"Create a clean illustrated costume reference sheet with five figures, materials swatches, fasteners, accessories, and color palette strip.",imageRefs: [],+ // Composite sheets lock-by-default — see sanitizeCompositeSheet.+ locked: true,},]);});@@ -174,6 +179,8 @@ describe("universeBuilder service", () => {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: [],+ // Composite sheets lock-by-default — see sanitizeCompositeSheet.+ locked: true,},]);});@@ -1133,27 +1140,30 @@ describe("universeBuilder service", () => {});describe("per-item locks", () => {- it("round-trips a `locked: true` flag on variations", async () => {+ it("defaults variations to locked + preserves explicit lock state", async () => {+ // Variations now lock-by-default: an entry with no `locked` field+ // reads as locked, and explicit `false` survives the round-trip so+ // a user-unlock isn't silently re-locked on the next read.const w = await seedWorld({categories: {landscapes: {variations: [- {- label: "Pinned canyon",- prompt: "pinned canyon prompt",- locked: true,- },+ { label: "Pinned canyon", prompt: "pinned canyon prompt", locked: true },{ label: "Open canyon", prompt: "open canyon prompt" },+ { label: "Hand-unlocked", prompt: "hand unlocked prompt", locked: false },],},},});const vs = w.categories.landscapes.variations;expect(vs.find((v) => v.label === "Pinned canyon").locked).toBe(true);- expect(vs.find((v) => v.label === "Open canyon").locked).toBeUndefined();+ expect(vs.find((v) => v.label === "Open canyon").locked).toBe(true);+ expect(vs.find((v) => v.label === "Hand-unlocked").locked).toBe(false);});- it("drops non-true `locked` values rather than recording them", async () => {+ it("coerces non-boolean `locked` values to the locked-by-default state", async () => {+ // Anything other than `false` collapses to the default (true); only+ // explicit `false` records an unlock.const w = await seedWorld({categories: {landscapes: {@@ -1168,12 +1178,12 @@ describe("universeBuilder service", () => {const labels = Object.fromEntries(w.categories.landscapes.variations.map((v) => [v.label, v.locked]),);- expect(labels.A).toBeUndefined();- expect(labels.B).toBeUndefined();- expect(labels.C).toBeUndefined();+ expect(labels.A).toBe(false);+ expect(labels.B).toBe(true);+ expect(labels.C).toBe(true);});- it("round-trips a `locked: true` flag on composite sheets", async () => {+ it("defaults composite sheets to locked + preserves explicit lock state", async () => {const w = await seedWorld({compositeSheets: [{@@ -1183,6 +1193,7 @@ describe("universeBuilder service", () => {locked: true,},{ label: "Open sheet", prompt: "open sheet prompt long enough" },+ { label: "Unlocked sheet", prompt: "unlocked sheet prompt long enough", locked: false },],});expect(@@ -1190,7 +1201,10 @@ describe("universeBuilder service", () => {).toBe(true);expect(w.compositeSheets.find((s) => s.label === "Open sheet").locked,- ).toBeUndefined();+ ).toBe(true);+ expect(+ w.compositeSheets.find((s) => s.label === "Unlocked sheet").locked,+ ).toBe(false);});});diff --git a/server/services/universeBuilderExpand.test.js b/server/services/universeBuilderExpand.test.jsindex 55552da2eb..d535a83e8b 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([- { 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: [] },+ { id: expect.stringMatching(/^var-/), label: "Crystalline canyon basin", prompt: "Crystalline canyon basin", imageRefs: [], locked: true },+ { id: expect.stringMatching(/^var-/), label: "Salt flat ruins", prompt: "Salt flat ruins", imageRefs: [], locked: true },]);});@@ -183,7 +183,7 @@ describe("universeBuilderExpand.normalizeCategories", () => {},});expect(out.vehicles.variations).toEqual([- { id: expect.stringMatching(/^var-/), label: "Walker mech", prompt: "rusted six-leg walker mech", imageRefs: [] },+ { id: expect.stringMatching(/^var-/), label: "Walker mech", prompt: "rusted six-leg walker mech", imageRefs: [], locked: true },]);});@@ -200,7 +200,7 @@ describe("universeBuilderExpand.normalizeCategories", () => {},});expect(out.structures.variations).toEqual([- { id: expect.stringMatching(/^var-/), label: "Tower", prompt: "spire of obsidian", imageRefs: [] },+ { id: expect.stringMatching(/^var-/), label: "Tower", prompt: "spire of obsidian", imageRefs: [], locked: true },]);});@@ -215,7 +215,7 @@ describe("universeBuilderExpand.normalizeCategories", () => {});expect(out.landscapes.variations).toHaveLength(1);expect(out.raider_pirate_clans.variations).toEqual([- { id: expect.stringMatching(/^var-/), label: "Wake Jackals", prompt: "spare moebius scavenger raiders", imageRefs: [] },+ { id: expect.stringMatching(/^var-/), label: "Wake Jackals", prompt: "spare moebius scavenger raiders", imageRefs: [], locked: true },]);});@@ -264,6 +264,7 @@ describe("universeBuilderExpand.normalizeCompositeSheets", () => {prompt:"Create a clean illustrated costume reference sheet with five figures, material swatches, fasteners, accessories, color palette strip, and simple floating-platform background.",imageRefs: [],+ locked: true,},]);});@@ -277,6 +278,7 @@ describe("universeBuilderExpand.normalizeCompositeSheets", () => {label: "Canopy Symbiotes reference board",prompt: "Canopy Symbiotes reference board",imageRefs: [],+ locked: true,},]);});@@ -298,6 +300,7 @@ describe("universeBuilderExpand.normalizeCompositeSheets", () => {prompt:"Create a cinematic universe summary concept pitch poster with hero panorama, inset environments, culture callouts, palette, materials, light atmosphere, and theme icons.",imageRefs: [],+ locked: true,},]);});diff --git a/server/services/universeBuilderPromote.js b/server/services/universeBuilderPromote.jsindex dfc02db918..9ca18a8294 100644--- a/server/services/universeBuilderPromote.js+++ b/server/services/universeBuilderPromote.js@@ -272,6 +272,10 @@ export async function promoteVariationToCanon(universeId, options = {}) {...stripCanonControlFields(parsed),name: (typeof parsed?.name === 'string' && parsed.name.trim()) ? parsed.name.trim() : variation.label,source: BIBLE_SOURCE.UNIVERSE_EXPAND,+ // Default-lock promoted canon entries. Promotion produces a named identity+ // the user picked deliberately; treat it as user-authoritative so AI+ // refine/differentiate paths skip it until the user explicitly unlocks.+ locked: true,};if (!enriched.prompt && typeof variation.prompt === 'string' && variation.prompt.trim()) {enriched.prompt = variation.prompt.trim();diff --git a/server/services/universeBuilderPromote.test.js b/server/services/universeBuilderPromote.test.jsindex 34a268d226..ee85afbbde 100644--- a/server/services/universeBuilderPromote.test.js+++ b/server/services/universeBuilderPromote.test.js@@ -406,8 +406,11 @@ describe('universeBuilderPromote — control field stripping', () => {});// ID stripped → sanitizer mints a fresh one.expect(result.entry.id).not.toBe('set-hallucinated');- // `locked` stripped → user has to explicitly lock from the canon UI.- expect(result.entry.locked).toBeUndefined();+ // LLM's `locked` flag is stripped, but promote stamps `locked: true` at+ // the service layer as part of the universe-builder lock-by-default+ // contract — promoted identities are user-deliberate so AI rewrite paths+ // should skip them until the user explicitly unlocks.+ expect(result.entry.locked).toBe(true);// Image refs stripped → those are operational, owned by the render UI.expect(result.entry.imageRefs).toEqual([]);expect(result.entry.primaryImageRef).toBe(null);diff --git a/server/services/universeCanon.js b/server/services/universeCanon.jsindex 6315aa3671..a28b68d773 100644--- a/server/services/universeCanon.js+++ b/server/services/universeCanon.js@@ -71,16 +71,46 @@ export async function extractCanonFromProse(universeId, opts = {}) {? await Promise.all(kinds.map(runOne)): await kinds.reduce(async (acc, kind) => [...(await acc), await runOne(kind)], Promise.resolve([]));+ const wantsLock = opts.autoLock !== false;const mergeOpts = {source: opts.source || BIBLE_SOURCE.SERIES_EXTRACT,- autoLock: opts.autoLock === true,+ // Default to locked-on-insert. New canon entries are protected from AI+ // overwrite from the moment they land so users don't have to chase a+ // batch extract with a Lock All click. Callers can opt out with an+ // explicit `autoLock: false` — in that case we still stamp `locked:+ // false` on the new entries below so the universe-side+ // lock-by-default contract (sanitizeTemplate.defaultLockCanon) doesn't+ // silently re-lock them on the next read.+ autoLock: wantsLock,sourceSeriesId: opts.sourceSeriesId || null,};const results = {};const patch = {};for (const { kind, result } of completed) {const field = BIBLE_FIELD[kind];- patch[field] = mergeExtractedBible(universe[field] || [], result.extracted, kind, mergeOpts);+ // Capture existing ids BEFORE the merge — mergeExtractedBible mutates the+ // existing list in place via push(), so reading universe[field] after the+ // merge already includes the new inserts and breaks the "is this an+ // already-known entry?" check below.+ const existingIds = wantsLock+ ? null+ : new Set((universe[field] || []).map((e) => e?.id).filter(Boolean));+ const merged = mergeExtractedBible(universe[field] || [], result.extracted, kind, mergeOpts);+ // Opt-out path: caller asked for unlocked inserts. The merge step left+ // `locked` absent on new entries; sanitizeTemplate.defaultLockCanon+ // would then read them back as locked. Stamp explicit `false` on every+ // entry the merge inserted that doesn't already have a `locked` field+ // so the unlock survives the round-trip.+ if (!wantsLock) {+ patch[field] = merged.map((e) => {+ if (!e || typeof e !== 'object') return e;+ if (existingIds.has(e.id)) return e;+ if (e.locked === true || e.locked === false) return e;+ return { ...e, locked: false };+ });+ } else {+ patch[field] = merged;+ }results[field] = {extracted: result.extracted, runId: result.runId,providerId: result.providerId, model: result.model,@@ -248,14 +278,41 @@ export async function setCanonEntryLock(universeId, kind, entryId, locked) {if ((target.locked === true) === (locked === true)) {return { universe, entry: target };}- // applyCanonExtras strips locked: false on save, so we can pass it through- // directly instead of destructure-stripping here.+ // applyCanonExtras now persists explicit locked:false (the universe-builder+ // contract), so the bit survives the round-trip and the unlock sticks.const nextList = list.map((e, i) => (i === idx ? { ...e, locked } : e));const updated = await updateUniverse(universeId, { [field]: nextList });const entry = (updated[field] || []).find((e) => e.id === entryId) || null;return { universe: updated, entry };}+/**+ * Bulk-set the `locked` flag on every canon entry of a single kind. Returns+ * the updated universe plus the count of entries whose lock state actually+ * changed (no-op on entries already in the target state, so the response+ * carries enough info for a toast like "Locked 7 characters").+ */+export async function setCanonKindLockAll(universeId, kind, locked) {+ if (!BIBLE_KINDS.includes(kind)) {+ throw new ServerError(+ `Invalid canon kind "${kind}" — expected one of: ${BIBLE_KINDS.join(', ')}`,+ { status: 400, code: 'UNIVERSE_CANON_INVALID_KIND' },+ );+ }+ const universe = await getUniverse(universeId);+ const field = BIBLE_FIELD[kind];+ const list = Array.isArray(universe[field]) ? universe[field] : [];+ let changed = 0;+ const nextList = list.map((e) => {+ if ((e.locked === true) === (locked === true)) return e;+ changed += 1;+ return { ...e, locked };+ });+ if (changed === 0) return { universe, kind, locked, changed: 0, total: list.length };+ const updated = await updateUniverse(universeId, { [field]: nextList });+ return { universe: updated, kind, locked, changed, total: list.length };+}+/*** Strip a filename from every `imageRefs[]` across every universe's* characters/places/objects. Mirror of the series-side purge so the image-diff --git a/server/services/universeCanon.test.js b/server/services/universeCanon.test.jsindex 046133fd5c..8714e08e3f 100644--- a/server/services/universeCanon.test.js+++ b/server/services/universeCanon.test.js@@ -70,13 +70,19 @@ describe('universeCanon — setCanonEntryLock', () => {expect(reread.characters.find((c) => c.id === entryId).locked).toBe(true);});- it('removes the locked field entirely on unlock (minimal on-disk shape)', async () => {+ it('persists explicit locked: false on unlock so the bit survives round-trips', async () => {+ // After PR #N the universe-builder canon contract is "locked by default":+ // a missing `locked` field reads as locked. Unlock therefore MUST persist+ // explicit `false` rather than collapsing to absent — otherwise the next+ // read of the same record would re-lock it.const w = await seedUniverseWithCharacters([{ name: 'Alex', physicalDescription: 'jacket', locked: true },]);const entryId = w.characters[0].id;const { entry } = await canonSvc.setCanonEntryLock(w.id, 'character', entryId, false);- expect(entry.locked).toBeUndefined();+ expect(entry.locked).toBe(false);+ const reread = (await svc.listUniverses())[0];+ expect(reread.characters.find((c) => c.id === entryId).locked).toBe(false);});it('rejects unknown kind with a 400-coded ServerError', async () => {@@ -111,9 +117,12 @@ describe('universeCanon — refineUniverseCharacter respects locks', () => {});it('proceeds when the character is unlocked', async () => {+ // Universe canon is locked-by-default — seed entries with explicit+ // `locked: false` to put them in the unlocked state the refine guard+ // requires.const w = await seedUniverseWithCharacters([- { name: 'Alex', physicalDescription: 'jacket' },- { name: 'Beth', physicalDescription: 'coat' },+ { name: 'Alex', physicalDescription: 'jacket', locked: false },+ { name: 'Beth', physicalDescription: 'coat', locked: false },]);runPromptRefineMock.mockResolvedValue({refined: 'fresh description', changes: [], rationale: 'distinct from Beth',@@ -127,9 +136,11 @@ describe('universeCanon — refineUniverseCharacter respects locks', () => {describe('universeCanon — differentiateUniverseCast respects locks', () => {it('skips locked entries at apply time even though the LLM saw them', async () => {+ // Beth is explicitly unlocked so the cast isn't all-locked (the guard+ // before the LLM call) while Alex stays protected at apply time.const w = await seedUniverseWithCharacters([{ name: 'Alex', physicalDescription: 'jacket', locked: true },- { name: 'Beth', physicalDescription: 'coat' },+ { name: 'Beth', physicalDescription: 'coat', locked: false },]);const [alex, beth] = w.characters;runStagedLLMMock.mockResolvedValue({@@ -182,7 +193,10 @@ describe('universeCanon — extractCanonFromProse passes autoLock + sourceSeriesexpect(inserted.sourceSeriesId).toBe('ser-active');});- it('without autoLock, new entries are unlocked (universe-side direct extraction)', async () => {+ it('without an explicit autoLock=false, new entries lock by default', async () => {+ // The universe-builder default is "lock new canon on insert" so users+ // don't have to chase batch extracts with a Lock All click; only an+ // explicit `autoLock: false` opts out.const w = await seedUniverseWithCharacters([]);extractBibleMock.mockImplementation(async ({ kind }) => ({extracted: kind === 'character' ? [{ name: 'Newby' }] : [],@@ -193,7 +207,22 @@ describe('universeCanon — extractCanonFromProse passes autoLock + sourceSerieskinds: ['character'],});const inserted = result.universe.characters.find((c) => c.name === 'Newby');- expect(inserted.locked).toBeUndefined();+ expect(inserted.locked).toBe(true);expect(inserted.source).toBe('series-extract'); // default new vocab});++ it('autoLock=false opts out so the entry lands unlocked', async () => {+ const w = await seedUniverseWithCharacters([]);+ extractBibleMock.mockImplementation(async ({ kind }) => ({+ extracted: kind === 'character' ? [{ name: 'Optout' }] : [],+ runId: 'r', providerId: 'p', model: 'm',+ }));+ const result = await canonSvc.extractCanonFromProse(w.id, {+ corpus: 'some prose',+ kinds: ['character'],+ autoLock: false,+ });+ const inserted = result.universe.characters.find((c) => c.name === 'Optout');+ expect(inserted.locked).not.toBe(true);+ });});