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

feat(world-builder): per-list influence locks, drag-reorder chips, current-state-aware expand, collapsible sidebar

[._.]/ Adam Eivyb39e2cf12339
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index d618eb0510..642fef8926 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -13,6 +13,10 @@ In-tree `portos-ai-toolkit`, auto-migration of legacy codex provider configs, an
- **World Builder — per-item locks on variations + composite boards.** Each variation row in `CategoryEditor` and each board in `CompositeSheetsEditor` now has a Lock/Unlock icon. On re-expand, the client extracts locked items, sends them to the server as `preservedVariations` / `preservedCompositeSheets` so the LLM is told not to regenerate those labels, then merges locked-first + LLM additions with case-insensitive label dedupe per category. Locked rows render with an accent-colored border.
- **World Builder — deep routing.** The selected world id now lives in the URL: `/media/world-builder/:worldId` and `/world-builder/:worldId`. Back/forward buttons, refresh, and direct deep-links all work. Sidebar selection, post-create, and post-delete navigations go through `useNavigate`.
- **World Builder — bible context in refine.** The Refine modal now sends `logline`, `premise`, `styleNotes`, and `influences` to the LLM alongside the existing prompts; the LLM rewrites all seven fields together so the bible stays narratively coherent with the prompts. Locked fields are excluded from the rewrite client- and server-side.
+- **World Builder — current world state passed to expand.** Generate From Idea now sends the full bible/prompt state plus the lock map to the expander; locked fields get a `[LOCKED]` tag in the prompt and the LLM is told to echo them unchanged so its regenerated premise/styleNotes/etc. stay consistent with a pinned logline (etc.) instead of being written in isolation.
+- **World Builder — independent locks for embrace + avoid influences.** The single influences lock split into `influencesEmbrace` and `influencesAvoid`. Each list has its own lock toggle in the UI; the embrace and avoid lines in the LLM prompt get `[LOCKED]` flags independently. Legacy `locked.influences: true` is migrated to both per-list locks on read (no data migration step needed).
+- **World Builder — drag-to-reorder for influence chips.** Embrace and avoid chips now reorder via `@dnd-kit` (`rectSortingStrategy` since chips wrap). Each chip has a `GripVertical` handle; the renderer prepends them in the new order to `stylePrompt`/`negativePrompt`. 8px activation distance keeps the X remove button and the trailing input click-safe; keyboard sensor enables space-to-grab + arrow-key reordering.
+- **World Builder — collapsible Worlds sidebar with deep routing + tight layout.** The Worlds list now collapses to a 32px rail via a localStorage-backed toggle (persists across visits). The page is full-width (no outer page padding) and the sidebar uses `border-r` + tinted bg matching the WritersRoom layout convention. Selected world id lives in the URL (`/world-builder/:worldId` and `/media/world-builder/:worldId`).
## Changed
diff --git a/PLAN.md b/PLAN.md
index 588e3dbbb0..f9f304b7f5 100644
--- a/PLAN.md
+++ b/PLAN.md
@@ -53,6 +53,7 @@ The dgrauet/ltx-2-mlx runtime ships with FFLF (true keyframe interpolation), aud
- [ ] **Server-side bulk endpoint for collection items** — `MediaCollectionDetail`'s bulk Move/Copy/Remove currently makes N sequential HTTP calls (server has no per-collection lock, so parallel writes would lose updates on the JSON read-modify-write). At ~30ms localhost RTT, 20 items ≈ 600ms; 50 items ≈ 1.5s (move = 2 × that). The user's stated use case is "select all" on a world-builder collection that could legitimately have 50+ items. Add `POST /api/media/collections/:id/items/bulk` taking `{ add: [{kind,ref}], remove: [key] }` and doing one read-modify-write per collection. Halves wall-clock for Move (single source-side commit instead of N), dodges the race window entirely. Surfaced from the bulk-actions /simplify pass.
- [ ] **Drop legacy `description` fallback in `sanitizeCharacter`** — `server/lib/storyBible.js:130` carries an inline `TODO(item-4): drop the description fallback once pipeline characters extract natively.` Item 4 (shared bible-extraction service) shipped 2026-05-10 — extraction now writes the canonical `physicalDescription` field directly. Plan: write a one-shot migration that rewrites every `series.characters[].description` → `physicalDescription` in `data/pipeline-series.json` (idempotent: skip entries that already have `physicalDescription`), drop the `|| raw.description` fallback at `storyBible.js:137`, and remove the TODO comment. Audit `data.sample/` + tests for any remaining `description` reads before merging.
- [ ] **Migrate `worldBuilderRefine.runRefine` onto `runPromptThroughProvider`** — `server/services/worldBuilderRefine.js:131-162` still hand-rolls the createRun → branch-on-type → executeApiRun/executeCliRun → accumulate-text → reject-on-error pattern that the parent unification (PR #221) collapsed for the other four LLM-runner sites. The effective-model resolution was unified in this PR, but the full runner-wrapper migration was deferred to keep scope tight. Replace the inline `runRefine` with a single `runPromptThroughProvider({ provider, model, prompt, source: 'world-builder-refine' })` call (mirroring `worldBuilderExpand.js`). Drop the local `createRun`/`executeApiRun`/`executeCliRun` imports. ~30 LOC dedup. Surfaced from /do:review on the resolveEffectiveModel PR.
+- [ ] **Extract `usePersistedState` hook for the localStorage-backed boolean pattern.** The same `useState(() => localStorage.getItem(KEY) === '1')` + setter-with-persist pattern is now duplicated across at least 6 sites: `client/src/pages/WorldBuilder.jsx:243-252` (`worldBuilder.worldsCollapsed`), `client/src/pages/WritersRoom.jsx:25-34` (`wr.libraryCollapsed`), `client/src/pages/ChiefOfStaff.jsx:65-93`, `client/src/pages/Instances.jsx:84-95`, `client/src/pages/PipelineSeries.jsx:39-68`, and Layout.jsx's collapse toggles. Extract `client/src/hooks/usePersistedState.js` exposing `useLocalStorageBool(key, defaultValue)` returning `[value, toggle]` (and a sibling `useLocalStorageState(key, default, serialize)` for the JSON-blob variant CalendarTab uses). Migrate all sites. ~50 LOC dedup + future consistency. Surfaced from /simplify pass on the WorldBuilder collapse work.
### Civitai LoRA / Z-Image-Turbo follow-ups (from /simplify pass)
diff --git a/client/src/components/Layout.jsx b/client/src/components/Layout.jsx
index 420117cb94..2d28029047 100644
--- a/client/src/components/Layout.jsx
+++ b/client/src/components/Layout.jsx
@@ -984,6 +984,7 @@ export default function Layout() {
location.pathname === '/review' ||
location.pathname.startsWith('/settings') ||
location.pathname.startsWith('/wiki') ||
+ location.pathname.startsWith('/world-builder') ||
location.pathname.startsWith('/writers-room') ||
location.pathname.startsWith('/agents') ||
location.pathname === '/shell' ||
diff --git a/client/src/components/worldBuilder/InfluenceChipsInput.jsx b/client/src/components/worldBuilder/InfluenceChipsInput.jsx
index 7c08172caf..68470ba6c3 100644
--- a/client/src/components/worldBuilder/InfluenceChipsInput.jsx
+++ b/client/src/components/worldBuilder/InfluenceChipsInput.jsx
@@ -1,5 +1,21 @@
import { useState } from 'react';
-import { X } from 'lucide-react';
+import { X, GripVertical } from 'lucide-react';
+import {
+ DndContext,
+ KeyboardSensor,
+ PointerSensor,
+ closestCenter,
+ useSensor,
+ useSensors,
+} from '@dnd-kit/core';
+import {
+ SortableContext,
+ arrayMove,
+ rectSortingStrategy,
+ sortableKeyboardCoordinates,
+ useSortable,
+} from '@dnd-kit/sortable';
+import { CSS } from '@dnd-kit/utilities';
import { WORLD_INFLUENCE_ENTRY_MAX, WORLD_INFLUENCES_PER_LIST_MAX } from '../../services/api';
const TONE_CLASS = {
@@ -12,10 +28,14 @@ const TONE_CLASS = {
* Chip input for an influence list (embrace or avoid). Used by both the
* inline World Builder editor and the Refine modal — extracting one
* implementation keeps Enter/comma/paste/Backspace behavior, dedupe rules,
- * and per-entry caps in lockstep across both surfaces.
+ * per-entry caps, and drag-to-reorder in lockstep across both surfaces.
+ *
+ * Order is meaningful: the renderer prepends embrace + avoid to
+ * stylePrompt/negativePrompt verbatim, so dragging a chip toward the front
+ * gives it priority in the rendered prompt.
*
* `readOnly` collapses the editor to a plain chip preview (no input, no X
- * buttons) so locked influences render with the same chrome.
+ * buttons, no drag handles) so locked influences render with the same chrome.
*/
export default function InfluenceChipsInput({
tokens,
@@ -29,6 +49,15 @@ export default function InfluenceChipsInput({
const safe = Array.isArray(tokens) ? tokens : [];
const toneClass = TONE_CLASS[tone] || TONE_CLASS.accent;
+ // 8px activation distance keeps single clicks on the X button (remove) and
+ // the trailing input from accidentally triggering a drag — drag has to be
+ // a deliberate gesture. Keyboard sensor enables accessible reordering via
+ // space/enter to grab + arrow keys.
+ const sensors = useSensors(
+ useSensor(PointerSensor, { activationConstraint: { distance: 8 } }),
+ useSensor(KeyboardSensor, { coordinateGetter: sortableKeyboardCoordinates }),
+ );
+
if (readOnly && safe.length === 0) {
return <div className="text-[11px] text-gray-600">{emptyLabel}</div>;
}
@@ -55,27 +84,48 @@ export default function InfluenceChipsInput({
const removeAt = (idx) => onChange(safe.filter((_, i) => i !== idx));
+ const handleDragEnd = (event) => {
+ const { active, over } = event;
+ if (!over || active.id === over.id) return;
+ const oldIdx = safe.findIndex((t) => t === active.id);
+ const newIdx = safe.findIndex((t) => t === over.id);
+ if (oldIdx === -1 || newIdx === -1) return;
+ onChange(arrayMove(safe, oldIdx, newIdx));
+ };
+
+ const containerCls = `flex flex-wrap items-center gap-1.5 p-2 bg-port-bg border border-port-border rounded ${readOnly ? 'opacity-70' : ''}`;
+
+ // Read-only path: no DnD wrapper, no input, no remove buttons — just chips.
+ if (readOnly) {
+ return (
+ <div className={containerCls}>
+ {safe.map((v, idx) => (
+ <span
+ key={`${v}-${idx}`}
+ className={`inline-flex items-center gap-1 px-2 py-0.5 text-xs rounded-full border ${toneClass}`}
+ >
+ {v}
+ </span>
+ ))}
+ </div>
+ );
+ }
+
return (
- <div className={`flex flex-wrap items-center gap-1.5 p-2 bg-port-bg border border-port-border rounded ${readOnly ? 'opacity-70' : ''}`}>
- {safe.map((v, idx) => (
- <span
- key={`${v}-${idx}`}
- className={`inline-flex items-center gap-1 px-2 py-0.5 text-xs rounded-full border ${toneClass}`}
- >
- {v}
- {!readOnly && (
- <button
- type="button"
- onClick={() => removeAt(idx)}
- className="text-current/70 hover:text-current"
- aria-label={`Remove ${v}`}
- >
- <X size={11} />
- </button>
- )}
- </span>
- ))}
- {!readOnly && safe.length < WORLD_INFLUENCES_PER_LIST_MAX && (
+ <div className={containerCls}>
+ <DndContext sensors={sensors} collisionDetection={closestCenter} onDragEnd={handleDragEnd}>
+ <SortableContext items={safe} strategy={rectSortingStrategy}>
+ {safe.map((v, idx) => (
+ <SortableChip
+ key={v}
+ token={v}
+ toneClass={toneClass}
+ onRemove={() => removeAt(idx)}
+ />
+ ))}
+ </SortableContext>
+ </DndContext>
+ {safe.length < WORLD_INFLUENCES_PER_LIST_MAX && (
<input
type="text"
value={input}
@@ -101,9 +151,47 @@ export default function InfluenceChipsInput({
className="flex-1 min-w-[120px] bg-transparent text-sm text-white placeholder-gray-500 focus:outline-none"
/>
)}
- {!readOnly && safe.length >= WORLD_INFLUENCES_PER_LIST_MAX && (
+ {safe.length >= WORLD_INFLUENCES_PER_LIST_MAX && (
<span className="text-[11px] text-gray-500">Max {WORLD_INFLUENCES_PER_LIST_MAX} reached</span>
)}
</div>
);
}
+
+function SortableChip({ token, toneClass, onRemove }) {
+ const { attributes, listeners, setNodeRef, transform, transition, isDragging } = useSortable({ id: token });
+ const style = {
+ transform: CSS.Transform.toString(transform),
+ transition,
+ opacity: isDragging ? 0.5 : 1,
+ zIndex: isDragging ? 10 : 'auto',
+ };
+ return (
+ <span
+ ref={setNodeRef}
+ style={style}
+ className={`inline-flex items-center gap-1 pl-1 pr-2 py-0.5 text-xs rounded-full border ${toneClass} ${isDragging ? 'cursor-grabbing' : ''}`}
+ >
+ <button
+ type="button"
+ {...attributes}
+ {...listeners}
+ className="cursor-grab active:cursor-grabbing text-current/60 hover:text-current focus:outline-none"
+ aria-label={`Drag ${token} to reorder`}
+ title="Drag to reorder"
+ >
+ <GripVertical size={11} />
+ </button>
+ {token}
+ <button
+ type="button"
+ onClick={onRemove}
+ onPointerDown={(e) => e.stopPropagation()}
+ className="text-current/70 hover:text-current"
+ aria-label={`Remove ${token}`}
+ >
+ <X size={11} />
+ </button>
+ </span>
+ );
+}
diff --git a/client/src/components/worldBuilder/WorldPromptRefineModal.jsx b/client/src/components/worldBuilder/WorldPromptRefineModal.jsx
index aa12d9f5f3..135fd29016 100644
--- a/client/src/components/worldBuilder/WorldPromptRefineModal.jsx
+++ b/client/src/components/worldBuilder/WorldPromptRefineModal.jsx
@@ -1,9 +1,11 @@
-import { useEffect, useState } from 'react';
+import { useEffect, useMemo, useState } from 'react';
import { Check, Lock, Sparkles, Wand2, X } from 'lucide-react';
import ProviderModelSelector from '../ProviderModelSelector';
import toast from '../ui/Toast';
import useProviderModels from '../../hooks/useProviderModels';
-import { refineWorldPrompts, WORLD_LOCKABLE_FIELDS, ensureInfluences } from '../../services/api';
+import {
+ refineWorldPrompts, WORLD_LOCKABLE_FIELDS, ensureInfluences, isInfluenceLockField,
+} from '../../services/api';
import InfluenceChipsInput from './InfluenceChipsInput';
/**
@@ -24,13 +26,10 @@ const FIELD_LABELS = {
logline: 'Logline',
premise: 'Premise',
styleNotes: 'Style notes',
- influences: 'Influences',
};
-// Single-line fields render as text inputs; multi-line as textareas with
-// per-field row counts so the modal scales sensibly without scroll-traps.
-// `influences` is handled by a dedicated chips renderer, not the textarea
-// path, so it has no row count entry.
+// Multi-line fields use a textarea with per-field row counts (logline gets a
+// single-line input via rows=0). Influences uses its own chip renderer.
const FIELD_ROWS = {
starterPrompt: 4,
stylePrompt: 4,
@@ -70,10 +69,13 @@ export default function WorldPromptRefineModal({
loading: providersLoading,
} = useProviderModels();
- const originals = {
+ // Memoized so child components receive a stable ref across renders. Without
+ // this, every keystroke in the feedback box rebuilt `originals.influences`
+ // and forced ReadOnlyInfluences / RefinedInfluences to re-render unnecessarily.
+ const originals = useMemo(() => ({
starterPrompt, stylePrompt, negativePrompt, logline, premise, styleNotes,
influences: ensureInfluences(influences),
- };
+ }), [starterPrompt, stylePrompt, negativePrompt, logline, premise, styleNotes, influences]);
const [feedback, setFeedback] = useState('');
const [refined, setRefined] = useState({});
@@ -127,9 +129,10 @@ export default function WorldPromptRefineModal({
if (!result) return;
const next = {};
for (const key of WORLD_LOCKABLE_FIELDS) {
- if (key === 'influences') next[key] = ensureInfluences(result[key]);
- else next[key] = result[key] ?? '';
+ if (isInfluenceLockField(key)) continue;
+ next[key] = result[key] ?? '';
}
+ next.influences = ensureInfluences(result.influences);
setRefined(next);
setRationale(result.rationale || '');
setChanges(Array.isArray(result.changes) ? result.changes : []);
@@ -141,13 +144,20 @@ export default function WorldPromptRefineModal({
if (!canApply) return;
// Only emit unlocked fields — the server already enforces this, but
// belt-and-suspenders prevents a stale lock-toggle race from clobbering
- // a pinned value.
+ // a pinned value. Influences uses per-list locks: build the new object
+ // by picking originals for locked lists and refined for unlocked.
const patch = {};
for (const key of WORLD_LOCKABLE_FIELDS) {
+ if (isInfluenceLockField(key)) continue;
if (locked[key]) continue;
- if (key === 'influences') patch[key] = ensureInfluences(refined[key]);
- else patch[key] = (refined[key] ?? '').trim();
+ patch[key] = (refined[key] ?? '').trim();
}
+ const refinedInf = ensureInfluences(refined.influences);
+ const origInf = originals.influences;
+ patch.influences = {
+ embrace: locked.influencesEmbrace ? origInf.embrace : refinedInf.embrace,
+ avoid: locked.influencesAvoid ? origInf.avoid : refinedInf.avoid,
+ };
onApply(patch);
toast.success('Refined fields applied');
onClose();
@@ -193,7 +203,7 @@ export default function WorldPromptRefineModal({
{/* Originals — read-only preview so the user remembers what's about
to change. Lock indicator surfaces which fields the LLM will skip. */}
<div className="grid grid-cols-1 sm:grid-cols-2 gap-2 text-xs">
- {WORLD_LOCKABLE_FIELDS.filter((k) => k !== 'influences').map((key) => (
+ {WORLD_LOCKABLE_FIELDS.filter((k) => !isInfluenceLockField(k)).map((key) => (
<ReadOnlyField
key={key}
label={FIELD_LABELS[key]}
@@ -202,9 +212,10 @@ export default function WorldPromptRefineModal({
/>
))}
<ReadOnlyInfluences
- label={FIELD_LABELS.influences}
+ label="Influences"
value={originals.influences}
- locked={!!locked.influences}
+ lockedEmbrace={!!locked.influencesEmbrace}
+ lockedAvoid={!!locked.influencesAvoid}
/>
</div>
@@ -275,7 +286,7 @@ export default function WorldPromptRefineModal({
</ul>
)}
- {WORLD_LOCKABLE_FIELDS.filter((k) => k !== 'influences').map((key) => (
+ {WORLD_LOCKABLE_FIELDS.filter((k) => !isInfluenceLockField(k)).map((key) => (
<RefinedField
key={key}
label={`New ${FIELD_LABELS[key].toLowerCase()}`}
@@ -286,10 +297,11 @@ export default function WorldPromptRefineModal({
/>
))}
<RefinedInfluences
- label={`New ${FIELD_LABELS.influences.toLowerCase()}`}
+ label="New influences"
value={ensureInfluences(refined.influences)}
onChange={(v) => setRefinedField('influences', v)}
- locked={!!locked.influences}
+ lockedEmbrace={!!locked.influencesEmbrace}
+ lockedAvoid={!!locked.influencesAvoid}
/>
</div>
)}
@@ -336,17 +348,17 @@ function ReadOnlyField({ label, value, locked }) {
);
}
-function ReadOnlyInfluences({ label, value, locked }) {
+function ReadOnlyInfluences({ label, value, lockedEmbrace, lockedAvoid }) {
const hasAny = value.embrace.length || value.avoid.length;
+ const anyLocked = lockedEmbrace || lockedAvoid;
return (
- <div className={`bg-port-bg border rounded p-2 sm:col-span-2 ${locked ? 'border-port-accent/40' : 'border-port-border'}`}>
+ <div className={`bg-port-bg border rounded p-2 sm:col-span-2 ${anyLocked ? 'border-port-accent/40' : 'border-port-border'}`}>
<div className="flex items-center justify-between gap-2 mb-1">
<div className="text-[10px] uppercase tracking-wide text-gray-500">{label}</div>
- {locked && (
- <span className="inline-flex items-center gap-1 text-[10px] uppercase tracking-wide text-port-accent">
- <Lock className="w-3 h-3" /> Locked
- </span>
- )}
+ <div className="flex items-center gap-2 text-[10px] uppercase tracking-wide text-port-accent">
+ {lockedEmbrace && <span className="inline-flex items-center gap-1"><Lock className="w-3 h-3" /> Embrace</span>}
+ {lockedAvoid && <span className="inline-flex items-center gap-1"><Lock className="w-3 h-3" /> Avoid</span>}
+ </div>
</div>
{hasAny ? (
<div className="grid grid-cols-2 gap-2">
@@ -360,42 +372,39 @@ function ReadOnlyInfluences({ label, value, locked }) {
);
}
-function RefinedInfluences({ label, value, onChange, locked }) {
- if (locked) {
- return (
- <div>
- <div className="flex items-center justify-between gap-2 mb-1">
- <label className="block text-[11px] uppercase tracking-wide text-gray-500">{label}</label>
- <span className="inline-flex items-center gap-1 text-[10px] uppercase tracking-wide text-port-accent">
- <Lock className="w-3 h-3" /> Locked — kept as-is
- </span>
- </div>
- <div className="grid grid-cols-2 gap-2">
- <InfluenceChipsInput tokens={value.embrace} onChange={() => {}} tone="success" readOnly />
- <InfluenceChipsInput tokens={value.avoid} onChange={() => {}} tone="error" readOnly />
- </div>
- </div>
- );
- }
+function RefinedInfluences({ label, value, onChange, lockedEmbrace, lockedAvoid }) {
+ const lockBadge = (
+ <span className="inline-flex items-center gap-1 text-[10px] uppercase tracking-wide text-port-accent">
+ <Lock className="w-3 h-3" /> Kept as-is
+ </span>
+ );
return (
<div>
<label className="block text-[11px] uppercase tracking-wide text-gray-500 mb-1">{label}</label>
<div className="grid grid-cols-1 md:grid-cols-2 gap-2">
<div>
- <div className="text-[10px] uppercase tracking-wide text-port-success/80 mb-1">Embrace</div>
+ <div className="flex items-center justify-between gap-2 mb-1">
+ <div className="text-[10px] uppercase tracking-wide text-port-success/80">Embrace</div>
+ {lockedEmbrace && lockBadge}
+ </div>
<InfluenceChipsInput
tokens={value.embrace}
onChange={(next) => onChange({ ...value, embrace: next })}
tone="success"
+ readOnly={lockedEmbrace}
/>
</div>
<div>
- <div className="text-[10px] uppercase tracking-wide text-port-error/80 mb-1">Avoid</div>
+ <div className="flex items-center justify-between gap-2 mb-1">
+ <div className="text-[10px] uppercase tracking-wide text-port-error/80">Avoid</div>
+ {lockedAvoid && lockBadge}
+ </div>
<InfluenceChipsInput
tokens={value.avoid}
onChange={(next) => onChange({ ...value, avoid: next })}
tone="error"
placeholder="Add avoid token, press Enter"
+ readOnly={lockedAvoid}
/>
</div>
</div>
diff --git a/client/src/pages/WorldBuilder.jsx b/client/src/pages/WorldBuilder.jsx
index d0f731e8d4..863241e0c7 100644
--- a/client/src/pages/WorldBuilder.jsx
+++ b/client/src/pages/WorldBuilder.jsx
@@ -12,6 +12,7 @@ import { Link, useLocation, useNavigate, useParams } from 'react-router-dom';
import {
Globe2, Plus, Trash2, Sparkles, Wand2, Loader2, Save, FolderOpen,
Edit3, X, MessageSquarePlus, Play, Lock, Unlock,
+ PanelLeftClose, PanelLeftOpen,
} from 'lucide-react';
import toast from '../components/ui/Toast';
import {
@@ -20,7 +21,7 @@ import {
WORLD_CATEGORY_KEY_MAX, COMPOSITE_PROMPT_MAX, WORLD_LOGLINE_MAX,
WORLD_PREMISE_MAX, WORLD_STYLE_NOTES_MAX, WORLD_LOCKABLE_FIELDS,
WORLD_INFLUENCE_ENTRY_MAX, WORLD_INFLUENCES_PER_LIST_MAX,
- ensureInfluences,
+ ensureInfluences, isInfluenceLockField, mergeInfluencesWithLocks,
listImageModels, getSettings,
} from '../services/api';
import InfluenceChipsInput from '../components/worldBuilder/InfluenceChipsInput';
@@ -146,34 +147,38 @@ function FieldLabel({ htmlFor, children, field, locked, onToggleLock }) {
// to stylePrompt / negativePrompt.
function InfluencesEditor({ influences, onChange, locked, onToggleLock }) {
const safe = ensureInfluences(influences);
- const isLocked = !!locked?.influences;
return (
<div>
- <div className="flex items-center justify-between gap-2 mb-1">
+ <div className="mb-1">
<label className="text-xs text-gray-400">
- Influences <span className="text-gray-600">— prepended to render prompts deterministically</span>
+ Influences <span className="text-gray-600">— prepended to render prompts deterministically; embrace + avoid lock independently</span>
</label>
- <LockButton field="influences" locked={locked} onToggle={onToggleLock} label="Influences" />
</div>
<div className="grid grid-cols-1 md:grid-cols-2 gap-3">
<div>
- <div className="text-[11px] uppercase tracking-wide text-port-success/80 mb-1">Embrace</div>
+ <div className="flex items-center justify-between gap-2 mb-1">
+ <div className="text-[11px] uppercase tracking-wide text-port-success/80">Embrace</div>
+ <LockButton field="influencesEmbrace" locked={locked} onToggle={onToggleLock} label="Embrace influences" />
+ </div>
<InfluenceChipsInput
tokens={safe.embrace}
onChange={(next) => onChange({ ...safe, embrace: next })}
placeholder="Moebius, cel-shading…"
tone="success"
- readOnly={isLocked}
+ readOnly={!!locked?.influencesEmbrace}
/>
</div>
<div>
- <div className="text-[11px] uppercase tracking-wide text-port-error/80 mb-1">Avoid</div>
+ <div className="flex items-center justify-between gap-2 mb-1">
+ <div className="text-[11px] uppercase tracking-wide text-port-error/80">Avoid</div>
+ <LockButton field="influencesAvoid" locked={locked} onToggle={onToggleLock} label="Avoid influences" />
+ </div>
<InfluenceChipsInput
tokens={safe.avoid}
onChange={(next) => onChange({ ...safe, avoid: next })}
placeholder="Ghibli painterly, neon cyberpunk…"
tone="error"
- readOnly={isLocked}
+ readOnly={!!locked?.influencesAvoid}
/>
</div>
</div>
@@ -232,6 +237,20 @@ export default function WorldBuilder() {
const [refineOpen, setRefineOpen] = useState(false);
+ // Worlds list collapsed state — desktop only (mobile stacks the sidebar
+ // above the editor and there's no horizontal-space tradeoff to make).
+ // Persists across visits so users who prefer a maximized editor stay there.
+ const [worldsCollapsed, setWorldsCollapsed] = useState(() => {
+ try { return localStorage.getItem('worldBuilder.worldsCollapsed') === '1'; } catch { return false; }
+ });
+ const toggleWorldsCollapsed = () => {
+ setWorldsCollapsed((prev) => {
+ const next = !prev;
+ try { localStorage.setItem('worldBuilder.worldsCollapsed', next ? '1' : '0'); } catch { /* sandboxed */ }
+ return next;
+ });
+ };
+
const refresh = async () => {
setLoading(true);
const [list, provData, models, settings] = await Promise.all([
@@ -376,10 +395,15 @@ export default function WorldBuilder() {
setExpanding(true);
const result = await expandWorld({
starterPrompt: draft.starterPrompt,
- // Pass current influences so re-expansions stay on-direction —
- // without this, the LLM regenerates from the bare starter idea and
- // any prior refinement is lost.
+ // Full prior state + locks ride along so the LLM can keep its output
+ // consistent with refined/pinned bible fields (see expand prompt builder).
influences: ensureInfluences(draft.influences),
+ logline: draft.logline || '',
+ premise: draft.premise || '',
+ styleNotes: draft.styleNotes || '',
+ stylePrompt: draft.stylePrompt || '',
+ negativePrompt: draft.negativePrompt || '',
+ locked: draft.locked || {},
preservedVariations,
preservedCompositeSheets,
providerId: draft.llm?.provider || undefined,
@@ -402,13 +426,7 @@ export default function WorldBuilder() {
if (locks[key]) return draft[key];
return llmValue == null ? draft[key] : llmValue;
};
- // Influences: preserve the draft's lists when locked OR when the LLM
- // returned empty (defensive — sanitizeInfluences server-side already
- // falls back, but the client's own lock state must dominate too).
- const llmInf = ensureInfluences(result.influences);
- const refinedInfluences = locks.influences
- ? ensureInfluences(draft.influences)
- : ((llmInf.embrace.length || llmInf.avoid.length) ? llmInf : ensureInfluences(draft.influences));
+ const refinedInfluences = mergeInfluencesWithLocks(locks, result.influences, draft.influences);
// Per-item lock merge: for each category, locked items survive at the
// top of the list; LLM-generated items follow, deduped case-insensitively
// by label so the LLM can't accidentally regenerate a pinned label.
@@ -512,9 +530,13 @@ export default function WorldBuilder() {
const applyRefinement = async (patch = {}) => {
const next = { ...draft };
for (const key of WORLD_LOCKABLE_FIELDS) {
+ // Influences live under one top-level `influences` object (not as
+ // `influencesEmbrace`/`influencesAvoid` keys on the world); handle below.
+ if (isInfluenceLockField(key)) continue;
if (!(key in patch) || patch[key] == null) continue;
- next[key] = key === 'influences' ? ensureInfluences(patch[key]) : patch[key];
+ next[key] = patch[key];
}
+ if (patch.influences != null) next.influences = ensureInfluences(patch.influences);
setDraft(next);
if (selectedId && next.name?.trim()) {
const updated = await updateWorld(selectedId, {
@@ -651,52 +673,90 @@ export default function WorldBuilder() {
const totalSheets = draft.compositeSheets?.length || 0;
const renderTotal = renderPromptCount(draft, renderOpts.promptMode);
+ // Mobile = flex column (grid template ignored); lg+ = grid where the inline
+ // `gridTemplateColumns` swap between collapsed/expanded widths takes effect.
+ // Flipping `display` at the breakpoint (rather than overriding grid-cols-1
+ // with an inline style) keeps the mobile stack working.
+ const desktopGridCols = worldsCollapsed ? '32px minmax(0, 1fr)' : '260px minmax(0, 1fr)';
+
return (
- <div className="grid grid-cols-1 lg:grid-cols-[260px_1fr] gap-4">
- {/* Sidebar — world list */}
- <aside className="bg-port-card border border-port-border rounded p-3 flex flex-col gap-2 min-h-[60vh]">
- <div className="flex items-center justify-between">
- <h2 className="text-sm font-semibold text-white flex items-center gap-2">
- <Globe2 size={16} className="text-port-accent" /> Worlds
- </h2>
+ <div className="flex flex-col h-full">
+ <div
+ className="flex-1 flex flex-col lg:grid min-h-0"
+ style={{ gridTemplateColumns: desktopGridCols }}
+ >
+ {/* Sidebar — world list. Collapses to a thin rail with just an open
+ button on desktop; mobile keeps the full sidebar inline (the page
+ stacks vertically below `lg`, so collapsing doesn't help there).
+ Border-r + tinted bg matches WritersRoom's tight integrated look —
+ the editor area flows directly off the sidebar without a card gap. */}
+ {worldsCollapsed ? (
+ <aside className="hidden lg:flex border-r border-port-border bg-port-card/40 items-start justify-center pt-3">
<button
- onClick={handleNew}
- className="text-xs px-2 py-1 bg-port-accent/15 hover:bg-port-accent/25 text-port-accent rounded flex items-center gap-1 min-h-[40px] sm:min-h-0"
- title="New world"
+ onClick={toggleWorldsCollapsed}
+ className="p-1.5 text-gray-500 hover:text-white"
+ title="Show worlds"
+ aria-label="Show worlds"
>
- <Plus size={14} /> New
+ <PanelLeftOpen size={14} />
</button>
- </div>
- {loading ? (
- <p className="text-xs text-gray-500">Loading…</p>
- ) : worlds.length === 0 ? (
- <p className="text-xs text-gray-500">No worlds yet — click <span className="text-port-accent">New</span> to start.</p>
- ) : (
- <ul className="flex flex-col gap-1 overflow-y-auto">
- {worlds.map((w) => {
- const active = w.id === selectedId;
- return (
- <li key={w.id}>
- <button
- onClick={() => goToWorld(w.id)}
- className={`w-full text-left px-2 py-2 rounded text-sm transition-colors min-h-[40px] ${
- active
- ? 'bg-port-accent/15 text-port-accent border border-port-accent/40'
- : 'text-gray-300 hover:bg-port-bg border border-transparent'
- }`}
- >
- <div className="font-medium truncate">{w.name}</div>
- <div className="text-[11px] text-gray-500 truncate">{w.starterPrompt || 'No starter prompt'}</div>
- </button>
- </li>
- );
- })}
- </ul>
- )}
- </aside>
+ </aside>
+ ) : (
+ <aside className="border-b lg:border-b-0 lg:border-r border-port-border bg-port-card/40 px-3 py-3 flex flex-col gap-2 lg:overflow-y-auto">
+ <div className="flex items-center justify-between">
+ <h2 className="text-sm font-semibold text-white flex items-center gap-2">
+ <Globe2 size={16} className="text-port-accent" /> Worlds
+ </h2>
+ <div className="flex items-center gap-1">
+ <button
+ onClick={handleNew}
+ className="text-xs px-2 py-1 bg-port-accent/15 hover:bg-port-accent/25 text-port-accent rounded flex items-center gap-1 min-h-[40px] sm:min-h-0"
+ title="New world"
+ >
+ <Plus size={14} /> New
+ </button>
+ <button
+ onClick={toggleWorldsCollapsed}
+ className="hidden lg:inline-flex p-1.5 text-gray-500 hover:text-white"
+ title="Collapse worlds"
+ aria-label="Collapse worlds"
+ >
+ <PanelLeftClose size={14} />
+ </button>
+ </div>
+ </div>
+ {loading ? (
+ <p className="text-xs text-gray-500">Loading…</p>
+ ) : worlds.length === 0 ? (
+ <p className="text-xs text-gray-500">No worlds yet — click <span className="text-port-accent">New</span> to start.</p>
+ ) : (
+ <ul className="flex flex-col gap-1 overflow-y-auto">
+ {worlds.map((w) => {
+ const active = w.id === selectedId;
+ return (
+ <li key={w.id}>
+ <button
+ onClick={() => goToWorld(w.id)}
+ className={`w-full text-left px-2 py-2 rounded text-sm transition-colors min-h-[40px] ${
+ active
+ ? 'bg-port-accent/15 text-port-accent border border-port-accent/40'
+ : 'text-gray-300 hover:bg-port-bg border border-transparent'
+ }`}
+ >
+ <div className="font-medium truncate">{w.name}</div>
+ <div className="text-[11px] text-gray-500 truncate">{w.starterPrompt || 'No starter prompt'}</div>
+ </button>
+ </li>
+ );
+ })}
+ </ul>
+ )}
+ </aside>
+ )}
- {/* Editor */}
- <section className="flex flex-col gap-4">
+ {/* Editor — owns its own scroll inside the full-width main so the
+ sidebar can stay pinned while the long card stack scrolls. */}
+ <section className="flex flex-col gap-4 p-4 min-h-0 lg:overflow-y-auto">
<header className="bg-port-card border border-port-border rounded p-4 flex flex-col gap-3">
<div className="flex items-center gap-2 flex-wrap">
<input
@@ -1063,6 +1123,7 @@ export default function WorldBuilder() {
</section>
)}
</section>
+ </div>
</div>
);
}
diff --git a/client/src/services/apiWorldBuilder.js b/client/src/services/apiWorldBuilder.js
index 29bd3ed3b5..3b0cf85e12 100644
--- a/client/src/services/apiWorldBuilder.js
+++ b/client/src/services/apiWorldBuilder.js
@@ -34,12 +34,16 @@ export const deleteWorld = (id) => request(`/world-builder/${encodeURIComponent(
export const expandWorld = ({
starterPrompt, influences,
preservedVariations, preservedCompositeSheets,
+ logline, premise, styleNotes, stylePrompt, negativePrompt,
+ locked,
providerId, model,
} = {}) => request('/world-builder/expand', {
method: 'POST',
body: JSON.stringify({
starterPrompt, influences,
preservedVariations, preservedCompositeSheets,
+ logline, premise, styleNotes, stylePrompt, negativePrompt,
+ locked,
providerId, model,
}),
});
@@ -70,17 +74,48 @@ export const WORLD_LOCKABLE_FIELDS = [
'logline',
'premise',
'styleNotes',
- 'influences',
+ 'influencesEmbrace',
+ 'influencesAvoid',
];
// Coerce whatever shape the server / draft / patch hands us into a strict
// `{ embrace: [], avoid: [] }` so consumers never have to guard undefined.
-// The server has its own sanitizer (sanitizeInfluences) — this one just
-// normalizes shape on the client side.
-export const ensureInfluences = (raw) => ({
- embrace: Array.isArray(raw?.embrace) ? raw.embrace : [],
- avoid: Array.isArray(raw?.avoid) ? raw.avoid : [],
-});
+// Fast-path: if the input is already shape-correct, return it unchanged so
+// downstream React refs stay stable (avoids per-render object churn that
+// would invalidate memoized children).
+export const ensureInfluences = (raw) => {
+ if (raw && Array.isArray(raw.embrace) && Array.isArray(raw.avoid)) return raw;
+ return {
+ embrace: Array.isArray(raw?.embrace) ? raw.embrace : [],
+ avoid: Array.isArray(raw?.avoid) ? raw.avoid : [],
+ };
+};
+
+// Lockable lock-map keys that target one of the two influence sub-lists
+// (embrace + avoid). Use this instead of `.startsWith('influences')` so a
+// future LOCKABLE_FIELDS entry like `influencesPriority` doesn't get silently
+// swept into per-list handling.
+export const WORLD_INFLUENCE_LOCK_FIELDS = ['influencesEmbrace', 'influencesAvoid'];
+export const isInfluenceLockField = (key) => WORLD_INFLUENCE_LOCK_FIELDS.includes(key);
+
+// Build a refined influences object that honors per-list locks. Locked lists
+// take their value from `fallback` (the user's current draft / originals);
+// unlocked lists take from `fresh` (the LLM output), falling back to
+// `fallback` when the LLM omitted that list. Used by handleExpand merge AND
+// the server-side refine merge (mirrored). The refine modal's apply path
+// uses different semantics (no fallback-on-empty) and inlines its own build.
+export const mergeInfluencesWithLocks = (locked, fresh, fallback) => {
+ const freshSafe = ensureInfluences(fresh);
+ const fallbackSafe = ensureInfluences(fallback);
+ return {
+ embrace: locked?.influencesEmbrace
+ ? fallbackSafe.embrace
+ : (freshSafe.embrace.length ? freshSafe.embrace : fallbackSafe.embrace),
+ avoid: locked?.influencesAvoid
+ ? fallbackSafe.avoid
+ : (freshSafe.avoid.length ? freshSafe.avoid : fallbackSafe.avoid),
+ };
+};
export const renderWorld = (id, options) => request(`/world-builder/${encodeURIComponent(id)}/render`, {
method: 'POST',
diff --git a/server/routes/worldBuilder.js b/server/routes/worldBuilder.js
index 823056c2a0..45dcd4dbc0 100644
--- a/server/routes/worldBuilder.js
+++ b/server/routes/worldBuilder.js
@@ -124,6 +124,14 @@ const expandSchema = z.object({
z.array(variationSchema).max(svc.VARIATIONS_PER_CATEGORY_MAX),
).optional(),
preservedCompositeSheets: z.array(compositeSheetSchema).max(svc.COMPOSITE_SHEETS_MAX).optional(),
+ // Current bible/prompt state — locked entries are echoed verbatim, others
+ // are starting points the LLM can refine while staying consistent.
+ logline: z.string().trim().max(svc.LOGLINE_MAX).optional(),
+ premise: z.string().trim().max(svc.PREMISE_MAX).optional(),
+ styleNotes: z.string().trim().max(svc.STYLE_NOTES_MAX).optional(),
+ stylePrompt: z.string().trim().max(svc.PROMPT_FRAGMENT_MAX).optional(),
+ negativePrompt: z.string().trim().max(svc.PROMPT_FRAGMENT_MAX).optional(),
+ locked: lockedSchema.optional(),
providerId: z.string().trim().max(80).optional(),
model: z.string().trim().max(200).optional(),
});
diff --git a/server/services/worldBuilder.js b/server/services/worldBuilder.js
index 7a5c9a3e1e..d9ae9e864f 100644
--- a/server/services/worldBuilder.js
+++ b/server/services/worldBuilder.js
@@ -73,9 +73,32 @@ export const LOCKABLE_FIELDS = Object.freeze([
'logline',
'premise',
'styleNotes',
- 'influences',
+ 'influencesEmbrace',
+ 'influencesAvoid',
]);
+// Human-readable labels for lockable fields. Single source of truth for the
+// LLM prompt builders (refine emits "starter idea", expand emits "STARTER IDEA"
+// — both derive from this map). Adding a new lockable field only requires
+// extending LOCKABLE_FIELDS + this map; the prompts pick it up automatically.
+export const LOCKABLE_FIELD_LABELS = Object.freeze({
+ starterPrompt: 'starter idea',
+ stylePrompt: 'style prompt',
+ negativePrompt: 'negative prompt',
+ logline: 'logline',
+ premise: 'premise',
+ styleNotes: 'style notes',
+ influencesEmbrace: 'embrace influences',
+ influencesAvoid: 'avoid influences',
+});
+
+// Lockable lock-map keys that target one of the two influence sub-lists.
+// Use `isInfluenceLockField` instead of `.startsWith('influences')` so a
+// future LOCKABLE_FIELDS entry like `influencesPriority` doesn't accidentally
+// get swept into per-list handling.
+export const INFLUENCE_LOCK_FIELDS = Object.freeze(['influencesEmbrace', 'influencesAvoid']);
+export const isInfluenceLockField = (key) => INFLUENCE_LOCK_FIELDS.includes(key);
+
// Starter buckets the UI surfaces for a fresh world. They remain for
// compatibility, but saved templates may carry any additional sanitized
// category keys the LLM or user creates.
@@ -210,12 +233,36 @@ export const sanitizeInfluences = (raw = {}) => {
};
};
+// Build a refined influences object that honors per-list locks. Locked lists
+// take their value from `fallback` (originals); unlocked lists take from
+// `fresh` (the LLM output), falling back to `fallback` when the LLM omitted
+// that list. Mirrors `mergeInfluencesWithLocks` in client/services/apiWorldBuilder.js.
+export const mergeInfluencesWithLocks = (locked, fresh, fallback) => {
+ const freshSafe = sanitizeInfluences(fresh);
+ const fallbackSafe = sanitizeInfluences(fallback);
+ return {
+ embrace: locked?.influencesEmbrace
+ ? fallbackSafe.embrace
+ : (freshSafe.embrace.length ? freshSafe.embrace : fallbackSafe.embrace),
+ avoid: locked?.influencesAvoid
+ ? fallbackSafe.avoid
+ : (freshSafe.avoid.length ? freshSafe.avoid : fallbackSafe.avoid),
+ };
+};
+
export const sanitizeLocked = (raw = {}) => {
if (!raw || typeof raw !== 'object') return {};
const out = {};
for (const key of LOCKABLE_FIELDS) {
if (raw[key] === true) out[key] = true;
}
+ // Migration: prior schema had a single `influences` lock covering both
+ // embrace + avoid. Expand into the two per-list locks so existing worlds
+ // keep working without a data migration step.
+ if (raw.influences === true) {
+ out.influencesEmbrace = true;
+ out.influencesAvoid = true;
+ }
return out;
};
diff --git a/server/services/worldBuilder.test.js b/server/services/worldBuilder.test.js
index 6df0eeac6e..62017bf588 100644
--- a/server/services/worldBuilder.test.js
+++ b/server/services/worldBuilder.test.js
@@ -548,9 +548,9 @@ describe("worldBuilder service", () => {
describe("locked", () => {
it("round-trips a sparse lock map and replaces wholesale on patch", async () => {
const w = await seedWorld({
- locked: { logline: true, influences: true },
+ locked: { logline: true, influencesEmbrace: true },
});
- expect(w.locked).toEqual({ logline: true, influences: true });
+ expect(w.locked).toEqual({ logline: true, influencesEmbrace: true });
const patched = await svc.updateWorld(w.id, {
locked: { styleNotes: true },
});
@@ -563,6 +563,18 @@ describe("worldBuilder service", () => {
});
expect(w.locked).toEqual({ premise: true });
});
+
+ it("migrates legacy `locked.influences: true` into per-list locks", async () => {
+ // Prior schema combined embrace + avoid into one `influences` lock. The
+ // sanitizer now splits it into two so existing on-disk worlds keep working
+ // without a data migration step.
+ const w = await seedWorld({ locked: { influences: true, premise: true } });
+ expect(w.locked).toEqual({
+ premise: true,
+ influencesEmbrace: true,
+ influencesAvoid: true,
+ });
+ });
});
describe("sanitizers", () => {
diff --git a/server/services/worldBuilderExpand.js b/server/services/worldBuilderExpand.js
index 204fef7ff0..657362cfac 100644
--- a/server/services/worldBuilderExpand.js
+++ b/server/services/worldBuilderExpand.js
@@ -14,12 +14,15 @@
import { getActiveProvider, getProviderById } from "./providers.js";
import {
WORLD_CATEGORIES,
+ LOCKABLE_FIELDS,
+ LOCKABLE_FIELD_LABELS,
PROMPT_FRAGMENT_MAX,
COMPOSITE_PROMPT_MAX,
VARIATIONS_PER_CATEGORY_MAX,
LOGLINE_MAX,
PREMISE_MAX,
STYLE_NOTES_MAX,
+ isInfluenceLockField,
sanitizeCategories,
sanitizeCompositeSheets,
sanitizeInfluences,
@@ -33,11 +36,28 @@ import {
const LABEL_MAX = 80;
+// Bible/prompt fields the LLM sees as "current world state" so re-expansion
+// stays consistent with prior refinements. Derived from LOCKABLE_FIELDS so a
+// new lockable field automatically reaches this prompt; excludes starterPrompt
+// (already shown above as the seed) and influences (rendered in its own
+// section).
+const CURRENT_STATE_FIELDS = LOCKABLE_FIELDS
+ .filter((k) => k !== 'starterPrompt' && !isInfluenceLockField(k))
+ .map((k) => [k, LOCKABLE_FIELD_LABELS[k].toUpperCase()]);
+
function buildExpansionPrompt({
starterPrompt,
influences,
preservedVariations,
preservedCompositeSheets,
+ // Prior bible/prompt state — locked entries echo back unchanged; unlocked
+ // entries seed the LLM. Empty/missing fields are skipped.
+ priorLogline = '',
+ priorPremise = '',
+ priorStyleNotes = '',
+ priorStylePrompt = '',
+ priorNegativePrompt = '',
+ locked = {},
}) {
const embrace = Array.isArray(influences?.embrace)
? influences.embrace.filter(Boolean)
@@ -45,11 +65,33 @@ function buildExpansionPrompt({
const avoid = Array.isArray(influences?.avoid)
? influences.avoid.filter(Boolean)
: [];
+ const embraceTag = locked?.influencesEmbrace ? ' [LOCKED]' : '';
+ const avoidTag = locked?.influencesAvoid ? ' [LOCKED]' : '';
const influencesSection =
embrace.length || avoid.length
- ? `\n# Influences (canonical reference list — these MUST inform stylePrompt + styleNotes for embraces and negativePrompt for avoids)\nEmbrace: ${embrace.join(", ") || "(none)"}\nAvoid: ${avoid.join(", ") || "(none)"}\n`
+ ? `\n# Influences (canonical reference list — these MUST inform stylePrompt + styleNotes for embraces and negativePrompt for avoids)\nEmbrace${embraceTag}: ${embrace.join(", ") || "(none)"}\nAvoid${avoidTag}: ${avoid.join(", ") || "(none)"}\n`
: "";
+ // Locked entries are flagged and MUST be echoed verbatim; unlocked entries
+ // are starting points the LLM can refine. Consistency goal: an LLM-generated
+ // premise should align with a locked logline, not be written in isolation.
+ const priorValues = {
+ logline: priorLogline,
+ premise: priorPremise,
+ styleNotes: priorStyleNotes,
+ stylePrompt: priorStylePrompt,
+ negativePrompt: priorNegativePrompt,
+ };
+ const stateLines = CURRENT_STATE_FIELDS
+ .filter(([key]) => typeof priorValues[key] === 'string' && priorValues[key].trim())
+ .map(([key, label]) => `${label}${locked?.[key] ? ' [LOCKED]' : ''}: ${priorValues[key].trim()}`);
+ const anyLocked = stateLines.length
+ && Object.keys(locked || {}).some((k) => locked[k] === true);
+ const currentStateSection = stateLines.length
+ ? `\n# Current world state — established context for this expansion${anyLocked ? '. Fields marked [LOCKED] MUST be echoed unchanged in your output' : ''}.
+${stateLines.join('\n\n')}\n`
+ : '';
+
// Preserved items: the client extracted user-pinned variations and
// composite boards. List them by category + label so the LLM can avoid
// generating duplicates, but tell it explicitly NOT to echo them in its
@@ -80,7 +122,7 @@ ${preservedVariationLines.length ? `Pinned variations:\n${preservedVariationLine
# Starter idea
${starterPrompt}
-${influencesSection}${preservedSection}
+${influencesSection}${currentStateSection}${preservedSection}
# Output contract
Return a SINGLE JSON object. NO markdown, NO commentary. The object MUST have these top-level keys:
@@ -120,6 +162,7 @@ Concrete compositeSheets examples:
- Reference-sheet prompts must include a clear board structure: title/subject, 4-6 figure lineup roles when relevant, materials swatches, fasteners/accessories icons, color palette strip, background hint, and simplicity constraints such as minimal readable layout, fewer tiny objects, clean silhouettes, not baroque, not hyper-detailed.
- World pitch poster prompts must include a clear editorial poster structure: world title/subtitle/logline area, dominant hero panorama, inset environment/culture/creature images, visual-language strip, color palette, materials/textures, light/atmosphere, themes/icons, and concise labeled blocks for world, feel, aesthetic, environments, cultures, and tone. Mention that body copy should be short, clean, and readable; avoid dense tiny text.
- If the world needs pitch posters, do not put "text" in the negativePrompt. Prefer "watermark, logo, unreadable tiny text, text artifacts" so title/section typography remains possible.
+- When "Current world state" is provided above: treat it as the established world. Fields marked [LOCKED] MUST be echoed in your output exactly as given — do not reword, expand, or trim them. Unlocked current-state fields are starting points; you may refine them, but stay consistent with locked fields, the starter idea, and influences.
- Output JUST the JSON object. No prose before or after.`;
}
@@ -237,6 +280,15 @@ export async function expandWorldTemplate({
influences,
preservedVariations = {},
preservedCompositeSheets = [],
+ // Prior bible/prompt state — locked entries echo back unchanged, unlocked
+ // entries seed the LLM. Renamed to `prior*` so the parsed-LLM-output locals
+ // below can keep their canonical names.
+ logline: priorLogline = '',
+ premise: priorPremise = '',
+ styleNotes: priorStyleNotes = '',
+ stylePrompt: priorStylePrompt = '',
+ negativePrompt: priorNegativePrompt = '',
+ locked = {},
providerId,
model,
} = {}) {
@@ -265,6 +317,12 @@ export async function expandWorldTemplate({
influences: safeInfluences,
preservedVariations,
preservedCompositeSheets,
+ priorLogline,
+ priorPremise,
+ priorStyleNotes,
+ priorStylePrompt,
+ priorNegativePrompt,
+ locked,
});
const totalIn = safeInfluences.embrace.length + safeInfluences.avoid.length;
const preservedVarCount = Object.values(preservedVariations || {}).reduce(
diff --git a/server/services/worldBuilderExpand.test.js b/server/services/worldBuilderExpand.test.js
index f27e74140d..dff462a2e5 100644
--- a/server/services/worldBuilderExpand.test.js
+++ b/server/services/worldBuilderExpand.test.js
@@ -325,4 +325,74 @@ describe("worldBuilderExpand.EXPANSION_PROMPT", () => {
expect(out).toContain("Embrace: Moebius, cel-shading");
expect(out).toContain("Avoid: Ghibli painterly");
});
+
+ it("omits the Current world state section when no bible/prompt fields are provided", () => {
+ const out = buildExpansionPrompt({ starterPrompt: "seed" });
+ expect(out).not.toContain("# Current world state");
+ });
+
+ it("includes provided bible + prompt fields as Current world state context", () => {
+ const out = buildExpansionPrompt({
+ starterPrompt: "seed",
+ priorLogline: "A foundry city goes silent.",
+ priorPremise: "Three families inherit the silence.",
+ priorStyleNotes: "Tarkovsky pacing, Moebius palette.",
+ priorStylePrompt: "moebius linework, dust palette",
+ priorNegativePrompt: "blurry, lowres",
+ });
+ expect(out).toContain("# Current world state");
+ expect(out).toContain("LOGLINE: A foundry city goes silent.");
+ expect(out).toContain("PREMISE: Three families inherit the silence.");
+ expect(out).toContain("STYLE NOTES: Tarkovsky pacing, Moebius palette.");
+ expect(out).toContain("STYLE PROMPT: moebius linework, dust palette");
+ expect(out).toContain("NEGATIVE PROMPT: blurry, lowres");
+ });
+
+ it("flags locked fields with [LOCKED] and adds the must-preserve instruction", () => {
+ const out = buildExpansionPrompt({
+ starterPrompt: "seed",
+ priorLogline: "Locked logline.",
+ priorPremise: "Loose premise.",
+ locked: { logline: true },
+ });
+ expect(out).toContain("LOGLINE [LOCKED]: Locked logline.");
+ expect(out).toContain("PREMISE: Loose premise.");
+ expect(out).not.toContain("PREMISE [LOCKED]");
+ expect(out).toContain("Fields marked [LOCKED] MUST be echoed unchanged");
+ });
+
+ it("flags locked embrace influences with [LOCKED] on the Embrace line", () => {
+ const out = buildExpansionPrompt({
+ starterPrompt: "seed",
+ influences: { embrace: ["Moebius"], avoid: ["Ghibli"] },
+ locked: { influencesEmbrace: true },
+ });
+ expect(out).toMatch(/Embrace \[LOCKED\]: Moebius/);
+ // Avoid is untagged when not locked.
+ expect(out).toMatch(/Avoid: Ghibli/);
+ expect(out).not.toMatch(/Avoid \[LOCKED\]/);
+ });
+
+ it("flags locked avoid influences independently of embrace", () => {
+ const out = buildExpansionPrompt({
+ starterPrompt: "seed",
+ influences: { embrace: ["Moebius"], avoid: ["Ghibli"] },
+ locked: { influencesAvoid: true },
+ });
+ expect(out).toMatch(/Embrace: Moebius/);
+ expect(out).not.toMatch(/Embrace \[LOCKED\]/);
+ expect(out).toMatch(/Avoid \[LOCKED\]: Ghibli/);
+ });
+
+ it("skips empty bible/prompt fields from Current world state", () => {
+ const out = buildExpansionPrompt({
+ starterPrompt: "seed",
+ priorLogline: "Just a logline.",
+ priorPremise: "",
+ priorStyleNotes: " ",
+ });
+ expect(out).toContain("LOGLINE: Just a logline.");
+ expect(out).not.toContain("PREMISE:");
+ expect(out).not.toContain("STYLE NOTES:");
+ });
});
diff --git a/server/services/worldBuilderRefine.js b/server/services/worldBuilderRefine.js
index 14df032c40..f84239a6f5 100644
--- a/server/services/worldBuilderRefine.js
+++ b/server/services/worldBuilderRefine.js
@@ -17,11 +17,14 @@ import { createRun, executeApiRun, executeCliRun } from "./runner.js";
import { resolveEffectiveModel } from "../lib/promptRunner.js";
import {
LOCKABLE_FIELDS,
+ LOCKABLE_FIELD_LABELS,
LOGLINE_MAX,
PREMISE_MAX,
PROMPT_FRAGMENT_MAX,
STARTER_PROMPT_MAX,
STYLE_NOTES_MAX,
+ isInfluenceLockField,
+ mergeInfluencesWithLocks,
sanitizeInfluences,
sanitizeLocked,
} from "./worldBuilder.js";
@@ -114,20 +117,9 @@ function extractRefinementJson(raw) {
);
}
-// Field labels surfaced to the LLM so the "DO NOT MODIFY" list reads naturally.
-const FIELD_LABELS = {
- starterPrompt: "starter idea",
- stylePrompt: "style prompt",
- negativePrompt: "negative prompt",
- logline: "logline",
- premise: "premise",
- styleNotes: "style notes",
- influences: "influences (embrace + avoid)",
-};
-
const lockedList = (locked) =>
LOCKABLE_FIELDS.filter((k) => locked && locked[k] === true).map(
- (k) => `- ${FIELD_LABELS[k]} ("${k}")`,
+ (k) => `- ${LOCKABLE_FIELD_LABELS[k]} ("${k}")`,
);
/**
@@ -418,13 +410,13 @@ export async function refineWorldPrompts({
styleNotes: STYLE_NOTES_MAX,
};
- // For each lockable field: if locked, echo the original; otherwise take
- // the LLM's value (or fall back to original when missing/empty so the
- // modal never receives a blank where the user had content). Influences is
- // an object — handle it after the scalar loop.
+ // Scalar fields: if locked, echo the original; otherwise take the LLM's
+ // value (or fall back to original when missing/empty so the modal never
+ // receives a blank where the user had content). Influences is an object
+ // with per-list locks — handled separately below.
const refined = {};
for (const key of LOCKABLE_FIELDS) {
- if (key === "influences") continue;
+ if (isInfluenceLockField(key)) continue;
if (safeLocked[key]) {
refined[key] = originals[key];
continue;
@@ -432,19 +424,7 @@ export async function refineWorldPrompts({
const llmValue = trimTo(parsed[key], FIELD_CAPS[key]);
refined[key] = llmValue || originals[key];
}
-
- // Influences: locked → echo originals; unlocked → take the LLM's lists
- // (sanitized for caps + dedupe). When the LLM omits it entirely we keep
- // the originals rather than wiping them.
- if (safeLocked.influences) {
- refined.influences = originals.influences;
- } else {
- const llmInfluences = sanitizeInfluences(parsed.influences);
- refined.influences =
- llmInfluences.embrace.length || llmInfluences.avoid.length
- ? llmInfluences
- : originals.influences;
- }
+ refined.influences = mergeInfluencesWithLocks(safeLocked, parsed.influences, originals.influences);
// Legacy cleanup: prior refinements may have stuffed a "Style direction:"
// paragraph into the starter. Now that influences carries the direction