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: lightbox prev/next nav + auto-refresh on completion + world-pitch-poster boards
Adam Eivya34e76391d8e
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 553898f9bb..4ca03fc559 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -2,6 +2,10 @@## Added+- **Lightbox prev/next navigation across Image Gen, Video Gen, and Media History.** The MediaLightbox now exposes left/right chevron buttons (visible on hover, top of the modal at `top-1/2 -translate-y-1/2`) and binds `ArrowLeft` / `ArrowRight` keyboard shortcuts so you can flip through the active gallery without closing/reopening. Each page passes its own filtered+sorted list as the navigation source — Image Gen uses visible+hidden gallery (respecting the "show hidden" toggle), Video Gen uses visible+hidden history (same toggle), and Media History uses the search/filter-scoped merged timeline so you only navigate within what's currently visible. New helpers: `getAdjacentMedia(items, item)` returns `{ previous, next, hasPrevious, hasNext }` keyed by `item.key`, and `getMediaNavProps(items, item, onSelect)` returns the four ready-to-spread Lightbox props so call sites stay one line.+- **Auto-refresh Image Gen, Video Gen, and Media History on completion.** The three media pages now subscribe to `image-gen:completed` / `video-gen:completed` socket events via a new `useMediaCompletionRefresh` hook and silently re-fetch their galleries (250 ms debounce to coalesce burst completions). MediaHistory's `refresh()` gains a `silent: true` option so the auto-refresh doesn't flash the loading state on top of the existing list. No need to reload the page after a render finishes — the new image/video appears in place.+- **World Builder: world-pitch-poster composite board kind.** The `compositeSheets` list now distinguishes between two complementary board kinds: `reference_sheet` (existing — costume guides, material swatches, fastener icons) and `world_pitch_poster` (new — single-image cinematic concept-pitch posters with a hero panorama, inset environments, palette/materials strips, theme icons, and section headers like "The World", "The Feel", "Cultures"). The expansion prompt asks the LLM to emit 1-3 pitch posters in addition to any reference sheets when the starter idea spans a broad world/setting, and warns it to keep "text" out of the negativePrompt for those (so titles/section labels can render). Each sheet's `kind` is editable in-place via a select in the Composite Boards editor; when rendered, pitch posters are tagged with `category: 'world_pitch_posters'` instead of `composite_sheets` so they're separable downstream. Server `COMPOSITE_SHEET_KINDS` is the canonical enum (frozen, mirrored client-side); unknown kinds coerce to `reference_sheet` for forward-compat. UI strings flipped from "composite sheets" to "composite boards" to reflect the broader scope.+- **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/components/media/MediaLightbox.jsx b/client/src/components/media/MediaLightbox.jsxindex 29e39c6b16..93d824140a 100644--- a/client/src/components/media/MediaLightbox.jsx+++ b/client/src/components/media/MediaLightbox.jsx@@ -1,5 +1,8 @@-import { useEffect, useState } from 'react';-import { X, Copy, Sparkles, Film, Image as ImageIcon, Download, Eraser } from 'lucide-react';+import { useEffect, useRef, useState } from 'react';+import {+ X, Copy, Sparkles, Film, Image as ImageIcon, Download, Eraser,+ ChevronLeft, ChevronRight,+} from 'lucide-react';import toast from '../ui/Toast';// Mirror of CLEAN_LEVELS in server/routes/imageClean.js. If the server adds a@@ -8,16 +11,46 @@ const CLEAN_LEVEL_LABELS = { light: 'Light', aggressive: 'Aggressive' };// onClean(item, level) — optional. Returning a rejected promise keeps the// lightbox open (e.g. on error) so the user can retry.-export default function MediaLightbox({ item, onClose, onRemix, onSendToVideo, onContinue, onClean }) {+export default function MediaLightbox({+ item,+ onClose,+ onRemix,+ onSendToVideo,+ onContinue,+ onClean,+ onPrevious,+ onNext,+ hasPrevious = false,+ hasNext = false,+}) {const [cleaning, setCleaning] = useState(null);+ // Read callbacks from refs so the keydown listener doesn't re-subscribe on+ // every parent render (callers pass inline arrows; the lightbox parent re-+ // renders constantly while media-gen events stream in).+ const callbacksRef = useRef({ onClose, onPrevious, onNext });+ useEffect(() => { callbacksRef.current = { onClose, onPrevious, onNext }; });useEffect(() => {if (!item) return;- const onKey = (e) => { if (e.key === 'Escape') onClose(); };+ const onKey = (e) => {+ const cb = callbacksRef.current;+ if (e.key === 'Escape') {+ cb.onClose();+ return;+ }+ if (e.key === 'ArrowLeft' && hasPrevious && cb.onPrevious) {+ e.preventDefault();+ cb.onPrevious();+ }+ if (e.key === 'ArrowRight' && hasNext && cb.onNext) {+ e.preventDefault();+ cb.onNext();+ }+ };window.addEventListener('keydown', onKey);const prev = document.body.style.overflow;document.body.style.overflow = 'hidden';return () => { window.removeEventListener('keydown', onKey); document.body.style.overflow = prev; };- }, [item, onClose]);+ }, [item, hasPrevious, hasNext]);if (!item) return null;const isVideo = item.kind === 'video';@@ -51,6 +84,28 @@ export default function MediaLightbox({ item, onClose, onRemix, onSendToVideo, oonClick={onClose}onKeyDown={(e) => e.key === 'Escape' && onClose()}>+ {hasPrevious && (+ <button+ type="button"+ onClick={(e) => { e.stopPropagation(); onPrevious?.(); }}+ className="absolute left-3 md:left-5 top-1/2 -translate-y-1/2 z-10 p-2.5 rounded-full bg-black/55 text-white border border-white/15 hover:bg-black/75 focus:outline-none focus:ring-2 focus:ring-port-accent"+ aria-label="Previous media"+ title="Previous"+ >+ <ChevronLeft className="w-6 h-6" />+ </button>+ )}+ {hasNext && (+ <button+ type="button"+ onClick={(e) => { e.stopPropagation(); onNext?.(); }}+ className="absolute right-3 md:right-5 top-1/2 -translate-y-1/2 z-10 p-2.5 rounded-full bg-black/55 text-white border border-white/15 hover:bg-black/75 focus:outline-none focus:ring-2 focus:ring-port-accent"+ aria-label="Next media"+ title="Next"+ >+ <ChevronRight className="w-6 h-6" />+ </button>+ )}<divclassName="relative bg-port-card border border-port-border rounded-xl overflow-hidden max-w-6xl w-full max-h-[92vh] flex flex-col md:flex-row"onClick={(e) => e.stopPropagation()}diff --git a/client/src/hooks/useMediaCompletionRefresh.js b/client/src/hooks/useMediaCompletionRefresh.jsnew file mode 100644index 0000000000..4d6a3a1113--- /dev/null+++ b/client/src/hooks/useMediaCompletionRefresh.js@@ -0,0 +1,37 @@+import { useEffect, useRef } from 'react';+import socket from '../services/socket';++export function useMediaCompletionRefresh({ onImageCompleted, onVideoCompleted, delay = 250 } = {}) {+ const imageCallbackRef = useRef(onImageCompleted);+ const videoCallbackRef = useRef(onVideoCompleted);+ const timersRef = useRef({ image: null, video: null });++ useEffect(() => { imageCallbackRef.current = onImageCompleted; }, [onImageCompleted]);+ useEffect(() => { videoCallbackRef.current = onVideoCompleted; }, [onVideoCompleted]);++ useEffect(() => {+ const schedule = (kind, callbackRef) => {+ if (!callbackRef.current) return;+ if (timersRef.current[kind]) clearTimeout(timersRef.current[kind]);+ timersRef.current[kind] = setTimeout(() => {+ timersRef.current[kind] = null;+ callbackRef.current?.();+ }, delay);+ };++ const onImageDone = () => schedule('image', imageCallbackRef);+ const onVideoDone = () => schedule('video', videoCallbackRef);++ socket.on('image-gen:completed', onImageDone);+ socket.on('video-gen:completed', onVideoDone);++ return () => {+ socket.off('image-gen:completed', onImageDone);+ socket.off('video-gen:completed', onVideoDone);+ Object.values(timersRef.current).forEach((timer) => {+ if (timer) clearTimeout(timer);+ });+ timersRef.current = { image: null, video: null };+ };+ }, [delay]);+}diff --git a/client/src/lib/mediaNavigation.js b/client/src/lib/mediaNavigation.jsnew file mode 100644index 0000000000..453c75ae83--- /dev/null+++ b/client/src/lib/mediaNavigation.js@@ -0,0 +1,31 @@+export function getAdjacentMedia(items, item) {+ const list = Array.isArray(items) ? items : [];+ const key = item?.key;+ const index = key ? list.findIndex((candidate) => candidate?.key === key) : -1;++ if (index === -1) {+ return { previous: null, next: null, hasPrevious: false, hasNext: false };+ }++ const previous = index > 0 ? list[index - 1] : null;+ const next = index < list.length - 1 ? list[index + 1] : null;++ return {+ previous,+ next,+ hasPrevious: Boolean(previous),+ hasNext: Boolean(next),+ };+}++// Returns the four MediaLightbox nav props ready to spread, so call sites+// don't repeat the previous/next/hasPrevious/hasNext wiring.+export function getMediaNavProps(items, item, onSelect) {+ const nav = getAdjacentMedia(items, item);+ return {+ onPrevious: () => nav.previous && onSelect(nav.previous),+ onNext: () => nav.next && onSelect(nav.next),+ hasPrevious: nav.hasPrevious,+ hasNext: nav.hasNext,+ };+}diff --git a/client/src/pages/ImageGen.jsx b/client/src/pages/ImageGen.jsxindex b30d9086a0..c5bf9b11d3 100644--- a/client/src/pages/ImageGen.jsx+++ b/client/src/pages/ImageGen.jsx@@ -21,12 +21,14 @@ import Flux2InstallModal from '../components/imageGen/Flux2InstallModal';import Flux2TokenBanner from '../components/imageGen/Flux2TokenBanner';import ImageGenControls from '../components/imageGen/ImageGenControls';import MediaJobsQueue from '../components/media/MediaJobsQueue';+import { useMediaCompletionRefresh } from '../hooks/useMediaCompletionRefresh';import {Image as ImageIcon, Sparkles, Download, RefreshCw, Settings as SettingsIcon,AlertTriangle, X, Film,} from 'lucide-react';import { composeStyledPrompt } from '../lib/composeStyledPrompt';import { deriveAvailableBackends, IMAGE_GEN_MODE } from '../lib/imageGenBackends';+import { getMediaNavProps } from '../lib/mediaNavigation';import toast from '../components/ui/Toast';import BrailleSpinner from '../components/BrailleSpinner';import { useImageGenProgress } from '../hooks/useImageGenProgress';@@ -190,6 +192,7 @@ export default function ImageGen() {const refreshGallery = useCallback(() => {listImageGallery().then(setGallery).catch(() => {});}, []);+ useMediaCompletionRefresh({ onImageCompleted: refreshGallery });// Re-runnable so the Settings drawer can trigger a refresh on close// without forcing a full page reload.@@ -446,6 +449,11 @@ export default function ImageGen() {visibleGallery: gallery.filter((img) => !img.hidden),hiddenGallery: gallery.filter((img) => img.hidden),}), [gallery]);+ const previewItems = useMemo(() => [+ ...visibleGallery.map(normalizeImage),+ ...(showHidden ? hiddenGallery.map(normalizeImage) : []),+ ], [visibleGallery, hiddenGallery, showHidden]);+ const previewNavProps = getMediaNavProps(previewItems, preview, setPreview);// Snapshots current form state into a server payload + POSTs it to the// mediaJobQueue. Returns the queue's response ({ jobId, position, ... }).@@ -1081,7 +1089,7 @@ export default function ImageGen() {<MediaCardkey={item.key}item={item}- onPreview={() => setPreview(img)}+ onPreview={() => setPreview(item)}onRemix={() => handleRemix(img)}onSendToVideo={() => sendToVideo(img)}onDelete={() => handleDelete(img.filename)}@@ -1111,7 +1119,7 @@ export default function ImageGen() {<MediaCardkey={item.key}item={item}- onPreview={() => setPreview(img)}+ onPreview={() => setPreview(item)}onRemix={() => handleRemix(img)}onSendToVideo={() => sendToVideo(img)}onDelete={() => handleDelete(img.filename)}@@ -1125,14 +1133,12 @@ export default function ImageGen() {)}<MediaLightbox- item={preview ? normalizeImage(preview) : null}+ item={preview}onClose={() => setPreview(null)}- // Guard against the click landing after the lightbox close path has- // already nulled `preview` — without this the closure throws on- // preview.filename access.- onRemix={() => preview && handleRemix(preview)}- onSendToVideo={() => preview?.filename && sendToVideo(preview)}- onClean={(_item, level) => handleClean(preview, level)}+ onRemix={(item) => item?.raw && handleRemix(item.raw)}+ onSendToVideo={(item) => item?.raw?.filename && sendToVideo(item.raw)}+ onClean={(item, level) => handleClean(item?.raw, level)}+ {...previewNavProps}/>diff --git a/client/src/pages/MediaHistory.jsx b/client/src/pages/MediaHistory.jsxindex 93c4ca735a..14e6ac5bba 100644--- a/client/src/pages/MediaHistory.jsx+++ b/client/src/pages/MediaHistory.jsx@@ -11,6 +11,8 @@ import toast from '../components/ui/Toast';import MediaCard from '../components/media/MediaCard';import MediaLightbox from '../components/media/MediaLightbox';import { normalizeImage, normalizeVideo } from '../components/media/normalize';+import { useMediaCompletionRefresh } from '../hooks/useMediaCompletionRefresh';+import { getMediaNavProps } from '../lib/mediaNavigation';import {listVideoHistory, deleteVideoHistoryItem, extractLastFrame, stitchVideos,upscaleVideo,@@ -34,8 +36,8 @@ export default function MediaHistory() {const [stitching, setStitching] = useState(false);const [preview, setPreview] = useState(null);- const refresh = useCallback(async () => {- setLoading(true);+ const refresh = useCallback(async ({ silent = false } = {}) => {+ if (!silent) setLoading(true);const [images, videos] = await Promise.all([listImageGallery().catch(() => []),listVideoHistory().catch(() => []),@@ -49,6 +51,10 @@ export default function MediaHistory() {}, []);useEffect(() => { refresh(); }, [refresh]);+ useMediaCompletionRefresh({+ onImageCompleted: () => refresh({ silent: true }),+ onVideoCompleted: () => refresh({ silent: true }),+ });// Precompute the searchable haystack per item once per items list — keystrokes// then only re-run token .includes() against a cached string instead of@@ -82,6 +88,7 @@ export default function MediaHistory() {() => filter === 'all' ? searched : searched.filter(i => i.kind === filter),[searched, filter]);+ const previewNavProps = getMediaNavProps(filtered, preview, setPreview);const counts = useMemo(() => {const c = { all: 0, image: 0, video: 0 };for (const i of searched) {@@ -289,6 +296,7 @@ export default function MediaHistory() {onRemix={handleRemix}onSendToVideo={handleSendToVideo}onContinue={handleContinue}+ {...previewNavProps}/></div>);diff --git a/client/src/pages/VideoGen.jsx b/client/src/pages/VideoGen.jsxindex d831dac477..f5dea2e94f 100644--- a/client/src/pages/VideoGen.jsx+++ b/client/src/pages/VideoGen.jsx@@ -41,6 +41,7 @@ import toast from '../components/ui/Toast';import BrailleSpinner from '../components/BrailleSpinner';import BatchQueuePanel from '../components/media/BatchQueuePanel';import MediaJobsQueue from '../components/media/MediaJobsQueue';+import { useMediaCompletionRefresh } from '../hooks/useMediaCompletionRefresh';import {getVideoGenStatus, generateVideo, cancelVideoGen,listVideoHistory, deleteVideoHistoryItem, setVideoHidden, extractLastFrame,@@ -48,6 +49,7 @@ import {listImageGallery,} from '../services/api';import { randomSeed, safeParseJSON } from '../lib/genUtils';+import { getMediaNavProps } from '../lib/mediaNavigation';const RESOLUTIONS = [{ label: '512×320 (16:10)', w: 512, h: 320 },@@ -204,6 +206,7 @@ export default function VideoGen() {const refreshHistory = useCallback(() => {listVideoHistory().then((items) => setHistory(Array.isArray(items) ? items : [])).catch(() => {});}, []);+ useMediaCompletionRefresh({ onVideoCompleted: refreshHistory });useEffect(() => { refreshHistory(); }, [refreshHistory]);useEffect(() => { listImageGallery().then(setImageGallery).catch(() => {}); }, []);@@ -211,6 +214,11 @@ export default function VideoGen() {visibleHistory: history.filter((v) => !v.hidden),hiddenHistory: history.filter((v) => v.hidden),}), [history]);+ const previewItems = useMemo(() => [+ ...visibleHistory.map(normalizeVideo),+ ...(showHidden ? hiddenHistory.map(normalizeVideo) : []),+ ], [visibleHistory, hiddenHistory, showHidden]);+ const previewNavProps = getMediaNavProps(previewItems, preview, setPreview);const handleDeleteHistory = async (item) => {await deleteVideoHistoryItem(item.id).catch((err) => toast.error(err.message || 'Delete failed'));@@ -1327,6 +1335,7 @@ export default function VideoGen() {item={preview}onClose={() => setPreview(null)}onContinue={(item) => handleContinueHistory(item.raw)}+ {...previewNavProps}/><Drawer open={settingsOpen} onClose={closeSettings} title="Media Generation Settings">diff --git a/client/src/pages/WorldBuilder.jsx b/client/src/pages/WorldBuilder.jsxindex 8719db03ee..dc1d3cec2b 100644--- a/client/src/pages/WorldBuilder.jsx+++ b/client/src/pages/WorldBuilder.jsx@@ -74,6 +74,15 @@ const DEFAULT_RENDER_OPTS = {batchPerVariation: 1,};+// Mirror of COMPOSITE_SHEET_KINDS in server/services/worldBuilder.js — keep+// in sync when adding kinds.+const COMPOSITE_BOARD_KINDS = [+ { value: 'reference_sheet', label: 'Reference sheet' },+ { value: 'world_pitch_poster', label: 'World pitch poster' },+];++const compositeKindLabel = (kind) => COMPOSITE_BOARD_KINDS.find((k) => k.value === kind)?.label || 'Reference sheet';+const emptyTemplate = () => ({name: '',starterPrompt: '',@@ -273,11 +282,11 @@ export default function WorldBuilder() {const without = prev.filter((w) => w.id !== updated.id);return [updated, ...without];});- toast.success(`Expanded into ${total} variations and ${expandedDraft.compositeSheets?.length || 0} sheets — saved`);+ toast.success(`Expanded into ${total} variations and ${expandedDraft.compositeSheets?.length || 0} boards — saved`);return;}}- toast.success(`Expanded into ${total} variations and ${expandedDraft.compositeSheets?.length || 0} sheets — review then Save`);+ toast.success(`Expanded into ${total} variations and ${expandedDraft.compositeSheets?.length || 0} boards — review then Save`);};const handleRender = async () => {@@ -489,7 +498,7 @@ export default function WorldBuilder() {Expand starter → variations</button><span className="text-xs text-gray-500">- {totalVariations} variation{totalVariations === 1 ? '' : 's'} across {categoryKeys.length} categories · {totalSheets} composite sheet{totalSheets === 1 ? '' : 's'}+ {totalVariations} variation{totalVariations === 1 ? '' : 's'} across {categoryKeys.length} categories · {totalSheets} composite board{totalSheets === 1 ? '' : 's'}</span></div></header>@@ -596,7 +605,7 @@ export default function WorldBuilder() {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="sheets" disabled={totalSheets === 0}>Composite boards ({totalSheets})</option><option value="variations" disabled={totalVariations === 0}>Atomic variations ({totalVariations})</option><option value="all" disabled={totalSheets + totalVariations === 0}>Everything ({totalSheets + totalVariations})</option></select>@@ -689,9 +698,11 @@ function renderPromptCount(world, promptMode = 'variations') {function CompositeSheetsEditor({ sheets, onChange }) {const [adding, setAdding] = useState(false);+ const [newKind, setNewKind] = useState('reference_sheet');const [newLabel, setNewLabel] = useState('');const [newPrompt, setNewPrompt] = useState('');const [editIdx, setEditIdx] = useState(null);+ const [editKind, setEditKind] = useState('reference_sheet');const [editLabel, setEditLabel] = useState('');const [editPrompt, setEditPrompt] = useState('');@@ -699,7 +710,8 @@ function CompositeSheetsEditor({ sheets, onChange }) {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) }]);+ onChange([...sheets, { kind: newKind, label: label.slice(0, 120), prompt: prompt.slice(0, COMPOSITE_PROMPT_MAX) }]);+ setNewKind('reference_sheet');setNewLabel('');setNewPrompt('');setAdding(false);@@ -709,6 +721,7 @@ function CompositeSheetsEditor({ sheets, onChange }) {const startEdit = (idx, sheet) => {setEditIdx(idx);+ setEditKind(sheet.kind || 'reference_sheet');setEditLabel(sheet.label);setEditPrompt(sheet.prompt);};@@ -718,7 +731,7 @@ function CompositeSheetsEditor({ sheets, onChange }) {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) };+ next[editIdx] = { kind: editKind, label: label.slice(0, 120), prompt: prompt.slice(0, COMPOSITE_PROMPT_MAX) };onChange(next);setEditIdx(null);};@@ -727,7 +740,7 @@ function CompositeSheetsEditor({ sheets, onChange }) {<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+ Composite boards<span className="ml-2 text-xs text-gray-500">{sheets.length}</span></h2><button@@ -739,17 +752,28 @@ function CompositeSheetsEditor({ sheets, onChange }) {</div>{adding && (<div className="bg-port-bg border border-port-border rounded p-2 flex flex-col gap-2">+ <select+ value={newKind}+ onChange={(e) => setNewKind(e.target.value)}+ className="bg-port-card border border-port-border rounded px-2 py-1 text-white text-sm min-h-[40px]"+ >+ {COMPOSITE_BOARD_KINDS.map((kind) => (+ <option key={kind.value} value={kind.value}>{kind.label}</option>+ ))}+ </select><inputvalue={newLabel}onChange={(e) => setNewLabel(e.target.value)}- placeholder="Gas-Giant Drifters costume sheet"+ placeholder={newKind === 'world_pitch_poster' ? 'World summary concept pitch poster' : 'Gas-Giant Drifters costume sheet'}className="bg-port-card border border-port-border rounded px-2 py-1 text-white text-sm"maxLength={120}/><textareavalue={newPrompt}onChange={(e) => setNewPrompt(e.target.value)}- placeholder="Create a clean illustrated costume reference sheet..."+ placeholder={newKind === 'world_pitch_poster'+ ? 'Create a cinematic world summary concept pitch poster with a hero panorama, inset environments, cultures, creatures, visual language, palette, materials, and theme icons...'+ : '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}@@ -763,7 +787,12 @@ function CompositeSheetsEditor({ sheets, onChange }) {Save</button><button- onClick={() => { setAdding(false); setNewLabel(''); setNewPrompt(''); }}+ onClick={() => {+ setAdding(false);+ setNewKind('reference_sheet');+ 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@@ -772,13 +801,22 @@ function CompositeSheetsEditor({ sheets, onChange }) {</div>)}{sheets.length === 0 ? (- <p className="text-xs text-gray-500">No composite sheets yet.</p>+ <p className="text-xs text-gray-500">No composite boards 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">+ <select+ value={editKind}+ onChange={(e) => setEditKind(e.target.value)}+ className="bg-port-card border border-port-border rounded px-2 py-1 text-white text-sm min-h-[40px]"+ >+ {COMPOSITE_BOARD_KINDS.map((kind) => (+ <option key={kind.value} value={kind.value}>{kind.label}</option>+ ))}+ </select><inputvalue={editLabel}onChange={(e) => setEditLabel(e.target.value)}@@ -800,7 +838,12 @@ function CompositeSheetsEditor({ sheets, onChange }) {) : (<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="flex items-center gap-2">+ <div className="text-white font-medium truncate">{sheet.label}</div>+ <span className="shrink-0 text-[10px] uppercase tracking-wide px-1.5 py-0.5 rounded bg-port-accent/10 text-port-accent border border-port-accent/20">+ {compositeKindLabel(sheet.kind)}+ </span>+ </div><div className="text-xs text-gray-400 line-clamp-3">{sheet.prompt}</div></div><div className="flex items-center gap-1 shrink-0">diff --git a/server/routes/worldBuilder.js b/server/routes/worldBuilder.jsindex 90a534eade..463fe0ef56 100644--- a/server/routes/worldBuilder.js+++ b/server/routes/worldBuilder.js@@ -42,6 +42,7 @@ const variationSchema = z.object({prompt: z.string().trim().min(1).max(svc.PROMPT_FRAGMENT_MAX),});const compositeSheetSchema = z.object({+ kind: z.enum(svc.COMPOSITE_SHEET_KINDS).optional(),label: z.string().trim().min(1).max(svc.VARIATION_LABEL_MAX),prompt: z.string().trim().min(1).max(svc.COMPOSITE_PROMPT_MAX),});diff --git a/server/routes/worldBuilder.test.js b/server/routes/worldBuilder.test.jsindex 07f8004474..aa29b0ac72 100644--- a/server/routes/worldBuilder.test.js+++ b/server/routes/worldBuilder.test.js@@ -31,7 +31,8 @@ vi.mock('../services/worldBuilderExpand.js', () => ({vehicles: { variations: [] },},compositeSheets: [- { label: 'Mock costume sheet', prompt: 'mocked complete costume reference sheet with lineup, materials, fasteners, palette' },+ { kind: 'reference_sheet', label: 'Mock costume sheet', prompt: 'mocked complete costume reference sheet with lineup, materials, fasteners, palette' },+ { kind: 'world_pitch_poster', label: 'Mock world pitch poster', prompt: 'mocked world summary concept pitch poster with hero panorama, inset cultures, palette, materials, and theme icons' },],llm: { provider: 'anthropic', model: 'claude' },})),@@ -122,9 +123,24 @@ describe('world-builder routes', () => {});expect(res.status).toBe(201);expect(res.body.compositeSheets).toHaveLength(1);+ expect(res.body.compositeSheets[0].kind).toBe('reference_sheet');expect(res.body.compositeSheets[0].label).toBe('Gas-Giant Drifters sheet');});+ it('POST / accepts world pitch poster composite prompts', async () => {+ const res = await request(buildApp())+ .post('/api/world-builder')+ .send({+ name: 'Pitch Posters',+ compositeSheets: [+ { kind: 'world_pitch_poster', label: 'World summary concept pitch poster', prompt: 'Create a cinematic world summary concept pitch poster with hero panorama, inset environments, cultures, creatures, visual language strip, color palette, materials, light atmosphere, and theme icons.' },+ ],+ });+ expect(res.status).toBe(201);+ expect(res.body.compositeSheets).toHaveLength(1);+ expect(res.body.compositeSheets[0].kind).toBe('world_pitch_poster');+ });+it('POST / rejects missing name', async () => {const res = await request(buildApp()).post('/api/world-builder')@@ -159,7 +175,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.compositeSheets).toHaveLength(2);expect(res.body.llm.provider).toBe('anthropic');});diff --git a/server/services/worldBuilder.js b/server/services/worldBuilder.jsindex 3b7f697af0..3aca2a998c 100644--- a/server/services/worldBuilder.js+++ b/server/services/worldBuilder.js@@ -9,9 +9,9 @@* 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+ * - compositeSheets: complete board/poster prompts that combine several+ * buckets into one image, e.g. a colony costume guide or a world summary+ * concept pitch poster** 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@@ -42,6 +42,10 @@ 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 COMPOSITE_SHEET_KINDS = Object.freeze([+ 'reference_sheet',+ 'world_pitch_poster',+]);export const WORLD_CATEGORY_KEY_MAX = 64;export const WORLD_CATEGORY_COUNT_MAX = 30;@@ -86,7 +90,8 @@ const sanitizeCompositeSheet = (raw) => {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 kind = COMPOSITE_SHEET_KINDS.includes(raw.kind) ? raw.kind : 'reference_sheet';+ return { kind, label, prompt };};const sanitizeCategory = (raw) => {@@ -373,9 +378,12 @@ export function compilePrompts(world, options = {}) {: 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(', ');+ const category = sheet.kind === 'world_pitch_poster'+ ? 'world_pitch_posters'+ : 'composite_sheets';for (let i = 0; i < batchPerVariation; i += 1) {compiled.push({- category: 'composite_sheets',+ category,label: sheet.label,prompt,negativePrompt,diff --git a/server/services/worldBuilder.test.js b/server/services/worldBuilder.test.jsindex 6bf1c94730..ace2e4cebe 100644--- a/server/services/worldBuilder.test.js+++ b/server/services/worldBuilder.test.js@@ -79,7 +79,18 @@ describe('worldBuilder service', () => {],});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.' },+ { kind: 'reference_sheet', label: 'Gas-Giant Drifters costume sheet', prompt: 'Create a clean illustrated costume reference sheet with five figures, materials swatches, fasteners, accessories, and color palette strip.' },+ ]);+ });++ it('createWorld persists world pitch poster prompts separately from categories', async () => {+ const w = await seedWorld({+ compositeSheets: [+ { kind: 'world_pitch_poster', label: 'World summary concept pitch poster', prompt: 'Create a cinematic world summary concept pitch poster with hero panorama, inset environments, cultures, creatures, visual language, color palette, materials, light atmosphere, and theme icons.' },+ ],+ });+ expect(w.compositeSheets).toEqual([+ { kind: 'world_pitch_poster', label: 'World summary concept pitch poster', prompt: 'Create a cinematic world summary concept pitch poster with hero panorama, inset environments, cultures, creatures, visual language, color palette, materials, light atmosphere, and theme icons.' },]);});@@ -202,6 +213,21 @@ describe('worldBuilder service', () => {});});+ it('tags world pitch poster prompts separately from reference sheets', async () => {+ const w = await seedWorld({+ categories: {},+ compositeSheets: [+ { kind: 'world_pitch_poster', label: 'World pitch poster', prompt: 'cinematic world summary pitch poster, hero panorama, inset cultures, palette, themes' },+ ],+ });+ const compiled = svc.compilePrompts(w, { promptMode: 'sheets' });+ expect(compiled).toHaveLength(1);+ expect(compiled[0]).toMatchObject({+ category: 'world_pitch_posters',+ label: 'World pitch poster',+ });+ });+it('can compile atomic variations and composite sheets together', async () => {const w = await seedWorld({compositeSheets: [diff --git a/server/services/worldBuilderExpand.js b/server/services/worldBuilderExpand.jsindex d11fe6f9d9..391f9c4c41 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: { ... }, compositeSheets: [{ label, prompt }] }+ * { stylePrompt, negativePrompt, categories: { ... }, compositeSheets: [{ kind, 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@@ -39,7 +39,7 @@ Return a SINGLE JSON object. NO markdown, NO commentary. The object MUST have th${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.+- compositeSheets: array. Complete, ready-to-render composite board prompts. Each item has { "kind": "reference_sheet" | "world_pitch_poster", "label": string, "prompt": string up to 4000 chars }. These are NOT atomic fragments; each prompt must describe one complete board/poster 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": [@@ -48,19 +48,23 @@ 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." }+Concrete compositeSheets examples:+ { "kind": "reference_sheet", "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." }+ { "kind": "world_pitch_poster", "label": "World summary concept pitch poster", "prompt": "Create a cinematic world summary concept pitch poster for the whole setting. Use an editorial art-board layout: one dominant hero panorama showing the signature world location, several smaller inset environment and culture images, a small creature/species lineup, visual-language thumbnails, color palette strip, material/texture swatches, light-and-atmosphere notes, and theme icons. Include large title typography and a short subtitle/logline area, plus readable section headers such as The World, The Feel, Aesthetic, Environments, Cultures, Tone, Color Palette, Materials & Textures, and Light & Atmosphere. Keep body copy as short graphic blocks, not dense paragraphs. The poster should feel like a concept pitch board for a film/series/game, with clear hierarchy, elegant negative space, and cohesive art direction." }# Rules- 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.+- Generate 3-8 compositeSheets when the starter idea involves clothing systems, colonies, factions, cultures, species, vehicles, settlements, props, posters, decks, or other grouped visual-design systems.+- For broad world/universe/story settings, always include 1-3 "world_pitch_poster" compositeSheets in addition to any "reference_sheet" boards. These are summary concept pitch posters, not atomic character or environment sheets.- "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.+- If the user asks for style sheets, reference sheets, clothing guides, materials, colonies, factions, tribes, species, pirate/raider groups, world summary boards, concept pitch posters, or pitch-deck posters, 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.+- Reference-sheet prompts must include a clear board structure: title/subject, 4-6 figure lineup roles when relevant, 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.+- World pitch poster prompts must include a clear editorial poster structure: world title/subtitle/logline area, dominant hero panorama, inset environment/culture/creature images, visual-language strip, color palette, materials/textures, light/atmosphere, themes/icons, and concise labeled blocks for world, feel, aesthetic, environments, cultures, and tone. Mention that body copy should be short, clean, and readable; avoid dense tiny text.+- If the world needs pitch posters, do not put "text" in the negativePrompt. Prefer "watermark, logo, unreadable tiny text, text artifacts" so title/section typography remains possible.- Output JUST the JSON object. No prose before or after.`;const isCliProvider = (provider) => provider?.type === 'cli';diff --git a/server/services/worldBuilderExpand.test.js b/server/services/worldBuilderExpand.test.jsindex 1ee8db1b21..682ba70677 100644--- a/server/services/worldBuilderExpand.test.js+++ b/server/services/worldBuilderExpand.test.js@@ -189,6 +189,7 @@ describe('worldBuilderExpand.normalizeCompositeSheets', () => {]);expect(out).toEqual([{+ kind: 'reference_sheet',label: 'Gas-Giant Drifters costume sheet',prompt: 'Create a clean illustrated costume reference sheet with five figures, material swatches, fasteners, accessories, color palette strip, and simple floating-platform background.',},@@ -198,9 +199,33 @@ describe('worldBuilderExpand.normalizeCompositeSheets', () => {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' },+ { kind: 'reference_sheet', label: 'Canopy Symbiotes reference board', prompt: 'Canopy Symbiotes reference board' },]);});++ it('preserves world pitch poster board kind', () => {+ const out = normalizeCompositeSheets([+ {+ kind: 'world_pitch_poster',+ label: 'World summary concept pitch poster',+ prompt: 'Create a cinematic world summary concept pitch poster with hero panorama, inset environments, culture callouts, palette, materials, light atmosphere, and theme icons.',+ },+ ]);+ expect(out).toEqual([+ {+ kind: 'world_pitch_poster',+ label: 'World summary concept pitch poster',+ prompt: 'Create a cinematic world summary concept pitch poster with hero panorama, inset environments, culture callouts, palette, materials, light atmosphere, and theme icons.',+ },+ ]);+ });++ it('falls back to reference_sheet for unknown kinds', () => {+ const out = normalizeCompositeSheets([+ { kind: 'bogus_kind', label: 'Mystery board', prompt: 'A board of unknown lineage with figures, palette, materials, and atmosphere.' },+ ]);+ expect(out[0].kind).toBe('reference_sheet');+ });});describe('worldBuilderExpand.EXPANSION_PROMPT', () => {@@ -210,6 +235,8 @@ describe('worldBuilderExpand.EXPANSION_PROMPT', () => {expect(EXPANSION_PROMPT).toContain('clothing guides');expect(EXPANSION_PROMPT).toContain('raider_clans');expect(EXPANSION_PROMPT).toContain('compositeSheets');+ expect(EXPANSION_PROMPT).toContain('world_pitch_poster');+ expect(EXPANSION_PROMPT).toContain('world summary concept pitch poster');expect(EXPANSION_PROMPT).toContain('materials swatches');});});