Skip to content

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

refactor([issue-2532]): extract Universe Builder panels

[._.]/ Adam Eivy3aa81a404e9a
diff --git a/client/src/components/universeBuilder/UniverseBibleTab.jsx b/client/src/components/universeBuilder/UniverseBibleTab.jsx
new file mode 100644
index 0000000000..7d1a9a6d8a
--- /dev/null
+++ b/client/src/components/universeBuilder/UniverseBibleTab.jsx
@@ -0,0 +1,386 @@
+import { useState } from 'react';
+import {
+ Images, Loader2, Lock, MessageSquarePlus, Unlock, Wand2, X,
+} from 'lucide-react';
+import {
+ WORLD_LOGLINE_MAX,
+ WORLD_PREMISE_MAX,
+ WORLD_STYLE_NOTES_MAX,
+ ensureInfluences,
+} from '../../services/api';
+import ProviderModelSelector from '../ProviderModelSelector';
+import GalleryImagePicker from '../imageGen/GalleryImagePicker';
+import MoodBoardReferenceStrip from '../moodBoard/MoodBoardReferenceStrip';
+import StyleProbeImage from '../universe/StyleProbeImage';
+import VisionProviderPicker from '../universe/VisionProviderPicker';
+import InfluenceChipsInput from './InfluenceChipsInput';
+
+function LockButton({ field, locked, onToggle, label }) {
+ const isLocked = !!locked?.[field];
+ const Icon = isLocked ? Lock : Unlock;
+ return (
+ <button
+ type="button"
+ onClick={() => onToggle(field)}
+ className={`p-1 rounded -mr-1 transition-colors ${
+ isLocked
+ ? 'bg-port-accent/20 text-port-accent ring-1 ring-port-accent/50 hover:bg-port-accent/30'
+ : 'text-gray-600 hover:text-gray-300 hover:bg-white/5'
+ }`}
+ title={isLocked ? `${label} locked — AI refine/expand will skip it` : `Lock ${label} against AI refine/expand`}
+ aria-label={isLocked ? `Unlock ${label}` : `Lock ${label}`}
+ aria-pressed={isLocked}
+ >
+ <Icon size={13} />
+ </button>
+ );
+}
+
+// Render a label row with the field name + lock toggle. Used by every
+// lockable bible/prompt field so the lock UI stays consistent.
+function FieldLabel({ htmlFor, children, field, locked, onToggleLock }) {
+ return (
+ <div className="flex items-center justify-between gap-2 mb-1">
+ <label htmlFor={htmlFor} className="text-xs text-gray-400">{children}</label>
+ <LockButton field={field} locked={locked} onToggle={onToggleLock} label={typeof children === 'string' ? children : field} />
+ </div>
+ );
+}
+
+// Style prompt + Negative prompt editor — two parallel chip lists. Embrace
+// tokens become the positive style prompt prepended to every render; avoid
+// tokens become the negative prompt. Each list locks independently.
+function StyleNegativePromptEditor({ influences, onChange, locked, onToggleLock }) {
+ const safe = ensureInfluences(influences);
+ return (
+ <div>
+ <div className="mb-1">
+ <label className="text-xs text-gray-400">
+ Style + Negative prompts <span className="text-gray-600">— prepended to every render; drag to reorder, click × to remove</span>
+ </label>
+ </div>
+ <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
+ <div>
+ <div className="flex items-center justify-between gap-2 mb-1">
+ <div className="text-[11px] uppercase tracking-wide text-port-success/80">Style prompt (embrace)</div>
+ <LockButton field="influencesEmbrace" locked={locked} onToggle={onToggleLock} label="Style prompt" />
+ </div>
+ <InfluenceChipsInput
+ tokens={safe.embrace}
+ onChange={(next) => onChange({ ...safe, embrace: next })}
+ placeholder="moebius linework, cel-shading, dust palette…"
+ tone="success"
+ readOnly={!!locked?.influencesEmbrace}
+ />
+ </div>
+ <div>
+ <div className="flex items-center justify-between gap-2 mb-1">
+ <div className="text-[11px] uppercase tracking-wide text-port-error/80">Negative prompt (avoid)</div>
+ <LockButton field="influencesAvoid" locked={locked} onToggle={onToggleLock} label="Negative prompt" />
+ </div>
+ <InfluenceChipsInput
+ tokens={safe.avoid}
+ onChange={(next) => onChange({ ...safe, avoid: next })}
+ placeholder="blurry, lowres, watermark, neon cyberpunk…"
+ tone="error"
+ readOnly={!!locked?.influencesAvoid}
+ />
+ </div>
+ </div>
+ </div>
+ );
+}
+
+// Universe autocomplete combobox: search existing universes or create one when
+// the trimmed query doesn't exactly match any. `onCreate` is wired to a
+// dedicated create path (not handleSave) so typing a new name while an existing
+// universe is selected never accidentally renames it. The match-or-create UX
+// lives in the shared `EntityCombobox`; this thin wrapper maps universes into
+// its `{ id, name, subtitle }` item shape and preserves the universe-specific
+// labels/ids.
+export default function BibleTab({
+ draft, updateDraft, toggleLock,
+ llm,
+ handleExpand, expanding, saving,
+ refine,
+ totalVariations, categoryKeyCount, totalSheets,
+ onPreview,
+ onStyleProbeRenderComplete = null,
+ styleProbeDirty = false,
+}) {
+ const { providers, providerModels, providerLabel, activeProviderId } = llm;
+ const {
+ open: refineOpen, setOpen: setRefineOpen,
+ feedback: refineFeedback, setFeedback: setRefineFeedback,
+ run: runRefine, running: refining, reset: resetRefinePanel,
+ rationale: refineRationale, changes: refineChanges,
+ image: refineImage, setImage: setRefineImage,
+ } = refine;
+ // Local-only: gallery picker visibility for the optional style-reference image.
+ const [refineGalleryOpen, setRefineGalleryOpen] = useState(false);
+ // Vision provider/model selection, lifted from VisionProviderPicker — which is
+ // mounted only when a style-reference image is attached, so the refine runs
+ // through a vision-capable API provider (not the universe's default expansion
+ // LLM) and the provider fetch is deferred until it's actually needed.
+ const [refineVision, setRefineVision] = useState({ providerId: '', model: '', hasProviders: false, noVisionModel: false });
+ return (
+ <>
+ <section className="bg-port-card border border-port-border rounded p-4 flex flex-col gap-3">
+ <div className="grid grid-cols-1 md:grid-cols-[1fr_220px] gap-3">
+ <div>
+ <FieldLabel field="starterPrompt" locked={draft.locked} onToggleLock={toggleLock}>
+ Starter idea
+ </FieldLabel>
+ <textarea
+ value={draft.starterPrompt}
+ onChange={(e) => updateDraft({ starterPrompt: e.target.value })}
+ placeholder="moebius and scavengers reign meets Prophet inspired sci fi universe"
+ className="w-full bg-port-bg border border-port-border rounded px-3 py-2 text-white text-sm focus:outline-none focus:border-port-accent"
+ rows={2}
+ />
+ </div>
+ <div>
+ <p className="text-xs text-gray-400 mb-1 block">LLM for expansion</p>
+ {/* The selection here is part of the draft and persisted to the
+ server (feeds expand/render), not ephemeral like the Importer —
+ so we drive it from `draft.llm` and use only the shared
+ component, not useProviderModels' auto-select/load machinery. */}
+ <ProviderModelSelector
+ providers={providers}
+ selectedProviderId={draft.llm?.provider ?? ''}
+ selectedModel={draft.llm?.model || ''}
+ availableModels={providerModels}
+ onProviderChange={(id) => updateDraft({ llm: { ...draft.llm, provider: id || null, model: null } })}
+ onModelChange={(m) => updateDraft({ llm: { ...draft.llm, model: m || null } })}
+ compact
+ label="LLM for expansion"
+ layout="stacked"
+ emptyProviderOption={`Active provider (${providerLabel(activeProviderId)})`}
+ emptyModelOption="Default model"
+ alwaysShowModel
+ />
+ </div>
+ </div>
+
+ <MoodBoardReferenceStrip storageKey="universe-builder" />
+
+ <div className="flex items-center gap-2 flex-wrap">
+ <button
+ onClick={handleExpand}
+ disabled={expanding || saving || !draft.starterPrompt?.trim()}
+ className="px-3 py-2 bg-port-accent-2/30 hover:bg-port-accent-2/50 disabled:opacity-50 text-port-accent-2 border border-port-accent-2/40 rounded flex items-center gap-2 min-h-[40px]"
+ >
+ {expanding ? <Loader2 size={16} className="animate-spin" /> : <Wand2 size={16} />}
+ Generate From Idea
+ </button>
+ <button
+ onClick={() => setRefineOpen((v) => !v)}
+ disabled={!draft.starterPrompt?.trim()}
+ aria-expanded={refineOpen}
+ className={`px-3 py-2 disabled:opacity-50 text-port-accent border border-port-accent/40 rounded flex items-center gap-2 min-h-[40px] ${
+ refineOpen ? 'bg-port-accent/25' : 'bg-port-accent/15 hover:bg-port-accent/25'
+ }`}
+ title="Give feedback to refine the prompts in place — uses the LLM picked above"
+ >
+ <MessageSquarePlus size={16} />
+ Refine prompts
+ </button>
+ <span className="text-xs text-gray-500">
+ {totalVariations} variation{totalVariations === 1 ? '' : 's'} across {categoryKeyCount} categories · {totalSheets} composite board{totalSheets === 1 ? '' : 's'}
+ </span>
+ </div>
+
+ {refineOpen && (
+ <div className="border border-port-accent/40 bg-port-accent/5 rounded p-3 flex flex-col gap-2">
+ <label htmlFor="world-refine-feedback" className="text-[11px] uppercase tracking-wide text-gray-500">
+ Feedback — describe what you want changed
+ </label>
+ <textarea
+ id="world-refine-feedback"
+ value={refineFeedback}
+ onChange={(e) => setRefineFeedback(e.target.value)}
+ placeholder="e.g. lean grimmer and more spiritual; pull style toward Moebius + Tarkovsky; avoid neon and cyberpunk clichés."
+ rows={3}
+ disabled={refining}
+ className="w-full bg-port-bg border border-port-border rounded p-2 text-sm text-white placeholder-gray-500 focus:outline-none focus:border-port-accent resize-y disabled:opacity-60"
+ />
+ {/* Optional visual style reference from the gallery — when set, the
+ server refines through a vision-capable API provider. */}
+ <div className="flex items-center gap-2 flex-wrap">
+ <span className="text-[11px] uppercase tracking-wide text-gray-500">Style reference (optional)</span>
+ {refineImage ? (
+ <div className="relative w-14 h-14">
+ <img
+ src={refineImage.preview || `/data/images/${encodeURIComponent(refineImage.filename)}`}
+ alt="style reference"
+ className="w-full h-full object-cover rounded border border-port-border"
+ />
+ <button
+ type="button"
+ onClick={() => setRefineImage(null)}
+ title="Remove reference image"
+ aria-label="Remove reference image"
+ className="absolute -top-1.5 -right-1.5 bg-port-bg border border-port-border rounded-full p-0.5 text-gray-400 hover:text-port-error"
+ >
+ <X size={11} />
+ </button>
+ </div>
+ ) : (
+ <button
+ type="button"
+ onClick={() => setRefineGalleryOpen(true)}
+ disabled={refining}
+ className="px-2.5 py-1.5 text-xs text-port-accent border border-port-accent/40 rounded flex items-center gap-1.5 hover:bg-port-accent/10 disabled:opacity-50"
+ >
+ <Images size={14} />
+ Pick from gallery
+ </button>
+ )}
+ {refineImage ? (
+ <span className="text-[11px] text-gray-500">Folds the image's palette/mood into influences + style notes.</span>
+ ) : null}
+ </div>
+ {/* Vision provider/model picker — only when an image is attached, since
+ the server forces a vision-capable API provider for image refine.
+ Mounting it conditionally also defers its provider fetch. */}
+ {refineImage ? (
+ <VisionProviderPicker label="Vision provider (for image refine)" onChange={setRefineVision} />
+ ) : null}
+ <div className="flex items-center gap-2 flex-wrap">
+ <button
+ type="button"
+ onClick={() => runRefine(refineImage
+ ? { providerId: refineVision.providerId, model: refineVision.model }
+ : null)}
+ disabled={refining || !refineFeedback.trim() || !draft.starterPrompt?.trim() || (!!refineImage && !refineVision.model)}
+ className="px-3 py-2 bg-port-accent hover:bg-port-accent/90 disabled:opacity-50 disabled:cursor-not-allowed text-white rounded flex items-center gap-2 min-h-[40px]"
+ >
+ {refining ? <Loader2 size={14} className="animate-spin" /> : <Wand2 size={14} />}
+ {refining ? 'Refining…' : 'Refine'}
+ </button>
+ <button
+ type="button"
+ onClick={resetRefinePanel}
+ disabled={refining}
+ className="px-3 py-2 text-sm text-gray-400 hover:text-white rounded min-h-[40px]"
+ >
+ Close
+ </button>
+ <span className="text-[11px] text-gray-500">
+ Applies in place — locked fields stay pinned.
+ </span>
+ </div>
+ {(refineRationale || refineChanges.length > 0) && (
+ <div className="border-t border-port-border/60 pt-2 mt-1 space-y-1.5">
+ {refineRationale && (
+ <p className="text-xs text-gray-300 whitespace-pre-wrap">{refineRationale}</p>
+ )}
+ {refineChanges.length > 0 && (
+ <ul className="text-[11px] text-gray-400 list-disc pl-5 space-y-0.5">
+ {refineChanges.map((c, idx) => (
+ <li key={idx}>{c}</li>
+ ))}
+ </ul>
+ )}
+ </div>
+ )}
+ <GalleryImagePicker
+ open={refineGalleryOpen}
+ onClose={() => setRefineGalleryOpen(false)}
+ onSelect={(item) => {
+ if (item?.filename) setRefineImage({ filename: item.filename, preview: item.previewUrl });
+ }}
+ />
+ </div>
+ )}
+ </section>
+
+ <section className="bg-port-card border border-port-border rounded p-4 flex flex-col gap-3">
+ <div>
+ <h2 className="text-sm font-semibold text-white">Story bible</h2>
+ <p className="text-xs text-gray-500 mt-0.5">
+ Pulled into the Pipeline → New Series form when this world is selected.
+ </p>
+ </div>
+ <div>
+ <FieldLabel htmlFor="world-logline" field="logline" locked={draft.locked} onToggleLock={toggleLock}>
+ Logline
+ </FieldLabel>
+ <input
+ id="world-logline"
+ type="text"
+ value={draft.logline || ''}
+ onChange={(e) => updateDraft({ logline: e.target.value })}
+ placeholder="One-sentence hook — A foundry city goes silent, and the only survivor is a child."
+ className="w-full bg-port-bg border border-port-border rounded px-3 py-2 text-white text-sm focus:outline-none focus:border-port-accent"
+ maxLength={WORLD_LOGLINE_MAX}
+ />
+ </div>
+ <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
+ <div>
+ <FieldLabel htmlFor="world-premise" field="premise" locked={draft.locked} onToggleLock={toggleLock}>
+ Premise
+ </FieldLabel>
+ <textarea
+ id="world-premise"
+ value={draft.premise || ''}
+ onChange={(e) => updateDraft({ premise: e.target.value })}
+ placeholder="Elevator pitch — 1-3 short paragraphs about the setting, central conflict, stakes, and tone."
+ className="w-full bg-port-bg border border-port-border rounded px-3 py-2 text-white text-sm focus:outline-none focus:border-port-accent"
+ rows={6}
+ maxLength={WORLD_PREMISE_MAX}
+ />
+ </div>
+ <div>
+ <FieldLabel htmlFor="world-style-notes" field="styleNotes" locked={draft.locked} onToggleLock={toggleLock}>
+ Style notes
+ </FieldLabel>
+ <textarea
+ id="world-style-notes"
+ value={draft.styleNotes || ''}
+ onChange={(e) => updateDraft({ styleNotes: e.target.value })}
+ placeholder="Narrative style: references (artists / films / comics), mood, palette, pacing, voice. Prose, not tokens."
+ className="w-full bg-port-bg border border-port-border rounded px-3 py-2 text-white text-sm focus:outline-none focus:border-port-accent"
+ rows={6}
+ maxLength={WORLD_STYLE_NOTES_MAX}
+ />
+ </div>
+ </div>
+ <StyleNegativePromptEditor
+ influences={draft.influences}
+ onChange={(next) => updateDraft({ influences: next })}
+ locked={draft.locked}
+ onToggleLock={toggleLock}
+ />
+ <div className="mt-4 pt-4 border-t border-port-border">
+ {/* StyleProbeImage persists styleImageRefs server-side itself; merge
+ only that field into the draft so unsaved style edits aren't lost.
+ `styleDirty` blocks the render while influences have unsaved edits —
+ otherwise the probe pins to a saved record that lacks that style. */}
+ {/* The probe's in-flight render state (the EntryThumbSlot spinner +
+ the async completion handler) is scoped to one universe by
+ `useSingleImageRender`'s `scopeId` (the universe id), so this stays
+ mounted across a `/universes/:id` switch WITHOUT a `key` remount —
+ no per-switch settings refetch, and switching back resumes a
+ still-running render instead of abandoning its completion. */}
+ <StyleProbeImage
+ universe={draft}
+ onUniverseChange={(updated) => updateDraft({ styleImageRefs: updated?.styleImageRefs || [] })}
+ onPreview={onPreview}
+ onRenderComplete={() => onStyleProbeRenderComplete?.()}
+ styleDirty={styleProbeDirty}
+ />
+ </div>
+ </section>
+ </>
+ );
+}
+
+// Sub-bucket chip strip used by TrunkView + OtherTab. The "All" chip is a
+// pseudo-bucket that clears `?bucket=`. Each real bucket key gets its own
+// chip; clicking toggles it on/off (toggle-off returns to All). Designed so
+// it works one-handed on mobile (38px tap targets, wraps to multiple lines).
+// Per-trunk view. Three modes driven by `?bucket=`:
+// - blank (default "All"): renders canon + every variation under this trunk
+// - BUCKET_CANON: renders only canon entries (via the existing UniverseCanonSection)
+// - <bucketKey>: renders that bucket's variations via CategoryEditor
diff --git a/client/src/components/universeBuilder/UniverseBuilderPage.jsx b/client/src/components/universeBuilder/UniverseBuilderPage.jsx
index 033d923cf2..b89e8acf55 100644
--- a/client/src/components/universeBuilder/UniverseBuilderPage.jsx
+++ b/client/src/components/universeBuilder/UniverseBuilderPage.jsx
@@ -1,147 +1,65 @@
/**
- * Universe Builder editor (Media Gen → Universe Builder).
+ * Universe Builder editor composition (Media Gen → Universe 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.
+ * Stateful record, expansion, gallery, and render concerns live in hooks.
+ * Tab-specific presentation lives in the sibling panel modules.
*/
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { Link, useLocation, useParams, useSearchParams } from 'react-router-dom';
import {
- Plus, Trash2, Sparkles, Wand2, Loader2, Save,
- Edit3, X, MessageSquarePlus, Play, Lock, Unlock,
- ArrowUpCircle, ArrowLeft,
- BookOpen, Users, MapPin, Package, Layers, ImagePlus, FolderTree, Images,
+ ArrowLeft, BookOpen, FolderTree, ImagePlus, Layers, Loader2,
+ MapPin, Package, Plus, Save, Trash2, Users,
} from 'lucide-react';
import toast from '../ui/Toast';
import InlineConfirmRow from '../ui/InlineConfirmRow';
import {
- updateUniverse,
- generateCategoryVariations, promoteVariationToCanon, autoSortBuckets,
- WORLD_CATEGORIES,
- WORLD_CATEGORY_KEY_MAX, WORLD_LOGLINE_MAX,
- WORLD_PREMISE_MAX, WORLD_STYLE_NOTES_MAX,
+ WORLD_CATEGORY_KEY_MAX,
+ autoSortBuckets,
ensureInfluences,
+ generateCategoryVariations,
+ promoteVariationToCanon,
+ updateUniverse,
} from '../../services/api';
-import useClickOutside from '../../hooks/useClickOutside';
-import EntityCombobox from '../EntityCombobox';
import useUniverseAction from '../../hooks/useUniverseAction';
-import { useUniverseNav } from '../../hooks/useUniverseNav';
-import InfluenceChipsInput from './InfluenceChipsInput';
-import CompositeSheetsEditor from './CompositeSheetsEditor';
-import BucketChipStrip from './BucketChipStrip';
-import RenderTab from './RenderTab';
-import ProviderModelSelector from '../ProviderModelSelector';
-import VisionProviderPicker from '../universe/VisionProviderPicker';
-import GalleryImagePicker from '../imageGen/GalleryImagePicker';
-import ShareToButton from '../sharing/ShareToButton';
-import SyncToPeerButton from '../sharing/SyncToPeerButton';
-import OriginBadge from '../sharing/OriginBadge';
-import MoodBoardReferenceStrip from '../moodBoard/MoodBoardReferenceStrip';
-import UniverseCanonSection from '../universe/UniverseCanonSection';
-import StyleProbeImage from '../universe/StyleProbeImage';
-import EntryCard from '../universe/EntryCard';
-import EntryThumbSlot from '../universe/EntryThumbSlot';
-import useMediaJobProgress from '../../hooks/useMediaJobProgress';
-import MediaPreview from '../media/MediaPreview';
-import useUniverseGallery from '../../hooks/useUniverseGallery';
import useUniverseDraft from '../../hooks/useUniverseDraft';
import useUniverseExpand from '../../hooks/useUniverseExpand';
+import useUniverseGallery from '../../hooks/useUniverseGallery';
+import { useUniverseNav } from '../../hooks/useUniverseNav';
import useUniverseRender from '../../hooks/useUniverseRender';
+import EntityCombobox from '../EntityCombobox';
+import MediaPreview from '../media/MediaPreview';
+import OriginBadge from '../sharing/OriginBadge';
+import ShareToButton from '../sharing/ShareToButton';
+import SyncToPeerButton from '../sharing/SyncToPeerButton';
import TabPills from '../ui/TabPills';
-import { upsertByIdPrepend } from '../../lib/upsertByIdPrepend';
+import CompositeSheetsEditor from './CompositeSheetsEditor';
+import RenderTab from './RenderTab';
+import UniverseBibleTab from './UniverseBibleTab';
+import { OtherTab, TrunkView } from './UniverseTrunkPanels';
import { capImageRefs } from '../../lib/bibleLimits';
+import { upsertByIdPrepend } from '../../lib/upsertByIdPrepend';
import { mergeVariations } from '../../lib/universeBuilderExpand';
+import { totalVariationCount } from '../../lib/universeBuilderCounts';
import {
- TAB_BIBLE, TAB_CAST, TAB_PLACES, TAB_OBJECTS, TAB_OTHER, TAB_COMPOSITES, TAB_RENDER,
- BUCKET_CANON, TRUNK_TABS, TRUNK_BY_ID, TRUNK_BY_KIND,
- groupBucketsByKind, humanizeCategory, normalizeCategoryKey,
+ BUCKET_CANON,
+ TAB_BIBLE,
+ TAB_CAST,
+ TAB_COMPOSITES,
+ TAB_OBJECTS,
+ TAB_OTHER,
+ TAB_PLACES,
+ TAB_RENDER,
+ TRUNK_BY_ID,
+ TRUNK_TABS,
getCategoryKeys,
+ groupBucketsByKind,
+ humanizeCategory,
} from '../../lib/universeBuilderShared';
-import {
- totalVariationCount, canonEntryHasContent,
-} from '../../lib/universeBuilderCounts';
-
-// Renders a small lock-toggle button to the right of a field label. The user
-// clicks it to pin a field against AI refinement/expansion. The icon flips
-// between locked (filled) and unlocked (outline) to make state obvious.
-function LockButton({ field, locked, onToggle, label }) {
- const isLocked = !!locked?.[field];
- const Icon = isLocked ? Lock : Unlock;
- return (
- <button
- type="button"
- onClick={() => onToggle(field)}
- className={`p-1 rounded -mr-1 transition-colors ${
- isLocked
- ? 'bg-port-accent/20 text-port-accent ring-1 ring-port-accent/50 hover:bg-port-accent/30'
- : 'text-gray-600 hover:text-gray-300 hover:bg-white/5'
- }`}
- title={isLocked ? `${label} locked — AI refine/expand will skip it` : `Lock ${label} against AI refine/expand`}
- aria-label={isLocked ? `Unlock ${label}` : `Lock ${label}`}
- aria-pressed={isLocked}
- >
- <Icon size={13} />
- </button>
- );
-}
-// Render a label row with the field name + lock toggle. Used by every
-// lockable bible/prompt field so the lock UI stays consistent.
-function FieldLabel({ htmlFor, children, field, locked, onToggleLock }) {
- return (
- <div className="flex items-center justify-between gap-2 mb-1">
- <label htmlFor={htmlFor} className="text-xs text-gray-400">{children}</label>
- <LockButton field={field} locked={locked} onToggle={onToggleLock} label={typeof children === 'string' ? children : field} />
- </div>
- );
-}
+export { CategoryEditor } from './UniverseCategoryEditor';
+export { OtherTab, TrunkView };
-// Style prompt + Negative prompt editor — two parallel chip lists. Embrace
-// tokens become the positive style prompt prepended to every render; avoid
-// tokens become the negative prompt. Each list locks independently.
-function StyleNegativePromptEditor({ influences, onChange, locked, onToggleLock }) {
- const safe = ensureInfluences(influences);
- return (
- <div>
- <div className="mb-1">
- <label className="text-xs text-gray-400">
- Style + Negative prompts <span className="text-gray-600">— prepended to every render; drag to reorder, click × to remove</span>
- </label>
- </div>
- <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
- <div>
- <div className="flex items-center justify-between gap-2 mb-1">
- <div className="text-[11px] uppercase tracking-wide text-port-success/80">Style prompt (embrace)</div>
- <LockButton field="influencesEmbrace" locked={locked} onToggle={onToggleLock} label="Style prompt" />
- </div>
- <InfluenceChipsInput
- tokens={safe.embrace}
- onChange={(next) => onChange({ ...safe, embrace: next })}
- placeholder="moebius linework, cel-shading, dust palette…"
- tone="success"
- readOnly={!!locked?.influencesEmbrace}
- />
- </div>
- <div>
- <div className="flex items-center justify-between gap-2 mb-1">
- <div className="text-[11px] uppercase tracking-wide text-port-error/80">Negative prompt (avoid)</div>
- <LockButton field="influencesAvoid" locked={locked} onToggle={onToggleLock} label="Negative prompt" />
- </div>
- <InfluenceChipsInput
- tokens={safe.avoid}
- onChange={(next) => onChange({ ...safe, avoid: next })}
- placeholder="blurry, lowres, watermark, neon cyberpunk…"
- tone="error"
- readOnly={!!locked?.influencesAvoid}
- />
- </div>
- </div>
- </div>
- );
-}
// Universe autocomplete combobox: search existing universes or create one when
// the trimmed query doesn't exactly match any. `onCreate` is wired to a
@@ -628,7 +546,7 @@ export default function UniverseBuilder() {
/>
{activeTab === TAB_BIBLE && (
- <BibleTab
+ <UniverseBibleTab
draft={draft}
updateDraft={updateDraft}
toggleLock={toggleLock}
@@ -847,1081 +765,3 @@ export default function UniverseBuilder() {
</div>
);
}
-
-
-const GENERATE_PRESETS = [3, 5, 10];
-const GENERATE_CUSTOM_MIN = 1;
-const GENERATE_CUSTOM_MAX = 50;
-
-export function CategoryEditor({
- category, variations, canRemove = false, onChange, onRemove,
- canRender = false, onRenderCategory = null, onRenderVariation = null,
- onGenerate = null,
- // `bucketKind` drives the promote-button UX: when `'other'` (or absent)
- // the picker opens to choose a trunk; otherwise we promote directly.
- // `canPromote` gates on universe-persisted (the action reads the saved record).
- canPromote = false, bucketKind = null, onPromote = null,
- // Only set by OtherTab — clicking opens a picker that retags the bucket's
- // `kind` to a canon trunk. Variations stay in place; bucket moves tabs.
- onAssignBucketKind = null,
- // Clicking the row's thumbnail opens the page-level MediaPreview lightbox
- // (same modal that the history / gallery uses). Receives the visible
- // filename so the modal lands on the exact ref the user saw, not a stale
- // primary that may have walked-back on a 404.
- onPreviewVariation = null,
- // Per-row render-pending plumbing — `pendingByEntryId[v.id]` returns the
- // in-flight jobId (or undefined). Completion / failure callbacks fire when
- // the row's MediaJobThumb settles.
- pendingByEntryId = {}, onJobCompleted = null, onJobFailed = null,
-}) {
- const requiresTargetKind = !TRUNK_BY_KIND[bucketKind];
- const [adding, setAdding] = useState(false);
- const [newLabel, setNewLabel] = useState('');
- const [newPrompt, setNewPrompt] = useState('');
- const [editIdx, setEditIdx] = useState(null);
- const [editLabel, setEditLabel] = useState('');
- const [editPrompt, setEditPrompt] = useState('');
- const [genOpen, setGenOpen] = useState(false);
- const [genCustom, setGenCustom] = useState('');
- const [generating, setGenerating] = useState(false);
- const [promotingIdx, setPromotingIdx] = useState(null);
- const [pickerIdx, setPickerIdx] = useState(null);
- const [assignOpen, setAssignOpen] = useState(false);
- const genWrapRef = useRef(null);
- const pickerWrapRef = useRef(null);
- const assignWrapRef = useRef(null);
-
- useClickOutside(genWrapRef, genOpen, () => setGenOpen(false));
- useClickOutside(pickerWrapRef, pickerIdx !== null, () => setPickerIdx(null));
- useClickOutside(assignWrapRef, assignOpen, () => setAssignOpen(false));
- useEffect(() => {
- if (!genOpen) return undefined;
- const onKey = (e) => { if (e.key === 'Escape') setGenOpen(false); };
- document.addEventListener('keydown', onKey);
- return () => document.removeEventListener('keydown', onKey);
- }, [genOpen]);
- useEffect(() => {
- if (pickerIdx === null) return undefined;
- const onKey = (e) => { if (e.key === 'Escape') setPickerIdx(null); };
- document.addEventListener('keydown', onKey);
- return () => document.removeEventListener('keydown', onKey);
- }, [pickerIdx]);
- useEffect(() => {
- if (!assignOpen) return undefined;
- const onKey = (e) => { if (e.key === 'Escape') setAssignOpen(false); };
- document.addEventListener('keydown', onKey);
- return () => document.removeEventListener('keydown', onKey);
- }, [assignOpen]);
-
- const editorMountedRef = useRef(true);
- useEffect(() => () => { editorMountedRef.current = false; }, []);
- const runPromote = async (idx, variation, opts) => {
- if (!onPromote) return;
- setPickerIdx(null);
- setPromotingIdx(idx);
- try {
- await onPromote(variation, opts);
- } finally {
- if (editorMountedRef.current) setPromotingIdx(null);
- }
- };
-
- const runGenerate = async (count) => {
- const n = Math.max(GENERATE_CUSTOM_MIN, Math.min(GENERATE_CUSTOM_MAX, parseInt(count, 10) || 0));
- if (!n || !onGenerate) return;
- setGenOpen(false);
- setGenerating(true);
- try {
- await onGenerate(n);
- } finally {
- setGenerating(false);
- setGenCustom('');
- }
- };
-
- const addVariation = () => {
- const label = newLabel.trim();
- const prompt = newPrompt.trim();
- if (!label || !prompt) return;
- // Stamp `locked: true` so the in-draft row matches the lock-by-default
- // contract before the next save round-trips through sanitizeVariation.
- // Without this, the bulk-toggle counts a freshly-added variation as
- // unlocked even though the user expects every new entry to land locked.
- onChange([...variations, { label: label.slice(0, 120), prompt: prompt.slice(0, 2000), locked: true }]);
- setNewLabel('');
- setNewPrompt('');
- setAdding(false);
- };
-
- const removeAt = (idx) => onChange(variations.filter((_, i) => i !== idx));
-
- // Variations default to locked at the sanitizer (locked-by-default contract),
- // so an unlock must persist as explicit `false` — not as an absent key —
- // otherwise the next read would re-lock the entry the user just unlocked.
- const toggleLockAt = (idx) => onChange(variations.map((v, i) => {
- if (i !== idx) return v;
- return { ...v, locked: !v.locked };
- }));
-
- // Bulk lock/unlock everything in this bucket. Same persistence contract:
- // unlock writes explicit `false` so it survives the round-trip.
- const setAllLocked = (nextLocked) =>
- onChange(variations.map((v) => (v?.locked === nextLocked ? v : { ...v, locked: nextLocked })));
- const lockedCount = variations.filter((v) => v?.locked === true).length;
- const allLocked = variations.length > 0 && lockedCount === variations.length;
-
- const startEdit = (idx, v) => {
- setEditIdx(idx);
- setEditLabel(v.label);
- 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];
- // Preserve `id`, `locked`, and `imageRefs` — only label + prompt are
- // editable in this row. A naive replacement would re-mint the variation's
- // id (breaking the link to its render history) and drop accrued imageRefs.
- // The server's stale-PATCH guard catches some of this via length + tail
- // comparison (variations with NEW renders in cur survive an empty patch),
- // but a stale variation whose history hasn't grown server-side since the
- // client loaded would still get its imageRefs cleared if we sent an empty
- // array. Echoing cur's array verbatim avoids relying on the guard.
- next[editIdx] = {
- ...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">
- {humanizeCategory(category)}
- <span className="ml-2 text-xs text-gray-500">{variations.length}</span>
- </h3>
- <div className="flex items-center gap-1">
- {onRenderCategory && (
- <button
- onClick={onRenderCategory}
- disabled={!canRender || variations.length === 0}
- className="p-1 text-port-accent hover:bg-port-accent/20 disabled:opacity-30 disabled:cursor-not-allowed rounded"
- title={variations.length === 0 ? 'Add variations first' : 'Render this category'}
- aria-label="Render this category"
- >
- <Play size={14} />
- </button>
- )}
- {onAssignBucketKind && requiresTargetKind && (
- <div className="relative" ref={assignWrapRef}>
- <button
- onClick={() => setAssignOpen((v) => !v)}
- className="p-1 text-port-accent hover:bg-port-accent/20 rounded"
- title="Move this bucket into a canon trunk (variations stay in place)"
- aria-label="Assign bucket to a canon trunk"
- aria-haspopup="menu"
- aria-expanded={assignOpen}
- >
- <FolderTree size={14} />
- </button>
- {assignOpen && (
- <div
- role="menu"
- className="absolute right-0 top-full mt-1 z-20 w-44 bg-port-card border border-port-border rounded shadow-lg p-1 flex flex-col gap-0.5"
- >
- <div className="px-2 pt-1 pb-1 text-[10px] uppercase tracking-wide text-gray-500">
- Move bucket to trunk
- </div>
- {TRUNK_TABS.map((trunk) => {
- const TrunkIcon = trunk.icon;
- return (
- <button
- key={trunk.kind}
- role="menuitem"
- onClick={() => { setAssignOpen(false); onAssignBucketKind(trunk.kind); }}
- className="text-left text-xs px-2 py-1.5 text-gray-200 hover:bg-port-accent/20 rounded flex items-center gap-2"
- >
- <TrunkIcon size={12} className="text-port-accent" /> {trunk.label}
- </button>
- );
- })}
- </div>
- )}
- </div>
- )}
- {onGenerate && (
- <div className="relative" ref={genWrapRef}>
- <button
- onClick={() => setGenOpen((v) => !v)}
- disabled={generating}
- className="p-1 text-port-accent hover:bg-port-accent/20 disabled:opacity-30 disabled:cursor-not-allowed rounded"
- title="Ask the LLM for more variations in this category"
- aria-label="Generate more variations"
- aria-haspopup="menu"
- aria-expanded={genOpen}
- >
- {generating ? <Loader2 size={14} className="animate-spin" /> : <Sparkles size={14} />}
- </button>
- {genOpen && (
- <div
- role="menu"
- className="absolute right-0 top-full mt-1 z-20 w-44 bg-port-card border border-port-border rounded shadow-lg p-1 flex flex-col gap-0.5"
- >
- {GENERATE_PRESETS.map((n) => (
- <button
- key={n}
- role="menuitem"
- onClick={() => runGenerate(n)}
- className="text-left text-xs px-2 py-1.5 text-gray-200 hover:bg-port-accent/20 rounded"
- >
- Generate {n} more
- </button>
- ))}
- <div className="border-t border-port-border my-1" />
- <div className="flex items-center gap-1 px-1 pb-1">
- <input
- type="number"
- min={GENERATE_CUSTOM_MIN}
- max={GENERATE_CUSTOM_MAX}
- value={genCustom}
- onChange={(e) => setGenCustom(e.target.value)}
- onKeyDown={(e) => { if (e.key === 'Enter') runGenerate(genCustom); }}
- placeholder="Custom"
- className="w-16 bg-port-bg border border-port-border rounded px-1.5 py-1 text-white text-xs focus:outline-none focus:border-port-accent"
- />
- <button
- onClick={() => runGenerate(genCustom)}
- disabled={!Number(genCustom) || Number(genCustom) < GENERATE_CUSTOM_MIN}
- className="flex-1 text-xs px-2 py-1 bg-port-accent/20 hover:bg-port-accent/30 disabled:opacity-30 disabled:cursor-not-allowed text-port-accent rounded"
- >
- Go
- </button>
- </div>
- </div>
- )}
- </div>
- )}
- {variations.length > 0 && (
- // Single toggle — mirrors the per-row lock button. Lock icon when
- // every variation is locked (click unlocks all); Unlock icon for
- // the all-unlocked + mixed cases so a click always locks the
- // holdouts.
- <button
- onClick={() => setAllLocked(!allLocked)}
- title={allLocked
- ? 'Unlock all variations — Expand / Generate may overwrite them'
- : 'Lock all variations — Expand / Generate will preserve them'}
- aria-label={allLocked ? 'Unlock all variations' : 'Lock all variations'}
- aria-pressed={allLocked}
- className={`p-1 rounded ${
- allLocked
- ? 'text-port-accent hover:bg-port-accent/20'
- : 'text-gray-500 hover:text-gray-300'
- }`}
- >
- {allLocked ? <Lock size={14} /> : <Unlock size={14} />}
- </button>
- )}
- {canRemove && (
- <button
- onClick={onRemove}
- className="p-1 text-gray-400 hover:text-port-error rounded"
- title="Remove category"
- >
- <Trash2 size={14} />
- </button>
- )}
- <button
- onClick={() => setAdding((v) => !v)}
- className="text-xs px-2 py-1 bg-port-accent/15 hover:bg-port-accent/25 text-port-accent rounded flex items-center gap-1 min-h-[40px] sm:min-h-0"
- >
- <Plus size={12} /> Add
- </button>
- </div>
- </div>
- {adding && (
- <div className="bg-port-bg border border-port-border rounded p-2 mb-2 flex flex-col gap-2">
- <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) => (
- <VariationCard
- key={`${v.label}-${idx}`}
- variation={v}
- idx={idx}
- editMode={editIdx === idx}
- editLabel={editLabel}
- editPrompt={editPrompt}
- setEditLabel={setEditLabel}
- setEditPrompt={setEditPrompt}
- saveEdit={saveEdit}
- cancelEdit={() => setEditIdx(null)}
- startEdit={() => startEdit(idx, v)}
- toggleLock={() => toggleLockAt(idx)}
- remove={() => removeAt(idx)}
- onPromote={onPromote}
- canPromote={canPromote}
- requiresTargetKind={requiresTargetKind}
- promotingIdx={promotingIdx}
- pickerIdx={pickerIdx}
- setPickerIdx={setPickerIdx}
- pickerWrapRef={pickerWrapRef}
- runPromote={runPromote}
- onRenderVariation={onRenderVariation}
- canRender={canRender}
- onPreviewVariation={onPreviewVariation}
- inFlightJobId={pendingByEntryId[v.id] || null}
- onJobCompleted={onJobCompleted}
- onJobFailed={onJobFailed}
- />
- ))}
- </ul>
- )}
- </div>
- );
-}
-
-// Renders through `EntryCard` so the locked accent + layout stay in
-// lock-step with `CanonCard`.
-function VariationCard({
- variation: v, idx, editMode,
- editLabel, editPrompt, setEditLabel, setEditPrompt,
- saveEdit, cancelEdit, startEdit, toggleLock, remove,
- onPromote, canPromote, requiresTargetKind, promotingIdx,
- pickerIdx, setPickerIdx, pickerWrapRef, runPromote,
- onRenderVariation, canRender,
- onPreviewVariation = null,
- inFlightJobId = null, onJobCompleted = null, onJobFailed = null,
-}) {
- const locked = !!v.locked;
- // Hooks MUST run unconditionally and in stable order — calling them after
- // the editMode early-return below would change the hook count between
- // display ↔ edit toggles and crash React with "Rendered more hooks than
- // during the previous render". Subscribe to the row's in-flight job here
- // so completion / failure callbacks fire back up to the parent (which
- // clears pending state + appends the new filename to the variation's
- // imageRefs[] optimistically). settledRef prevents duplicate fires under
- // React 18 StrictMode's mount → cleanup → mount dev double-fire.
- const { status: jobStatus, filename: jobFilename, error: jobError } = useMediaJobProgress(inFlightJobId);
- const settledRef = useRef(null);
- useEffect(() => {
- if (!inFlightJobId) { settledRef.current = null; return; }
- if (settledRef.current === inFlightJobId) return;
- if (jobStatus === 'completed' && jobFilename) {
- settledRef.current = inFlightJobId;
- // Pass `inFlightJobId` back so the parent can shift exactly this jobId
- // out of its per-entry queue. Without the jobId, `clearPendingForEntry`
- // would drop every queued job for the row — wrong when `batchPerVariation
- // > 1` queues N siblings and only one has just finished.
- onJobCompleted?.(v.id, jobFilename, inFlightJobId);
- } else if (jobStatus === 'failed' || jobStatus === 'canceled') {
- settledRef.current = inFlightJobId;
- onJobFailed?.(v.id, jobError || jobStatus, inFlightJobId);
- }
- }, [inFlightJobId, jobStatus, jobFilename, jobError, v.id, onJobCompleted, onJobFailed]);
-
- if (editMode) {
- return (
- <EntryCard
- locked={locked}
- body={(
- <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={cancelEdit} 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>
- )}
- />
- );
- }
-
- const promoteTitle = !canPromote
- ? 'Save the universe first to enable promote'
- : requiresTargetKind
- ? 'Promote to canon — pick a trunk'
- : 'Promote to canon — LLM expands this variation into a full canon entry';
-
- // Thumbnail slot is three-state (pending / empty / completed) — see
- // `EntryThumbSlot`. Hook subscription that drives this lives above the
- // editMode early-return so the hook order stays stable across toggles.
- const renders = Array.isArray(v.imageRefs) ? v.imageRefs : [];
- const thumbnail = (
- <EntryThumbSlot
- inFlightJobId={inFlightJobId}
- imageRefs={renders}
- alt={`${v.label} render`}
- canRender={!!onRenderVariation && canRender}
- onRender={onRenderVariation ? () => onRenderVariation(v) : null}
- onPreview={onPreviewVariation || null}
- />
- );
-
- const title = <div className="text-sm text-white font-medium truncate">{v.label}</div>;
- const body = <div className="text-xs text-gray-400 line-clamp-2 mt-1">{v.prompt}</div>;
- const actions = (
- <div className="flex items-center gap-1">
- {onPromote && (
- <div className="relative" ref={pickerIdx === idx ? pickerWrapRef : null}>
- <button
- onClick={() => {
- if (requiresTargetKind) {
- setPickerIdx(pickerIdx === idx ? null : idx);
- return;
- }
- runPromote(idx, v);
- }}
- disabled={!canPromote || promotingIdx !== null}
- className="p-1 text-gray-400 hover:text-port-success disabled:opacity-30 disabled:cursor-not-allowed rounded"
- title={promoteTitle}
- aria-haspopup={requiresTargetKind ? 'menu' : undefined}
- aria-expanded={requiresTargetKind ? pickerIdx === idx : undefined}
- >
- {promotingIdx === idx
- ? <Loader2 size={14} className="animate-spin" />
- : <ArrowUpCircle size={14} />}
- </button>
- {pickerIdx === idx && requiresTargetKind && (
- <div
- role="menu"
- className="absolute right-0 top-full mt-1 z-20 w-44 bg-port-card border border-port-border rounded shadow-lg p-1 flex flex-col gap-0.5"
- >
- <div className="px-2 pt-1 pb-1 text-[10px] uppercase tracking-wide text-gray-500">
- Promote to canon as…
- </div>
- {TRUNK_TABS.map((trunk) => (
- <button
- key={trunk.kind}
- role="menuitem"
- onClick={() => runPromote(idx, v, { targetKind: trunk.kind })}
- className="text-left text-xs px-2 py-1.5 text-gray-200 hover:bg-port-success/20 rounded"
- >
- {trunk.label}
- </button>
- ))}
- </div>
- )}
- </div>
- )}
- {onRenderVariation && (
- <button
- onClick={() => onRenderVariation(v)}
- disabled={!canRender}
- className="p-1 text-gray-400 hover:text-port-accent disabled:opacity-30 disabled:cursor-not-allowed rounded"
- title={canRender ? 'Render this variation' : 'Save the world and configure a render backend to enable'}
- >
- <Play size={14} />
- </button>
- )}
- <button
- onClick={toggleLock}
- className={`p-1 rounded ${locked ? 'text-port-accent hover:bg-port-accent/20' : 'text-gray-500 hover:text-gray-300'}`}
- title={locked ? 'Locked — AI expand will preserve this variation' : 'Lock this variation against AI expand'}
- aria-pressed={locked}
- >
- {locked ? <Lock size={14} /> : <Unlock size={14} />}
- </button>
- <button
- onClick={startEdit}
- className="p-1 text-gray-400 hover:text-port-accent rounded"
- title="Edit"
- >
- <Edit3 size={14} />
- </button>
- <button
- onClick={remove}
- className="p-1 text-gray-400 hover:text-port-error rounded"
- title="Remove"
- >
- <X size={14} />
- </button>
- </div>
- );
-
- return <EntryCard locked={locked} thumbnail={thumbnail} title={title} body={body} actions={actions} />;
-}
-
-function BibleTab({
- draft, updateDraft, toggleLock,
- llm,
- handleExpand, expanding, saving,
- refine,
- totalVariations, categoryKeyCount, totalSheets,
- onPreview,
- onStyleProbeRenderComplete = null,
- styleProbeDirty = false,
-}) {
- const { providers, providerModels, providerLabel, activeProviderId } = llm;
- const {
- open: refineOpen, setOpen: setRefineOpen,
- feedback: refineFeedback, setFeedback: setRefineFeedback,
- run: runRefine, running: refining, reset: resetRefinePanel,
- rationale: refineRationale, changes: refineChanges,
- image: refineImage, setImage: setRefineImage,
- } = refine;
- // Local-only: gallery picker visibility for the optional style-reference image.
- const [refineGalleryOpen, setRefineGalleryOpen] = useState(false);
- // Vision provider/model selection, lifted from VisionProviderPicker — which is
- // mounted only when a style-reference image is attached, so the refine runs
- // through a vision-capable API provider (not the universe's default expansion
- // LLM) and the provider fetch is deferred until it's actually needed.
- const [refineVision, setRefineVision] = useState({ providerId: '', model: '', hasProviders: false, noVisionModel: false });
- return (
- <>
- <section className="bg-port-card border border-port-border rounded p-4 flex flex-col gap-3">
- <div className="grid grid-cols-1 md:grid-cols-[1fr_220px] gap-3">
- <div>
- <FieldLabel field="starterPrompt" locked={draft.locked} onToggleLock={toggleLock}>
- Starter idea
- </FieldLabel>
- <textarea
- value={draft.starterPrompt}
- onChange={(e) => updateDraft({ starterPrompt: e.target.value })}
- placeholder="moebius and scavengers reign meets Prophet inspired sci fi universe"
- className="w-full bg-port-bg border border-port-border rounded px-3 py-2 text-white text-sm focus:outline-none focus:border-port-accent"
- rows={2}
- />
- </div>
- <div>
- <p className="text-xs text-gray-400 mb-1 block">LLM for expansion</p>
- {/* The selection here is part of the draft and persisted to the
- server (feeds expand/render), not ephemeral like the Importer —
- so we drive it from `draft.llm` and use only the shared
- component, not useProviderModels' auto-select/load machinery. */}
- <ProviderModelSelector
- providers={providers}
- selectedProviderId={draft.llm?.provider ?? ''}
- selectedModel={draft.llm?.model || ''}
- availableModels={providerModels}
- onProviderChange={(id) => updateDraft({ llm: { ...draft.llm, provider: id || null, model: null } })}
- onModelChange={(m) => updateDraft({ llm: { ...draft.llm, model: m || null } })}
- compact
- label="LLM for expansion"
- layout="stacked"
- emptyProviderOption={`Active provider (${providerLabel(activeProviderId)})`}
- emptyModelOption="Default model"
- alwaysShowModel
- />
- </div>
- </div>
-
- <MoodBoardReferenceStrip storageKey="universe-builder" />
-
- <div className="flex items-center gap-2 flex-wrap">
- <button
- onClick={handleExpand}
- disabled={expanding || saving || !draft.starterPrompt?.trim()}
- className="px-3 py-2 bg-port-accent-2/30 hover:bg-port-accent-2/50 disabled:opacity-50 text-port-accent-2 border border-port-accent-2/40 rounded flex items-center gap-2 min-h-[40px]"
- >
- {expanding ? <Loader2 size={16} className="animate-spin" /> : <Wand2 size={16} />}
- Generate From Idea
- </button>
- <button
- onClick={() => setRefineOpen((v) => !v)}
- disabled={!draft.starterPrompt?.trim()}
- aria-expanded={refineOpen}
- className={`px-3 py-2 disabled:opacity-50 text-port-accent border border-port-accent/40 rounded flex items-center gap-2 min-h-[40px] ${
- refineOpen ? 'bg-port-accent/25' : 'bg-port-accent/15 hover:bg-port-accent/25'
- }`}
- title="Give feedback to refine the prompts in place — uses the LLM picked above"
- >
- <MessageSquarePlus size={16} />
- Refine prompts
- </button>
- <span className="text-xs text-gray-500">
- {totalVariations} variation{totalVariations === 1 ? '' : 's'} across {categoryKeyCount} categories · {totalSheets} composite board{totalSheets === 1 ? '' : 's'}
- </span>
- </div>
-
- {refineOpen && (
- <div className="border border-port-accent/40 bg-port-accent/5 rounded p-3 flex flex-col gap-2">
- <label htmlFor="world-refine-feedback" className="text-[11px] uppercase tracking-wide text-gray-500">
- Feedback — describe what you want changed
- </label>
- <textarea
- id="world-refine-feedback"
- value={refineFeedback}
- onChange={(e) => setRefineFeedback(e.target.value)}
- placeholder="e.g. lean grimmer and more spiritual; pull style toward Moebius + Tarkovsky; avoid neon and cyberpunk clichés."
- rows={3}
- disabled={refining}
- className="w-full bg-port-bg border border-port-border rounded p-2 text-sm text-white placeholder-gray-500 focus:outline-none focus:border-port-accent resize-y disabled:opacity-60"
- />
- {/* Optional visual style reference from the gallery — when set, the
- server refines through a vision-capable API provider. */}
- <div className="flex items-center gap-2 flex-wrap">
- <span className="text-[11px] uppercase tracking-wide text-gray-500">Style reference (optional)</span>
- {refineImage ? (
- <div className="relative w-14 h-14">
- <img
- src={refineImage.preview || `/data/images/${encodeURIComponent(refineImage.filename)}`}
- alt="style reference"
- className="w-full h-full object-cover rounded border border-port-border"
- />
- <button
- type="button"
- onClick={() => setRefineImage(null)}
- title="Remove reference image"
- aria-label="Remove reference image"
- className="absolute -top-1.5 -right-1.5 bg-port-bg border border-port-border rounded-full p-0.5 text-gray-400 hover:text-port-error"
- >
- <X size={11} />
- </button>
- </div>
- ) : (
- <button
- type="button"
- onClick={() => setRefineGalleryOpen(true)}
- disabled={refining}
- className="px-2.5 py-1.5 text-xs text-port-accent border border-port-accent/40 rounded flex items-center gap-1.5 hover:bg-port-accent/10 disabled:opacity-50"
- >
- <Images size={14} />
- Pick from gallery
- </button>
- )}
- {refineImage ? (
- <span className="text-[11px] text-gray-500">Folds the image's palette/mood into influences + style notes.</span>
- ) : null}
- </div>
- {/* Vision provider/model picker — only when an image is attached, since
- the server forces a vision-capable API provider for image refine.
- Mounting it conditionally also defers its provider fetch. */}
- {refineImage ? (
- <VisionProviderPicker label="Vision provider (for image refine)" onChange={setRefineVision} />
- ) : null}
- <div className="flex items-center gap-2 flex-wrap">
- <button
- type="button"
- onClick={() => runRefine(refineImage
- ? { providerId: refineVision.providerId, model: refineVision.model }
- : null)}
- disabled={refining || !refineFeedback.trim() || !draft.starterPrompt?.trim() || (!!refineImage && !refineVision.model)}
- className="px-3 py-2 bg-port-accent hover:bg-port-accent/90 disabled:opacity-50 disabled:cursor-not-allowed text-white rounded flex items-center gap-2 min-h-[40px]"
- >
- {refining ? <Loader2 size={14} className="animate-spin" /> : <Wand2 size={14} />}
- {refining ? 'Refining…' : 'Refine'}
- </button>
- <button
- type="button"
- onClick={resetRefinePanel}
- disabled={refining}
- className="px-3 py-2 text-sm text-gray-400 hover:text-white rounded min-h-[40px]"
- >
- Close
- </button>
- <span className="text-[11px] text-gray-500">
- Applies in place — locked fields stay pinned.
- </span>
- </div>
- {(refineRationale || refineChanges.length > 0) && (
- <div className="border-t border-port-border/60 pt-2 mt-1 space-y-1.5">
- {refineRationale && (
- <p className="text-xs text-gray-300 whitespace-pre-wrap">{refineRationale}</p>
- )}
- {refineChanges.length > 0 && (
- <ul className="text-[11px] text-gray-400 list-disc pl-5 space-y-0.5">
- {refineChanges.map((c, idx) => (
- <li key={idx}>{c}</li>
- ))}
- </ul>
- )}
- </div>
- )}
- <GalleryImagePicker
- open={refineGalleryOpen}
- onClose={() => setRefineGalleryOpen(false)}
- onSelect={(item) => {
- if (item?.filename) setRefineImage({ filename: item.filename, preview: item.previewUrl });
- }}
- />
- </div>
- )}
- </section>
-
- <section className="bg-port-card border border-port-border rounded p-4 flex flex-col gap-3">
- <div>
- <h2 className="text-sm font-semibold text-white">Story bible</h2>
- <p className="text-xs text-gray-500 mt-0.5">
- Pulled into the Pipeline → New Series form when this world is selected.
- </p>
- </div>
- <div>
- <FieldLabel htmlFor="world-logline" field="logline" locked={draft.locked} onToggleLock={toggleLock}>
- Logline
- </FieldLabel>
- <input
- id="world-logline"
- type="text"
- value={draft.logline || ''}
- onChange={(e) => updateDraft({ logline: e.target.value })}
- placeholder="One-sentence hook — A foundry city goes silent, and the only survivor is a child."
- className="w-full bg-port-bg border border-port-border rounded px-3 py-2 text-white text-sm focus:outline-none focus:border-port-accent"
- maxLength={WORLD_LOGLINE_MAX}
- />
- </div>
- <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
- <div>
- <FieldLabel htmlFor="world-premise" field="premise" locked={draft.locked} onToggleLock={toggleLock}>
- Premise
- </FieldLabel>
- <textarea
- id="world-premise"
- value={draft.premise || ''}
- onChange={(e) => updateDraft({ premise: e.target.value })}
- placeholder="Elevator pitch — 1-3 short paragraphs about the setting, central conflict, stakes, and tone."
- className="w-full bg-port-bg border border-port-border rounded px-3 py-2 text-white text-sm focus:outline-none focus:border-port-accent"
- rows={6}
- maxLength={WORLD_PREMISE_MAX}
- />
- </div>
- <div>
- <FieldLabel htmlFor="world-style-notes" field="styleNotes" locked={draft.locked} onToggleLock={toggleLock}>
- Style notes
- </FieldLabel>
- <textarea
- id="world-style-notes"
- value={draft.styleNotes || ''}
- onChange={(e) => updateDraft({ styleNotes: e.target.value })}
- placeholder="Narrative style: references (artists / films / comics), mood, palette, pacing, voice. Prose, not tokens."
- className="w-full bg-port-bg border border-port-border rounded px-3 py-2 text-white text-sm focus:outline-none focus:border-port-accent"
- rows={6}
- maxLength={WORLD_STYLE_NOTES_MAX}
- />
- </div>
- </div>
- <StyleNegativePromptEditor
- influences={draft.influences}
- onChange={(next) => updateDraft({ influences: next })}
- locked={draft.locked}
- onToggleLock={toggleLock}
- />
- <div className="mt-4 pt-4 border-t border-port-border">
- {/* StyleProbeImage persists styleImageRefs server-side itself; merge
- only that field into the draft so unsaved style edits aren't lost.
- `styleDirty` blocks the render while influences have unsaved edits —
- otherwise the probe pins to a saved record that lacks that style. */}
- {/* The probe's in-flight render state (the EntryThumbSlot spinner +
- the async completion handler) is scoped to one universe by
- `useSingleImageRender`'s `scopeId` (the universe id), so this stays
- mounted across a `/universes/:id` switch WITHOUT a `key` remount —
- no per-switch settings refetch, and switching back resumes a
- still-running render instead of abandoning its completion. */}
- <StyleProbeImage
- universe={draft}
- onUniverseChange={(updated) => updateDraft({ styleImageRefs: updated?.styleImageRefs || [] })}
- onPreview={onPreview}
- onRenderComplete={() => onStyleProbeRenderComplete?.()}
- styleDirty={styleProbeDirty}
- />
- </div>
- </section>
- </>
- );
-}
-
-// Sub-bucket chip strip used by TrunkView + OtherTab. The "All" chip is a
-// pseudo-bucket that clears `?bucket=`. Each real bucket key gets its own
-// chip; clicking toggles it on/off (toggle-off returns to All). Designed so
-// it works one-handed on mobile (38px tap targets, wraps to multiple lines).
-// Per-trunk view. Three modes driven by `?bucket=`:
-// - blank (default "All"): renders canon + every variation under this trunk
-// - BUCKET_CANON: renders only canon entries (via the existing UniverseCanonSection)
-// - <bucketKey>: renders that bucket's variations via CategoryEditor
-export function TrunkView({
- trunk, draft, selectedId, buckets, activeBucket, setBucket,
- canRender, canPromote, imageCfg, onUniverseChange,
- onRemoveBucket, onUpdateBucket, onGenerateInBucket, onPromoteVariation,
- onBulkRenderBucket, onRenderVariation, onBulkRenderTrunk,
- onAddBucket,
- onPreviewVariation = null,
- onCanonPreview = null,
- pendingByEntryId = {},
- // Same pending head-map, passed through to UniverseCanonSection so canon
- // rows show a spinner when a batch `/render` queues canon prompts.
- externalPendingByEntryId = null,
- onPendingCleared = null, onJobCompletedForEntry = null,
-}) {
- const canonList = Array.isArray(draft[trunk.kind]) ? draft[trunk.kind] : [];
- // Only count canon entries the server will actually compile — mirror the
- // `synthesizeCanonPrompt`-empty-seed skip via `canonEntryHasContent`. Without
- // this, "Bulk-render all (N)" would advertise more images than land, and the
- // server can 400 with WORLD_BUILDER_EMPTY when every entry under the trunk
- // synthesizes to nothing.
- const canonRenderable = canonList.filter((e) => canonEntryHasContent(e, trunk.kind)).length;
- const totalUnderTrunk =
- canonRenderable
- + buckets.reduce((n, k) => n + (draft.categories?.[k]?.variations?.length || 0), 0);
- const [addingBucket, setAddingBucket] = useState(false);
- const [newBucketName, setNewBucketName] = useState('');
-
- const handleAddBucket = () => {
- const key = normalizeCategoryKey(newBucketName);
- if (!key) {
- toast.error('Use letters or numbers for the bucket name');
- return;
- }
- if (draft.categories?.[key]) {
- toast.error('A bucket with that name already exists');
- return;
- }
- onAddBucket({ key });
- setNewBucketName('');
- setAddingBucket(false);
- setBucket(key);
- };
-
- return (
- <>
- <section className="bg-port-card border border-port-border rounded p-3 flex flex-col gap-2">
- <div className="flex items-center justify-between gap-2 flex-wrap">
- <BucketChipStrip
- buckets={buckets}
- activeBucket={activeBucket}
- setBucket={setBucket}
- extraChips={canonList.length > 0 ? [{ key: BUCKET_CANON, label: `Canon (${canonList.length})` }] : []}
- />
- <div className="flex items-center gap-1.5 flex-wrap">
- <button
- type="button"
- onClick={() => setAddingBucket((v) => !v)}
- className="text-xs px-2 py-1.5 bg-port-bg hover:bg-port-border text-gray-300 border border-port-border rounded flex items-center gap-1 min-h-[32px]"
- title={`Add a sub-bucket under ${trunk.label}`}
- >
- <Plus size={12} /> Bucket
- </button>
- <button
- type="button"
- onClick={onBulkRenderTrunk}
- disabled={!canRender || totalUnderTrunk === 0}
- className="text-xs px-2 py-1.5 bg-port-accent/15 hover:bg-port-accent/25 disabled:opacity-30 disabled:cursor-not-allowed text-port-accent rounded flex items-center gap-1 min-h-[32px]"
- title={totalUnderTrunk === 0 ? `No ${trunk.label.toLowerCase()} to render yet` : `Bulk-render all ${trunk.label.toLowerCase()} — ${totalUnderTrunk} prompt${totalUnderTrunk === 1 ? '' : 's'}`}
- >
- <Sparkles size={12} /> Bulk-render all ({totalUnderTrunk})
- </button>
- </div>
- </div>
- {addingBucket && (
- <div className="flex items-center gap-2 flex-wrap pt-1">
- <input
- type="text"
- value={newBucketName}
- onChange={(e) => setNewBucketName(e.target.value)}
- onKeyDown={(e) => { if (e.key === 'Enter') handleAddBucket(); }}
- placeholder={trunk.kind === 'characters' ? 'heroes, villains, factions' : trunk.kind === 'places' ? 'colonies, ruins' : 'weapons, vehicles'}
- className="flex-1 min-w-[160px] bg-port-bg border border-port-border rounded px-2 py-1.5 text-white text-sm focus:outline-none focus:border-port-accent"
- maxLength={WORLD_CATEGORY_KEY_MAX}
- autoFocus
- />
- <button
- onClick={handleAddBucket}
- disabled={!newBucketName.trim()}
- className="text-xs px-2 py-1.5 bg-port-accent hover:bg-port-accent/90 disabled:opacity-50 text-white rounded min-h-[32px]"
- >
- Add
- </button>
- <button
- onClick={() => { setAddingBucket(false); setNewBucketName(''); }}
- className="text-xs px-2 py-1.5 bg-port-bg hover:bg-port-border text-gray-300 rounded min-h-[32px]"
- >
- Cancel
- </button>
- </div>
- )}
- </section>
-
- {/* Canon visibility: "All" (no bucket selected) or the canon pseudo-bucket.
- Gated on `draft.id === selectedId` to avoid the universe-switch race
- documented on UniverseCanonSection itself. */}
- {(!activeBucket || activeBucket === BUCKET_CANON) && selectedId && draft.id === selectedId ? (
- <UniverseCanonSection
- universe={draft}
- universeId={selectedId}
- onUniverseChange={onUniverseChange}
- imageCfg={imageCfg}
- kindFilter={trunk.kind}
- externalPendingByEntryId={externalPendingByEntryId}
- onExternalCanonJobSettled={onPendingCleared}
- onPreview={onCanonPreview}
- />
- ) : null}
-
- {activeBucket !== BUCKET_CANON && (
- <>
- {(activeBucket ? [activeBucket] : buckets).length === 0 ? (
- <section className="bg-port-card border border-port-border rounded p-6 text-center text-sm text-gray-500">
- No {trunk.label.toLowerCase()} sub-buckets yet.{' '}
- <button
- type="button"
- onClick={() => setAddingBucket(true)}
- className="text-port-accent hover:underline"
- >
- Add one
- </button>
- {' '}or click <em>Generate From Idea</em> on the Bible tab to seed them.
- </section>
- ) : (
- <section className="grid grid-cols-1 md:grid-cols-2 gap-3">
- {(activeBucket ? [activeBucket] : buckets).map((cat) => (
- <CategoryEditor
- key={cat}
- category={cat}
- variations={draft.categories?.[cat]?.variations || []}
- canRemove={!WORLD_CATEGORIES.includes(cat)}
- onChange={(next) => onUpdateBucket(cat, next)}
- onRemove={() => onRemoveBucket(cat)}
- canRender={canRender}
- onRenderCategory={() => onBulkRenderBucket(cat)}
- onRenderVariation={(v) => onRenderVariation(cat, v)}
- onGenerate={(count) => onGenerateInBucket(cat, count)}
- canPromote={canPromote}
- bucketKind={draft.categories?.[cat]?.kind ?? trunk.kind}
- onPromote={onPromoteVariation ? (v) => onPromoteVariation(cat, v) : null}
- onPreviewVariation={onPreviewVariation}
- pendingByEntryId={pendingByEntryId}
- onJobCompleted={(entryId, filename, completedJobId) =>
- onJobCompletedForEntry?.(entryId, filename, cat, completedJobId)}
- onJobFailed={(entryId, err, failedJobId) => {
- // Toast BEFORE clearing — clearing removes the
- // MediaJobThumb from the row and the failure state
- // disappears with it. Without the toast, a failed
- // variation render collapses silently to the empty
- // thumbnail (mirrors UniverseCanonSection.onJobFailed).
- if (err) toast.error(`Render failed: ${typeof err === 'string' ? err : (err.message || err)}`);
- onPendingCleared?.(entryId, failedJobId);
- }}
- />
- ))}
- </section>
- )}
- </>
- )}
- </>
- );
-}
-
-// Other tab — un-kinded buckets that haven't been sorted into a trunk yet.
-// Same card grid as TrunkView but no canon plumbing, plus an "Auto-sort"
-// action that (eventually) LLM-classifies each bucket into the right trunk.
-export function OtherTab({
- draft, buckets, activeBucket, setBucket, canRender, canPromote,
- onUpdateBucket, onRemoveBucket, onGenerateInBucket, onPromoteVariation,
- onBulkRenderBucket, onRenderVariation, onAssignBucketKind, onAutoSort,
- autoSorting = false,
- onPreviewVariation = null,
- pendingByEntryId = {}, onPendingCleared = null, onJobCompletedForEntry = null,
-}) {
- return (
- <>
- <section className="bg-port-card border border-port-border rounded p-3 flex flex-col gap-2">
- <div className="flex items-center justify-between gap-2 flex-wrap">
- <BucketChipStrip
- buckets={buckets}
- activeBucket={activeBucket}
- setBucket={setBucket}
- />
- <button
- type="button"
- onClick={onAutoSort}
- disabled={autoSorting}
- className="text-xs px-2 py-1.5 bg-port-accent/15 hover:bg-port-accent/25 disabled:opacity-50 text-port-accent rounded flex items-center gap-1 min-h-[32px]"
- title="Auto-sort with AI — sends every Other-tab bucket to the active LLM and assigns each to characters / places / objects"
- >
- {autoSorting ? <Loader2 size={12} className="animate-spin" /> : <Wand2 size={12} />}
- {autoSorting ? 'Sorting…' : 'Auto-sort with AI'}
- </button>
- </div>
- <p className="text-[11px] text-gray-500">
- These buckets aren't tagged as Cast / Places / Objects yet — they were
- either added manually or imported from a pre-Phase-A universe. Auto-sort
- asks the active LLM to classify every bucket into the right trunk.
- </p>
- </section>
-
- <section className="grid grid-cols-1 md:grid-cols-2 gap-3">
- {(activeBucket ? [activeBucket] : buckets).map((cat) => (
- <CategoryEditor
- key={cat}
- category={cat}
- variations={draft.categories?.[cat]?.variations || []}
- canRemove={!WORLD_CATEGORIES.includes(cat)}
- onChange={(next) => onUpdateBucket(cat, next)}
- onRemove={() => onRemoveBucket(cat)}
- canRender={canRender}
- onRenderCategory={() => onBulkRenderBucket(cat)}
- onRenderVariation={(v) => onRenderVariation(cat, v)}
- onGenerate={(count) => onGenerateInBucket(cat, count)}
- canPromote={canPromote}
- bucketKind={draft.categories?.[cat]?.kind}
- onPromote={onPromoteVariation ? (v, opts) => onPromoteVariation(cat, v, opts) : null}
- onAssignBucketKind={onAssignBucketKind ? (targetKind) => onAssignBucketKind(cat, targetKind) : null}
- onPreviewVariation={onPreviewVariation}
- pendingByEntryId={pendingByEntryId}
- onJobCompleted={(entryId, filename, completedJobId) =>
- onJobCompletedForEntry?.(entryId, filename, cat, completedJobId)}
- onJobFailed={(entryId, err, failedJobId) => {
- // Same surface-then-clear order as the Trunk-tab handler above:
- // MediaJobThumb is unmounted on clear, so the toast must fire
- // first or the user gets no signal that the render failed.
- if (err) toast.error(`Render failed: ${typeof err === 'string' ? err : (err.message || err)}`);
- onPendingCleared?.(entryId, failedJobId);
- }}
- />
- ))}
- </section>
- </>
- );
-}
diff --git a/client/src/components/universeBuilder/UniverseCategoryEditor.jsx b/client/src/components/universeBuilder/UniverseCategoryEditor.jsx
new file mode 100644
index 0000000000..cc2f30b5fd
--- /dev/null
+++ b/client/src/components/universeBuilder/UniverseCategoryEditor.jsx
@@ -0,0 +1,560 @@
+import { useEffect, useRef, useState } from 'react';
+import {
+ ArrowUpCircle, Edit3, FolderTree, Loader2, Lock, Play, Plus,
+ Sparkles, Trash2, Unlock, X,
+} from 'lucide-react';
+import useClickOutside from '../../hooks/useClickOutside';
+import useMediaJobProgress from '../../hooks/useMediaJobProgress';
+import {
+ TRUNK_BY_KIND,
+ TRUNK_TABS,
+ humanizeCategory,
+} from '../../lib/universeBuilderShared';
+import EntryCard from '../universe/EntryCard';
+import EntryThumbSlot from '../universe/EntryThumbSlot';
+
+const GENERATE_PRESETS = [3, 5, 10];
+const GENERATE_CUSTOM_MIN = 1;
+const GENERATE_CUSTOM_MAX = 50;
+
+export function CategoryEditor({
+ category, variations, canRemove = false, onChange, onRemove,
+ canRender = false, onRenderCategory = null, onRenderVariation = null,
+ onGenerate = null,
+ // `bucketKind` drives the promote-button UX: when `'other'` (or absent)
+ // the picker opens to choose a trunk; otherwise we promote directly.
+ // `canPromote` gates on universe-persisted (the action reads the saved record).
+ canPromote = false, bucketKind = null, onPromote = null,
+ // Only set by OtherTab — clicking opens a picker that retags the bucket's
+ // `kind` to a canon trunk. Variations stay in place; bucket moves tabs.
+ onAssignBucketKind = null,
+ // Clicking the row's thumbnail opens the page-level MediaPreview lightbox
+ // (same modal that the history / gallery uses). Receives the visible
+ // filename so the modal lands on the exact ref the user saw, not a stale
+ // primary that may have walked-back on a 404.
+ onPreviewVariation = null,
+ // Per-row render-pending plumbing — `pendingByEntryId[v.id]` returns the
+ // in-flight jobId (or undefined). Completion / failure callbacks fire when
+ // the row's MediaJobThumb settles.
+ pendingByEntryId = {}, onJobCompleted = null, onJobFailed = null,
+}) {
+ const requiresTargetKind = !TRUNK_BY_KIND[bucketKind];
+ const [adding, setAdding] = useState(false);
+ const [newLabel, setNewLabel] = useState('');
+ const [newPrompt, setNewPrompt] = useState('');
+ const [editIdx, setEditIdx] = useState(null);
+ const [editLabel, setEditLabel] = useState('');
+ const [editPrompt, setEditPrompt] = useState('');
+ const [genOpen, setGenOpen] = useState(false);
+ const [genCustom, setGenCustom] = useState('');
+ const [generating, setGenerating] = useState(false);
+ const [promotingIdx, setPromotingIdx] = useState(null);
+ const [pickerIdx, setPickerIdx] = useState(null);
+ const [assignOpen, setAssignOpen] = useState(false);
+ const genWrapRef = useRef(null);
+ const pickerWrapRef = useRef(null);
+ const assignWrapRef = useRef(null);
+
+ useClickOutside(genWrapRef, genOpen, () => setGenOpen(false));
+ useClickOutside(pickerWrapRef, pickerIdx !== null, () => setPickerIdx(null));
+ useClickOutside(assignWrapRef, assignOpen, () => setAssignOpen(false));
+ useEffect(() => {
+ if (!genOpen) return undefined;
+ const onKey = (e) => { if (e.key === 'Escape') setGenOpen(false); };
+ document.addEventListener('keydown', onKey);
+ return () => document.removeEventListener('keydown', onKey);
+ }, [genOpen]);
+ useEffect(() => {
+ if (pickerIdx === null) return undefined;
+ const onKey = (e) => { if (e.key === 'Escape') setPickerIdx(null); };
+ document.addEventListener('keydown', onKey);
+ return () => document.removeEventListener('keydown', onKey);
+ }, [pickerIdx]);
+ useEffect(() => {
+ if (!assignOpen) return undefined;
+ const onKey = (e) => { if (e.key === 'Escape') setAssignOpen(false); };
+ document.addEventListener('keydown', onKey);
+ return () => document.removeEventListener('keydown', onKey);
+ }, [assignOpen]);
+
+ const editorMountedRef = useRef(true);
+ useEffect(() => () => { editorMountedRef.current = false; }, []);
+ const runPromote = async (idx, variation, opts) => {
+ if (!onPromote) return;
+ setPickerIdx(null);
+ setPromotingIdx(idx);
+ try {
+ await onPromote(variation, opts);
+ } finally {
+ if (editorMountedRef.current) setPromotingIdx(null);
+ }
+ };
+
+ const runGenerate = async (count) => {
+ const n = Math.max(GENERATE_CUSTOM_MIN, Math.min(GENERATE_CUSTOM_MAX, parseInt(count, 10) || 0));
+ if (!n || !onGenerate) return;
+ setGenOpen(false);
+ setGenerating(true);
+ try {
+ await onGenerate(n);
+ } finally {
+ setGenerating(false);
+ setGenCustom('');
+ }
+ };
+
+ const addVariation = () => {
+ const label = newLabel.trim();
+ const prompt = newPrompt.trim();
+ if (!label || !prompt) return;
+ // Stamp `locked: true` so the in-draft row matches the lock-by-default
+ // contract before the next save round-trips through sanitizeVariation.
+ // Without this, the bulk-toggle counts a freshly-added variation as
+ // unlocked even though the user expects every new entry to land locked.
+ onChange([...variations, { label: label.slice(0, 120), prompt: prompt.slice(0, 2000), locked: true }]);
+ setNewLabel('');
+ setNewPrompt('');
+ setAdding(false);
+ };
+
+ const removeAt = (idx) => onChange(variations.filter((_, i) => i !== idx));
+
+ // Variations default to locked at the sanitizer (locked-by-default contract),
+ // so an unlock must persist as explicit `false` — not as an absent key —
+ // otherwise the next read would re-lock the entry the user just unlocked.
+ const toggleLockAt = (idx) => onChange(variations.map((v, i) => {
+ if (i !== idx) return v;
+ return { ...v, locked: !v.locked };
+ }));
+
+ // Bulk lock/unlock everything in this bucket. Same persistence contract:
+ // unlock writes explicit `false` so it survives the round-trip.
+ const setAllLocked = (nextLocked) =>
+ onChange(variations.map((v) => (v?.locked === nextLocked ? v : { ...v, locked: nextLocked })));
+ const lockedCount = variations.filter((v) => v?.locked === true).length;
+ const allLocked = variations.length > 0 && lockedCount === variations.length;
+
+ const startEdit = (idx, v) => {
+ setEditIdx(idx);
+ setEditLabel(v.label);
+ 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];
+ // Preserve `id`, `locked`, and `imageRefs` — only label + prompt are
+ // editable in this row. A naive replacement would re-mint the variation's
+ // id (breaking the link to its render history) and drop accrued imageRefs.
+ // The server's stale-PATCH guard catches some of this via length + tail
+ // comparison (variations with NEW renders in cur survive an empty patch),
+ // but a stale variation whose history hasn't grown server-side since the
+ // client loaded would still get its imageRefs cleared if we sent an empty
+ // array. Echoing cur's array verbatim avoids relying on the guard.
+ next[editIdx] = {
+ ...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">
+ {humanizeCategory(category)}
+ <span className="ml-2 text-xs text-gray-500">{variations.length}</span>
+ </h3>
+ <div className="flex items-center gap-1">
+ {onRenderCategory && (
+ <button
+ onClick={onRenderCategory}
+ disabled={!canRender || variations.length === 0}
+ className="p-1 text-port-accent hover:bg-port-accent/20 disabled:opacity-30 disabled:cursor-not-allowed rounded"
+ title={variations.length === 0 ? 'Add variations first' : 'Render this category'}
+ aria-label="Render this category"
+ >
+ <Play size={14} />
+ </button>
+ )}
+ {onAssignBucketKind && requiresTargetKind && (
+ <div className="relative" ref={assignWrapRef}>
+ <button
+ onClick={() => setAssignOpen((v) => !v)}
+ className="p-1 text-port-accent hover:bg-port-accent/20 rounded"
+ title="Move this bucket into a canon trunk (variations stay in place)"
+ aria-label="Assign bucket to a canon trunk"
+ aria-haspopup="menu"
+ aria-expanded={assignOpen}
+ >
+ <FolderTree size={14} />
+ </button>
+ {assignOpen && (
+ <div
+ role="menu"
+ className="absolute right-0 top-full mt-1 z-20 w-44 bg-port-card border border-port-border rounded shadow-lg p-1 flex flex-col gap-0.5"
+ >
+ <div className="px-2 pt-1 pb-1 text-[10px] uppercase tracking-wide text-gray-500">
+ Move bucket to trunk
+ </div>
+ {TRUNK_TABS.map((trunk) => {
+ const TrunkIcon = trunk.icon;
+ return (
+ <button
+ key={trunk.kind}
+ role="menuitem"
+ onClick={() => { setAssignOpen(false); onAssignBucketKind(trunk.kind); }}
+ className="text-left text-xs px-2 py-1.5 text-gray-200 hover:bg-port-accent/20 rounded flex items-center gap-2"
+ >
+ <TrunkIcon size={12} className="text-port-accent" /> {trunk.label}
+ </button>
+ );
+ })}
+ </div>
+ )}
+ </div>
+ )}
+ {onGenerate && (
+ <div className="relative" ref={genWrapRef}>
+ <button
+ onClick={() => setGenOpen((v) => !v)}
+ disabled={generating}
+ className="p-1 text-port-accent hover:bg-port-accent/20 disabled:opacity-30 disabled:cursor-not-allowed rounded"
+ title="Ask the LLM for more variations in this category"
+ aria-label="Generate more variations"
+ aria-haspopup="menu"
+ aria-expanded={genOpen}
+ >
+ {generating ? <Loader2 size={14} className="animate-spin" /> : <Sparkles size={14} />}
+ </button>
+ {genOpen && (
+ <div
+ role="menu"
+ className="absolute right-0 top-full mt-1 z-20 w-44 bg-port-card border border-port-border rounded shadow-lg p-1 flex flex-col gap-0.5"
+ >
+ {GENERATE_PRESETS.map((n) => (
+ <button
+ key={n}
+ role="menuitem"
+ onClick={() => runGenerate(n)}
+ className="text-left text-xs px-2 py-1.5 text-gray-200 hover:bg-port-accent/20 rounded"
+ >
+ Generate {n} more
+ </button>
+ ))}
+ <div className="border-t border-port-border my-1" />
+ <div className="flex items-center gap-1 px-1 pb-1">
+ <input
+ type="number"
+ min={GENERATE_CUSTOM_MIN}
+ max={GENERATE_CUSTOM_MAX}
+ value={genCustom}
+ onChange={(e) => setGenCustom(e.target.value)}
+ onKeyDown={(e) => { if (e.key === 'Enter') runGenerate(genCustom); }}
+ placeholder="Custom"
+ className="w-16 bg-port-bg border border-port-border rounded px-1.5 py-1 text-white text-xs focus:outline-none focus:border-port-accent"
+ />
+ <button
+ onClick={() => runGenerate(genCustom)}
+ disabled={!Number(genCustom) || Number(genCustom) < GENERATE_CUSTOM_MIN}
+ className="flex-1 text-xs px-2 py-1 bg-port-accent/20 hover:bg-port-accent/30 disabled:opacity-30 disabled:cursor-not-allowed text-port-accent rounded"
+ >
+ Go
+ </button>
+ </div>
+ </div>
+ )}
+ </div>
+ )}
+ {variations.length > 0 && (
+ // Single toggle — mirrors the per-row lock button. Lock icon when
+ // every variation is locked (click unlocks all); Unlock icon for
+ // the all-unlocked + mixed cases so a click always locks the
+ // holdouts.
+ <button
+ onClick={() => setAllLocked(!allLocked)}
+ title={allLocked
+ ? 'Unlock all variations — Expand / Generate may overwrite them'
+ : 'Lock all variations — Expand / Generate will preserve them'}
+ aria-label={allLocked ? 'Unlock all variations' : 'Lock all variations'}
+ aria-pressed={allLocked}
+ className={`p-1 rounded ${
+ allLocked
+ ? 'text-port-accent hover:bg-port-accent/20'
+ : 'text-gray-500 hover:text-gray-300'
+ }`}
+ >
+ {allLocked ? <Lock size={14} /> : <Unlock size={14} />}
+ </button>
+ )}
+ {canRemove && (
+ <button
+ onClick={onRemove}
+ className="p-1 text-gray-400 hover:text-port-error rounded"
+ title="Remove category"
+ >
+ <Trash2 size={14} />
+ </button>
+ )}
+ <button
+ onClick={() => setAdding((v) => !v)}
+ className="text-xs px-2 py-1 bg-port-accent/15 hover:bg-port-accent/25 text-port-accent rounded flex items-center gap-1 min-h-[40px] sm:min-h-0"
+ >
+ <Plus size={12} /> Add
+ </button>
+ </div>
+ </div>
+ {adding && (
+ <div className="bg-port-bg border border-port-border rounded p-2 mb-2 flex flex-col gap-2">
+ <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) => (
+ <VariationCard
+ key={`${v.label}-${idx}`}
+ variation={v}
+ idx={idx}
+ editMode={editIdx === idx}
+ editLabel={editLabel}
+ editPrompt={editPrompt}
+ setEditLabel={setEditLabel}
+ setEditPrompt={setEditPrompt}
+ saveEdit={saveEdit}
+ cancelEdit={() => setEditIdx(null)}
+ startEdit={() => startEdit(idx, v)}
+ toggleLock={() => toggleLockAt(idx)}
+ remove={() => removeAt(idx)}
+ onPromote={onPromote}
+ canPromote={canPromote}
+ requiresTargetKind={requiresTargetKind}
+ promotingIdx={promotingIdx}
+ pickerIdx={pickerIdx}
+ setPickerIdx={setPickerIdx}
+ pickerWrapRef={pickerWrapRef}
+ runPromote={runPromote}
+ onRenderVariation={onRenderVariation}
+ canRender={canRender}
+ onPreviewVariation={onPreviewVariation}
+ inFlightJobId={pendingByEntryId[v.id] || null}
+ onJobCompleted={onJobCompleted}
+ onJobFailed={onJobFailed}
+ />
+ ))}
+ </ul>
+ )}
+ </div>
+ );
+}
+
+// Renders through `EntryCard` so the locked accent + layout stay in
+// lock-step with `CanonCard`.
+function VariationCard({
+ variation: v, idx, editMode,
+ editLabel, editPrompt, setEditLabel, setEditPrompt,
+ saveEdit, cancelEdit, startEdit, toggleLock, remove,
+ onPromote, canPromote, requiresTargetKind, promotingIdx,
+ pickerIdx, setPickerIdx, pickerWrapRef, runPromote,
+ onRenderVariation, canRender,
+ onPreviewVariation = null,
+ inFlightJobId = null, onJobCompleted = null, onJobFailed = null,
+}) {
+ const locked = !!v.locked;
+ // Hooks MUST run unconditionally and in stable order — calling them after
+ // the editMode early-return below would change the hook count between
+ // display ↔ edit toggles and crash React with "Rendered more hooks than
+ // during the previous render". Subscribe to the row's in-flight job here
+ // so completion / failure callbacks fire back up to the parent (which
+ // clears pending state + appends the new filename to the variation's
+ // imageRefs[] optimistically). settledRef prevents duplicate fires under
+ // React 18 StrictMode's mount → cleanup → mount dev double-fire.
+ const { status: jobStatus, filename: jobFilename, error: jobError } = useMediaJobProgress(inFlightJobId);
+ const settledRef = useRef(null);
+ useEffect(() => {
+ if (!inFlightJobId) { settledRef.current = null; return; }
+ if (settledRef.current === inFlightJobId) return;
+ if (jobStatus === 'completed' && jobFilename) {
+ settledRef.current = inFlightJobId;
+ // Pass `inFlightJobId` back so the parent can shift exactly this jobId
+ // out of its per-entry queue. Without the jobId, `clearPendingForEntry`
+ // would drop every queued job for the row — wrong when `batchPerVariation
+ // > 1` queues N siblings and only one has just finished.
+ onJobCompleted?.(v.id, jobFilename, inFlightJobId);
+ } else if (jobStatus === 'failed' || jobStatus === 'canceled') {
+ settledRef.current = inFlightJobId;
+ onJobFailed?.(v.id, jobError || jobStatus, inFlightJobId);
+ }
+ }, [inFlightJobId, jobStatus, jobFilename, jobError, v.id, onJobCompleted, onJobFailed]);
+
+ if (editMode) {
+ return (
+ <EntryCard
+ locked={locked}
+ body={(
+ <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={cancelEdit} 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>
+ )}
+ />
+ );
+ }
+
+ const promoteTitle = !canPromote
+ ? 'Save the universe first to enable promote'
+ : requiresTargetKind
+ ? 'Promote to canon — pick a trunk'
+ : 'Promote to canon — LLM expands this variation into a full canon entry';
+
+ // Thumbnail slot is three-state (pending / empty / completed) — see
+ // `EntryThumbSlot`. Hook subscription that drives this lives above the
+ // editMode early-return so the hook order stays stable across toggles.
+ const renders = Array.isArray(v.imageRefs) ? v.imageRefs : [];
+ const thumbnail = (
+ <EntryThumbSlot
+ inFlightJobId={inFlightJobId}
+ imageRefs={renders}
+ alt={`${v.label} render`}
+ canRender={!!onRenderVariation && canRender}
+ onRender={onRenderVariation ? () => onRenderVariation(v) : null}
+ onPreview={onPreviewVariation || null}
+ />
+ );
+
+ const title = <div className="text-sm text-white font-medium truncate">{v.label}</div>;
+ const body = <div className="text-xs text-gray-400 line-clamp-2 mt-1">{v.prompt}</div>;
+ const actions = (
+ <div className="flex items-center gap-1">
+ {onPromote && (
+ <div className="relative" ref={pickerIdx === idx ? pickerWrapRef : null}>
+ <button
+ onClick={() => {
+ if (requiresTargetKind) {
+ setPickerIdx(pickerIdx === idx ? null : idx);
+ return;
+ }
+ runPromote(idx, v);
+ }}
+ disabled={!canPromote || promotingIdx !== null}
+ className="p-1 text-gray-400 hover:text-port-success disabled:opacity-30 disabled:cursor-not-allowed rounded"
+ title={promoteTitle}
+ aria-haspopup={requiresTargetKind ? 'menu' : undefined}
+ aria-expanded={requiresTargetKind ? pickerIdx === idx : undefined}
+ >
+ {promotingIdx === idx
+ ? <Loader2 size={14} className="animate-spin" />
+ : <ArrowUpCircle size={14} />}
+ </button>
+ {pickerIdx === idx && requiresTargetKind && (
+ <div
+ role="menu"
+ className="absolute right-0 top-full mt-1 z-20 w-44 bg-port-card border border-port-border rounded shadow-lg p-1 flex flex-col gap-0.5"
+ >
+ <div className="px-2 pt-1 pb-1 text-[10px] uppercase tracking-wide text-gray-500">
+ Promote to canon as…
+ </div>
+ {TRUNK_TABS.map((trunk) => (
+ <button
+ key={trunk.kind}
+ role="menuitem"
+ onClick={() => runPromote(idx, v, { targetKind: trunk.kind })}
+ className="text-left text-xs px-2 py-1.5 text-gray-200 hover:bg-port-success/20 rounded"
+ >
+ {trunk.label}
+ </button>
+ ))}
+ </div>
+ )}
+ </div>
+ )}
+ {onRenderVariation && (
+ <button
+ onClick={() => onRenderVariation(v)}
+ disabled={!canRender}
+ className="p-1 text-gray-400 hover:text-port-accent disabled:opacity-30 disabled:cursor-not-allowed rounded"
+ title={canRender ? 'Render this variation' : 'Save the world and configure a render backend to enable'}
+ >
+ <Play size={14} />
+ </button>
+ )}
+ <button
+ onClick={toggleLock}
+ className={`p-1 rounded ${locked ? 'text-port-accent hover:bg-port-accent/20' : 'text-gray-500 hover:text-gray-300'}`}
+ title={locked ? 'Locked — AI expand will preserve this variation' : 'Lock this variation against AI expand'}
+ aria-pressed={locked}
+ >
+ {locked ? <Lock size={14} /> : <Unlock size={14} />}
+ </button>
+ <button
+ onClick={startEdit}
+ className="p-1 text-gray-400 hover:text-port-accent rounded"
+ title="Edit"
+ >
+ <Edit3 size={14} />
+ </button>
+ <button
+ onClick={remove}
+ className="p-1 text-gray-400 hover:text-port-error rounded"
+ title="Remove"
+ >
+ <X size={14} />
+ </button>
+ </div>
+ );
+
+ return <EntryCard locked={locked} thumbnail={thumbnail} title={title} body={body} actions={actions} />;
+}
diff --git a/client/src/components/universeBuilder/UniverseTrunkPanels.jsx b/client/src/components/universeBuilder/UniverseTrunkPanels.jsx
new file mode 100644
index 0000000000..434697c6b2
--- /dev/null
+++ b/client/src/components/universeBuilder/UniverseTrunkPanels.jsx
@@ -0,0 +1,259 @@
+import { useState } from 'react';
+import { Loader2, Plus, Sparkles, Wand2 } from 'lucide-react';
+import toast from '../ui/Toast';
+import {
+ WORLD_CATEGORIES,
+ WORLD_CATEGORY_KEY_MAX,
+} from '../../services/api';
+import {
+ BUCKET_CANON,
+ normalizeCategoryKey,
+} from '../../lib/universeBuilderShared';
+import { canonEntryHasContent } from '../../lib/universeBuilderCounts';
+import UniverseCanonSection from '../universe/UniverseCanonSection';
+import BucketChipStrip from './BucketChipStrip';
+import { CategoryEditor } from './UniverseCategoryEditor';
+
+export function TrunkView({
+ trunk, draft, selectedId, buckets, activeBucket, setBucket,
+ canRender, canPromote, imageCfg, onUniverseChange,
+ onRemoveBucket, onUpdateBucket, onGenerateInBucket, onPromoteVariation,
+ onBulkRenderBucket, onRenderVariation, onBulkRenderTrunk,
+ onAddBucket,
+ onPreviewVariation = null,
+ onCanonPreview = null,
+ pendingByEntryId = {},
+ // Same pending head-map, passed through to UniverseCanonSection so canon
+ // rows show a spinner when a batch `/render` queues canon prompts.
+ externalPendingByEntryId = null,
+ onPendingCleared = null, onJobCompletedForEntry = null,
+}) {
+ const canonList = Array.isArray(draft[trunk.kind]) ? draft[trunk.kind] : [];
+ // Only count canon entries the server will actually compile — mirror the
+ // `synthesizeCanonPrompt`-empty-seed skip via `canonEntryHasContent`. Without
+ // this, "Bulk-render all (N)" would advertise more images than land, and the
+ // server can 400 with WORLD_BUILDER_EMPTY when every entry under the trunk
+ // synthesizes to nothing.
+ const canonRenderable = canonList.filter((e) => canonEntryHasContent(e, trunk.kind)).length;
+ const totalUnderTrunk =
+ canonRenderable
+ + buckets.reduce((n, k) => n + (draft.categories?.[k]?.variations?.length || 0), 0);
+ const [addingBucket, setAddingBucket] = useState(false);
+ const [newBucketName, setNewBucketName] = useState('');
+
+ const handleAddBucket = () => {
+ const key = normalizeCategoryKey(newBucketName);
+ if (!key) {
+ toast.error('Use letters or numbers for the bucket name');
+ return;
+ }
+ if (draft.categories?.[key]) {
+ toast.error('A bucket with that name already exists');
+ return;
+ }
+ onAddBucket({ key });
+ setNewBucketName('');
+ setAddingBucket(false);
+ setBucket(key);
+ };
+
+ return (
+ <>
+ <section className="bg-port-card border border-port-border rounded p-3 flex flex-col gap-2">
+ <div className="flex items-center justify-between gap-2 flex-wrap">
+ <BucketChipStrip
+ buckets={buckets}
+ activeBucket={activeBucket}
+ setBucket={setBucket}
+ extraChips={canonList.length > 0 ? [{ key: BUCKET_CANON, label: `Canon (${canonList.length})` }] : []}
+ />
+ <div className="flex items-center gap-1.5 flex-wrap">
+ <button
+ type="button"
+ onClick={() => setAddingBucket((v) => !v)}
+ className="text-xs px-2 py-1.5 bg-port-bg hover:bg-port-border text-gray-300 border border-port-border rounded flex items-center gap-1 min-h-[32px]"
+ title={`Add a sub-bucket under ${trunk.label}`}
+ >
+ <Plus size={12} /> Bucket
+ </button>
+ <button
+ type="button"
+ onClick={onBulkRenderTrunk}
+ disabled={!canRender || totalUnderTrunk === 0}
+ className="text-xs px-2 py-1.5 bg-port-accent/15 hover:bg-port-accent/25 disabled:opacity-30 disabled:cursor-not-allowed text-port-accent rounded flex items-center gap-1 min-h-[32px]"
+ title={totalUnderTrunk === 0 ? `No ${trunk.label.toLowerCase()} to render yet` : `Bulk-render all ${trunk.label.toLowerCase()} — ${totalUnderTrunk} prompt${totalUnderTrunk === 1 ? '' : 's'}`}
+ >
+ <Sparkles size={12} /> Bulk-render all ({totalUnderTrunk})
+ </button>
+ </div>
+ </div>
+ {addingBucket && (
+ <div className="flex items-center gap-2 flex-wrap pt-1">
+ <input
+ type="text"
+ value={newBucketName}
+ onChange={(e) => setNewBucketName(e.target.value)}
+ onKeyDown={(e) => { if (e.key === 'Enter') handleAddBucket(); }}
+ placeholder={trunk.kind === 'characters' ? 'heroes, villains, factions' : trunk.kind === 'places' ? 'colonies, ruins' : 'weapons, vehicles'}
+ className="flex-1 min-w-[160px] bg-port-bg border border-port-border rounded px-2 py-1.5 text-white text-sm focus:outline-none focus:border-port-accent"
+ maxLength={WORLD_CATEGORY_KEY_MAX}
+ autoFocus
+ />
+ <button
+ onClick={handleAddBucket}
+ disabled={!newBucketName.trim()}
+ className="text-xs px-2 py-1.5 bg-port-accent hover:bg-port-accent/90 disabled:opacity-50 text-white rounded min-h-[32px]"
+ >
+ Add
+ </button>
+ <button
+ onClick={() => { setAddingBucket(false); setNewBucketName(''); }}
+ className="text-xs px-2 py-1.5 bg-port-bg hover:bg-port-border text-gray-300 rounded min-h-[32px]"
+ >
+ Cancel
+ </button>
+ </div>
+ )}
+ </section>
+
+ {/* Canon visibility: "All" (no bucket selected) or the canon pseudo-bucket.
+ Gated on `draft.id === selectedId` to avoid the universe-switch race
+ documented on UniverseCanonSection itself. */}
+ {(!activeBucket || activeBucket === BUCKET_CANON) && selectedId && draft.id === selectedId ? (
+ <UniverseCanonSection
+ universe={draft}
+ universeId={selectedId}
+ onUniverseChange={onUniverseChange}
+ imageCfg={imageCfg}
+ kindFilter={trunk.kind}
+ externalPendingByEntryId={externalPendingByEntryId}
+ onExternalCanonJobSettled={onPendingCleared}
+ onPreview={onCanonPreview}
+ />
+ ) : null}
+
+ {activeBucket !== BUCKET_CANON && (
+ <>
+ {(activeBucket ? [activeBucket] : buckets).length === 0 ? (
+ <section className="bg-port-card border border-port-border rounded p-6 text-center text-sm text-gray-500">
+ No {trunk.label.toLowerCase()} sub-buckets yet.{' '}
+ <button
+ type="button"
+ onClick={() => setAddingBucket(true)}
+ className="text-port-accent hover:underline"
+ >
+ Add one
+ </button>
+ {' '}or click <em>Generate From Idea</em> on the Bible tab to seed them.
+ </section>
+ ) : (
+ <section className="grid grid-cols-1 md:grid-cols-2 gap-3">
+ {(activeBucket ? [activeBucket] : buckets).map((cat) => (
+ <CategoryEditor
+ key={cat}
+ category={cat}
+ variations={draft.categories?.[cat]?.variations || []}
+ canRemove={!WORLD_CATEGORIES.includes(cat)}
+ onChange={(next) => onUpdateBucket(cat, next)}
+ onRemove={() => onRemoveBucket(cat)}
+ canRender={canRender}
+ onRenderCategory={() => onBulkRenderBucket(cat)}
+ onRenderVariation={(v) => onRenderVariation(cat, v)}
+ onGenerate={(count) => onGenerateInBucket(cat, count)}
+ canPromote={canPromote}
+ bucketKind={draft.categories?.[cat]?.kind ?? trunk.kind}
+ onPromote={onPromoteVariation ? (v) => onPromoteVariation(cat, v) : null}
+ onPreviewVariation={onPreviewVariation}
+ pendingByEntryId={pendingByEntryId}
+ onJobCompleted={(entryId, filename, completedJobId) =>
+ onJobCompletedForEntry?.(entryId, filename, cat, completedJobId)}
+ onJobFailed={(entryId, err, failedJobId) => {
+ // Toast BEFORE clearing — clearing removes the
+ // MediaJobThumb from the row and the failure state
+ // disappears with it. Without the toast, a failed
+ // variation render collapses silently to the empty
+ // thumbnail (mirrors UniverseCanonSection.onJobFailed).
+ if (err) toast.error(`Render failed: ${typeof err === 'string' ? err : (err.message || err)}`);
+ onPendingCleared?.(entryId, failedJobId);
+ }}
+ />
+ ))}
+ </section>
+ )}
+ </>
+ )}
+ </>
+ );
+}
+// Other tab — un-kinded buckets that haven't been sorted into a trunk yet.
+// Same card grid as TrunkView but no canon plumbing, plus an "Auto-sort"
+// action that (eventually) LLM-classifies each bucket into the right trunk.
+export function OtherTab({
+ draft, buckets, activeBucket, setBucket, canRender, canPromote,
+ onUpdateBucket, onRemoveBucket, onGenerateInBucket, onPromoteVariation,
+ onBulkRenderBucket, onRenderVariation, onAssignBucketKind, onAutoSort,
+ autoSorting = false,
+ onPreviewVariation = null,
+ pendingByEntryId = {}, onPendingCleared = null, onJobCompletedForEntry = null,
+}) {
+ return (
+ <>
+ <section className="bg-port-card border border-port-border rounded p-3 flex flex-col gap-2">
+ <div className="flex items-center justify-between gap-2 flex-wrap">
+ <BucketChipStrip
+ buckets={buckets}
+ activeBucket={activeBucket}
+ setBucket={setBucket}
+ />
+ <button
+ type="button"
+ onClick={onAutoSort}
+ disabled={autoSorting}
+ className="text-xs px-2 py-1.5 bg-port-accent/15 hover:bg-port-accent/25 disabled:opacity-50 text-port-accent rounded flex items-center gap-1 min-h-[32px]"
+ title="Auto-sort with AI — sends every Other-tab bucket to the active LLM and assigns each to characters / places / objects"
+ >
+ {autoSorting ? <Loader2 size={12} className="animate-spin" /> : <Wand2 size={12} />}
+ {autoSorting ? 'Sorting…' : 'Auto-sort with AI'}
+ </button>
+ </div>
+ <p className="text-[11px] text-gray-500">
+ These buckets aren't tagged as Cast / Places / Objects yet — they were
+ either added manually or imported from a pre-Phase-A universe. Auto-sort
+ asks the active LLM to classify every bucket into the right trunk.
+ </p>
+ </section>
+
+ <section className="grid grid-cols-1 md:grid-cols-2 gap-3">
+ {(activeBucket ? [activeBucket] : buckets).map((cat) => (
+ <CategoryEditor
+ key={cat}
+ category={cat}
+ variations={draft.categories?.[cat]?.variations || []}
+ canRemove={!WORLD_CATEGORIES.includes(cat)}
+ onChange={(next) => onUpdateBucket(cat, next)}
+ onRemove={() => onRemoveBucket(cat)}
+ canRender={canRender}
+ onRenderCategory={() => onBulkRenderBucket(cat)}
+ onRenderVariation={(v) => onRenderVariation(cat, v)}
+ onGenerate={(count) => onGenerateInBucket(cat, count)}
+ canPromote={canPromote}
+ bucketKind={draft.categories?.[cat]?.kind}
+ onPromote={onPromoteVariation ? (v, opts) => onPromoteVariation(cat, v, opts) : null}
+ onAssignBucketKind={onAssignBucketKind ? (targetKind) => onAssignBucketKind(cat, targetKind) : null}
+ onPreviewVariation={onPreviewVariation}
+ pendingByEntryId={pendingByEntryId}
+ onJobCompleted={(entryId, filename, completedJobId) =>
+ onJobCompletedForEntry?.(entryId, filename, cat, completedJobId)}
+ onJobFailed={(entryId, err, failedJobId) => {
+ // Same surface-then-clear order as the Trunk-tab handler above:
+ // MediaJobThumb is unmounted on clear, so the toast must fire
+ // first or the user gets no signal that the render failed.
+ if (err) toast.error(`Render failed: ${typeof err === 'string' ? err : (err.message || err)}`);
+ onPendingCleared?.(entryId, failedJobId);
+ }}
+ />
+ ))}
+ </section>
+ </>
+ );
+}