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

Universe Builder: Other→trunk, full Render, DRY batch + drop MediaGen UB tab (#287)

[._.]/ Adam Eivy7653a9e090c9
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 0d098f9bdb..f86aaa1316 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -1,3 +1,25 @@
+# Unreleased
+
+## Features
+
+### Universe Builder
+
+- **Other tab — manual trunk assignment.** Each bucket on the Other tab now has an **Assign to…** menu (Cast / Places / Objects) that retags `categories[bucket].kind` so the bucket moves out of Other into the matching trunk on next render. Variations stay in place; per-variation promote-to-canon remains a separate action.
+- **Render tab — Other group + dedupe.** Removed the redundant "Prompt set" dropdown from the Batch render card — scope is now always chosen via the Render targets section below. Render targets gained an **Other** group with per-bucket sub-buttons and a `Bulk-render all (N)` button. Top-level action is now **Render everything (N)**.
+- **Batch render — full Image Gen surface.** Batch Render now uses the shared `ImageGenSettingsForm`, so switching the backend chip (Local / External / Codex) reveals every per-mode option: model, resolution, steps, guidance/CFG, quantize, seed, **LoRAs**, **style preset**, negative prompt, and extra style. Server-side render schema accepts these as optional per-batch overrides and threads them through prompt composition + every enqueued job (`server/routes/universeBuilder.js` + `server/services/universeBuilder.js`).
+
+### Media Gen
+
+- **Removed duplicate Universe Builder tab.** The MediaGen tab strip no longer shows a Universe Builder entry — the Create sidebar already links straight to `/universe-builder`. Legacy `/media/universe-builder/*` URLs redirect to the top-level routes so bookmarks keep working.
+
## Changed
- **Universe Builder — starter idea is no longer capped at 4000 chars.** The starter idea is whatever the user wants to type, from a one-line pitch to a full treatment. The Zod-backed `STARTER_PROMPT_MAX` is raised to 200,000 chars (a sanity ceiling, not an artificial brevity constraint) and the textarea's `maxLength={4000}` attribute is removed.
+- **Sidebar + ⌘K label shortened to "Universe".** The Create sidebar link and palette manifest entry for `/universe-builder` now read "Universe" instead of "Universe Builder"; voice/palette aliases still include `universe-builder` so old phrasings keep resolving.
+
+## Refactors
+
+- **`LoraPicker` extracted** (`client/src/components/imageGen/LoraPicker.jsx`). The LoRA multi-select previously inlined in `ImageGen.jsx` is now a shared component used by both the standalone Image Gen page and the Universe Builder batch-render form.
+- **`ImageGenSettingsForm` extended** with `showLoras` + `showStylePreset` props (mounts `LoraPicker` / `StylePresetPicker`) and the previously-hidden CFG / quantize / model-defaults reset.
+- **`getStylePresetById` helper** added to `server/lib/writersRoomStylePresets.js` — Map-backed O(1) lookup that replaces the hand-rolled `STYLE_PRESETS.find(...)` pattern.
+- **`updateUniverse(id, patch, options)`** API client now passes options through to the underlying `request()` helper, enabling silent error mode.
diff --git a/client/src/App.jsx b/client/src/App.jsx
index 4fa45ae9a1..c6551706a8 100644
--- a/client/src/App.jsx
+++ b/client/src/App.jsx
@@ -113,6 +113,19 @@ function CanonRedirect() {
return <Navigate to={`${pathname.replace(/\/canon\/?$/, '')}${search}#canon`} replace />;
}
+// /media/universe-builder/* → /universe-builder/* redirect for legacy bookmarks
+// after the MediaGen tab for Universe Builder was removed in favor of the
+// Create sidebar link. The canon variant forces `#canon` to scroll the
+// embedded canon section; non-canon preserves whatever hash the user had.
+function UniverseBuilderRedirect({ canon = false }) {
+ const { pathname, search, hash } = useLocation();
+ const rest = pathname.replace(/^\/media\/universe-builder/, '');
+ const target = canon
+ ? `/universe-builder${rest.replace(/\/canon\/?$/, '')}${search}#canon`
+ : `/universe-builder${rest}${search}${hash}`;
+ return <Navigate to={target} replace />;
+}
+
// Force full reload on HMR — partial hot-replacement of the route tree
// causes stale lazy imports and React Router errors on nested paths
if (import.meta.hot) {
@@ -221,9 +234,12 @@ export default function App() {
<Route path="timeline/:projectId" element={<VideoTimelineEditor />} />
<Route path="models" element={<MediaModels />} />
<Route path="loras" element={<Loras />} />
- <Route path="universe-builder" element={<UniverseBuilder />} />
- <Route path="universe-builder/:universeId" element={<UniverseBuilder />} />
- <Route path="universe-builder/:universeId/canon" element={<CanonRedirect />} />
+ {/* Universe Builder lives at /universe-builder (Create sidebar
+ link). These redirects keep legacy /media/universe-builder
+ bookmarks working after the MediaGen tab was removed. */}
+ <Route path="universe-builder" element={<Navigate to="/universe-builder" replace />} />
+ <Route path="universe-builder/:universeId" element={<UniverseBuilderRedirect />} />
+ <Route path="universe-builder/:universeId/canon" element={<UniverseBuilderRedirect canon />} />
</Route>
<Route path="image-gen" element={<RedirectWithSearch to="/media/image" />} />
<Route path="video-gen" element={<RedirectWithSearch to="/media/video" />} />
diff --git a/client/src/components/Layout.jsx b/client/src/components/Layout.jsx
index 60cee376b6..0ac686f4fb 100644
--- a/client/src/components/Layout.jsx
+++ b/client/src/components/Layout.jsx
@@ -199,7 +199,7 @@ const navItems = [
{ to: '/media', label: 'Media Gen', icon: Layers },
{ to: '/pipeline', label: 'Series Pipeline', icon: WorkflowIcon, dynamic: 'pipelineSeries' },
{ to: '/sharing', label: 'Sharing', icon: Share2 },
- { to: '/universe-builder', label: 'Universe Builder', icon: Globe },
+ { to: '/universe-builder', label: 'Universe', icon: Globe },
{ to: '/writers-room', label: 'Writers Room', icon: NotebookPen }
]
},
diff --git a/client/src/components/imageGen/ImageGenSettingsForm.jsx b/client/src/components/imageGen/ImageGenSettingsForm.jsx
index 09ccc29625..2b010e88f0 100644
--- a/client/src/components/imageGen/ImageGenSettingsForm.jsx
+++ b/client/src/components/imageGen/ImageGenSettingsForm.jsx
@@ -10,6 +10,8 @@
import BackendChipStrip from '../media/BackendChipStrip';
import ImageGenControls from './ImageGenControls';
+import LoraPicker from './LoraPicker';
+import StylePresetPicker from '../media/StylePresetPicker';
import { IMAGE_GEN_MODE } from '../../lib/imageGenBackends';
export default function ImageGenSettingsForm({
@@ -18,11 +20,22 @@ export default function ImageGenSettingsForm({
models = [],
availableBackends = [],
showStyleFields = true,
+ // LoRA picker — local mode only. Pass `availableLoras` + `currentRunnerFamily`
+ // to enable. `cfg.loras` holds the selected `[{ filename, name, scale }]`.
+ showLoras = false,
+ availableLoras = [],
+ currentRunnerFamily = null,
+ onAppendTrigger = null,
+ // Style preset picker — sits above the extra-style textarea. `cfg.stylePreset`
+ // holds the full preset object (not just the id) so consumers can compose
+ // styled prompts without a second lookup.
+ showStylePreset = false,
disabled = false,
}) {
const cfg = value || {};
const merge = (patch) => onChange?.({ ...cfg, ...patch });
const isCodex = cfg.mode === IMAGE_GEN_MODE.CODEX;
+ const isLocal = cfg.mode === IMAGE_GEN_MODE.LOCAL;
const labelCls = 'block text-xs font-medium text-gray-400 mb-1';
const textareaCls = 'w-full bg-port-bg border border-port-border rounded-lg px-2 py-2 text-sm text-white focus:outline-none focus:border-port-accent disabled:opacity-50 resize-y';
@@ -58,7 +71,7 @@ export default function ImageGenSettingsForm({
mode={cfg.mode}
models={models}
modelId={cfg.modelId}
- onModelChange={(modelId) => merge({ modelId })}
+ onModelChange={(modelId) => merge({ modelId, steps: '', guidance: '' })}
width={cfg.width}
height={cfg.height}
onResolutionChange={(width, height) => merge({ width, height })}
@@ -66,13 +79,35 @@ export default function ImageGenSettingsForm({
onStepsChange={(steps) => merge({ steps })}
guidance={cfg.guidance}
onGuidanceChange={(guidance) => merge({ guidance })}
+ cfgScale={cfg.cfgScale}
+ onCfgScaleChange={(cfgScale) => merge({ cfgScale })}
+ quantize={cfg.quantize}
+ onQuantizeChange={(quantize) => merge({ quantize })}
seed={cfg.seed}
onSeedChange={(seed) => merge({ seed })}
showSeed
- showQuantize={false}
disabled={disabled}
/>
+ {showLoras && isLocal ? (
+ <LoraPicker
+ availableLoras={availableLoras}
+ selected={Array.isArray(cfg.loras) ? cfg.loras : []}
+ onChange={(loras) => merge({ loras })}
+ currentRunnerFamily={currentRunnerFamily}
+ onAppendTrigger={onAppendTrigger}
+ disabled={disabled}
+ />
+ ) : null}
+
+ {showStylePreset ? (
+ <StylePresetPicker
+ value={cfg.stylePreset?.id || ''}
+ onChange={(preset) => merge({ stylePreset: preset })}
+ disabled={disabled}
+ />
+ ) : null}
+
{showStyleFields ? (
<div className="space-y-3">
<label className="block">
diff --git a/client/src/components/imageGen/LoraPicker.jsx b/client/src/components/imageGen/LoraPicker.jsx
new file mode 100644
index 0000000000..f65de048de
--- /dev/null
+++ b/client/src/components/imageGen/LoraPicker.jsx
@@ -0,0 +1,121 @@
+// Shared LoRA multi-select used by the Image Gen page and the Universe
+// Builder batch-render form. Filters `availableLoras` by `currentRunnerFamily`
+// (legacy entries with `runnerFamily === null` are shown too — the runner
+// may still accept them and we surface a clear error otherwise).
+//
+// `selected` is the caller-owned list of `{ filename, name, scale }` entries.
+// `onChange(next)` receives the full updated list (add / remove / scale edit).
+//
+// When `onAppendTrigger` is provided, each selected LoRA with trigger words
+// gets a `+ trigger` button — typically wired to append the trigger tokens to
+// the caller's prompt. Omit it (or pass `null`) where there's no prompt to
+// append into (batch render with per-variation prompts).
+
+import { Link } from 'react-router-dom';
+
+// Matches /api/image-gen/generate and /api/universe-builder/:id/render's
+// .max(8) on the LoRA list. Hard cap stops the user from queuing a render
+// that the server would reject with a confusing 400.
+const MAX_SELECTED_LORAS = 8;
+
+export default function LoraPicker({
+ availableLoras = [],
+ selected = [],
+ onChange,
+ currentRunnerFamily,
+ onAppendTrigger = null,
+ disabled = false,
+}) {
+ if (!availableLoras.length) return null;
+ const compatible = availableLoras.filter((l) => !l.runnerFamily || l.runnerFamily === currentRunnerFamily);
+ const atCap = selected.length >= MAX_SELECTED_LORAS;
+
+ const toggle = (lora, on) => {
+ if (on) {
+ if (atCap) return;
+ const recommended = typeof lora.recommendedScale === 'number' ? lora.recommendedScale : 1.0;
+ onChange?.([...selected, { filename: lora.filename, name: lora.name, scale: recommended }]);
+ } else {
+ onChange?.(selected.filter((s) => s.filename !== lora.filename));
+ }
+ };
+ const setScale = (filename, scale) => {
+ onChange?.(selected.map((s) => s.filename === filename ? { ...s, scale } : s));
+ };
+
+ return (
+ <div>
+ <div className="flex items-center justify-between mb-1">
+ <label className="block text-xs font-medium text-gray-400">
+ LoRAs <span className="text-gray-600 font-normal">
+ ({compatible.length}/{availableLoras.length} compatible
+ {selected.length > 0 ? ` · ${selected.length}/${MAX_SELECTED_LORAS} selected` : ''})
+ </span>
+ </label>
+ <Link to="/media/loras" className="text-[11px] text-port-accent hover:underline">Manage →</Link>
+ </div>
+ {compatible.length === 0 ? (
+ <p className="text-xs text-gray-500 italic">
+ No LoRAs match this model&apos;s runner. Install one matching <code>{currentRunnerFamily}</code> on the LoRAs page.
+ </p>
+ ) : (
+ <div className="space-y-1.5 max-h-40 overflow-y-auto pr-1">
+ {compatible.map((lora) => {
+ const sel = selected.find((s) => s.filename === lora.filename);
+ const recommended = typeof lora.recommendedScale === 'number' ? lora.recommendedScale : 1.0;
+ const triggers = lora.triggerWords || [];
+ return (
+ <div key={lora.filename} className="flex items-center gap-2">
+ <label className={`flex items-center gap-2 flex-1 min-w-0 ${atCap && !sel ? 'cursor-not-allowed opacity-50' : 'cursor-pointer'}`}>
+ <input
+ type="checkbox"
+ checked={!!sel}
+ disabled={disabled || (atCap && !sel)}
+ onChange={(e) => toggle(lora, e.target.checked)}
+ className="rounded"
+ title={atCap && !sel ? `Maximum ${MAX_SELECTED_LORAS} LoRAs per render — uncheck one to swap` : undefined}
+ />
+ <span className="text-xs text-gray-300 truncate flex-1" title={triggers.length ? `Trigger words: ${triggers.join(', ')}` : lora.name}>
+ {lora.name}
+ {/* baseModel suffix disambiguates multiple installed
+ versions of the same model (e.g. ZImageBase vs
+ ZImageTurbo, both mapping to 'z-image' family). */}
+ {lora.civitai?.baseModel && (
+ <span className="ml-1.5 text-[10px] text-gray-600 font-mono">[{lora.civitai.baseModel}]</span>
+ )}
+ {triggers.length > 0 && (
+ <span className="ml-2 text-[10px] text-gray-500 font-mono">{triggers.slice(0, 2).join(', ')}{triggers.length > 2 ? '…' : ''}</span>
+ )}
+ </span>
+ </label>
+ {sel && (
+ <div className="flex items-center gap-2">
+ {triggers.length > 0 && onAppendTrigger && (
+ <button
+ type="button"
+ onClick={() => onAppendTrigger(triggers)}
+ disabled={disabled}
+ title={`Append to prompt: ${triggers.join(', ')}`}
+ className="text-[11px] px-2 py-1 rounded bg-port-accent/10 text-port-accent border border-port-accent/30 hover:bg-port-accent/20 disabled:opacity-50 whitespace-nowrap"
+ >
+ + trigger
+ </button>
+ )}
+ <span className="text-xs text-gray-500" title={`Recommended: ${recommended.toFixed(2)}`}>Scale</span>
+ <input
+ type="number" min={0} max={2} step={0.1}
+ value={sel.scale}
+ disabled={disabled}
+ onChange={(e) => setScale(lora.filename, parseFloat(e.target.value) || 0)}
+ className="w-20 bg-port-bg border border-port-border rounded px-2 py-1 text-sm text-gray-200"
+ />
+ </div>
+ )}
+ </div>
+ );
+ })}
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/client/src/pages/ImageGen.jsx b/client/src/pages/ImageGen.jsx
index 5b85f220b8..90bacc7906 100644
--- a/client/src/pages/ImageGen.jsx
+++ b/client/src/pages/ImageGen.jsx
@@ -22,6 +22,7 @@ import { RUNNER_FAMILIES } from '../lib/runnerFamilies';
import Flux2InstallModal from '../components/imageGen/Flux2InstallModal';
import HfTokenBanner from '../components/imageGen/HfTokenBanner';
import ImageGenControls from '../components/imageGen/ImageGenControls';
+import LoraPicker from '../components/imageGen/LoraPicker';
import MediaJobsQueue from '../components/media/MediaJobsQueue';
import { useMediaCompletionRefresh } from '../hooks/useMediaCompletionRefresh';
import { useMediaAnnotations } from '../hooks/useMediaAnnotations';
@@ -387,12 +388,8 @@ export default function ImageGen() {
const currentModel = models.find((m) => m.id === modelId);
const isFlux2Model = currentModel?.runner === RUNNER_FAMILIES.FLUX2;
// mflux is the default runner for entries with no explicit `runner` field.
- // Used to filter the LoRA picker so users only see compatible weights for
- // the selected model. LoRAs with `runnerFamily === null` (legacy / unknown
- // base) are shown too with a warning indicator — the runner may still
- // accept them, or surface a clear error.
+ // LoraPicker filters compatible weights itself; we just pass the family.
const currentRunnerFamily = currentModel?.runner || RUNNER_FAMILIES.MFLUX;
- const compatibleLoras = availableLoras.filter((l) => !l.runnerFamily || l.runnerFamily === currentRunnerFamily);
const refreshFlux2Status = useCallback((signal) => {
return fetch('/api/image-gen/setup/flux2-status', { signal })
@@ -886,79 +883,15 @@ export default function ImageGen() {
disabled={statusLoading}
/>
- {isLocalMode && availableLoras.length > 0 && (
- <div>
- <div className="flex items-center justify-between mb-1">
- <label className="block text-xs font-medium text-gray-400">
- LoRAs <span className="text-gray-600 font-normal">({compatibleLoras.length}/{availableLoras.length} compatible)</span>
- </label>
- <Link to="/media/loras" className="text-[11px] text-port-accent hover:underline">Manage →</Link>
- </div>
- {compatibleLoras.length === 0 ? (
- <p className="text-xs text-gray-500 italic">No LoRAs match this model's runner. Install one matching <code>{currentRunnerFamily}</code> on the LoRAs page.</p>
- ) : (
- <div className="space-y-1.5 max-h-40 overflow-y-auto pr-1">
- {compatibleLoras.map((lora) => {
- const selected = selectedLoras.find((s) => s.filename === lora.filename);
- const recommended = typeof lora.recommendedScale === 'number' ? lora.recommendedScale : 1.0;
- return (
- <div key={lora.filename} className="flex items-center gap-2">
- <label className="flex items-center gap-2 cursor-pointer flex-1 min-w-0">
- <input
- type="checkbox"
- checked={!!selected}
- disabled={statusLoading}
- onChange={(e) => {
- if (e.target.checked) setSelectedLoras((p) => [...p, { filename: lora.filename, name: lora.name, scale: recommended }]);
- else setSelectedLoras((p) => p.filter((s) => s.filename !== lora.filename));
- }}
- className="rounded"
- />
- <span className="text-xs text-gray-300 truncate flex-1" title={(lora.triggerWords || []).length ? `Trigger words: ${lora.triggerWords.join(', ')}` : lora.name}>
- {lora.name}
- {/* baseModel suffix disambiguates multiple installed
- versions of the same model (e.g. ZImageBase vs
- ZImageTurbo, both mapping to 'z-image' family). */}
- {lora.civitai?.baseModel && (
- <span className="ml-1.5 text-[10px] text-gray-600 font-mono">[{lora.civitai.baseModel}]</span>
- )}
- {(lora.triggerWords || []).length > 0 && (
- <span className="ml-2 text-[10px] text-gray-500 font-mono">{lora.triggerWords.slice(0, 2).join(', ')}{lora.triggerWords.length > 2 ? '…' : ''}</span>
- )}
- </span>
- </label>
- {selected && (
- <div className="flex items-center gap-2">
- {(lora.triggerWords || []).length > 0 && (
- <button
- type="button"
- onClick={() => setPrompt((p) => appendTriggerWords(p, lora.triggerWords))}
- disabled={statusLoading}
- title={`Append to prompt: ${lora.triggerWords.join(', ')}`}
- className="text-[11px] px-2 py-1 rounded bg-port-accent/10 text-port-accent border border-port-accent/30 hover:bg-port-accent/20 disabled:opacity-50 whitespace-nowrap"
- >
- + trigger
- </button>
- )}
- <span className="text-xs text-gray-500" title={`Recommended: ${recommended.toFixed(2)}`}>Scale</span>
- <input
- type="number" min={0} max={2} step={0.1}
- value={selected.scale}
- disabled={statusLoading}
- onChange={(e) => {
- const scale = parseFloat(e.target.value) || 0;
- setSelectedLoras((p) => p.map((s) => s.filename === lora.filename ? { ...s, scale } : s));
- }}
- className="w-20 bg-port-bg border border-port-border rounded px-2 py-1 text-sm text-gray-200"
- />
- </div>
- )}
- </div>
- );
- })}
- </div>
- )}
- </div>
+ {isLocalMode && (
+ <LoraPicker
+ availableLoras={availableLoras}
+ selected={selectedLoras}
+ onChange={setSelectedLoras}
+ currentRunnerFamily={currentRunnerFamily}
+ onAppendTrigger={(words) => setPrompt((p) => appendTriggerWords(p, words))}
+ disabled={statusLoading}
+ />
)}
{isLocalMode && (
diff --git a/client/src/pages/MediaGen.jsx b/client/src/pages/MediaGen.jsx
index 7a7c5dfaf9..0bb23403be 100644
--- a/client/src/pages/MediaGen.jsx
+++ b/client/src/pages/MediaGen.jsx
@@ -1,10 +1,9 @@
import { useNavigate, useLocation, Outlet } from 'react-router-dom';
-import { Layers, Image as ImageIcon, Film, History, HardDrive, Scissors, FolderOpen, Clapperboard, Globe2, Sparkles } from 'lucide-react';
+import { Layers, Image as ImageIcon, Film, History, HardDrive, Scissors, FolderOpen, Clapperboard, Sparkles } from 'lucide-react';
const TABS = [
{ id: 'image', label: 'Image', icon: ImageIcon },
{ id: 'video', label: 'Video', icon: Film },
- { id: 'universe-builder', label: 'Universe Builder', icon: Globe2 },
{ id: 'timeline', label: 'Timeline', icon: Scissors },
{ id: 'creative-director', label: 'Creative Director', icon: Clapperboard },
{ id: 'history', label: 'History', icon: History },
diff --git a/client/src/pages/UniverseBuilder.jsx b/client/src/pages/UniverseBuilder.jsx
index b7093c0bea..52d202e5b2 100644
--- a/client/src/pages/UniverseBuilder.jsx
+++ b/client/src/pages/UniverseBuilder.jsx
@@ -23,13 +23,13 @@ import {
WORLD_CATEGORY_KEY_MAX, COMPOSITE_PROMPT_MAX, WORLD_LOGLINE_MAX,
WORLD_PREMISE_MAX, WORLD_STYLE_NOTES_MAX, WORLD_LOCKABLE_FIELDS,
ensureInfluences, isInfluenceLockField, mergeInfluencesWithLocks,
- listImageModels, getSettings,
+ listImageModels, listLorasFull, getSettings,
} from '../services/api';
import useClickOutside from '../hooks/useClickOutside';
import { useLocalStoragePersisted } from '../hooks/useLocalStorageBool';
import InfluenceChipsInput from '../components/universeBuilder/InfluenceChipsInput';
-import BackendChipStrip from '../components/media/BackendChipStrip';
-import ImageGenControls from '../components/imageGen/ImageGenControls';
+import ImageGenSettingsForm from '../components/imageGen/ImageGenSettingsForm';
+import { RUNNER_FAMILIES } from '../lib/runnerFamilies';
import ShareToButton from '../components/sharing/ShareToButton';
import OriginBadge from '../components/sharing/OriginBadge';
import UniverseCanonSection from '../components/universe/UniverseCanonSection';
@@ -225,6 +225,13 @@ const DEFAULT_RENDER_OPTS = {
mode: '',
promptMode: 'variations',
batchPerVariation: 1,
+ // Extended Image Gen surface used by the batch render form. Server accepts
+ // these as optional patches on top of the universe's stored influences.
+ seed: '',
+ negativePrompt: '',
+ extraStyle: '',
+ stylePreset: null,
+ loras: [],
};
// Mirror of COMPOSITE_SHEET_KINDS in server/services/universeBuilder.js — keep
@@ -527,6 +534,7 @@ export default function UniverseBuilder() {
const [activeProviderId, setActiveProviderId] = useState(null);
// Image-gen plumbing for the batch-render form (reused from Image Gen).
const [imageModels, setImageModels] = useState([]);
+ const [availableLoras, setAvailableLoras] = useState([]);
const [availableBackends, setAvailableBackends] = useState([]);
const [defaultMode, setDefaultMode] = useState(null);
// Per-render config used by the embedded Canon section for reference
@@ -543,6 +551,13 @@ export default function UniverseBuilder() {
// double-mount stays clean.
const mountedRef = useRef(true);
useEffect(() => () => { mountedRef.current = false; }, []);
+ // Always-current draft snapshot. Click handlers that close over `draft`
+ // can race against in-flight setDraft calls (e.g. handleGenerateInCategory
+ // finishes its auto-save between render and click) — read draftRef.current
+ // for the freshest local state so PATCH payloads carry the latest merged
+ // categories instead of the stale closure value.
+ const draftRef = useRef(null);
+ useEffect(() => { draftRef.current = draft; }, [draft]);
// Page-level in-flight gate for the promote action. Ref + state pair so
// the disable check stays synchronous (ref) while still triggering renders
// (state). Promote writes to `universe[bibleField]` and `categories[key]`
@@ -604,16 +619,18 @@ export default function UniverseBuilder() {
const refresh = async () => {
setLoading(true);
- const [list, provData, models, settings] = await Promise.all([
+ const [list, provData, models, loras, settings] = await Promise.all([
listUniverses().catch(() => []),
getProviders().catch(() => ({ providers: [] })),
listImageModels().catch(() => []),
+ listLorasFull().catch(() => []),
getSettings().catch(() => ({})),
]);
setWorlds(list);
setProviders(provData.providers || []);
setActiveProviderId(provData.activeProvider || null);
setImageModels(models || []);
+ setAvailableLoras(Array.isArray(loras) ? loras : []);
// Batch render rejects external (would block the request for the whole
// batch), so hide that chip even if it's configured.
const backends = deriveAvailableBackends(settings, { excludeExternal: true });
@@ -1223,8 +1240,18 @@ export default function UniverseBuilder() {
const needsCanonDefault = !scope && (promptMode === 'canon' || promptMode === 'all');
const effectiveCanonSelection = scope?.canonSelection
?? (needsCanonDefault
- ? { characters: 'all', settings: 'all', objects: 'all' }
+ ? Object.fromEntries(TRUNK_TABS.map((t) => [t.kind, 'all']))
: undefined);
+ // Per-batch overrides from the ImageGenSettingsForm. Empty strings →
+ // undefined so the server falls back to the universe's stored influences.
+ // Seed coerces to a non-negative int (matching /api/image-gen/generate
+ // semantics) — non-numeric strings become undefined rather than NaN.
+ const seedRaw = renderOpts.seed;
+ const seedNum = seedRaw === '' || seedRaw == null ? null : Number(seedRaw);
+ const seed = Number.isFinite(seedNum) && seedNum >= 0 ? Math.trunc(seedNum) : undefined;
+ const loras = Array.isArray(renderOpts.loras) && renderOpts.loras.length
+ ? renderOpts.loras
+ : undefined;
setRendering(true);
const result = await renderWorld(selectedId, {
mode: effectiveMode,
@@ -1240,6 +1267,11 @@ export default function UniverseBuilder() {
selection: scope?.selection,
sheetSelection: scope?.sheetSelection,
canonSelection: effectiveCanonSelection,
+ seed,
+ negativePrompt: renderOpts.negativePrompt?.trim() || undefined,
+ extraStyle: renderOpts.extraStyle?.trim() || undefined,
+ stylePresetId: renderOpts.stylePreset?.id || undefined,
+ loras,
}).catch((e) => { toast.error(`Render failed: ${e.message}`); return null; });
setRendering(false);
if (!result) return;
@@ -1316,6 +1348,45 @@ export default function UniverseBuilder() {
// trunk to `other`.
categories: { ...d.categories, [cat]: { ...(d.categories?.[cat] || {}), variations } },
}));
+ // Retag an Other-tab bucket as a canon trunk (Cast / Places / Objects).
+ // Variations stay in place; the bucket simply moves out of the Other tab
+ // into the matching trunk on next render via groupBucketsByKind.
+ const assignBucketKind = async (bucket, targetKind) => {
+ if (!TRUNK_BY_KIND[targetKind]) return;
+ // Read from draftRef so a generate's just-landed auto-save (which set
+ // draft via setDraft) is visible here even if React hasn't committed a
+ // re-render yet — without this, the PATCH below could overwrite the new
+ // variations with the closure's stale ones.
+ const latestDraft = draftRef.current || draft;
+ const current = latestDraft.categories?.[bucket];
+ if (!current) return;
+ const nextBucket = { ...current, kind: targetKind };
+ // Only the affected bucket is sent in the PATCH — the server's categories
+ // patch is keyed (per-bucket replace), so omitting other keys leaves them
+ // untouched. That keeps concurrent edits to other buckets safe even when
+ // this handler raced an in-flight setDraft.
+ setDraft((d) => ({
+ ...d,
+ categories: {
+ ...d.categories,
+ [bucket]: { ...(d.categories?.[bucket] || current), kind: targetKind },
+ },
+ }));
+ const trunk = TRUNK_BY_KIND[targetKind];
+ if (!selectedId) {
+ toast.success(`Tagged "${humanizeCategory(bucket)}" as ${trunk.label} — save to persist`);
+ return;
+ }
+ const updated = await updateUniverse(selectedId, { categories: { [bucket]: nextBucket } }, { silent: true })
+ .catch((e) => { toast.error(`Move failed: ${e.message}`); return null; });
+ if (updated) {
+ setWorlds((prev) => {
+ const without = prev.filter((w) => w.id !== updated.id);
+ return [updated, ...without];
+ });
+ toast.success(`Moved "${humanizeCategory(bucket)}" to ${trunk.label}`);
+ }
+ };
const handleGenerateInCategory = async (cat, count) => {
const current = draft.categories?.[cat]?.variations || [];
const existingLabels = current.map((v) => v.label).filter(Boolean);
@@ -1663,6 +1734,7 @@ export default function UniverseBuilder() {
onPromoteVariation={(bucket, v, opts) => handlePromoteVariation(bucket, v, opts)}
onBulkRenderBucket={(bucket) => runRender({ promptMode: 'variations', selection: { [bucket]: 'all' } })}
onRenderVariation={(bucket, v) => runRender({ promptMode: 'variations', selection: { [bucket]: [v.label] } })}
+ onAssignBucketKind={assignBucketKind}
onAutoSort={() => {
toast('Auto-sort with AI is wired in a follow-up. Re-run "Generate From Idea" — Phase B\'s expand call now classifies buckets into the right trunk.', { icon: 'ℹ️' });
}}
@@ -1713,6 +1785,7 @@ export default function UniverseBuilder() {
availableBackends={availableBackends}
defaultMode={defaultMode}
imageModels={imageModels}
+ availableLoras={availableLoras}
handleRender={handleRender}
rendering={rendering}
runs={runs}
@@ -2068,6 +2141,9 @@ function CategoryEditor({
// 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,
}) {
const requiresTargetKind = !TRUNK_BY_KIND[bucketKind];
const [adding, setAdding] = useState(false);
@@ -2081,11 +2157,14 @@ function CategoryEditor({
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); };
@@ -2098,6 +2177,12 @@ function CategoryEditor({
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; }, []);
@@ -2182,6 +2267,42 @@ function CategoryEditor({
<Play size={12} /> Render
</button>
)}
+ {onAssignBucketKind && requiresTargetKind && (
+ <div className="relative" ref={assignWrapRef}>
+ <button
+ onClick={() => setAssignOpen((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"
+ title="Move this bucket into a canon trunk (variations stay in place)"
+ aria-haspopup="menu"
+ aria-expanded={assignOpen}
+ >
+ <FolderTree size={12} /> Assign to…
+ </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
@@ -2889,7 +3010,7 @@ function TrunkView({
function OtherTab({
draft, buckets, activeBucket, setBucket, canRender, canPromote,
onUpdateBucket, onRemoveBucket, onGenerateInBucket, onPromoteVariation,
- onBulkRenderBucket, onRenderVariation, onAutoSort,
+ onBulkRenderBucket, onRenderVariation, onAssignBucketKind, onAutoSort,
}) {
return (
<>
@@ -2932,6 +3053,7 @@ function OtherTab({
canPromote={canPromote}
bucketKind={draft.categories?.[cat]?.kind}
onPromote={onPromoteVariation ? (v, opts) => onPromoteVariation(cat, v, opts) : null}
+ onAssignBucketKind={onAssignBucketKind ? (targetKind) => onAssignBucketKind(cat, targetKind) : null}
/>
))}
</section>
@@ -2941,74 +3063,63 @@ function OtherTab({
function RenderTab({
draft, selectedId, bucketsByKind, renderOpts, setRenderOpts,
- availableBackends, defaultMode, imageModels, handleRender, rendering, runs,
+ availableBackends, defaultMode, imageModels, availableLoras = [],
+ handleRender, rendering, runs,
}) {
- const totalSheets = draft.compositeSheets?.length || 0;
- const totalVariations = totalVariationCount(draft);
- // Mirror server-side compile skip rules — `renderPromptCount` already filters
- // canon via `canonEntryHasContent`, so the "All canon (N)" option label and
- // the actual enqueued count agree.
- const totalCanon = countCanonWithContent(draft, 'characters')
- + countCanonWithContent(draft, 'settings')
- + countCanonWithContent(draft, 'objects');
- const renderTotal = renderPromptCount(draft, renderOpts.promptMode || 'variations');
+ const currentRunnerFamily = useMemo(() => {
+ const currentModel = imageModels.find((m) => m.id === renderOpts.modelId);
+ return currentModel?.runner || RUNNER_FAMILIES.MFLUX;
+ }, [imageModels, renderOpts.modelId]);
+ // Memoize the counts that drive button labels + disable states. Drafts can
+ // be large (full canon + variations + sheets) and ImageGenSettingsForm
+ // re-renders RenderTab on every keystroke into the per-batch fields.
+ const counts = useMemo(() => {
+ // Mirror server-side compile skip rules — `renderPromptCount` already
+ // filters canon via `canonEntryHasContent`, so each trunk's counts and
+ // the "Render everything" total agree with what the server enqueues.
+ const totalSheets = draft.compositeSheets?.length || 0;
+ const totalVariations = totalVariationCount(draft);
+ const totalCanon = countCanonWithContent(draft, 'characters')
+ + countCanonWithContent(draft, 'settings')
+ + countCanonWithContent(draft, 'objects');
+ const otherBuckets = bucketsByKind?.other || [];
+ const totalOtherVariations = otherBuckets.reduce(
+ (n, k) => n + (draft.categories?.[k]?.variations?.length || 0),
+ 0,
+ );
+ return {
+ totalSheets,
+ totalVariations,
+ totalCanon,
+ otherBuckets,
+ totalOtherVariations,
+ totalEverything: totalSheets + totalVariations + totalCanon,
+ };
+ }, [draft, bucketsByKind]);
+ const { totalSheets, totalCanon, otherBuckets, totalOtherVariations, totalEverything } = counts;
+ const perPrompt = renderOpts.batchPerVariation || 1;
return (
<>
<section className="bg-port-card border border-port-border rounded p-4 flex flex-col gap-3">
- <div className="flex items-center justify-between gap-2 flex-wrap">
- <h2 className="text-sm font-semibold text-white flex items-center gap-2">
- <FolderOpen size={16} className="text-port-accent" /> Batch render
- </h2>
- {availableBackends.length > 1 && (
- <BackendChipStrip
- availableBackends={availableBackends}
- value={renderOpts.mode || defaultMode}
- onChange={(id) => setRenderOpts((r) => ({ ...r, mode: id }))}
- titlePrefix="Render via"
- />
- )}
- </div>
+ <h2 className="text-sm font-semibold text-white flex items-center gap-2">
+ <FolderOpen size={16} className="text-port-accent" /> Batch render
+ </h2>
{availableBackends.length === 0 && (
<p className="text-xs text-port-warning">
Configure a local mflux Python path or enable Codex Imagegen in Settings → Image Gen
to enable batch render.
</p>
)}
- <div className="grid grid-cols-1 sm:grid-cols-3 gap-3">
- <div>
- <label htmlFor="world-render-prompt-mode" className="block text-xs font-medium text-gray-400 mb-1">Prompt set</label>
- <select
- id="world-render-prompt-mode"
- value={renderOpts.promptMode || 'variations'}
- onChange={(e) => setRenderOpts((r) => ({ ...r, promptMode: e.target.value }))}
- className="w-full bg-port-bg border border-port-border rounded-lg px-2 py-2 text-sm text-white focus:outline-none focus:border-port-accent min-h-[40px]"
- >
- <option value="variations" disabled={totalVariations === 0}>Atomic variations ({totalVariations})</option>
- <option value="sheets" disabled={totalSheets === 0}>Composite boards ({totalSheets})</option>
- <option value="canon" disabled={totalCanon === 0}>All canon ({totalCanon})</option>
- <option value="all" disabled={totalSheets + totalVariations + totalCanon === 0}>
- Everything ({totalSheets + totalVariations + totalCanon})
- </option>
- </select>
- </div>
- </div>
- <ImageGenControls
- mode={renderOpts.mode || defaultMode || 'local'}
+ <ImageGenSettingsForm
+ value={{ ...renderOpts, mode: renderOpts.mode || defaultMode || 'local' }}
+ onChange={(next) => setRenderOpts(next)}
models={imageModels}
- modelId={renderOpts.modelId}
- onModelChange={(id) => setRenderOpts((r) => ({ ...r, modelId: id, steps: '', guidance: '' }))}
- width={renderOpts.width}
- height={renderOpts.height}
- onResolutionChange={(w, h) => setRenderOpts((r) => ({ ...r, width: w, height: h }))}
- steps={renderOpts.steps}
- onStepsChange={(v) => setRenderOpts((r) => ({ ...r, steps: v }))}
- guidance={renderOpts.guidance}
- onGuidanceChange={(v) => setRenderOpts((r) => ({ ...r, guidance: v }))}
- cfgScale={renderOpts.cfgScale}
- onCfgScaleChange={(v) => setRenderOpts((r) => ({ ...r, cfgScale: v }))}
- quantize={renderOpts.quantize}
- onQuantizeChange={(v) => setRenderOpts((r) => ({ ...r, quantize: v }))}
+ availableBackends={availableBackends}
+ showLoras
+ availableLoras={availableLoras}
+ currentRunnerFamily={currentRunnerFamily}
+ showStylePreset
/>
<div className="grid grid-cols-2 sm:grid-cols-3 gap-3">
<div>
@@ -3027,13 +3138,23 @@ function RenderTab({
</div>
<div className="flex items-center gap-2 flex-wrap">
<button
- onClick={() => handleRender()}
- disabled={rendering || !selectedId || renderTotal === 0 || availableBackends.length === 0}
+ onClick={() => handleRender({
+ promptMode: 'all',
+ // Both `scopedPromptCount` (client) and `compilePrompts` (server)
+ // skip canon entirely when `canonSelection` is omitted. The button
+ // label promises "everything", so we must explicitly select every
+ // canon trunk — derived from TRUNK_TABS so the set stays in sync
+ // when a new trunk is added.
+ canonSelection: Object.fromEntries(TRUNK_TABS.map((t) => [t.kind, 'all'])),
+ })}
+ disabled={rendering || !selectedId || totalEverything === 0 || availableBackends.length === 0}
className="px-4 py-2 bg-port-accent hover:bg-port-accent/90 disabled:opacity-50 text-white rounded flex items-center gap-2 min-h-[40px]"
+ title="Render every canon entry + every variation + every composite board with these knobs"
>
{rendering ? <Loader2 size={16} className="animate-spin" /> : <Sparkles size={16} />}
- Render {renderTotal * (renderOpts.batchPerVariation || 1)} image{renderTotal * (renderOpts.batchPerVariation || 1) === 1 ? '' : 's'}
+ Render everything ({totalEverything * perPrompt} image{totalEverything * perPrompt === 1 ? '' : 's'})
</button>
+ <span className="text-[11px] text-gray-500">…or pick a narrower scope below.</span>
</div>
{!selectedId && <p className="text-xs text-gray-500">Save the world first to enable rendering.</p>}
</section>
@@ -3103,6 +3224,49 @@ function RenderTab({
</div>
);
})}
+ {otherBuckets.length > 0 && totalOtherVariations > 0 ? (
+ <div className="border border-port-border rounded p-2 bg-port-bg flex flex-col gap-1.5">
+ <div className="flex items-center justify-between gap-2 flex-wrap">
+ <div className="flex items-center gap-2 text-sm text-gray-200">
+ <FolderTree size={14} className="text-port-accent" />
+ <span className="font-medium">Other</span>
+ <span className="text-[11px] text-gray-500">
+ {otherBuckets.length} bucket{otherBuckets.length === 1 ? '' : 's'}
+ {' · '}{totalOtherVariations} variation{totalOtherVariations === 1 ? '' : 's'}
+ </span>
+ </div>
+ <button
+ type="button"
+ onClick={() => handleRender({
+ promptMode: 'variations',
+ selection: Object.fromEntries(otherBuckets.map((b) => [b, 'all'])),
+ })}
+ disabled={!selectedId || availableBackends.length === 0 || rendering}
+ className="text-xs px-2 py-1 bg-port-accent/15 hover:bg-port-accent/25 disabled:opacity-30 disabled:cursor-not-allowed text-port-accent rounded min-h-[32px]"
+ title="Render every variation in every Other bucket"
+ >
+ Bulk-render all ({totalOtherVariations})
+ </button>
+ </div>
+ <div className="flex flex-wrap items-center gap-1 pl-5">
+ {otherBuckets.map((bucket) => {
+ const count = draft.categories?.[bucket]?.variations?.length || 0;
+ return (
+ <button
+ key={bucket}
+ type="button"
+ onClick={() => handleRender({ promptMode: 'variations', selection: { [bucket]: 'all' } })}
+ disabled={count === 0 || !selectedId || availableBackends.length === 0 || rendering}
+ className="text-[11px] px-1.5 py-0.5 bg-port-card border border-port-border hover:border-port-accent disabled:opacity-30 disabled:cursor-not-allowed text-gray-300 rounded"
+ title={count === 0 ? 'No variations yet' : `Bulk-render ${humanizeCategory(bucket)} (${count})`}
+ >
+ {humanizeCategory(bucket)} ({count})
+ </button>
+ );
+ })}
+ </div>
+ </div>
+ ) : null}
{totalCanon > 0 ? (
<div className="border border-port-border rounded p-2 bg-port-bg flex items-center justify-between gap-2">
<span className="text-sm text-gray-200 flex items-center gap-2">
@@ -3116,11 +3280,7 @@ function RenderTab({
type="button"
onClick={() => handleRender({
promptMode: 'canon',
- canonSelection: {
- characters: 'all',
- settings: 'all',
- objects: 'all',
- },
+ canonSelection: Object.fromEntries(TRUNK_TABS.map((t) => [t.kind, 'all'])),
})}
disabled={!selectedId || availableBackends.length === 0 || rendering}
className="text-xs px-2 py-1 bg-port-accent/15 hover:bg-port-accent/25 disabled:opacity-30 disabled:cursor-not-allowed text-port-accent rounded min-h-[32px]"
diff --git a/client/src/services/apiUniverseBuilder.js b/client/src/services/apiUniverseBuilder.js
index 84deb79098..ca01956cdf 100644
--- a/client/src/services/apiUniverseBuilder.js
+++ b/client/src/services/apiUniverseBuilder.js
@@ -22,9 +22,10 @@ export const createUniverse = (data) => request('/universe-builder', {
body: JSON.stringify(data),
});
-export const updateUniverse = (id, patch) => request(`/universe-builder/${encodeURIComponent(id)}`, {
+export const updateUniverse = (id, patch, options = {}) => request(`/universe-builder/${encodeURIComponent(id)}`, {
method: 'PATCH',
body: JSON.stringify(patch),
+ ...options,
});
export const deleteUniverse = (id) => request(`/universe-builder/${encodeURIComponent(id)}`, {
diff --git a/server/lib/navManifest.js b/server/lib/navManifest.js
index 386f98864b..caa189cfff 100644
--- a/server/lib/navManifest.js
+++ b/server/lib/navManifest.js
@@ -18,7 +18,7 @@ export const NAV_COMMANDS = [
{ id: 'nav.media.creative-director', path: '/media/creative-director', label: 'Creative Director', section: 'Create', aliases: ['creative-director', 'creative', 'director', 'long-form', 'episode'], keywords: ['story', 'episode', 'narrative', 'agent', 'auto-video', 'long-form'] },
{ id: 'nav.media.timeline', path: '/media/timeline', label: 'Timeline', section: 'Create', aliases: ['timeline', 'video-timeline', 'editor'], keywords: ['edit', 'trim', 'composite', 'stitch', 'cut', 'compose'] },
{ id: 'nav.media.models', path: '/media/models', label: 'Media Models', section: 'Create', aliases: ['media-models', 'image-models', 'video-models', 'huggingface'], keywords: ['hf cache', 'model storage', 'disk'] },
- { id: 'nav.create.universe-builder', path: '/universe-builder', label: 'Universe Builder', section: 'Create', aliases: ['universe-builder', 'worldbuilder', 'worldbuild', 'world', 'universe', 'lore', 'universe-canon', 'canon'], keywords: ['style template', 'sci-fi', 'fantasy', 'concept art', 'batch render', 'variations', 'characters', 'settings', 'objects', 'canon entries'] },
+ { id: 'nav.create.universe-builder', path: '/universe-builder', label: 'Universe', section: 'Create', aliases: ['universe', 'universe-builder', 'worldbuilder', 'worldbuild', 'world', 'lore', 'universe-canon', 'canon'], keywords: ['style template', 'sci-fi', 'fantasy', 'concept art', 'batch render', 'variations', 'characters', 'settings', 'objects', 'canon entries'] },
{ id: 'nav.create.importer', path: '/importer', label: 'Importer', section: 'Create', aliases: ['importer', 'import'], keywords: ['paste', 'screenplay', 'novel', 'short story', 'comic script', 'analyze', 'reverse-engineer', 'extract'] },
{ id: 'nav.create.pipeline', path: '/pipeline', label: 'Series Pipeline', section: 'Create', aliases: ['series', 'pipeline', 'production', 'series-pipeline', 'production-pipeline'], keywords: ['series', 'issue', 'episode', 'comic', 'script', 'prose', 'storyboard', 'narrative', 'workflow'] },
{ id: 'nav.create.sharing', path: '/sharing', label: 'Sharing', section: 'Create', aliases: ['sharing', 'share', 'buckets', 'share-buckets'], keywords: ['google drive', 'dropbox', 'icloud', 'syncthing', 'export', 'import', 'collaborate', 'federation', 'peer', 'cross-network'] },
diff --git a/server/lib/writersRoomStylePresets.js b/server/lib/writersRoomStylePresets.js
index a248477345..aeeb31982b 100644
--- a/server/lib/writersRoomStylePresets.js
+++ b/server/lib/writersRoomStylePresets.js
@@ -347,6 +347,14 @@ export const STYLE_PRESETS = [
export const STYLE_PRESET_IDS = STYLE_PRESETS.map((p) => p.id);
+// id → preset map for O(1) lookups; callers that hand-roll
+// STYLE_PRESETS.find(p => p.id === id) should use this instead.
+const STYLE_PRESET_BY_ID = new Map(STYLE_PRESETS.map((p) => [p.id, p]));
+export function getStylePresetById(id) {
+ if (!id || typeof id !== 'string') return null;
+ return STYLE_PRESET_BY_ID.get(id) || null;
+}
+
// 'custom' = user wrote their own prompt without picking a preset.
// 'none' = no style applied (image-gen uses scene visualPrompt verbatim).
export const STYLE_ID = { NONE: 'none', CUSTOM: 'custom' };
diff --git a/server/routes/universeBuilder.js b/server/routes/universeBuilder.js
index 502991b4b8..ec7eb24b10 100644
--- a/server/routes/universeBuilder.js
+++ b/server/routes/universeBuilder.js
@@ -28,6 +28,7 @@ import { getSettings } from '../services/settings.js';
import { findOrCreateUniverseCollection } from '../services/mediaCollections.js';
import { registerUniverseBuilderRun } from '../services/universeBuilderCollectionHook.js';
import { getImageModels, isFlux2, isZImage, isErnie } from '../lib/mediaModels.js';
+import { getStylePresetById } from '../lib/writersRoomStylePresets.js';
const router = Router();
@@ -289,6 +290,24 @@ const renderSchema = z.object({
selection: selectionSchema.optional(),
sheetSelection: z.union([z.literal('all'), z.array(z.string().trim().min(1).max(svc.VARIATION_LABEL_MAX)).max(svc.COMPOSITE_SHEETS_MAX)]).optional(),
canonSelection: canonSelectionSchema.optional(),
+ // Per-batch overrides surfaced through the full Image-Gen form. All optional;
+ // empty values are treated as "use the universe's existing influences."
+ // `seed` matches /api/image-gen/generate's contract (non-negative integer) —
+ // local image gen coerces via Number(seed) and would yield NaN for arbitrary
+ // strings, so reject early at the boundary.
+ seed: z.number().int().min(0).optional(),
+ negativePrompt: z.string().trim().max(svc.PROMPT_FRAGMENT_MAX).optional(),
+ extraStyle: z.string().trim().max(svc.PROMPT_FRAGMENT_MAX).optional(),
+ stylePresetId: z.string().trim().max(80).optional(),
+ // Matches /api/image-gen/generate's LoRA contract: basenames only (server
+ // resolves against PATHS.loras), max 8 stacked LoRAs per render. Keeping
+ // the two routes in sync so a payload that's accepted here can also flow
+ // through /api/image-gen/generate if we ever proxy it.
+ loras: z.array(z.object({
+ filename: z.string().trim().min(1).max(256).regex(/^[^/\\]+$/, 'lora filename must not contain path separators'),
+ scale: z.number().min(0).max(2),
+ name: z.string().trim().max(256).optional(),
+ })).max(8).optional(),
}).refine((body) => body.collectionName === undefined, {
message: 'collectionName is no longer supported — the linked collection follows the universe name automatically. Remove this field.',
path: ['collectionName'],
@@ -349,12 +368,22 @@ router.post('/:id/render', asyncHandler(async (req, res) => {
const body = validateRequest(renderSchema, req.body ?? {});
const universe = await svc.getUniverse(req.params.id).catch((err) => { throw mapServiceError(err); });
+ // Resolve a style preset (server-side authoritative list) so the embrace
+ // tokens are deterministic for this render even if the client sent a stale
+ // preset object. Unknown ids are ignored (server is the source of truth).
+ const stylePreset = getStylePresetById(body.stylePresetId);
+ // `negativePrompt` is the schema field; `extraNegative` is compilePrompts'
+ // option name (avoids shadowing `negativePrompt` on each compiled item).
const compiled = svc.compilePrompts(universe, {
promptMode: body.promptMode,
selection: body.selection,
sheetSelection: body.sheetSelection,
canonSelection: body.canonSelection,
batchPerVariation: body.batchPerVariation,
+ extraStyle: body.extraStyle,
+ extraNegative: body.negativePrompt,
+ stylePresetPrompt: stylePreset?.prompt,
+ stylePresetNegative: stylePreset?.negativePrompt,
});
if (!compiled.length) {
throw new ServerError('No prompts to render — add canon entries, variations, or composite sheets first', {
@@ -421,6 +450,15 @@ router.post('/:id/render', asyncHandler(async (req, res) => {
// dispatcher), so without this mapping the Universe Builder UI's CFG control
// would silently no-op for local renders.
const guidance = body.guidance ?? body.cfgScale;
+ // Local image gen reads `loraFilenames` (basenames) + `loraScales` (parallel
+ // array of numbers), not the `[{filename, scale}]` UI shape. Convert here so
+ // every enqueued job actually applies the user's LoRA selection.
+ const loraFilenames = Array.isArray(body.loras) && body.loras.length
+ ? body.loras.map((l) => l.filename)
+ : undefined;
+ const loraScales = Array.isArray(body.loras) && body.loras.length
+ ? body.loras.map((l) => l.scale)
+ : undefined;
const baseParams = {
width: body.width,
height: body.height,
@@ -428,6 +466,9 @@ router.post('/:id/render', asyncHandler(async (req, res) => {
cfgScale: body.cfgScale,
guidance,
quantize: body.quantize,
+ seed: body.seed,
+ loraFilenames,
+ loraScales,
};
for (const item of compiled) {
diff --git a/server/routes/universeBuilder.test.js b/server/routes/universeBuilder.test.js
index a04d1c5736..313a0f0410 100644
--- a/server/routes/universeBuilder.test.js
+++ b/server/routes/universeBuilder.test.js
@@ -2,6 +2,7 @@ import { describe, it, expect, vi, beforeEach } from 'vitest';
import express from 'express';
import { request } from '../lib/testHelper.js';
import { errorMiddleware } from '../lib/errorHandler.js';
+import { enqueueJob } from '../services/mediaJobQueue/index.js';
const fileStore = new Map();
@@ -455,6 +456,71 @@ describe('universe-builder routes', () => {
expect(JSON.stringify(res.body)).toMatch(/collectionName/i);
});
+ it('POST /:id/render forwards seed + LoRAs in the wire format local image gen reads', async () => {
+ vi.mocked(enqueueJob).mockClear();
+ const app = buildApp();
+ const created = await request(app).post('/api/universe-builder').send({
+ name: 'Override Universe',
+ categories: {
+ landscapes: { variations: [{ label: 'A', prompt: 'a' }] },
+ },
+ });
+ const res = await request(app)
+ .post(`/api/universe-builder/${created.body.id}/render`)
+ .send({
+ mode: 'local',
+ seed: 42,
+ negativePrompt: 'low quality',
+ extraStyle: 'high contrast',
+ loras: [
+ { filename: 'foo.safetensors', name: 'Foo', scale: 0.8 },
+ { filename: 'bar.safetensors', name: 'Bar', scale: 1.2 },
+ ],
+ });
+ expect(res.status).toBe(200);
+ expect(res.body.promptCount).toBe(1);
+ // Verify the enqueued job carries the local-runner wire shape
+ // (loraFilenames + loraScales as parallel arrays), not the UI's
+ // [{filename, scale}] objects which the runner would silently ignore.
+ expect(vi.mocked(enqueueJob)).toHaveBeenCalledTimes(1);
+ const enqueuedParams = vi.mocked(enqueueJob).mock.calls[0][0].params;
+ expect(enqueuedParams.seed).toBe(42);
+ expect(enqueuedParams.loraFilenames).toEqual(['foo.safetensors', 'bar.safetensors']);
+ expect(enqueuedParams.loraScales).toEqual([0.8, 1.2]);
+ expect(enqueuedParams.loras).toBeUndefined();
+ });
+
+ it('POST /:id/render rejects non-numeric seed (local image gen would NaN)', async () => {
+ const app = buildApp();
+ const created = await request(app).post('/api/universe-builder').send({
+ name: 'Bad Seed Universe',
+ categories: {
+ landscapes: { variations: [{ label: 'A', prompt: 'a' }] },
+ },
+ });
+ const res = await request(app)
+ .post(`/api/universe-builder/${created.body.id}/render`)
+ .send({ mode: 'local', seed: 'abc123' });
+ expect(res.status).toBe(400);
+ });
+
+ it('POST /:id/render rejects lora filename with path separators (basenames only)', async () => {
+ const app = buildApp();
+ const created = await request(app).post('/api/universe-builder').send({
+ name: 'Bad LoRA Universe',
+ categories: {
+ landscapes: { variations: [{ label: 'A', prompt: 'a' }] },
+ },
+ });
+ const res = await request(app)
+ .post(`/api/universe-builder/${created.body.id}/render`)
+ .send({
+ mode: 'local',
+ loras: [{ filename: '../escape.safetensors', scale: 1.0 }],
+ });
+ expect(res.status).toBe(400);
+ });
+
it('POST /:id/render rejects when no variations exist', async () => {
const app = buildApp();
const created = await request(app).post('/api/universe-builder').send({ name: 'Empty' });
diff --git a/server/services/universeBuilder.js b/server/services/universeBuilder.js
index 5b4c618f56..5f6c2362e5 100644
--- a/server/services/universeBuilder.js
+++ b/server/services/universeBuilder.js
@@ -995,9 +995,21 @@ export function compilePrompts(universe, options = {}) {
}
const batchPerVariation = Math.max(1, Math.min(20, Number(options.batchPerVariation) || 1));
+ // The universe's stored influences are the baseline; per-batch overrides
+ // append on top so the user can layer an extra-style chip, a style preset,
+ // or an extra negative without editing the persistent influences. Token
+ // lists are comma-joined to match composeStyledPrompt's input expectation.
+ const baselineEmbrace = joinInfluenceList(universe.influences?.embrace);
+ const baselineAvoid = joinInfluenceList(universe.influences?.avoid);
+ const embraceParts = [baselineEmbrace, options.stylePresetPrompt, options.extraStyle]
+ .map((s) => (typeof s === 'string' ? s.trim() : ''))
+ .filter(Boolean);
+ const avoidParts = [baselineAvoid, options.stylePresetNegative, options.extraNegative]
+ .map((s) => (typeof s === 'string' ? s.trim() : ''))
+ .filter(Boolean);
const stylePreset = {
- prompt: joinInfluenceList(universe.influences?.embrace),
- negativePrompt: joinInfluenceList(universe.influences?.avoid),
+ prompt: embraceParts.join(', '),
+ negativePrompt: avoidParts.join(', '),
};
const compiled = [];
diff --git a/server/services/universeBuilder.test.js b/server/services/universeBuilder.test.js
index 28a78b7fe3..76a59753d3 100644
--- a/server/services/universeBuilder.test.js
+++ b/server/services/universeBuilder.test.js
@@ -411,6 +411,40 @@ describe("universeBuilder service", () => {
expect(compiled[0].label).toBe("Wake Jackals");
});
+ it("layers per-batch overrides on top of universe influences", async () => {
+ const w = await seedWorld();
+ const compiled = svc.compilePrompts(w, {
+ selection: { landscapes: ["crystal canyon"] },
+ extraStyle: "high contrast",
+ extraNegative: "low quality",
+ stylePresetPrompt: "noir cinematography",
+ stylePresetNegative: "color photo",
+ });
+ expect(compiled).toHaveLength(1);
+ // Baseline + preset + extra are comma-joined into the stylePreset prefix
+ // and composeStyledPrompt sticks ". " between style and variation.
+ expect(compiled[0].prompt).toBe(
+ "moebius linework, scavengers reign palette, noir cinematography, high contrast. crystalline canyon, alien sun",
+ );
+ // Negative parts are comma-joined; composeStyledPrompt also adds a comma
+ // when the user negative is non-empty, but here userNegative is empty so
+ // we just see baseline + preset + extra.
+ expect(compiled[0].negativePrompt).toBe(
+ "blurry, lowres, color photo, low quality",
+ );
+ });
+
+ it("override fields default to baseline influences when omitted", async () => {
+ const w = await seedWorld();
+ const compiled = svc.compilePrompts(w, {
+ selection: { landscapes: ["crystal canyon"] },
+ });
+ expect(compiled[0].prompt).toBe(
+ "moebius linework, scavengers reign palette. crystalline canyon, alien sun",
+ );
+ expect(compiled[0].negativePrompt).toBe("blurry, lowres");
+ });
+
it("clamps batchPerVariation to 1..20", async () => {
const w = await seedWorld();
// 0 → 1