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
Work building I want the media gen section to have a world building page that will take a simple st (#211)
[._.]/ Adam Eivy6a6a90ea07fd
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 50303a97d6..4cc60e2f47 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -2,8 +2,8 @@## Added+- **World Builder for Media Gen.** A new `Media Gen → World Builder` tab (`/media/world-builder`) takes a one-line starter prompt — e.g. "moebius and scavengers reign meets Prophet inspired sci fi universe" — and asks the LLM of your choice to expand it into a structured prompt set: a positive `stylePrompt` prefix, a `negativePrompt`, and 6–10 variations across five canonical buckets (landscapes, environments, characters, structures, vehicles). You can edit any field, save the world, then kick off a batch render that compiles `stylePrompt + variation.prompt` for every selected bucket and queues them through the existing image-gen pipeline (local mflux or Codex; external SD-API not supported for batches). Each batch lands in an auto-named Media Collection ("World: <name> — <timestamp>") so the renders stay grouped with the template that produced them. Worlds support full CRUD, the LLM provider/model is per-template (falls back to active provider), and runs are logged with deep-links into the resulting collection. Backed by `server/services/worldBuilder.js` (storage + prompt compilation), `server/services/worldBuilderExpand.js` (LLM call), `server/routes/worldBuilder.js` (REST surface), and `server/services/worldBuilderCollectionHook.js` (hooks media-job completion → collection assignment). State persists in `data/world-builder.json`. 20 new tests cover sanitizers, compile-prompts logic, and the route surface.- **Workflow tab in Chief of Staff with canonical project-maintenance ordering.** A new `/cos/workflow` page (and a `Workflow` tab in the CoS panel) renders the full set of scheduled tasks and autonomous jobs as a left-to-right pipeline grouped into seven canonical stages — Hygiene → Review → Plan → Audit → Build → Report → Ambient — so it's obvious which work happens before which. Each card surfaces its own schedule, last-run time, run count, enabled state, and live "due / waiting / disabled / waiting-on-dependencies" badge, plus inline `runAfter` arrows showing hard prerequisites. Backed by a new `GET /api/cos/workflow` endpoint and `server/services/workflow.js` with stage definitions, gate state for jobs, and dependency edges. Two default `runAfter` wirings ship with this: `do-replan` runs after `pr-reviewer` and `branch-cleanup` (so the plan reflects merged reality), and `feature-ideas` runs after `do-replan` (so new feature work lands on a fresh plan). Both can be overridden per task or per app from the existing Schedule tab.-- **Dismissible AI Recommendations on the Learning tab.** Each recommendation in the Chief of Staff Learning Analytics panel now has an X to dismiss it. Dismissals persist to `data/cos/dismissed-recommendations.json` and are filtered out of future loads. For count-based alerts (e.g., "unknown errors occurred 74 times"), the dismissal records the count snapshot and only re-surfaces if the count grows materially worse (≥1.5× and at least +20). Rate-based recommendations stay dismissed until restored. A "Show dismissed" expander lets you restore individual entries or clear them all.## Fixeddiff --git a/client/src/App.jsx b/client/src/App.jsxindex c0e401eef4..5c4e4e15fd 100644--- a/client/src/App.jsx+++ b/client/src/App.jsx@@ -50,6 +50,7 @@ const MediaHistory = lazyWithReload(() => import('./pages/MediaHistory'));const MediaCollections = lazyWithReload(() => import('./pages/MediaCollections'));const MediaCollectionDetail = lazyWithReload(() => import('./pages/MediaCollectionDetail'));const MediaModels = lazyWithReload(() => import('./pages/MediaModels'));+const WorldBuilder = lazyWithReload(() => import('./pages/WorldBuilder'));const VideoTimeline = lazyWithReload(() => import('./pages/VideoTimeline'));const VideoTimelineEditor = lazyWithReload(() => import('./pages/VideoTimelineEditor'));const CreativeDirector = lazyWithReload(() => import('./pages/CreativeDirector'));@@ -202,6 +203,7 @@ export default function App() {<Route path="timeline" element={<VideoTimeline />} /><Route path="timeline/:projectId" element={<VideoTimelineEditor />} /><Route path="models" element={<MediaModels />} />+ <Route path="world-builder" element={<WorldBuilder />} /></Route><Route path="image-gen" element={<RedirectWithSearch to="/media/image" />} /><Route path="video-gen" element={<RedirectWithSearch to="/media/video" />} />diff --git a/client/src/pages/MediaGen.jsx b/client/src/pages/MediaGen.jsxindex 4c183fd1f3..f2226c5e69 100644--- a/client/src/pages/MediaGen.jsx+++ b/client/src/pages/MediaGen.jsx@@ -1,9 +1,10 @@import { useNavigate, useLocation, Outlet } from 'react-router-dom';-import { Layers, Image as ImageIcon, Film, History, HardDrive, Scissors, FolderOpen, Clapperboard, ListOrdered } from 'lucide-react';+import { Layers, Image as ImageIcon, Film, History, HardDrive, Scissors, FolderOpen, Clapperboard, ListOrdered, Globe2 } from 'lucide-react';const TABS = [{ id: 'image', label: 'Image', icon: ImageIcon },{ id: 'video', label: 'Video', icon: Film },+ { id: 'world-builder', label: 'World Builder', icon: Globe2 },{ id: 'timeline', label: 'Timeline', icon: Scissors },{ id: 'creative-director', label: 'Creative Director', icon: Clapperboard },{ id: 'queue', label: 'Render Queue', icon: ListOrdered },diff --git a/client/src/pages/WorldBuilder.jsx b/client/src/pages/WorldBuilder.jsxnew file mode 100644index 0000000000..fe9ccf8e08--- /dev/null+++ b/client/src/pages/WorldBuilder.jsx@@ -0,0 +1,651 @@+/**+ * World Builder page (Media Gen → World Builder).+ *+ * Lets the user describe a universe in one starter prompt, expand it into a+ * full set of style + per-category variation prompts via the LLM of their+ * choice, edit/save the template, and kick off a batch of image renders+ * that all land in a single auto-named collection.+ */++import { useEffect, useMemo, useState } from 'react';+import { Link } from 'react-router-dom';+import {+ Globe2, Plus, Trash2, Sparkles, Wand2, Loader2, Save, FolderOpen,+ Edit3, X,+} from 'lucide-react';+import toast from '../components/ui/Toast';+import {+ listWorlds, getWorld, createWorld, updateWorld, deleteWorld, expandWorld,+ renderWorld, listWorldRuns, getProviders, WORLD_CATEGORIES,+} from '../services/api';++const CATEGORY_LABELS = {+ landscapes: 'Landscapes',+ environments: 'Environments',+ characters: 'Characters',+ structures: 'Structures',+ vehicles: 'Vehicles',+};++// Default per-render knobs. Mirrors the Image Gen page's default chip.+const DEFAULT_RENDER_OPTS = {+ width: 1024,+ height: 1024,+ steps: 30,+ cfgScale: 7,+ batchPerVariation: 1,+};++const emptyTemplate = () => ({+ name: '',+ starterPrompt: '',+ stylePrompt: '',+ negativePrompt: '',+ categories: Object.fromEntries(WORLD_CATEGORIES.map((c) => [c, { variations: [] }])),+ llm: { provider: null, model: null },+});++export default function WorldBuilder() {+ const [worlds, setWorlds] = useState([]);+ const [selectedId, setSelectedId] = useState(null);+ const [loading, setLoading] = useState(true);+ const [saving, setSaving] = useState(false);+ const [expanding, setExpanding] = useState(false);+ const [rendering, setRendering] = useState(false);+ const [providers, setProviders] = useState([]);+ const [activeProviderId, setActiveProviderId] = useState(null);++ // 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());++ // Per-page render knobs. Persisted to localStorage so the user's+ // preferred batch size sticks across visits.+ const [renderOpts, setRenderOpts] = useState(() => {+ const saved = localStorage.getItem('worldBuilder.renderOpts');+ if (saved) {+ try { return { ...DEFAULT_RENDER_OPTS, ...JSON.parse(saved) }; } catch { /* fall through */ }+ }+ return DEFAULT_RENDER_OPTS;+ });+ useEffect(() => {+ localStorage.setItem('worldBuilder.renderOpts', JSON.stringify(renderOpts));+ }, [renderOpts]);++ const [runs, setRuns] = useState([]);++ // Two-click delete: first click flips this to the world id; a second+ // click within the live render confirms. Avoids window.confirm per+ // CLAUDE.md UI Patterns.+ const [pendingDeleteId, setPendingDeleteId] = useState(null);++ const refresh = async () => {+ setLoading(true);+ const [list, provData] = await Promise.all([+ listWorlds().catch(() => []),+ getProviders().catch(() => ({ providers: [] })),+ ]);+ setWorlds(list);+ setProviders(provData.providers || []);+ setActiveProviderId(provData.activeProvider || null);+ setLoading(false);+ };++ useEffect(() => { refresh(); }, []);++ // Whenever the selection changes, deep-load that world (for runs) and+ // hydrate the draft.+ useEffect(() => {+ setPendingDeleteId(null);+ if (!selectedId) {+ setDraft(emptyTemplate());+ setRuns([]);+ return;+ }+ let cancelled = false;+ Promise.all([+ getWorld(selectedId).catch(() => null),+ listWorldRuns(selectedId).catch(() => []),+ ]).then(([w, r]) => {+ if (cancelled) return;+ 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: [] }])),+ llm: w.llm || { provider: null, model: null },+ });+ }+ setRuns(r);+ });+ return () => { cancelled = true; };+ }, [selectedId]);++ const handleNew = () => {+ setSelectedId(null);+ setDraft(emptyTemplate());+ setRuns([]);+ };++ const handleSave = async () => {+ if (!draft.name?.trim()) {+ toast.error('Name is required');+ return;+ }+ setSaving(true);+ const payload = {+ name: draft.name.trim(),+ starterPrompt: draft.starterPrompt || '',+ stylePrompt: draft.stylePrompt || '',+ negativePrompt: draft.negativePrompt || '',+ categories: draft.categories,+ llm: draft.llm || {},+ };+ const result = selectedId+ ? await updateWorld(selectedId, payload).catch((e) => { toast.error(`Save failed: ${e.message}`); return null; })+ : await createWorld(payload).catch((e) => { toast.error(`Save failed: ${e.message}`); return null; });+ setSaving(false);+ if (result) {+ toast.success(selectedId ? 'World updated' : 'World created');+ setWorlds((prev) => {+ const without = prev.filter((w) => w.id !== result.id);+ return [result, ...without];+ });+ setSelectedId(result.id);+ }+ };++ const handleDelete = async () => {+ if (!selectedId) return;+ if (pendingDeleteId !== selectedId) {+ setPendingDeleteId(selectedId);+ toast(`Click delete again to confirm — "${draft.name}" will be removed`, { icon: '⚠️' });+ return;+ }+ const id = selectedId;+ await deleteWorld(id).catch((e) => toast.error(`Delete failed: ${e.message}`));+ setWorlds((prev) => prev.filter((w) => w.id !== id));+ setSelectedId(null);+ setDraft(emptyTemplate());+ setPendingDeleteId(null);+ toast.success('World deleted');+ };++ const handleExpand = async () => {+ if (!draft.starterPrompt?.trim()) {+ toast.error('Add a starter prompt to expand');+ return;+ }+ setExpanding(true);+ const result = await expandWorld({+ starterPrompt: draft.starterPrompt,+ providerId: draft.llm?.provider || undefined,+ model: draft.llm?.model || undefined,+ }).catch((e) => { toast.error(`Expansion failed: ${e.message}`); return null; });+ setExpanding(false);+ if (!result) return;+ setDraft((d) => ({+ ...d,+ stylePrompt: result.stylePrompt || d.stylePrompt,+ negativePrompt: result.negativePrompt || d.negativePrompt,+ categories: Object.fromEntries(WORLD_CATEGORIES.map((c) => [c, result.categories?.[c] || { variations: [] }])),+ llm: result.llm || d.llm,+ }));+ const total = WORLD_CATEGORIES.reduce((n, k) => n + (result.categories?.[k]?.variations?.length || 0), 0);+ toast.success(`Expanded into ${total} variations — review then Save`);+ };++ const handleRender = async () => {+ if (!selectedId) {+ toast.error('Save the world first');+ return;+ }+ const total = totalVariationCount(draft);+ if (!total) {+ toast.error('No variations — expand the template first');+ return;+ }+ setRendering(true);+ const result = await renderWorld(selectedId, {+ mode: renderOpts.mode || undefined,+ modelId: renderOpts.modelId || undefined,+ width: renderOpts.width,+ height: renderOpts.height,+ steps: renderOpts.steps,+ cfgScale: renderOpts.cfgScale,+ batchPerVariation: renderOpts.batchPerVariation,+ }).catch((e) => { toast.error(`Render failed: ${e.message}`); return null; });+ setRendering(false);+ if (!result) return;+ toast.success(`Queued ${result.promptCount} renders → "${result.collectionName}"`);+ const updated = await listWorldRuns(selectedId).catch(() => runs);+ setRuns(updated);+ };++ const updateDraft = (patch) => setDraft((d) => ({ ...d, ...patch }));+ const updateCategory = (cat, variations) => setDraft((d) => ({+ ...d,+ categories: { ...d.categories, [cat]: { variations } },+ }));++ const providerLabel = (id) => providers.find((p) => p.id === id)?.name || id || '—';+ const providerModels = useMemo(() => {+ const p = providers.find((x) => x.id === draft.llm?.provider) || providers.find((x) => x.id === activeProviderId);+ return p?.models || [];+ }, [providers, activeProviderId, draft.llm?.provider]);++ const totalVariations = totalVariationCount(draft);++ return (+ <div className="grid grid-cols-1 lg:grid-cols-[260px_1fr] gap-4">+ {/* Sidebar — world list */}+ <aside className="bg-port-card border border-port-border rounded p-3 flex flex-col gap-2 min-h-[60vh]">+ <div className="flex items-center justify-between">+ <h2 className="text-sm font-semibold text-white flex items-center gap-2">+ <Globe2 size={16} className="text-port-accent" /> Worlds+ </h2>+ <button+ onClick={handleNew}+ 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"+ title="New world"+ >+ <Plus size={14} /> New+ </button>+ </div>+ {loading ? (+ <p className="text-xs text-gray-500">Loading…</p>+ ) : worlds.length === 0 ? (+ <p className="text-xs text-gray-500">No worlds yet — click <span className="text-port-accent">New</span> to start.</p>+ ) : (+ <ul className="flex flex-col gap-1 overflow-y-auto">+ {worlds.map((w) => {+ const active = w.id === selectedId;+ return (+ <li key={w.id}>+ <button+ onClick={() => setSelectedId(w.id)}+ className={`w-full text-left px-2 py-2 rounded text-sm transition-colors min-h-[40px] ${+ active+ ? 'bg-port-accent/15 text-port-accent border border-port-accent/40'+ : 'text-gray-300 hover:bg-port-bg border border-transparent'+ }`}+ >+ <div className="font-medium truncate">{w.name}</div>+ <div className="text-[11px] text-gray-500 truncate">{w.starterPrompt || 'No starter prompt'}</div>+ </button>+ </li>+ );+ })}+ </ul>+ )}+ </aside>++ {/* Editor */}+ <section className="flex flex-col gap-4">+ <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 && (+ <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>+ <label className="text-xs text-gray-400 mb-1 block">Starter idea</label>+ <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 className="text-xs text-gray-400 mb-1 block">LLM for expansion</label>+ <select+ // 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]"+ >+ <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 || !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} />}+ Expand starter → variations+ </button>+ <span className="text-xs text-gray-500">+ {totalVariations} variation{totalVariations === 1 ? '' : 's'} across {WORLD_CATEGORIES.length} categories+ </span>+ </div>+ </header>++ {/* Style template */}+ <section className="bg-port-card border border-port-border rounded p-4 grid grid-cols-1 md:grid-cols-2 gap-3">+ <div>+ <label className="text-xs text-gray-400 mb-1 block flex items-center gap-1">+ <Sparkles size={12} /> Style prompt (prepended to every variation)+ </label>+ <textarea+ value={draft.stylePrompt}+ onChange={(e) => updateDraft({ stylePrompt: e.target.value })}+ placeholder="moebius linework, scavengers reign palette, oil-on-canvas grain, cinematic lighting…"+ 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={4}+ maxLength={2000}+ />+ </div>+ <div>+ <label className="text-xs text-gray-400 mb-1 block">Negative prompt</label>+ <textarea+ value={draft.negativePrompt}+ onChange={(e) => updateDraft({ negativePrompt: e.target.value })}+ placeholder="blurry, lowres, watermark, extra fingers…"+ 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={4}+ maxLength={2000}+ />+ </div>+ </section>++ {/* Categories */}+ <section className="grid grid-cols-1 md:grid-cols-2 gap-3">+ {WORLD_CATEGORIES.map((cat) => (+ <CategoryEditor+ key={cat}+ category={cat}+ variations={draft.categories?.[cat]?.variations || []}+ onChange={(next) => updateCategory(cat, next)}+ />+ ))}+ </section>++ {/* Render controls */}+ <section className="bg-port-card border border-port-border rounded p-4 flex flex-col gap-3">+ <h2 className="text-sm font-semibold text-white flex items-center gap-2">+ <FolderOpen size={16} className="text-port-accent" /> Batch render+ </h2>+ <div className="grid grid-cols-2 md:grid-cols-5 gap-2">+ <NumberField label="Width" value={renderOpts.width} min={64} max={2048} onChange={(v) => setRenderOpts({ ...renderOpts, width: v })} />+ <NumberField label="Height" value={renderOpts.height} min={64} max={2048} onChange={(v) => setRenderOpts({ ...renderOpts, height: v })} />+ <NumberField label="Steps" value={renderOpts.steps} min={1} max={150} onChange={(v) => setRenderOpts({ ...renderOpts, steps: v })} />+ <NumberField label="CFG" value={renderOpts.cfgScale} min={0} max={30} step={0.5} onChange={(v) => setRenderOpts({ ...renderOpts, cfgScale: v })} />+ <NumberField label="Per-variation" value={renderOpts.batchPerVariation} min={1} max={20} onChange={(v) => setRenderOpts({ ...renderOpts, batchPerVariation: v })} />+ </div>+ <div className="flex items-center gap-2 flex-wrap">+ <select+ value={renderOpts.mode || ''}+ onChange={(e) => setRenderOpts({ ...renderOpts, mode: e.target.value || undefined })}+ className="bg-port-bg border border-port-border rounded px-2 py-2 text-white text-sm min-h-[40px]"+ >+ <option value="">Default backend</option>+ <option value="local">Local (mflux)</option>+ <option value="codex">Codex</option>+ </select>+ <button+ onClick={handleRender}+ disabled={rendering || !selectedId || totalVariations === 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'}+ </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>+ );+}++function totalVariationCount(world) {+ return WORLD_CATEGORIES.reduce((n, c) => n + (world.categories?.[c]?.variations?.length || 0), 0);+}++function CategoryEditor({ category, variations, 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 addVariation = () => {+ const label = newLabel.trim();+ const prompt = newPrompt.trim();+ if (!label || !prompt) return;+ onChange([...variations, { label: label.slice(0, 120), prompt: prompt.slice(0, 2000) }]);+ setNewLabel('');+ setNewPrompt('');+ setAdding(false);+ };++ const removeAt = (idx) => onChange(variations.filter((_, i) => i !== idx));++ const startEdit = (idx, v) => {+ setEditIdx(idx);+ setEditLabel(v.label);+ setEditPrompt(v.prompt);+ };++ const saveEdit = () => {+ const label = editLabel.trim();+ const prompt = editPrompt.trim();+ // Mirror addVariation()'s validation — server-side sanitize would drop+ // a blank entry on save/reload, so refuse rather than store ghost rows+ // the user can't see why they vanished.+ if (!label || !prompt) return;+ const next = [...variations];+ next[editIdx] = { label: label.slice(0, 120), prompt: prompt.slice(0, 2000) };+ onChange(next);+ setEditIdx(null);+ };++ return (+ <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}+ <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>+ {adding && (+ <div className="bg-port-bg border border-port-border rounded p-2 mb-2 flex flex-col gap-2">+ <input+ value={newLabel}+ onChange={(e) => setNewLabel(e.target.value)}+ placeholder="Label (e.g. Crystalline canyon basin)"+ 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="Prompt fragment (subject only)"+ className="bg-port-card border border-port-border rounded px-2 py-1 text-white text-sm"+ rows={2}+ maxLength={2000}+ />+ <div className="flex items-center gap-2">+ <button+ onClick={addVariation}+ 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>+ )}+ {variations.length === 0 ? (+ <p className="text-xs text-gray-500">No variations yet — expand the starter prompt or add one manually.</p>+ ) : (+ <ul className="flex flex-col gap-1.5 max-h-72 overflow-y-auto">+ {variations.map((v, idx) => (+ <li key={`${v.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={3}+ className="bg-port-card border border-port-border rounded px-2 py-1 text-white text-sm"+ maxLength={2000}+ />+ <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">{v.label}</div>+ <div className="text-xs text-gray-400 line-clamp-2">{v.prompt}</div>+ </div>+ <div className="flex items-center gap-1 shrink-0">+ <button+ onClick={() => startEdit(idx, v)}+ 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>+ )}+ </div>+ );+}++function NumberField({ label, value, min, max, step = 1, onChange }) {+ return (+ <label className="flex flex-col">+ <span className="text-xs text-gray-400 mb-1">{label}</span>+ <input+ type="number"+ value={value ?? ''}+ min={min}+ max={max}+ step={step}+ onChange={(e) => {+ const raw = e.target.value;+ if (raw === '') { onChange(undefined); return; }+ const n = Number(raw);+ if (Number.isFinite(n)) onChange(n);+ }}+ className="bg-port-bg border border-port-border rounded px-2 py-1.5 text-white text-sm focus:outline-none focus:border-port-accent min-h-[40px]"+ />+ </label>+ );+}diff --git a/client/src/services/api.js b/client/src/services/api.jsindex ca98b00812..4fc8c59f2b 100644--- a/client/src/services/api.js+++ b/client/src/services/api.js@@ -39,6 +39,7 @@ export * from './apiAsk.js';export * from './apiImageVideo.js';export * from './apiMediaJobs.js';export * from './apiWritersRoom.js';+export * from './apiWorldBuilder.js';// Default export for simplified imports (get/post/put/delete helpers)export { default } from './apiCore.js';diff --git a/client/src/services/apiWorldBuilder.js b/client/src/services/apiWorldBuilder.jsnew file mode 100644index 0000000000..cb6254fc73--- /dev/null+++ b/client/src/services/apiWorldBuilder.js@@ -0,0 +1,32 @@+import { request } from './apiCore.js';++export const WORLD_CATEGORIES = ['landscapes', 'environments', 'characters', 'structures', 'vehicles'];++export const listWorlds = () => request('/world-builder');+export const getWorld = (id) => request(`/world-builder/${encodeURIComponent(id)}`);++export const createWorld = (data) => request('/world-builder', {+ method: 'POST',+ body: JSON.stringify(data),+});++export const updateWorld = (id, patch) => request(`/world-builder/${encodeURIComponent(id)}`, {+ method: 'PATCH',+ body: JSON.stringify(patch),+});++export const deleteWorld = (id) => request(`/world-builder/${encodeURIComponent(id)}`, {+ method: 'DELETE',+});++export const expandWorld = ({ starterPrompt, providerId, model } = {}) => request('/world-builder/expand', {+ method: 'POST',+ body: JSON.stringify({ starterPrompt, providerId, model }),+});++export const renderWorld = (id, options) => request(`/world-builder/${encodeURIComponent(id)}/render`, {+ method: 'POST',+ body: JSON.stringify(options || {}),+});++export const listWorldRuns = (id) => request(`/world-builder/${encodeURIComponent(id)}/runs`);diff --git a/server/index.js b/server/index.jsindex 6a202fecfb..451f24be6a 100644--- a/server/index.js+++ b/server/index.js@@ -86,6 +86,8 @@ import videoTimelineRoutes from './routes/videoTimeline.js';import mediaJobsRoutes from './routes/mediaJobs.js';import creativeDirectorRoutes from './routes/creativeDirector.js';import writersRoomRoutes from './routes/writersRoom.js';+import worldBuilderRoutes from './routes/worldBuilder.js';+import { initWorldBuilderCollectionHook } from './services/worldBuilderCollectionHook.js';import { initMediaJobQueue } from './services/mediaJobQueue/index.js';import { recoverInFlightProjects } from './services/creativeDirector/recovery.js';import imageVideoModelsRoutes from './routes/imageVideoModels.js';@@ -327,6 +329,7 @@ app.use('/api/video-timeline', videoTimelineRoutes);app.use('/api/media-jobs', mediaJobsRoutes);app.use('/api/creative-director', creativeDirectorRoutes);app.use('/api/writers-room', writersRoomRoutes);+app.use('/api/world-builder', worldBuilderRoutes);app.use('/api/image-video/models', imageVideoModelsRoutes);// AUTOMATIC1111-compatible surface for tailnet clients — gated by// settings.imageGen.expose.a1111 so it returns 403 unless the user opted in.@@ -458,6 +461,11 @@ app.use(errorMiddleware);ensureSelf().then(() => initSyncLog()).then(() => initMediaJobQueue())+ .then(() => {+ // World Builder needs the media job queue running before it can listen+ // for `completed` events — so initialize the hook here.+ initWorldBuilderCollectionHook();+ }).then(() => {// Fire-and-forget — resume any Creative Director projects that were mid-// flight when the server died. The queue reload above just reclassifieddiff --git a/server/lib/navManifest.js b/server/lib/navManifest.jsindex f9b8bc5aa7..1f239c2460 100644--- a/server/lib/navManifest.js+++ b/server/lib/navManifest.js@@ -19,6 +19,7 @@ export const NAV_COMMANDS = [{ id: 'nav.media.queue', path: '/media/queue', label: 'Render Queue', section: 'Create', aliases: ['render-queue', 'queue', 'media-queue', 'media-jobs'], keywords: ['render', 'queue', 'pending', 'jobs', 'pipeline'] },{ id: 'nav.media.timeline', path: '/media/timeline', label: 'Timeline', section: 'Create', aliases: ['timeline', 'video-timeline', 'editor'], keywords: ['edit', 'trim', 'composite', 'stitch', 'cut', 'compose'] },{ id: 'nav.media.models', path: '/media/models', label: 'Media Models', section: 'Create', aliases: ['media-models', 'image-models', 'video-models', 'huggingface', 'loras'], keywords: ['hf cache', 'lora', 'model storage', 'disk'] },+ { id: 'nav.media.world-builder', path: '/media/world-builder', label: 'World Builder', section: 'Create', aliases: ['world-builder', 'worldbuilder', 'worldbuild', 'world', 'universe', 'lore'], keywords: ['style template', 'sci-fi', 'fantasy', 'concept art', 'batch render', 'variations'] },{ id: 'nav.media.settings', path: '/media/image?settings=1', label: 'Media Gen Settings', section: 'Create', aliases: ['media-settings', 'image-gen-settings', 'sd-settings', 'video-gen-settings'] },{ id: 'nav.writers-room', path: '/writers-room', label: 'Writers Room', section: 'Create', aliases: ['writers-room', 'writersroom', 'writer', 'write', 'studio', 'novel'], keywords: ['prose', 'screenplay', 'story', 'draft', 'manuscript', 'literary', 'novel', 'short story'] },{ id: 'nav.settings.prompts', path: '/prompts', label: 'Prompts', section: 'Settings', aliases: ['prompts'] },diff --git a/server/routes/worldBuilder.js b/server/routes/worldBuilder.jsnew file mode 100644index 0000000000..9c9244fc1b--- /dev/null+++ b/server/routes/worldBuilder.js@@ -0,0 +1,273 @@+/**+ * World Builder Routes+ *+ * GET /api/world-builder → World[]+ * POST /api/world-builder → World+ * 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/:id/render → { runId, collectionId, jobIds, promptCount }+ * GET /api/world-builder/:id/runs → Run[]+ */++import { Router } from 'express';+import { z } from 'zod';+import { randomUUID } from 'crypto';+import { asyncHandler, ServerError } from '../lib/errorHandler.js';+import { validateRequest } from '../lib/validation.js';+import * as svc from '../services/worldBuilder.js';+import { expandWorldTemplate } from '../services/worldBuilderExpand.js';+import { enqueueJob } from '../services/mediaJobQueue/index.js';+import { getSettings } from '../services/settings.js';+import { createCollection, NAME_MAX_LENGTH as COLLECTION_NAME_MAX } from '../services/mediaCollections.js';+import { getImageModels, isFlux2 } from '../lib/mediaModels.js';++const router = Router();++const SERVICE_ERROR_STATUS = {+ [svc.ERR_NOT_FOUND]: 404,+ [svc.ERR_VALIDATION]: 400,+};++const mapServiceError = (err) => {+ const status = SERVICE_ERROR_STATUS[err?.code];+ if (status) return new ServerError(err.message, { status, code: err.code });+ return err;+};++// ---- shared zod fragments ----+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 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 llmSchema = z.object({+ provider: z.string().trim().max(80).nullable().optional(),+ model: z.string().trim().max(200).nullable().optional(),+}).optional();++const createSchema = z.object({+ name: z.string().trim().min(1).max(svc.NAME_MAX_LENGTH),+ starterPrompt: z.string().trim().max(svc.STARTER_PROMPT_MAX).optional().default(''),+ 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(),+ llm: llmSchema,+});++const patchSchema = z.object({+ name: z.string().trim().min(1).max(svc.NAME_MAX_LENGTH).optional(),+ starterPrompt: z.string().trim().max(svc.STARTER_PROMPT_MAX).optional(),+ stylePrompt: z.string().trim().max(svc.PROMPT_FRAGMENT_MAX).optional(),+ negativePrompt: z.string().trim().max(svc.PROMPT_FRAGMENT_MAX).optional(),+ categories: categoriesSchema.optional(),+ llm: llmSchema,+}).refine((p) => Object.keys(p).length > 0, { message: 'patch must include at least one field' });++const expandSchema = z.object({+ starterPrompt: z.string().trim().min(1).max(svc.STARTER_PROMPT_MAX),+ providerId: z.string().trim().max(80).optional(),+ model: z.string().trim().max(200).optional(),+});++// `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 renderSchema = z.object({+ // Optional friendly name for the resulting collection. If omitted, server+ // synthesizes "World: <name> (timestamp)".+ collectionName: z.string().trim().min(1).max(COLLECTION_NAME_MAX).optional(),+ // Image-gen knobs — these mirror /api/image-gen/generate so the user can+ // pick mode/size/steps without bouncing to the Image page first.+ mode: z.enum(['external', 'local', 'codex']).optional(),+ modelId: z.string().trim().max(64).optional(),+ width: z.number().int().min(64).max(2048).optional(),+ height: z.number().int().min(64).max(2048).optional(),+ steps: z.number().int().min(1).max(150).optional(),+ cfgScale: z.number().min(0).max(30).optional(),+ guidance: z.number().min(0).max(30).optional(),+ // Per-variation render count and per-category subset.+ batchPerVariation: z.number().int().min(1).max(20).optional().default(1),+ selection: selectionSchema.optional(),+});++router.get('/', asyncHandler(async (_req, res) => {+ res.json(await svc.listWorlds());+}));++router.post('/', asyncHandler(async (req, res) => {+ const body = validateRequest(createSchema, req.body ?? {});+ res.status(201).json(await svc.createWorld(body));+}));++// `expand` is a sub-resource — keep it ahead of `/:id` so the wildcard+// doesn't catch "expand" as a world id.+router.post('/expand', asyncHandler(async (req, res) => {+ const body = validateRequest(expandSchema, req.body ?? {});+ const result = await expandWorldTemplate(body);+ res.json(result);+}));++router.get('/:id', asyncHandler(async (req, res) => {+ const w = await svc.getWorld(req.params.id).catch((err) => { throw mapServiceError(err); });+ res.json(w);+}));++router.patch('/:id', asyncHandler(async (req, res) => {+ const body = validateRequest(patchSchema, req.body ?? {});+ const w = await svc.updateWorld(req.params.id, body).catch((err) => { throw mapServiceError(err); });+ res.json(w);+}));++router.delete('/:id', asyncHandler(async (req, res) => {+ const r = await svc.deleteWorld(req.params.id).catch((err) => { throw mapServiceError(err); });+ res.json(r);+}));++router.get('/:id/runs', asyncHandler(async (req, res) => {+ res.json(await svc.listRuns(req.params.id));+}));++router.post('/:id/render', asyncHandler(async (req, res) => {+ const body = validateRequest(renderSchema, req.body ?? {});+ const world = await svc.getWorld(req.params.id).catch((err) => { throw mapServiceError(err); });++ const compiled = svc.compilePrompts(world, {+ selection: body.selection,+ batchPerVariation: body.batchPerVariation,+ });+ if (!compiled.length) {+ throw new ServerError('No prompts to render — add variations or expand the template first', {+ status: 400, code: 'WORLD_BUILDER_EMPTY',+ });+ }++ const settings = await getSettings();+ const mode = body.mode || settings.imageGen?.mode || 'external';++ // Reject `external` mode upfront — batch rendering against a remote SD-API+ // would block this request for the entire batch, and we don't want to leave+ // an orphaned media collection behind when we discover this mid-loop below.+ if (mode !== 'local' && mode !== 'codex') {+ throw new ServerError(+ 'Batch render requires local or codex mode — switch image-gen mode in Settings → Image Gen',+ { status: 400, code: 'WORLD_BUILDER_EXTERNAL_UNSUPPORTED' },+ );+ }++ // Mirror the upfront validation /api/image-gen/generate does so a doomed+ // batch fails before any jobs land in the queue.+ if (mode === 'codex' && !settings.imageGen?.codex?.enabled) {+ throw new ServerError(+ 'Codex Imagegen is disabled — enable it in Settings → Image Gen first',+ { status: 400, code: 'CODEX_IMAGEGEN_DISABLED' },+ );+ }+ if (mode === 'local') {+ const py = settings.imageGen?.local?.pythonPath || null;+ const allModels = getImageModels();+ if (body.modelId && !allModels.some((m) => m.id === body.modelId)) {+ throw new ServerError(`Unknown modelId: ${body.modelId}`, { status: 400, code: 'IMAGE_GEN_UNKNOWN_MODEL' });+ }+ const selectedModel = allModels.find((m) => m.id === body.modelId)+ ?? allModels.find((m) => m.id === 'dev')+ ?? allModels[0];+ if (selectedModel && !isFlux2(selectedModel) && !py) {+ throw new ServerError(+ 'Local image generation is not configured (settings.imageGen.local.pythonPath is missing).',+ { status: 400, code: 'IMAGE_GEN_NOT_CONFIGURED' },+ );+ }+ }++ // Provision the collection up front so renders can be tagged as they+ // complete. The completion hook (worldBuilderCollectionHook) will add+ // each finished image's filename to this collection.+ const collectionName = body.collectionName?.trim()+ || `World: ${world.name} — ${new Date().toISOString().slice(0, 16).replace('T', ' ')}`;+ const collection = await createCollection({+ name: collectionName.slice(0, COLLECTION_NAME_MAX),+ description: `World Builder run for "${world.name}" (${compiled.length} prompts)`,+ });++ const runId = randomUUID();+ const jobIds = [];+ // Map cfgScale → guidance the same way /api/image-gen/generate does. The+ // mediaJobQueue calls imageGen/local.generateImage() directly (not the+ // dispatcher), so without this mapping the World Builder UI's CFG control+ // would silently no-op for local renders.+ const guidance = body.guidance ?? body.cfgScale;+ const baseParams = {+ width: body.width,+ height: body.height,+ steps: body.steps,+ cfgScale: body.cfgScale,+ guidance,+ };++ for (const item of compiled) {+ const params = {+ ...baseParams,+ prompt: item.prompt,+ negativePrompt: item.negativePrompt || undefined,+ // Tag every job so the completion hook can route the result back+ // into the run's collection without us having to thread additional+ // arguments through the queue.+ worldRun: {+ runId,+ worldId: world.id,+ collectionId: collection.id,+ category: item.category,+ label: item.label,+ },+ };+ if (mode === 'codex') {+ const c = settings.imageGen?.codex || {};+ const queued = enqueueJob({+ kind: 'image',+ params: { mode: 'codex', codexPath: c.codexPath, model: c.model, ...params },+ });+ jobIds.push(queued.jobId);+ continue;+ }+ // mode === 'local' (validated upfront).+ const py = settings.imageGen?.local?.pythonPath || null;+ const queued = enqueueJob({+ kind: 'image',+ params: { pythonPath: py, modelId: body.modelId, ...params },+ });+ jobIds.push(queued.jobId);+ }++ const run = await svc.recordRun({+ id: runId,+ worldId: world.id,+ collectionId: collection.id,+ jobIds,+ promptCount: compiled.length,+ createdAt: new Date().toISOString(),+ });++ console.log(`🌍 World Builder render — world=${world.name} prompts=${compiled.length} mode=${mode} runId=${runId.slice(0, 8)}`);++ res.json({+ runId: run.id,+ collectionId: collection.id,+ collectionName: collection.name,+ promptCount: compiled.length,+ jobIds,+ mode,+ });+}));++export default router;diff --git a/server/routes/worldBuilder.test.js b/server/routes/worldBuilder.test.jsnew file mode 100644index 0000000000..c7667e14d0--- /dev/null+++ b/server/routes/worldBuilder.test.js@@ -0,0 +1,164 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';+import express from 'express';+import { request } from '../lib/testHelper.js';+import { errorMiddleware } from '../lib/errorHandler.js';++const fileStore = new Map();++vi.mock('../lib/fileUtils.js', () => ({+ PATHS: { data: '/mock/data' },+ ensureDir: vi.fn().mockResolvedValue(undefined),+ atomicWrite: vi.fn(async (path, data) => { fileStore.set(path, data); }),+ readJSONFile: vi.fn(async (path, fallback) => (fileStore.has(path) ? fileStore.get(path) : fallback)),+}));++let uuidCounter = 0;+vi.mock('crypto', async () => {+ const actual = await vi.importActual('crypto');+ return { ...actual, randomUUID: () => `uuid-${++uuidCounter}` };+});++// Stub the LLM expander so the route test doesn't shell out to a real provider.+vi.mock('../services/worldBuilderExpand.js', () => ({+ expandWorldTemplate: vi.fn(async ({ starterPrompt }) => ({+ stylePrompt: 'mocked style for ' + starterPrompt,+ negativePrompt: 'blurry',+ categories: {+ landscapes: { variations: [{ label: 'Mock Land', prompt: 'mocked landscape' }] },+ environments: { variations: [] },+ characters: { variations: [{ label: 'Mock Char', prompt: 'mocked character' }] },+ structures: { variations: [] },+ vehicles: { variations: [] },+ },+ llm: { provider: 'anthropic', model: 'claude' },+ })),+}));++// Skip provisioning real settings — we only exercise CRUD + expand here.+vi.mock('../services/settings.js', () => ({+ getSettings: vi.fn(async () => ({ imageGen: { mode: 'local', local: { pythonPath: '/usr/bin/python3' } } })),+ saveSettings: vi.fn(),+}));++vi.mock('../services/mediaJobQueue/index.js', () => ({+ enqueueJob: vi.fn(({ params }) => ({ jobId: `job-${++uuidCounter}`, position: 1, status: 'queued', params })),+}));++vi.mock('../services/mediaCollections.js', () => ({+ createCollection: vi.fn(async ({ name }) => ({ id: 'col-1', name, items: [] })),+ addItem: vi.fn(),+ ERR_DUPLICATE: 'DUPLICATE',+ NAME_MAX_LENGTH: 80,+}));++vi.mock('../lib/mediaModels.js', () => ({+ getImageModels: () => [{ id: 'dev', label: 'mflux dev' }],+ isFlux2: () => false,+}));++const worldBuilderRoutes = (await import('./worldBuilder.js')).default;++const buildApp = () => {+ const app = express();+ app.use(express.json());+ app.use('/api/world-builder', worldBuilderRoutes);+ app.use(errorMiddleware);+ return app;+};++describe('world-builder routes', () => {+ beforeEach(() => {+ fileStore.clear();+ uuidCounter = 0;+ });++ it('GET / returns []', async () => {+ const res = await request(buildApp()).get('/api/world-builder');+ expect(res.status).toBe(200);+ expect(res.body).toEqual([]);+ });++ it('POST / creates a world', async () => {+ const res = await request(buildApp())+ .post('/api/world-builder')+ .send({ name: 'My World', starterPrompt: 'cyber forest' });+ expect(res.status).toBe(201);+ expect(res.body.id).toBe('uuid-1');+ expect(res.body.name).toBe('My World');+ // All five categories populated even when not supplied.+ expect(Object.keys(res.body.categories).sort()).toEqual(+ ['characters', 'environments', 'landscapes', 'structures', 'vehicles'],+ );+ });++ it('POST / rejects missing name', async () => {+ const res = await request(buildApp())+ .post('/api/world-builder')+ .send({ starterPrompt: 'cyber forest' });+ expect(res.status).toBe(400);+ });++ it('PATCH /:id updates fields', async () => {+ const app = buildApp();+ const c = await request(app).post('/api/world-builder').send({ name: 'A' });+ const res = await request(app)+ .patch(`/api/world-builder/${c.body.id}`)+ .send({ name: 'B', stylePrompt: 'oil painting' });+ expect(res.status).toBe(200);+ expect(res.body.name).toBe('B');+ expect(res.body.stylePrompt).toBe('oil painting');+ });++ it('DELETE /:id removes the world', async () => {+ const app = buildApp();+ const c = await request(app).post('/api/world-builder').send({ name: 'A' });+ const del = await request(app).delete(`/api/world-builder/${c.body.id}`);+ expect(del.status).toBe(200);+ const list = await request(app).get('/api/world-builder');+ expect(list.body).toEqual([]);+ });++ it('POST /expand returns LLM expansion', async () => {+ const res = await request(buildApp())+ .post('/api/world-builder/expand')+ .send({ starterPrompt: 'moebius scifi' });+ expect(res.status).toBe(200);+ expect(res.body.stylePrompt).toContain('moebius scifi');+ expect(res.body.categories.landscapes.variations).toHaveLength(1);+ expect(res.body.llm.provider).toBe('anthropic');+ });++ it('POST /:id/render queues image jobs and records run', async () => {+ const app = buildApp();+ const created = await request(app).post('/api/world-builder').send({+ name: 'Render Test',+ stylePrompt: 'style',+ negativePrompt: 'neg',+ categories: {+ landscapes: { variations: [{ label: 'A', prompt: 'a prompt' }, { label: 'B', prompt: 'b prompt' }] },+ characters: { variations: [{ label: 'C', prompt: 'c prompt' }] },+ },+ });+ const res = await request(app)+ .post(`/api/world-builder/${created.body.id}/render`)+ .send({ batchPerVariation: 2, mode: 'local' });+ expect(res.status).toBe(200);+ expect(res.body.promptCount).toBe(6); // 3 variations × 2 batch+ expect(res.body.jobIds).toHaveLength(6);+ expect(res.body.collectionId).toBe('col-1');+ // Run is recorded.+ const runs = await request(app).get(`/api/world-builder/${created.body.id}/runs`);+ expect(runs.body).toHaveLength(1);+ expect(runs.body[0].promptCount).toBe(6);+ });++ 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' });+ const res = await request(app)+ .post(`/api/world-builder/${created.body.id}/render`)+ .send({ mode: 'local' });+ expect(res.status).toBe(400);+ expect(res.body.code).toBe('WORLD_BUILDER_EMPTY');+ });+});diff --git a/server/services/worldBuilder.js b/server/services/worldBuilder.jsnew file mode 100644index 0000000000..3e82ec8edf--- /dev/null+++ b/server/services/worldBuilder.js@@ -0,0 +1,280 @@+/**+ * World Builder Service+ *+ * Stores user-created "world templates" — sci-fi/fantasy/etc. universe+ * descriptions expanded by an LLM into a structured prompt set:+ *+ * - stylePrompt + negativePrompt (positive style fragment + negative prompt)+ * - categories: landscapes / environments / characters / structures / vehicles+ * (each with a list of `variations` — short prompt fragments)+ *+ * 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+ * `runId` so the resulting renders form a self-contained collection.+ *+ * Persisted to data/world-builder.json. Renders for a run land in a+ * media-collections.json collection named "World: <worldName>" (or any+ * other name the user picks at kickoff).+ */++import { join } from 'path';+import { randomUUID } from 'crypto';+import { PATHS, atomicWrite, readJSONFile, ensureDir } from '../lib/fileUtils.js';++const STATE_PATH = join(PATHS.data, 'world-builder.json');++export const ERR_NOT_FOUND = 'NOT_FOUND';+export const ERR_VALIDATION = 'VALIDATION_ERROR';+const makeErr = (message, code) => Object.assign(new Error(message), { code });++export const NAME_MAX_LENGTH = 100;+// A render can enqueue up to 5 categories × 50 variations × 20 batchPerVariation+// = 5000 jobs. Cap at 10k to leave headroom against future bumps to those caps.+const MAX_RUN_JOB_IDS = 10000;+export const STARTER_PROMPT_MAX = 4000;+export const PROMPT_FRAGMENT_MAX = 2000;+export const VARIATION_LABEL_MAX = 120;+export const VARIATIONS_PER_CATEGORY_MAX = 50;++// 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.+export const WORLD_CATEGORIES = Object.freeze([+ 'landscapes',+ 'environments',+ 'characters',+ 'structures',+ 'vehicles',+]);++const DEFAULT_STATE = { worlds: [], runs: [] };++const isStr = (v) => typeof v === 'string';+const trimTo = (v, max) => (isStr(v) ? v.trim().slice(0, max) : '');++const sanitizeVariation = (raw) => {+ if (!raw || typeof raw !== 'object') return null;+ const label = trimTo(raw.label, VARIATION_LABEL_MAX);+ const prompt = trimTo(raw.prompt, PROMPT_FRAGMENT_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.+ if (!raw || typeof raw !== 'object') return { variations: [] };+ const variations = [];+ if (Array.isArray(raw.variations)) {+ for (const v of raw.variations) {+ const s = sanitizeVariation(v);+ if (!s) continue;+ variations.push(s);+ if (variations.length >= VARIATIONS_PER_CATEGORY_MAX) break;+ }+ }+ return { variations };+};++const sanitizeTemplate = (raw) => {+ if (!raw || typeof raw !== 'object') return null;+ if (!isStr(raw.id) || !raw.id) return null;+ const name = trimTo(raw.name, NAME_MAX_LENGTH);+ if (!name) return null;+ 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 llm = raw.llm && typeof raw.llm === 'object'+ ? {+ provider: trimTo(raw.llm.provider, 80) || null,+ model: trimTo(raw.llm.model, 200) || null,+ }+ : { provider: null, model: null };+ const createdAt = isStr(raw.createdAt) ? raw.createdAt : new Date().toISOString();+ const updatedAt = isStr(raw.updatedAt) ? raw.updatedAt : createdAt;+ return {+ id: raw.id,+ name,+ starterPrompt,+ stylePrompt,+ negativePrompt,+ categories,+ llm,+ createdAt,+ updatedAt,+ };+};++const sanitizeRun = (raw) => {+ if (!raw || typeof raw !== 'object') return null;+ if (!isStr(raw.id) || !raw.id) return null;+ if (!isStr(raw.worldId) || !raw.worldId) return null;+ return {+ id: raw.id,+ worldId: raw.worldId,+ collectionId: isStr(raw.collectionId) ? raw.collectionId : null,+ jobIds: Array.isArray(raw.jobIds) ? raw.jobIds.filter(isStr).slice(0, MAX_RUN_JOB_IDS) : [],+ promptCount: Number.isFinite(raw.promptCount) ? raw.promptCount : 0,+ createdAt: isStr(raw.createdAt) ? raw.createdAt : new Date().toISOString(),+ };+};++async function readState() {+ await ensureDir(PATHS.data);+ const raw = await readJSONFile(STATE_PATH, DEFAULT_STATE, { logError: false });+ const worlds = Array.isArray(raw.worlds) ? raw.worlds.map(sanitizeTemplate).filter(Boolean) : [];+ const runs = Array.isArray(raw.runs) ? raw.runs.map(sanitizeRun).filter(Boolean) : [];+ return { worlds, runs };+}++async function writeState(state) {+ await atomicWrite(STATE_PATH, state);+}++export async function listWorlds() {+ const { worlds } = await readState();+ // Newest first — matches user expectation for a "your worlds" list.+ return [...worlds].sort((a, b) => (b.createdAt || '').localeCompare(a.createdAt || ''));+}++export async function getWorld(id) {+ const { worlds } = await readState();+ const w = worlds.find((x) => x.id === id);+ if (!w) throw makeErr(`World not found: ${id}`, ERR_NOT_FOUND);+ return w;+}++export async function createWorld(input = {}) {+ const name = trimTo(input.name, NAME_MAX_LENGTH);+ if (!name) throw makeErr(`World name is required (1..${NAME_MAX_LENGTH} chars)`, ERR_VALIDATION);+ const state = await readState();+ const now = new Date().toISOString();+ const next = sanitizeTemplate({+ id: randomUUID(),+ name,+ starterPrompt: input.starterPrompt || '',+ stylePrompt: input.stylePrompt || '',+ negativePrompt: input.negativePrompt || '',+ categories: input.categories || {},+ llm: input.llm || {},+ createdAt: now,+ updatedAt: now,+ });+ state.worlds.push(next);+ await writeState(state);+ return next;+}++export async function updateWorld(id, patch = {}) {+ const state = await readState();+ const idx = state.worlds.findIndex((w) => w.id === id);+ if (idx < 0) throw makeErr(`World not found: ${id}`, ERR_NOT_FOUND);+ const cur = state.worlds[idx];++ // Merge `categories` per-key — a partial PATCH that only includes+ // `landscapes` must NOT wipe characters/structures/etc. Whole categories+ // not present in the patch are kept as-is from the current world.+ const mergedCategories = 'categories' in patch+ ? { ...cur.categories, ...(patch.categories || {}) }+ : cur.categories;++ // Merge `llm` field-by-field — sending only `{ provider }` shouldn't+ // clear `model` and vice versa.+ const mergedLlm = 'llm' in patch+ ? { ...(cur.llm || {}), ...(patch.llm || {}) }+ : cur.llm;++ const merged = sanitizeTemplate({+ ...cur,+ ...('name' in patch ? { name: patch.name } : {}),+ ...('starterPrompt' in patch ? { starterPrompt: patch.starterPrompt } : {}),+ ...('stylePrompt' in patch ? { stylePrompt: patch.stylePrompt } : {}),+ ...('negativePrompt' in patch ? { negativePrompt: patch.negativePrompt } : {}),+ categories: mergedCategories,+ llm: mergedLlm,+ updatedAt: new Date().toISOString(),+ });+ if (!merged) throw makeErr('Invalid world payload', ERR_VALIDATION);+ state.worlds[idx] = merged;+ await writeState(state);+ return merged;+}++export async function deleteWorld(id) {+ const state = await readState();+ const before = state.worlds.length;+ state.worlds = state.worlds.filter((w) => w.id !== id);+ if (state.worlds.length === before) throw makeErr(`World not found: ${id}`, ERR_NOT_FOUND);+ // Drop runs referencing the deleted world — they're useless without it.+ state.runs = state.runs.filter((r) => r.worldId !== id);+ await writeState(state);+ return { id };+}++export async function recordRun(run) {+ const sanitized = sanitizeRun(run);+ if (!sanitized) throw makeErr('Invalid run payload', ERR_VALIDATION);+ const state = await readState();+ state.runs.push(sanitized);+ // Keep last 200 runs to bound state growth.+ if (state.runs.length > 200) state.runs = state.runs.slice(-200);+ await writeState(state);+ return sanitized;+}++export async function listRuns(worldId = null) {+ const { runs } = await readState();+ const filtered = worldId ? runs.filter((r) => r.worldId === worldId) : runs;+ return [...filtered].sort((a, b) => (b.createdAt || '').localeCompare(a.createdAt || ''));+}++/**+ * Compile the world template into an ordered list of full image-gen+ * prompts. Each entry combines the world's style prompt with one+ * variation from a chosen category.+ *+ * selection: { landscapes: 'all' | string[], characters: ... }+ * - 'all' → use every variation+ * - array of labels → only those labels (case-insensitive match)+ * - missing key → skip the category entirely+ *+ * batchPerVariation: how many renders per variation (1..20)+ */+export function compilePrompts(world, options = {}) {+ if (!world || !world.categories) return [];+ const selection = options.selection && typeof options.selection === 'object'+ ? options.selection+ : Object.fromEntries(WORLD_CATEGORIES.map((c) => [c, 'all']));+ 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(', ');+ for (let i = 0; i < batchPerVariation; i += 1) {+ compiled.push({+ category,+ label: variation.label,+ prompt,+ negativePrompt,+ batchIndex: i,+ });+ }+ }+ }++ return compiled;+}diff --git a/server/services/worldBuilder.test.js b/server/services/worldBuilder.test.jsnew file mode 100644index 0000000000..25af7c2b7d--- /dev/null+++ b/server/services/worldBuilder.test.js@@ -0,0 +1,163 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';++const fileStore = new Map();++vi.mock('../lib/fileUtils.js', () => ({+ PATHS: { data: '/mock/data' },+ ensureDir: vi.fn().mockResolvedValue(undefined),+ atomicWrite: vi.fn(async (path, data) => { fileStore.set(path, data); }),+ readJSONFile: vi.fn(async (path, fallback) => (fileStore.has(path) ? fileStore.get(path) : fallback)),+}));++let uuidCounter = 0;+vi.mock('crypto', async () => {+ const actual = await vi.importActual('crypto');+ return { ...actual, randomUUID: () => `uuid-${++uuidCounter}` };+});++const svc = await import('./worldBuilder.js');++const seedWorld = async (overrides = {}) => svc.createWorld({+ name: 'Moebius SciFi',+ starterPrompt: 'moebius and scavengers reign meets prophet',+ stylePrompt: 'moebius linework, scavengers reign palette',+ negativePrompt: 'blurry, lowres',+ categories: {+ landscapes: { variations: [+ { label: 'Crystal Canyon', prompt: 'crystalline canyon, alien sun' },+ { label: 'Sand Sea', prompt: 'endless sand sea, dunes' },+ ] },+ characters: { variations: [+ { label: 'Scavenger', prompt: 'lone scavenger figure, weathered cloak' },+ ] },+ },+ ...overrides,+});++describe('worldBuilder service', () => {+ beforeEach(() => {+ fileStore.clear();+ uuidCounter = 0;+ });++ it('listWorlds returns [] for fresh state', async () => {+ expect(await svc.listWorlds()).toEqual([]);+ });++ it('createWorld persists with sanitized categories', async () => {+ const w = await seedWorld();+ expect(w.id).toBe('uuid-1');+ expect(w.name).toBe('Moebius SciFi');+ // All five categories materialized even when only two were provided.+ for (const c of svc.WORLD_CATEGORIES) {+ expect(w.categories[c]).toBeDefined();+ expect(Array.isArray(w.categories[c].variations)).toBe(true);+ }+ expect(w.categories.landscapes.variations).toHaveLength(2);+ expect(w.categories.characters.variations).toHaveLength(1);+ expect(w.categories.environments.variations).toHaveLength(0);+ });++ it('createWorld rejects empty name', async () => {+ await expect(svc.createWorld({ name: '' })).rejects.toThrow(/name is required/);+ });++ it('updateWorld merges partial patches', async () => {+ const w = await seedWorld();+ const patched = await svc.updateWorld(w.id, { name: 'Renamed', stylePrompt: 'new style' });+ expect(patched.name).toBe('Renamed');+ expect(patched.stylePrompt).toBe('new style');+ // Untouched fields preserved.+ expect(patched.starterPrompt).toBe(w.starterPrompt);+ expect(patched.categories.landscapes.variations).toHaveLength(2);+ });++ it('updateWorld throws NOT_FOUND for unknown id', async () => {+ await expect(svc.updateWorld('no-such', { name: 'X' })).rejects.toMatchObject({ code: svc.ERR_NOT_FOUND });+ });++ it('deleteWorld removes the world and its runs', async () => {+ const w = await seedWorld();+ await svc.recordRun({+ id: 'run-1', worldId: w.id, collectionId: 'col-1', jobIds: ['j1'], promptCount: 3,+ });+ expect((await svc.listRuns(w.id))).toHaveLength(1);+ await svc.deleteWorld(w.id);+ expect(await svc.listWorlds()).toEqual([]);+ expect(await svc.listRuns(w.id)).toEqual([]);+ });++ describe('compilePrompts', () => {+ it('returns one prompt per variation across selected categories with style prefix', async () => {+ const w = await seedWorld();+ const compiled = svc.compilePrompts(w);+ // 2 landscapes + 1 character = 3 (other categories empty)+ expect(compiled).toHaveLength(3);+ expect(compiled[0].prompt).toBe('moebius linework, scavengers reign palette, crystalline canyon, alien sun');+ expect(compiled[0].category).toBe('landscapes');+ expect(compiled[0].label).toBe('Crystal Canyon');+ expect(compiled[0].negativePrompt).toBe('blurry, lowres');+ });++ it('respects batchPerVariation', async () => {+ const w = await seedWorld();+ const compiled = svc.compilePrompts(w, { batchPerVariation: 3 });+ expect(compiled).toHaveLength(9); // 3 variations × 3 batch+ expect(compiled.filter((c) => c.label === 'Crystal Canyon')).toHaveLength(3);+ });++ it('selection: array filters by label (case-insensitive)', async () => {+ const w = await seedWorld();+ const compiled = svc.compilePrompts(w, {+ selection: { landscapes: ['crystal canyon'], characters: 'all' },+ });+ // 1 landscape (filtered) + 1 character (all) = 2+ expect(compiled).toHaveLength(2);+ expect(compiled.map((c) => c.label).sort()).toEqual(['Crystal Canyon', 'Scavenger']);+ });++ it('selection: missing key skips category', async () => {+ const w = await seedWorld();+ const compiled = svc.compilePrompts(w, { selection: { landscapes: 'all' } });+ expect(compiled).toHaveLength(2);+ expect(compiled.every((c) => c.category === 'landscapes')).toBe(true);+ });++ it('clamps batchPerVariation to 1..20', async () => {+ const w = await seedWorld();+ // 0 → 1+ expect(svc.compilePrompts(w, { batchPerVariation: 0 })).toHaveLength(3);+ // 100 → 20+ const big = svc.compilePrompts(w, { batchPerVariation: 100 });+ expect(big).toHaveLength(60); // 3 × 20+ });+ });++ describe('sanitizers', () => {+ it('drops malformed variations on read', async () => {+ // Manually plant invalid state — sanitizeTemplate strips it on read.+ fileStore.set('/mock/data/world-builder.json', {+ worlds: [{+ id: 'w1',+ name: 'X',+ starterPrompt: '',+ stylePrompt: '',+ negativePrompt: '',+ categories: {+ landscapes: { variations: [+ { label: 'Good', prompt: 'good prompt' },+ { label: '', prompt: 'no label' },+ { label: 'No prompt', prompt: '' },+ null,+ ] },+ },+ createdAt: '2024-01-01T00:00:00Z',+ }],+ runs: [],+ });+ const list = await svc.listWorlds();+ expect(list[0].categories.landscapes.variations).toHaveLength(1);+ expect(list[0].categories.landscapes.variations[0].label).toBe('Good');+ });+ });+});diff --git a/server/services/worldBuilderCollectionHook.js b/server/services/worldBuilderCollectionHook.jsnew file mode 100644index 0000000000..bf62073024--- /dev/null+++ b/server/services/worldBuilderCollectionHook.js@@ -0,0 +1,68 @@+/**+ * World Builder — collection hook.+ *+ * Subscribes to mediaJobEvents and, for each completed image job that+ * carries `params.worldRun.collectionId`, files the rendered filename+ * into that collection.+ *+ * Mounted once at server boot from server/index.js so it can listen for+ * the lifetime of the process. Failures here are logged but never thrown+ * — a bookkeeping miss must not crash the server or fail the user's+ * render.+ */++import { mediaJobEvents } from './mediaJobQueue/index.js';+import { addItem, ERR_DUPLICATE } from './mediaCollections.js';++let registeredHandler = null;++export function initWorldBuilderCollectionHook() {+ // Idempotent: a stray double-init (test reload, future refactor) would+ // otherwise register two listeners and double-file every completed image.+ if (registeredHandler) return;++ // EventEmitter does not await async listeners and does not catch their+ // rejections — any throw here would surface as an unhandled promise+ // rejection (process-killing on Node ≥15). Use a sync listener that+ // launches an async IIFE with a top-level catch so this bookkeeping+ // miss can never crash the server or fail the user's render.+ registeredHandler = (job) => {+ void (async () => {+ if (!job || job.kind !== 'image') return;+ const tag = job.params?.worldRun;+ if (!tag?.collectionId) return;+ const filename = job.result?.filename;+ if (!filename || typeof filename !== 'string') return;+ const status = await addItem(tag.collectionId, { kind: 'image', ref: filename })+ .then(() => 'added')+ .catch((err) => {+ // A duplicate (same filename rendered twice in the same run) is+ // expected when batchPerVariation > 1 and the gen output collides.+ if (err?.code === ERR_DUPLICATE) return 'duplicate';+ console.log(`⚠️ world-builder collection hook failed for ${filename}: ${err?.message || String(err)}`);+ return 'failed';+ });+ if (status === 'added') {+ console.log(`🌍 world-builder run=${tag.runId?.slice(0, 8)} category=${tag.category} → ${filename}`);+ } else if (status === 'duplicate') {+ console.log(`🌍 world-builder run=${tag.runId?.slice(0, 8)} category=${tag.category} duplicate skipped: ${filename}`);+ }+ })().catch((err) => {+ // Last-resort net for synchronous throws (unexpected job shape, etc).+ console.log(`⚠️ world-builder collection hook crashed: ${err?.message || err}`);+ });+ };+ mediaJobEvents.on('completed', registeredHandler);+ console.log('🌍 World Builder collection hook initialized');+}++// Test-only reset hook so suites that re-init can do so cleanly. Removes the+// previously registered listener so re-init doesn't leak handlers.+export const __testing = {+ reset: () => {+ if (registeredHandler) {+ mediaJobEvents.off('completed', registeredHandler);+ registeredHandler = null;+ }+ },+};diff --git a/server/services/worldBuilderExpand.js b/server/services/worldBuilderExpand.jsnew file mode 100644index 0000000000..9fe327e398--- /dev/null+++ b/server/services/worldBuilderExpand.js@@ -0,0 +1,205 @@+/**+ * World Builder — LLM expansion.+ *+ * 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 }] }, ... } }+ *+ * The LLM choice is per-call: caller passes { providerId, model }. If+ * either is missing we fall back to the active provider / its default+ * model so the UI still works for users who haven't configured a stage.+ */++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';++const LABEL_MAX = 80;++const EXPANSION_PROMPT = `You are a world-building prompt engineer for a Stable-Diffusion-style image generation pipeline. You will turn the user's starter idea into a structured prompt set that produces a visually consistent universe across many renders.++# Starter idea+{starterPrompt}++# Output contract+Return a SINGLE JSON object. NO markdown, NO commentary. The object MUST have these top-level keys:++- 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:+${WORLD_CATEGORIES.map((c) => ` - ${c}`).join('\n')}++Each category value is an object: { "variations": [...] }+Each variation is { "label": string (max 80 chars), "prompt": string (max 400 chars, comma-separated tokens describing ONE specific subject in this category) }++# Rules+- Generate 6-10 variations per category. They must be visually distinct from each other but stylistically consistent with the world.+- "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.+- Output JUST the JSON object. No prose before or after.`;++const isCliProvider = (provider) => provider?.type === 'cli';++// Awaiting createRun separately keeps the Promise executor synchronous —+// an `async` executor body silently swallows rejected awaits, leaving the+// caller's Promise hanging forever if createRun throws.+async function callLLM(provider, model, prompt) {+ const { runId } = await createRun({+ providerId: provider.id,+ model,+ prompt,+ source: 'world-builder-expansion',+ });+ return new Promise((resolve, reject) => {+ let text = '';+ // Both executeCliRun / executeApiRun are async — they can reject before+ // onComplete ever fires (ensureDir/read/write failures, toolkit not+ // initialized, provider errors). Without a rejection handler the awaiter+ // would hang forever and Node would log an unhandledRejection. Forward+ // the rejection through `reject` so callLLM() always settles.+ if (isCliProvider(provider)) {+ executeCliRun(+ runId,+ provider,+ prompt,+ process.cwd(),+ (chunk) => { text += chunk; },+ (result) => {+ if (result?.error || result?.success === false) {+ reject(new Error(result?.error || 'CLI execution failed'));+ } else {+ resolve(text);+ }+ },+ provider.timeout ?? 300000,+ ).catch(reject);+ } else {+ executeApiRun(+ runId,+ provider,+ model,+ prompt,+ process.cwd(),+ [],+ (data) => { text += typeof data === 'string' ? data : (data?.text || ''); },+ (result) => {+ if (result?.error) reject(new Error(result.error));+ else resolve(text);+ },+ ).catch(reject);+ }+ });+}++const extractJson = (raw) => {+ if (!raw || typeof raw !== 'string') throw new Error('Empty LLM response');+ let s = raw.trim();+ // Strip ```json fences if present.+ const fence = s.match(/```(?:json)?\s*([\s\S]*?)```/);+ if (fence) s = fence[1].trim();+ // Extract the first complete brace-balanced { … } block — guards against+ // preamble ("Here is…") and trailing junk after the JSON object. The scan+ // is string-aware so braces inside JSON string values (e.g. a prompt that+ // contains "{" or "}") don't unbalance the depth counter.+ const start = s.indexOf('{');+ if (start !== -1) {+ let depth = 0;+ let inString = false;+ let escaped = false;+ let end = -1;+ for (let i = start; i < s.length; i += 1) {+ const ch = s[i];+ if (inString) {+ if (escaped) escaped = false;+ else if (ch === '\\') escaped = true;+ else if (ch === '"') inString = false;+ continue;+ }+ if (ch === '"') { inString = true; continue; }+ if (ch === '{') depth += 1;+ else if (ch === '}') {+ depth -= 1;+ if (depth === 0) { end = i; break; }+ }+ }+ if (end !== -1) s = s.slice(start, end + 1);+ }+ return JSON.parse(s);+};++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.+ const out = {};+ for (const key of WORLD_CATEGORIES) {+ const node = raw?.[key];+ let variations = [];+ if (Array.isArray(node)) variations = node;+ else if (Array.isArray(node?.variations)) variations = node.variations;+ out[key] = {+ // Clamp to the same per-category cap the route schema enforces (50)+ // so a runaway LLM response can't bloat /expand output.+ variations: variations.slice(0, VARIATIONS_PER_CATEGORY_MAX).map((v) => {+ if (typeof v === 'string') {+ const trimmed = v.trim();+ return {+ label: trimmed.slice(0, LABEL_MAX),+ prompt: trimmed.slice(0, PROMPT_FRAGMENT_MAX),+ };+ }+ const label = typeof v?.label === 'string' ? v.label.trim().slice(0, LABEL_MAX) : '';+ const prompt = typeof v?.prompt === 'string' ? v.prompt.trim().slice(0, PROMPT_FRAGMENT_MAX) : '';+ return { label, prompt };+ }).filter((v) => v.label && v.prompt),+ };+ }+ return out;+};++/**+ * Expand a starter prompt into a structured world template draft.+ * Returns { stylePrompt, negativePrompt, categories, llm: { provider, model } }.+ *+ * @param {object} options+ * @param {string} options.starterPrompt+ * @param {string} [options.providerId] — optional override; falls back to active.+ * @param {string} [options.model] — optional override; falls back to provider default.+ */+export async function expandWorldTemplate({ starterPrompt, providerId, model } = {}) {+ if (!starterPrompt || !starterPrompt.trim()) {+ throw new Error('starterPrompt is required');+ }++ let provider = providerId ? await getProviderById(providerId).catch(() => null) : null;+ if (!provider) provider = await getActiveProvider();+ if (!provider) throw new Error('No AI provider available for world expansion');+ const selectedModel = model || provider.defaultModel || provider.models?.[0];++ const fullPrompt = EXPANSION_PROMPT.replace('{starterPrompt}', starterPrompt.trim());+ console.log(`🌍 World Builder expanding via ${provider.name}/${selectedModel || 'default'}`);++ const raw = await callLLM(provider, selectedModel, fullPrompt);+ const parsed = extractJson(raw);++ 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 totalVariations = WORLD_CATEGORIES.reduce((n, k) => n + (categories[k]?.variations?.length || 0), 0);+ console.log(`🌍 World Builder expansion complete — ${totalVariations} variations across ${WORLD_CATEGORIES.length} categories`);++ return {+ stylePrompt,+ negativePrompt,+ categories,+ llm: { provider: provider.id, model: selectedModel || null },+ };+}++// Export for tests.+export const __testing = { extractJson, normalizeCategories, EXPANSION_PROMPT };diff --git a/server/services/worldBuilderExpand.test.js b/server/services/worldBuilderExpand.test.jsnew file mode 100644index 0000000000..8562e33b3a--- /dev/null+++ b/server/services/worldBuilderExpand.test.js@@ -0,0 +1,104 @@+import { describe, it, expect } from 'vitest';+import { __testing } from './worldBuilderExpand.js';+import { WORLD_CATEGORIES } from './worldBuilder.js';++const { extractJson, normalizeCategories } = __testing;++describe('worldBuilderExpand.extractJson', () => {+ it('parses a raw JSON object', () => {+ const obj = { stylePrompt: 'a, b, c', negativePrompt: 'blur', categories: {} };+ expect(extractJson(JSON.stringify(obj))).toEqual(obj);+ });++ it('strips ```json fences', () => {+ const fenced = '```json\n{"stylePrompt":"x","categories":{}}\n```';+ expect(extractJson(fenced)).toEqual({ stylePrompt: 'x', categories: {} });+ });++ it('strips bare ``` fences', () => {+ const fenced = '```\n{"stylePrompt":"x"}\n```';+ expect(extractJson(fenced)).toEqual({ stylePrompt: 'x' });+ });++ it('skips a preamble before the first { … } block', () => {+ const raw = 'Here is the JSON you asked for:\n{"stylePrompt":"x","negativePrompt":"y"}\nHope this helps!';+ expect(extractJson(raw)).toEqual({ stylePrompt: 'x', negativePrompt: 'y' });+ });++ it('rejects empty / non-string input', () => {+ expect(() => extractJson('')).toThrow(/Empty LLM response/);+ expect(() => extractJson(null)).toThrow(/Empty LLM response/);+ expect(() => extractJson(undefined)).toThrow(/Empty LLM response/);+ });++ it('throws when no JSON object can be parsed', () => {+ expect(() => extractJson('totally bogus output, no braces')).toThrow();+ expect(() => extractJson('{ this is not valid json')).toThrow();+ });+});++describe('worldBuilderExpand.normalizeCategories', () => {+ it('returns all canonical categories with empty variations on empty input', () => {+ const out = normalizeCategories({});+ for (const key of WORLD_CATEGORIES) {+ expect(out[key]).toEqual({ variations: [] });+ }+ });++ it('coerces a flat array of strings into label/prompt pairs', () => {+ const out = normalizeCategories({+ landscapes: ['Crystalline canyon basin', 'Salt flat ruins'],+ });+ expect(out.landscapes.variations).toEqual([+ { label: 'Crystalline canyon basin', prompt: 'Crystalline canyon basin' },+ { label: 'Salt flat ruins', prompt: 'Salt flat ruins' },+ ]);+ });++ it('truncates long string-shape labels at 80 chars', () => {+ const longText = 'x'.repeat(200);+ const out = normalizeCategories({ characters: [longText] });+ expect(out.characters.variations[0].label).toHaveLength(80);+ expect(out.characters.variations[0].prompt).toBe(longText);+ });++ it('accepts the canonical { variations: [{label,prompt}] } shape', () => {+ const out = normalizeCategories({+ vehicles: { variations: [{ label: 'Walker mech', prompt: 'rusted six-leg walker mech' }] },+ });+ expect(out.vehicles.variations).toEqual([+ { label: 'Walker mech', prompt: 'rusted six-leg walker mech' },+ ]);+ });++ it('drops malformed variations with missing label or prompt', () => {+ const out = normalizeCategories({+ structures: {+ variations: [+ { label: 'Tower', prompt: 'spire of obsidian' }, // keep+ { label: '', prompt: 'no label' }, // drop+ { label: 'No prompt', prompt: '' }, // drop+ { label: 42, prompt: 'numeric label' }, // drop (label not string)+ null, // drop+ ],+ },+ });+ expect(out.structures.variations).toEqual([+ { label: 'Tower', prompt: 'spire of obsidian' },+ ]);+ });++ it('ignores unknown categories not in WORLD_CATEGORIES', () => {+ const out = normalizeCategories({+ landscapes: { variations: [{ label: 'A', prompt: 'a' }] },+ bogus: { variations: [{ label: 'X', prompt: 'x' }] },+ });+ expect(out.landscapes.variations).toHaveLength(1);+ expect(out.bogus).toBeUndefined();+ });++ it('treats a non-object category as empty variations (not a crash)', () => {+ const out = normalizeCategories({ characters: 'not an object' });+ expect(out.characters).toEqual({ variations: [] });+ });+});