Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat(world-builder): refine-prompts modal + per-element render buttons
Adam Eivyb277d0392753
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 8ed7e7b3d5..62f31f9548 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -2,6 +2,8 @@## Added+- **World Builder — per-element Render buttons.** Each composite board, each category item (variation), and each category header now has its own inline Render button — no need to render the whole batch when you just want to iterate on one image. Per-board and per-variation buttons render exactly one prompt; the per-category header button renders every variation in that category. All three reuse the page's existing render-options panel (backend, model, resolution, batch-per-prompt) and route through the same job-queue + collection-tagging path as the full batch render, so toast + run history behave identically. Buttons disable themselves when the world isn't saved, no backend is configured, or a render is already in flight; per-category disables when the category has no variations yet.+- **World Builder — Refine prompts modal.** Once a world has a starter idea, click *Refine prompts* to describe a tweak in plain English ("more painterly", "lean harder into the moebius linework", "drop the cyberpunk neon") and the LLM rewrites the starter, style, and negative prompts together, with a one-line rationale shown alongside each. Each rewritten field is editable inline before *Apply*; applying auto-persists the result back to a saved world (mirrors the *Expand* flow's auto-save) so subsequent renders/expansions pick up the refinement immediately. Backed by `POST /api/world-builder/refine-prompts` + `server/services/worldBuilderRefine.js` reusing the same stage-runner plumbing the Expand pass uses.- **Refine Prompt action in the Media Lightbox.** Open any past image or video render and click *Refine Prompt* to describe what you'd like to change in plain English ("more painterly", "switch to watercolor", "drop the cyberpunk neon"). PortOS hands the original prompt + your feedback to any enabled AI provider — API (OpenAI, Anthropic, LM Studio) or CLI (Codex, Claude Code, Gemini CLI) — and shows the rewritten positive and negative prompts as editable text plus a one-line rationale. Tweak the new prompt if you want, then *Queue Render* to make a new render that inherits the original's model, resolution, LoRAs, seed, and other settings.- **Pipeline — Arc canvas UI.** PipelineSeries's right-side canvas is now a structural Arc → Season → Episode tree. Top of the canvas shows the series arc card (logline, themes, collapsible summary + protagonist arc, edit-in-place fields). One-click `Generate arc` runs the Phase 3 LLM pass and persists `series.arc` + `series.seasons[]`; `Verify arc` surfaces continuity findings inline with severity badges. Each season expands/collapses, shows `N / target episodes` count, and exposes inline edit (number / title / logline / synopsis / ending hook / status / episode-count target). Episodes render as compact rows with delete, hover-revealed season picker (move between seasons), and direct deep-link into the issue editor. `Generate episodes (LLM)` on an empty season runs the per-season-episodes pass and creates one issue per beat with `seasonId` + `arcPosition` pre-filled; un-grouped issues stay visible in a dedicated bottom panel. Replaces the flat issue-card grid from Phase 1; backed by the schema + endpoints from Phases 2 + 3. Two-click-arm replace guard on arc regeneration and per-season delete. Phase 4 of the Story Arc Planning initiative.- **Pipeline — LLM-driven series-arc planning.** Three new staged-LLM passes that plan and verify a multi-season series: (1) `POST /api/pipeline/series/:id/arc/generate` proposes the top-level arc — series-level logline, summary, themes, protagonist arc — plus a 2–5 season breakdown with per-season loglines, ending hooks, and episode-count targets, default `model: 'heavy'`. (2) `POST /api/pipeline/series/:id/seasons/:seasonId/episodes/generate` proposes the episode-by-episode breakdown for one season, taking the whole-arc protagonist trajectory and prior seasons' synopses as continuity context. (3) `POST /api/pipeline/series/:id/arc/verify` runs a cross-season continuity pass that surfaces character contradictions, dropped subplots, episode-count/arc-weight mismatch, unresolved finale hooks, arc-role imbalance, and theme drift as actionable `{ severity, location, problem, suggestion }` issues. All three calls accept `{ providerOverride, modelOverride }` and routes 1 + 2 also accept `commit: true` to persist the proposal in one shot (default returns a preview the UI can confirm before writing). Backed by `server/services/pipeline/arcPlanner.js` (~280 LOC) on top of the shared `stageRunner.js` + new stage prompts in `data.sample/prompts/stages/pipeline-arc-{overview,verify}.md` + `pipeline-season-episodes.md`, all three reusing the `_partials/bible-deference.md` block for character/setting consistency. Phase 3 of the Story Arc Planning initiative — no UI yet (Phase 4 builds the arc canvas on top of these endpoints).diff --git a/client/src/components/worldBuilder/WorldPromptRefineModal.jsx b/client/src/components/worldBuilder/WorldPromptRefineModal.jsxnew file mode 100644index 0000000000..ee3e8114e5--- /dev/null+++ b/client/src/components/worldBuilder/WorldPromptRefineModal.jsx@@ -0,0 +1,289 @@+import { useEffect, useState } from 'react';+import { Check, Sparkles, Wand2, X } from 'lucide-react';+import ProviderModelSelector from '../ProviderModelSelector';+import toast from '../ui/Toast';+import useProviderModels from '../../hooks/useProviderModels';+import { refineWorldPrompts } from '../../services/api';++/**+ * Refines the three top-level world prompts (Starter Idea, Style Prompt,+ * Negative Prompt) based on user feedback. Mirrors PromptRefineModal's+ * shape — feedback box, provider/model selector, refined-fields review,+ * then apply.+ *+ * The modal is stateless from the server's perspective: applying the+ * refinement writes back to the page-level draft, and saving the world+ * is the user's choice (matches existing expansion-flow behavior).+ */+export default function WorldPromptRefineModal({+ open,+ onClose,+ onApply,+ starterPrompt = '',+ stylePrompt = '',+ negativePrompt = '',+ // Optional pre-selected provider/model — when a world already pins an LLM+ // for expansion, default the refiner to the same combo so the user doesn't+ // have to re-pick.+ defaultProviderId = null,+ defaultModel = null,+}) {+ const {+ providers,+ selectedProviderId,+ selectedModel,+ availableModels,+ setSelectedProviderId,+ setSelectedModel,+ loading: providersLoading,+ } = useProviderModels();++ const [feedback, setFeedback] = useState('');+ const [refinedStarter, setRefinedStarter] = useState('');+ const [refinedStyle, setRefinedStyle] = useState('');+ const [refinedNegative, setRefinedNegative] = useState('');+ const [rationale, setRationale] = useState('');+ const [changes, setChanges] = useState([]);+ const [refining, setRefining] = useState(false);++ // Reset transient state every time the modal is re-opened so a previous+ // refinement doesn't leak into a new session.+ useEffect(() => {+ if (!open) return;+ setFeedback('');+ setRefinedStarter('');+ setRefinedStyle('');+ setRefinedNegative('');+ setRationale('');+ setChanges([]);+ }, [open]);++ // Seed the provider/model picker from the world's stored LLM choice the+ // first time it becomes available — but never clobber an in-flight user+ // selection.+ useEffect(() => {+ if (!open) return;+ if (defaultProviderId && !selectedProviderId) {+ setSelectedProviderId(defaultProviderId);+ if (defaultModel) setSelectedModel(defaultModel);+ }+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [open, defaultProviderId, defaultModel]);++ if (!open) return null;++ const hasResult = refinedStarter !== '' || rationale !== '';+ const canRefine = feedback.trim() && starterPrompt.trim() && selectedProviderId && !refining;+ const canApply = hasResult && refinedStarter.trim();++ const runRefine = async () => {+ if (!canRefine) return;+ setRefining(true);+ setRefinedStarter('');+ setRefinedStyle('');+ setRefinedNegative('');+ setRationale('');+ setChanges([]);+ const result = await refineWorldPrompts({+ starterPrompt,+ stylePrompt,+ negativePrompt,+ feedback: feedback.trim(),+ providerId: selectedProviderId,+ model: selectedModel || undefined,+ }).catch(() => null); // services/apiCore#request already toasts on errors.+ setRefining(false);+ if (!result) return;+ setRefinedStarter(result.starterPrompt || '');+ setRefinedStyle(result.stylePrompt || '');+ setRefinedNegative(result.negativePrompt || '');+ setRationale(result.rationale || '');+ setChanges(Array.isArray(result.changes) ? result.changes : []);+ };++ const handleApply = () => {+ if (!canApply) return;+ onApply({+ starterPrompt: refinedStarter.trim(),+ stylePrompt: refinedStyle.trim(),+ negativePrompt: refinedNegative.trim(),+ });+ toast.success('Refined prompts applied');+ onClose();+ };++ return (+ <div+ className="fixed inset-0 z-[70] bg-black/80 flex items-center justify-center p-4"+ onClick={onClose}+ role="presentation"+ >+ <section+ className="w-full max-w-3xl max-h-[90vh] overflow-hidden bg-port-card border border-port-border rounded-xl shadow-2xl flex flex-col"+ onClick={(e) => e.stopPropagation()}+ role="dialog"+ aria-modal="true"+ aria-labelledby="world-refine-title"+ >+ <header className="flex items-center justify-between gap-3 px-4 py-3 border-b border-port-border">+ <div className="flex items-center gap-2 min-w-0">+ <Sparkles className="w-4 h-4 text-port-accent shrink-0" />+ <h2 id="world-refine-title" className="text-sm font-semibold text-white">+ Refine world prompts+ </h2>+ </div>+ <button+ type="button"+ onClick={onClose}+ className="p-1.5 rounded text-gray-400 hover:text-white hover:bg-port-border/50"+ aria-label="Close"+ >+ <X className="w-4 h-4" />+ </button>+ </header>++ <div className="flex-1 overflow-y-auto p-4 space-y-4">+ <p className="text-xs text-gray-400">+ Describe what you want the world to feel like — story tone, era, art-direction+ references, what to avoid. The LLM rewrites your Starter Idea, Style Prompt, and+ Negative Prompt to match. Review the result before applying.+ </p>++ {/* Originals — collapsed-ish read-only preview so the user remembers+ what's about to change. */}+ <div className="grid grid-cols-1 sm:grid-cols-3 gap-2 text-xs">+ <ReadOnlyField label="Starter idea" value={starterPrompt} />+ <ReadOnlyField label="Style prompt" value={stylePrompt} />+ <ReadOnlyField label="Negative prompt" value={negativePrompt} />+ </div>++ <div>+ <label htmlFor="world-refine-feedback" className="block text-[11px] uppercase tracking-wide text-gray-500 mb-1">+ Feedback+ </label>+ <textarea+ id="world-refine-feedback"+ value={feedback}+ onChange={(e) => setFeedback(e.target.value)}+ placeholder="e.g. lean grimmer and more spiritual; pull style toward Moebius + Tarkovsky; avoid neon and cyberpunk clichés."+ rows={4}+ className="w-full bg-port-bg border border-port-border rounded-lg p-3 text-sm text-white placeholder-gray-500 focus:outline-none focus:border-port-accent resize-y"+ />+ </div>++ <ProviderModelSelector+ providers={providers}+ selectedProviderId={selectedProviderId}+ selectedModel={selectedModel}+ availableModels={availableModels}+ onProviderChange={setSelectedProviderId}+ onModelChange={setSelectedModel}+ label="LLM Provider"+ disabled={providersLoading || refining}+ />++ {providers.length === 0 && !providersLoading && (+ <p className="text-xs text-port-warning">No enabled providers are configured.</p>+ )}++ {!starterPrompt.trim() && (+ <p className="text-xs text-port-warning">+ Add a starter idea on the world first — there's nothing for the LLM to refine.+ </p>+ )}++ <button+ type="button"+ onClick={runRefine}+ disabled={!canRefine}+ className="inline-flex items-center gap-2 px-3 py-2 rounded-lg bg-port-accent text-white text-sm disabled:opacity-50 disabled:cursor-not-allowed hover:opacity-90"+ >+ <Wand2 className="w-4 h-4" />+ {refining ? 'Refining…' : (hasResult ? 'Refine again' : 'Refine prompts')}+ </button>++ {hasResult && (+ <div className="space-y-4">+ {rationale && (+ <p className="text-sm text-gray-300 bg-port-bg border border-port-border rounded-lg p-3">+ {rationale}+ </p>+ )}++ {changes.length > 0 && (+ <ul className="text-xs text-gray-400 list-disc pl-5 space-y-0.5">+ {changes.map((c, idx) => (+ <li key={`${c.slice(0, 24)}-${idx}`}>{c}</li>+ ))}+ </ul>+ )}++ <RefinedTextarea+ label="New starter idea"+ value={refinedStarter}+ onChange={setRefinedStarter}+ rows={3}+ />+ <RefinedTextarea+ label="New style prompt"+ value={refinedStyle}+ onChange={setRefinedStyle}+ rows={4}+ />+ <RefinedTextarea+ label="New negative prompt"+ value={refinedNegative}+ onChange={setRefinedNegative}+ rows={3}+ />+ </div>+ )}+ </div>++ <footer className="flex items-center justify-end gap-2 px-4 py-3 border-t border-port-border">+ <button+ type="button"+ onClick={onClose}+ className="px-3 py-2 rounded-lg text-sm text-gray-300 hover:text-white hover:bg-port-border/50"+ >+ Cancel+ </button>+ <button+ type="button"+ onClick={handleApply}+ disabled={!canApply}+ className="inline-flex items-center gap-2 px-3 py-2 rounded-lg bg-port-success text-white text-sm disabled:opacity-50 disabled:cursor-not-allowed hover:opacity-90"+ >+ <Check className="w-4 h-4" />+ Apply to world+ </button>+ </footer>+ </section>+ </div>+ );+}++function ReadOnlyField({ label, value }) {+ return (+ <div className="bg-port-bg border border-port-border rounded p-2">+ <div className="text-[10px] uppercase tracking-wide text-gray-500 mb-1">{label}</div>+ <div className="text-[11px] text-gray-300 line-clamp-4 whitespace-pre-wrap">+ {value?.trim() ? value : <span className="text-gray-600">(empty)</span>}+ </div>+ </div>+ );+}++function RefinedTextarea({ label, value, onChange, rows }) {+ return (+ <div>+ <label className="block text-[11px] uppercase tracking-wide text-gray-500 mb-1">{label}</label>+ <textarea+ value={value}+ onChange={(e) => onChange(e.target.value)}+ rows={rows}+ className="w-full bg-port-bg border border-port-border rounded-lg p-3 text-sm text-white focus:outline-none focus:border-port-accent resize-y"+ />+ </div>+ );+}diff --git a/client/src/pages/WorldBuilder.jsx b/client/src/pages/WorldBuilder.jsxindex 525d85292a..fa9b850e77 100644--- a/client/src/pages/WorldBuilder.jsx+++ b/client/src/pages/WorldBuilder.jsx@@ -11,7 +11,7 @@ import { useEffect, useMemo, useState } from 'react';import { Link } from 'react-router-dom';import {Globe2, Plus, Trash2, Sparkles, Wand2, Loader2, Save, FolderOpen,- Edit3, X,+ Edit3, X, MessageSquarePlus, Play,} from 'lucide-react';import toast from '../components/ui/Toast';import {@@ -22,6 +22,7 @@ import {import BackendChipStrip from '../components/media/BackendChipStrip';import ImageGenControls from '../components/imageGen/ImageGenControls';import { deriveAvailableBackends, IMAGE_GEN_MODE } from '../lib/imageGenBackends';+import WorldPromptRefineModal from '../components/worldBuilder/WorldPromptRefineModal';const CATEGORY_LABELS = {landscapes: 'Landscapes',@@ -132,6 +133,8 @@ export default function WorldBuilder() {// CLAUDE.md UI Patterns.const [pendingDeleteId, setPendingDeleteId] = useState(null);+ const [refineOpen, setRefineOpen] = useState(false);+const refresh = async () => {setLoading(true);const [list, provData, models, settings] = await Promise.all([@@ -296,16 +299,56 @@ export default function WorldBuilder() {toast.success(`Expanded into ${total} variations and ${expandedDraft.compositeSheets?.length || 0} boards — review then Save`);};- const handleRender = async () => {+ // Writes the LLM-refined starter/style/negative back to the draft. Mirrors+ // handleExpand's auto-save: if the world is already persisted, persist the+ // refinement immediately so subsequent renders/expansions see it on disk.+ const applyRefinement = async ({ starterPrompt, stylePrompt, negativePrompt }) => {+ const next = {+ ...draft,+ starterPrompt: starterPrompt ?? draft.starterPrompt,+ stylePrompt: stylePrompt ?? draft.stylePrompt,+ negativePrompt: negativePrompt ?? draft.negativePrompt,+ };+ setDraft(next);+ if (selectedId && next.name?.trim()) {+ const updated = await updateWorld(selectedId, {+ name: next.name.trim(),+ starterPrompt: next.starterPrompt || '',+ stylePrompt: next.stylePrompt || '',+ negativePrompt: next.negativePrompt || '',+ categories: next.categories,+ compositeSheets: next.compositeSheets || [],+ llm: next.llm || {},+ }).catch((e) => { toast.error(`Auto-save after refine failed: ${e.message}`); return null; });+ if (updated) {+ setWorlds((prev) => {+ const without = prev.filter((w) => w.id !== updated.id);+ return [updated, ...without];+ });+ }+ }+ };++ // Render either the full batch (driven by the renderOpts.promptMode dropdown)+ // or a narrow scope passed in by an inline button. Scope shape:+ // { promptMode, selection?, sheetSelection? } — see server renderSchema.+ const runRender = async (scope = null) => {if (!selectedId) {toast.error('Save the world first');return;}- const total = renderPromptCount(draft, renderOpts.promptMode);+ const promptMode = scope?.promptMode || renderOpts.promptMode || 'variations';+ const total = scope+ ? scopedPromptCount(draft, scope)+ : renderPromptCount(draft, promptMode);if (!total) {toast.error('No prompts — expand the template first');return;}+ if (availableBackends.length === 0) {+ toast.error('Configure an image-gen backend first');+ return;+ }const effectiveMode = renderOpts.mode || defaultMode || undefined;const numericOrUndef = (v) => {if (v === '' || v == null) return undefined;@@ -322,8 +365,10 @@ export default function WorldBuilder() {guidance: numericOrUndef(renderOpts.guidance),cfgScale: numericOrUndef(renderOpts.cfgScale),quantize: renderOpts.quantize || undefined,- promptMode: renderOpts.promptMode || 'variations',+ promptMode,batchPerVariation: renderOpts.batchPerVariation,+ selection: scope?.selection,+ sheetSelection: scope?.sheetSelection,}).catch((e) => { toast.error(`Render failed: ${e.message}`); return null; });setRendering(false);if (!result) return;@@ -332,6 +377,10 @@ export default function WorldBuilder() {setRuns(updated);};+ const handleRender = () => runRender(null);++ const canRender = !!selectedId && availableBackends.length > 0 && !rendering;+const updateDraft = (patch) => setDraft((d) => ({ ...d, ...patch }));const updateCategory = (cat, variations) => setDraft((d) => ({...d,@@ -504,12 +553,32 @@ export default function WorldBuilder() {{expanding ? <Loader2 size={16} className="animate-spin" /> : <Wand2 size={16} />}Expand starter → variations</button>+ <button+ onClick={() => setRefineOpen(true)}+ disabled={!draft.starterPrompt?.trim()}+ className="px-3 py-2 bg-port-accent/15 hover:bg-port-accent/25 disabled:opacity-50 text-port-accent border border-port-accent/40 rounded flex items-center gap-2 min-h-[40px]"+ title="Give feedback to refine the Starter Idea, Style Prompt, and Negative Prompt"+ >+ <MessageSquarePlus size={16} />+ Refine prompts+ </button><span className="text-xs text-gray-500">{totalVariations} variation{totalVariations === 1 ? '' : 's'} across {categoryKeys.length} categories · {totalSheets} composite board{totalSheets === 1 ? '' : 's'}</span></div></header>+ <WorldPromptRefineModal+ open={refineOpen}+ onClose={() => setRefineOpen(false)}+ onApply={applyRefinement}+ starterPrompt={draft.starterPrompt || ''}+ stylePrompt={draft.stylePrompt || ''}+ negativePrompt={draft.negativePrompt || ''}+ defaultProviderId={draft.llm?.provider || activeProviderId || null}+ defaultModel={draft.llm?.model || null}+ />+{/* Style template */}<section className="bg-port-card border border-port-border rounded p-4 grid grid-cols-1 md:grid-cols-2 gap-3"><div>@@ -541,6 +610,8 @@ export default function WorldBuilder() {<CompositeSheetsEditorsheets={draft.compositeSheets || []}onChange={updateCompositeSheets}+ canRender={canRender}+ onRender={(sheet) => runRender({ promptMode: 'sheets', sheetSelection: [sheet.label] })}/>{/* Categories */}@@ -578,6 +649,9 @@ export default function WorldBuilder() {canRemove={!WORLD_CATEGORIES.includes(cat)}onChange={(next) => updateCategory(cat, next)}onRemove={() => removeCategory(cat)}+ canRender={canRender}+ onRenderCategory={() => runRender({ promptMode: 'variations', selection: { [cat]: 'all' } })}+ onRenderVariation={(v) => runRender({ promptMode: 'variations', selection: { [cat]: [v.label] } })}/>))}</section>@@ -703,7 +777,29 @@ function renderPromptCount(world, promptMode = 'variations') {return variations;}-function CompositeSheetsEditor({ sheets, onChange }) {+// Mirrors the server's compilePrompts for selection/sheetSelection so an inline+// "Render" button can disable itself + show an accurate count without a round trip.+function scopedPromptCount(world, scope) {+ if (!scope) return 0;+ if (scope.promptMode === 'sheets') {+ const sheets = world.compositeSheets || [];+ if (scope.sheetSelection === 'all' || !scope.sheetSelection) return sheets.length;+ const set = new Set(scope.sheetSelection);+ return sheets.filter((s) => set.has(s.label)).length;+ }+ // variations+ if (!scope.selection) return 0;+ let n = 0;+ for (const [cat, pick] of Object.entries(scope.selection)) {+ const vars = world.categories?.[cat]?.variations || [];+ if (pick === 'all') { n += vars.length; continue; }+ const labels = new Set(pick);+ n += vars.filter((v) => labels.has(v.label)).length;+ }+ return n;+}++function CompositeSheetsEditor({ sheets, onChange, canRender = false, onRender = null }) {const [adding, setAdding] = useState(false);const [newKind, setNewKind] = useState('reference_sheet');const [newLabel, setNewLabel] = useState('');@@ -854,6 +950,16 @@ function CompositeSheetsEditor({ sheets, onChange }) {<div className="text-xs text-gray-400 line-clamp-3">{sheet.prompt}</div></div><div className="flex items-center gap-1 shrink-0">+ {onRender && (+ <button+ onClick={() => onRender(sheet)}+ disabled={!canRender}+ className="p-1 text-gray-400 hover:text-port-accent disabled:opacity-30 disabled:cursor-not-allowed rounded"+ title={canRender ? 'Render this board' : 'Save the world and configure a render backend to enable'}+ >+ <Play size={14} />+ </button>+ )}<buttononClick={() => startEdit(idx, sheet)}className="p-1 text-gray-400 hover:text-port-accent rounded"@@ -879,7 +985,10 @@ function CompositeSheetsEditor({ sheets, onChange }) {);}-function CategoryEditor({ category, variations, canRemove = false, onChange, onRemove }) {+function CategoryEditor({+ category, variations, canRemove = false, onChange, onRemove,+ canRender = false, onRenderCategory = null, onRenderVariation = null,+}) {const [adding, setAdding] = useState(false);const [newLabel, setNewLabel] = useState('');const [newPrompt, setNewPrompt] = useState('');@@ -926,6 +1035,16 @@ function CategoryEditor({ category, variations, canRemove = false, onChange, onR<span className="ml-2 text-xs text-gray-500">{variations.length}</span></h3><div className="flex items-center gap-1">+ {onRenderCategory && (+ <button+ onClick={onRenderCategory}+ disabled={!canRender || variations.length === 0}+ className="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 flex items-center gap-1 min-h-[40px] sm:min-h-0"+ title={variations.length === 0 ? 'Add variations first' : 'Render this category'}+ >+ <Play size={12} /> Render+ </button>+ )}{canRemove && (<buttononClick={onRemove}@@ -1010,6 +1129,16 @@ function CategoryEditor({ category, variations, canRemove = false, onChange, onR<div className="text-xs text-gray-400 line-clamp-2">{v.prompt}</div></div><div className="flex items-center gap-1 shrink-0">+ {onRenderVariation && (+ <button+ onClick={() => onRenderVariation(v)}+ disabled={!canRender}+ className="p-1 text-gray-400 hover:text-port-accent disabled:opacity-30 disabled:cursor-not-allowed rounded"+ title={canRender ? 'Render this variation' : 'Save the world and configure a render backend to enable'}+ >+ <Play size={14} />+ </button>+ )}<buttononClick={() => startEdit(idx, v)}className="p-1 text-gray-400 hover:text-port-accent rounded"diff --git a/client/src/services/apiWorldBuilder.js b/client/src/services/apiWorldBuilder.jsindex 12c12274bf..47f809d089 100644--- a/client/src/services/apiWorldBuilder.js+++ b/client/src/services/apiWorldBuilder.js@@ -26,6 +26,13 @@ export const expandWorld = ({ starterPrompt, providerId, model } = {}) => requesbody: JSON.stringify({ starterPrompt, providerId, model }),});+export const refineWorldPrompts = ({+ starterPrompt, stylePrompt, negativePrompt, feedback, providerId, model,+} = {}) => request('/world-builder/refine-prompts', {+ method: 'POST',+ body: JSON.stringify({ starterPrompt, stylePrompt, negativePrompt, feedback, providerId, model }),+});+export const renderWorld = (id, options) => request(`/world-builder/${encodeURIComponent(id)}/render`, {method: 'POST',body: JSON.stringify(options || {}),diff --git a/server/routes/worldBuilder.js b/server/routes/worldBuilder.jsindex 463fe0ef56..c58b75da30 100644--- a/server/routes/worldBuilder.js+++ b/server/routes/worldBuilder.js@@ -18,6 +18,7 @@ import { asyncHandler, ServerError } from '../lib/errorHandler.js';import { validateRequest } from '../lib/validation.js';import * as svc from '../services/worldBuilder.js';import { expandWorldTemplate } from '../services/worldBuilderExpand.js';+import { refineWorldPrompts } from '../services/worldBuilderRefine.js';import { enqueueJob } from '../services/mediaJobQueue/index.js';import { getSettings } from '../services/settings.js';import { createCollection, NAME_MAX_LENGTH as COLLECTION_NAME_MAX } from '../services/mediaCollections.js';@@ -87,6 +88,21 @@ const expandSchema = z.object({model: z.string().trim().max(200).optional(),});+const refinePromptsSchema = z.object({+ starterPrompt: z.string().trim().min(1).max(svc.STARTER_PROMPT_MAX),+ stylePrompt: z.string().trim().max(svc.PROMPT_FRAGMENT_MAX).optional().default(''),+ negativePrompt: z.string().trim().max(svc.PROMPT_FRAGMENT_MAX).optional().default(''),+ feedback: z.string().trim().min(1).max(3000),+ providerId: z.string().trim().max(80).optional(),+ // Whitespace-only model → undefined so the refiner's defaultModel /+ // models[0] fallback kicks in instead of a blank string reaching the+ // provider. Mirrors how /api/media-jobs/refine-prompt handles it.+ model: z.string().max(200).optional().transform((s) => {+ const v = (s ?? '').trim();+ return v.length > 0 ? v : undefined;+ }),+});+// `selection` per category: 'all' or array of variation labels.const selectionValueSchema = z.union([z.literal('all'), z.array(z.string().trim().min(1).max(svc.VARIATION_LABEL_MAX)).max(svc.VARIATIONS_PER_CATEGORY_MAX)]);const selectionSchema = z.record(@@ -134,6 +150,14 @@ router.post('/expand', asyncHandler(async (req, res) => {res.json(result);}));+// Refines the 3 top-level prompts (starter / style / negative) based on+// user feedback. Stateless — the caller decides whether to write the+// result back to a saved world. Keep ahead of `/:id`.+router.post('/refine-prompts', asyncHandler(async (req, res) => {+ const body = validateRequest(refinePromptsSchema, req.body ?? {});+ res.json(await refineWorldPrompts(body));+}));+router.get('/:id', asyncHandler(async (req, res) => {const w = await svc.getWorld(req.params.id).catch((err) => { throw mapServiceError(err); });res.json(w);diff --git a/server/services/worldBuilderRefine.js b/server/services/worldBuilderRefine.jsnew file mode 100644index 0000000000..4c3e5dbaf4--- /dev/null+++ b/server/services/worldBuilderRefine.js@@ -0,0 +1,242 @@+/**+ * World Builder — refine the 3 top-level prompts (starter idea, style prompt,+ * negative prompt) based on user feedback. Mirrors the media prompt-refine+ * flow (see `mediaPromptRefiner.js`) but operates on a world template rather+ * than an individual render.+ *+ * The LLM gets the originals + a free-form feedback string and returns:+ * { starterPrompt, stylePrompt, negativePrompt, rationale, changes? }+ *+ * The caller (route → UI) presents the refined fields for review before they+ * overwrite the draft, so the LLM never silently mutates a saved world.+ */++import { ServerError } from '../lib/errorHandler.js';+import { getActiveProvider, getProviderById } from './providers.js';+import { createRun, executeApiRun, executeCliRun } from './runner.js';+import {+ PROMPT_FRAGMENT_MAX,+ STARTER_PROMPT_MAX,+} from './worldBuilder.js';++const MAX_FEEDBACK = 3000;+const MAX_RATIONALE = 1200;+const MAX_CHANGES = 8;++const trimTo = (value, max) =>+ typeof value === 'string' ? value.trim().slice(0, max) : '';++const cleanChanges = (changes) => (+ Array.isArray(changes)+ ? changes.map((c) => trimTo(c, 240)).filter(Boolean).slice(0, MAX_CHANGES)+ : []+);++// Same brace-walker as mediaPromptRefiner: Codex CLI echoes the prompt to+// stdout before the model response, and the prompt itself contains a JSON+// schema example whose braces balance but whose contents are placeholder+// text. Walk every brace-balanced block in order and return the first that+// looks like a refinement payload (object with a `starterPrompt` string).+const isPlaceholder = (s) => typeof s === 'string' && /^\s*<.+>\s*$/.test(s);++function extractRefinementJson(raw) {+ if (typeof raw !== 'string' || !raw.trim()) throw new Error('Empty AI response');+ let s = raw.trim();+ const fence = s.match(/```(?:json)?\s*([\s\S]*?)```/);+ if (fence) s = fence[1].trim();++ let i = 0;+ let lastErr;+ let placeholderSeen = false;+ while (i < s.length) {+ const start = s.indexOf('{', i);+ if (start === -1) break;+ let depth = 0;+ let inString = false;+ let escaped = false;+ let end = -1;+ for (let j = start; j < s.length; j += 1) {+ const ch = s[j];+ if (inString) {+ if (escaped) escaped = false;+ else if (ch === '\\') escaped = true;+ else if (ch === '"') inString = false;+ continue;+ }+ if (ch === '"') { inString = true; continue; }+ if (ch === '{') depth += 1;+ else if (ch === '}') {+ depth -= 1;+ if (depth === 0) { end = j; break; }+ }+ }+ if (end === -1) break;+ const block = s.slice(start, end + 1);+ try {+ const value = JSON.parse(block);+ if (value && typeof value === 'object' && typeof value.starterPrompt === 'string') {+ if (isPlaceholder(value.starterPrompt)) { placeholderSeen = true; }+ else return value;+ }+ } catch (e) { lastErr = e; }+ i = end + 1;+ }+ if (placeholderSeen) {+ throw new Error('AI returned the schema placeholder instead of a real refinement — try a stronger model or rerun');+ }+ throw new Error(`Invalid JSON in AI response${lastErr ? `: ${lastErr.message}` : ''}`);+}++export function buildWorldRefinePrompt({ starterPrompt, stylePrompt, negativePrompt, feedback }) {+ return `You are a senior world-building prompt editor for a Stable-Diffusion-style image-generation pipeline.++The user has three top-level prompts that define a "world": a STARTER IDEA (the high-concept seed), a STYLE PROMPT (visual style fragment prepended to every render — palette, lighting, render quality, artist references), and a NEGATIVE PROMPT (tokens to avoid). They have given feedback about the story concept, mood, style, design, or any aspect of the world they want refined.++Rewrite all three prompts so they more faithfully express the user's intention. Output the COMPLETE rewritten text for each — not a placeholder, not a summary, not a diff.++Return ONLY valid JSON in this schema (replace every <…> with real content; do NOT output the literal angle-bracket text):+{+ "starterPrompt": "<full rewritten high-concept starter idea, 1-3 sentences, ready to feed back into the world expander>",+ "stylePrompt": "<full rewritten style fragment, comma-separated tokens, no subject nouns — palette, lighting, render quality, artist references>",+ "negativePrompt": "<full rewritten negative prompt, comma-separated tokens to avoid; empty string if none>",+ "rationale": "<one concise sentence explaining the overall edit>",+ "changes": ["<short bullet of what changed and why>"]+}++Rules:+- Preserve story/character/world DNA from the originals unless the user's feedback explicitly contradicts it.+- The "starterPrompt" should remain a seed — the high-concept hook the world expander will fan out into categories. Do not list category content (landscapes, factions, etc.) here.+- The "stylePrompt" must be comma-separated visual-style tokens only. No subject nouns. No camera/aspect tokens. Under 400 characters.+- The "negativePrompt" must be comma-separated tokens. If the world relies on text/typography (e.g. pitch posters), avoid putting "text" in negatives — prefer "watermark, logo, unreadable tiny text, text artifacts".+- Apply the user's feedback decisively. If they ask for a different style/mood/era, move toward it in the style prompt AND name the things to avoid in the negative prompt.+- The "starterPrompt" field must NEVER equal the schema placeholder text — it must be the actual rewritten seed.++ORIGINAL STARTER IDEA:+${starterPrompt || '(empty)'}++ORIGINAL STYLE PROMPT:+${stylePrompt || '(empty)'}++ORIGINAL NEGATIVE PROMPT:+${negativePrompt || '(empty)'}++USER FEEDBACK:+${feedback}`;+}++// CLI providers (codex/claude-code/gemini-cli) need provider-specific arg+// shapes that the toolkit runner already knows about — going through the+// runner avoids the "stdin is not a terminal" failure mode that hits when+// you spawn `codex` directly without the `exec -` invocation.+async function runRefine(provider, model, prompt) {+ const { runId } = await createRun({+ providerId: provider.id,+ model,+ prompt,+ source: 'world-builder-refine',+ });++ let text = '';+ return new Promise((resolve, reject) => {+ const onData = (chunk) => { text += typeof chunk === 'string' ? chunk : (chunk?.text || ''); };+ const onComplete = (result) => {+ if (result?.error || result?.success === false) {+ reject(new ServerError(result?.error || 'World refinement failed', { status: 502, code: 'WORLD_REFINE_FAILED' }));+ } else {+ resolve({ text, runId });+ }+ };+ if (provider.type === 'cli') {+ // Mirror the media refiner: only Codex's `buildCliArgs` honors a per-call+ // model override today, so don't lie about which model ran for the others.+ const canOverrideModel = provider.id === 'codex';+ const providerForCli = canOverrideModel && model && model !== provider.defaultModel+ ? { ...provider, defaultModel: model }+ : provider;+ executeCliRun(runId, providerForCli, prompt, process.cwd(), onData, onComplete, provider.timeout ?? 300000).catch(reject);+ } else {+ executeApiRun(runId, provider, model, prompt, process.cwd(), [], onData, onComplete).catch(reject);+ }+ });+}++/**+ * Refine the 3 top-level world prompts.+ *+ * @param {object} args+ * @param {string} args.starterPrompt — original+ * @param {string} [args.stylePrompt] — original (may be empty)+ * @param {string} [args.negativePrompt] — original (may be empty)+ * @param {string} args.feedback — required user feedback+ * @param {string} [args.providerId] — overrides the active provider+ * @param {string} [args.model] — overrides the provider's default model+ */+export async function refineWorldPrompts({+ starterPrompt,+ stylePrompt = '',+ negativePrompt = '',+ feedback,+ providerId,+ model,+} = {}) {+ if (!feedback || !feedback.trim()) {+ throw new ServerError('Feedback is required', { status: 400, code: 'FEEDBACK_REQUIRED' });+ }+ if (!starterPrompt || !starterPrompt.trim()) {+ throw new ServerError('Starter prompt is required to refine', { status: 400, code: 'STARTER_REQUIRED' });+ }++ let provider = providerId ? await getProviderById(providerId).catch(() => null) : null;+ if (!provider) provider = await getActiveProvider();+ if (!provider) {+ throw new ServerError('No AI provider available for world refinement', { status: 400, code: 'NO_PROVIDER' });+ }+ if (provider.enabled === false) {+ throw new ServerError(+ `Provider "${provider.name || provider.id}" is disabled — enable it in Settings → Providers first`,+ { status: 400, code: 'PROVIDER_DISABLED' },+ );+ }++ const honorsModelOverride = provider.type === 'api' || provider.id === 'codex';+ const selectedModel = honorsModelOverride+ ? (model || provider.defaultModel || provider.models?.[0] || '')+ : (provider.defaultModel || provider.models?.[0] || '');+ if (!selectedModel && provider.type === 'api') {+ throw new ServerError('Model is required for world refinement', { status: 400, code: 'MODEL_REQUIRED' });+ }++ const llmPrompt = buildWorldRefinePrompt({+ starterPrompt: trimTo(starterPrompt, STARTER_PROMPT_MAX),+ stylePrompt: trimTo(stylePrompt, PROMPT_FRAGMENT_MAX),+ negativePrompt: trimTo(negativePrompt, PROMPT_FRAGMENT_MAX),+ feedback: trimTo(feedback, MAX_FEEDBACK),+ });++ const { text, runId } = await runRefine(provider, selectedModel, llmPrompt);++ let parsed;+ try {+ parsed = extractRefinementJson(text || '');+ } catch (e) {+ console.warn(`⚠️ world-refine [${provider.id}/${selectedModel || 'default'} runId=${runId}] parse failed: ${e.message} (response size: ${(text || '').length} chars)`);+ throw new ServerError(e.message, { status: 502, code: 'WORLD_REFINE_BAD_JSON' });+ }++ const refinedStarter = trimTo(parsed.starterPrompt, STARTER_PROMPT_MAX);+ if (!refinedStarter) {+ throw new ServerError('LLM returned an empty starter prompt', { status: 502, code: 'WORLD_REFINE_EMPTY_STARTER' });+ }++ return {+ starterPrompt: refinedStarter,+ stylePrompt: trimTo(parsed.stylePrompt, PROMPT_FRAGMENT_MAX),+ negativePrompt: trimTo(parsed.negativePrompt, PROMPT_FRAGMENT_MAX),+ rationale: trimTo(parsed.rationale, MAX_RATIONALE),+ changes: cleanChanges(parsed.changes),+ providerId: provider.id,+ model: selectedModel,+ };+}++export const __testing = { extractRefinementJson, buildWorldRefinePrompt };diff --git a/server/services/worldBuilderRefine.test.js b/server/services/worldBuilderRefine.test.jsnew file mode 100644index 0000000000..c16a123995--- /dev/null+++ b/server/services/worldBuilderRefine.test.js@@ -0,0 +1,87 @@+import { describe, it, expect } from 'vitest';+import { __testing } from './worldBuilderRefine.js';++const { extractRefinementJson, buildWorldRefinePrompt } = __testing;++describe('worldBuilderRefine.extractRefinementJson', () => {+ it('parses a raw refinement object', () => {+ const obj = {+ starterPrompt: 'a darker scavenger world',+ stylePrompt: 'gritty palette, deep shadows',+ negativePrompt: 'cute, neon',+ rationale: 'pushed mood toward grim',+ };+ expect(extractRefinementJson(JSON.stringify(obj))).toEqual(obj);+ });++ it('strips ```json fences', () => {+ const fenced = '```json\n{"starterPrompt":"x","stylePrompt":"y","negativePrompt":""}\n```';+ expect(extractRefinementJson(fenced)).toMatchObject({ starterPrompt: 'x', stylePrompt: 'y' });+ });++ it('skips preamble before the JSON', () => {+ const raw = 'Here is the refinement:\n{"starterPrompt":"x","stylePrompt":"y"}\nend';+ expect(extractRefinementJson(raw)).toMatchObject({ starterPrompt: 'x' });+ });++ it('skips a schema-example block that has a <…> placeholder starterPrompt and parses the real block (Codex CLI prompt echo)', () => {+ const raw = [+ 'codex banner',+ // The prompt template body — its first balanced { ... } block contains+ // <…> placeholders that walked past extractRefinementJson by mistake+ // would surface as "AI returned schema placeholder" instead of finding+ // the real response below it.+ '{"starterPrompt":"<full rewritten…>","stylePrompt":"<…>","negativePrompt":"<…>"}',+ 'codex response:',+ '{"starterPrompt":"a darker world","stylePrompt":"gritty","negativePrompt":""}',+ ].join('\n');+ const out = extractRefinementJson(raw);+ expect(out.starterPrompt).toBe('a darker world');+ expect(out.stylePrompt).toBe('gritty');+ });++ it('throws when ONLY schema-placeholder blocks are present', () => {+ const raw = '{"starterPrompt":"<placeholder>","stylePrompt":"<x>"}';+ expect(() => extractRefinementJson(raw)).toThrow(/schema placeholder/);+ });++ it('throws on empty / non-string input', () => {+ expect(() => extractRefinementJson('')).toThrow(/Empty AI response/);+ expect(() => extractRefinementJson(null)).toThrow(/Empty AI response/);+ });++ it('throws when no balanced JSON object with starterPrompt is present', () => {+ expect(() => extractRefinementJson('just prose, no json')).toThrow(/Invalid JSON/);+ expect(() => extractRefinementJson('{"prompt":"unrelated shape"}')).toThrow(/Invalid JSON/);+ });+});++describe('worldBuilderRefine.buildWorldRefinePrompt', () => {+ it('includes all three originals + feedback verbatim', () => {+ const out = buildWorldRefinePrompt({+ starterPrompt: 'moebius scavengers',+ stylePrompt: 'comic ink, dust palette',+ negativePrompt: 'lowres',+ feedback: 'lean grimmer and more spiritual',+ });+ expect(out).toContain('moebius scavengers');+ expect(out).toContain('comic ink, dust palette');+ expect(out).toContain('lowres');+ expect(out).toContain('lean grimmer and more spiritual');+ // Schema must mention the three output keys so the LLM can comply.+ expect(out).toContain('"starterPrompt"');+ expect(out).toContain('"stylePrompt"');+ expect(out).toContain('"negativePrompt"');+ });++ it('substitutes (empty) for missing originals so the LLM sees the slot', () => {+ const out = buildWorldRefinePrompt({+ starterPrompt: 'seed',+ stylePrompt: '',+ negativePrompt: '',+ feedback: 'go dark',+ });+ expect(out).toMatch(/ORIGINAL STYLE PROMPT:\n\(empty\)/);+ expect(out).toMatch(/ORIGINAL NEGATIVE PROMPT:\n\(empty\)/);+ });+});