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): full image-gen knob set on batch render + harden Codex JSON expansion
Adam Eivy6a56aee3b772
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 2c9a903b44..1055e59529 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -9,6 +9,7 @@## Fixed+- **World Builder expansion no longer 0-variations on Codex CLI responses.** The expand-starter step had three failure modes against Codex's CLI provider that all manifested as "Expanded into 0 variations": (1) Codex echoes the user prompt back to stdout before the model's reply, and the prompt itself contains a JSON-shaped *schema example* (`{ "label": string (max 80 chars), "prompt": … }`) — its braces balance but its contents are not valid JSON, so the previous first-balanced-block extractor crashed on it; (2) Codex occasionally emits an orphan `}` between a variation's close-brace and the array's `]` (`…blister"}}]}}}`), making `JSON.parse` throw on otherwise-recoverable output; (3) some prompt variants embed small literal `{ "label": …, "prompt": … }` example variations that parse cleanly but are not the response, so the extractor would happily return the wrong object. `extractJson` now (a) walks every top-level brace-balanced block and tries each in order, (b) prefers a block that has any of `stylePrompt` / `negativePrompt` / `categories` at the top level over an example-shaped one, and (c) attempts cheap repairs for trailing commas and the orphan-brace `}}]` → `}]` corruption before giving up. The expand path also logs the toolkit `runId` plus per-category variation counts so a 0-variation outcome is debuggable from `data/runs/<id>/output.txt`. Four new tests cover the Codex prompt-echo, orphan-brace, trailing-comma, and shape-preference cases.- **CoS review-loop tasks now actually loop until clean and merge the PR.** Previously, scheduled or user tasks running with worktree + openPR + reviewLoop only fired one Copilot review request and stopped — the worktree got cleaned up immediately, the PR sat with whatever feedback Copilot returned, and nothing addressed comments or merged. The fix adds a follow-up internal task that the original cleanup hook spawns once the PR is open and the initial Copilot review has been requested. The follow-up agent attaches a fresh worktree to the PR branch (via a new `existingBranch` option on `createWorktree`), runs the full `/do:rpr`-style poll/fix/push/re-request loop until Copilot returns zero unresolved comments (or hits a 10-iteration guardrail), then merges the PR with `gh pr merge --squash --auto --delete-branch`. The follow-up's own cleanup pass passes `skipMerge: true` so the worktree branch isn't re-merged locally on top of the squash-merge gh just executed. GitLab MRs and other non-GitHub forges still skip the loop entirely (Copilot reviewer is GitHub-only). See `server/services/agentLifecycle.js` (`spawnReviewLoopFollowUp`) and `server/services/agentPromptBuilder.js` (`reviewLoopFollowUpSection`).- **Dashboard form input no longer wipes when rotating between portrait and landscape.** `DashboardGrid` was returning two structurally different render trees on either side of the 640px breakpoint — a flat `<div className="space-y-4">` on mobile and a relative-positioned absolute-grid wrapper on desktop. Crossing the breakpoint (which happens any time you rotate an iPhone, since portrait ~390px is below it and landscape ~844px is above) put the widget at a different DOM depth, so React unmounted every widget and remounted a new one — taking any in-progress `useState` value with it. The Quick Capture text field reset to empty mid-typing. The grid now uses a single render tree across both modes, toggling only `className`/`style` between flow and absolute layouts. Widget components keep their state across rotation.- **Toast notifications and the eye-exam form no longer overflow on mobile.** The agent-feedback toast had a hard `w-[480px]` when expanded that overflowed past the right edge of a 375px viewport, and the global toast container's `max-w-[520px]` could similarly extend past the screen on narrow viewports. Both now cap at `calc(100vw - 2rem)` on mobile and switch to their full width at the `sm:` breakpoint (640px+). The eye-exam editor on MeatSpace → Body was also unusable on mobile — its `grid-cols-7` layout squeezed seven number inputs into ~42px each at 375px wide; it now reflows to two columns on mobile (with the date field full-width), four on tablet, seven on desktop.@@ -17,4 +18,5 @@## Changed+- **World Builder batch-render form gains the full Image Gen knob set.** The `/media/world-builder` Batch render panel previously exposed only Width / Height / Steps / CFG / Per-variation, and a backend dropdown limited to "Local (mflux)" / "Codex". It now reuses the same controls as the standalone Image Gen page via a new shared `client/src/components/imageGen/ImageGenControls` component: Model picker (auto-populated from `listImageModels`), resolution presets (extracted into `client/src/lib/imageGenResolutions.js` so both pages stay in lockstep), Steps, Guidance, CFG Scale (external mode), Quantize (mflux), plus a `BackendChipStrip` that mirrors Image Gen's chip-style selector and hides external SD-API (which the batch path can't drive). The `/api/world-builder/:id/render` route accepts the new `quantize` field. Successful expansion now auto-saves the world if it already has a name, so clicking "Render" right after "Expand starter → variations" no longer trips "No prompts to render" on a stale on-disk copy.- **Browser downloads default to `~/Downloads`.** The CDP browser previously sent downloads to `data/browser-downloads/` inside the project; it now writes to the OS-native user Downloads directory (`~/Downloads` on macOS/Linux, `C:\Users\<u>\Downloads` on Windows) via `os.homedir()`. Both the keep-alive `Browser.setDownloadBehavior` call in `browser/server.js` and `PATHS.browserDownloads` in `server/lib/fileUtils.js` were updated so the Browser page UI's listing/delete operations stay in sync with where Chrome actually writes. Existing installs without an explicit `downloadDir` in `data/browser-config.json` pick up the new location automatically; users who want the old behavior can pin it by setting `downloadDir` in that config file.diff --git a/client/src/components/imageGen/ImageGenControls.jsx b/client/src/components/imageGen/ImageGenControls.jsxnew file mode 100644index 0000000000..c470b2390e--- /dev/null+++ b/client/src/components/imageGen/ImageGenControls.jsx@@ -0,0 +1,172 @@+// Shared image-gen knob grid. Renders model + resolution + steps + guidance/CFG ++// quantize + (optional) seed in a 2- or 3-column grid that matches the standalone+// Image Gen page. Used by ImageGen and World Builder batch render so the form+// looks and behaves the same in both places.+//+// Props are intentionally per-field (value + onChange pairs) rather than a single+// `value` object so callers can keep using their existing useState fields without+// reshaping. `mode` drives which knobs are visible: codex hides everything except+// resolution; external swaps guidance for cfgScale; local shows guidance + quantize.++import { Dice5 } from 'lucide-react';+import { RESOLUTIONS, findResolution } from '../../lib/imageGenResolutions';+import { randomSeed } from '../../lib/genUtils';++const QUANTIZE_OPTIONS = [+ { value: '3', label: '3-bit' },+ { value: '4', label: '4-bit (fast)' },+ { value: '5', label: '5-bit' },+ { value: '6', label: '6-bit' },+ { value: '8', label: '8-bit (default)' },+];++export default function ImageGenControls({+ mode,+ models = [],+ modelId, onModelChange,+ width, height, onResolutionChange,+ steps, onStepsChange,+ guidance, onGuidanceChange,+ cfgScale, onCfgScaleChange,+ quantize, onQuantizeChange,+ seed, onSeedChange,+ showSeed = false,+ showQuantize = true,+ showModel = true,+ disabled = false,+ // Optional column override — defaults to 2/3 like the Image Gen page.+ // Pass e.g. "grid-cols-2 sm:grid-cols-4" to fit a denser layout.+ className = 'grid grid-cols-2 sm:grid-cols-3 gap-3',+}) {+ const isLocal = mode === 'local';+ const isCodex = mode === 'codex';++ const currentModel = models.find((m) => m.id === modelId);+ const isFlux2 = currentModel?.runner === 'flux2';++ const matched = findResolution(width, height);+ const resolutionLabel = matched?.label || (width && height ? `${width}×${height}` : '');+ const handleResolution = (e) => {+ const r = RESOLUTIONS.find((opt) => opt.label === e.target.value);+ if (r) onResolutionChange?.(r.w, r.h);+ };++ const inputCls = 'w-full bg-port-bg border border-port-border rounded-lg px-2 py-2 text-sm text-white focus:outline-none focus:border-port-accent disabled:opacity-50';++ return (+ <div className={className}>+ {showModel && isLocal && models.length > 0 && (+ <div>+ <label className="block text-xs font-medium text-gray-400 mb-1">Model</label>+ <select+ value={modelId || ''}+ onChange={(e) => onModelChange?.(e.target.value)}+ disabled={disabled}+ className={inputCls}+ >+ {models.map((m) => <option key={m.id} value={m.id}>{m.name}</option>)}+ </select>+ </div>+ )}++ <div>+ <label className="block text-xs font-medium text-gray-400 mb-1">Resolution</label>+ <select+ value={resolutionLabel}+ onChange={handleResolution}+ disabled={disabled}+ className={inputCls}+ >+ {RESOLUTIONS.map((r) => <option key={r.label} value={r.label}>{r.label}</option>)}+ {!matched && resolutionLabel && <option value={resolutionLabel}>{resolutionLabel} (custom)</option>}+ </select>+ </div>++ {/* Codex's image_gen tool ignores seed/steps/guidance — only resolution+ is honored, so the rest of the knobs are hidden in that mode. */}+ {!isCodex && showSeed && (+ <div>+ <label className="block text-xs font-medium text-gray-400 mb-1">Seed</label>+ <div className="flex items-center gap-1">+ <input+ type="number"+ value={seed ?? ''}+ onChange={(e) => onSeedChange?.(e.target.value)}+ disabled={disabled}+ placeholder="Random"+ className={`flex-1 ${inputCls}`}+ />+ <button+ type="button"+ onClick={() => onSeedChange?.(randomSeed())}+ disabled={disabled}+ className="p-2 text-gray-400 hover:text-white border border-port-border rounded-lg hover:bg-port-border/50 disabled:opacity-50 min-h-[40px] min-w-[40px] flex items-center justify-center"+ title="Randomize seed"+ >+ <Dice5 className="w-4 h-4" />+ </button>+ </div>+ </div>+ )}++ {!isCodex && (+ <div>+ <label className="block text-xs font-medium text-gray-400 mb-1">+ Steps {currentModel?.steps && `(default: ${currentModel.steps})`}+ </label>+ <input+ type="number" min={1} max={150}+ value={steps ?? ''}+ onChange={(e) => onStepsChange?.(e.target.value)}+ placeholder={String(currentModel?.steps || 25)}+ disabled={disabled}+ className={inputCls}+ />+ </div>+ )}++ {!isCodex && isLocal && (+ <div>+ <label className="block text-xs font-medium text-gray-400 mb-1">+ Guidance {currentModel?.guidance != null && `(default: ${currentModel.guidance})`}+ </label>+ <input+ type="number" min={0} max={20} step={0.5}+ value={guidance ?? ''}+ onChange={(e) => onGuidanceChange?.(e.target.value)}+ placeholder={String(currentModel?.guidance ?? '')}+ disabled={disabled}+ className={inputCls}+ />+ </div>+ )}++ {!isCodex && isLocal && showQuantize && !isFlux2 && (+ <div>+ <label className="block text-xs font-medium text-gray-400 mb-1">Quantize (bits)</label>+ <select+ value={quantize ?? '8'}+ onChange={(e) => onQuantizeChange?.(e.target.value)}+ disabled={disabled}+ className={inputCls}+ >+ {QUANTIZE_OPTIONS.map((q) => <option key={q.value} value={q.value}>{q.label}</option>)}+ </select>+ </div>+ )}++ {!isCodex && !isLocal && onCfgScaleChange && (+ <div>+ <label className="block text-xs font-medium text-gray-400 mb-1">CFG Scale ({cfgScale})</label>+ <input+ type="range" min={1} max={20} step={0.5}+ value={cfgScale ?? 7}+ disabled={disabled}+ onChange={(e) => onCfgScaleChange?.(Number(e.target.value))}+ className="w-full accent-port-accent"+ />+ </div>+ )}+ </div>+ );+}diff --git a/client/src/lib/imageGenResolutions.js b/client/src/lib/imageGenResolutions.jsnew file mode 100644index 0000000000..85c6bc6f42--- /dev/null+++ b/client/src/lib/imageGenResolutions.js@@ -0,0 +1,16 @@+// Shared resolution presets for image generation. Used by the standalone+// Image Gen page and the World Builder batch render so the size dropdown+// stays consistent everywhere.+export const RESOLUTIONS = [+ { label: '512×512', w: 512, h: 512 },+ { label: '768×512', w: 768, h: 512 },+ { label: '512×768', w: 512, h: 768 },+ { label: '768×768', w: 768, h: 768 },+ { label: '1024×1024', w: 1024, h: 1024 },+ { label: '832×1216 (Flux portrait)', w: 832, h: 1216 },+ { label: '1216×832 (Flux landscape)', w: 1216, h: 832 },+ { label: '1024×576 (16:9)', w: 1024, h: 576 },+ { label: '576×1024 (9:16)', w: 576, h: 1024 },+];++export const findResolution = (w, h) => RESOLUTIONS.find((r) => r.w === w && r.h === h);diff --git a/client/src/pages/ImageGen.jsx b/client/src/pages/ImageGen.jsxindex 845adc946d..7e0ac432ac 100644--- a/client/src/pages/ImageGen.jsx+++ b/client/src/pages/ImageGen.jsx@@ -19,9 +19,10 @@ import BackendChipStrip from '../components/media/BackendChipStrip';import { normalizeImage } from '../components/media/normalize';import Flux2InstallModal from '../components/imageGen/Flux2InstallModal';import Flux2TokenBanner from '../components/imageGen/Flux2TokenBanner';+import ImageGenControls from '../components/imageGen/ImageGenControls';import {Image as ImageIcon, Sparkles, Download, RefreshCw, Settings as SettingsIcon,- Dice5, AlertTriangle, X, Film,+ AlertTriangle, X, Film,} from 'lucide-react';import { composeStyledPrompt } from '../lib/composeStyledPrompt';import { deriveAvailableBackends, IMAGE_GEN_MODE } from '../lib/imageGenBackends';@@ -33,19 +34,7 @@ import {cancelImageGen, deleteImage, setImageHidden, cleanGalleryImage, getActiveImageJob, getSettings,buildFormData, listMediaJobs,} from '../services/api';-import { randomSeed, safeParseJSON } from '../lib/genUtils';--const RESOLUTIONS = [- { label: '512×512', w: 512, h: 512 },- { label: '768×512', w: 768, h: 512 },- { label: '512×768', w: 512, h: 768 },- { label: '768×768', w: 768, h: 768 },- { label: '1024×1024', w: 1024, h: 1024 },- { label: '832×1216 (Flux portrait)', w: 832, h: 1216 },- { label: '1216×832 (Flux landscape)', w: 1216, h: 832 },- { label: '1024×576 (16:9)', w: 1024, h: 576 },- { label: '576×1024 (9:16)', w: 576, h: 1024 },-];+import { safeParseJSON } from '../lib/genUtils';const DEFAULT_NEGATIVE = 'blurry, low quality, distorted, deformed, ugly, watermark, text, signature';@@ -334,8 +323,6 @@ export default function ImageGen() {}, [settingsOpen, reloadBackends]);const currentModel = models.find((m) => m.id === modelId);- const matchedResolution = RESOLUTIONS.find((r) => r.w === width && r.h === height);- const resolutionLabel = matchedResolution?.label || `${width}×${height}`;const isFlux2Model = currentModel?.runner === 'flux2';const refreshFlux2Status = useCallback((signal) => {@@ -405,13 +392,6 @@ export default function ImageGen() {hiddenGallery: gallery.filter((img) => img.hidden),}), [gallery]);- const handleResolutionChange = (e) => {- const r = RESOLUTIONS.find((r) => r.label === e.target.value);- if (r) { setWidth(r.w); setHeight(r.h); }- };-- const handleRandomSeed = () => setSeed(randomSeed());-// Snapshots current form state into a server payload + POSTs it to the// mediaJobQueue. Returns the queue's response ({ jobId, position, ... }).// Shared between startLocalGeneration (which then opens SSE for the job)@@ -770,120 +750,24 @@ export default function ImageGen() {/>)}- <div className="grid grid-cols-2 sm:grid-cols-3 gap-3">- {isLocalMode && models.length > 0 && (- <div>- <label className="block text-xs font-medium text-gray-400 mb-1">Model</label>- <select- value={modelId}- onChange={(e) => { setModelId(e.target.value); setSteps(''); setGuidance(''); }}- disabled={statusLoading}- className="w-full bg-port-bg border border-port-border rounded-lg px-2 py-2 text-sm text-white focus:outline-none focus:border-port-accent disabled:opacity-50"- >- {models.map((m) => <option key={m.id} value={m.id}>{m.name}</option>)}- </select>- </div>- )}-- <div>- <label className="block text-xs font-medium text-gray-400 mb-1">Resolution</label>- <select- value={resolutionLabel}- onChange={handleResolutionChange}- disabled={statusLoading}- className="w-full bg-port-bg border border-port-border rounded-lg px-2 py-2 text-sm text-white focus:outline-none focus:border-port-accent disabled:opacity-50"- >- {RESOLUTIONS.map((r) => <option key={r.label} value={r.label}>{r.label}</option>)}- {!matchedResolution && <option value={resolutionLabel}>{resolutionLabel} (custom)</option>}- </select>- </div>-- {/* Codex's built-in image_gen tool ignores seed/steps/guidance —- only the prompt + (optional) resolution hint matter. Hide- irrelevant knobs in that mode. */}- {!isCodexMode && (- <div>- <label className="block text-xs font-medium text-gray-400 mb-1">Seed</label>- <div className="flex items-center gap-1">- <input- type="number"- value={seed}- onChange={(e) => setSeed(e.target.value)}- disabled={statusLoading}- placeholder="Random"- className="flex-1 bg-port-bg border border-port-border rounded-lg px-2 py-2 text-sm text-white focus:outline-none focus:border-port-accent disabled:opacity-50"- />- <button- type="button"- onClick={handleRandomSeed}- disabled={statusLoading}- className="p-2 text-gray-400 hover:text-white border border-port-border rounded-lg hover:bg-port-border/50 disabled:opacity-50 min-h-[40px] min-w-[40px] flex items-center justify-center"- title="Randomize seed"- >- <Dice5 className="w-4 h-4" />- </button>- </div>- </div>- )}-- {!isCodexMode && (- <div>- <label className="block text-xs font-medium text-gray-400 mb-1">- Steps {currentModel?.steps && `(default: ${currentModel.steps})`}- </label>- <input- type="number" min={1} max={150}- value={steps}- onChange={(e) => setSteps(e.target.value)}- placeholder={String(currentModel?.steps || 25)}- disabled={statusLoading}- className="w-full bg-port-bg border border-port-border rounded-lg px-2 py-2 text-sm text-white focus:outline-none focus:border-port-accent disabled:opacity-50"- />- </div>- )}-- {!isCodexMode && (isLocalMode ? (- <>- <div>- <label className="block text-xs font-medium text-gray-400 mb-1">- Guidance {currentModel?.guidance != null && `(default: ${currentModel.guidance})`}- </label>- <input- type="number" min={0} max={20} step={0.5}- value={guidance}- onChange={(e) => setGuidance(e.target.value)}- placeholder={String(currentModel?.guidance ?? '')}- disabled={statusLoading}- className="w-full bg-port-bg border border-port-border rounded-lg px-2 py-2 text-sm text-white focus:outline-none focus:border-port-accent disabled:opacity-50"- />- </div>- {!isFlux2Model && (- <div>- <label className="block text-xs font-medium text-gray-400 mb-1">Quantize (bits)</label>- <select- value={quantize}- onChange={(e) => setQuantize(e.target.value)}- disabled={statusLoading}- className="w-full bg-port-bg border border-port-border rounded-lg px-2 py-2 text-sm text-white focus:outline-none focus:border-port-accent disabled:opacity-50"- >- {['3', '4', '5', '6', '8'].map((q) => <option key={q} value={q}>{q}-bit{q === '8' ? ' (default)' : q === '4' ? ' (fast)' : ''}</option>)}- </select>- </div>- )}- </>- ) : (- <div>- <label className="block text-xs font-medium text-gray-400 mb-1">CFG Scale ({cfgScale})</label>- <input- type="range" min={1} max={20} step={0.5}- value={cfgScale}- disabled={statusLoading}- onChange={(e) => setCfgScale(Number(e.target.value))}- className="w-full accent-port-accent"- />- </div>- ))}- </div>+ <ImageGenControls+ mode={effectiveMode}+ models={models}+ modelId={modelId}+ // Reset steps + guidance when switching models so the placeholder+ // (model defaults) takes effect instead of leaking the previous+ // model's tuned values onto the new one.+ onModelChange={(id) => { setModelId(id); setSteps(''); setGuidance(''); }}+ width={width} height={height}+ onResolutionChange={(w, h) => { setWidth(w); setHeight(h); }}+ steps={steps} onStepsChange={setSteps}+ guidance={guidance} onGuidanceChange={setGuidance}+ cfgScale={cfgScale} onCfgScaleChange={setCfgScale}+ quantize={quantize} onQuantizeChange={setQuantize}+ seed={seed} onSeedChange={setSeed}+ showSeed+ disabled={statusLoading}+ />{isLocalMode && !isFlux2Model && availableLoras.length > 0 && (<div>diff --git a/client/src/pages/WorldBuilder.jsx b/client/src/pages/WorldBuilder.jsxindex fe9ccf8e08..698853c82e 100644--- a/client/src/pages/WorldBuilder.jsx+++ b/client/src/pages/WorldBuilder.jsx@@ -17,7 +17,11 @@ import toast from '../components/ui/Toast';import {listWorlds, getWorld, createWorld, updateWorld, deleteWorld, expandWorld,renderWorld, listWorldRuns, getProviders, WORLD_CATEGORIES,+ listImageModels, getSettings,} from '../services/api';+import BackendChipStrip from '../components/media/BackendChipStrip';+import ImageGenControls from '../components/imageGen/ImageGenControls';+import { deriveAvailableBackends, IMAGE_GEN_MODE } from '../lib/imageGenBackends';const CATEGORY_LABELS = {landscapes: 'Landscapes',@@ -32,7 +36,11 @@ const DEFAULT_RENDER_OPTS = {width: 1024,height: 1024,steps: 30,+ guidance: '',cfgScale: 7,+ quantize: '8',+ modelId: '',+ mode: '',batchPerVariation: 1,};@@ -54,6 +62,10 @@ export default function WorldBuilder() {const [rendering, setRendering] = useState(false);const [providers, setProviders] = useState([]);const [activeProviderId, setActiveProviderId] = useState(null);+ // Image-gen plumbing for the batch-render form (reused from Image Gen).+ const [imageModels, setImageModels] = useState([]);+ const [availableBackends, setAvailableBackends] = useState([]);+ const [defaultMode, setDefaultMode] = useState(null);// The draft is the editable copy of the currently-selected world. New// worlds start as a draft with no id; saving creates the persisted record.@@ -81,13 +93,23 @@ export default function WorldBuilder() {const refresh = async () => {setLoading(true);- const [list, provData] = await Promise.all([+ const [list, provData, models, settings] = await Promise.all([listWorlds().catch(() => []),getProviders().catch(() => ({ providers: [] })),+ listImageModels().catch(() => []),+ getSettings().catch(() => ({})),]);setWorlds(list);setProviders(provData.providers || []);setActiveProviderId(provData.activeProvider || null);+ setImageModels(models || []);+ // Batch render rejects external (would block the request for the whole+ // batch), so hide that chip even if it's configured.+ const backends = deriveAvailableBackends(settings, { excludeExternal: true });+ setAvailableBackends(backends);+ const saved = settings?.imageGen?.mode;+ const fallback = backends.find((b) => b.id === saved)?.id || backends[0]?.id || IMAGE_GEN_MODE.LOCAL;+ setDefaultMode(fallback);setLoading(false);};@@ -185,14 +207,37 @@ export default function WorldBuilder() {}).catch((e) => { toast.error(`Expansion failed: ${e.message}`); return null; });setExpanding(false);if (!result) return;- setDraft((d) => ({- ...d,- stylePrompt: result.stylePrompt || d.stylePrompt,- negativePrompt: result.negativePrompt || d.negativePrompt,+ const expandedDraft = {+ ...draft,+ stylePrompt: result.stylePrompt || draft.stylePrompt,+ negativePrompt: result.negativePrompt || draft.negativePrompt,categories: Object.fromEntries(WORLD_CATEGORIES.map((c) => [c, result.categories?.[c] || { variations: [] }])),- llm: result.llm || d.llm,- }));+ llm: result.llm || draft.llm,+ };+ setDraft(expandedDraft);const total = WORLD_CATEGORIES.reduce((n, k) => n + (result.categories?.[k]?.variations?.length || 0), 0);+ // Auto-persist expansion if the world is already saved — otherwise the+ // user clicks Render and hits "No prompts to render" because the disk+ // copy still has empty categories. New (unsaved) drafts still need a+ // manual Save since they have no name yet.+ if (selectedId && expandedDraft.name?.trim()) {+ const updated = await updateWorld(selectedId, {+ name: expandedDraft.name.trim(),+ starterPrompt: expandedDraft.starterPrompt || '',+ stylePrompt: expandedDraft.stylePrompt || '',+ negativePrompt: expandedDraft.negativePrompt || '',+ categories: expandedDraft.categories,+ llm: expandedDraft.llm || {},+ }).catch((e) => { toast.error(`Auto-save after expand failed: ${e.message}`); return null; });+ if (updated) {+ setWorlds((prev) => {+ const without = prev.filter((w) => w.id !== updated.id);+ return [updated, ...without];+ });+ toast.success(`Expanded into ${total} variations — saved`);+ return;+ }+ }toast.success(`Expanded into ${total} variations — review then Save`);};@@ -206,14 +251,22 @@ export default function WorldBuilder() {toast.error('No variations — expand the template first');return;}+ const effectiveMode = renderOpts.mode || defaultMode || undefined;+ const numericOrUndef = (v) => {+ if (v === '' || v == null) return undefined;+ const n = Number(v);+ return Number.isFinite(n) ? n : undefined;+ };setRendering(true);const result = await renderWorld(selectedId, {- mode: renderOpts.mode || undefined,+ mode: effectiveMode,modelId: renderOpts.modelId || undefined,width: renderOpts.width,height: renderOpts.height,- steps: renderOpts.steps,- cfgScale: renderOpts.cfgScale,+ steps: numericOrUndef(renderOpts.steps),+ guidance: numericOrUndef(renderOpts.guidance),+ cfgScale: numericOrUndef(renderOpts.cfgScale),+ quantize: renderOpts.quantize || undefined,batchPerVariation: renderOpts.batchPerVariation,}).catch((e) => { toast.error(`Render failed: ${e.message}`); return null; });setRendering(false);@@ -416,31 +469,63 @@ export default function WorldBuilder() {))}</section>- {/* Render controls */}+ {/* Render controls — reuses Image Gen's backend chip + knob grid so+ the model picker, resolution presets, etc. stay in lockstep. */}<section className="bg-port-card border border-port-border rounded p-4 flex flex-col gap-3">- <h2 className="text-sm font-semibold text-white flex items-center gap-2">- <FolderOpen size={16} className="text-port-accent" /> Batch render- </h2>- <div className="grid grid-cols-2 md:grid-cols-5 gap-2">- <NumberField label="Width" value={renderOpts.width} min={64} max={2048} onChange={(v) => setRenderOpts({ ...renderOpts, width: v })} />- <NumberField label="Height" value={renderOpts.height} min={64} max={2048} onChange={(v) => setRenderOpts({ ...renderOpts, height: v })} />- <NumberField label="Steps" value={renderOpts.steps} min={1} max={150} onChange={(v) => setRenderOpts({ ...renderOpts, steps: v })} />- <NumberField label="CFG" value={renderOpts.cfgScale} min={0} max={30} step={0.5} onChange={(v) => setRenderOpts({ ...renderOpts, cfgScale: v })} />- <NumberField label="Per-variation" value={renderOpts.batchPerVariation} min={1} max={20} onChange={(v) => setRenderOpts({ ...renderOpts, batchPerVariation: v })} />+ <div className="flex items-center justify-between gap-2 flex-wrap">+ <h2 className="text-sm font-semibold text-white flex items-center gap-2">+ <FolderOpen size={16} className="text-port-accent" /> Batch render+ </h2>+ {availableBackends.length > 1 && (+ <BackendChipStrip+ availableBackends={availableBackends}+ value={renderOpts.mode || defaultMode}+ onChange={(id) => setRenderOpts((r) => ({ ...r, mode: id }))}+ titlePrefix="Render via"+ />+ )}+ </div>+ {availableBackends.length === 0 && (+ <p className="text-xs text-port-warning">+ Configure a local mflux Python path or enable Codex Imagegen in Settings → Image Gen+ to enable batch render.+ </p>+ )}+ <ImageGenControls+ mode={renderOpts.mode || defaultMode || 'local'}+ models={imageModels}+ modelId={renderOpts.modelId}+ onModelChange={(id) => setRenderOpts((r) => ({ ...r, modelId: id, steps: '', guidance: '' }))}+ width={renderOpts.width}+ height={renderOpts.height}+ onResolutionChange={(w, h) => setRenderOpts((r) => ({ ...r, width: w, height: h }))}+ steps={renderOpts.steps}+ onStepsChange={(v) => setRenderOpts((r) => ({ ...r, steps: v }))}+ guidance={renderOpts.guidance}+ onGuidanceChange={(v) => setRenderOpts((r) => ({ ...r, guidance: v }))}+ cfgScale={renderOpts.cfgScale}+ onCfgScaleChange={(v) => setRenderOpts((r) => ({ ...r, cfgScale: v }))}+ quantize={renderOpts.quantize}+ onQuantizeChange={(v) => setRenderOpts((r) => ({ ...r, quantize: v }))}+ />+ <div className="grid grid-cols-2 sm:grid-cols-3 gap-3">+ <div>+ <label className="block text-xs font-medium text-gray-400 mb-1">Renders per variation</label>+ <input+ type="number" min={1} max={20}+ value={renderOpts.batchPerVariation ?? 1}+ onChange={(e) => {+ const n = Number(e.target.value);+ setRenderOpts((r) => ({ ...r, batchPerVariation: Number.isFinite(n) && n > 0 ? n : 1 }));+ }}+ className="w-full bg-port-bg border border-port-border rounded-lg px-2 py-2 text-sm text-white focus:outline-none focus:border-port-accent"+ />+ </div></div><div className="flex items-center gap-2 flex-wrap">- <select- value={renderOpts.mode || ''}- onChange={(e) => setRenderOpts({ ...renderOpts, mode: e.target.value || undefined })}- className="bg-port-bg border border-port-border rounded px-2 py-2 text-white text-sm min-h-[40px]"- >- <option value="">Default backend</option>- <option value="local">Local (mflux)</option>- <option value="codex">Codex</option>- </select><buttononClick={handleRender}- disabled={rendering || !selectedId || totalVariations === 0}+ disabled={rendering || !selectedId || totalVariations === 0 || availableBackends.length === 0}className="px-4 py-2 bg-port-accent hover:bg-port-accent/90 disabled:opacity-50 text-white rounded flex items-center gap-2 min-h-[40px]">{rendering ? <Loader2 size={16} className="animate-spin" /> : <Sparkles size={16} />}@@ -628,24 +713,3 @@ function CategoryEditor({ category, variations, onChange }) {);}-function NumberField({ label, value, min, max, step = 1, onChange }) {- return (- <label className="flex flex-col">- <span className="text-xs text-gray-400 mb-1">{label}</span>- <input- type="number"- value={value ?? ''}- min={min}- max={max}- step={step}- onChange={(e) => {- const raw = e.target.value;- if (raw === '') { onChange(undefined); return; }- const n = Number(raw);- if (Number.isFinite(n)) onChange(n);- }}- className="bg-port-bg border border-port-border rounded px-2 py-1.5 text-white text-sm focus:outline-none focus:border-port-accent min-h-[40px]"- />- </label>- );-}diff --git a/server/routes/worldBuilder.js b/server/routes/worldBuilder.jsindex 9c9244fc1b..d753e48dfd 100644--- a/server/routes/worldBuilder.js+++ b/server/routes/worldBuilder.js@@ -96,6 +96,7 @@ const renderSchema = z.object({steps: z.number().int().min(1).max(150).optional(),cfgScale: z.number().min(0).max(30).optional(),guidance: z.number().min(0).max(30).optional(),+ quantize: z.enum(['3', '4', '5', '6', '8']).optional(),// Per-variation render count and per-category subset.batchPerVariation: z.number().int().min(1).max(20).optional().default(1),selection: selectionSchema.optional(),@@ -213,6 +214,7 @@ router.post('/:id/render', asyncHandler(async (req, res) => {steps: body.steps,cfgScale: body.cfgScale,guidance,+ quantize: body.quantize,};for (const item of compiled) {diff --git a/server/services/worldBuilderExpand.js b/server/services/worldBuilderExpand.jsindex 59fcfdc993..457315b8ee 100644--- a/server/services/worldBuilderExpand.js+++ b/server/services/worldBuilderExpand.js@@ -51,6 +51,8 @@ const isCliProvider = (provider) => provider?.type === 'cli';// Awaiting createRun separately keeps the Promise executor synchronous —// an `async` executor body silently swallows rejected awaits, leaving the// caller's Promise hanging forever if createRun throws.+// Returns { text, runId } — runId is logged so a user debugging an empty+// expansion can find the raw stdout at data/runs/<runId>/output.txt.async function callLLM(provider, model, prompt) {const { runId } = await createRun({providerId: provider.id,@@ -76,7 +78,7 @@ async function callLLM(provider, model, prompt) {if (result?.error || result?.success === false) {reject(new Error(result?.error || 'CLI execution failed'));} else {- resolve(text);+ resolve({ text, runId });}},provider.timeout ?? 300000,@@ -92,31 +94,32 @@ async function callLLM(provider, model, prompt) {(data) => { text += typeof data === 'string' ? data : (data?.text || ''); },(result) => {if (result?.error) reject(new Error(result.error));- else resolve(text);+ else resolve({ text, runId });},).catch(reject);}});}-const extractJson = (raw) => {- if (!raw || typeof raw !== 'string') throw new Error('Empty LLM response');- let s = raw.trim();- // Strip ```json fences if present.- const fence = s.match(/```(?:json)?\s*([\s\S]*?)```/);- if (fence) s = fence[1].trim();- // Extract the first complete brace-balanced { … } block — guards against- // preamble ("Here is…") and trailing junk after the JSON object. The scan- // is string-aware so braces inside JSON string values (e.g. a prompt that- // contains "{" or "}") don't unbalance the depth counter.- const start = s.indexOf('{');- if (start !== -1) {+// Walk the string and return every top-level brace-balanced { … } block, in+// order. String-aware so braces inside JSON string values don't throw off the+// depth counter. Used by extractJson — Codex CLI echoes the user prompt back+// to stdout before the model response, and the prompt itself contains a+// JSON-shaped *schema example* (e.g. `{ "label": string (max 80 chars), … }`)+// whose braces balance but whose contents are not valid JSON. Returning every+// block lets the caller try each in turn instead of giving up on the first.+const findBalancedBlocks = (s) => {+ const blocks = [];+ let i = 0;+ 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 i = start; i < s.length; i += 1) {- const ch = s[i];+ for (let j = start; j < s.length; j += 1) {+ const ch = s[j];if (inString) {if (escaped) escaped = false;else if (ch === '\\') escaped = true;@@ -127,28 +130,87 @@ const extractJson = (raw) => {if (ch === '{') depth += 1;else if (ch === '}') {depth -= 1;- if (depth === 0) { end = i; break; }+ if (depth === 0) { end = j; break; }}}- if (end !== -1) s = s.slice(start, end + 1);+ if (end === -1) break; // unbalanced — no later block can balance either+ blocks.push(s.slice(start, end + 1));+ i = end + 1;+ }+ return blocks;+};++// Try JSON.parse on a candidate block; if it fails, attempt a few cheap+// repairs that handle observed LLM corruption patterns:+// - Codex CLI sometimes emits an EXTRA `}` between a variation's close-brace+// and its enclosing array's `]` (`}}]}}}` instead of `}]}}}`). Brace+// balance still works because the extra `{` was hallucinated upstream.+// - Trailing comma before `]` or `}`.+// We try removing/normalizing one suspicious char at a time, capped at a few+// attempts so a genuinely broken block still bubbles a parse error.+const tryParseWithRepair = (block) => {+ try { return { value: JSON.parse(block) }; } catch (initialErr) {+ // Remove trailing commas before `}` or `]` (common LLM mistake).+ let candidate = block.replace(/,(\s*[}\]])/g, '$1');+ if (candidate !== block) {+ try { return { value: JSON.parse(candidate) }; } catch { /* keep trying */ }+ }+ // Fix Codex's `}}]` → `}]}` pattern: the variation object closes+ // correctly, then an orphan `}` lands BEFORE the array's `]` instead of+ // after it. Swapping (not dropping) keeps the brace count correct so the+ // outer container still closes — dropping the brace would leave a+ // dangling object open further out.+ candidate = candidate.replace(/}\s*}\s*]/g, '}]}');+ try { return { value: JSON.parse(candidate) }; } catch (err) {+ return { error: err };+ }}- // Recovery: some LLMs (notably Codex CLI) echo the prompt's `[...]`- // schema-notation back as a literal value. Replace such empty-placeholder- // arrays with `[]` so the rest of the parse can succeed; normalizeCategories- // will see them as empty and report 0 variations rather than 500-ing.- s = s.replace(/\[\s*\.\.\.\s*\]/g, '[]');- try {- return JSON.parse(s);- } catch (err) {- throw new ServerError(- 'LLM returned invalid JSON for world expansion. Try a different model or rerun.',- {- status: 502,- code: 'LLM_INVALID_JSON',- context: { details: { reason: err.message, preview: s.slice(0, 200) } },- },- );+};++const extractJson = (raw) => {+ if (!raw || typeof raw !== 'string') throw new Error('Empty LLM response');+ let s = raw.trim();+ // Strip ```json fences if present.+ const fence = s.match(/```(?:json)?\s*([\s\S]*?)```/);+ if (fence) s = fence[1].trim();+ // Try each brace-balanced block in order. This skips preamble ("Here is…"),+ // prompt echoes (Codex CLI), and pseudo-JSON schema examples in the prompt.+ // We prefer a block that *looks like* a world-expansion response (has any of+ // stylePrompt / negativePrompt / categories at the top level) — the prompt+ // template includes small JSON examples like+ // { "label": "Crystalline canyon basin", "prompt": "…" }+ // which parse cleanly but aren't the response. Without the shape preference+ // we'd return that first valid-but-wrong object and end up with 0 variations.+ const candidates = findBalancedBlocks(s);+ if (!candidates.length) candidates.push(s);+ const isExpansionShape = (o) => o && typeof o === 'object'+ && (typeof o.stylePrompt === 'string' || typeof o.negativePrompt === 'string' || (o.categories && typeof o.categories === 'object'));+ let firstParsed;+ let lastErr;+ let lastPreview = s;+ for (const block of candidates) {+ // Recovery: some LLMs (notably Codex CLI) echo the prompt's `[...]`+ // schema-notation back as a literal value. Replace such empty-placeholder+ // arrays with `[]` so the rest of the parse can succeed.+ const cleaned = block.replace(/\[\s*\.\.\.\s*\]/g, '[]');+ const { value: parsed, error } = tryParseWithRepair(cleaned);+ if (parsed !== undefined) {+ if (isExpansionShape(parsed)) return parsed;+ if (firstParsed === undefined) firstParsed = parsed;+ } else {+ lastErr = error;+ lastPreview = cleaned;+ }}+ if (firstParsed !== undefined) return firstParsed;+ throw new ServerError(+ 'LLM returned invalid JSON for world expansion. Try a different model or rerun.',+ {+ status: 502,+ code: 'LLM_INVALID_JSON',+ context: { details: { reason: lastErr?.message || 'no JSON object found', preview: lastPreview.slice(0, 200) } },+ },+ );};const normalizeCategories = (raw) => {@@ -203,16 +265,25 @@ export async function expandWorldTemplate({ starterPrompt, providerId, model } =const fullPrompt = EXPANSION_PROMPT.replace('{starterPrompt}', starterPrompt.trim());console.log(`🌍 World Builder expanding via ${provider.name}/${selectedModel || 'default'}`);- const raw = await callLLM(provider, selectedModel, fullPrompt);+ const { text: raw, runId } = await callLLM(provider, selectedModel, fullPrompt);+ // Log raw response shape so a "0 variations" outcome is debuggable from+ // the server console alone — the runId points at data/runs/<id>/output.txt+ // for the full transcript.+ console.log(`🌍 World Builder raw response — runId=${runId} length=${raw?.length || 0}`);const parsed = extractJson(raw);+ console.log(`🌍 World Builder parsed JSON — keys=[${Object.keys(parsed || {}).join(',')}] categoryKeys=[${Object.keys(parsed?.categories || {}).join(',')}]`);const stylePrompt = typeof parsed.stylePrompt === 'string'? parsed.stylePrompt.trim().slice(0, PROMPT_FRAGMENT_MAX) : '';const negativePrompt = typeof parsed.negativePrompt === 'string'? parsed.negativePrompt.trim().slice(0, PROMPT_FRAGMENT_MAX) : '';const categories = normalizeCategories(parsed.categories || {});+ const perCat = WORLD_CATEGORIES.map((k) => `${k}=${categories[k]?.variations?.length || 0}`).join(' ');const totalVariations = WORLD_CATEGORIES.reduce((n, k) => n + (categories[k]?.variations?.length || 0), 0);- console.log(`🌍 World Builder expansion complete — ${totalVariations} variations across ${WORLD_CATEGORIES.length} categories`);+ console.log(`🌍 World Builder expansion complete — runId=${runId} ${totalVariations} variations (${perCat})`);+ if (totalVariations === 0) {+ console.warn(`⚠️ World Builder expansion produced 0 variations — inspect data/runs/${runId}/output.txt for the raw LLM response`);+ }return {stylePrompt,diff --git a/server/services/worldBuilderExpand.test.js b/server/services/worldBuilderExpand.test.jsindex da753148a0..7dac3a1665 100644--- a/server/services/worldBuilderExpand.test.js+++ b/server/services/worldBuilderExpand.test.js@@ -43,6 +43,64 @@ describe('worldBuilderExpand.extractJson', () => {expect(out.categories.vehicles.variations).toEqual([]);});+ it('skips a pseudo-JSON schema example in echoed prompt and parses the real response (Codex CLI)', () => {+ // Codex CLI echoes the user prompt back to stdout before printing the model's+ // response. The prompt contains a JSON-shaped schema example using bare+ // identifiers as placeholder values — its braces balance but its contents+ // are not valid JSON. Earlier extractJson grabbed the first balanced block+ // and crashed; it should now fall through to the next block.+ const raw = [+ 'OpenAI Codex v0.128.0 (research preview)',+ '--------',+ 'workdir: /tmp',+ '--------',+ 'user',+ 'Each variation has the shape { "label": string (max 80 chars), "prompt": string (max 400 chars, comma-separated tokens describing ONE specific subject) }.',+ 'codex',+ '{"stylePrompt":"x","negativePrompt":"y","categories":{"vehicles":{"variations":[{"label":"a","prompt":"b"}]}}}',+ 'tokens used',+ '2,787',+ ].join('\n');+ const out = extractJson(raw);+ expect(out.stylePrompt).toBe('x');+ expect(out.negativePrompt).toBe('y');+ expect(out.categories.vehicles.variations).toEqual([{ label: 'a', prompt: 'b' }]);+ });++ it('repairs Codex CLI orphan-brace corruption (`}}]` → `}]`) inside the response', () => {+ // Real-world: Codex produced `{"label":"...","prompt":"…blister"}}]}}}`+ // — an extra `}` snuck in between the variation's close-brace and the+ // array's `]`. extractJson must recover that to a parsed expansion shape.+ const badJson = '{"stylePrompt":"x","categories":{"vehicles":{"variations":[{"label":"a","prompt":"…blister"}}]}}}';+ const out = extractJson(badJson);+ expect(out.stylePrompt).toBe('x');+ expect(out.categories.vehicles.variations).toEqual([{ label: 'a', prompt: '…blister' }]);+ });++ it('strips a trailing comma before `]` (common LLM mistake)', () => {+ const raw = '{"stylePrompt":"x","categories":{"landscapes":{"variations":[{"label":"a","prompt":"b"},]}}}';+ const out = extractJson(raw);+ expect(out.categories.landscapes.variations).toEqual([{ label: 'a', prompt: 'b' }]);+ });++ it('prefers a world-expansion-shaped object over an in-prompt JSON example', () => {+ // The actual prompt template includes literal JSON example variations:+ // { "label": "Crystalline canyon basin", "prompt": "…" }+ // These are valid JSON and brace-balance cleanly, but they aren't the+ // response. extractJson must skip them and return the larger object that+ // has the world-expansion top-level keys.+ const raw = [+ 'codex',+ '{ "label": "Crystalline canyon basin", "prompt": "vast crystalline canyon, salt flats" }',+ '{ "label": "Scrap-iron dune sea", "prompt": "rolling dunes of rusted scrap" }',+ 'codex',+ '{"stylePrompt":"painterly","categories":{"landscapes":{"variations":[{"label":"Real","prompt":"real prompt"}]}}}',+ ].join('\n');+ const out = extractJson(raw);+ expect(out.stylePrompt).toBe('painterly');+ expect(out.categories.landscapes.variations).toEqual([{ label: 'Real', prompt: 'real prompt' }]);+ });+it('wraps a JSON.parse failure in a 502 LLM_INVALID_JSON ServerError (no raw 500)', () => {let thrown;try { extractJson('{ "stylePrompt": "x", "broken'); } catch (e) { thrown = e; }