Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

feat(universe-builder): Phase C — tabbed-trunk layout + canon batch render (#279)

[._.]/ Adam Eivyda6f9348925f
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 39e7eb54ef..04fe4f8a83 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -2,6 +2,7 @@
## Changed
+- **Universe Builder redesign — tabbed trunks replace the long-scroll layout.** The Universe Builder page is now organized into seven tabs — **Bible / Cast / Places / Objects / Composites / Render** (plus **Other** when un-classified buckets exist) — driven by `?tab=…&bucket=…` URL params (deep-linkable, back/forward works, mobile collapses to a `<select>`). Each canon trunk surfaces the universe's canon entries alongside that trunk's sub-buckets in one card grid: filter by sub-bucket via chip strip, "Bulk-render all Cast/Places/Objects" hits canon + every variation under the trunk in one render run, "Bulk-render this bucket" scopes to a single sub-bucket. The **Render** tab consolidates the batch-render controls + adds per-trunk, per-bucket, "All canon" and "All composites" one-click targets. Server-side: `compilePrompts` now accepts `canonSelection` and a new `promptMode: 'canon'` (`'all'` includes canon too), synthesizing the render prompt from `name + physicalDescription / palette / description / recurringDetails / significance` for entries without a hand-authored prompt. The legacy long-scroll layout is gone.
- **CoS agent completion paths now share `finalizeAgent` + `releaseAgentLane` helpers.** The TUI shell-session path, the direct-CLI path, and the runner-mode completion handler used to each carry their own copy of the lane release / completeAgent / completeAgentRun / updateTask / provider-marker / processAgentCompletion sequence. Drift between them silently broke one path at a time. Lane release + tool-execution tracking now run early (before output I/O) via `releaseAgentLane()`, and the centralized state writes (completeAgent → completeAgentRun → updateTask → provider markers → processAgentCompletion) go through `finalizeAgent()` — a future change in either contract is a one-place fix.
- **CoS runner-agent map no longer leaks on hook crashes.** A throw from any post-completion step (memory extraction, JIRA push, provider marker, etc.) used to skip the final `runnerAgents.delete(agentId)` and strand the entry forever. The completion sequence is now wrapped in try/finally; the error still surfaces but the in-memory state stays coherent.
- **TUI providers are now usable from the manual `/api/runs` runner panel.** The "Run Prompt" button on `/settings/ai-providers` was disabled for TUI providers with a hint that they had to go through CoS tasks. The server-side `executeTuiRun` branch already handled them — the client-side disable was stale.
diff --git a/PLAN.md b/PLAN.md
index e58dce75df..1ee651ec1c 100644
--- a/PLAN.md
+++ b/PLAN.md
@@ -11,6 +11,11 @@ For project goals, see [GOALS.md](./GOALS.md). For completed work, see [DONE.md]
- **Phase B — Expand contract enrichment.** Teach `buildExpansionPrompt()` (`server/services/universeBuilderExpand.js`) to return rich canon arrays (`characters[]`/`settings[]`/`objects[]` with `physicalDescription`/`palette`/`recurringDetails`/`wardrobe`) alongside the existing `categories` (now kind-tagged) + `compositeSheets`. Update `isExpansionShape()` predicate. Client `handleExpand` in `UniverseBuilder.jsx` merges canon entries into the canon arrays parallel to the category merge (dedupe by name, respect per-entry locks). Categories the LLM emits include a `kind` so they land under the right trunk.
- **Phase C — Layout rewrite.** Tabbed top-level (Bible / Cast / Places / Objects / Other / Composites / Render) with URL state (`?tab=cast&bucket=heroes` per CLAUDE.md linkable-routes convention) — Bible is its own tab (not a sticky header). Per-trunk view = sub-bucket chip filter row + responsive card grid. Unify `CanonCard` + a new card for category variations into a single `EntryCard` component (renders thumbnail from `primaryImageRef` or most recent render). **Canon entries are first-class batch-render targets** alongside category variations and composite sheets: per-bucket actions are "Generate N more" + "Bulk-render this bucket"; per-trunk action is "Bulk-render all Cast/Places/Objects" (includes BOTH canon entries AND every variation in every sub-bucket under that trunk); the Batch Render tab itself offers per-trunk, per-bucket, and "All canon" selectors plus the existing composite-sheets mode. Composite reference images stay intact as their own render mode (no regression). Server-side: extend `compilePrompts` to accept canon entries as render sources (synthesize a prompt from `name + physicalDescription/palette/description`, layered with the universe style preset the same way variations are today). The **Other** tab only appears when un-kinded buckets exist, and shows the **Auto-sort with AI** action. Mobile: tabs collapse to a select dropdown.
- **Phase D — Polish & promotion.** "Promote variation to canon" action: take a `{label, prompt}` variation, expand it via LLM into a full canon entry (`name`, `physicalDescription`, etc.) and move it from the category bucket into the canon array. Tests for the new components. Extract design to `docs/features/universe-builder.md` if the doc warrants it.
+ - **Phase C follow-ups (deferred from the Phase C PR):**
+ - [ ] **Auto-sort with AI** — LLM-classify each `kind: 'other'` bucket into characters/settings/objects + suggest a meaningful name. New server route `POST /api/universe-builder/:id/auto-sort` that sends bucket keys + variation labels to the active LLM and applies the classification. Currently the Other-tab button is a stub that points users at re-running Generate From Idea (Phase B's expand emits kind tags). Land in a follow-up to keep the Phase C PR scoped.
+ - [ ] **Unify `CanonCard` + variation card into a single `EntryCard`.** Phase C reuses `CanonCard` for canon and `CategoryEditor` for variations inside the same TrunkView. Visual consistency is achieved through shared Tailwind classes; an actual single-component unification (with thumbnail-from-`primaryImageRef`-or-recent-render) is the Phase D card-extraction task.
+ - [ ] **Extract a shared `<TabPills>` primitive in `client/src/components/ui/`.** Phase C's `TabNav` in `UniverseBuilder.jsx` duplicates the pattern in `StoryboardPanel.jsx` `TabNav` + 5 inline tab-button pages (`Calendar.jsx`, `ChiefOfStaff.jsx`, `DigitalTwin.jsx`, `Messages.jsx`, etc.). One primitive that accepts `{ tabs: [{id,label,icon,count}], activeTab, onChange }` would consolidate. Cross-cutting refactor — defer until next time we touch tab UI somewhere.
+ - [ ] **Extract `descriptorForCanonEntry(kind, entry)` into `server/lib/canonPrompt.js` (mirror in client).** The new server-side `synthesizeCanonPrompt()` in `server/services/universeBuilder.js` duplicates the per-kind descriptor logic already present in `client/src/components/universe/UniverseCanonSection.jsx`'s `KINDS[].descFor` closures and overlaps with `server/lib/scenePrompt.js` (`settingFrags`). One helper would let canon-render synthesis, the canon UI summary, and scene-prompt framing all share the same field-precedence rules.
2. **Step-by-step approval/lock UX across Universe → Series → Arc → Seasons → Episodes.** Iteration 1 shipped a single arc-level lock; extend to per-season + per-field locks, lock the bulk runners, surface stage-progress strip, enforce locks server-side before LLM invocations.
3. **Sharing v2 contracts** — per-peer subscription filenames (`sub-<kind>-<recordId>-<senderInstanceId>.json`), tombstone-based item removals, "🔄 live" badge on inbox subscription rows.
4. **Pipeline continuity gaps** — plumb character physicalDescription/personality/background into idea-stage prompt; plumb setting `palette`/`era`/`weather`/`recurringDetails` into visual stages; add `worldEntitiesSummary` to text stages; add a dedicated `voice` / speech-pattern field to the bible schema.
diff --git a/client/src/components/universe/UniverseCanonSection.jsx b/client/src/components/universe/UniverseCanonSection.jsx
index b8b9d37a76..b5c66ad0bb 100644
--- a/client/src/components/universe/UniverseCanonSection.jsx
+++ b/client/src/components/universe/UniverseCanonSection.jsx
@@ -54,7 +54,7 @@ const KINDS = [
},
];
-export default function UniverseCanonSection({ universe, universeId, onUniverseChange, imageCfg }) {
+export default function UniverseCanonSection({ universe, universeId, onUniverseChange, imageCfg, kindFilter = null }) {
const mountedRef = useMounted();
const [searchParams, setSearchParams] = useSearchParams();
const seriesFilter = searchParams.get('series') || '';
@@ -359,11 +359,14 @@ export default function UniverseCanonSection({ universe, universeId, onUniverseC
<section id="canon" className="bg-port-card border border-port-border rounded p-4 flex flex-col gap-3 scroll-mt-4">
<div className="flex items-center justify-between gap-3 flex-wrap">
<div>
- <h2 className="text-sm font-semibold text-white">Canon</h2>
+ <h2 className="text-sm font-semibold text-white">
+ {kindFilter ? (KINDS.find((k) => k.key === kindFilter)?.label || 'Canon') : 'Canon'}
+ </h2>
<p className="text-xs text-gray-500 mt-0.5">
- People, places, and things that exist in this universe. Series in this
- universe share the same canon — episodes/issues reference these entries
- so a character renders consistently across crossovers.
+ {kindFilter === 'characters' && 'Recurring people in this universe. Series share the same canon — issues reference these entries so a character renders consistently across crossovers.'}
+ {kindFilter === 'settings' && 'Recurring places in this universe. Series share the same canon — slugline-anchored entries can be referenced across issues.'}
+ {kindFilter === 'objects' && 'Recurring objects/items in this universe. Series share the same canon — issues reference these entries for visual continuity.'}
+ {!kindFilter && 'People, places, and things that exist in this universe. Series in this universe share the same canon — episodes/issues reference these entries so a character renders consistently across crossovers.'}
</p>
</div>
<div className="flex items-center gap-2 flex-wrap">
@@ -391,16 +394,23 @@ export default function UniverseCanonSection({ universe, universeId, onUniverseC
>
<Library size={12} /> Extract from prose
</button>
- <button
- type="button"
- onClick={handleDifferentiate}
- disabled={differentiating || charCount < 2}
- title={charCount < 2 ? 'Need at least 2 characters to differentiate' : 'Rewrite every character so the cast renders visually distinct'}
- className="inline-flex items-center gap-1.5 px-2.5 py-1.5 rounded bg-port-accent/15 hover:bg-port-accent/25 text-port-accent border border-port-accent/40 text-xs disabled:opacity-40"
- >
- {differentiating ? <Loader2 size={12} className="animate-spin" /> : <Wand2 size={12} />}
- AI: differentiate cast
- </button>
+ {/* "AI: differentiate cast" is a character-only operation. When the
+ parent passes `kindFilter` to scope this section to settings or
+ objects, hide the action so it doesn't look applicable to the
+ current trunk. Keep it visible on the all-kinds view + on the
+ characters-filtered view. */}
+ {(!kindFilter || kindFilter === 'characters') ? (
+ <button
+ type="button"
+ onClick={handleDifferentiate}
+ disabled={differentiating || charCount < 2}
+ title={charCount < 2 ? 'Need at least 2 characters to differentiate' : 'Rewrite every character so the cast renders visually distinct'}
+ className="inline-flex items-center gap-1.5 px-2.5 py-1.5 rounded bg-port-accent/15 hover:bg-port-accent/25 text-port-accent border border-port-accent/40 text-xs disabled:opacity-40"
+ >
+ {differentiating ? <Loader2 size={12} className="animate-spin" /> : <Wand2 size={12} />}
+ AI: differentiate cast
+ </button>
+ ) : null}
</div>
</div>
@@ -447,7 +457,7 @@ export default function UniverseCanonSection({ universe, universeId, onUniverseC
</p>
) : null}
- {KINDS.map((kind) => (
+ {KINDS.filter((kind) => !kindFilter || kind.key === kindFilter).map((kind) => (
<KindSection
key={kind.key}
kind={kind}
diff --git a/client/src/pages/UniverseBuilder.jsx b/client/src/pages/UniverseBuilder.jsx
index f8138100c6..9a8d0bd305 100644
--- a/client/src/pages/UniverseBuilder.jsx
+++ b/client/src/pages/UniverseBuilder.jsx
@@ -7,12 +7,13 @@
* that all land in a single auto-named collection.
*/
-import { useEffect, useMemo, useRef, useState } from 'react';
-import { Link, useLocation, useNavigate, useParams } from 'react-router-dom';
+import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
+import { Link, useLocation, useNavigate, useParams, useSearchParams } from 'react-router-dom';
import {
Globe2, Plus, Trash2, Sparkles, Wand2, Loader2, Save, FolderOpen,
Edit3, X, MessageSquarePlus, Play, Lock, Unlock,
PanelLeftClose, PanelLeftOpen,
+ BookOpen, Users, MapPin, Package, Layers, ImagePlus, FolderTree,
} from 'lucide-react';
import toast from '../components/ui/Toast';
import {
@@ -21,7 +22,6 @@ import {
renderWorld, listWorldRuns, getProviders, refineWorldPrompts, WORLD_CATEGORIES,
WORLD_CATEGORY_KEY_MAX, COMPOSITE_PROMPT_MAX, WORLD_LOGLINE_MAX,
WORLD_PREMISE_MAX, WORLD_STYLE_NOTES_MAX, WORLD_LOCKABLE_FIELDS,
- WORLD_INFLUENCE_ENTRY_MAX, WORLD_INFLUENCES_PER_LIST_MAX,
ensureInfluences, isInfluenceLockField, mergeInfluencesWithLocks,
listImageModels, getSettings,
} from '../services/api';
@@ -44,6 +44,42 @@ const CATEGORY_LABELS = {
vehicles: 'Vehicles',
};
+// Tab order in the Universe Builder. Bible / Composites / Render are always
+// visible; the three canon trunks (Cast / Places / Objects) render even when
+// empty so the user has a discoverable target for canon+variation work; Other
+// only renders when at least one un-kinded bucket exists.
+const TAB_BIBLE = 'bible';
+const TAB_CAST = 'cast';
+const TAB_PLACES = 'places';
+const TAB_OBJECTS = 'objects';
+const TAB_OTHER = 'other';
+const TAB_COMPOSITES = 'composites';
+const TAB_RENDER = 'render';
+// Pseudo-bucket key for the canon-only view inside a trunk. Overloads
+// `?bucket=` (alongside real bucket keys) AND a `promptMode` value on the
+// render route; same string in both contexts to keep the contract consistent.
+const BUCKET_CANON = 'canon';
+// `kind` doubles as the canon-array key on the universe (`draft[kind]`) and
+// the canon-trunk identifier the server's `canonSelection` schema accepts.
+const TRUNK_TABS = [
+ { id: TAB_CAST, kind: 'characters', label: 'Cast', icon: Users },
+ { id: TAB_PLACES, kind: 'settings', label: 'Places', icon: MapPin },
+ { id: TAB_OBJECTS, kind: 'objects', label: 'Objects', icon: Package },
+];
+const TRUNK_BY_ID = Object.fromEntries(TRUNK_TABS.map((t) => [t.id, t]));
+
+// Group category buckets by their `kind` tag. Buckets with an unknown / missing
+// kind fall into the `other` bin — that bin drives whether the Other tab shows.
+const groupBucketsByKind = (categories = {}) => {
+ const out = { characters: [], settings: [], objects: [], other: [] };
+ for (const [key, bucket] of Object.entries(categories || {})) {
+ const kind = bucket?.kind || 'other';
+ if (out[kind]) out[kind].push(key);
+ else out.other.push(key);
+ }
+ return out;
+};
+
const normalizeCategoryKey = (raw) => (raw || '')
.trim()
.toLowerCase()
@@ -302,7 +338,15 @@ export default function UniverseBuilder() {
const location = useLocation();
const selectedId = params.universeId || null;
const basePath = location.pathname.replace(/\/universe-builder(?:\/.*)?$/, '/universe-builder');
- const goToWorld = (id) => navigate(id ? `${basePath}/${encodeURIComponent(id)}` : basePath);
+ // Preserve the `?tab=&bucket=` (and `?series=`) query string so the
+ // auto-save → create path doesn't snap the user back to the Bible tab
+ // after they triggered Generate From Idea from inside Cast/Places/Objects.
+ // The stale-bucket effect already strips any bucket that no longer exists
+ // under the new universe's categories.
+ const goToWorld = (id) => navigate({
+ pathname: id ? `${basePath}/${encodeURIComponent(id)}` : basePath,
+ search: location.search,
+ });
const [universes, setWorlds] = useState([]);
const [loading, setLoading] = useState(true);
@@ -953,7 +997,8 @@ export default function UniverseBuilder() {
// Render either the full batch (driven by the renderOpts.promptMode dropdown)
// or a narrow scope passed in by an inline button. Scope shape:
- // { promptMode, selection?, sheetSelection? } — see server renderSchema.
+ // { promptMode, selection?, sheetSelection?, canonSelection? } — see
+ // server renderSchema.
const runRender = async (scope = null) => {
if (!selectedId) {
toast.error('Save the world first');
@@ -977,6 +1022,18 @@ export default function UniverseBuilder() {
const n = Number(v);
return Number.isFinite(n) ? n : undefined;
};
+ // Server contract: `compilePrompts` in canon/all modes only emits canon
+ // prompts when `canonSelection` is non-null (missing key skips the trunk
+ // entirely). When the user picks "canon" or "all" in the Render tab and
+ // clicks the bare "Render N images" button (no scope), the UI count
+ // already includes canon — so default the payload to "every trunk → all"
+ // so the server actually compiles them. Scoped calls always pass their
+ // own canonSelection and bypass this default.
+ const needsCanonDefault = !scope && (promptMode === 'canon' || promptMode === 'all');
+ const effectiveCanonSelection = scope?.canonSelection
+ ?? (needsCanonDefault
+ ? { characters: 'all', settings: 'all', objects: 'all' }
+ : undefined);
setRendering(true);
const result = await renderWorld(selectedId, {
mode: effectiveMode,
@@ -991,6 +1048,7 @@ export default function UniverseBuilder() {
batchPerVariation: renderOpts.batchPerVariation,
selection: scope?.selection,
sheetSelection: scope?.sheetSelection,
+ canonSelection: effectiveCanonSelection,
}).catch((e) => { toast.error(`Render failed: ${e.message}`); return null; });
setRendering(false);
if (!result) return;
@@ -999,7 +1057,9 @@ export default function UniverseBuilder() {
setRuns(updated);
};
- const handleRender = () => runRender(null);
+ // RenderTab and per-trunk Bulk-render buttons pass a scope object; the
+ // bare "Render N images" button passes nothing (= use the renderOpts).
+ const handleRender = (scope = null) => runRender(scope);
const canRender = !!selectedId && availableBackends.length > 0 && !rendering;
@@ -1141,7 +1201,85 @@ export default function UniverseBuilder() {
const categoryKeys = getCategoryKeys(draft.categories);
const totalVariations = totalVariationCount(draft);
const totalSheets = draft.compositeSheets?.length || 0;
- const renderTotal = renderPromptCount(draft, renderOpts.promptMode);
+
+ // URL-driven tab + bucket state (per CLAUDE.md "Linkable routes for all
+ // views"). `?tab=cast&bucket=heroes` deep-links into a sub-bucket; both fall
+ // back to bible / "" (All) on first load. We also forward existing params
+ // (e.g. `?series=` on the embedded Canon section) untouched.
+ const [searchParams, setSearchParams] = useSearchParams();
+ const bucketsByKind = useMemo(() => groupBucketsByKind(draft.categories), [draft.categories]);
+ const hasOtherBuckets = bucketsByKind.other.length > 0;
+ const requestedTab = searchParams.get('tab');
+ const isValidTab = (tab) => (
+ tab === TAB_BIBLE || tab === TAB_CAST || tab === TAB_PLACES || tab === TAB_OBJECTS
+ || tab === TAB_COMPOSITES || tab === TAB_RENDER
+ || (tab === TAB_OTHER && hasOtherBuckets)
+ );
+ const activeTab = isValidTab(requestedTab) ? requestedTab : TAB_BIBLE;
+ const activeBucket = searchParams.get('bucket') || '';
+ const setTab = useCallback((tab, opts = {}) => {
+ const currentTab = searchParams.get('tab') || TAB_BIBLE;
+ const isSameTab = tab === currentTab;
+ const next = new URLSearchParams(searchParams);
+ if (tab === TAB_BIBLE) next.delete('tab');
+ else next.set('tab', tab);
+ // Bucket behavior:
+ // - explicit `opts.bucket` value (string) → set
+ // - explicit `opts.bucket: null` → clear (callers that want to drop the
+ // filter on the same tab pass null intentionally)
+ // - omitted + same tab → preserve current bucket (re-clicking the
+ // active tab shouldn't drop the user's chip/canon filter)
+ // - omitted + tab transition → clear (the old bucket is meaningless on
+ // the new tab's bucket namespace)
+ if (opts.bucket === null) next.delete('bucket');
+ else if (opts.bucket) next.set('bucket', opts.bucket);
+ else if (!isSameTab) next.delete('bucket');
+ setSearchParams(next, { replace: !!opts.replace });
+ }, [searchParams, setSearchParams]);
+ // Explicit user bucket clicks push a history entry so back/forward actually
+ // walks tab+bucket navigation (the PR's headline deep-link promise). The
+ // stale-bucket-cleanup effect below uses `replace: true` directly so an
+ // implicit URL fix-up doesn't fork the history stack.
+ const setBucket = useCallback((bucket, opts = {}) => {
+ const next = new URLSearchParams(searchParams);
+ if (bucket) next.set('bucket', bucket);
+ else next.delete('bucket');
+ setSearchParams(next, { replace: !!opts.replace });
+ }, [searchParams, setSearchParams]);
+
+ // Drop a stale `?tab=` if it points to an unknown value or `tab=other`
+ // when the user has emptied the Other bucket bin. Without this, the URL
+ // and UI disagree: `activeTab` silently falls back to Bible but the param
+ // stays in the address bar — breaking the deep-link promise and confusing
+ // back/forward.
+ useEffect(() => {
+ if (!requestedTab) return;
+ if (isValidTab(requestedTab)) return;
+ const next = new URLSearchParams(searchParams);
+ next.delete('tab');
+ setSearchParams(next, { replace: true });
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [requestedTab, hasOtherBuckets]);
+
+ // Drop a stale `?bucket=` if the bucket no longer exists under the current
+ // tab (e.g. user deleted the bucket, or auto-sort moved it to another kind).
+ // `BUCKET_CANON` is a valid pseudo-bucket on every trunk tab — without an
+ // explicit allow, the chip's `setBucket(BUCKET_CANON)` flashed in the URL
+ // then immediately got stripped by this effect, hiding the canon-only view.
+ // Other tab buckets must validate against `bucketsByKind.other`; non-trunk
+ // non-Other tabs (Bible / Composites / Render) have no valid bucket scope.
+ useEffect(() => {
+ if (!activeBucket) return;
+ const trunk = TRUNK_BY_ID[activeTab];
+ if (trunk && activeBucket === BUCKET_CANON) return;
+ const validBuckets = trunk
+ ? (bucketsByKind[trunk.kind] || [])
+ : (activeTab === TAB_OTHER ? bucketsByKind.other : []);
+ if (validBuckets.includes(activeBucket)) return;
+ const next = new URLSearchParams(searchParams);
+ next.delete('bucket');
+ setSearchParams(next, { replace: true });
+ }, [activeTab, activeBucket, bucketsByKind, searchParams, setSearchParams]);
// Mobile = flex column (grid template ignored); lg+ = grid where the inline
// `gridTemplateColumns` swap between collapsed/expanded widths takes effect.
@@ -1230,263 +1368,152 @@ export default function UniverseBuilder() {
{/* Editor — owns its own scroll inside the full-width main so the
sidebar can stay pinned while the long card stack scrolls. */}
- <section className="flex flex-col gap-4 p-4 min-h-0 lg:overflow-y-auto">
- <header className="bg-port-card border border-port-border rounded p-4 flex flex-col gap-3">
- <div className="flex items-center gap-2 flex-wrap">
- <input
- type="text"
- value={draft.name}
- onChange={(e) => updateDraft({ name: e.target.value })}
- placeholder="World name (e.g. Moebius / Scavenger sci-fi)"
- className="flex-1 min-w-[180px] bg-port-bg border border-port-border rounded px-3 py-2 text-white focus:outline-none focus:border-port-accent"
- maxLength={100}
- />
- <button
- onClick={handleSave}
- disabled={saving || !draft.name?.trim()}
- className="px-3 py-2 bg-port-accent hover:bg-port-accent/90 disabled:opacity-50 text-white rounded flex items-center gap-2 min-h-[40px]"
- >
- {saving ? <Loader2 size={16} className="animate-spin" /> : <Save size={16} />}
- {selectedId ? 'Save' : 'Create'}
- </button>
- {selectedId && (
- <>
- <ShareToButton kind="universe" ids={[selectedId]} label="Share" />
- {draft.origin ? <OriginBadge origin={draft.origin} /> : null}
- <button
- onClick={handleDelete}
- className={`px-3 py-2 rounded flex items-center gap-2 min-h-[40px] ${
- pendingDeleteId === selectedId
- ? 'bg-red-700 hover:bg-red-600 text-white'
- : 'bg-red-900/30 hover:bg-red-900/50 text-red-300'
- }`}
- title="Delete world"
- >
- <Trash2 size={16} /> {pendingDeleteId === selectedId ? 'Confirm delete' : 'Delete'}
- </button>
- </>
- )}
- </div>
-
- {/* Starter prompt + LLM picker */}
- <div className="grid grid-cols-1 md:grid-cols-[1fr_220px] gap-3">
- <div>
- <FieldLabel field="starterPrompt" locked={draft.locked} onToggleLock={toggleLock}>
- Starter idea
- </FieldLabel>
- <textarea
- value={draft.starterPrompt}
- onChange={(e) => updateDraft({ starterPrompt: e.target.value })}
- placeholder="moebius and scavengers reign meets Prophet inspired sci fi universe"
- className="w-full bg-port-bg border border-port-border rounded px-3 py-2 text-white text-sm focus:outline-none focus:border-port-accent"
- rows={2}
- maxLength={4000}
- />
- </div>
- <div>
- <label htmlFor="world-llm-provider" className="text-xs text-gray-400 mb-1 block">LLM for expansion</label>
- <select
- id="world-llm-provider"
- // Bind to `?? ''` (NOT `|| activeProviderId || ''`) — when
- // provider is null/unset, the empty value should select the
- // "Active provider" option, not silently switch the dropdown
- // to the active provider's explicit option (which would
- // misrepresent saved state as a pinned provider).
- value={draft.llm?.provider ?? ''}
- onChange={(e) => updateDraft({ llm: { ...draft.llm, provider: e.target.value || null, model: null } })}
- className="w-full bg-port-bg border border-port-border rounded px-2 py-2 text-white text-sm min-h-[40px]"
- >
- <option value="">Active provider ({providerLabel(activeProviderId)})</option>
- {providers.map((p) => (
- <option key={p.id} value={p.id}>{p.name}</option>
- ))}
- </select>
- <select
- value={draft.llm?.model || ''}
- onChange={(e) => updateDraft({ llm: { ...draft.llm, model: e.target.value || null } })}
- className="mt-1 w-full bg-port-bg border border-port-border rounded px-2 py-2 text-white text-sm min-h-[40px]"
+ <section className="flex flex-col gap-3 p-4 min-h-0 lg:overflow-y-auto">
+ {/* Thin action header — name + Save + Share + Delete sit above the
+ tab nav so they're reachable from any tab. The Bible-tab actions
+ (Generate / Refine, starter idea, story-bible fields) live inside
+ the Bible tab itself, per Phase C "Bible is its own tab". */}
+ <header className="bg-port-card border border-port-border rounded p-3 flex items-center gap-2 flex-wrap">
+ <input
+ type="text"
+ value={draft.name}
+ onChange={(e) => updateDraft({ name: e.target.value })}
+ placeholder="World name (e.g. Moebius / Scavenger sci-fi)"
+ className="flex-1 min-w-[180px] bg-port-bg border border-port-border rounded px-3 py-2 text-white focus:outline-none focus:border-port-accent"
+ maxLength={100}
+ />
+ <button
+ onClick={handleSave}
+ disabled={saving || !draft.name?.trim()}
+ className="px-3 py-2 bg-port-accent hover:bg-port-accent/90 disabled:opacity-50 text-white rounded flex items-center gap-2 min-h-[40px]"
+ >
+ {saving ? <Loader2 size={16} className="animate-spin" /> : <Save size={16} />}
+ {selectedId ? 'Save' : 'Create'}
+ </button>
+ {selectedId && (
+ <>
+ <ShareToButton kind="universe" ids={[selectedId]} label="Share" />
+ {draft.origin ? <OriginBadge origin={draft.origin} /> : null}
+ <button
+ onClick={handleDelete}
+ className={`px-3 py-2 rounded flex items-center gap-2 min-h-[40px] ${
+ pendingDeleteId === selectedId
+ ? 'bg-red-700 hover:bg-red-600 text-white'
+ : 'bg-red-900/30 hover:bg-red-900/50 text-red-300'
+ }`}
+ title="Delete world"
>
- <option value="">Default model</option>
- {providerModels.map((m) => {
- const id = typeof m === 'string' ? m : m.id;
- const label = typeof m === 'string' ? m : (m.name || m.id);
- return <option key={id} value={id}>{label}</option>;
- })}
- </select>
- </div>
- </div>
-
- <div className="flex items-center gap-2 flex-wrap">
- <button
- onClick={handleExpand}
- disabled={expanding || saving || !draft.starterPrompt?.trim()}
- className="px-3 py-2 bg-purple-600/30 hover:bg-purple-600/50 disabled:opacity-50 text-purple-200 border border-purple-600/40 rounded flex items-center gap-2 min-h-[40px]"
- >
- {expanding ? <Loader2 size={16} className="animate-spin" /> : <Wand2 size={16} />}
- Generate From Idea
- </button>
- <button
- onClick={() => setRefineOpen((v) => !v)}
- disabled={!draft.starterPrompt?.trim()}
- aria-expanded={refineOpen}
- className={`px-3 py-2 disabled:opacity-50 text-port-accent border border-port-accent/40 rounded flex items-center gap-2 min-h-[40px] ${
- refineOpen ? 'bg-port-accent/25' : 'bg-port-accent/15 hover:bg-port-accent/25'
- }`}
- title="Give feedback to refine the prompts in place — uses the LLM picked above"
- >
- <MessageSquarePlus size={16} />
- Refine prompts
- </button>
- <span className="text-xs text-gray-500">
- {totalVariations} variation{totalVariations === 1 ? '' : 's'} across {categoryKeys.length} categories · {totalSheets} composite board{totalSheets === 1 ? '' : 's'}
- </span>
- </div>
-
- {refineOpen && (
- <div className="border border-port-accent/40 bg-port-accent/5 rounded p-3 flex flex-col gap-2">
- <label htmlFor="world-refine-feedback" className="text-[11px] uppercase tracking-wide text-gray-500">
- Feedback — describe what you want changed
- </label>
- <textarea
- id="world-refine-feedback"
- value={refineFeedback}
- onChange={(e) => setRefineFeedback(e.target.value)}
- placeholder="e.g. lean grimmer and more spiritual; pull style toward Moebius + Tarkovsky; avoid neon and cyberpunk clichés."
- rows={3}
- disabled={refining}
- className="w-full bg-port-bg border border-port-border rounded p-2 text-sm text-white placeholder-gray-500 focus:outline-none focus:border-port-accent resize-y disabled:opacity-60"
- />
- <div className="flex items-center gap-2 flex-wrap">
- <button
- type="button"
- onClick={runRefine}
- disabled={refining || !refineFeedback.trim() || !draft.starterPrompt?.trim()}
- className="px-3 py-2 bg-port-accent hover:bg-port-accent/90 disabled:opacity-50 disabled:cursor-not-allowed text-white rounded flex items-center gap-2 min-h-[40px]"
- >
- {refining ? <Loader2 size={14} className="animate-spin" /> : <Wand2 size={14} />}
- {refining ? 'Refining…' : 'Refine'}
- </button>
- <button
- type="button"
- onClick={resetRefinePanel}
- disabled={refining}
- className="px-3 py-2 text-sm text-gray-400 hover:text-white rounded min-h-[40px]"
- >
- Close
- </button>
- <span className="text-[11px] text-gray-500">
- Applies in place — locked fields stay pinned.
- </span>
- </div>
- {(refineRationale || refineChanges.length > 0) && (
- <div className="border-t border-port-border/60 pt-2 mt-1 space-y-1.5">
- {refineRationale && (
- <p className="text-xs text-gray-300 whitespace-pre-wrap">{refineRationale}</p>
- )}
- {refineChanges.length > 0 && (
- <ul className="text-[11px] text-gray-400 list-disc pl-5 space-y-0.5">
- {refineChanges.map((c, idx) => (
- <li key={idx}>{c}</li>
- ))}
- </ul>
- )}
- </div>
- )}
- </div>
+ <Trash2 size={16} /> {pendingDeleteId === selectedId ? 'Confirm delete' : 'Delete'}
+ </button>
+ </>
)}
</header>
- <section className="bg-port-card border border-port-border rounded p-4 flex flex-col gap-3">
- <div>
- <h2 className="text-sm font-semibold text-white">Story bible</h2>
- <p className="text-xs text-gray-500 mt-0.5">
- Pulled into the Pipeline → New Series form when this world is selected.
- </p>
- </div>
- <div>
- <FieldLabel htmlFor="world-logline" field="logline" locked={draft.locked} onToggleLock={toggleLock}>
- Logline
- </FieldLabel>
- <input
- id="world-logline"
- type="text"
- value={draft.logline || ''}
- onChange={(e) => updateDraft({ logline: e.target.value })}
- placeholder="One-sentence hook — A foundry city goes silent, and the only survivor is a child."
- className="w-full bg-port-bg border border-port-border rounded px-3 py-2 text-white text-sm focus:outline-none focus:border-port-accent"
- maxLength={WORLD_LOGLINE_MAX}
- />
- </div>
- <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
- <div>
- <FieldLabel htmlFor="world-premise" field="premise" locked={draft.locked} onToggleLock={toggleLock}>
- Premise
- </FieldLabel>
- <textarea
- id="world-premise"
- value={draft.premise || ''}
- onChange={(e) => updateDraft({ premise: e.target.value })}
- placeholder="Elevator pitch — 1-3 short paragraphs about the setting, central conflict, stakes, and tone."
- className="w-full bg-port-bg border border-port-border rounded px-3 py-2 text-white text-sm focus:outline-none focus:border-port-accent"
- rows={6}
- maxLength={WORLD_PREMISE_MAX}
- />
- </div>
- <div>
- <FieldLabel htmlFor="world-style-notes" field="styleNotes" locked={draft.locked} onToggleLock={toggleLock}>
- Style notes
- </FieldLabel>
- <textarea
- id="world-style-notes"
- value={draft.styleNotes || ''}
- onChange={(e) => updateDraft({ styleNotes: e.target.value })}
- placeholder="Narrative style: references (artists / films / comics), mood, palette, pacing, voice. Prose, not tokens."
- className="w-full bg-port-bg border border-port-border rounded px-3 py-2 text-white text-sm focus:outline-none focus:border-port-accent"
- rows={6}
- maxLength={WORLD_STYLE_NOTES_MAX}
- />
- </div>
- </div>
- <StyleNegativePromptEditor
- influences={draft.influences}
- onChange={(next) => updateDraft({ influences: next })}
- locked={draft.locked}
- onToggleLock={toggleLock}
- />
- </section>
+ <TabNav
+ activeTab={activeTab}
+ setTab={setTab}
+ hasOtherBuckets={hasOtherBuckets}
+ counts={{
+ cast: (draft.characters?.length || 0) + bucketsByKind.characters.reduce((n, k) => n + (draft.categories?.[k]?.variations?.length || 0), 0),
+ places: (draft.settings?.length || 0) + bucketsByKind.settings.reduce((n, k) => n + (draft.categories?.[k]?.variations?.length || 0), 0),
+ objects: (draft.objects?.length || 0) + bucketsByKind.objects.reduce((n, k) => n + (draft.categories?.[k]?.variations?.length || 0), 0),
+ other: bucketsByKind.other.reduce((n, k) => n + (draft.categories?.[k]?.variations?.length || 0), 0),
+ composites: totalSheets,
+ }}
+ />
- {/*
- Gate on `draft.id === selectedId` — when the user switches universes,
- `selectedId` updates synchronously but the new `draft` arrives after
- an async `getUniverse(selectedId)` resolves. During that window, an
- optimistic canon mutation routed through `onUniverseChange` would
- send the *previous* universe's canon arrays to
- `updateUniverse(selectedId, ...)`, wholesale-overwriting the newly
- selected universe's canon on the server.
- */}
- {selectedId && draft.id === selectedId ? (
- <UniverseCanonSection
- universe={draft}
- universeId={selectedId}
- onUniverseChange={handleCanonChange}
- imageCfg={imageCfg}
+ {activeTab === TAB_BIBLE && (
+ <BibleTab
+ draft={draft}
+ updateDraft={updateDraft}
+ toggleLock={toggleLock}
+ llm={{ providers, providerModels, providerLabel, activeProviderId }}
+ handleExpand={handleExpand}
+ expanding={expanding}
+ saving={saving}
+ refine={{
+ open: refineOpen, setOpen: setRefineOpen,
+ feedback: refineFeedback, setFeedback: setRefineFeedback,
+ run: runRefine, running: refining, reset: resetRefinePanel,
+ rationale: refineRationale, changes: refineChanges,
+ }}
+ totalVariations={totalVariations}
+ categoryKeyCount={categoryKeys.length}
+ totalSheets={totalSheets}
/>
- ) : null}
+ )}
- <CompositeSheetsEditor
- sheets={draft.compositeSheets || []}
- onChange={updateCompositeSheets}
- canRender={canRender}
- onRender={(sheet) => runRender({ promptMode: 'sheets', sheetSelection: [sheet.label] })}
- />
+ {TRUNK_TABS.map((trunk) => (
+ activeTab === trunk.id ? (
+ <TrunkView
+ key={trunk.id}
+ trunk={trunk}
+ draft={draft}
+ selectedId={selectedId}
+ buckets={bucketsByKind[trunk.kind] || []}
+ activeBucket={activeBucket}
+ setBucket={setBucket}
+ canRender={canRender}
+ imageCfg={imageCfg}
+ onUniverseChange={handleCanonChange}
+ onRemoveBucket={removeCategory}
+ onUpdateBucket={updateCategory}
+ onGenerateInBucket={handleGenerateInCategory}
+ onBulkRenderBucket={(bucket) => runRender({ promptMode: 'variations', selection: { [bucket]: 'all' } })}
+ onRenderVariation={(bucket, v) => runRender({ promptMode: 'variations', selection: { [bucket]: [v.label] } })}
+ onBulkRenderTrunk={() => {
+ const selection = Object.fromEntries(
+ (bucketsByKind[trunk.kind] || []).map((b) => [b, 'all']),
+ );
+ const canonSelection = { [trunk.kind]: 'all' };
+ // Empty sheetSelection opts out of composite sheets — without
+ // it, the server's `sheetSelection || 'all'` default would
+ // queue every sheet alongside the trunk's canon + variations,
+ // overshooting the user-facing "N images" count.
+ runRender({ promptMode: 'all', selection, canonSelection, sheetSelection: [] });
+ }}
+ onAddBucket={({ key }) => {
+ setDraft((d) => ({
+ ...d,
+ categories: { ...d.categories, [key]: { kind: trunk.kind, variations: [] } },
+ }));
+ }}
+ />
+ ) : null
+ ))}
+
+ {activeTab === TAB_OTHER && hasOtherBuckets && (
+ <OtherTab
+ draft={draft}
+ buckets={bucketsByKind.other}
+ activeBucket={activeBucket}
+ setBucket={setBucket}
+ canRender={canRender}
+ onUpdateBucket={updateCategory}
+ onRemoveBucket={removeCategory}
+ onGenerateInBucket={handleGenerateInCategory}
+ onBulkRenderBucket={(bucket) => runRender({ promptMode: 'variations', selection: { [bucket]: 'all' } })}
+ onRenderVariation={(bucket, v) => runRender({ promptMode: 'variations', selection: { [bucket]: [v.label] } })}
+ onAutoSort={() => {
+ toast('Auto-sort with AI is wired in a follow-up. Re-run "Generate From Idea" — Phase B\'s expand call now classifies buckets into the right trunk.', { icon: 'ℹ️' });
+ }}
+ />
+ )}
- {/* Categories */}
- <section className="bg-port-card border border-port-border rounded p-4 flex flex-col gap-3">
- <div className="flex items-end justify-between gap-3 flex-wrap">
- <div>
- <h2 className="text-sm font-semibold text-white">Prompt categories</h2>
- </div>
- <div className="flex items-center gap-2">
+ {activeTab === TAB_COMPOSITES && (
+ <>
+ <CompositeSheetsEditor
+ sheets={draft.compositeSheets || []}
+ onChange={updateCompositeSheets}
+ canRender={canRender}
+ onRender={(sheet) => runRender({ promptMode: 'sheets', sheetSelection: [sheet.label] })}
+ />
+ {/* Add-bucket row stays available here for power users who want to
+ introduce a brand-new custom bucket without going through
+ expand. New buckets default to kind='other' so they land under
+ the Other tab. */}
+ <section className="bg-port-card border border-port-border rounded p-3 flex items-center gap-2 flex-wrap">
+ <span className="text-xs text-gray-400 mr-1">Add a custom sub-bucket (lands under Other):</span>
<input
type="text"
value={newCategoryName}
@@ -1503,131 +1530,24 @@ export default function UniverseBuilder() {
>
<Plus size={14} /> Add
</button>
- </div>
- </div>
- </section>
- <section className="grid grid-cols-1 md:grid-cols-2 gap-3">
- {categoryKeys.map((cat) => (
- <CategoryEditor
- key={cat}
- category={cat}
- variations={draft.categories?.[cat]?.variations || []}
- canRemove={!WORLD_CATEGORIES.includes(cat)}
- onChange={(next) => updateCategory(cat, next)}
- onRemove={() => removeCategory(cat)}
- canRender={canRender}
- onRenderCategory={() => runRender({ promptMode: 'variations', selection: { [cat]: 'all' } })}
- onRenderVariation={(v) => runRender({ promptMode: 'variations', selection: { [cat]: [v.label] } })}
- onGenerate={(count) => handleGenerateInCategory(cat, count)}
- />
- ))}
- </section>
+ </section>
+ </>
+ )}
- {/* Render controls — reuses Image Gen's backend chip + knob grid so
- the model picker, resolution presets, etc. stay in lockstep. */}
- <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 flex-wrap">
- <h2 className="text-sm font-semibold text-white flex items-center gap-2">
- <FolderOpen size={16} className="text-port-accent" /> Batch render
- </h2>
- {availableBackends.length > 1 && (
- <BackendChipStrip
- availableBackends={availableBackends}
- value={renderOpts.mode || defaultMode}
- onChange={(id) => setRenderOpts((r) => ({ ...r, mode: id }))}
- titlePrefix="Render via"
- />
- )}
- </div>
- {availableBackends.length === 0 && (
- <p className="text-xs text-port-warning">
- Configure a local mflux Python path or enable Codex Imagegen in Settings → Image Gen
- to enable batch render.
- </p>
- )}
- <div className="grid grid-cols-1 sm:grid-cols-3 gap-3">
- <div>
- <label htmlFor="world-render-prompt-mode" className="block text-xs font-medium text-gray-400 mb-1">Prompt set</label>
- <select
- id="world-render-prompt-mode"
- value={renderOpts.promptMode || 'variations'}
- onChange={(e) => setRenderOpts((r) => ({ ...r, promptMode: e.target.value }))}
- className="w-full bg-port-bg border border-port-border rounded-lg px-2 py-2 text-sm text-white focus:outline-none focus:border-port-accent min-h-[40px]"
- >
- <option value="sheets" disabled={totalSheets === 0}>Composite boards ({totalSheets})</option>
- <option value="variations" disabled={totalVariations === 0}>Atomic variations ({totalVariations})</option>
- <option value="all" disabled={totalSheets + totalVariations === 0}>Everything ({totalSheets + totalVariations})</option>
- </select>
- </div>
- </div>
- <ImageGenControls
- mode={renderOpts.mode || defaultMode || 'local'}
- models={imageModels}
- modelId={renderOpts.modelId}
- onModelChange={(id) => setRenderOpts((r) => ({ ...r, modelId: id, steps: '', guidance: '' }))}
- width={renderOpts.width}
- height={renderOpts.height}
- onResolutionChange={(w, h) => setRenderOpts((r) => ({ ...r, width: w, height: h }))}
- steps={renderOpts.steps}
- onStepsChange={(v) => setRenderOpts((r) => ({ ...r, steps: v }))}
- guidance={renderOpts.guidance}
- onGuidanceChange={(v) => setRenderOpts((r) => ({ ...r, guidance: v }))}
- cfgScale={renderOpts.cfgScale}
- onCfgScaleChange={(v) => setRenderOpts((r) => ({ ...r, cfgScale: v }))}
- quantize={renderOpts.quantize}
- onQuantizeChange={(v) => setRenderOpts((r) => ({ ...r, quantize: v }))}
+ {activeTab === TAB_RENDER && (
+ <RenderTab
+ draft={draft}
+ selectedId={selectedId}
+ bucketsByKind={bucketsByKind}
+ renderOpts={renderOpts}
+ setRenderOpts={setRenderOpts}
+ availableBackends={availableBackends}
+ defaultMode={defaultMode}
+ imageModels={imageModels}
+ handleRender={handleRender}
+ rendering={rendering}
+ runs={runs}
/>
- <div className="grid grid-cols-2 sm:grid-cols-3 gap-3">
- <div>
- <label htmlFor="world-render-batch" className="block text-xs font-medium text-gray-400 mb-1">Renders per prompt</label>
- <input
- id="world-render-batch"
- type="number" min={1} max={20}
- value={renderOpts.batchPerVariation ?? 1}
- onChange={(e) => {
- const n = Number(e.target.value);
- setRenderOpts((r) => ({ ...r, batchPerVariation: Number.isFinite(n) && n > 0 ? n : 1 }));
- }}
- className="w-full bg-port-bg border border-port-border rounded-lg px-2 py-2 text-sm text-white focus:outline-none focus:border-port-accent"
- />
- </div>
- </div>
- <div className="flex items-center gap-2 flex-wrap">
- <button
- onClick={handleRender}
- disabled={rendering || !selectedId || renderTotal === 0 || availableBackends.length === 0}
- className="px-4 py-2 bg-port-accent hover:bg-port-accent/90 disabled:opacity-50 text-white rounded flex items-center gap-2 min-h-[40px]"
- >
- {rendering ? <Loader2 size={16} className="animate-spin" /> : <Sparkles size={16} />}
- Render {renderTotal * (renderOpts.batchPerVariation || 1)} image{renderTotal * (renderOpts.batchPerVariation || 1) === 1 ? '' : 's'}
- </button>
- </div>
- {!selectedId && <p className="text-xs text-gray-500">Save the world first to enable rendering.</p>}
- </section>
-
- {/* Run history */}
- {selectedId && runs.length > 0 && (
- <section className="bg-port-card border border-port-border rounded p-4">
- <h2 className="text-sm font-semibold text-white mb-2">Recent runs</h2>
- <ul className="flex flex-col gap-1">
- {runs.map((r) => (
- <li key={r.id} className="flex items-center justify-between text-sm text-gray-300 border-b border-port-border/40 py-1.5">
- <span className="truncate">
- <span className="text-gray-500">{new Date(r.createdAt).toLocaleString()} —</span>{' '}
- {r.promptCount} prompt{r.promptCount === 1 ? '' : 's'}
- </span>
- {r.collectionId && (
- <Link
- to={`/media/collections/${r.collectionId}`}
- className="text-xs text-port-accent hover:underline whitespace-nowrap"
- >
- Open collection →
- </Link>
- )}
- </li>
- ))}
- </ul>
- </section>
)}
</section>
</div>
@@ -1639,32 +1559,129 @@ function totalVariationCount(world) {
return getCategoryKeys(world.categories).reduce((n, c) => n + (world.categories?.[c]?.variations?.length || 0), 0);
}
+// Match server-side `synthesizeCanonPrompt` (server/services/universeBuilder.js)
+// per-kind: entries with no identity-anchor (name / slugline / hand-authored
+// prompt) AND no descriptive content for that kind compile to an empty seed and
+// get skipped. Mirror the predicate here so the "Render N images" button count
+// doesn't overshoot what the server will actually enqueue.
+//
+// IMPORTANT: keep the per-kind field lists in sync with server's
+// `synthesizeCanonPrompt`. Drift between client/server here makes scoped render
+// counts and disabled states lie about what will actually be enqueued.
+// Server's `synthesizeCanonPrompt` trims each string field before pushing into
+// `parts` and then filters out empty results via `String(p).trim().filter(Boolean)`.
+// A whitespace-only field doesn't anchor renderability there — mirror that here
+// so client-side counts/disable states agree under optimistic edits.
+const hasNonBlankString = (v) => typeof v === 'string' && v.trim().length > 0;
+
+const canonEntryHasContent = (e, kind) => {
+ if (!e) return false;
+ if (hasNonBlankString(e.prompt)) return true;
+ // Identifier anchors per kind — settings allow slugline-only entries (bible
+ // sanitizer); characters/objects ignore stray slugline. Mirrors server
+ // synthesizeCanonPrompt's identifier-seed rule.
+ if (hasNonBlankString(e.name)) return true;
+ if (kind === 'settings' && hasNonBlankString(e.slugline)) return true;
+ if (kind === 'characters') {
+ return hasNonBlankString(e.physicalDescription) || hasNonBlankString(e.role);
+ }
+ if (kind === 'settings') {
+ return hasNonBlankString(e.description) || hasNonBlankString(e.palette)
+ || hasNonBlankString(e.era) || hasNonBlankString(e.weather)
+ || hasNonBlankString(e.recurringDetails);
+ }
+ if (kind === 'objects') {
+ return hasNonBlankString(e.description) || hasNonBlankString(e.significance);
+ }
+ // Unknown kind — fall back to the inclusive union so an unrecognized trunk
+ // doesn't silently collapse to 0.
+ return hasNonBlankString(e.physicalDescription) || hasNonBlankString(e.description)
+ || hasNonBlankString(e.palette) || hasNonBlankString(e.era) || hasNonBlankString(e.weather)
+ || hasNonBlankString(e.recurringDetails) || hasNonBlankString(e.role)
+ || hasNonBlankString(e.significance);
+};
+
+const countCanonWithContent = (world, kind) =>
+ (Array.isArray(world?.[kind]) ? world[kind] : []).filter((e) => canonEntryHasContent(e, kind)).length;
+
function renderPromptCount(world, promptMode = 'variations') {
const variations = totalVariationCount(world);
const sheets = world.compositeSheets?.length || 0;
+ const canon = countCanonWithContent(world, 'characters')
+ + countCanonWithContent(world, 'settings')
+ + countCanonWithContent(world, 'objects');
if (promptMode === 'sheets') return sheets;
- if (promptMode === 'all') return variations + sheets;
+ if (promptMode === 'canon') return canon;
+ if (promptMode === 'all') return variations + sheets + canon;
return variations;
}
-// Mirrors the server's compilePrompts for selection/sheetSelection so an inline
-// "Render" button can disable itself + show an accurate count without a round trip.
+// Mirrors the server's compilePrompts for selection/sheetSelection/canonSelection
+// so an inline "Render" button can disable itself + show an accurate count
+// without a round trip.
+//
+// Defaulting rules — mirror server/services/universeBuilder.js compilePrompts:
+// - sheets/all + no sheetSelection → render every sheet (server defaults to 'all')
+// - variations/all + no selection → render every category (server falls back
+// to a full category map via getWorldCategoryKeys)
+// - canon/all + no canonSelection → render NOTHING (server gates on a non-null
+// canonSelection; missing key skips the trunk entirely)
+// Canon entries are filtered through `canonEntryHasContent(kind)` since the
+// server skips entries whose synthesized seed is empty.
function scopedPromptCount(world, scope) {
if (!scope) return 0;
- if (scope.promptMode === 'sheets') {
+ const mode = scope.promptMode || 'variations';
+ let n = 0;
+ if (mode === 'sheets' || mode === 'all') {
const sheets = world.compositeSheets || [];
- if (scope.sheetSelection === 'all' || !scope.sheetSelection) return sheets.length;
- const set = new Set(scope.sheetSelection);
- return sheets.filter((s) => set.has(s.label)).length;
+ if (scope.sheetSelection === 'all' || scope.sheetSelection === undefined || scope.sheetSelection === null) {
+ // Both `sheets` and `all` default to every sheet when sheetSelection is
+ // omitted — server: `options.sheetSelection || 'all'`.
+ n += sheets.length;
+ } else if (Array.isArray(scope.sheetSelection)) {
+ const set = new Set(scope.sheetSelection.map((s) => s.toLowerCase()));
+ n += sheets.filter((s) => set.has((s.label || '').toLowerCase())).length;
+ }
}
- // variations
- if (!scope.selection) return 0;
- let n = 0;
- for (const [cat, pick] of Object.entries(scope.selection)) {
- const vars = world.categories?.[cat]?.variations || [];
- if (pick === 'all') { n += vars.length; continue; }
- const labels = new Set(pick);
- n += vars.filter((v) => labels.has(v.label)).length;
+ if (mode === 'variations' || mode === 'all') {
+ if (scope.selection) {
+ for (const [cat, pick] of Object.entries(scope.selection)) {
+ const vars = world.categories?.[cat]?.variations || [];
+ if (pick === 'all') n += vars.length;
+ else if (Array.isArray(pick)) {
+ const labels = new Set(pick.map((p) => p.toLowerCase()));
+ n += vars.filter((v) => labels.has((v.label || '').toLowerCase())).length;
+ }
+ }
+ } else {
+ // No selection ⇒ server treats this as "every category, all variations".
+ n += totalVariationCount(world);
+ }
+ }
+ if (mode === 'canon' || mode === 'all') {
+ if (scope.canonSelection) {
+ for (const trunk of ['characters', 'settings', 'objects']) {
+ const pick = scope.canonSelection[trunk];
+ if (!pick) continue;
+ const entries = Array.isArray(world[trunk]) ? world[trunk] : [];
+ const withContent = entries.filter((e) => canonEntryHasContent(e, trunk));
+ if (pick === 'all') n += withContent.length;
+ else if (Array.isArray(pick)) {
+ const needles = new Set(pick.map((p) => p.toLowerCase()));
+ // Mirror server: slugline matching is settings-only — name is the
+ // shared anchor for characters/objects.
+ n += withContent.filter((e) => {
+ const name = (e.name || '').toLowerCase();
+ if (needles.has(name)) return true;
+ if (trunk === 'settings') {
+ const slug = (e.slugline || '').toLowerCase();
+ if (needles.has(slug)) return true;
+ }
+ return false;
+ }).length;
+ }
+ }
+ }
}
return n;
}
@@ -2147,3 +2164,764 @@ function CategoryEditor({
</div>
);
}
+
+// Tab nav — desktop shows a horizontal pill row; mobile collapses to a
+// <select> dropdown (CLAUDE.md "Mobile responsive"). The Other tab only
+// renders when at least one un-kinded bucket exists, per Phase C spec.
+function TabNav({ activeTab, setTab, hasOtherBuckets, counts }) {
+ const tabs = [
+ { id: TAB_BIBLE, label: 'Bible', icon: BookOpen, count: null },
+ { id: TAB_CAST, label: 'Cast', icon: Users, count: counts.cast },
+ { id: TAB_PLACES, label: 'Places', icon: MapPin, count: counts.places },
+ { id: TAB_OBJECTS, label: 'Objects', icon: Package, count: counts.objects },
+ ...(hasOtherBuckets ? [{ id: TAB_OTHER, label: 'Other', icon: FolderTree, count: counts.other }] : []),
+ { id: TAB_COMPOSITES, label: 'Composites', icon: Layers, count: counts.composites },
+ { id: TAB_RENDER, label: 'Render', icon: ImagePlus, count: null },
+ ];
+ return (
+ <>
+ {/* Mobile dropdown */}
+ <div className="sm:hidden">
+ <label htmlFor="ub-tab-select" className="sr-only">Section</label>
+ <select
+ id="ub-tab-select"
+ value={activeTab}
+ onChange={(e) => setTab(e.target.value)}
+ className="w-full bg-port-card border border-port-border rounded px-3 py-2 text-white text-sm focus:outline-none focus:border-port-accent min-h-[40px]"
+ >
+ {tabs.map((t) => (
+ <option key={t.id} value={t.id}>
+ {t.label}{t.count != null ? ` (${t.count})` : ''}
+ </option>
+ ))}
+ </select>
+ </div>
+ {/* Desktop pill row */}
+ <div className="hidden sm:flex items-center gap-1 bg-port-card border border-port-border rounded p-1 overflow-x-auto" role="tablist">
+ {tabs.map((t) => {
+ const Icon = t.icon;
+ const active = t.id === activeTab;
+ return (
+ <button
+ key={t.id}
+ type="button"
+ role="tab"
+ aria-selected={active}
+ onClick={() => setTab(t.id)}
+ className={`flex items-center gap-1.5 px-3 py-1.5 rounded text-sm transition-colors whitespace-nowrap ${
+ active
+ ? 'bg-port-accent/20 text-port-accent border border-port-accent/40'
+ : 'text-gray-300 hover:bg-port-bg border border-transparent'
+ }`}
+ >
+ <Icon size={14} />
+ {t.label}
+ {t.count != null && (
+ <span className={`text-[10px] ${active ? 'text-port-accent/70' : 'text-gray-500'}`}>
+ {t.count}
+ </span>
+ )}
+ </button>
+ );
+ })}
+ </div>
+ </>
+ );
+}
+
+function BibleTab({
+ draft, updateDraft, toggleLock,
+ llm,
+ handleExpand, expanding, saving,
+ refine,
+ totalVariations, categoryKeyCount, totalSheets,
+}) {
+ const { providers, providerModels, providerLabel, activeProviderId } = llm;
+ const {
+ open: refineOpen, setOpen: setRefineOpen,
+ feedback: refineFeedback, setFeedback: setRefineFeedback,
+ run: runRefine, running: refining, reset: resetRefinePanel,
+ rationale: refineRationale, changes: refineChanges,
+ } = refine;
+ return (
+ <>
+ <section className="bg-port-card border border-port-border rounded p-4 flex flex-col gap-3">
+ <div className="grid grid-cols-1 md:grid-cols-[1fr_220px] gap-3">
+ <div>
+ <FieldLabel field="starterPrompt" locked={draft.locked} onToggleLock={toggleLock}>
+ Starter idea
+ </FieldLabel>
+ <textarea
+ value={draft.starterPrompt}
+ onChange={(e) => updateDraft({ starterPrompt: e.target.value })}
+ placeholder="moebius and scavengers reign meets Prophet inspired sci fi universe"
+ className="w-full bg-port-bg border border-port-border rounded px-3 py-2 text-white text-sm focus:outline-none focus:border-port-accent"
+ rows={2}
+ maxLength={4000}
+ />
+ </div>
+ <div>
+ <label htmlFor="world-llm-provider" className="text-xs text-gray-400 mb-1 block">LLM for expansion</label>
+ <select
+ id="world-llm-provider"
+ value={draft.llm?.provider ?? ''}
+ onChange={(e) => updateDraft({ llm: { ...draft.llm, provider: e.target.value || null, model: null } })}
+ className="w-full bg-port-bg border border-port-border rounded px-2 py-2 text-white text-sm min-h-[40px]"
+ >
+ <option value="">Active provider ({providerLabel(activeProviderId)})</option>
+ {providers.map((p) => (
+ <option key={p.id} value={p.id}>{p.name}</option>
+ ))}
+ </select>
+ <select
+ value={draft.llm?.model || ''}
+ onChange={(e) => updateDraft({ llm: { ...draft.llm, model: e.target.value || null } })}
+ className="mt-1 w-full bg-port-bg border border-port-border rounded px-2 py-2 text-white text-sm min-h-[40px]"
+ >
+ <option value="">Default model</option>
+ {providerModels.map((m) => {
+ const id = typeof m === 'string' ? m : m.id;
+ const label = typeof m === 'string' ? m : (m.name || m.id);
+ return <option key={id} value={id}>{label}</option>;
+ })}
+ </select>
+ </div>
+ </div>
+
+ <div className="flex items-center gap-2 flex-wrap">
+ <button
+ onClick={handleExpand}
+ disabled={expanding || saving || !draft.starterPrompt?.trim()}
+ className="px-3 py-2 bg-purple-600/30 hover:bg-purple-600/50 disabled:opacity-50 text-purple-200 border border-purple-600/40 rounded flex items-center gap-2 min-h-[40px]"
+ >
+ {expanding ? <Loader2 size={16} className="animate-spin" /> : <Wand2 size={16} />}
+ Generate From Idea
+ </button>
+ <button
+ onClick={() => setRefineOpen((v) => !v)}
+ disabled={!draft.starterPrompt?.trim()}
+ aria-expanded={refineOpen}
+ className={`px-3 py-2 disabled:opacity-50 text-port-accent border border-port-accent/40 rounded flex items-center gap-2 min-h-[40px] ${
+ refineOpen ? 'bg-port-accent/25' : 'bg-port-accent/15 hover:bg-port-accent/25'
+ }`}
+ title="Give feedback to refine the prompts in place — uses the LLM picked above"
+ >
+ <MessageSquarePlus size={16} />
+ Refine prompts
+ </button>
+ <span className="text-xs text-gray-500">
+ {totalVariations} variation{totalVariations === 1 ? '' : 's'} across {categoryKeyCount} categories · {totalSheets} composite board{totalSheets === 1 ? '' : 's'}
+ </span>
+ </div>
+
+ {refineOpen && (
+ <div className="border border-port-accent/40 bg-port-accent/5 rounded p-3 flex flex-col gap-2">
+ <label htmlFor="world-refine-feedback" className="text-[11px] uppercase tracking-wide text-gray-500">
+ Feedback — describe what you want changed
+ </label>
+ <textarea
+ id="world-refine-feedback"
+ value={refineFeedback}
+ onChange={(e) => setRefineFeedback(e.target.value)}
+ placeholder="e.g. lean grimmer and more spiritual; pull style toward Moebius + Tarkovsky; avoid neon and cyberpunk clichés."
+ rows={3}
+ disabled={refining}
+ className="w-full bg-port-bg border border-port-border rounded p-2 text-sm text-white placeholder-gray-500 focus:outline-none focus:border-port-accent resize-y disabled:opacity-60"
+ />
+ <div className="flex items-center gap-2 flex-wrap">
+ <button
+ type="button"
+ onClick={runRefine}
+ disabled={refining || !refineFeedback.trim() || !draft.starterPrompt?.trim()}
+ className="px-3 py-2 bg-port-accent hover:bg-port-accent/90 disabled:opacity-50 disabled:cursor-not-allowed text-white rounded flex items-center gap-2 min-h-[40px]"
+ >
+ {refining ? <Loader2 size={14} className="animate-spin" /> : <Wand2 size={14} />}
+ {refining ? 'Refining…' : 'Refine'}
+ </button>
+ <button
+ type="button"
+ onClick={resetRefinePanel}
+ disabled={refining}
+ className="px-3 py-2 text-sm text-gray-400 hover:text-white rounded min-h-[40px]"
+ >
+ Close
+ </button>
+ <span className="text-[11px] text-gray-500">
+ Applies in place — locked fields stay pinned.
+ </span>
+ </div>
+ {(refineRationale || refineChanges.length > 0) && (
+ <div className="border-t border-port-border/60 pt-2 mt-1 space-y-1.5">
+ {refineRationale && (
+ <p className="text-xs text-gray-300 whitespace-pre-wrap">{refineRationale}</p>
+ )}
+ {refineChanges.length > 0 && (
+ <ul className="text-[11px] text-gray-400 list-disc pl-5 space-y-0.5">
+ {refineChanges.map((c, idx) => (
+ <li key={idx}>{c}</li>
+ ))}
+ </ul>
+ )}
+ </div>
+ )}
+ </div>
+ )}
+ </section>
+
+ <section className="bg-port-card border border-port-border rounded p-4 flex flex-col gap-3">
+ <div>
+ <h2 className="text-sm font-semibold text-white">Story bible</h2>
+ <p className="text-xs text-gray-500 mt-0.5">
+ Pulled into the Pipeline → New Series form when this world is selected.
+ </p>
+ </div>
+ <div>
+ <FieldLabel htmlFor="world-logline" field="logline" locked={draft.locked} onToggleLock={toggleLock}>
+ Logline
+ </FieldLabel>
+ <input
+ id="world-logline"
+ type="text"
+ value={draft.logline || ''}
+ onChange={(e) => updateDraft({ logline: e.target.value })}
+ placeholder="One-sentence hook — A foundry city goes silent, and the only survivor is a child."
+ className="w-full bg-port-bg border border-port-border rounded px-3 py-2 text-white text-sm focus:outline-none focus:border-port-accent"
+ maxLength={WORLD_LOGLINE_MAX}
+ />
+ </div>
+ <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
+ <div>
+ <FieldLabel htmlFor="world-premise" field="premise" locked={draft.locked} onToggleLock={toggleLock}>
+ Premise
+ </FieldLabel>
+ <textarea
+ id="world-premise"
+ value={draft.premise || ''}
+ onChange={(e) => updateDraft({ premise: e.target.value })}
+ placeholder="Elevator pitch — 1-3 short paragraphs about the setting, central conflict, stakes, and tone."
+ className="w-full bg-port-bg border border-port-border rounded px-3 py-2 text-white text-sm focus:outline-none focus:border-port-accent"
+ rows={6}
+ maxLength={WORLD_PREMISE_MAX}
+ />
+ </div>
+ <div>
+ <FieldLabel htmlFor="world-style-notes" field="styleNotes" locked={draft.locked} onToggleLock={toggleLock}>
+ Style notes
+ </FieldLabel>
+ <textarea
+ id="world-style-notes"
+ value={draft.styleNotes || ''}
+ onChange={(e) => updateDraft({ styleNotes: e.target.value })}
+ placeholder="Narrative style: references (artists / films / comics), mood, palette, pacing, voice. Prose, not tokens."
+ className="w-full bg-port-bg border border-port-border rounded px-3 py-2 text-white text-sm focus:outline-none focus:border-port-accent"
+ rows={6}
+ maxLength={WORLD_STYLE_NOTES_MAX}
+ />
+ </div>
+ </div>
+ <StyleNegativePromptEditor
+ influences={draft.influences}
+ onChange={(next) => updateDraft({ influences: next })}
+ locked={draft.locked}
+ onToggleLock={toggleLock}
+ />
+ </section>
+ </>
+ );
+}
+
+// Sub-bucket chip strip used by TrunkView + OtherTab. The "All" chip is a
+// pseudo-bucket that clears `?bucket=`. Each real bucket key gets its own
+// chip; clicking toggles it on/off (toggle-off returns to All). Designed so
+// it works one-handed on mobile (38px tap targets, wraps to multiple lines).
+function BucketChipStrip({ buckets, activeBucket, setBucket, showAll = true, extraChips = [] }) {
+ if (buckets.length === 0 && extraChips.length === 0) return null;
+ return (
+ <div className="flex flex-wrap items-center gap-1.5">
+ {showAll && (
+ <button
+ type="button"
+ onClick={() => setBucket('')}
+ className={`px-2.5 py-1.5 rounded-full text-xs min-h-[32px] transition-colors ${
+ !activeBucket
+ ? 'bg-port-accent/25 text-port-accent border border-port-accent/40'
+ : 'bg-port-bg text-gray-300 border border-port-border hover:border-gray-500'
+ }`}
+ >
+ All
+ </button>
+ )}
+ {extraChips.map((chip) => (
+ <button
+ key={chip.key}
+ type="button"
+ onClick={() => setBucket(chip.key)}
+ className={`px-2.5 py-1.5 rounded-full text-xs min-h-[32px] transition-colors ${
+ activeBucket === chip.key
+ ? 'bg-port-accent/25 text-port-accent border border-port-accent/40'
+ : 'bg-port-bg text-gray-300 border border-port-border hover:border-gray-500'
+ }`}
+ >
+ {chip.label}
+ </button>
+ ))}
+ {buckets.map((bucket) => {
+ const active = activeBucket === bucket;
+ return (
+ <button
+ key={bucket}
+ type="button"
+ onClick={() => setBucket(active ? '' : bucket)}
+ className={`px-2.5 py-1.5 rounded-full text-xs min-h-[32px] transition-colors ${
+ active
+ ? 'bg-port-accent/25 text-port-accent border border-port-accent/40'
+ : 'bg-port-bg text-gray-300 border border-port-border hover:border-gray-500'
+ }`}
+ >
+ {humanizeCategory(bucket)}
+ </button>
+ );
+ })}
+ </div>
+ );
+}
+
+// Per-trunk view. Three modes driven by `?bucket=`:
+// - blank (default "All"): renders canon + every variation under this trunk
+// - BUCKET_CANON: renders only canon entries (via the existing UniverseCanonSection)
+// - <bucketKey>: renders that bucket's variations via CategoryEditor
+function TrunkView({
+ trunk, draft, selectedId, buckets, activeBucket, setBucket,
+ canRender, imageCfg, onUniverseChange,
+ onRemoveBucket, onUpdateBucket, onGenerateInBucket,
+ onBulkRenderBucket, onRenderVariation, onBulkRenderTrunk,
+ onAddBucket,
+}) {
+ const canonList = Array.isArray(draft[trunk.kind]) ? draft[trunk.kind] : [];
+ // Only count canon entries the server will actually compile — mirror the
+ // `synthesizeCanonPrompt`-empty-seed skip via `canonEntryHasContent`. Without
+ // this, "Bulk-render all (N)" would advertise more images than land, and the
+ // server can 400 with WORLD_BUILDER_EMPTY when every entry under the trunk
+ // synthesizes to nothing.
+ const canonRenderable = canonList.filter((e) => canonEntryHasContent(e, trunk.kind)).length;
+ const totalUnderTrunk =
+ canonRenderable
+ + buckets.reduce((n, k) => n + (draft.categories?.[k]?.variations?.length || 0), 0);
+ const [addingBucket, setAddingBucket] = useState(false);
+ const [newBucketName, setNewBucketName] = useState('');
+
+ const handleAddBucket = () => {
+ const key = normalizeCategoryKey(newBucketName);
+ if (!key) {
+ toast.error('Use letters or numbers for the bucket name');
+ return;
+ }
+ if (draft.categories?.[key]) {
+ toast.error('A bucket with that name already exists');
+ return;
+ }
+ onAddBucket({ key });
+ setNewBucketName('');
+ setAddingBucket(false);
+ setBucket(key);
+ };
+
+ return (
+ <>
+ <section className="bg-port-card border border-port-border rounded p-3 flex flex-col gap-2">
+ <div className="flex items-center justify-between gap-2 flex-wrap">
+ <BucketChipStrip
+ buckets={buckets}
+ activeBucket={activeBucket}
+ setBucket={setBucket}
+ extraChips={canonList.length > 0 ? [{ key: BUCKET_CANON, label: `Canon (${canonList.length})` }] : []}
+ />
+ <div className="flex items-center gap-1.5 flex-wrap">
+ <button
+ type="button"
+ onClick={() => setAddingBucket((v) => !v)}
+ className="text-xs px-2 py-1.5 bg-port-bg hover:bg-port-border text-gray-300 border border-port-border rounded flex items-center gap-1 min-h-[32px]"
+ title={`Add a sub-bucket under ${trunk.label}`}
+ >
+ <Plus size={12} /> Bucket
+ </button>
+ <button
+ type="button"
+ onClick={onBulkRenderTrunk}
+ disabled={!canRender || totalUnderTrunk === 0}
+ className="text-xs px-2 py-1.5 bg-port-accent/15 hover:bg-port-accent/25 disabled:opacity-30 disabled:cursor-not-allowed text-port-accent rounded flex items-center gap-1 min-h-[32px]"
+ title={totalUnderTrunk === 0 ? `No ${trunk.label.toLowerCase()} to render yet` : `Bulk-render all ${trunk.label.toLowerCase()} — ${totalUnderTrunk} prompt${totalUnderTrunk === 1 ? '' : 's'}`}
+ >
+ <Sparkles size={12} /> Bulk-render all ({totalUnderTrunk})
+ </button>
+ </div>
+ </div>
+ {addingBucket && (
+ <div className="flex items-center gap-2 flex-wrap pt-1">
+ <input
+ type="text"
+ value={newBucketName}
+ onChange={(e) => setNewBucketName(e.target.value)}
+ onKeyDown={(e) => { if (e.key === 'Enter') handleAddBucket(); }}
+ placeholder={trunk.kind === 'characters' ? 'heroes, villains, factions' : trunk.kind === 'settings' ? 'colonies, ruins' : 'weapons, vehicles'}
+ className="flex-1 min-w-[160px] bg-port-bg border border-port-border rounded px-2 py-1.5 text-white text-sm focus:outline-none focus:border-port-accent"
+ maxLength={WORLD_CATEGORY_KEY_MAX}
+ autoFocus
+ />
+ <button
+ onClick={handleAddBucket}
+ disabled={!newBucketName.trim()}
+ className="text-xs px-2 py-1.5 bg-port-accent hover:bg-port-accent/90 disabled:opacity-50 text-white rounded min-h-[32px]"
+ >
+ Add
+ </button>
+ <button
+ onClick={() => { setAddingBucket(false); setNewBucketName(''); }}
+ className="text-xs px-2 py-1.5 bg-port-bg hover:bg-port-border text-gray-300 rounded min-h-[32px]"
+ >
+ Cancel
+ </button>
+ </div>
+ )}
+ </section>
+
+ {/* Canon visibility: "All" (no bucket selected) or the canon pseudo-bucket.
+ Gated on `draft.id === selectedId` to avoid the universe-switch race
+ documented on UniverseCanonSection itself. */}
+ {(!activeBucket || activeBucket === BUCKET_CANON) && selectedId && draft.id === selectedId ? (
+ <UniverseCanonSection
+ universe={draft}
+ universeId={selectedId}
+ onUniverseChange={onUniverseChange}
+ imageCfg={imageCfg}
+ kindFilter={trunk.kind}
+ />
+ ) : null}
+
+ {activeBucket !== BUCKET_CANON && (
+ <>
+ {(activeBucket ? [activeBucket] : buckets).length === 0 ? (
+ <section className="bg-port-card border border-port-border rounded p-6 text-center text-sm text-gray-500">
+ No {trunk.label.toLowerCase()} sub-buckets yet.{' '}
+ <button
+ type="button"
+ onClick={() => setAddingBucket(true)}
+ className="text-port-accent hover:underline"
+ >
+ Add one
+ </button>
+ {' '}or click <em>Generate From Idea</em> on the Bible tab to seed them.
+ </section>
+ ) : (
+ <section className="grid grid-cols-1 md:grid-cols-2 gap-3">
+ {(activeBucket ? [activeBucket] : buckets).map((cat) => (
+ <CategoryEditor
+ key={cat}
+ category={cat}
+ variations={draft.categories?.[cat]?.variations || []}
+ canRemove={!WORLD_CATEGORIES.includes(cat)}
+ onChange={(next) => onUpdateBucket(cat, next)}
+ onRemove={() => onRemoveBucket(cat)}
+ canRender={canRender}
+ onRenderCategory={() => onBulkRenderBucket(cat)}
+ onRenderVariation={(v) => onRenderVariation(cat, v)}
+ onGenerate={(count) => onGenerateInBucket(cat, count)}
+ />
+ ))}
+ </section>
+ )}
+ </>
+ )}
+ </>
+ );
+}
+
+// Other tab — un-kinded buckets that haven't been sorted into a trunk yet.
+// Same card grid as TrunkView but no canon plumbing, plus an "Auto-sort"
+// action that (eventually) LLM-classifies each bucket into the right trunk.
+function OtherTab({
+ draft, buckets, activeBucket, setBucket, canRender,
+ onUpdateBucket, onRemoveBucket, onGenerateInBucket,
+ onBulkRenderBucket, onRenderVariation, onAutoSort,
+}) {
+ return (
+ <>
+ <section className="bg-port-card border border-port-border rounded p-3 flex flex-col gap-2">
+ <div className="flex items-center justify-between gap-2 flex-wrap">
+ <BucketChipStrip
+ buckets={buckets}
+ activeBucket={activeBucket}
+ setBucket={setBucket}
+ />
+ <button
+ type="button"
+ onClick={onAutoSort}
+ className="text-xs px-2 py-1.5 bg-port-accent/15 hover:bg-port-accent/25 text-port-accent rounded flex items-center gap-1 min-h-[32px]"
+ title="Auto-sort with AI — shows guidance until the dedicated endpoint lands (tracked in PLAN.md)"
+ >
+ <Wand2 size={12} /> Auto-sort with AI
+ </button>
+ </div>
+ <p className="text-[11px] text-gray-500">
+ These buckets aren't tagged as Cast / Places / Objects yet — they were
+ either added manually or imported from a pre-Phase-A universe. Auto-sort
+ will classify each bucket into the right trunk with a meaningful name.
+ </p>
+ </section>
+
+ <section className="grid grid-cols-1 md:grid-cols-2 gap-3">
+ {(activeBucket ? [activeBucket] : buckets).map((cat) => (
+ <CategoryEditor
+ key={cat}
+ category={cat}
+ variations={draft.categories?.[cat]?.variations || []}
+ canRemove={!WORLD_CATEGORIES.includes(cat)}
+ onChange={(next) => onUpdateBucket(cat, next)}
+ onRemove={() => onRemoveBucket(cat)}
+ canRender={canRender}
+ onRenderCategory={() => onBulkRenderBucket(cat)}
+ onRenderVariation={(v) => onRenderVariation(cat, v)}
+ onGenerate={(count) => onGenerateInBucket(cat, count)}
+ />
+ ))}
+ </section>
+ </>
+ );
+}
+
+function RenderTab({
+ draft, selectedId, bucketsByKind, renderOpts, setRenderOpts,
+ availableBackends, defaultMode, imageModels, handleRender, rendering, runs,
+}) {
+ const totalSheets = draft.compositeSheets?.length || 0;
+ const totalVariations = totalVariationCount(draft);
+ // Mirror server-side compile skip rules — `renderPromptCount` already filters
+ // canon via `canonEntryHasContent`, so the "All canon (N)" option label and
+ // the actual enqueued count agree.
+ const totalCanon = countCanonWithContent(draft, 'characters')
+ + countCanonWithContent(draft, 'settings')
+ + countCanonWithContent(draft, 'objects');
+ const renderTotal = renderPromptCount(draft, renderOpts.promptMode || 'variations');
+
+ 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 flex-wrap">
+ <h2 className="text-sm font-semibold text-white flex items-center gap-2">
+ <FolderOpen size={16} className="text-port-accent" /> Batch render
+ </h2>
+ {availableBackends.length > 1 && (
+ <BackendChipStrip
+ availableBackends={availableBackends}
+ value={renderOpts.mode || defaultMode}
+ onChange={(id) => setRenderOpts((r) => ({ ...r, mode: id }))}
+ titlePrefix="Render via"
+ />
+ )}
+ </div>
+ {availableBackends.length === 0 && (
+ <p className="text-xs text-port-warning">
+ Configure a local mflux Python path or enable Codex Imagegen in Settings → Image Gen
+ to enable batch render.
+ </p>
+ )}
+ <div className="grid grid-cols-1 sm:grid-cols-3 gap-3">
+ <div>
+ <label htmlFor="world-render-prompt-mode" className="block text-xs font-medium text-gray-400 mb-1">Prompt set</label>
+ <select
+ id="world-render-prompt-mode"
+ value={renderOpts.promptMode || 'variations'}
+ onChange={(e) => setRenderOpts((r) => ({ ...r, promptMode: e.target.value }))}
+ className="w-full bg-port-bg border border-port-border rounded-lg px-2 py-2 text-sm text-white focus:outline-none focus:border-port-accent min-h-[40px]"
+ >
+ <option value="variations" disabled={totalVariations === 0}>Atomic variations ({totalVariations})</option>
+ <option value="sheets" disabled={totalSheets === 0}>Composite boards ({totalSheets})</option>
+ <option value="canon" disabled={totalCanon === 0}>All canon ({totalCanon})</option>
+ <option value="all" disabled={totalSheets + totalVariations + totalCanon === 0}>
+ Everything ({totalSheets + totalVariations + totalCanon})
+ </option>
+ </select>
+ </div>
+ </div>
+ <ImageGenControls
+ mode={renderOpts.mode || defaultMode || 'local'}
+ models={imageModels}
+ modelId={renderOpts.modelId}
+ onModelChange={(id) => setRenderOpts((r) => ({ ...r, modelId: id, steps: '', guidance: '' }))}
+ width={renderOpts.width}
+ height={renderOpts.height}
+ onResolutionChange={(w, h) => setRenderOpts((r) => ({ ...r, width: w, height: h }))}
+ steps={renderOpts.steps}
+ onStepsChange={(v) => setRenderOpts((r) => ({ ...r, steps: v }))}
+ guidance={renderOpts.guidance}
+ onGuidanceChange={(v) => setRenderOpts((r) => ({ ...r, guidance: v }))}
+ cfgScale={renderOpts.cfgScale}
+ onCfgScaleChange={(v) => setRenderOpts((r) => ({ ...r, cfgScale: v }))}
+ quantize={renderOpts.quantize}
+ onQuantizeChange={(v) => setRenderOpts((r) => ({ ...r, quantize: v }))}
+ />
+ <div className="grid grid-cols-2 sm:grid-cols-3 gap-3">
+ <div>
+ <label htmlFor="world-render-batch" className="block text-xs font-medium text-gray-400 mb-1">Renders per prompt</label>
+ <input
+ id="world-render-batch"
+ type="number" min={1} max={20}
+ value={renderOpts.batchPerVariation ?? 1}
+ onChange={(e) => {
+ const n = Number(e.target.value);
+ setRenderOpts((r) => ({ ...r, batchPerVariation: Number.isFinite(n) && n > 0 ? n : 1 }));
+ }}
+ className="w-full bg-port-bg border border-port-border rounded-lg px-2 py-2 text-sm text-white focus:outline-none focus:border-port-accent"
+ />
+ </div>
+ </div>
+ <div className="flex items-center gap-2 flex-wrap">
+ <button
+ onClick={() => handleRender()}
+ disabled={rendering || !selectedId || renderTotal === 0 || availableBackends.length === 0}
+ className="px-4 py-2 bg-port-accent hover:bg-port-accent/90 disabled:opacity-50 text-white rounded flex items-center gap-2 min-h-[40px]"
+ >
+ {rendering ? <Loader2 size={16} className="animate-spin" /> : <Sparkles size={16} />}
+ Render {renderTotal * (renderOpts.batchPerVariation || 1)} image{renderTotal * (renderOpts.batchPerVariation || 1) === 1 ? '' : 's'}
+ </button>
+ </div>
+ {!selectedId && <p className="text-xs text-gray-500">Save the world first to enable rendering.</p>}
+ </section>
+
+ <section className="bg-port-card border border-port-border rounded p-4 flex flex-col gap-3">
+ <h3 className="text-sm font-semibold text-white">Render targets</h3>
+ <p className="text-[11px] text-gray-500 -mt-1">
+ Click a target to queue that scope immediately with the knobs above.
+ </p>
+ <div className="flex flex-col gap-2">
+ {TRUNK_TABS.map((trunk) => {
+ const buckets = bucketsByKind[trunk.kind] || [];
+ // Use the synthesizable count for both the display label and the
+ // "Bulk-render all" total so the button advertises the number that
+ // will actually land on the server.
+ const canonCount = countCanonWithContent(draft, trunk.kind);
+ const variationCount = buckets.reduce((n, k) => n + (draft.categories?.[k]?.variations?.length || 0), 0);
+ const total = canonCount + variationCount;
+ if (total === 0) return null;
+ const Icon = trunk.icon;
+ return (
+ <div key={trunk.id} className="border border-port-border rounded p-2 bg-port-bg flex flex-col gap-1.5">
+ <div className="flex items-center justify-between gap-2 flex-wrap">
+ <div className="flex items-center gap-2 text-sm text-gray-200">
+ <Icon size={14} className="text-port-accent" />
+ <span className="font-medium">{trunk.label}</span>
+ <span className="text-[11px] text-gray-500">
+ {canonCount} canon · {variationCount} variation{variationCount === 1 ? '' : 's'}
+ </span>
+ </div>
+ <button
+ type="button"
+ onClick={() => handleRender({
+ promptMode: 'all',
+ selection: Object.fromEntries(buckets.map((b) => [b, 'all'])),
+ canonSelection: canonCount > 0 ? { [trunk.kind]: 'all' } : undefined,
+ // Trunk scope excludes composite sheets — see comment on
+ // TrunkView's onBulkRenderTrunk for why this opt-out matters.
+ sheetSelection: [],
+ })}
+ disabled={!selectedId || availableBackends.length === 0 || rendering}
+ className="text-xs px-2 py-1 bg-port-accent/15 hover:bg-port-accent/25 disabled:opacity-30 disabled:cursor-not-allowed text-port-accent rounded min-h-[32px]"
+ title={`Render every ${trunk.label.toLowerCase()} canon entry AND every variation under this trunk`}
+ >
+ Bulk-render all ({total})
+ </button>
+ </div>
+ {buckets.length > 0 && (
+ <div className="flex flex-wrap items-center gap-1 pl-5">
+ {buckets.map((bucket) => {
+ const count = draft.categories?.[bucket]?.variations?.length || 0;
+ return (
+ <button
+ key={bucket}
+ type="button"
+ onClick={() => handleRender({ promptMode: 'variations', selection: { [bucket]: 'all' } })}
+ disabled={count === 0 || !selectedId || availableBackends.length === 0 || rendering}
+ className="text-[11px] px-1.5 py-0.5 bg-port-card border border-port-border hover:border-port-accent disabled:opacity-30 disabled:cursor-not-allowed text-gray-300 rounded"
+ title={count === 0 ? 'No variations yet' : `Bulk-render ${humanizeCategory(bucket)} (${count})`}
+ >
+ {humanizeCategory(bucket)} ({count})
+ </button>
+ );
+ })}
+ </div>
+ )}
+ </div>
+ );
+ })}
+ {totalCanon > 0 ? (
+ <div className="border border-port-border rounded p-2 bg-port-bg flex items-center justify-between gap-2">
+ <span className="text-sm text-gray-200 flex items-center gap-2">
+ <Sparkles size={14} className="text-port-accent" />
+ All canon
+ <span className="text-[11px] text-gray-500">
+ {totalCanon} entr{totalCanon === 1 ? 'y' : 'ies'}
+ </span>
+ </span>
+ <button
+ type="button"
+ onClick={() => handleRender({
+ promptMode: 'canon',
+ canonSelection: {
+ characters: 'all',
+ settings: 'all',
+ objects: 'all',
+ },
+ })}
+ disabled={!selectedId || availableBackends.length === 0 || rendering}
+ className="text-xs px-2 py-1 bg-port-accent/15 hover:bg-port-accent/25 disabled:opacity-30 disabled:cursor-not-allowed text-port-accent rounded min-h-[32px]"
+ >
+ Bulk-render all canon
+ </button>
+ </div>
+ ) : null}
+ {totalSheets > 0 && (
+ <div className="border border-port-border rounded p-2 bg-port-bg flex items-center justify-between gap-2">
+ <span className="text-sm text-gray-200 flex items-center gap-2">
+ <Layers size={14} className="text-port-accent" />
+ Composite boards
+ <span className="text-[11px] text-gray-500">{totalSheets} board{totalSheets === 1 ? '' : 's'}</span>
+ </span>
+ <button
+ type="button"
+ onClick={() => handleRender({ promptMode: 'sheets', sheetSelection: 'all' })}
+ disabled={!selectedId || availableBackends.length === 0 || rendering}
+ className="text-xs px-2 py-1 bg-port-accent/15 hover:bg-port-accent/25 disabled:opacity-30 disabled:cursor-not-allowed text-port-accent rounded min-h-[32px]"
+ >
+ Bulk-render composites
+ </button>
+ </div>
+ )}
+ </div>
+ </section>
+
+ {selectedId && runs.length > 0 && (
+ <section className="bg-port-card border border-port-border rounded p-4">
+ <h2 className="text-sm font-semibold text-white mb-2">Recent runs</h2>
+ <ul className="flex flex-col gap-1">
+ {runs.map((r) => (
+ <li key={r.id} className="flex items-center justify-between text-sm text-gray-300 border-b border-port-border/40 py-1.5">
+ <span className="truncate">
+ <span className="text-gray-500">{new Date(r.createdAt).toLocaleString()} —</span>{' '}
+ {r.promptCount} prompt{r.promptCount === 1 ? '' : 's'}
+ </span>
+ {r.collectionId && (
+ <Link
+ to={`/media/collections/${r.collectionId}`}
+ className="text-xs text-port-accent hover:underline whitespace-nowrap"
+ >
+ Open collection →
+ </Link>
+ )}
+ </li>
+ ))}
+ </ul>
+ </section>
+ )}
+ </>
+ );
+}
diff --git a/server/routes/universeBuilder.js b/server/routes/universeBuilder.js
index 973188e08d..06080befb4 100644
--- a/server/routes/universeBuilder.js
+++ b/server/routes/universeBuilder.js
@@ -18,7 +18,7 @@ import { asyncHandler, ServerError } from '../lib/errorHandler.js';
import { validateRequest } from '../lib/validation.js';
import * as svc from '../services/universeBuilder.js';
import * as canonSvc from '../services/universeCanon.js';
-import { BIBLE_KINDS } from '../lib/storyBible.js';
+import { BIBLE_KINDS, BIBLE_LIMITS } from '../lib/storyBible.js';
import { getUniverseCanonUsage } from '../services/canonUsage.js';
import { expandWorldTemplate, generateCategoryVariations } from '../services/universeBuilderExpand.js';
import { refineWorldPrompts } from '../services/universeBuilderRefine.js';
@@ -237,6 +237,23 @@ const selectionSchema = z.record(
message: `selection cannot exceed ${svc.WORLD_CATEGORY_COUNT_MAX} buckets`,
});
+// `canonSelection` per trunk: 'all' or array of canon-entry names (case-insensitive).
+// Settings entries also match on `slugline` so a render queued from the Places
+// tab can target an entry the user filed by slugline ("INT. FOUNDRY — DAY").
+// Per-trunk cap mirrors the bible sanitizer (`ENTRIES_PER_BIBLE_MAX`) so this
+// can't enqueue more entries than the server actually persists; per-string cap
+// uses the looser of `NAME_MAX` / `SLUGLINE_MAX` so a settings entry filed by
+// slugline isn't rejected if those limits ever diverge (both 200 today).
+const CANON_TRUNK_KEYS = ['characters', 'settings', 'objects'];
+const CANON_NEEDLE_MAX = Math.max(BIBLE_LIMITS.NAME_MAX, BIBLE_LIMITS.SLUGLINE_MAX);
+const canonSelectionValueSchema = z.union([
+ z.literal('all'),
+ z.array(z.string().trim().min(1).max(CANON_NEEDLE_MAX)).max(BIBLE_LIMITS.ENTRIES_PER_BIBLE_MAX),
+]);
+const canonSelectionSchema = z.object(
+ Object.fromEntries(CANON_TRUNK_KEYS.map((k) => [k, canonSelectionValueSchema.optional()])),
+).strict();
+
const renderSchema = z.object({
// Removed: callers that still send `collectionName` get an explicit 400
// (see the .refine() below) instead of a confusing silent no-op. The
@@ -255,10 +272,11 @@ const renderSchema = z.object({
guidance: z.number().min(0).max(30).optional(),
quantize: z.enum(['3', '4', '5', '6', '8']).optional(),
// Per-variation render count and per-category subset.
- promptMode: z.enum(['variations', 'sheets', 'all']).optional().default('variations'),
+ promptMode: z.enum(['variations', 'sheets', 'canon', 'all']).optional().default('variations'),
batchPerVariation: z.number().int().min(1).max(20).optional().default(1),
selection: selectionSchema.optional(),
sheetSelection: z.union([z.literal('all'), z.array(z.string().trim().min(1).max(svc.VARIATION_LABEL_MAX)).max(svc.COMPOSITE_SHEETS_MAX)]).optional(),
+ canonSelection: canonSelectionSchema.optional(),
}).refine((body) => body.collectionName === undefined, {
message: 'collectionName is no longer supported — the linked collection follows the universe name automatically. Remove this field.',
path: ['collectionName'],
@@ -323,10 +341,11 @@ router.post('/:id/render', asyncHandler(async (req, res) => {
promptMode: body.promptMode,
selection: body.selection,
sheetSelection: body.sheetSelection,
+ canonSelection: body.canonSelection,
batchPerVariation: body.batchPerVariation,
});
if (!compiled.length) {
- throw new ServerError('No prompts to render — add variations or composite sheets first', {
+ throw new ServerError('No prompts to render — add canon entries, variations, or composite sheets first', {
status: 400, code: 'WORLD_BUILDER_EMPTY',
});
}
diff --git a/server/services/universeBuilder.js b/server/services/universeBuilder.js
index e452ac6c0f..15fd13598e 100644
--- a/server/services/universeBuilder.js
+++ b/server/services/universeBuilder.js
@@ -874,21 +874,77 @@ export function joinInfluenceList(structured = []) {
return structured.filter((t) => typeof t === 'string' && t.trim()).join(', ');
}
+// Order matches the Universe Builder tab order (Cast → Places → Objects) so
+// the compiled-prompts list is stable across renders.
+const CANON_TRUNKS = Object.freeze([
+ { key: 'characters', category: 'canon:characters' },
+ { key: 'settings', category: 'canon:settings' },
+ { key: 'objects', category: 'canon:objects' },
+]);
+
+// Synthesize a render prompt from a canon entry. `entry.prompt` wins when the
+// user has hand-authored one; otherwise stitch together the descriptive fields
+// that exist for this kind (per-kind contract in `BIBLE_FIELD_WHITELIST`):
+// - characters: physicalDescription, role
+// - settings: description, palette, era, weather, recurringDetails
+// - objects: description, significance
+// The output is fed through `composeStyledPrompt(...)` so the universe's
+// embrace tokens still prefix every canon render.
+export function synthesizeCanonPrompt(kind, entry) {
+ if (!entry) return '';
+ if (typeof entry.prompt === 'string' && entry.prompt.trim()) return entry.prompt.trim();
+ // Identifier seed: `name` is the shared anchor for all kinds. For
+ // `settings`, the bible sanitizer allows entries whose ONLY identifier is
+ // a slugline (e.g. "EXT. FOUNDRY CITY — DAY") with no separate name — fall
+ // back to slugline so those entries don't synthesize to an empty seed and
+ // get silently skipped at render time.
+ const name = typeof entry.name === 'string' ? entry.name.trim() : '';
+ const sluglineId = (kind === 'settings' && typeof entry.slugline === 'string')
+ ? entry.slugline.trim()
+ : '';
+ const identifier = name || sluglineId;
+ const parts = [];
+ if (kind === 'characters') {
+ if (entry.physicalDescription) parts.push(entry.physicalDescription);
+ if (entry.role) parts.push(entry.role);
+ } else if (kind === 'settings') {
+ if (entry.description) parts.push(entry.description);
+ if (entry.palette) parts.push(`palette: ${entry.palette}`);
+ if (entry.era) parts.push(`era: ${entry.era}`);
+ if (entry.weather) parts.push(`weather: ${entry.weather}`);
+ if (entry.recurringDetails) parts.push(entry.recurringDetails);
+ } else if (kind === 'objects') {
+ if (entry.description) parts.push(entry.description);
+ if (entry.significance) parts.push(`significance: ${entry.significance}`);
+ }
+ const body = parts.map((p) => String(p).trim()).filter(Boolean).join('. ');
+ if (identifier && body) return `${identifier} — ${body}`;
+ return identifier || body;
+}
+
/**
* Compile the universe template into an ordered list of full image-gen
* prompts. Each entry combines the universe's style prompt with one
- * variation from a chosen category.
+ * variation from a chosen category, one composite sheet, or one canon entry.
+ *
+ * promptMode: 'variations' | 'sheets' | 'canon' | 'all'
*
* selection: { landscapes: 'all' | string[], characters: ... }
* - 'all' → use every variation
* - array of labels → only those labels (case-insensitive match)
* - missing key → skip the category entirely
*
+ * canonSelection: { characters?: 'all' | string[], settings?: ..., objects?: ... }
+ * - 'all' → render every entry in that canon trunk
+ * - array of names → only those names (case-insensitive match against
+ * `name` and, for settings, `slugline`)
+ * - missing key → skip the trunk entirely
+ *
* batchPerVariation: how many renders per variation (1..20)
*/
export function compilePrompts(universe, options = {}) {
if (!universe) return [];
- const promptMode = ['variations', 'sheets', 'all'].includes(options.promptMode)
+ const promptMode = ['variations', 'sheets', 'canon', 'all'].includes(options.promptMode)
? options.promptMode
: 'variations';
const selection = options.selection && typeof options.selection === 'object'
@@ -953,5 +1009,49 @@ export function compilePrompts(universe, options = {}) {
}
}
+ if (promptMode === 'canon' || promptMode === 'all') {
+ const canonSelection = options.canonSelection && typeof options.canonSelection === 'object'
+ ? options.canonSelection
+ : null;
+ if (canonSelection) {
+ for (const trunk of CANON_TRUNKS) {
+ const sel = canonSelection[trunk.key];
+ if (!sel) continue;
+ const entries = Array.isArray(universe[trunk.key]) ? universe[trunk.key] : [];
+ const filtered = sel === 'all'
+ ? entries
+ : entries.filter((e) => Array.isArray(sel) && sel.some((s) => {
+ const needle = s.toLowerCase();
+ if (typeof e.name === 'string' && e.name.toLowerCase() === needle) return true;
+ // Slugline is settings-only (see canonSelection docstring above
+ // and BIBLE_FIELD_WHITELIST). Avoid matching a stray slugline
+ // field on a character/object payload — that field isn't part of
+ // the canon contract for those kinds.
+ if (trunk.key === 'settings'
+ && typeof e.slugline === 'string'
+ && e.slugline.toLowerCase() === needle) return true;
+ return false;
+ }));
+ for (const entry of filtered) {
+ const seed = synthesizeCanonPrompt(trunk.key, entry);
+ // An entry with no name and no descriptive content yields nothing —
+ // skip rather than enqueue a style-prompt-only render that would
+ // produce a generic image with no identity anchor.
+ if (!seed) continue;
+ const { prompt, negativePrompt } = composeStyledPrompt(seed, '', stylePreset);
+ for (let i = 0; i < batchPerVariation; i += 1) {
+ compiled.push({
+ category: trunk.category,
+ label: entry.name || entry.slugline || trunk.key,
+ prompt,
+ negativePrompt,
+ batchIndex: i,
+ });
+ }
+ }
+ }
+ }
+ }
+
return compiled;
}
diff --git a/server/services/universeBuilder.test.js b/server/services/universeBuilder.test.js
index d01db86043..c4e1b49464 100644
--- a/server/services/universeBuilder.test.js
+++ b/server/services/universeBuilder.test.js
@@ -457,6 +457,218 @@ describe("universeBuilder service", () => {
expect(compiled).toHaveLength(4); // 3 atomic variations + 1 composite
expect(compiled.map((p) => p.category)).toContain("composite_sheets");
});
+
+ describe("canon", () => {
+ // Compile canon directly off a draft (createUniverse doesn't accept canon —
+ // it lands via the canon-extract / refine path or the expand auto-save).
+ // The synthesis path doesn't touch persistence, so a literal world shape
+ // is enough.
+ const canonWorld = () => ({
+ influences: {
+ embrace: ["moebius linework"],
+ avoid: ["blurry"],
+ },
+ characters: [
+ {
+ name: "Mira",
+ physicalDescription: "weathered scavenger, dust mask, copper goggles",
+ role: "protagonist",
+ },
+ { name: "Vex", physicalDescription: "tall, scarred, plate-armor smith" },
+ ],
+ settings: [
+ {
+ name: "Foundry City",
+ slugline: "EXT. FOUNDRY CITY — DAY",
+ description: "vast smelting works at the canyon rim",
+ palette: "rust + bone",
+ },
+ ],
+ objects: [
+ { name: "Brass Compass", description: "always points away from home" },
+ ],
+ });
+
+ it("synthesizes canon prompts from name + descriptive fields with style prefix", () => {
+ const w = canonWorld();
+ const compiled = svc.compilePrompts(w, {
+ promptMode: "canon",
+ canonSelection: { characters: "all", settings: "all", objects: "all" },
+ });
+ // 2 characters + 1 setting + 1 object = 4
+ expect(compiled).toHaveLength(4);
+ const mira = compiled.find((c) => c.label === "Mira");
+ expect(mira.category).toBe("canon:characters");
+ expect(mira.prompt).toBe(
+ "moebius linework. Mira — weathered scavenger, dust mask, copper goggles. protagonist",
+ );
+ expect(mira.negativePrompt).toBe("blurry");
+ const place = compiled.find((c) => c.label === "Foundry City");
+ expect(place.category).toBe("canon:settings");
+ expect(place.prompt).toContain("Foundry City");
+ expect(place.prompt).toContain("palette: rust + bone");
+ });
+
+ it("canonSelection: missing trunk skips it", () => {
+ const w = canonWorld();
+ const compiled = svc.compilePrompts(w, {
+ promptMode: "canon",
+ canonSelection: { settings: "all" },
+ });
+ expect(compiled).toHaveLength(1);
+ expect(compiled[0].category).toBe("canon:settings");
+ });
+
+ it("canonSelection: array filters by name (case-insensitive)", () => {
+ const w = canonWorld();
+ const compiled = svc.compilePrompts(w, {
+ promptMode: "canon",
+ canonSelection: { characters: ["mira"] },
+ });
+ expect(compiled).toHaveLength(1);
+ expect(compiled[0].label).toBe("Mira");
+ });
+
+ it("synthesizes a settings prompt from slugline-only entries (no name)", () => {
+ // The bible sanitizer accepts a setting whose only identifier is a
+ // slugline (name field empty). synthesizeCanonPrompt must fall back
+ // to slugline as the identifier seed so such entries don't silently
+ // synthesize to '' and get skipped at render time.
+ const w = canonWorld();
+ w.settings.push({
+ // No name — only a slugline identifier + description.
+ slugline: "INT. OLD ARCHIVE — NIGHT",
+ description: "lantern-lit shelves of ledgers",
+ });
+ const compiled = svc.compilePrompts(w, {
+ promptMode: "canon",
+ canonSelection: { settings: "all" },
+ });
+ // Two settings now: the named Foundry City + the slugline-only Archive.
+ expect(compiled).toHaveLength(2);
+ const archive = compiled.find((c) => c.label === "INT. OLD ARCHIVE — NIGHT");
+ expect(archive).toBeTruthy();
+ expect(archive.prompt).toContain("INT. OLD ARCHIVE — NIGHT");
+ expect(archive.prompt).toContain("lantern-lit shelves of ledgers");
+ });
+
+ it("canonSelection: settings also matches by slugline", () => {
+ const w = canonWorld();
+ const compiled = svc.compilePrompts(w, {
+ promptMode: "canon",
+ canonSelection: { settings: ["EXT. FOUNDRY CITY — DAY"] },
+ });
+ expect(compiled).toHaveLength(1);
+ expect(compiled[0].label).toBe("Foundry City");
+ });
+
+ it("canonSelection: slugline matching is settings-only (characters/objects ignore stray slugline)", () => {
+ // A stray `slugline` on a character or object should NOT participate
+ // in canon-selection matching — slugline is part of the settings
+ // schema only. This guards against accidental cross-trunk selection
+ // when an upstream tool mis-tags an entry.
+ const w = {
+ ...canonWorld(),
+ characters: [
+ {
+ name: "Ghost",
+ slugline: "should-not-match-on-character",
+ physicalDescription: "spectral",
+ },
+ ],
+ objects: [
+ {
+ name: "Shard",
+ slugline: "should-not-match-on-object",
+ description: "humming crystal",
+ },
+ ],
+ };
+ const charsCompiled = svc.compilePrompts(w, {
+ promptMode: "canon",
+ canonSelection: { characters: ["should-not-match-on-character"] },
+ });
+ expect(charsCompiled).toHaveLength(0);
+ const objsCompiled = svc.compilePrompts(w, {
+ promptMode: "canon",
+ canonSelection: { objects: ["should-not-match-on-object"] },
+ });
+ expect(objsCompiled).toHaveLength(0);
+ // Sanity — name still matches.
+ const nameMatched = svc.compilePrompts(w, {
+ promptMode: "canon",
+ canonSelection: { characters: ["Ghost"], objects: ["Shard"] },
+ });
+ expect(nameMatched).toHaveLength(2);
+ });
+
+ it("entry.prompt wins over synthesized fields", () => {
+ const w = {
+ ...canonWorld(),
+ characters: [
+ {
+ name: "Mira",
+ physicalDescription: "ignored",
+ prompt: "explicit hand-authored prompt",
+ },
+ ],
+ };
+ const compiled = svc.compilePrompts(w, {
+ promptMode: "canon",
+ canonSelection: { characters: "all" },
+ });
+ expect(compiled).toHaveLength(1);
+ expect(compiled[0].prompt).toBe(
+ "moebius linework. explicit hand-authored prompt",
+ );
+ });
+
+ it("skips entries with no name and no descriptive content", () => {
+ const w = { ...canonWorld(), characters: [{}, { name: "Mira" }] };
+ const compiled = svc.compilePrompts(w, {
+ promptMode: "canon",
+ canonSelection: { characters: "all" },
+ });
+ expect(compiled).toHaveLength(1);
+ expect(compiled[0].label).toBe("Mira");
+ });
+
+ it("promptMode=all compiles variations + sheets + canon together", async () => {
+ const w = await seedWorld({
+ compositeSheets: [
+ { label: "Sheet", prompt: "clean reference sheet" },
+ ],
+ });
+ // Layer canon directly onto the persisted world for this scenario.
+ w.characters = [
+ { name: "Mira", physicalDescription: "weathered scavenger" },
+ ];
+ const compiled = svc.compilePrompts(w, {
+ promptMode: "all",
+ canonSelection: { characters: "all" },
+ });
+ // 3 variations + 1 sheet + 1 canon = 5
+ expect(compiled).toHaveLength(5);
+ expect(compiled.map((c) => c.category)).toContain("canon:characters");
+ });
+
+ it("respects batchPerVariation for canon", () => {
+ const w = canonWorld();
+ const compiled = svc.compilePrompts(w, {
+ promptMode: "canon",
+ canonSelection: { characters: ["mira"] },
+ batchPerVariation: 3,
+ });
+ expect(compiled).toHaveLength(3);
+ expect(compiled.every((c) => c.label === "Mira")).toBe(true);
+ });
+
+ it("canon promptMode without canonSelection produces no prompts", () => {
+ const w = canonWorld();
+ const compiled = svc.compilePrompts(w, { promptMode: "canon" });
+ expect(compiled).toEqual([]);
+ });
+ });
});
describe("influences", () => {