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: Nouns stage, world-styled refs, codex-default comic image gen

[._.]/ Adam Eivyd0bf1d8b7eb2
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index da492ad18c..265665bbd5 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -109,8 +109,62 @@
premise, etc.) to the server so the LLM runs against the on-screen state
rather than the last manually-saved snapshot.
+- **Pipeline — Nouns stage between Prose and Comic.** New UI-only tab that
+ surfaces, per-issue, the characters / settings / objects appearing in the
+ prose. Each entry shows its canonical description and an `imageRefs[]`
+ thumbnail strip with a *Render reference* button that fires a styled image
+ gen and pins the resulting filename onto the series bible — so the
+ comic-page renderer (which now cites those rich descriptions in its prompt)
+ keeps characters and settings visually consistent across pages without
+ having to pass actual reference images (which Codex's `$imagegen` doesn't
+ accept). Extract from prose lives here now too; removed from the Prose tab.
+ Reference renders inherit the linked world's `stylePrompt` + `negativePrompt`
+ via `composeStyledPrompt`, so the aesthetic stays consistent with comic pages.
+ The card defers the series PATCH until the job's `useMediaJobProgress`
+ reports `completed`, so the UI never tries to load a not-yet-written
+ `/data/images/<jobId>.png`.
+
+- **Comic page renderer — cite settings + objects in the prompt, not just
+ characters.** `enqueueVisualComicPage` now builds the matched bible set
+ from the union of dialogue CAPS speakers and panel description / caption /
+ SFX prose. `composeComicPagePrompt` emits new `Setting — <name>: …, palette,
+ recurring details` and `Notable — <name>: <description>` clauses alongside
+ the existing `Featuring —` clause. Fixes the case where a panel like
+ "Wren pins the navy woman's wrist against the pavement" rendered with the
+ model re-improvising both subjects every time because dialogue-only
+ matching never saw them. New `matchSettingsInText` + `matchObjectsInText`
+ mirror the character matcher; all three share a private
+ `matchEntriesByCandidates` helper.
+
+- **Pipeline image-gen — DRY settings form + codex-by-default for comic
+ pages.** New `ImageGenSettingsForm` component bundles the backend chip
+ strip + per-model controls + style textareas behind a single
+ `{value, onChange}` contract; reused by the Comic Pages tab and the new
+ Nouns tab. Settings persist to `settings.pipeline.imageGen` and default to
+ Codex whenever the system has `imageGen.codex.enabled === true`, matching
+ the recommendation that cloud models render comic pages dramatically
+ better than local diffusion. Default resolution is now `1024×1536`
+ (2:3 portrait, the closest preset to a real comic-book trim) instead of
+ `1024×1024`. Right-side `Drawer` opened via a header gear button.
+
+- **Pipeline image-gen — seed support for comic page + scene renders.**
+ `comicPageRenderSchema` and `visualGenerateSchema` (server) now accept
+ `seed`, and `enqueueImageJob` threads it into the queued job params.
+ Client form exposes a seed input + random-dice button. Local mflux and
+ diffusers runners honor it; codex still picks its own.
+
+- **Series bible — `imageRefs[]` on settings and objects.** Previously
+ characters-only; the Nouns stage's *Render reference* button writes to all
+ three. Pipeline route schemas already use `.passthrough()`, so the client
+ PATCH round-trips cleanly through the canonical sanitizer with no other
+ schema changes.
+
## Changed
+- **Pipeline nav — shorter tab labels.** *Comic Pages* → *Comic*,
+ *Episode Video* → *Video*. The full names were redundant inside the
+ Pipeline page where every tab is obviously a pipeline stage.
+
- **Pipeline Series — Regenerate arc button no longer requires two clicks.**
Dropped the `useArmedAction` two-click-arm pattern from the regenerate
button; one click runs. The pattern was confusing — users didn't realize
diff --git a/client/src/components/imageGen/ImageGenSettingsForm.jsx b/client/src/components/imageGen/ImageGenSettingsForm.jsx
new file mode 100644
index 0000000000..09ccc29625
--- /dev/null
+++ b/client/src/components/imageGen/ImageGenSettingsForm.jsx
@@ -0,0 +1,104 @@
+// Shared image-gen settings form. Bundles the backend chip strip + the
+// per-model ImageGenControls grid + optional negativePrompt / extraStyle
+// textareas behind a single `value`/`onChange` contract. Use it anywhere
+// you'd otherwise hand-roll the same trio (Drawer settings panels, in-page
+// config sections, modal pickers).
+//
+// Caller owns the `value` shape — typically a flat object like
+// { mode, modelId, width, height, steps, guidance, negativePrompt, extraStyle }
+// — and a single `onChange(next)` callback receives the merged object.
+
+import BackendChipStrip from '../media/BackendChipStrip';
+import ImageGenControls from './ImageGenControls';
+import { IMAGE_GEN_MODE } from '../../lib/imageGenBackends';
+
+export default function ImageGenSettingsForm({
+ value,
+ onChange,
+ models = [],
+ availableBackends = [],
+ showStyleFields = true,
+ disabled = false,
+}) {
+ const cfg = value || {};
+ const merge = (patch) => onChange?.({ ...cfg, ...patch });
+ const isCodex = cfg.mode === IMAGE_GEN_MODE.CODEX;
+ const labelCls = 'block text-xs font-medium text-gray-400 mb-1';
+ const textareaCls = 'w-full bg-port-bg border border-port-border rounded-lg px-2 py-2 text-sm text-white focus:outline-none focus:border-port-accent disabled:opacity-50 resize-y';
+
+ return (
+ <div className="space-y-4">
+ {availableBackends.length === 0 ? (
+ <div className="text-[11px] text-port-warning bg-port-warning/10 border border-port-warning/40 rounded px-2 py-1.5">
+ No image gen backend configured. Open Settings → Image Gen to enable Local mflux or Codex <code className="text-gray-400">$imagegen</code>.
+ </div>
+ ) : null}
+
+ {availableBackends.length > 0 ? (
+ <div>
+ <span className={labelCls}>Backend</span>
+ <BackendChipStrip
+ availableBackends={availableBackends}
+ value={cfg.mode}
+ onChange={(id) => merge({ mode: id })}
+ size="md"
+ ariaLabel="Image gen backend"
+ titlePrefix="Render via"
+ disabled={disabled}
+ />
+ {isCodex ? (
+ <p className="text-[10px] text-gray-500 mt-1">
+ Codex's <code className="text-gray-400">$imagegen</code> picks model, steps, and seed internally. Only resolution + style fields apply.
+ </p>
+ ) : null}
+ </div>
+ ) : null}
+
+ <ImageGenControls
+ mode={cfg.mode}
+ models={models}
+ modelId={cfg.modelId}
+ onModelChange={(modelId) => merge({ modelId })}
+ width={cfg.width}
+ height={cfg.height}
+ onResolutionChange={(width, height) => merge({ width, height })}
+ steps={cfg.steps}
+ onStepsChange={(steps) => merge({ steps })}
+ guidance={cfg.guidance}
+ onGuidanceChange={(guidance) => merge({ guidance })}
+ seed={cfg.seed}
+ onSeedChange={(seed) => merge({ seed })}
+ showSeed
+ showQuantize={false}
+ disabled={disabled}
+ />
+
+ {showStyleFields ? (
+ <div className="space-y-3">
+ <label className="block">
+ <span className={labelCls}>Extra style (optional)</span>
+ <textarea
+ rows={2}
+ value={cfg.extraStyle || ''}
+ onChange={(e) => merge({ extraStyle: e.target.value })}
+ placeholder="cinematic ink, bold panel borders…"
+ className={textareaCls}
+ disabled={disabled}
+ />
+ </label>
+ <label className="block">
+ <span className={labelCls}>Negative prompt (optional)</span>
+ <textarea
+ rows={2}
+ value={cfg.negativePrompt || ''}
+ onChange={(e) => merge({ negativePrompt: e.target.value })}
+ placeholder="blurry, low quality, watermark…"
+ className={textareaCls}
+ disabled={disabled}
+ />
+ </label>
+ </div>
+ ) : null}
+ </div>
+ );
+}
diff --git a/client/src/components/pipeline/stages/ComicScriptStage.jsx b/client/src/components/pipeline/stages/ComicScriptStage.jsx
index c8d0f58862..57c65e7425 100644
--- a/client/src/components/pipeline/stages/ComicScriptStage.jsx
+++ b/client/src/components/pipeline/stages/ComicScriptStage.jsx
@@ -7,8 +7,9 @@
* render prompt stays high-quality, but they're never shown.
*/
-import { useEffect, useMemo, useState } from 'react';
-import { Loader2, Sparkles, ImageIcon, Save, Trash2, ChevronDown, ChevronRight } from 'lucide-react';
+import { useCallback, useEffect, useMemo, useState } from 'react';
+import { useSearchParams } from 'react-router-dom';
+import { Loader2, Sparkles, ImageIcon, Save, Trash2, ChevronDown, ChevronRight, Settings as SettingsIcon } from 'lucide-react';
import toast from '../../ui/Toast';
import {
generatePipelineStage,
@@ -20,7 +21,17 @@ import {
PIPELINE_STAGE_STATUS_LABEL as STATUS_LABEL,
PIPELINE_STAGE_STATUS_COLOR as STATUS_COLOR,
} from '../../../services/api';
+import { getSettings, updateSettings } from '../../../services/apiSystem';
+import { listImageModels } from '../../../services/apiImageVideo';
import MediaJobThumb from '../MediaJobThumb';
+import Drawer from '../../Drawer';
+import ImageGenSettingsForm from '../../imageGen/ImageGenSettingsForm';
+import { deriveAvailableBackends } from '../../../lib/imageGenBackends';
+import {
+ PIPELINE_IMAGE_DEFAULTS,
+ readPipelineImageSettings,
+ pipelineImageCfgToRenderOpts,
+} from '../../../lib/pipelineImageDefaults';
// Reconstructs a page's markdown from its parsed `panels[]`. Used as a
// fallback for pages persisted BEFORE the parser started preserving rawText —
@@ -59,6 +70,62 @@ export default function ComicScriptStage({ issue, series, onStageUpdate }) {
const [extracting, setExtracting] = useState(false);
const [showSource, setShowSource] = useState(false);
+ // Per-render image-gen config. Defaults pick Codex if it's enabled
+ // system-wide; the user can override via the right-side Drawer and we
+ // persist their choice to settings.pipeline.imageGen so it sticks across
+ // page reloads.
+ const [imageCfg, setImageCfg] = useState(PIPELINE_IMAGE_DEFAULTS);
+ const [imageModels, setImageModels] = useState([]);
+ const [sysSettings, setSysSettings] = useState(null);
+ const availableBackends = useMemo(
+ () => deriveAvailableBackends(sysSettings, { excludeExternal: true }),
+ [sysSettings],
+ );
+
+ useEffect(() => {
+ let cancelled = false;
+ Promise.all([
+ getSettings().catch(() => ({})),
+ listImageModels().catch(() => []),
+ ]).then(([s, modelList]) => {
+ if (cancelled) return;
+ setSysSettings(s);
+ setImageCfg(readPipelineImageSettings(s));
+ setImageModels(Array.isArray(modelList) ? modelList : []);
+ });
+ return () => { cancelled = true; };
+ }, []);
+
+ const persistImageCfg = useCallback(async (next) => {
+ setImageCfg(next);
+ const current = await getSettings().catch(() => ({}));
+ await updateSettings({
+ ...current,
+ pipeline: { ...(current.pipeline || {}), imageGen: next },
+ }).catch((err) => toast.error(`Settings save failed: ${err.message}`));
+ }, []);
+
+ // URL-driven drawer state — mirrors StoryboardPanel so the settings panel
+ // is deep-linkable per project convention.
+ const [searchParams, setSearchParams] = useSearchParams();
+ const settingsOpen = searchParams.get('settings') === 'comic-image';
+ const openImageSettings = useCallback(() => {
+ setSearchParams((prev) => {
+ const next = new URLSearchParams(prev);
+ next.set('settings', 'comic-image');
+ return next;
+ });
+ }, [setSearchParams]);
+ const closeImageSettings = useCallback(() => {
+ setSearchParams((prev) => {
+ const next = new URLSearchParams(prev);
+ next.delete('settings');
+ return next;
+ });
+ }, [setSearchParams]);
+
+ const renderOpts = useMemo(() => pipelineImageCfgToRenderOpts(imageCfg), [imageCfg]);
+
const overrides = {
providerId: series?.llm?.provider || undefined,
model: series?.llm?.model || undefined,
@@ -106,6 +173,14 @@ export default function ComicScriptStage({ issue, series, onStageUpdate }) {
) : null}
</div>
<div className="flex items-center gap-2">
+ <button
+ type="button"
+ onClick={openImageSettings}
+ className="inline-flex items-center gap-1 px-2 py-1.5 rounded-lg bg-port-card border border-port-border text-gray-300 text-xs hover:border-port-accent/50 hover:text-white"
+ title={`Image gen settings — backend: ${imageCfg.mode}`}
+ >
+ <SettingsIcon size={12} /> Image gen
+ </button>
{hasScript && pages.length === 0 ? (
<button
type="button"
@@ -149,6 +224,7 @@ export default function ComicScriptStage({ issue, series, onStageUpdate }) {
issue={issue}
pageIndex={pi}
page={page}
+ renderOpts={renderOpts}
onStageUpdate={onStageUpdate}
/>
))}
@@ -169,11 +245,20 @@ export default function ComicScriptStage({ issue, series, onStageUpdate }) {
</pre>
</details>
) : null}
+
+ <Drawer open={settingsOpen} onClose={closeImageSettings} title="Comic page image gen">
+ <ImageGenSettingsForm
+ value={imageCfg}
+ onChange={persistImageCfg}
+ models={imageModels}
+ availableBackends={availableBackends}
+ />
+ </Drawer>
</div>
);
}
-function PageRow({ issue, pageIndex, page, onStageUpdate }) {
+function PageRow({ issue, pageIndex, page, renderOpts = {}, onStageUpdate }) {
const rawText = useMemo(
() => page.rawText || panelsToMarkdown(page.panels, pageIndex + 1),
[page.rawText, page.panels, pageIndex],
@@ -198,12 +283,12 @@ function PageRow({ issue, pageIndex, page, onStageUpdate }) {
const handleRender = async () => {
setRendering(true);
- const res = await generatePipelineComicPage(issue.id, pageIndex, {})
+ const res = await generatePipelineComicPage(issue.id, pageIndex, renderOpts)
.catch((err) => { toast.error(err.message || 'Render failed'); return null; });
setRendering(false);
if (res) {
onStageUpdate?.('comicPages', res.stage);
- toast.success(`Page ${pageIndex + 1} render queued`);
+ toast.success(`Page ${pageIndex + 1} render queued (${res.mode || renderOpts.mode || 'local'})`);
}
};
diff --git a/client/src/components/pipeline/stages/NounsStage.jsx b/client/src/components/pipeline/stages/NounsStage.jsx
new file mode 100644
index 0000000000..6a62a3ab66
--- /dev/null
+++ b/client/src/components/pipeline/stages/NounsStage.jsx
@@ -0,0 +1,441 @@
+/**
+ * Nouns stage — per-issue canonical-noun curation.
+ *
+ * UI-only pseudo-stage between Prose and Comic Pages. No server stage record;
+ * data lives on the series bible (`series.characters / .settings / .objects`).
+ * Two operations:
+ * 1. Extract bibles from this issue's prose (wraps the existing
+ * /pipeline/series/:id/extract-bible endpoint).
+ * 2. Render a canonical reference image per noun and pin the resulting
+ * filename onto the entry's `imageRefs[]` via a series PATCH.
+ *
+ * The renderer (server/services/pipeline/visualStages.js) reads these bibles
+ * and cites the rich descriptions in every comic-page prompt — that's the
+ * mechanism that keeps "Wren" and "the navy woman" looking consistent across
+ * pages, since Codex can't accept reference images directly.
+ */
+
+import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
+import { useSearchParams } from 'react-router-dom';
+import {
+ Library, Loader2, Users, MapPin, Package,
+ ImagePlus, Settings as SettingsIcon, ChevronDown, ChevronRight,
+} from 'lucide-react';
+import toast from '../../ui/Toast';
+import { extractPipelineBibles, updatePipelineSeries } from '../../../services/api';
+import { getWorld } from '../../../services/apiWorldBuilder';
+import { getSettings, updateSettings, generateImage } from '../../../services/apiSystem';
+import { listImageModels } from '../../../services/apiImageVideo';
+import {
+ matchCharactersInText, matchSettingsInText, matchObjectsInText,
+} from '../../../lib/scenePrompt';
+import { composeStyledPrompt } from '../../../lib/composeStyledPrompt';
+import { useAsyncAction } from '../../../hooks/useAsyncAction';
+import useMounted from '../../../hooks/useMounted';
+import useMediaJobProgress from '../../../hooks/useMediaJobProgress';
+import MediaJobThumb from '../MediaJobThumb';
+import Drawer from '../../Drawer';
+import ImageGenSettingsForm from '../../imageGen/ImageGenSettingsForm';
+import { deriveAvailableBackends } from '../../../lib/imageGenBackends';
+import {
+ PIPELINE_IMAGE_DEFAULTS,
+ readPipelineImageSettings,
+ pipelineImageCfgToRenderOpts,
+} from '../../../lib/pipelineImageDefaults';
+
+// Per-kind metadata. `descFor` picks the most visual field for ref-image
+// generation; `match` is the prose scanner that decides whether an entry
+// "appears in this issue".
+const KINDS = [
+ {
+ key: 'characters', label: 'Characters', singular: 'character', icon: Users,
+ descFor: (c) => c.physicalDescription || c.description || '',
+ match: matchCharactersInText,
+ },
+ {
+ key: 'settings', label: 'Settings', singular: 'setting', icon: MapPin,
+ descFor: (s) => [
+ s.description,
+ s.palette ? `Palette: ${s.palette}` : '',
+ s.recurringDetails,
+ ].filter(Boolean).join('. '),
+ match: matchSettingsInText,
+ },
+ {
+ key: 'objects', label: 'Objects', singular: 'object', icon: Package,
+ descFor: (o) => o.description || o.significance || '',
+ match: matchObjectsInText,
+ },
+];
+
+export default function NounsStage({ issue, series, onSeriesUpdate }) {
+ const mountedRef = useMounted();
+ const prose = (issue.stages?.prose?.output || '').trim();
+ const proseReady = prose.length > 0;
+
+ const [imageCfg, setImageCfg] = useState(PIPELINE_IMAGE_DEFAULTS);
+ const [imageModels, setImageModels] = useState([]);
+ const [sysSettings, setSysSettings] = useState(null);
+ const [world, setWorld] = useState(null);
+ // Per-entry in-flight render: { [entryId]: jobId }. NounCard subscribes to
+ // job progress and surfaces MediaJobThumb until completion — the entry's
+ // imageRefs[] is only PATCHed onto the series when the job actually
+ // finishes, so we never render broken <img>s for files that don't exist yet.
+ const [renderingJobs, setRenderingJobs] = useState({});
+
+ const availableBackends = useMemo(
+ () => deriveAvailableBackends(sysSettings, { excludeExternal: true }),
+ [sysSettings],
+ );
+
+ useEffect(() => {
+ let cancelled = false;
+ Promise.all([
+ getSettings().catch(() => ({})),
+ listImageModels().catch(() => []),
+ ]).then(([s, modelList]) => {
+ if (cancelled || !mountedRef.current) return;
+ setSysSettings(s);
+ setImageCfg(readPipelineImageSettings(s));
+ setImageModels(Array.isArray(modelList) ? modelList : []);
+ });
+ return () => { cancelled = true; };
+ }, [mountedRef]);
+
+ // Fetch the linked world so reference renders inherit the same
+ // stylePrompt + negativePrompt the comic-page renderer uses. Codex can't
+ // accept reference images, so a consistent aesthetic is the only knob
+ // keeping ref images and comic pages visually coherent.
+ useEffect(() => {
+ if (!series?.worldId) { setWorld(null); return; }
+ let cancelled = false;
+ getWorld(series.worldId).then((w) => {
+ if (cancelled || !mountedRef.current) return;
+ setWorld(w || null);
+ }).catch(() => { if (mountedRef.current) setWorld(null); });
+ return () => { cancelled = true; };
+ }, [series?.worldId, mountedRef]);
+
+ const persistImageCfg = useCallback(async (next) => {
+ setImageCfg(next);
+ const current = await getSettings().catch(() => ({}));
+ await updateSettings({
+ ...current,
+ pipeline: { ...(current.pipeline || {}), imageGen: next },
+ }).catch((err) => toast.error(`Settings save failed: ${err.message}`));
+ }, []);
+
+ const [searchParams, setSearchParams] = useSearchParams();
+ const settingsOpen = searchParams.get('settings') === 'noun-image';
+ const openSettings = useCallback(() => {
+ setSearchParams((prev) => {
+ const next = new URLSearchParams(prev);
+ next.set('settings', 'noun-image');
+ return next;
+ });
+ }, [setSearchParams]);
+ const closeSettings = useCallback(() => {
+ setSearchParams((prev) => {
+ const next = new URLSearchParams(prev);
+ next.delete('settings');
+ return next;
+ });
+ }, [setSearchParams]);
+
+ const [runExtract, extracting] = useAsyncAction(
+ () => extractPipelineBibles(series.id, { issueId: issue.id }),
+ { errorMessage: 'Extraction failed' },
+ );
+
+ const handleExtract = async () => {
+ if (!series || !proseReady) return;
+ const result = await runExtract();
+ if (!result || !mountedRef.current) return;
+ onSeriesUpdate?.(result.series);
+ const counts = KINDS
+ .map((k) => `${result.series[k.key]?.length ?? 0} ${k.key}`)
+ .join(', ');
+ toast.success(`Bibles updated — ${counts}`);
+ };
+
+ // Queue a reference render. The filename ISN'T persisted onto the entry's
+ // imageRefs[] yet — NounCard subscribes to job progress and calls
+ // `handleRefCompleted` once the file actually exists. Without that defer,
+ // the card would <img src> a not-yet-written /data/images/<jobId>.png and
+ // show the OS broken-image icon mid-render.
+ const handleRenderRef = async (kind, entry) => {
+ const description = kind.descFor(entry);
+ if (!description.trim()) {
+ toast.error(`Add a description before generating a reference for ${entry.name}`);
+ return;
+ }
+ const baseOpts = pipelineImageCfgToRenderOpts(imageCfg);
+ // Inject the world's stylePrompt as a prefix and merge negativePrompts so
+ // ref images and comic pages share the same aesthetic (Codex doesn't
+ // accept reference images, so style consistency comes from text alone).
+ const userPrompt = `${entry.name}: ${description}`;
+ const styled = composeStyledPrompt(
+ userPrompt,
+ baseOpts.negativePrompt || '',
+ world ? { prompt: world.stylePrompt, negativePrompt: world.negativePrompt } : null,
+ );
+ const payload = {
+ ...baseOpts,
+ prompt: styled.prompt,
+ negativePrompt: styled.negativePrompt || undefined,
+ };
+ const queued = await generateImage(payload)
+ .catch((err) => { toast.error(err.message || 'Render failed'); return null; });
+ if (!queued?.jobId || !mountedRef.current) return;
+ setRenderingJobs((prev) => ({ ...prev, [entry.id]: queued.jobId }));
+ toast.success(`Rendering reference for ${entry.name}`);
+ };
+
+ // Pin a freshly-completed render onto the series bible. Server replaces the
+ // full bible array on PATCH, so we send the kind's full list with this
+ // entry mutated. Single-user app — no race here.
+ const handleRefCompleted = useCallback(async (kindKey, entryId, filename) => {
+ if (!filename) return;
+ setRenderingJobs((prev) => {
+ if (!prev[entryId]) return prev;
+ const next = { ...prev };
+ delete next[entryId];
+ return next;
+ });
+ const list = (series[kindKey] || []).map((e) =>
+ e.id === entryId
+ ? { ...e, imageRefs: [...(e.imageRefs || []), filename] }
+ : e,
+ );
+ const updated = await updatePipelineSeries(series.id, { [kindKey]: list })
+ .catch((err) => { toast.error(`Save failed: ${err.message}`); return null; });
+ if (updated && mountedRef.current) onSeriesUpdate?.(updated);
+ }, [series, onSeriesUpdate, mountedRef]);
+
+ const handleRefFailed = useCallback((entryId, errMsg) => {
+ setRenderingJobs((prev) => {
+ if (!prev[entryId]) return prev;
+ const next = { ...prev };
+ delete next[entryId];
+ return next;
+ });
+ if (errMsg) toast.error(`Render failed: ${errMsg}`);
+ }, []);
+
+ if (!series) {
+ return <p className="text-sm text-gray-500 italic">Loading series…</p>;
+ }
+
+ return (
+ <div className="space-y-5">
+ <header className="flex items-center justify-between gap-3 flex-wrap">
+ <div>
+ <h2 className="text-lg font-semibold text-white">Nouns</h2>
+ <p className="text-xs text-gray-500 mt-0.5">
+ Canonical references for the people, places, and things in this issue.
+ The comic-page renderer cites these descriptions to keep characters and
+ settings visually consistent page-to-page.
+ </p>
+ </div>
+ <div className="flex items-center gap-2">
+ <button
+ type="button"
+ onClick={openSettings}
+ className="inline-flex items-center gap-1 px-2 py-1.5 rounded-lg bg-port-card border border-port-border text-gray-300 text-xs hover:border-port-accent/50 hover:text-white"
+ title={`Reference image gen settings — backend: ${imageCfg.mode}`}
+ >
+ <SettingsIcon size={12} /> Image gen
+ </button>
+ <button
+ type="button"
+ onClick={handleExtract}
+ disabled={extracting || !proseReady}
+ title={proseReady ? 'Extract characters, settings, and objects from the prose' : 'Generate prose first'}
+ className="inline-flex items-center gap-2 px-3 py-1.5 rounded-lg bg-port-accent text-white text-sm font-medium disabled:opacity-40"
+ >
+ {extracting ? <Loader2 size={14} className="animate-spin" /> : <Library size={14} />}
+ Extract from prose
+ </button>
+ </div>
+ </header>
+
+ {!proseReady ? (
+ <p className="text-sm text-gray-400 italic">
+ Generate the prose stage first, then come back here to extract and curate the nouns.
+ </p>
+ ) : null}
+
+ {KINDS.map((kind) => (
+ <KindSection
+ key={kind.key}
+ kind={kind}
+ all={series[kind.key] || []}
+ prose={prose}
+ renderingJobs={renderingJobs}
+ onRender={(entry) => handleRenderRef(kind, entry)}
+ onJobCompleted={(entryId, filename) => handleRefCompleted(kind.key, entryId, filename)}
+ onJobFailed={handleRefFailed}
+ />
+ ))}
+
+ <Drawer open={settingsOpen} onClose={closeSettings} title="Reference image gen">
+ <ImageGenSettingsForm
+ value={imageCfg}
+ onChange={persistImageCfg}
+ models={imageModels}
+ availableBackends={availableBackends}
+ />
+ </Drawer>
+ </div>
+ );
+}
+
+function KindSection({ kind, all, prose, renderingJobs, onRender, onJobCompleted, onJobFailed }) {
+ const Icon = kind.icon;
+ const inIssue = useMemo(() => kind.match(prose, all), [prose, all, kind]);
+ const inIssueIds = useMemo(() => new Set(inIssue.map((e) => e.id || e.name)), [inIssue]);
+ const others = useMemo(
+ () => all.filter((e) => !inIssueIds.has(e.id || e.name)),
+ [all, inIssueIds],
+ );
+ const [showOthers, setShowOthers] = useState(false);
+
+ return (
+ <section className="rounded-lg border border-port-border bg-port-card/40">
+ <div className="flex items-center gap-2 px-3 py-2 border-b border-port-border">
+ <Icon size={14} className="text-gray-400" />
+ <h3 className="text-sm font-semibold text-white">{kind.label}</h3>
+ <span className="text-[10px] text-gray-500">
+ {inIssue.length} in issue · {all.length} total
+ </span>
+ </div>
+
+ <div className="p-3 space-y-3">
+ <div>
+ <div className="text-[10px] uppercase tracking-wider text-gray-500 mb-2">
+ Appears in this issue
+ </div>
+ {inIssue.length === 0 ? (
+ <p className="text-xs text-gray-500 italic">
+ No matches yet. Extract from prose, or check that bible names line up with how the prose refers to them.
+ </p>
+ ) : (
+ <ul className="space-y-2">
+ {inIssue.map((entry) => (
+ <NounCard
+ key={entry.id || entry.name}
+ kind={kind}
+ entry={entry}
+ inFlightJobId={renderingJobs[entry.id]}
+ onRender={() => onRender(entry)}
+ onJobCompleted={onJobCompleted}
+ onJobFailed={onJobFailed}
+ />
+ ))}
+ </ul>
+ )}
+ </div>
+
+ {others.length > 0 ? (
+ <details open={showOthers} onToggle={(e) => setShowOthers(e.currentTarget.open)}>
+ <summary className="cursor-pointer text-[10px] uppercase tracking-wider text-gray-500 hover:text-white flex items-center gap-1">
+ {showOthers ? <ChevronDown size={10} /> : <ChevronRight size={10} />}
+ Other series canon ({others.length})
+ </summary>
+ <ul className="space-y-2 mt-2">
+ {others.map((entry) => (
+ <NounCard
+ key={entry.id || entry.name}
+ kind={kind}
+ entry={entry}
+ inFlightJobId={renderingJobs[entry.id]}
+ onRender={() => onRender(entry)}
+ onJobCompleted={onJobCompleted}
+ onJobFailed={onJobFailed}
+ />
+ ))}
+ </ul>
+ </details>
+ ) : null}
+ </div>
+ </section>
+ );
+}
+
+function NounCard({ kind, entry, inFlightJobId, onRender, onJobCompleted, onJobFailed }) {
+ const description = kind.descFor(entry);
+ const refs = Array.isArray(entry.imageRefs) ? entry.imageRefs : [];
+
+ // Subscribe to the in-flight job so we can fire onJobCompleted exactly
+ // once when the render finishes. MediaJobThumb opens its own subscription
+ // for visuals; both are filtered by jobId so they coexist without
+ // cross-talk. settledRef prevents duplicate completion callbacks under
+ // React 18 StrictMode's mount→cleanup→mount double-fire in dev.
+ const { status, filename, error } = useMediaJobProgress(inFlightJobId);
+ const settledRef = useRef(null);
+ useEffect(() => {
+ if (!inFlightJobId) { settledRef.current = null; return; }
+ if (settledRef.current === inFlightJobId) return;
+ if (status === 'completed' && filename) {
+ settledRef.current = inFlightJobId;
+ onJobCompleted?.(entry.id, filename);
+ } else if (status === 'failed' || status === 'canceled') {
+ settledRef.current = inFlightJobId;
+ onJobFailed?.(entry.id, error || status);
+ }
+ }, [inFlightJobId, status, filename, error, entry.id, onJobCompleted, onJobFailed]);
+
+ return (
+ <li className="rounded border border-port-border bg-port-bg/60 p-2">
+ <div className="flex items-start gap-3">
+ <div className="flex-1 min-w-0">
+ <div className="flex items-center gap-2">
+ <span className="text-sm text-white font-medium truncate">{entry.name}</span>
+ {entry.aliases?.length ? (
+ <span className="text-[10px] text-gray-500 truncate">
+ aka {entry.aliases.join(', ')}
+ </span>
+ ) : null}
+ </div>
+ <p className="text-xs text-gray-400 mt-1 line-clamp-3 whitespace-pre-wrap">
+ {description || <em className="text-gray-600">No description yet.</em>}
+ </p>
+ </div>
+ <button
+ type="button"
+ onClick={onRender}
+ disabled={!description.trim() || !!inFlightJobId}
+ className="shrink-0 inline-flex items-center gap-1 px-2 py-1 text-[10px] rounded border border-port-border text-gray-300 hover:bg-port-border/40 hover:text-white disabled:opacity-40"
+ title={description.trim() ? `Render a canonical reference image for ${entry.name}` : 'Add a description first'}
+ >
+ {inFlightJobId ? <Loader2 size={10} className="animate-spin" /> : <ImagePlus size={10} />}
+ Render reference
+ </button>
+ </div>
+ {(refs.length > 0 || inFlightJobId) ? (
+ <div className="flex items-center gap-2 mt-2 flex-wrap">
+ {inFlightJobId ? (
+ <MediaJobThumb jobId={inFlightJobId} label={`${entry.name} reference`} size="sm" />
+ ) : null}
+ {refs.map((ref) => (
+ <a
+ key={ref}
+ href={`/data/images/${ref}`}
+ target="_blank"
+ rel="noopener noreferrer"
+ title={ref}
+ className="w-16 h-16 bg-port-bg rounded overflow-hidden border border-port-border hover:border-port-accent/50"
+ >
+ <img
+ src={`/data/images/${ref}`}
+ alt={`${entry.name} reference`}
+ className="w-full h-full object-cover"
+ loading="lazy"
+ />
+ </a>
+ ))}
+ </div>
+ ) : null}
+ </li>
+ );
+}
diff --git a/client/src/components/pipeline/stages/ProseStage.jsx b/client/src/components/pipeline/stages/ProseStage.jsx
index c0d55f5be6..a4cd551820 100644
--- a/client/src/components/pipeline/stages/ProseStage.jsx
+++ b/client/src/components/pipeline/stages/ProseStage.jsx
@@ -1,28 +1,8 @@
-import { Library, Loader2 } from 'lucide-react';
-import toast from '../../ui/Toast';
-import { extractPipelineBibles } from '../../../services/api';
-import { useAsyncAction } from '../../../hooks/useAsyncAction';
import TextStagePanel from './TextStagePanel';
-export default function ProseStage({ issue, series, onStageUpdate, onSeriesUpdate }) {
- const proseReady = (issue.stages?.prose?.output || '').trim().length > 0;
-
- const [runExtract, extracting] = useAsyncAction(
- () => extractPipelineBibles(series.id, { issueId: issue.id }),
- { errorMessage: 'Extraction failed' },
- );
-
- const handleExtract = async () => {
- if (!series) return;
- const result = await runExtract();
- if (!result) return;
- onSeriesUpdate?.(result.series);
- const counts = ['characters', 'settings', 'objects'].map(
- (k) => `${result.series[k]?.length ?? 0} ${k}`,
- ).join(', ');
- toast.success(`Bibles updated — ${counts}`);
- };
-
+// Bibles extraction lives on the Nouns stage now — kept the prose panel a
+// thin pass-through so the workflow is Idea → Prose → Nouns → Comic.
+export default function ProseStage({ issue, onStageUpdate }) {
return (
<TextStagePanel
issue={issue}
@@ -30,18 +10,6 @@ export default function ProseStage({ issue, series, onStageUpdate, onSeriesUpdat
onStageUpdate={onStageUpdate}
generateLabel="Draft prose"
outputPlaceholder="An 800–1500 word short-story draft for this issue. Will be lightly structured with `## Scene N — Slugline` H2 markers so the comic and TV script stages have stable anchors."
- extraActions={(
- <button
- type="button"
- onClick={handleExtract}
- disabled={extracting || !proseReady}
- title={proseReady ? 'Extract characters, settings, and objects from the prose into the series bibles' : 'Generate prose first'}
- className="inline-flex items-center gap-2 px-3 py-1.5 rounded-lg bg-port-card border border-port-border text-white text-sm hover:border-port-accent/50 disabled:opacity-40"
- >
- {extracting ? <Loader2 size={14} className="animate-spin" /> : <Library size={14} />}
- Extract bibles
- </button>
- )}
/>
);
}
diff --git a/client/src/lib/pipelineImageDefaults.js b/client/src/lib/pipelineImageDefaults.js
new file mode 100644
index 0000000000..d3938184e0
--- /dev/null
+++ b/client/src/lib/pipelineImageDefaults.js
@@ -0,0 +1,67 @@
+// Pipeline comic-page image-gen defaults + settings reader.
+//
+// Mirrors the shape of wrImageDefaults.js but adds the comic-page knobs
+// (negativePrompt + extraStyle) and prefers Codex when it's enabled. Cloud
+// models render multi-panel pages dramatically better than local diffusion,
+// so Codex is the right default whenever the user has it wired up.
+
+import { IMAGE_GEN_MODE } from './imageGenBackends';
+
+// 1024×1536 = 2:3 portrait, the closest preset to a real comic-book trim
+// (~0.65 ratio). The "hi-res portrait" entry in imageGenResolutions is
+// gated to codex + FLUX2, which lines up with our codex-first default.
+export const PIPELINE_IMAGE_DEFAULTS = Object.freeze({
+ mode: IMAGE_GEN_MODE.LOCAL,
+ modelId: 'flux2-klein-4b',
+ width: 1024,
+ height: 1536,
+ steps: '',
+ guidance: '',
+ seed: '',
+ negativePrompt: '',
+ extraStyle: '',
+});
+
+// Resolve the per-render config. Codex-enabled systems default to codex
+// mode unless the user explicitly stored a different mode on
+// `settings.pipeline.imageGen` — that override always wins so the form
+// stays sticky.
+export function readPipelineImageSettings(settings) {
+ const stored = settings?.pipeline?.imageGen || {};
+ const codexEnabled = settings?.imageGen?.codex?.enabled === true;
+ const defaultMode = codexEnabled ? IMAGE_GEN_MODE.CODEX : PIPELINE_IMAGE_DEFAULTS.mode;
+ return {
+ mode: stored.mode || defaultMode,
+ modelId: stored.modelId || PIPELINE_IMAGE_DEFAULTS.modelId,
+ width: Number.isFinite(stored.width) ? stored.width : PIPELINE_IMAGE_DEFAULTS.width,
+ height: Number.isFinite(stored.height) ? stored.height : PIPELINE_IMAGE_DEFAULTS.height,
+ steps: stored.steps != null && stored.steps !== '' ? String(stored.steps) : '',
+ guidance: stored.guidance != null && stored.guidance !== '' ? String(stored.guidance) : '',
+ seed: stored.seed != null && stored.seed !== '' ? String(stored.seed) : '',
+ negativePrompt: stored.negativePrompt || '',
+ extraStyle: stored.extraStyle || '',
+ };
+}
+
+// Strip empty strings + coerce numerics so the request body only carries
+// fields the server should act on. Empty strings would otherwise serialize
+// to "" and trip the zod number coercion.
+export function pipelineImageCfgToRenderOpts(cfg) {
+ const opts = { mode: cfg.mode };
+ if (cfg.mode === IMAGE_GEN_MODE.LOCAL && cfg.modelId) opts.modelId = cfg.modelId;
+ if (Number.isFinite(cfg.width)) opts.width = cfg.width;
+ if (Number.isFinite(cfg.height)) opts.height = cfg.height;
+ if (cfg.mode !== IMAGE_GEN_MODE.CODEX) {
+ const steps = Number(cfg.steps);
+ if (Number.isFinite(steps) && steps > 0) opts.steps = steps;
+ const guidance = Number(cfg.guidance);
+ if (Number.isFinite(guidance) && guidance >= 0) opts.guidance = guidance;
+ const seed = Number(cfg.seed);
+ if (Number.isFinite(seed) && seed >= 0) opts.seed = seed;
+ }
+ const neg = (cfg.negativePrompt || '').trim();
+ if (neg) opts.negativePrompt = neg;
+ const extra = (cfg.extraStyle || '').trim();
+ if (extra) opts.extraStyle = extra;
+ return opts;
+}
diff --git a/client/src/lib/scenePrompt.js b/client/src/lib/scenePrompt.js
index 358088652d..65f947cbae 100644
--- a/client/src/lib/scenePrompt.js
+++ b/client/src/lib/scenePrompt.js
@@ -36,7 +36,26 @@ export function matchSceneCharacters(sceneCharacterNames = [], charByKey) {
}
export function matchCharactersInText(text, allCharacters) {
- if (!text || !Array.isArray(allCharacters) || !allCharacters.length) return [];
+ return matchEntriesByCandidates(text, allCharacters, (c) => [c.name, ...(c.aliases || [])]);
+}
+
+export function buildSettingByKey(allSettings) {
+ const map = new Map();
+ for (const setting of allSettings || []) {
+ const key = normalizeSlugline(setting.slugline || setting.name);
+ if (!key) continue;
+ map.set(key, setting);
+ }
+ return map;
+}
+
+export function matchSceneSetting(sceneSlugline, settingByKey) {
+ if (!sceneSlugline) return null;
+ return settingByKey?.get(normalizeSlugline(sceneSlugline)) || null;
+}
+
+function matchEntriesByCandidates(text, entries, candidatesFn) {
+ if (!text || !Array.isArray(entries) || !entries.length) return [];
const haystack = String(text);
const matched = [];
const seen = new Set();
@@ -45,31 +64,24 @@ export function matchCharactersInText(text, allCharacters) {
const escaped = needle.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
return new RegExp(`\\b${escaped}\\b`, 'i').test(haystack);
};
- for (const profile of allCharacters) {
- const key = profile.id || profile.name;
+ for (const entry of entries) {
+ const key = entry.id || entry.name;
if (!key || seen.has(key)) continue;
- const candidates = [profile.name, ...(profile.aliases || [])].filter(Boolean);
+ const candidates = candidatesFn(entry).filter(Boolean);
if (candidates.some(wordBoundary)) {
- matched.push(profile);
+ matched.push(entry);
seen.add(key);
}
}
return matched;
}
-export function buildSettingByKey(allSettings) {
- const map = new Map();
- for (const setting of allSettings || []) {
- const key = normalizeSlugline(setting.slugline || setting.name);
- if (!key) continue;
- map.set(key, setting);
- }
- return map;
+export function matchSettingsInText(text, allSettings) {
+ return matchEntriesByCandidates(text, allSettings, (s) => [s.name]);
}
-export function matchSceneSetting(sceneSlugline, settingByKey) {
- if (!sceneSlugline) return null;
- return settingByKey?.get(normalizeSlugline(sceneSlugline)) || null;
+export function matchObjectsInText(text, allObjects) {
+ return matchEntriesByCandidates(text, allObjects, (o) => [o.name, ...(o.aliases || [])]);
}
export function buildScenePrompt(workTitle, scene, matchedCharacters, worldStyle = '', matchedSetting = null) {
diff --git a/client/src/pages/PipelineIssue.jsx b/client/src/pages/PipelineIssue.jsx
index e9fe81eab7..98d2c3dc89 100644
--- a/client/src/pages/PipelineIssue.jsx
+++ b/client/src/pages/PipelineIssue.jsx
@@ -10,7 +10,7 @@ import { useEffect, useState, useMemo } from 'react';
import { Link, useParams, useNavigate } from 'react-router-dom';
import {
ArrowLeft, Sparkles, Loader2, X, Lightbulb, BookOpen, FileText, Film as FilmIcon,
- LayoutGrid, Image as ImageIcon, Clapperboard,
+ LayoutGrid, Image as ImageIcon, Clapperboard, Users,
} from 'lucide-react';
import toast from '../components/ui/Toast';
import {
@@ -21,6 +21,7 @@ import {
import { usePipelineAutoRunProgress } from '../hooks/usePipelineAutoRunProgress';
import IdeaStage from '../components/pipeline/stages/IdeaStage';
import ProseStage from '../components/pipeline/stages/ProseStage';
+import NounsStage from '../components/pipeline/stages/NounsStage';
import ComicScriptStage from '../components/pipeline/stages/ComicScriptStage';
import TVScriptStage from '../components/pipeline/stages/TVScriptStage';
import ComicPagesStage from '../components/pipeline/stages/ComicPagesStage';
@@ -31,6 +32,7 @@ import SeriesLlmPicker from '../components/pipeline/SeriesLlmPicker';
const STAGE_ICONS = {
idea: Lightbulb,
prose: BookOpen,
+ nouns: Users,
comicScript: FileText,
tvScript: FilmIcon,
comicPages: LayoutGrid,
@@ -41,6 +43,7 @@ const STAGE_ICONS = {
const STAGE_COMPONENTS = {
idea: IdeaStage,
prose: ProseStage,
+ nouns: NounsStage,
comicScript: ComicScriptStage,
tvScript: TVScriptStage,
comicPages: ComicPagesStage,
diff --git a/client/src/services/apiPipeline.js b/client/src/services/apiPipeline.js
index 73d6781498..5fcd1f1e0f 100644
--- a/client/src/services/apiPipeline.js
+++ b/client/src/services/apiPipeline.js
@@ -1,27 +1,36 @@
import { request } from './apiCore.js';
// Stage IDs mirror server/services/pipeline/issues.js — keep these in sync.
+// `nouns` is a UI-only pseudo-stage: it has no server stage record + no LLM
+// template, and its actions wrap existing endpoints (extract-bible + the
+// generic image gen API). It appears in PIPELINE_TAB_STAGES so it gets a tab
+// between Prose and Comic Pages, but it's NOT in server TEXT_STAGE_IDS — so
+// auto-run text chain skips it and POST /stages/nouns/generate would 400.
export const PIPELINE_TEXT_STAGES = Object.freeze(['idea', 'prose', 'comicScript', 'tvScript']);
export const PIPELINE_VISUAL_STAGES = Object.freeze(['comicPages', 'storyboards', 'episodeVideo']);
-export const PIPELINE_STAGES = Object.freeze([...PIPELINE_TEXT_STAGES, ...PIPELINE_VISUAL_STAGES]);
-
-// Stages that appear as their own tab. `comicPages` is folded into the Comic
-// Script tab (one merged page-by-page editor) — the data still flows through
-// the comicPages routes, the tab is just hidden.
-export const PIPELINE_TAB_STAGES = Object.freeze(
- PIPELINE_STAGES.filter((id) => id !== 'comicPages'),
-);
+export const PIPELINE_UI_STAGES = Object.freeze(['nouns']);
+export const PIPELINE_STAGES = Object.freeze([...PIPELINE_TEXT_STAGES, ...PIPELINE_VISUAL_STAGES, ...PIPELINE_UI_STAGES]);
+
+// Stages that appear as their own tab, in display order. `comicPages` is
+// folded into the Comic Script tab (one merged page-by-page editor) — the
+// data still flows through the comicPages routes, the tab is just hidden.
+// `nouns` is inserted between Prose and Comic Pages so the workflow reads
+// Idea → Prose → Nouns → Comic → TV Script → Storyboards → Episode Video.
+export const PIPELINE_TAB_STAGES = Object.freeze([
+ 'idea', 'prose', 'nouns', 'comicScript', 'tvScript', 'storyboards', 'episodeVideo',
+]);
export const PIPELINE_STAGE_LABELS = Object.freeze({
idea: 'Idea',
prose: 'Prose',
+ nouns: 'Nouns',
// `comicScript` stage now owns the merged Comic Pages editor — the
// standalone Comic Pages tab is hidden via PIPELINE_TAB_STAGES below.
- comicScript: 'Comic Pages',
+ comicScript: 'Comic',
tvScript: 'TV Script',
- comicPages: 'Comic Pages',
+ comicPages: 'Comic',
storyboards: 'Storyboards',
- episodeVideo: 'Episode Video',
+ episodeVideo: 'Video',
});
export const PIPELINE_TARGET_FORMATS = Object.freeze(['comic', 'tv', 'comic+tv']);
diff --git a/server/lib/scenePrompt.js b/server/lib/scenePrompt.js
index 51123c6928..b73db757e5 100644
--- a/server/lib/scenePrompt.js
+++ b/server/lib/scenePrompt.js
@@ -49,7 +49,28 @@ export function matchSceneCharacters(sceneCharacterNames = [], charByKey) {
* grounded in bible-canonical descriptions for everyone the LLM named.
*/
export function matchCharactersInText(text, allCharacters) {
- if (!text || !Array.isArray(allCharacters) || !allCharacters.length) return [];
+ return matchEntriesByCandidates(text, allCharacters, (c) => [c.name, ...(c.aliases || [])]);
+}
+
+export function buildSettingByKey(allSettings) {
+ const map = new Map();
+ for (const setting of allSettings || []) {
+ const key = normalizeSlugline(setting.slugline || setting.name);
+ if (!key) continue;
+ map.set(key, setting);
+ }
+ return map;
+}
+
+export function matchSceneSetting(sceneSlugline, settingByKey) {
+ if (!sceneSlugline) return null;
+ return settingByKey?.get(normalizeSlugline(sceneSlugline)) || null;
+}
+
+// Shared word-boundary scanner used by the *-InText helpers below. Returns
+// the entries whose `candidates(entry)` strings appear in the haystack.
+function matchEntriesByCandidates(text, entries, candidatesFn) {
+ if (!text || !Array.isArray(entries) || !entries.length) return [];
const haystack = String(text);
const matched = [];
const seen = new Set();
@@ -58,31 +79,30 @@ export function matchCharactersInText(text, allCharacters) {
const escaped = needle.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
return new RegExp(`\\b${escaped}\\b`, 'i').test(haystack);
};
- for (const profile of allCharacters) {
- const key = profile.id || profile.name;
+ for (const entry of entries) {
+ const key = entry.id || entry.name;
if (!key || seen.has(key)) continue;
- const candidates = [profile.name, ...(profile.aliases || [])].filter(Boolean);
+ const candidates = candidatesFn(entry).filter(Boolean);
if (candidates.some(wordBoundary)) {
- matched.push(profile);
+ matched.push(entry);
seen.add(key);
}
}
return matched;
}
-export function buildSettingByKey(allSettings) {
- const map = new Map();
- for (const setting of allSettings || []) {
- const key = normalizeSlugline(setting.slugline || setting.name);
- if (!key) continue;
- map.set(key, setting);
- }
- return map;
+// Scan free-form prose for bible-canonical settings. Mirrors
+// `matchCharactersInText` but tests against `name` (settings have no aliases
+// in the canonical schema — slugline is for screenplay matching, not prose).
+export function matchSettingsInText(text, allSettings) {
+ return matchEntriesByCandidates(text, allSettings, (s) => [s.name]);
}
-export function matchSceneSetting(sceneSlugline, settingByKey) {
- if (!sceneSlugline) return null;
- return settingByKey?.get(normalizeSlugline(sceneSlugline)) || null;
+// Scan free-form prose for bible-canonical objects. Mirrors
+// `matchCharactersInText` — objects carry `name` + `aliases[]` per
+// `server/lib/storyBible.js:PROMPT_FIELDS`.
+export function matchObjectsInText(text, allObjects) {
+ return matchEntriesByCandidates(text, allObjects, (o) => [o.name, ...(o.aliases || [])]);
}
/**
diff --git a/server/lib/storyBible.js b/server/lib/storyBible.js
index f9319790a0..c8feb9af3b 100644
--- a/server/lib/storyBible.js
+++ b/server/lib/storyBible.js
@@ -175,6 +175,7 @@ export function sanitizeSetting(raw, { idPrefix = DEFAULT_ID_PREFIX.setting, pre
weather: trimTo(raw.weather, BIBLE_LIMITS.WEATHER_MAX),
recurringDetails: trimTo(raw.recurringDetails, BIBLE_LIMITS.RECURRING_DETAILS_MAX),
notes: trimTo(raw.notes, BIBLE_LIMITS.NOTES_MAX),
+ imageRefs: cleanStringArray(raw.imageRefs, BIBLE_LIMITS.IMAGE_REF_MAX, BIBLE_LIMITS.IMAGE_REFS_PER_ENTRY_MAX),
firstAppearance: ensureFirstAppearance(raw.firstAppearance),
evidence: cleanStringArray(raw.evidence, BIBLE_LIMITS.EVIDENCE_ITEM_MAX, BIBLE_LIMITS.EVIDENCE_PER_ENTRY_MAX),
missingFromProse: cleanStringArray(raw.missingFromProse, BIBLE_LIMITS.EVIDENCE_ITEM_MAX, BIBLE_LIMITS.EVIDENCE_PER_ENTRY_MAX),
@@ -196,6 +197,7 @@ export function sanitizeObject(raw, { idPrefix = DEFAULT_ID_PREFIX.object, prese
description: trimTo(raw.description, BIBLE_LIMITS.OBJECT_DESCRIPTION_MAX),
significance: trimTo(raw.significance, BIBLE_LIMITS.SIGNIFICANCE_MAX),
notes: trimTo(raw.notes, BIBLE_LIMITS.NOTES_MAX),
+ imageRefs: cleanStringArray(raw.imageRefs, BIBLE_LIMITS.IMAGE_REF_MAX, BIBLE_LIMITS.IMAGE_REFS_PER_ENTRY_MAX),
firstAppearance: ensureFirstAppearance(raw.firstAppearance),
evidence: cleanStringArray(raw.evidence, BIBLE_LIMITS.EVIDENCE_ITEM_MAX, BIBLE_LIMITS.EVIDENCE_PER_ENTRY_MAX),
missingFromProse: cleanStringArray(raw.missingFromProse, BIBLE_LIMITS.EVIDENCE_ITEM_MAX, BIBLE_LIMITS.EVIDENCE_PER_ENTRY_MAX),
diff --git a/server/routes/pipeline.js b/server/routes/pipeline.js
index 756f5eafe5..e5a08d5426 100644
--- a/server/routes/pipeline.js
+++ b/server/routes/pipeline.js
@@ -237,6 +237,7 @@ const visualGenerateSchema = 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(),
+ seed: z.number().int().min(0).optional(),
});
// Full-comic-page render: same knobs as panel render minus `description` /
@@ -252,6 +253,7 @@ const comicPageRenderSchema = 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(),
+ seed: z.number().int().min(0).optional(),
});
const episodeVideoSchema = z.object({
diff --git a/server/services/pipeline/visualStages.js b/server/services/pipeline/visualStages.js
index 1d2aa3c821..bee5526cb3 100644
--- a/server/services/pipeline/visualStages.js
+++ b/server/services/pipeline/visualStages.js
@@ -32,6 +32,7 @@ import { ServerError } from '../../lib/errorHandler.js';
import {
buildScenePrompt, buildSettingByKey, matchSceneSetting,
buildCharByKey, matchSceneCharacters, matchCharactersInText,
+ matchSettingsInText, matchObjectsInText,
} from '../../lib/scenePrompt.js';
import { composeStyledPrompt } from '../../lib/composeStyledPrompt.js';
import { getDefaultVideoModelId, getVideoModels } from '../../lib/mediaModels.js';
@@ -83,6 +84,8 @@ const enqueueImageJob = ({ prompt, world, settings, options, mode, owner, logLin
steps: options.steps,
guidance: options.guidance ?? options.cfgScale,
cfgScale: options.cfgScale,
+ // Honored by local mflux + diffusers runners; codex picks its own.
+ ...(Number.isFinite(options.seed) ? { seed: options.seed } : {}),
};
const params = mode === 'codex'
? { mode: 'codex', codexPath: settings.imageGen?.codex?.codexPath, model: settings.imageGen?.codex?.model, ...baseParams }
@@ -104,7 +107,10 @@ export function composeVisualPrompt({ series, description, slugline = '', extraS
return applyWorldStyle(scenePrompt, world);
}
-export function composeComicPagePrompt({ series, world, page, pageNumber, extraStyle = '', matchedCharacters = [] }) {
+export function composeComicPagePrompt({
+ series, world, page, pageNumber, extraStyle = '',
+ matchedCharacters = [], matchedSettings = [], matchedObjects = [],
+}) {
const panels = Array.isArray(page?.panels) ? page.panels : [];
if (panels.length === 0) return '';
@@ -116,6 +122,30 @@ export function composeComicPagePrompt({ series, world, page, pageNumber, extraS
.map((c) => `${c.name}: ${c.desc}`)
.join('; ');
+ // Setting baseline: pull description + palette + recurringDetails per matched
+ // setting. Same pattern as buildScenePrompt's settingFrags, but multi-setting
+ // (a single comic page can span more than one location).
+ const settingsClause = (matchedSettings || [])
+ .map((s) => {
+ const parts = [s.name && `${s.name}:`, (s.description || '').trim()].filter(Boolean);
+ const head = parts.join(' ');
+ const tail = [
+ s.palette ? `palette: ${s.palette.trim()}` : '',
+ (s.recurringDetails || '').trim(),
+ ].filter(Boolean).join('; ');
+ return [head, tail].filter(Boolean).join('. ');
+ })
+ .filter(Boolean)
+ .join(' | ');
+
+ // Notable objects/props/vehicles cited in the prose. Keeps signature props
+ // (e.g. "the brass key", "Wren's sloop") visually canonical across pages.
+ const notable = (matchedObjects || [])
+ .map((o) => ({ name: o.name, desc: (o.description || '').trim() }))
+ .filter((o) => o.name && o.desc)
+ .map((o) => `${o.name}: ${o.desc}`)
+ .join('; ');
+
// Append a sentence-terminator unless the source text already ends in one —
// prose extracted from a script often carries its own `.`, `!`, or `?`, and
// double-punctuating like "...sunstreaming in.." is noisy in prompts. The
@@ -152,8 +182,10 @@ export function composeComicPagePrompt({ series, world, page, pageNumber, extraS
const layout = `A single full printable comic book page${seriesClause}, page ${pageNumber}. Render a balanced multi-panel comic page layout with ${panels.length} clearly bordered panel${panels.length === 1 ? '' : 's'} arranged for left-to-right, top-to-bottom reading. Include lettered speech balloons for dialogue, rectangular narration captions, and stylized SFX where indicated. Each panel must be visually distinct, with consistent character designs across panels.${styleClause}`;
const featuringClause = featuring ? `\n\nFeaturing — ${featuring}` : '';
+ const settingClause = settingsClause ? `\n\nSetting — ${settingsClause}` : '';
+ const notableClause = notable ? `\n\nNotable — ${notable}` : '';
- return applyWorldStyle(`${layout}${featuringClause}\n\n${panelLines.join('\n\n')}`, world);
+ return applyWorldStyle(`${layout}${featuringClause}${settingClause}${notableClause}\n\n${panelLines.join('\n\n')}`, world);
}
/**
@@ -186,19 +218,43 @@ export async function enqueueVisualComicPage(issueId, options = {}) {
}
const mode = resolveMode(options, settings);
- // Dialogue carries structured CAPS names, so match via charByKey rather than
- // scanning panel description prose (cheaper and more reliable).
- const charByKey = buildCharByKey(series.characters || []);
+
+ // Build a free-text haystack from every panel's prose (description +
+ // caption + sfx). Dialogue lines feed character matching via CAPS names
+ // separately because the parser already structures them.
+ const proseHaystack = page.panels
+ .flatMap((p) => [p.description, p.caption, p.sfx])
+ .filter(Boolean)
+ .join('\n');
const dialogueNames = page.panels.flatMap((p) =>
(p.dialogue || []).map((d) => d.character).filter(Boolean),
);
- const matchedCharacters = matchSceneCharacters(dialogueNames, charByKey);
+
+ // Characters: union of (a) dialogue CAPS speakers and (b) anyone named in
+ // panel prose. Deduplicates on id/name inside the matchers.
+ const charByKey = buildCharByKey(series.characters || []);
+ const fromDialogue = matchSceneCharacters(dialogueNames, charByKey);
+ const fromProse = matchCharactersInText(proseHaystack, series.characters || []);
+ const seenCharKeys = new Set();
+ const matchedCharacters = [...fromDialogue, ...fromProse].filter((c) => {
+ const k = c.id || c.name;
+ if (seenCharKeys.has(k)) return false;
+ seenCharKeys.add(k);
+ return true;
+ });
+
+ // Settings + objects: text-match against the panel prose. Codex can't take
+ // reference images, so rich text descriptions in the prompt are how we
+ // keep environments and signature props visually consistent page-to-page.
+ const matchedSettings = matchSettingsInText(proseHaystack, series.settings || []);
+ const matchedObjects = matchObjectsInText(proseHaystack, series.objects || []);
+
// composeComicPagePrompt only returns '' when panels.length === 0, which is
// already rejected above. The "(continuation of previous beat)" placeholder
// covers panels with no description, so the prompt is non-empty by here.
const prompt = composeComicPagePrompt({
series, world, page, pageNumber: pageIndex + 1, extraStyle: options.extraStyle,
- matchedCharacters,
+ matchedCharacters, matchedSettings, matchedObjects,
});
const jobId = enqueueImageJob({