Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat: World Builder custom categories + composite reference sheets
Adam Eivy1e4e465f78f4
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 1de199a275..553898f9bb 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -2,6 +2,7 @@## Added+- **World Builder: custom categories + composite reference sheets.** The world template is no longer locked to the original five buckets (landscapes/environments/characters/structures/vehicles). The expansion prompt now asks the LLM for **5–12 categories of its choosing** in snake_case (e.g. `colonies`, `factions`, `species`, `clothing_styles`, `material_palettes`, `raider_clans`) and the editor exposes an **Add category** input plus a per-category remove button — so a "Gas-Giant Drifters costume systems" world can carry the buckets it actually needs instead of being shoehorned into "characters". A new top-level **`compositeSheets`** array stores complete reference-board prompts (up to 4000 chars each, up to 50 per world) that combine multiple buckets into one image — costume sheets, material swatches, color palette strips, fastener/accessory icon boards, etc. — and the LLM is prompted to emit 3–8 of them when the starter idea involves clothing/colonies/factions/cultures/species/vehicles. The Batch render panel gains a **Prompt set** picker (Composite sheets / Atomic variations / Everything), and successful expansion that produced any sheets auto-selects the sheets mode so the next click renders the boards. Server-side: `WORLD_CATEGORIES` is now a starter list, not a contract; `categories` zod schema is `z.record` with a 30-bucket cap and a 64-char key cap; `normalizeCategoryKey` snake-cases incoming keys (`Clothing Styles` → `clothing_styles`) on both client and server so saved worlds stay portable; `compilePrompts` accepts `promptMode` + `sheetSelection` and tags rendered sheets with `category: 'composite_sheets'`. The `extractJson` shape-detector accepts responses that have only `compositeSheets` (no variations), and the expansion logger now reports per-bucket counts plus sheet count for fast debugging. Tests cover key normalization, custom-bucket round-trip, sheet sanitization, the new prompt-mode branches in `compilePrompts`, and the route schemas for arbitrary category names.- **Search box on Media History.** `/media/history` gains a search input (top-left of the toolbar) that filters the merged image+video timeline as you type. Whitespace tokens are AND-combined (e.g. `sunset flux2 1024` matches items whose searchable haystack contains all three substrings, in any order), and the haystack covers prompt, negative prompt, model id, filename, kind, seed, dimensions, LoRA names, plus virtual tokens for `extracted frame` / `stitched` / `upscaled 2x` so the existing corner badges are reachable through the search bar. Item counts in the Images / Videos / All filter chips update against the search-scoped totals, and the empty state offers a one-click "Clear search" when nothing matches. Haystacks are precomputed once per items list (memo keyed on `items`) so each keystroke only re-runs `String.includes()`, not array-build + join + lowercase per item — keeps the UI responsive on 500+ item galleries.- **Extracted video frames carry their video's prompt.** When you click "Continue" on a video card, PortOS extracts the last frame as a PNG into the gallery — that PNG now also gets a sidecar metadata.json copying the source video's `prompt`, `negativePrompt`, `modelId`, `width`/`height`, and `seed`, plus provenance fields (`extractedFromVideoId`, `extractedFromVideoFilename`, `kind: 'extracted-frame'`). The Media History card surfaces a yellow `frame` corner badge so extracted frames are visually distinct from raw renders, and the new fields flow through the search haystack so a query like `extracted frame` (or any prompt term from the parent video) filters the gallery to those frames. Sidecar write uses `writeFile({ flag: 'wx' })` so cache-hit re-clicks are race-free and cheap; pre-existing extracted frames get backfilled on the next continue-click without re-running ffmpeg.diff --git a/client/src/pages/WorldBuilder.jsx b/client/src/pages/WorldBuilder.jsxindex 698853c82e..8719db03ee 100644--- a/client/src/pages/WorldBuilder.jsx+++ b/client/src/pages/WorldBuilder.jsx@@ -17,7 +17,7 @@ import toast from '../components/ui/Toast';import {listWorlds, getWorld, createWorld, updateWorld, deleteWorld, expandWorld,renderWorld, listWorldRuns, getProviders, WORLD_CATEGORIES,- listImageModels, getSettings,+ WORLD_CATEGORY_KEY_MAX, COMPOSITE_PROMPT_MAX, listImageModels, getSettings,} from '../services/api';import BackendChipStrip from '../components/media/BackendChipStrip';import ImageGenControls from '../components/imageGen/ImageGenControls';@@ -31,6 +31,35 @@ const CATEGORY_LABELS = {vehicles: 'Vehicles',};+const normalizeCategoryKey = (raw) => (raw || '')+ .trim()+ .toLowerCase()+ .replace(/&/g, ' and ')+ .replace(/[^a-z0-9]+/g, '_')+ .replace(/^_+|_+$/g, '')+ .replace(/_{2,}/g, '_')+ .slice(0, WORLD_CATEGORY_KEY_MAX);++const humanizeCategory = (key) => CATEGORY_LABELS[key]+ || key.replace(/_/g, ' ').replace(/\b\w/g, (ch) => ch.toUpperCase());++const ensureDraftCategories = (categories = {}) => ({+ ...Object.fromEntries(WORLD_CATEGORIES.map((c) => [c, { variations: [] }])),+ ...(categories || {}),+});++const getCategoryKeys = (categories = {}) => {+ const seen = new Set();+ const keys = [];+ for (const key of [...WORLD_CATEGORIES, ...Object.keys(categories || {})]) {+ const normalized = normalizeCategoryKey(key);+ if (!normalized || seen.has(normalized)) continue;+ seen.add(normalized);+ keys.push(normalized);+ }+ return keys;+};+// Default per-render knobs. Mirrors the Image Gen page's default chip.const DEFAULT_RENDER_OPTS = {width: 1024,@@ -41,6 +70,7 @@ const DEFAULT_RENDER_OPTS = {quantize: '8',modelId: '',mode: '',+ promptMode: 'variations',batchPerVariation: 1,};@@ -49,7 +79,8 @@ const emptyTemplate = () => ({starterPrompt: '',stylePrompt: '',negativePrompt: '',- categories: Object.fromEntries(WORLD_CATEGORIES.map((c) => [c, { variations: [] }])),+ categories: ensureDraftCategories(),+ compositeSheets: [],llm: { provider: null, model: null },});@@ -70,6 +101,7 @@ export default function WorldBuilder() {// The draft is the editable copy of the currently-selected world. New// worlds start as a draft with no id; saving creates the persisted record.const [draft, setDraft] = useState(emptyTemplate());+ const [newCategoryName, setNewCategoryName] = useState('');// Per-page render knobs. Persisted to localStorage so the user's// preferred batch size sticks across visits.@@ -133,9 +165,10 @@ export default function WorldBuilder() {if (w) {setDraft({...w,- // Ensure all five categories exist in the draft so the editor- // grid renders even if the LLM skipped one.- categories: Object.fromEntries(WORLD_CATEGORIES.map((c) => [c, w.categories?.[c] || { variations: [] }])),+ // Ensure starter buckets exist, but preserve custom buckets returned+ // by the LLM or added by the user.+ categories: ensureDraftCategories(w.categories),+ compositeSheets: w.compositeSheets || [],llm: w.llm || { provider: null, model: null },});}@@ -162,6 +195,7 @@ export default function WorldBuilder() {stylePrompt: draft.stylePrompt || '',negativePrompt: draft.negativePrompt || '',categories: draft.categories,+ compositeSheets: draft.compositeSheets || [],llm: draft.llm || {},};const result = selectedId@@ -211,11 +245,15 @@ export default function WorldBuilder() {...draft,stylePrompt: result.stylePrompt || draft.stylePrompt,negativePrompt: result.negativePrompt || draft.negativePrompt,- categories: Object.fromEntries(WORLD_CATEGORIES.map((c) => [c, result.categories?.[c] || { variations: [] }])),+ categories: ensureDraftCategories(result.categories),+ compositeSheets: result.compositeSheets || draft.compositeSheets || [],llm: result.llm || draft.llm,};setDraft(expandedDraft);- const total = WORLD_CATEGORIES.reduce((n, k) => n + (result.categories?.[k]?.variations?.length || 0), 0);+ const total = totalVariationCount(expandedDraft);+ if (expandedDraft.compositeSheets?.length) {+ setRenderOpts((r) => ({ ...r, promptMode: 'sheets' }));+ }// Auto-persist expansion if the world is already saved — otherwise the// user clicks Render and hits "No prompts to render" because the disk// copy still has empty categories. New (unsaved) drafts still need a@@ -227,6 +265,7 @@ export default function WorldBuilder() {stylePrompt: expandedDraft.stylePrompt || '',negativePrompt: expandedDraft.negativePrompt || '',categories: expandedDraft.categories,+ compositeSheets: expandedDraft.compositeSheets || [],llm: expandedDraft.llm || {},}).catch((e) => { toast.error(`Auto-save after expand failed: ${e.message}`); return null; });if (updated) {@@ -234,11 +273,11 @@ export default function WorldBuilder() {const without = prev.filter((w) => w.id !== updated.id);return [updated, ...without];});- toast.success(`Expanded into ${total} variations — saved`);+ toast.success(`Expanded into ${total} variations and ${expandedDraft.compositeSheets?.length || 0} sheets — saved`);return;}}- toast.success(`Expanded into ${total} variations — review then Save`);+ toast.success(`Expanded into ${total} variations and ${expandedDraft.compositeSheets?.length || 0} sheets — review then Save`);};const handleRender = async () => {@@ -246,9 +285,9 @@ export default function WorldBuilder() {toast.error('Save the world first');return;}- const total = totalVariationCount(draft);+ const total = renderPromptCount(draft, renderOpts.promptMode);if (!total) {- toast.error('No variations — expand the template first');+ toast.error('No prompts — expand the template first');return;}const effectiveMode = renderOpts.mode || defaultMode || undefined;@@ -267,6 +306,7 @@ export default function WorldBuilder() {guidance: numericOrUndef(renderOpts.guidance),cfgScale: numericOrUndef(renderOpts.cfgScale),quantize: renderOpts.quantize || undefined,+ promptMode: renderOpts.promptMode || 'variations',batchPerVariation: renderOpts.batchPerVariation,}).catch((e) => { toast.error(`Render failed: ${e.message}`); return null; });setRendering(false);@@ -281,6 +321,28 @@ export default function WorldBuilder() {...d,categories: { ...d.categories, [cat]: { variations } },}));+ const updateCompositeSheets = (sheets) => setDraft((d) => ({ ...d, compositeSheets: sheets }));+ const addCategory = () => {+ const key = normalizeCategoryKey(newCategoryName);+ if (!key) {+ toast.error('Use letters or numbers for the category name');+ return;+ }+ if (draft.categories?.[key]) {+ toast.error('Category already exists');+ return;+ }+ setDraft((d) => ({+ ...d,+ categories: { ...d.categories, [key]: { variations: [] } },+ }));+ setNewCategoryName('');+ };+ const removeCategory = (cat) => setDraft((d) => {+ const next = { ...d.categories };+ delete next[cat];+ return { ...d, categories: ensureDraftCategories(next) };+ });const providerLabel = (id) => providers.find((p) => p.id === id)?.name || id || '—';const providerModels = useMemo(() => {@@ -288,7 +350,10 @@ export default function WorldBuilder() {return p?.models || [];}, [providers, activeProviderId, draft.llm?.provider]);+ const categoryKeys = getCategoryKeys(draft.categories);const totalVariations = totalVariationCount(draft);+ const totalSheets = draft.compositeSheets?.length || 0;+ const renderTotal = renderPromptCount(draft, renderOpts.promptMode);return (<div className="grid grid-cols-1 lg:grid-cols-[260px_1fr] gap-4">@@ -424,7 +489,7 @@ export default function WorldBuilder() {Expand starter → variations</button><span className="text-xs text-gray-500">- {totalVariations} variation{totalVariations === 1 ? '' : 's'} across {WORLD_CATEGORIES.length} categories+ {totalVariations} variation{totalVariations === 1 ? '' : 's'} across {categoryKeys.length} categories · {totalSheets} composite sheet{totalSheets === 1 ? '' : 's'}</span></div></header>@@ -457,14 +522,46 @@ export default function WorldBuilder() {</div></section>+ <CompositeSheetsEditor+ sheets={draft.compositeSheets || []}+ onChange={updateCompositeSheets}+ />+{/* 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">+ <input+ type="text"+ value={newCategoryName}+ onChange={(e) => setNewCategoryName(e.target.value)}+ onKeyDown={(e) => { if (e.key === 'Enter') addCategory(); }}+ placeholder="colonies, factions, species"+ className="w-44 bg-port-bg border border-port-border rounded px-2 py-2 text-white text-sm focus:outline-none focus:border-port-accent"+ maxLength={WORLD_CATEGORY_KEY_MAX}+ />+ <button+ onClick={addCategory}+ disabled={!newCategoryName.trim()}+ className="px-3 py-2 bg-port-accent/15 hover:bg-port-accent/25 disabled:opacity-50 text-port-accent rounded flex items-center gap-1 min-h-[40px]"+ >+ <Plus size={14} /> Add+ </button>+ </div>+ </div>+ </section><section className="grid grid-cols-1 md:grid-cols-2 gap-3">- {WORLD_CATEGORIES.map((cat) => (+ {categoryKeys.map((cat) => (<CategoryEditorkey={cat}category={cat}variations={draft.categories?.[cat]?.variations || []}+ canRemove={!WORLD_CATEGORIES.includes(cat)}onChange={(next) => updateCategory(cat, next)}+ onRemove={() => removeCategory(cat)}/>))}</section>@@ -491,6 +588,20 @@ export default function WorldBuilder() {to enable batch render.</p>)}+ <div className="grid grid-cols-1 sm:grid-cols-3 gap-3">+ <div>+ <label className="block text-xs font-medium text-gray-400 mb-1">Prompt set</label>+ <select+ 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 sheets ({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><ImageGenControlsmode={renderOpts.mode || defaultMode || 'local'}models={imageModels}@@ -510,7 +621,7 @@ export default function WorldBuilder() {/><div className="grid grid-cols-2 sm:grid-cols-3 gap-3"><div>- <label className="block text-xs font-medium text-gray-400 mb-1">Renders per variation</label>+ <label className="block text-xs font-medium text-gray-400 mb-1">Renders per prompt</label><inputtype="number" min={1} max={20}value={renderOpts.batchPerVariation ?? 1}@@ -525,11 +636,11 @@ export default function WorldBuilder() {<div className="flex items-center gap-2 flex-wrap"><buttononClick={handleRender}- disabled={rendering || !selectedId || totalVariations === 0 || availableBackends.length === 0}+ 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 {totalVariations * (renderOpts.batchPerVariation || 1)} image{totalVariations * (renderOpts.batchPerVariation || 1) === 1 ? '' : 's'}+ 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>}@@ -565,10 +676,160 @@ export default function WorldBuilder() {}function totalVariationCount(world) {- return WORLD_CATEGORIES.reduce((n, c) => n + (world.categories?.[c]?.variations?.length || 0), 0);+ return getCategoryKeys(world.categories).reduce((n, c) => n + (world.categories?.[c]?.variations?.length || 0), 0);+}++function renderPromptCount(world, promptMode = 'variations') {+ const variations = totalVariationCount(world);+ const sheets = world.compositeSheets?.length || 0;+ if (promptMode === 'sheets') return sheets;+ if (promptMode === 'all') return variations + sheets;+ return variations;}-function CategoryEditor({ category, variations, onChange }) {+function CompositeSheetsEditor({ sheets, onChange }) {+ const [adding, setAdding] = useState(false);+ const [newLabel, setNewLabel] = useState('');+ const [newPrompt, setNewPrompt] = useState('');+ const [editIdx, setEditIdx] = useState(null);+ const [editLabel, setEditLabel] = useState('');+ const [editPrompt, setEditPrompt] = useState('');++ const addSheet = () => {+ const label = newLabel.trim();+ const prompt = newPrompt.trim();+ if (!label || !prompt) return;+ onChange([...sheets, { label: label.slice(0, 120), prompt: prompt.slice(0, COMPOSITE_PROMPT_MAX) }]);+ setNewLabel('');+ setNewPrompt('');+ setAdding(false);+ };++ const removeAt = (idx) => onChange(sheets.filter((_, i) => i !== idx));++ const startEdit = (idx, sheet) => {+ setEditIdx(idx);+ setEditLabel(sheet.label);+ setEditPrompt(sheet.prompt);+ };++ const saveEdit = () => {+ const label = editLabel.trim();+ const prompt = editPrompt.trim();+ if (!label || !prompt) return;+ const next = [...sheets];+ next[editIdx] = { label: label.slice(0, 120), prompt: prompt.slice(0, COMPOSITE_PROMPT_MAX) };+ onChange(next);+ setEditIdx(null);+ };++ 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">+ <h2 className="text-sm font-semibold text-white">+ Composite sheets+ <span className="ml-2 text-xs text-gray-500">{sheets.length}</span>+ </h2>+ <button+ onClick={() => setAdding((v) => !v)}+ className="text-xs px-2 py-1 bg-port-accent/15 hover:bg-port-accent/25 text-port-accent rounded flex items-center gap-1 min-h-[40px] sm:min-h-0"+ >+ <Plus size={12} /> Add+ </button>+ </div>+ {adding && (+ <div className="bg-port-bg border border-port-border rounded p-2 flex flex-col gap-2">+ <input+ value={newLabel}+ onChange={(e) => setNewLabel(e.target.value)}+ placeholder="Gas-Giant Drifters costume sheet"+ className="bg-port-card border border-port-border rounded px-2 py-1 text-white text-sm"+ maxLength={120}+ />+ <textarea+ value={newPrompt}+ onChange={(e) => setNewPrompt(e.target.value)}+ placeholder="Create a clean illustrated costume reference sheet..."+ className="bg-port-card border border-port-border rounded px-2 py-1 text-white text-sm"+ rows={6}+ maxLength={COMPOSITE_PROMPT_MAX}+ />+ <div className="flex items-center gap-2">+ <button+ onClick={addSheet}+ disabled={!newLabel.trim() || !newPrompt.trim()}+ className="text-xs px-2 py-1 bg-port-accent hover:bg-port-accent/90 disabled:opacity-50 text-white rounded min-h-[40px] sm:min-h-0"+ >+ Save+ </button>+ <button+ onClick={() => { setAdding(false); setNewLabel(''); setNewPrompt(''); }}+ className="text-xs px-2 py-1 bg-port-bg hover:bg-port-border text-gray-300 rounded min-h-[40px] sm:min-h-0"+ >+ Cancel+ </button>+ </div>+ </div>+ )}+ {sheets.length === 0 ? (+ <p className="text-xs text-gray-500">No composite sheets yet.</p>+ ) : (+ <ul className="flex flex-col gap-1.5 max-h-96 overflow-y-auto">+ {sheets.map((sheet, idx) => (+ <li key={`${sheet.label}-${idx}`} className="bg-port-bg border border-port-border rounded p-2 text-sm">+ {editIdx === idx ? (+ <div className="flex flex-col gap-1">+ <input+ value={editLabel}+ onChange={(e) => setEditLabel(e.target.value)}+ className="bg-port-card border border-port-border rounded px-2 py-1 text-white text-sm"+ maxLength={120}+ />+ <textarea+ value={editPrompt}+ onChange={(e) => setEditPrompt(e.target.value)}+ rows={8}+ className="bg-port-card border border-port-border rounded px-2 py-1 text-white text-sm"+ maxLength={COMPOSITE_PROMPT_MAX}+ />+ <div className="flex gap-2">+ <button onClick={saveEdit} className="text-xs px-2 py-1 bg-port-accent text-white rounded min-h-[40px] sm:min-h-0">Save</button>+ <button onClick={() => setEditIdx(null)} className="text-xs px-2 py-1 bg-port-bg text-gray-300 rounded min-h-[40px] sm:min-h-0">Cancel</button>+ </div>+ </div>+ ) : (+ <div className="flex items-start justify-between gap-2">+ <div className="flex-1 min-w-0">+ <div className="text-white font-medium truncate">{sheet.label}</div>+ <div className="text-xs text-gray-400 line-clamp-3">{sheet.prompt}</div>+ </div>+ <div className="flex items-center gap-1 shrink-0">+ <button+ onClick={() => startEdit(idx, sheet)}+ className="p-1 text-gray-400 hover:text-port-accent rounded"+ title="Edit"+ >+ <Edit3 size={14} />+ </button>+ <button+ onClick={() => removeAt(idx)}+ className="p-1 text-gray-400 hover:text-red-400 rounded"+ title="Remove"+ >+ <X size={14} />+ </button>+ </div>+ </div>+ )}+ </li>+ ))}+ </ul>+ )}+ </section>+ );+}++function CategoryEditor({ category, variations, canRemove = false, onChange, onRemove }) {const [adding, setAdding] = useState(false);const [newLabel, setNewLabel] = useState('');const [newPrompt, setNewPrompt] = useState('');@@ -611,15 +872,26 @@ function CategoryEditor({ category, variations, onChange }) {<div className="bg-port-card border border-port-border rounded p-3"><div className="flex items-center justify-between mb-2"><h3 className="text-sm font-semibold text-white capitalize">- {CATEGORY_LABELS[category] || category}+ {humanizeCategory(category)}<span className="ml-2 text-xs text-gray-500">{variations.length}</span></h3>- <button- onClick={() => setAdding((v) => !v)}- className="text-xs px-2 py-1 bg-port-accent/15 hover:bg-port-accent/25 text-port-accent rounded flex items-center gap-1 min-h-[40px] sm:min-h-0"- >- <Plus size={12} /> Add- </button>+ <div className="flex items-center gap-1">+ {canRemove && (+ <button+ onClick={onRemove}+ className="p-1 text-gray-400 hover:text-red-400 rounded"+ title="Remove category"+ >+ <Trash2 size={14} />+ </button>+ )}+ <button+ onClick={() => setAdding((v) => !v)}+ className="text-xs px-2 py-1 bg-port-accent/15 hover:bg-port-accent/25 text-port-accent rounded flex items-center gap-1 min-h-[40px] sm:min-h-0"+ >+ <Plus size={12} /> Add+ </button>+ </div></div>{adding && (<div className="bg-port-bg border border-port-border rounded p-2 mb-2 flex flex-col gap-2">@@ -712,4 +984,3 @@ function CategoryEditor({ category, variations, onChange }) {</div>);}-diff --git a/client/src/services/apiWorldBuilder.js b/client/src/services/apiWorldBuilder.jsindex cb6254fc73..12c12274bf 100644--- a/client/src/services/apiWorldBuilder.js+++ b/client/src/services/apiWorldBuilder.js@@ -1,6 +1,8 @@import { request } from './apiCore.js';export const WORLD_CATEGORIES = ['landscapes', 'environments', 'characters', 'structures', 'vehicles'];+export const WORLD_CATEGORY_KEY_MAX = 64;+export const COMPOSITE_PROMPT_MAX = 4000;export const listWorlds = () => request('/world-builder');export const getWorld = (id) => request(`/world-builder/${encodeURIComponent(id)}`);diff --git a/server/routes/worldBuilder.js b/server/routes/worldBuilder.jsindex d89d2a1d84..90a534eade 100644--- a/server/routes/worldBuilder.js+++ b/server/routes/worldBuilder.js@@ -6,7 +6,7 @@* GET /api/world-builder/:id → World* PATCH /api/world-builder/:id → World* DELETE /api/world-builder/:id → { id }- * POST /api/world-builder/expand → { stylePrompt, negativePrompt, categories, llm }+ * POST /api/world-builder/expand → { stylePrompt, negativePrompt, categories, compositeSheets, llm }* POST /api/world-builder/:id/render → { runId, collectionId, jobIds, promptCount }* GET /api/world-builder/:id/runs → Run[]*/@@ -41,12 +41,19 @@ const variationSchema = z.object({label: z.string().trim().min(1).max(svc.VARIATION_LABEL_MAX),prompt: z.string().trim().min(1).max(svc.PROMPT_FRAGMENT_MAX),});+const compositeSheetSchema = z.object({+ label: z.string().trim().min(1).max(svc.VARIATION_LABEL_MAX),+ prompt: z.string().trim().min(1).max(svc.COMPOSITE_PROMPT_MAX),+});const categoryShape = z.object({variations: z.array(variationSchema).max(svc.VARIATIONS_PER_CATEGORY_MAX),-}).optional();-const categoriesSchema = z.object(- Object.fromEntries(svc.WORLD_CATEGORIES.map((c) => [c, categoryShape])),-).partial();+});+const categoriesSchema = z.record(+ z.string().trim().min(1).max(svc.WORLD_CATEGORY_KEY_MAX),+ categoryShape,+).refine((categories) => Object.keys(categories).length <= svc.WORLD_CATEGORY_COUNT_MAX, {+ message: `categories cannot exceed ${svc.WORLD_CATEGORY_COUNT_MAX} buckets`,+});const llmSchema = z.object({provider: z.string().trim().max(80).nullable().optional(),@@ -59,6 +66,7 @@ const createSchema = z.object({stylePrompt: z.string().trim().max(svc.PROMPT_FRAGMENT_MAX).optional().default(''),negativePrompt: z.string().trim().max(svc.PROMPT_FRAGMENT_MAX).optional().default(''),categories: categoriesSchema.optional(),+ compositeSheets: z.array(compositeSheetSchema).max(svc.COMPOSITE_SHEETS_MAX).optional(),llm: llmSchema,});@@ -68,6 +76,7 @@ const patchSchema = z.object({stylePrompt: z.string().trim().max(svc.PROMPT_FRAGMENT_MAX).optional(),negativePrompt: z.string().trim().max(svc.PROMPT_FRAGMENT_MAX).optional(),categories: categoriesSchema.optional(),+ compositeSheets: z.array(compositeSheetSchema).max(svc.COMPOSITE_SHEETS_MAX).optional(),llm: llmSchema,}).refine((p) => Object.keys(p).length > 0, { message: 'patch must include at least one field' });@@ -79,9 +88,12 @@ const expandSchema = z.object({// `selection` per category: 'all' or array of variation labels.const selectionValueSchema = z.union([z.literal('all'), z.array(z.string().trim().min(1).max(svc.VARIATION_LABEL_MAX)).max(svc.VARIATIONS_PER_CATEGORY_MAX)]);-const selectionSchema = z.object(- Object.fromEntries(svc.WORLD_CATEGORIES.map((c) => [c, selectionValueSchema.optional()])),-).partial();+const selectionSchema = z.record(+ z.string().trim().min(1).max(svc.WORLD_CATEGORY_KEY_MAX),+ selectionValueSchema,+).refine((selection) => Object.keys(selection).length <= svc.WORLD_CATEGORY_COUNT_MAX, {+ message: `selection cannot exceed ${svc.WORLD_CATEGORY_COUNT_MAX} buckets`,+});const renderSchema = z.object({// Optional friendly name for the resulting collection. If omitted, server@@ -98,8 +110,10 @@ 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'),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(),});router.get('/', asyncHandler(async (_req, res) => {@@ -144,11 +158,13 @@ router.post('/:id/render', asyncHandler(async (req, res) => {const world = await svc.getWorld(req.params.id).catch((err) => { throw mapServiceError(err); });const compiled = svc.compilePrompts(world, {+ promptMode: body.promptMode,selection: body.selection,+ sheetSelection: body.sheetSelection,batchPerVariation: body.batchPerVariation,});if (!compiled.length) {- throw new ServerError('No prompts to render — add variations or expand the template first', {+ throw new ServerError('No prompts to render — add variations or composite sheets first', {status: 400, code: 'WORLD_BUILDER_EMPTY',});}diff --git a/server/routes/worldBuilder.test.js b/server/routes/worldBuilder.test.jsindex 6eba136af4..07f8004474 100644--- a/server/routes/worldBuilder.test.js+++ b/server/routes/worldBuilder.test.js@@ -30,6 +30,9 @@ vi.mock('../services/worldBuilderExpand.js', () => ({structures: { variations: [] },vehicles: { variations: [] },},+ compositeSheets: [+ { label: 'Mock costume sheet', prompt: 'mocked complete costume reference sheet with lineup, materials, fasteners, palette' },+ ],llm: { provider: 'anthropic', model: 'claude' },})),}));@@ -93,6 +96,35 @@ describe('world-builder routes', () => {);});+ it('POST / accepts dynamic world-building categories', async () => {+ const res = await request(buildApp())+ .post('/api/world-builder')+ .send({+ name: 'Colonies',+ categories: {+ colonies: { variations: [{ label: 'Canopy Symbiotes', prompt: 'leaf fiber outfit reference sheet' }] },+ raider_clans: { variations: [{ label: 'Wake Jackals', prompt: 'simple scavenger pirate kit' }] },+ },+ });+ expect(res.status).toBe(201);+ expect(res.body.categories.colonies.variations).toHaveLength(1);+ expect(res.body.categories.raider_clans.variations[0].label).toBe('Wake Jackals');+ });++ it('POST / accepts composite sheet prompts', async () => {+ const res = await request(buildApp())+ .post('/api/world-builder')+ .send({+ name: 'Sheets',+ compositeSheets: [+ { label: 'Gas-Giant Drifters sheet', prompt: 'Create a clean illustrated costume reference sheet with five figures, material swatches, fasteners, accessories, and palette strip.' },+ ],+ });+ expect(res.status).toBe(201);+ expect(res.body.compositeSheets).toHaveLength(1);+ expect(res.body.compositeSheets[0].label).toBe('Gas-Giant Drifters sheet');+ });+it('POST / rejects missing name', async () => {const res = await request(buildApp()).post('/api/world-builder')@@ -127,6 +159,7 @@ describe('world-builder routes', () => {expect(res.status).toBe(200);expect(res.body.stylePrompt).toContain('moebius scifi');expect(res.body.categories.landscapes.variations).toHaveLength(1);+ expect(res.body.compositeSheets).toHaveLength(1);expect(res.body.llm.provider).toBe('anthropic');});@@ -154,6 +187,40 @@ describe('world-builder routes', () => {expect(runs.body[0].promptCount).toBe(6);});+ it('POST /:id/render queues custom category prompts', async () => {+ const app = buildApp();+ const created = await request(app).post('/api/world-builder').send({+ name: 'Clothing',+ stylePrompt: 'moebius, clean reference sheet',+ categories: {+ clothing_styles: { variations: [{ label: 'Gas-Giant Drifters', prompt: 'buckles, clips, pressure rings' }] },+ },+ });+ const res = await request(app)+ .post(`/api/world-builder/${created.body.id}/render`)+ .send({ mode: 'local', selection: { clothing_styles: 'all' } });+ expect(res.status).toBe(200);+ expect(res.body.promptCount).toBe(1);+ expect(res.body.jobIds).toHaveLength(1);+ });++ it('POST /:id/render queues composite sheet prompts', async () => {+ const app = buildApp();+ const created = await request(app).post('/api/world-builder').send({+ name: 'Composite Clothing',+ stylePrompt: 'moebius, clean reference sheet',+ compositeSheets: [+ { label: 'Gas-Giant Drifters sheet', prompt: 'complete costume reference sheet, five figures, material swatches, pressure rings, palette strip' },+ ],+ });+ const res = await request(app)+ .post(`/api/world-builder/${created.body.id}/render`)+ .send({ mode: 'local', promptMode: 'sheets' });+ expect(res.status).toBe(200);+ expect(res.body.promptCount).toBe(1);+ expect(res.body.jobIds).toHaveLength(1);+ });+it('POST /:id/render rejects when no variations exist', async () => {const app = buildApp();const created = await request(app).post('/api/world-builder').send({ name: 'Empty' });diff --git a/server/services/worldBuilder.js b/server/services/worldBuilder.jsindex 3e82ec8edf..3b7f697af0 100644--- a/server/services/worldBuilder.js+++ b/server/services/worldBuilder.js@@ -5,8 +5,13 @@* descriptions expanded by an LLM into a structured prompt set:** - stylePrompt + negativePrompt (positive style fragment + negative prompt)- * - categories: landscapes / environments / characters / structures / vehicles+ * - categories: named prompt buckets, seeded with common world-art buckets+ * like landscapes / characters / vehicles, but open to project-specific+ * buckets like colonies, factions, species, clothing_styles, or raider_clans* (each with a list of `variations` — short prompt fragments)+ * - compositeSheets: complete board/reference-sheet prompts that combine+ * several buckets into one image, e.g. a colony costume guide with lineup,+ * materials, fasteners, accessories, and palette** From those pieces the route can compile a flat list of full prompts and* enqueue them as image-gen jobs, all tagged with the same `worldId` and@@ -33,12 +38,16 @@ export const NAME_MAX_LENGTH = 100;const MAX_RUN_JOB_IDS = 10000;export const STARTER_PROMPT_MAX = 4000;export const PROMPT_FRAGMENT_MAX = 2000;+export const COMPOSITE_PROMPT_MAX = 4000;export const VARIATION_LABEL_MAX = 120;export const VARIATIONS_PER_CATEGORY_MAX = 50;+export const COMPOSITE_SHEETS_MAX = 50;+export const WORLD_CATEGORY_KEY_MAX = 64;+export const WORLD_CATEGORY_COUNT_MAX = 30;-// Five canonical buckets the UI surfaces. Stored on the template so a-// future template type (e.g. "creatures") only needs adding here. Order-// is the user-facing display order.+// Starter buckets the UI surfaces for a fresh world. They remain for+// compatibility, but saved templates may carry any additional sanitized+// category keys the LLM or user creates.export const WORLD_CATEGORIES = Object.freeze(['landscapes','environments',@@ -52,6 +61,18 @@ const DEFAULT_STATE = { worlds: [], runs: [] };const isStr = (v) => typeof v === 'string';const trimTo = (v, max) => (isStr(v) ? v.trim().slice(0, max) : '');+export const normalizeCategoryKey = (raw) => {+ if (!isStr(raw)) return '';+ return raw+ .trim()+ .toLowerCase()+ .replace(/&/g, ' and ')+ .replace(/[^a-z0-9]+/g, '_')+ .replace(/^_+|_+$/g, '')+ .replace(/_{2,}/g, '_')+ .slice(0, WORLD_CATEGORY_KEY_MAX);+};+const sanitizeVariation = (raw) => {if (!raw || typeof raw !== 'object') return null;const label = trimTo(raw.label, VARIATION_LABEL_MAX);@@ -60,6 +81,14 @@ const sanitizeVariation = (raw) => {return { label, prompt };};+const sanitizeCompositeSheet = (raw) => {+ if (!raw || typeof raw !== 'object') return null;+ const label = trimTo(raw.label, VARIATION_LABEL_MAX);+ const prompt = trimTo(raw.prompt, COMPOSITE_PROMPT_MAX);+ if (!label || !prompt) return null;+ return { label, prompt };+};+const sanitizeCategory = (raw) => {// Per-category structure: { variations: [{ label, prompt }] }. Cap so a// runaway LLM can't blow up the world template; matches the route schema.@@ -76,6 +105,55 @@ const sanitizeCategory = (raw) => {return { variations };};+const mergeCategories = (base, next) => {+ const merged = { ...base };+ for (const [key, category] of Object.entries(next)) {+ const current = merged[key]?.variations || [];+ const incoming = category?.variations || [];+ merged[key] = { variations: [...current, ...incoming].slice(0, VARIATIONS_PER_CATEGORY_MAX) };+ }+ return merged;+};++export const sanitizeCategories = (raw = {}) => {+ const categories = Object.fromEntries(WORLD_CATEGORIES.map((key) => [key, { variations: [] }]));+ if (!raw || typeof raw !== 'object') return categories;++ let customCount = WORLD_CATEGORIES.length;+ for (const [rawKey, rawCategory] of Object.entries(raw)) {+ const key = normalizeCategoryKey(rawKey);+ if (!key) continue;+ if (!categories[key] && customCount >= WORLD_CATEGORY_COUNT_MAX) continue;+ if (!categories[key]) customCount += 1;+ Object.assign(categories, mergeCategories(categories, { [key]: sanitizeCategory(rawCategory) }));+ }+ return categories;+};++export const getWorldCategoryKeys = (categories = {}) => {+ const seen = new Set();+ const keys = [];+ for (const key of [...WORLD_CATEGORIES, ...Object.keys(categories || {})]) {+ const normalized = normalizeCategoryKey(key);+ if (!normalized || seen.has(normalized)) continue;+ seen.add(normalized);+ keys.push(normalized);+ }+ return keys;+};++export const sanitizeCompositeSheets = (raw = []) => {+ if (!Array.isArray(raw)) return [];+ const sheets = [];+ for (const sheet of raw) {+ const sanitized = sanitizeCompositeSheet(sheet);+ if (!sanitized) continue;+ sheets.push(sanitized);+ if (sheets.length >= COMPOSITE_SHEETS_MAX) break;+ }+ return sheets;+};+const sanitizeTemplate = (raw) => {if (!raw || typeof raw !== 'object') return null;if (!isStr(raw.id) || !raw.id) return null;@@ -84,10 +162,8 @@ const sanitizeTemplate = (raw) => {const starterPrompt = trimTo(raw.starterPrompt, STARTER_PROMPT_MAX);const stylePrompt = trimTo(raw.stylePrompt, PROMPT_FRAGMENT_MAX);const negativePrompt = trimTo(raw.negativePrompt, PROMPT_FRAGMENT_MAX);- const categories = {};- for (const key of WORLD_CATEGORIES) {- categories[key] = sanitizeCategory(raw.categories?.[key]);- }+ const categories = sanitizeCategories(raw.categories || {});+ const compositeSheets = sanitizeCompositeSheets(raw.compositeSheets || []);const llm = raw.llm && typeof raw.llm === 'object'? {provider: trimTo(raw.llm.provider, 80) || null,@@ -103,6 +179,7 @@ const sanitizeTemplate = (raw) => {stylePrompt,negativePrompt,categories,+ compositeSheets,llm,createdAt,updatedAt,@@ -160,6 +237,7 @@ export async function createWorld(input = {}) {stylePrompt: input.stylePrompt || '',negativePrompt: input.negativePrompt || '',categories: input.categories || {},+ compositeSheets: input.compositeSheets || [],llm: input.llm || {},createdAt: now,updatedAt: now,@@ -194,6 +272,7 @@ export async function updateWorld(id, patch = {}) {...('starterPrompt' in patch ? { starterPrompt: patch.starterPrompt } : {}),...('stylePrompt' in patch ? { stylePrompt: patch.stylePrompt } : {}),...('negativePrompt' in patch ? { negativePrompt: patch.negativePrompt } : {}),+ ...('compositeSheets' in patch ? { compositeSheets: patch.compositeSheets } : {}),categories: mergedCategories,llm: mergedLlm,updatedAt: new Date().toISOString(),@@ -245,29 +324,59 @@ export async function listRuns(worldId = null) {* batchPerVariation: how many renders per variation (1..20)*/export function compilePrompts(world, options = {}) {- if (!world || !world.categories) return [];+ if (!world) return [];+ const promptMode = ['variations', 'sheets', 'all'].includes(options.promptMode)+ ? options.promptMode+ : 'variations';const selection = options.selection && typeof options.selection === 'object'? options.selection- : Object.fromEntries(WORLD_CATEGORIES.map((c) => [c, 'all']));+ : Object.fromEntries(getWorldCategoryKeys(world.categories).map((c) => [c, 'all']));+ const normalizedSelection = {};+ for (const [key, value] of Object.entries(selection)) {+ const normalized = normalizeCategoryKey(key);+ if (normalized) normalizedSelection[normalized] = value;+ }const batchPerVariation = Math.max(1, Math.min(20, Number(options.batchPerVariation) || 1));const stylePart = world.stylePrompt?.trim();const negativePrompt = world.negativePrompt?.trim() || '';const compiled = [];- for (const category of WORLD_CATEGORIES) {- const sel = selection[category];- if (!sel) continue;- const variations = world.categories[category]?.variations || [];- const filtered = sel === 'all'- ? variations- : variations.filter((v) => Array.isArray(sel) && sel.some((s) => s.toLowerCase() === v.label.toLowerCase()));- for (const variation of filtered) {- const prompt = [stylePart, variation.prompt].filter(Boolean).join(', ');+ if (promptMode === 'variations' || promptMode === 'all') {+ for (const category of getWorldCategoryKeys(normalizedSelection)) {+ const sel = normalizedSelection[category];+ if (!sel) continue;+ const variations = world.categories?.[category]?.variations || [];+ const filtered = sel === 'all'+ ? variations+ : variations.filter((v) => Array.isArray(sel) && sel.some((s) => s.toLowerCase() === v.label.toLowerCase()));+ for (const variation of filtered) {+ const prompt = [stylePart, variation.prompt].filter(Boolean).join(', ');+ for (let i = 0; i < batchPerVariation; i += 1) {+ compiled.push({+ category,+ label: variation.label,+ prompt,+ negativePrompt,+ batchIndex: i,+ });+ }+ }+ }+ }++ if (promptMode === 'sheets' || promptMode === 'all') {+ const sheetSelection = options.sheetSelection || 'all';+ const sheets = world.compositeSheets || [];+ const filteredSheets = sheetSelection === 'all'+ ? sheets+ : sheets.filter((s) => Array.isArray(sheetSelection) && sheetSelection.some((label) => label.toLowerCase() === s.label.toLowerCase()));+ for (const sheet of filteredSheets) {+ const prompt = [stylePart, sheet.prompt].filter(Boolean).join(', ');for (let i = 0; i < batchPerVariation; i += 1) {compiled.push({- category,- label: variation.label,+ category: 'composite_sheets',+ label: sheet.label,prompt,negativePrompt,batchIndex: i,diff --git a/server/services/worldBuilder.test.js b/server/services/worldBuilder.test.jsindex 25af7c2b7d..6bf1c94730 100644--- a/server/services/worldBuilder.test.js+++ b/server/services/worldBuilder.test.js@@ -58,6 +58,31 @@ describe('worldBuilder service', () => {expect(w.categories.environments.variations).toHaveLength(0);});+ it('createWorld preserves custom world-building categories', async () => {+ const w = await seedWorld({+ categories: {+ 'Clothing Styles': { variations: [{ label: 'Rib-Cage Nomads', prompt: 'reference sheet, layered sailcloth, bone toggles' }] },+ factions: { variations: [{ label: 'Wake Jackals', prompt: 'spare raider kit, patched pressure masks' }] },+ },+ });+ expect(w.categories.clothing_styles.variations).toEqual([+ { label: 'Rib-Cage Nomads', prompt: 'reference sheet, layered sailcloth, bone toggles' },+ ]);+ expect(w.categories.factions.variations).toHaveLength(1);+ expect(w.categories.landscapes.variations).toHaveLength(0);+ });++ it('createWorld persists composite sheet prompts separately from categories', async () => {+ const w = await seedWorld({+ compositeSheets: [+ { label: 'Gas-Giant Drifters costume sheet', prompt: 'Create a clean illustrated costume reference sheet with five figures, materials swatches, fasteners, accessories, and color palette strip.' },+ ],+ });+ expect(w.compositeSheets).toEqual([+ { label: 'Gas-Giant Drifters costume sheet', prompt: 'Create a clean illustrated costume reference sheet with five figures, materials swatches, fasteners, accessories, and color palette strip.' },+ ]);+ });+it('createWorld rejects empty name', async () => {await expect(svc.createWorld({ name: '' })).rejects.toThrow(/name is required/);});@@ -99,6 +124,20 @@ describe('worldBuilder service', () => {expect(compiled[0].negativePrompt).toBe('blurry, lowres');});+ it('includes custom categories by default', async () => {+ const w = await seedWorld({+ categories: {+ colonies: { variations: [{ label: 'Canopy Symbiotes', prompt: 'leaf-fiber clothing reference sheet, sap resin closures' }] },+ },+ });+ const compiled = svc.compilePrompts(w);+ expect(compiled).toHaveLength(1);+ expect(compiled[0]).toMatchObject({+ category: 'colonies',+ label: 'Canopy Symbiotes',+ });+ });+it('respects batchPerVariation', async () => {const w = await seedWorld();const compiled = svc.compilePrompts(w, { batchPerVariation: 3 });@@ -123,6 +162,20 @@ describe('worldBuilder service', () => {expect(compiled.every((c) => c.category === 'landscapes')).toBe(true);});+ it('selection supports custom category keys', async () => {+ const w = await seedWorld({+ categories: {+ raider_clans: { variations: [+ { label: 'Wake Jackals', prompt: 'clean scavenger raider outfit board' },+ { label: 'Hull Vultures', prompt: 'pressure-ring pirate boarding gear' },+ ] },+ },+ });+ const compiled = svc.compilePrompts(w, { selection: { raider_clans: ['wake jackals'] } });+ expect(compiled).toHaveLength(1);+ expect(compiled[0].label).toBe('Wake Jackals');+ });+it('clamps batchPerVariation to 1..20', async () => {const w = await seedWorld();// 0 → 1@@ -131,6 +184,34 @@ describe('worldBuilder service', () => {const big = svc.compilePrompts(w, { batchPerVariation: 100 });expect(big).toHaveLength(60); // 3 × 20});++ it('can compile composite sheets without atomic variations', async () => {+ const w = await seedWorld({+ categories: {},+ compositeSheets: [+ { label: 'Canopy Symbiotes sheet', prompt: 'clean costume reference sheet, lineup, materials, fasteners, palette' },+ { label: 'Gas-Giant Drifters sheet', prompt: 'clean costume reference sheet, pressure collars, clips, palette' },+ ],+ });+ const compiled = svc.compilePrompts(w, { promptMode: 'sheets' });+ expect(compiled).toHaveLength(2);+ expect(compiled[0]).toMatchObject({+ category: 'composite_sheets',+ label: 'Canopy Symbiotes sheet',+ prompt: 'moebius linework, scavengers reign palette, clean costume reference sheet, lineup, materials, fasteners, palette',+ });+ });++ it('can compile atomic variations and composite sheets together', async () => {+ const w = await seedWorld({+ compositeSheets: [+ { label: 'Gas-Giant Drifters sheet', prompt: 'clean costume reference sheet, pressure collars, clips, palette' },+ ],+ });+ const compiled = svc.compilePrompts(w, { promptMode: 'all' });+ expect(compiled).toHaveLength(4); // 3 atomic variations + 1 composite+ expect(compiled.map((p) => p.category)).toContain('composite_sheets');+ });});describe('sanitizers', () => {diff --git a/server/services/worldBuilderExpand.js b/server/services/worldBuilderExpand.jsindex 457315b8ee..d11fe6f9d9 100644--- a/server/services/worldBuilderExpand.js+++ b/server/services/worldBuilderExpand.js@@ -4,7 +4,7 @@* Takes a starter prompt like:* "moebius and scavengers reign meets Prophet inspired sci fi universe"* and asks the chosen LLM to return a structured JSON blob:- * { stylePrompt, negativePrompt, categories: { landscapes: { variations: [{ label, prompt }] }, ... } }+ * { stylePrompt, negativePrompt, categories: { ... }, compositeSheets: [{ label, prompt }] }** The LLM choice is per-call: caller passes { providerId, model }. If* either is missing we fall back to the active provider / its default@@ -13,7 +13,14 @@import { executeApiRun, executeCliRun, createRun } from './runner.js';import { getActiveProvider, getProviderById } from './providers.js';-import { WORLD_CATEGORIES, PROMPT_FRAGMENT_MAX, VARIATIONS_PER_CATEGORY_MAX } from './worldBuilder.js';+import {+ WORLD_CATEGORIES,+ PROMPT_FRAGMENT_MAX,+ COMPOSITE_PROMPT_MAX,+ VARIATIONS_PER_CATEGORY_MAX,+ sanitizeCategories,+ sanitizeCompositeSheets,+} from './worldBuilder.js';import { ServerError } from '../lib/errorHandler.js';const LABEL_MAX = 80;@@ -28,8 +35,11 @@ Return a SINGLE JSON object. NO markdown, NO commentary. The object MUST have th- stylePrompt: string. A single comma-separated style fragment (lighting, color palette, render quality, artist references) that will be PREFIXED to every variation prompt. Keep under 400 characters. No subject nouns — those go in variations.- negativePrompt: string. Comma-separated tokens to avoid (e.g. "blurry, lowres, watermark, extra fingers"). Tailor to the world's aesthetic.-- categories: object with these EXACT keys:+- categories: object. Atomic reusable buckets. Use snake_case keys. Start from these common buckets when useful:${WORLD_CATEGORIES.map((c) => ` - ${c}`).join('\n')}+ Add, remove, or rename buckets to fit the user's actual world-building task. Do not force every project into the starter buckets.+ Useful extra buckets include colonies, factions, tribes, species, cultures, clothing_styles, material_palettes, fasteners_and_closures, tools, rituals, raider_clans, vehicles, settlements, and artifacts.+- compositeSheets: array. Complete, ready-to-render reference-board prompts. Each item has { "label": string, "prompt": string up to 4000 chars }. These are NOT atomic fragments; each prompt must describe one complete sheet that combines multiple buckets into a single image.Each category value is an object containing a "variations" array. Each variation has the shape { "label": string (max 80 chars), "prompt": string (max 400 chars, comma-separated tokens describing ONE specific subject in this category) }. Concrete example for one category:"landscapes": { "variations": [@@ -38,12 +48,19 @@ Each category value is an object containing a "variations" array. Each variation] }Do NOT use \`[...]\`, \`…\`, or any other placeholder/elision tokens — every array MUST contain real variation objects.+Concrete compositeSheets example:+ { "label": "Gas-Giant Drifters costume sheet", "prompt": "Create a clean illustrated costume reference sheet for Gas-Giant Drifters, a human colony living on floating platforms and balloon settlements high in a gas giant atmosphere. Show a simplified character lineup with five figures: kite child, storm scout, main hero, sky elder, and rig worker. Include material swatches for sailcloth, balloon-skin, rubberized algae fabric, salvaged foil, flex-ceramic patches, storm-glass lenses, braided tether cord, and copper wire ornament. Include fastener/accessory icons for buckles, spring clips, pressure rings, carabiner hooks, breathing collar, goggles, tether belt, strapped sky boots, and wind streamer tabs. Include a color strip: storm blue, saffron, hot coral, orange, slate gray, cream, electric cyan, copper, cloud white. Minimal readable layout, elegant negative space, light background hints of balloon platforms and storm clouds, not baroque, not hyper-detailed." }+# Rules-- Generate 6-10 variations per category. They must be visually distinct from each other but stylistically consistent with the world.+- Generate 5-12 categories total, choosing the buckets that serve the starter idea. Generate 4-10 variations per category. They must be visually distinct from each other but stylistically consistent with the world.+- Generate 3-8 compositeSheets when the starter idea involves clothing systems, colonies, factions, cultures, species, vehicles, settlements, props, or other grouped visual-design systems.- "label" is a short name a human can recognize (e.g. "Crystalline canyon basin", "Scavenger walker mech").- "prompt" describes the SUBJECT only — the stylePrompt is automatically prepended at render time, so do NOT repeat style tokens in each variation.- Do not include camera/aspect tokens; the renderer adds those.- Ground the world in the references provided. If the starter mentions specific artists, comics, films, games, or moods, weave them into stylePrompt.+- If the user asks for style sheets, reference sheets, clothing guides, materials, colonies, factions, tribes, species, or pirate/raider groups, create specific categories for the atomic facts AND create compositeSheets for the complete boards.+- For colony clothing systems, include functional details like fasteners, closures, textile/material logic, silhouettes, class/role markers, weather or pressure adaptations, and culturally specific ornamentation.+- Composite sheet prompts must include a clear board structure: title/subject, 4-6 figure lineup roles, materials swatches, fasteners/accessories icons, color palette strip, background hint, and simplicity constraints such as minimal readable layout, fewer tiny objects, clean silhouettes, not baroque, not hyper-detailed.- Output JUST the JSON object. No prose before or after.`;const isCliProvider = (provider) => provider?.type === 'cli';@@ -184,7 +201,7 @@ const extractJson = (raw) => {const candidates = findBalancedBlocks(s);if (!candidates.length) candidates.push(s);const isExpansionShape = (o) => o && typeof o === 'object'- && (typeof o.stylePrompt === 'string' || typeof o.negativePrompt === 'string' || (o.categories && typeof o.categories === 'object'));+ && (typeof o.stylePrompt === 'string' || typeof o.negativePrompt === 'string' || (o.categories && typeof o.categories === 'object') || Array.isArray(o.compositeSheets));let firstParsed;let lastErr;let lastPreview = s;@@ -216,10 +233,12 @@ const extractJson = (raw) => {const normalizeCategories = (raw) => {// The LLM occasionally returns variations as a flat array of strings or// skips the wrapping `{ variations: [...] }` object. Coerce both shapes- // here so the world template stays consistent.+ // here so the world template stays consistent. Preserve custom buckets+ // (e.g. colonies, factions, clothing_styles) instead of forcing everything+ // into the starter categories.const out = {};- for (const key of WORLD_CATEGORIES) {- const node = raw?.[key];+ const rawEntries = raw && typeof raw === 'object' ? Object.entries(raw) : [];+ for (const [key, node] of rawEntries) {let variations = [];if (Array.isArray(node)) variations = node;else if (Array.isArray(node?.variations)) variations = node.variations;@@ -240,12 +259,24 @@ const normalizeCategories = (raw) => {}).filter((v) => v.label && v.prompt),};}- return out;+ return sanitizeCategories(out);};+const normalizeCompositeSheets = (raw) => sanitizeCompositeSheets(+ Array.isArray(raw)+ ? raw.map((sheet) => {+ if (typeof sheet === 'string') {+ const trimmed = sheet.trim();+ return { label: trimmed.slice(0, LABEL_MAX), prompt: trimmed.slice(0, COMPOSITE_PROMPT_MAX) };+ }+ return sheet;+ })+ : [],+);+/*** Expand a starter prompt into a structured world template draft.- * Returns { stylePrompt, negativePrompt, categories, llm: { provider, model } }.+ * Returns { stylePrompt, negativePrompt, categories, compositeSheets, llm: { provider, model } }.** @param {object} options* @param {string} options.starterPrompt@@ -271,17 +302,18 @@ export async function expandWorldTemplate({ starterPrompt, providerId, model } =// for the full transcript.console.log(`🌍 World Builder raw response — runId=${runId} length=${raw?.length || 0}`);const parsed = extractJson(raw);- console.log(`🌍 World Builder parsed JSON — keys=[${Object.keys(parsed || {}).join(',')}] categoryKeys=[${Object.keys(parsed?.categories || {}).join(',')}]`);+ console.log(`🌍 World Builder parsed JSON — keys=[${Object.keys(parsed || {}).join(',')}] categoryKeys=[${Object.keys(parsed?.categories || {}).join(',')}] compositeSheets=${Array.isArray(parsed?.compositeSheets) ? parsed.compositeSheets.length : 0}`);const stylePrompt = typeof parsed.stylePrompt === 'string'? parsed.stylePrompt.trim().slice(0, PROMPT_FRAGMENT_MAX) : '';const negativePrompt = typeof parsed.negativePrompt === 'string'? parsed.negativePrompt.trim().slice(0, PROMPT_FRAGMENT_MAX) : '';const categories = normalizeCategories(parsed.categories || {});- const perCat = WORLD_CATEGORIES.map((k) => `${k}=${categories[k]?.variations?.length || 0}`).join(' ');- const totalVariations = WORLD_CATEGORIES.reduce((n, k) => n + (categories[k]?.variations?.length || 0), 0);- console.log(`🌍 World Builder expansion complete — runId=${runId} ${totalVariations} variations (${perCat})`);- if (totalVariations === 0) {+ const compositeSheets = normalizeCompositeSheets(parsed.compositeSheets || []);+ const perCat = Object.keys(categories).map((k) => `${k}=${categories[k]?.variations?.length || 0}`).join(' ');+ const totalVariations = Object.values(categories).reduce((n, c) => n + (c?.variations?.length || 0), 0);+ console.log(`🌍 World Builder expansion complete — runId=${runId} ${totalVariations} variations, ${compositeSheets.length} composite sheets (${perCat})`);+ if (totalVariations === 0 && compositeSheets.length === 0) {console.warn(`⚠️ World Builder expansion produced 0 variations — inspect data/runs/${runId}/output.txt for the raw LLM response`);}@@ -289,9 +321,10 @@ export async function expandWorldTemplate({ starterPrompt, providerId, model } =stylePrompt,negativePrompt,categories,+ compositeSheets,llm: { provider: provider.id, model: selectedModel || null },};}// Export for tests.-export const __testing = { extractJson, normalizeCategories, EXPANSION_PROMPT };+export const __testing = { extractJson, normalizeCategories, normalizeCompositeSheets, EXPANSION_PROMPT };diff --git a/server/services/worldBuilderExpand.test.js b/server/services/worldBuilderExpand.test.jsindex 7dac3a1665..1ee8db1b21 100644--- a/server/services/worldBuilderExpand.test.js+++ b/server/services/worldBuilderExpand.test.js@@ -2,7 +2,7 @@ import { describe, it, expect } from 'vitest';import { __testing } from './worldBuilderExpand.js';import { WORLD_CATEGORIES } from './worldBuilder.js';-const { extractJson, normalizeCategories } = __testing;+const { extractJson, normalizeCategories, normalizeCompositeSheets, EXPANSION_PROMPT } = __testing;describe('worldBuilderExpand.extractJson', () => {it('parses a raw JSON object', () => {@@ -162,13 +162,15 @@ describe('worldBuilderExpand.normalizeCategories', () => {]);});- it('ignores unknown categories not in WORLD_CATEGORIES', () => {+ it('preserves custom categories beyond WORLD_CATEGORIES', () => {const out = normalizeCategories({landscapes: { variations: [{ label: 'A', prompt: 'a' }] },- bogus: { variations: [{ label: 'X', prompt: 'x' }] },+ 'Raider / Pirate Clans': { variations: [{ label: 'Wake Jackals', prompt: 'spare moebius scavenger raiders' }] },});expect(out.landscapes.variations).toHaveLength(1);- expect(out.bogus).toBeUndefined();+ expect(out.raider_pirate_clans.variations).toEqual([+ { label: 'Wake Jackals', prompt: 'spare moebius scavenger raiders' },+ ]);});it('treats a non-object category as empty variations (not a crash)', () => {@@ -176,3 +178,38 @@ describe('worldBuilderExpand.normalizeCategories', () => {expect(out.characters).toEqual({ variations: [] });});});++describe('worldBuilderExpand.normalizeCompositeSheets', () => {+ it('keeps complete composite reference-sheet prompts', () => {+ const out = normalizeCompositeSheets([+ {+ label: 'Gas-Giant Drifters costume sheet',+ prompt: 'Create a clean illustrated costume reference sheet with five figures, material swatches, fasteners, accessories, color palette strip, and simple floating-platform background.',+ },+ ]);+ expect(out).toEqual([+ {+ label: 'Gas-Giant Drifters costume sheet',+ prompt: 'Create a clean illustrated costume reference sheet with five figures, material swatches, fasteners, accessories, color palette strip, and simple floating-platform background.',+ },+ ]);+ });++ it('coerces string sheets into label/prompt pairs', () => {+ const out = normalizeCompositeSheets(['Canopy Symbiotes reference board']);+ expect(out).toEqual([+ { label: 'Canopy Symbiotes reference board', prompt: 'Canopy Symbiotes reference board' },+ ]);+ });+});++describe('worldBuilderExpand.EXPANSION_PROMPT', () => {+ it('allows dynamic world-building buckets and reference-sheet domains', () => {+ expect(EXPANSION_PROMPT).toContain('Add, remove, or rename buckets');+ expect(EXPANSION_PROMPT).toContain('colonies, factions, tribes, species');+ expect(EXPANSION_PROMPT).toContain('clothing guides');+ expect(EXPANSION_PROMPT).toContain('raider_clans');+ expect(EXPANSION_PROMPT).toContain('compositeSheets');+ expect(EXPANSION_PROMPT).toContain('materials swatches');+ });+});