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(universe-builder): fold canon UI into Universe Builder (#259)

[._.]/ Adam Eivy5ce97dbe6565
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
new file mode 100644
index 0000000000..25eac05acd
--- /dev/null
+++ b/.changelog/NEXT.md
@@ -0,0 +1,6 @@
+# Release v{NEXT}
+
+## Changed
+
+- **Universe canon now lives inside Universe Builder.** Characters, places, and objects are managed inline on the universe page — no separate canon page to navigate to. The old canon URL still works as a redirect, and the Series Pipeline link lands you on the same combined view. Pending edits to other universe fields are no longer lost when canon changes are saved.
+- **Locking a canon entry now also blocks new reference renders.** Locked characters/places/objects already prevented AI rewrites; they now prevent new reference and clean-plate image renders too, so a locked entry's identity stays frozen across both text and visuals. Disabled buttons explain the lock in their tooltips.
diff --git a/PLAN.md b/PLAN.md
index 48ef14bbbf..b644ba7829 100644
--- a/PLAN.md
+++ b/PLAN.md
@@ -6,7 +6,7 @@ For project goals, see [GOALS.md](./GOALS.md). For completed work, see [DONE.md]
## Next Up
-1. **Universe-as-Canon Phase 2 UI** — fold canon into UniverseBuilder, retire the standalone Canon page + route, retire `universe.categories` on the schema. (Backbone shipped; UI still on the two-page split.)
+1. **Universe-as-Canon Phase 2 UI — remaining schema retirement.** Canon is now folded into UniverseBuilder and the standalone Canon page is retired. Still to do: drop `universe.categories` from the schema (sanitizer, Zod, expand prompt template, `mergeCategoriesWithLocks`, `compilePrompts`'s `variations`/`all` branches) and enrich the expand LLM contract to ask for `characters[]`/`settings[]`/`objects[]` with rich metadata directly.
2. **Step-by-step approval/lock UX across Universe → Series → Arc → Seasons → Episodes.** Iteration 1 shipped a single arc-level lock; extend to per-season + per-field locks, lock the bulk runners, surface stage-progress strip, enforce locks server-side before LLM invocations.
3. **Sharing v2 contracts** — per-peer subscription filenames (`sub-<kind>-<recordId>-<senderInstanceId>.json`), tombstone-based item removals, "🔄 live" badge on inbox subscription rows.
4. **Pipeline continuity gaps** — plumb character physicalDescription/personality/background into idea-stage prompt; plumb setting `palette`/`era`/`weather`/`recurringDetails` into visual stages; add `worldEntitiesSummary` to text stages; add a dedicated `voice` / speech-pattern field to the bible schema.
@@ -35,9 +35,7 @@ For project goals, see [GOALS.md](./GOALS.md). For completed work, see [DONE.md]
### Universe-as-Canon — Phase 2 + extensions
-- [ ] **Extract shared `CanonCard`.** Pull `CanonCard` + `KindSection` out of `UniverseCanon.jsx` into `client/src/components/universe/CanonCard.jsx`. Add lock-toggle icon, "from series: <name>" provenance badge, tag chips. Disable Refine + Render when locked.
-- [ ] **Fold canon into `UniverseBuilder.jsx`.** Replace the categories grid with three kind-sections (Characters / Settings / Objects) using shared `CanonCard`. Move "Extract from prose" into header. Keep composite sheets unchanged.
-- [ ] **Retire the standalone Canon page + route.** Replace `UniverseCanon.jsx` with a Navigate redirect (or delete + drop the route). Update `navManifest.js` + sidebar + tests.
+- [ ] **CanonCard "from series: <name>" full provenance label.** Card currently shows a "from series" chip with the series id in the tooltip. Plumb a `seriesNameMap` (or `sourceSeriesName` per entry) so the chip can render the actual series name. Needs the parent (`UniverseCanonSection` / `NounsStage`) to pass a `{ [seriesId]: name }` lookup.
- [ ] **Retire `universe.categories` on the schema.** After UI no longer reads it, drop from `sanitizeTemplate`, route Zod schemas, expand prompt template, `mergeCategoriesWithLocks`, `compilePrompts`'s `'variations'`/`'all'` branches.
- [ ] **Universe expand LLM contract enrichment.** Ask the LLM directly for `characters[]` / `settings[]` / `objects[]` with rich narrative metadata alongside visual `prompt`.
- [ ] **Settings → Places kind rename.** `BIBLE_KIND.SETTING → BIBLE_KIND.PLACE`, `BIBLE_FIELD[SETTING]: 'settings' → 'places'`. Touches ~20 files. Stick the rename to bible context — app settings stays as "settings".
@@ -93,7 +91,6 @@ For project goals, see [GOALS.md](./GOALS.md). For completed work, see [DONE.md]
### Code quality / dedup (from `/simplify` passes)
-- [ ] **Route-level tests for proof/final `target` + `useProofAsBase`.** Three test cases on `comicPageRenderSchema` + `comicCoverRenderSchema`.
- [ ] **Extract `useSwipeNav` hook + `lib/clipboard.js`.** `MediaLightbox` swipe nav; clipboard inlined across 8+ call sites. Clipboard can move now.
- [ ] **Route `MediaLightbox` settings drawer through `components/Drawer.jsx`.** Reconcile `Drawer`'s flat Esc handler with the lightbox's layered Escape cascade.
- [ ] **Extract `<ModelSelect>` component for the active+Legacy optgroup pattern.** `VideoGen.jsx` + `CreativeDirector.jsx` render identical blocks differing only in `m.name` vs `m.name || m.id`.
diff --git a/client/src/App.jsx b/client/src/App.jsx
index bec7532551..4fa45ae9a1 100644
--- a/client/src/App.jsx
+++ b/client/src/App.jsx
@@ -52,7 +52,6 @@ const MediaCollectionDetail = lazyWithReload(() => import('./pages/MediaCollecti
const MediaModels = lazyWithReload(() => import('./pages/MediaModels'));
const Loras = lazyWithReload(() => import('./pages/Loras'));
const UniverseBuilder = lazyWithReload(() => import('./pages/UniverseBuilder'));
-const UniverseCanon = lazyWithReload(() => import('./pages/UniverseCanon'));
const VideoTimeline = lazyWithReload(() => import('./pages/VideoTimeline'));
const VideoTimelineEditor = lazyWithReload(() => import('./pages/VideoTimelineEditor'));
const CreativeDirector = lazyWithReload(() => import('./pages/CreativeDirector'));
@@ -102,6 +101,18 @@ function RedirectWithSearch({ to }) {
return <Navigate to={`${to}${search}`} replace />;
}
+// Canon page was folded into Universe Builder; redirect the old sub-route to
+// the builder so deep-links and bookmarks keep working. Strips the trailing
+// `/canon` (with optional trailing slash — React Router matches both forms,
+// otherwise `/universe-builder/abc/canon/` would self-loop), preserves the
+// query string (e.g. `?series=<id>` filter), and adds `#canon` so the
+// browser scrolls to the embedded canon section instead of the bible at the
+// top of the builder (UniverseCanonSection renders with `id="canon"`).
+function CanonRedirect() {
+ const { pathname, search } = useLocation();
+ return <Navigate to={`${pathname.replace(/\/canon\/?$/, '')}${search}#canon`} replace />;
+}
+
// Force full reload on HMR — partial hot-replacement of the route tree
// causes stale lazy imports and React Router errors on nested paths
if (import.meta.hot) {
@@ -212,7 +223,7 @@ export default function App() {
<Route path="loras" element={<Loras />} />
<Route path="universe-builder" element={<UniverseBuilder />} />
<Route path="universe-builder/:universeId" element={<UniverseBuilder />} />
- <Route path="universe-builder/:universeId/canon" element={<UniverseCanon />} />
+ <Route path="universe-builder/:universeId/canon" element={<CanonRedirect />} />
</Route>
<Route path="image-gen" element={<RedirectWithSearch to="/media/image" />} />
<Route path="video-gen" element={<RedirectWithSearch to="/media/video" />} />
@@ -223,7 +234,7 @@ export default function App() {
<Route path="rapid-reader" element={<RapidReaderPage />} />
<Route path="universe-builder" element={<UniverseBuilder />} />
<Route path="universe-builder/:universeId" element={<UniverseBuilder />} />
- <Route path="universe-builder/:universeId/canon" element={<UniverseCanon />} />
+ <Route path="universe-builder/:universeId/canon" element={<CanonRedirect />} />
<Route path="writers-room" element={<WritersRoom />} />
<Route path="sharing" element={<Sharing />} />
<Route path="importer" element={<Importer />} />
diff --git a/client/src/components/pipeline/CanonCard.jsx b/client/src/components/pipeline/CanonCard.jsx
index 40c3736fbe..fe3636a92d 100644
--- a/client/src/components/pipeline/CanonCard.jsx
+++ b/client/src/components/pipeline/CanonCard.jsx
@@ -3,8 +3,8 @@
* with description, render-reference button, optional AI-differentiate button
* (characters only), and click-to-preview image thumbnails.
*
- * Used by NounsStage (per-series, pre-Phase B) and UniverseCanon (per-
- * universe, Phase A and beyond).
+ * Used by NounsStage (per-series, pre-Phase B) and UniverseCanonSection
+ * (per-universe, embedded in UniverseBuilder).
*/
import { useEffect, useRef, useState } from 'react';
@@ -228,10 +228,16 @@ export default function CanonCard({
const refs = Array.isArray(entry.imageRefs) ? entry.imageRefs : [];
const locked = entry.locked === true;
const tags = Array.isArray(entry.tags) ? entry.tags.filter(Boolean) : [];
- // Refine + Render guarded against locked entries — the server returns 409
- // on refine; UI surfaces that as a disabled button with an explanatory tip
- // so the user doesn't fire a doomed request.
- const refineBlockedByLock = locked && !!onToggleLock;
+ // Refine + Render guarded against locked entries — locks signal "frozen
+ // identity"; both AI rewrite (refine/differentiate) and new visual refs are
+ // gated so the user explicitly unlocks before reshaping the entry.
+ // Gate on `locked` alone, NOT on `!!onToggleLock` — consumers like
+ // NounsStage embed CanonCard without passing a toggle, but the underlying
+ // entry's `locked` flag still represents frozen-identity semantics on the
+ // server (Refine → 409 `UNIVERSE_CANON_LOCKED`, Render persists a new
+ // visual ref through bypass). The unlock UX lives in Universe Builder; the
+ // pipeline view just needs to respect it.
+ const blockedByLock = locked;
// settledRef prevents duplicate completion callbacks under React 18
// StrictMode's mount→cleanup→mount double-fire in dev. MediaJobThumb
@@ -336,9 +342,9 @@ export default function CanonCard({
<button
type="button"
onClick={() => onRefine(entry.id)}
- disabled={refining || refineDisabled || refineBlockedByLock}
+ disabled={refining || refineDisabled || blockedByLock}
className="inline-flex items-center justify-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={refineBlockedByLock
+ title={blockedByLock
? `Unlock ${entry.name} to refine`
: `Rewrite ${entry.name}'s description so they render distinct from every other character`}
>
@@ -349,9 +355,11 @@ export default function CanonCard({
<button
type="button"
onClick={onRender}
- disabled={!description.trim() || !!inFlightJobId}
+ disabled={!description.trim() || !!inFlightJobId || blockedByLock}
className="inline-flex items-center justify-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'}
+ title={blockedByLock
+ ? `Unlock ${entry.name} to render a new reference`
+ : (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
@@ -360,11 +368,13 @@ export default function CanonCard({
<button
type="button"
onClick={() => onRenderCleanPlate(entry)}
- disabled={!description.trim() || !!inFlightJobId}
+ disabled={!description.trim() || !!inFlightJobId || blockedByLock}
className="inline-flex items-center justify-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 an empty-location plate for ${entry.name} — no people, edge-to-edge`
- : 'Add a description first'}
+ title={blockedByLock
+ ? `Unlock ${entry.name} to render a clean plate`
+ : (description.trim()
+ ? `Render an empty-location plate for ${entry.name} — no people, edge-to-edge`
+ : 'Add a description first')}
>
{inFlightJobId ? <Loader2 size={10} className="animate-spin" /> : <Square size={10} />}
Clean plate
diff --git a/client/src/components/pipeline/stages/NounsStage.jsx b/client/src/components/pipeline/stages/NounsStage.jsx
index f83491d03e..123b14dcf8 100644
--- a/client/src/components/pipeline/stages/NounsStage.jsx
+++ b/client/src/components/pipeline/stages/NounsStage.jsx
@@ -30,7 +30,7 @@ import {
} from '../../../lib/scenePrompt';
import { composeStyledPrompt } from '../../../lib/composeStyledPrompt';
import { composeCleanPlatePrompt } from '../../../lib/cleanPlatePrompt';
-import { joinInfluenceList } from '../../../lib/joinInfluenceList';
+import { universeStylePreset } from '../../../lib/universeStylePreset';
import useMounted from '../../../hooks/useMounted';
import CanonCard from '../CanonCard';
import MediaPreview from '../../media/MediaPreview';
@@ -68,22 +68,6 @@ const KINDS = [
},
];
-// Mirrors server-side `applyWorldStyle` (visualStages.js): the series'
-// optional `stylePromptOverride` prepends ahead of the universe's embrace
-// chip list, joined with the same `'. '` separator the server uses. Without
-// this parity, client preview renders drift from comic-page renders.
-// `universe` is allowed to be null — server-side buildStyleClause still
-// applies the override when only the series has style content (orphan or
-// failed-load), so the client preset must do the same.
-const universeStylePreset = (universe, series) => {
- const override = (series?.stylePromptOverride || '').trim();
- const embrace = universe ? joinInfluenceList(universe.influences?.embrace) : '';
- const avoid = universe ? joinInfluenceList(universe.influences?.avoid) : '';
- const prompt = [override, embrace].filter(Boolean).join('. ');
- if (!prompt && !avoid) return null;
- return { prompt, negativePrompt: avoid };
-};
-
export default function NounsStage({ issue, series }) {
const mountedRef = useMounted();
const prose = (issue.stages?.prose?.output || '').trim();
@@ -262,8 +246,14 @@ export default function NounsStage({ issue, series }) {
};
const handleRenderCleanPlate = async (entry) => {
- if (!entry?.description?.trim()) {
- toast.error(`Add a description before generating a clean plate for ${entry.name}`);
+ // Match CanonCard's button-enable predicate (descFor includes palette +
+ // recurringDetails for settings) — composeCleanPlatePrompt builds a valid
+ // prompt from any of {description, palette, recurringDetails}, so gating
+ // on `description` alone produces a button that fails with this toast
+ // even though the composer would have succeeded.
+ const hasContent = !!(entry?.description?.trim() || entry?.palette?.trim() || entry?.recurringDetails?.trim());
+ if (!hasContent) {
+ toast.error(`Add a description, palette, or recurring details before generating a clean plate for ${entry.name}`);
return;
}
const baseOpts = pipelineImageCfgToRenderOpts(imageCfg);
diff --git a/client/src/pages/UniverseCanon.jsx b/client/src/components/universe/UniverseCanonSection.jsx
similarity index 71%
rename from client/src/pages/UniverseCanon.jsx
rename to client/src/components/universe/UniverseCanonSection.jsx
index a2f0271bd8..b8b9d37a76 100644
--- a/client/src/pages/UniverseCanon.jsx
+++ b/client/src/components/universe/UniverseCanonSection.jsx
@@ -1,48 +1,39 @@
/**
- * Universe Canon — manage characters, places, and objects on a universe.
+ * Embeddable canon UI for a universe — Characters / Places / Objects with
+ * extract-from-prose, AI differentiate, per-entry lock + refine + render.
*
- * Phase A of the Universe-as-canon refactor: entity registries live on the
- * universe so multiple series can share them. Mirrors the Nouns page's
- * structure but reads/writes universe.characters[] / .settings[] / .objects[].
- * The Nouns page (per-series) keeps working until Phase B migrates series →
- * universe references.
+ * Lives inside UniverseBuilder (Phase 2 of Universe-as-Canon) so canon and
+ * the template live on one page. Reads the universe from the parent (which
+ * owns the editable draft) and writes back via `onUniverseChange(updated)` so
+ * canon mutations don't clobber pending edits to logline/premise/etc.
+ *
+ * The series filter is URL-driven (`?series=<id>`) so deep-links restore the
+ * filtered view. The dropdown only appears when ≥2 series reference this
+ * universe's canon.
*/
-
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
-import { Link, useParams, useSearchParams } from 'react-router-dom';
+import { useSearchParams } from 'react-router-dom';
import {
- Library, Loader2, Users, MapPin, Package, Globe2, Wand2, ArrowLeft, Filter,
+ Library, Loader2, Users, MapPin, Package, Wand2, Filter,
} from 'lucide-react';
-import toast from '../components/ui/Toast';
+import toast from '../ui/Toast';
import {
- getUniverse,
extractUniverseCanon,
refineUniverseCharacter,
differentiateUniverseCast,
updateUniverse,
getUniverseCanonUsage,
setUniverseCanonLock,
-} from '../services/apiUniverseBuilder';
-import { generateImage, getSettings } from '../services/apiSystem';
-import { composeStyledPrompt } from '../lib/composeStyledPrompt';
-import { composeCleanPlatePrompt } from '../lib/cleanPlatePrompt';
-import { useAsyncAction } from '../hooks/useAsyncAction';
-import useMounted from '../hooks/useMounted';
-import CanonCard from '../components/pipeline/CanonCard';
-import MediaPreview from '../components/media/MediaPreview';
-import {
- PIPELINE_IMAGE_DEFAULTS,
- readPipelineImageSettings,
- pipelineImageCfgToRenderOpts,
-} from '../lib/pipelineImageDefaults';
-import { joinInfluenceList } from '../lib/joinInfluenceList';
-
-const universeStylePreset = (universe) => {
- const embrace = joinInfluenceList(universe?.influences?.embrace);
- const avoid = joinInfluenceList(universe?.influences?.avoid);
- if (!embrace && !avoid) return null;
- return { prompt: embrace, negativePrompt: avoid };
-};
+} from '../../services/apiUniverseBuilder';
+import { generateImage } from '../../services/apiSystem';
+import { composeStyledPrompt } from '../../lib/composeStyledPrompt';
+import { composeCleanPlatePrompt } from '../../lib/cleanPlatePrompt';
+import { useAsyncAction } from '../../hooks/useAsyncAction';
+import useMounted from '../../hooks/useMounted';
+import CanonCard from '../pipeline/CanonCard';
+import MediaPreview from '../media/MediaPreview';
+import { pipelineImageCfgToRenderOpts } from '../../lib/pipelineImageDefaults';
+import { universeStylePreset } from '../../lib/universeStylePreset';
const KINDS = [
{
@@ -63,14 +54,10 @@ const KINDS = [
},
];
-export default function UniverseCanon() {
- const { universeId } = useParams();
+export default function UniverseCanonSection({ universe, universeId, onUniverseChange, imageCfg }) {
+ const mountedRef = useMounted();
const [searchParams, setSearchParams] = useSearchParams();
const seriesFilter = searchParams.get('series') || '';
- const mountedRef = useMounted();
- const [universe, setUniverse] = useState(null);
- const [loadErr, setLoadErr] = useState(null);
- const [imageCfg, setImageCfg] = useState(PIPELINE_IMAGE_DEFAULTS);
const [renderingJobs, setRenderingJobs] = useState({});
const [refiningId, setRefiningId] = useState(null);
const [differentiating, setDifferentiating] = useState(false);
@@ -83,34 +70,18 @@ export default function UniverseCanon() {
const [extractOpen, setExtractOpen] = useState(false);
const [preview, setPreview] = useState(null);
// Per-canon-entry usage map: `{ characters: { [entryId]: [{seriesId, seriesName, issueCount, ...}] }, ... }`.
- // Loaded lazily after the universe itself — usage is a derived view and
- // shouldn't block the initial render. Refetched after mutations that change
- // the canon shape (extract / differentiate-cast) so new entries get usage.
+ // Loaded lazily — usage is a derived view and shouldn't block the initial
+ // paint. Refetched after mutations that change the canon shape (extract /
+ // differentiate-cast) so new entries get usage.
const [usage, setUsage] = useState(null);
- useEffect(() => {
- let cancelled = false;
- Promise.all([
- getUniverse(universeId).catch((e) => { setLoadErr(e.message || 'Load failed'); return null; }),
- getSettings().catch(() => ({})),
- ]).then(([u, s]) => {
- if (cancelled || !mountedRef.current) return;
- setUniverse(u);
- setImageCfg(readPipelineImageSettings(s));
- });
- return () => { cancelled = true; };
- }, [universeId, mountedRef]);
-
- // Lazy usage fetch. Decoupled from the universe load so a slow cross-
- // reference scan doesn't gate the page paint, and so it can be refetched
- // independently after canon mutations. The captured `requestedFor` is
- // checked against the live `currentUniverseIdRef` so a slow response from
- // a previous universe (rapid navigation) can't repopulate `usage` with
- // stale data — `setUsage(null)` on universeId change would otherwise be
- // immediately undone.
+ // Lazy usage fetch. Captured `requestedFor` is checked against the live
+ // `currentUniverseIdRef` so a slow response from a previous universe can't
+ // repopulate `usage` with stale data after fast navigation.
const currentUniverseIdRef = useRef(universeId);
useEffect(() => { currentUniverseIdRef.current = universeId; }, [universeId]);
const refreshUsage = useCallback(() => {
+ if (!universeId) return;
const requestedFor = universeId;
getUniverseCanonUsage(requestedFor)
.then((u) => {
@@ -124,8 +95,7 @@ export default function UniverseCanon() {
// Series-with-usage options for the filter dropdown. Derived from the
// usage map rather than a fresh API call so the dropdown only lists
- // series that actually reference this universe's canon — a series linked
- // to the universe with zero issues has nothing to filter to.
+ // series that actually reference this universe's canon.
const seriesOptions = useMemo(() => {
if (!usage) return [];
const seen = new Map();
@@ -144,15 +114,8 @@ export default function UniverseCanon() {
.sort((a, b) => a.name.localeCompare(b.name));
}, [usage]);
- // If the URL names a series that isn't in this universe's usage map
- // (stale bookmark, deleted series), drop the param silently so the page
- // doesn't show an empty "filtered" view forever. One-shot per universe —
- // runs when usage first resolves; later URL changes are driven by the
- // dropdown (handleSeriesFilterChange) which only sets known-good ids.
- // Reset on universeId change so navigating between universes within the
- // same mount validates each universe's filter param independently. Also
- // clear `usage` so the validation effect doesn't run against the prior
- // universe's data during the transition.
+ // Drop a stale `?series=` param when usage resolves and the series isn't
+ // in this universe. Reset per-universe so cross-universe nav re-validates.
const validatedRef = useRef(false);
useEffect(() => {
validatedRef.current = false;
@@ -175,8 +138,6 @@ export default function UniverseCanon() {
setSearchParams(next, { replace: true });
}, [searchParams, setSearchParams]);
- // Build a per-kind filtered entry list. When no filter is active the
- // raw universe arrays pass through unchanged.
const filteredByKind = useMemo(() => {
if (!universe) return {};
const out = {};
@@ -225,14 +186,21 @@ export default function UniverseCanon() {
{ errorMessage: 'Extraction failed' },
);
+ // Drop late responses that arrive after the user has switched universes —
+ // otherwise universe A's refine/extract result would land in universe B's
+ // draft. The component stays mounted across selectedId changes (only the
+ // `universe` prop swaps), so mountedRef alone isn't sufficient.
+ const isStillCurrent = (capturedId) => mountedRef.current && currentUniverseIdRef.current === capturedId;
+
const handleExtract = async () => {
if (!extractText.trim()) {
toast.error('Paste prose into the textarea first');
return;
}
+ const capturedId = universeId;
const result = await runExtract();
- if (!result || !mountedRef.current) return;
- setUniverse(result.universe);
+ if (!result || !isStillCurrent(capturedId)) return;
+ onUniverseChange(result.universe);
refreshUsage();
const counts = KINDS
.map((k) => `${result.universe[k.key]?.length ?? 0} ${k.label.toLowerCase()}`)
@@ -245,13 +213,14 @@ export default function UniverseCanon() {
const handleDifferentiate = async () => {
if (!universe || differentiating) return;
setDifferentiating(true);
+ const capturedId = universeId;
const providerId = universe.llm?.provider || undefined;
const model = universe.llm?.model || undefined;
const result = await differentiateUniverseCast(universeId, { providerId, model })
.catch((err) => { toast.error(err.message || 'Differentiate failed'); return null; });
if (mountedRef.current) setDifferentiating(false);
- if (!result || !mountedRef.current) return;
- setUniverse(result.universe);
+ if (!result || !isStillCurrent(capturedId)) return;
+ onUniverseChange(result.universe);
toast.success(`Differentiated ${result.touched}/${result.touched + result.skipped} characters — ${(result.rationale || '').slice(0, 140)}`);
};
@@ -259,25 +228,27 @@ export default function UniverseCanon() {
if (togglingLockRef.current) return;
togglingLockRef.current = entryId;
setTogglingLockId(entryId);
+ const capturedId = universeId;
const result = await setUniverseCanonLock(universeId, kind.apiKind, entryId, nextLocked)
.catch((err) => { toast.error(err.message || 'Lock toggle failed'); return null; });
togglingLockRef.current = null;
if (mountedRef.current) setTogglingLockId(null);
- if (!result || !mountedRef.current) return;
- setUniverse(result.universe);
+ if (!result || !mountedRef.current || currentUniverseIdRef.current !== capturedId) return;
+ onUniverseChange(result.universe);
toast.success(`${result.entry?.name || 'Entry'} ${nextLocked ? 'locked' : 'unlocked'}`);
- }, [universeId, mountedRef]);
+ }, [universeId, onUniverseChange, mountedRef]);
const handleRefineCharacter = async (entryId) => {
if (!universe || refiningId) return;
setRefiningId(entryId);
+ const capturedId = universeId;
const providerId = universe.llm?.provider || undefined;
const model = universe.llm?.model || undefined;
const result = await refineUniverseCharacter(universeId, entryId, { providerId, model })
.catch((err) => { toast.error(err.message || 'Refine failed'); return null; });
if (mountedRef.current) setRefiningId(null);
- if (!result || !mountedRef.current) return;
- setUniverse(result.universe);
+ if (!result || !isStillCurrent(capturedId)) return;
+ onUniverseChange(result.universe);
toast.success(`Refined — ${(result.rationale || result.changes?.[0] || 'description rewritten').slice(0, 140)}`);
};
@@ -304,15 +275,20 @@ export default function UniverseCanon() {
};
const handleRenderCleanPlate = async (entry) => {
- if (!entry?.description?.trim()) {
- toast.error(`Add a description before generating a clean plate for ${entry.name}`);
+ // Match CanonCard's button-enable predicate (descFor includes palette +
+ // recurringDetails for settings) — composeCleanPlatePrompt builds a valid
+ // prompt from any of {description, palette, recurringDetails}, so gating
+ // on `description` alone produces a button that fails with this toast
+ // even though the composer would have succeeded.
+ const hasContent = !!(entry?.description?.trim() || entry?.palette?.trim() || entry?.recurringDetails?.trim());
+ if (!hasContent) {
+ toast.error(`Add a description, palette, or recurring details before generating a clean plate for ${entry.name}`);
return;
}
const baseOpts = pipelineImageCfgToRenderOpts(imageCfg);
const plate = composeCleanPlatePrompt(entry, baseOpts.negativePrompt || '');
- // Layer the universe style on top of the clean-plate composition so
- // the empty-location render shares the visual language of the
- // populated reference renders.
+ // Layer the universe style on top of the clean-plate composition so the
+ // empty-location render shares the visual language of the populated refs.
const styled = composeStyledPrompt(
plate.prompt,
plate.negativePrompt,
@@ -336,13 +312,14 @@ export default function UniverseCanon() {
delete next[entryId];
return next;
});
+ const capturedId = universeId;
const list = (universe[kindKey] || []).map((e) =>
e.id === entryId ? { ...e, imageRefs: [...(e.imageRefs || []), filename] } : e
);
const updated = await updateUniverse(universeId, { [kindKey]: list })
.catch((err) => { toast.error(`Save failed: ${err.message}`); return null; });
- if (updated && mountedRef.current) setUniverse(updated);
- }, [universe, universeId, mountedRef]);
+ if (updated && mountedRef.current && currentUniverseIdRef.current === capturedId) onUniverseChange(updated);
+ }, [universe, universeId, onUniverseChange, mountedRef]);
const handleRefFailed = useCallback((entryId, errMsg) => {
setRenderingJobs((prev) => {
@@ -355,48 +332,43 @@ export default function UniverseCanon() {
}, []);
// Inline-edit channel for canon fields the user types/picks directly
- // (today: setting intExt + timeOfDay chips). Optimistic — UI updates
- // before the server roundtrip so chip clicks feel instant.
+ // (setting intExt + timeOfDay chips, primaryImageRef pinning, wardrobe
+ // edits). Optimistic — UI updates before the server roundtrip so chip
+ // clicks feel instant.
const handlePatchEntry = useCallback(async (kind, entryId, patch) => {
if (!universe || !patch || typeof patch !== 'object') return;
+ const capturedId = universeId;
const kindKey = kind.key;
const list = (universe[kindKey] || []).map((e) =>
e.id === entryId ? { ...e, ...patch } : e
);
- setUniverse((prev) => prev ? { ...prev, [kindKey]: list } : prev);
+ onUniverseChange({ ...universe, [kindKey]: list });
const updated = await updateUniverse(universeId, { [kindKey]: list })
.catch((err) => { toast.error(`Save failed: ${err.message}`); return null; });
- if (updated && mountedRef.current) setUniverse(updated);
- }, [universe, universeId, mountedRef]);
+ if (updated && mountedRef.current && currentUniverseIdRef.current === capturedId) onUniverseChange(updated);
+ }, [universe, universeId, onUniverseChange, mountedRef]);
- if (loadErr) return <div className="p-4 text-port-error">{loadErr}</div>;
- if (!universe) return <div className="p-4 text-gray-500 italic">Loading universe…</div>;
+ if (!universe) return null;
const charCount = (universe.characters || []).length;
return (
- <div className="p-4 sm:p-6 max-w-5xl mx-auto space-y-5">
- <header className="flex items-start justify-between gap-3 flex-wrap">
+ // `id="canon"` is the scroll target for `/universe-builder/:id#canon`
+ // deep-links (legacy `/canon` route redirect + PipelineSeries "Manage
+ // characters, places, and objects" link). Keep this id stable.
+ <section id="canon" className="bg-port-card border border-port-border rounded p-4 flex flex-col gap-3 scroll-mt-4">
+ <div className="flex items-center justify-between gap-3 flex-wrap">
<div>
- <Link
- to={`/universe-builder/${encodeURIComponent(universeId)}`}
- className="inline-flex items-center gap-1 text-xs text-port-accent hover:underline"
- >
- <ArrowLeft size={12} /> Back to Universe Builder
- </Link>
- <h1 className="text-xl font-semibold text-white mt-1 flex items-center gap-2">
- <Globe2 size={18} className="text-port-accent" />
- Canon: {universe.name}
- </h1>
- <p className="text-xs text-gray-500 mt-1 max-w-2xl">
- People, places, and things that exist in this universe. Series within this universe
- share the same canon — once Phase B lands, episodes/issues will reference these
- entries directly so a character renders consistently across crossovers and cameos.
+ <h2 className="text-sm font-semibold text-white">Canon</h2>
+ <p className="text-xs text-gray-500 mt-0.5">
+ People, places, and things that exist in this universe. Series in this
+ universe share the same canon — episodes/issues reference these entries
+ so a character renders consistently across crossovers.
</p>
</div>
<div className="flex items-center gap-2 flex-wrap">
{seriesOptions.length > 1 ? (
- <label className="inline-flex items-center gap-1.5 px-2 py-1.5 rounded-lg bg-port-card border border-port-border text-gray-300 text-sm">
+ <label className="inline-flex items-center gap-1.5 px-2 py-1.5 rounded bg-port-bg border border-port-border text-gray-300 text-xs">
<Filter size={12} className="text-gray-500" />
<span className="sr-only">Filter by series</span>
<select
@@ -415,32 +387,33 @@ export default function UniverseCanon() {
<button
type="button"
onClick={() => setExtractOpen((v) => !v)}
- className="inline-flex items-center gap-1.5 px-3 py-1.5 rounded-lg bg-port-card border border-port-border text-gray-300 text-sm hover:border-port-accent/50 hover:text-white"
+ className="inline-flex items-center gap-1.5 px-2.5 py-1.5 rounded bg-port-bg border border-port-border text-gray-300 text-xs hover:border-port-accent/50 hover:text-white"
>
- <Library size={14} /> Extract from prose
+ <Library size={12} /> Extract from prose
</button>
<button
type="button"
onClick={handleDifferentiate}
disabled={differentiating || charCount < 2}
title={charCount < 2 ? 'Need at least 2 characters to differentiate' : 'Rewrite every character so the cast renders visually distinct'}
- className="inline-flex items-center gap-1.5 px-3 py-1.5 rounded-lg bg-port-accent text-white text-sm font-medium disabled:opacity-40"
+ className="inline-flex items-center gap-1.5 px-2.5 py-1.5 rounded bg-port-accent/15 hover:bg-port-accent/25 text-port-accent border border-port-accent/40 text-xs disabled:opacity-40"
>
- {differentiating ? <Loader2 size={14} className="animate-spin" /> : <Wand2 size={14} />}
+ {differentiating ? <Loader2 size={12} className="animate-spin" /> : <Wand2 size={12} />}
AI: differentiate cast
</button>
</div>
- </header>
+ </div>
{extractOpen ? (
- <section className="rounded border border-port-border bg-port-card/40 p-3">
- <label className="text-xs uppercase tracking-wider text-gray-500">Paste prose</label>
+ <div className="rounded border border-port-border bg-port-bg p-3">
+ <label htmlFor="canon-extract-textarea" className="text-xs uppercase tracking-wider text-gray-500">Paste prose</label>
<textarea
+ id="canon-extract-textarea"
value={extractText}
onChange={(e) => setExtractText(e.target.value)}
- rows={8}
+ rows={6}
placeholder="Paste an issue's prose stage output, a story draft, or any prose body. The LLM extracts characters, places, and objects and merges them into this universe's canon."
- className="w-full mt-1 px-2 py-1.5 bg-port-bg border border-port-border rounded text-white text-xs font-mono"
+ className="w-full mt-1 px-2 py-1.5 bg-port-card border border-port-border rounded text-white text-xs font-mono"
/>
<div className="flex items-center justify-end gap-2 mt-2">
<button
@@ -460,7 +433,7 @@ export default function UniverseCanon() {
Extract
</button>
</div>
- </section>
+ </div>
) : null}
{seriesFilter ? (
@@ -497,14 +470,14 @@ export default function UniverseCanon() {
))}
<MediaPreview preview={preview} setPreview={setPreview} items={previewItems} />
- </div>
+ </section>
);
}
function KindSection({ kind, all, totalCount, filtered, usage, renderingJobs, onRender, onJobCompleted, onJobFailed, onPreview, onRefine, refiningId, onToggleLock, togglingLockId, onPatchEntry, onRenderCleanPlate }) {
const Icon = kind.icon;
return (
- <section className="rounded-lg border border-port-border bg-port-card/40">
+ <section className="rounded border border-port-border bg-port-bg/60">
<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>
@@ -545,4 +518,3 @@ function KindSection({ kind, all, totalCount, filtered, usage, renderingJobs, on
</section>
);
}
-
diff --git a/client/src/lib/universeStylePreset.js b/client/src/lib/universeStylePreset.js
new file mode 100644
index 0000000000..4e2e98a73d
--- /dev/null
+++ b/client/src/lib/universeStylePreset.js
@@ -0,0 +1,19 @@
+import { joinInfluenceList } from './joinInfluenceList';
+
+// Build the client-side style preset that `composeStyledPrompt` layers on top
+// of per-entity image-gen prompts. Mirrors `applyWorldStyle` /
+// `buildStyleClause` on the server so canon ref renders share the same visual
+// language as comic-page renders.
+//
+// `universe` may be null — the server-side path still applies the series
+// override when only the series has style content (orphan or failed load), so
+// the client must do the same. `series` is optional; when omitted the result
+// is the universe-only preset (Universe Builder canon section).
+export const universeStylePreset = (universe, series = null) => {
+ const override = (series?.stylePromptOverride || '').trim();
+ const embrace = universe ? joinInfluenceList(universe.influences?.embrace) : '';
+ const avoid = universe ? joinInfluenceList(universe.influences?.avoid) : '';
+ const prompt = [override, embrace].filter(Boolean).join('. ');
+ if (!prompt && !avoid) return null;
+ return { prompt, negativePrompt: avoid };
+};
diff --git a/client/src/pages/PipelineSeries.jsx b/client/src/pages/PipelineSeries.jsx
index 7fd00a7e45..fe0b220fcf 100644
--- a/client/src/pages/PipelineSeries.jsx
+++ b/client/src/pages/PipelineSeries.jsx
@@ -337,8 +337,11 @@ function BibleSidebar({ series, universes, patchSeries, onCollapse }) {
<div>
<h3 className="text-xs uppercase tracking-wider text-gray-500 mb-2">Canon</h3>
{series.universeId ? (
+ // `#canon` scrolls to the embedded canon section (id="canon" on
+ // UniverseCanonSection) so users land on the folded-in canon UI
+ // instead of the bible at the top of the builder.
<Link
- to={`/universe-builder/${encodeURIComponent(series.universeId)}/canon`}
+ to={`/universe-builder/${encodeURIComponent(series.universeId)}#canon`}
className="block text-xs text-port-accent hover:underline"
>
Manage characters, places, and objects on the linked Universe →
diff --git a/client/src/pages/UniverseBuilder.jsx b/client/src/pages/UniverseBuilder.jsx
index 9b5c422ccb..584d6ebd99 100644
--- a/client/src/pages/UniverseBuilder.jsx
+++ b/client/src/pages/UniverseBuilder.jsx
@@ -11,7 +11,7 @@ import { useEffect, useMemo, useRef, useState } from 'react';
import { Link, useLocation, useNavigate, useParams } from 'react-router-dom';
import {
Globe2, Plus, Trash2, Sparkles, Wand2, Loader2, Save, FolderOpen,
- Edit3, X, MessageSquarePlus, Play, Lock, Unlock, Library,
+ Edit3, X, MessageSquarePlus, Play, Lock, Unlock,
PanelLeftClose, PanelLeftOpen,
} from 'lucide-react';
import toast from '../components/ui/Toast';
@@ -31,7 +31,9 @@ import BackendChipStrip from '../components/media/BackendChipStrip';
import ImageGenControls from '../components/imageGen/ImageGenControls';
import ShareToButton from '../components/sharing/ShareToButton';
import OriginBadge from '../components/sharing/OriginBadge';
+import UniverseCanonSection from '../components/universe/UniverseCanonSection';
import { deriveAvailableBackends, IMAGE_GEN_MODE } from '../lib/imageGenBackends';
+import { PIPELINE_IMAGE_DEFAULTS, readPipelineImageSettings } from '../lib/pipelineImageDefaults';
const CATEGORY_LABELS = {
landscapes: 'Landscapes',
@@ -224,6 +226,10 @@ export default function UniverseBuilder() {
const [imageModels, setImageModels] = useState([]);
const [availableBackends, setAvailableBackends] = useState([]);
const [defaultMode, setDefaultMode] = useState(null);
+ // Per-render config used by the embedded Canon section for reference
+ // renders (size, steps, etc.). Derived from the same settings fetch as the
+ // batch-render plumbing above so we don't round-trip getSettings() twice.
+ const [imageCfg, setImageCfg] = useState(PIPELINE_IMAGE_DEFAULTS);
// The draft is the editable copy of the currently-selected world. New
// universes start as a draft with no id; saving creates the persisted record.
@@ -296,6 +302,7 @@ export default function UniverseBuilder() {
const saved = settings?.imageGen?.mode;
const fallback = backends.find((b) => b.id === saved)?.id || backends[0]?.id || IMAGE_GEN_MODE.LOCAL;
setDefaultMode(fallback);
+ setImageCfg(readPipelineImageSettings(settings));
setLoading(false);
};
@@ -337,6 +344,24 @@ export default function UniverseBuilder() {
return () => { cancelled = true; };
}, [selectedId]);
+ // Hash-scroll for deep-links — the legacy `/canon` redirect and
+ // PipelineSeries' "Manage characters, places, and objects" link both
+ // navigate to `/universe-builder/<id>#canon`. React Router doesn't
+ // auto-scroll to hashes, so wait until the section is rendered (gated by
+ // `draft.id === selectedId`) then scroll. The element id (`canon`) is set
+ // on UniverseCanonSection's root <section>.
+ useEffect(() => {
+ if (!location.hash) return;
+ if (!selectedId || draft.id !== selectedId) return;
+ const id = location.hash.slice(1);
+ // Defer one frame so the lazy section is in the DOM before we query for it.
+ const t = setTimeout(() => {
+ const el = document.getElementById(id);
+ if (el) el.scrollIntoView({ behavior: 'smooth', block: 'start' });
+ }, 50);
+ return () => clearTimeout(t);
+ }, [location.hash, selectedId, draft.id]);
+
const handleNew = () => {
goToWorld(null);
setDraft(emptyTemplate());
@@ -685,6 +710,22 @@ export default function UniverseBuilder() {
const canRender = !!selectedId && availableBackends.length > 0 && !rendering;
const updateDraft = (patch) => setDraft((d) => ({ ...d, ...patch }));
+
+ // Canon mutations (extract / refine / differentiate / lock / render-ref)
+ // round-trip through the server and return the full universe. Only the
+ // canon arrays + their updatedAt timestamp flow back into the draft so
+ // unsaved edits to logline/premise/styleNotes aren't clobbered by the
+ // server's stale copy of those fields.
+ const handleCanonChange = (updated) => {
+ if (!updated) return;
+ setDraft((d) => ({
+ ...d,
+ characters: updated.characters,
+ settings: updated.settings,
+ objects: updated.objects,
+ updatedAt: updated.updatedAt,
+ }));
+ };
// Toggle a single field's lock state and (when the world is already saved)
// persist immediately — locks are part of the world template, so a stale
// disk copy would let a later refine/expand silently overwrite a "locked"
@@ -892,13 +933,6 @@ export default function UniverseBuilder() {
</button>
{selectedId && (
<>
- <Link
- to={`/universe-builder/${encodeURIComponent(selectedId)}/canon`}
- className="px-3 py-2 rounded flex items-center gap-2 min-h-[40px] bg-port-card border border-port-border text-gray-300 hover:border-port-accent/50 hover:text-white text-sm"
- title="Manage canon: characters, places, and objects that exist in this universe"
- >
- <Library size={16} /> Canon
- </Link>
<ShareToButton kind="universe" ids={[selectedId]} label="Share" />
{draft.origin ? <OriginBadge origin={draft.origin} /> : null}
<button
@@ -1103,6 +1137,24 @@ export default function UniverseBuilder() {
/>
</section>
+ {/*
+ Gate on `draft.id === selectedId` — when the user switches universes,
+ `selectedId` updates synchronously but the new `draft` arrives after
+ an async `getUniverse(selectedId)` resolves. During that window, an
+ optimistic canon mutation routed through `onUniverseChange` would
+ send the *previous* universe's canon arrays to
+ `updateUniverse(selectedId, ...)`, wholesale-overwriting the newly
+ selected universe's canon on the server.
+ */}
+ {selectedId && draft.id === selectedId ? (
+ <UniverseCanonSection
+ universe={draft}
+ universeId={selectedId}
+ onUniverseChange={handleCanonChange}
+ imageCfg={imageCfg}
+ />
+ ) : null}
+
<CompositeSheetsEditor
sheets={draft.compositeSheets || []}
onChange={updateCompositeSheets}
diff --git a/server/routes/pipeline.test.js b/server/routes/pipeline.test.js
index 5a17b809a9..bdd33eb96b 100644
--- a/server/routes/pipeline.test.js
+++ b/server/routes/pipeline.test.js
@@ -70,14 +70,20 @@ vi.mock('../services/pipeline/visualStages.js', () => ({
// Match the real service contract: pageNumber is 1-based (pageIndex + 1).
prompt: `comic-page prompt for page ${opts.pageIndex + 1}`,
pageIndex: opts.pageIndex,
+ // Forward proof/final variant + i2i flag so the route's slotKey + slot
+ // record reflect the schema-validated body (target defaults to 'proof').
+ variant: opts?.target === 'final' ? 'final' : 'proof',
+ fromProof: opts?.target === 'final' && opts?.useProofAsBase === true,
})),
// Front cover render. Returns shape the route merges with the persisted cover:
- // { jobId, mode, prompt, coverScript }.
+ // { jobId, mode, prompt, coverScript, variant, fromProof }.
enqueueComicCover: vi.fn(async (_issueId, body) => ({
jobId: `cover-job-${++uuidCounter}`,
mode: 'local',
prompt: 'cover art prompt',
coverScript: body?.coverScript ?? 'default cover concept',
+ variant: body?.target === 'final' ? 'final' : 'proof',
+ fromProof: body?.target === 'final' && body?.useProofAsBase === true,
})),
// Single-scene video render. Returns the shape the route forwards verbatim
// to clients: { jobId, prompt, sceneIndex, issue, stage }.
@@ -869,6 +875,85 @@ describe('pipeline routes', () => {
expect(r.status).toBe(400);
});
+ // ---- proof/final target + useProofAsBase semantics ----
+ // The render schemas (comicCoverRenderSchema + comicPageRenderSchema) carry a
+ // `target` enum ('proof'|'final', default 'proof') and `useProofAsBase`
+ // boolean. The route uses `slotKeyForVariant(result.variant)` to land the
+ // in-flight job on the matching slot (proofImage vs finalImage) and stamps
+ // `fromProof` on final-slot records so the UI can show "(upscaled from
+ // proof)" provenance.
+
+ it('POST /issues/:id/stages/comicPages/cover/render target=final + useProofAsBase=true persists onto finalImage with fromProof:true, leaving the prior proof slot untouched', async () => {
+ const app = makeApp();
+ const ser = await request(app).post('/api/pipeline/series').send({ name: 'S' });
+ const iss = await request(app).post(`/api/pipeline/series/${ser.body.id}/issues`).send({ title: 'I' });
+ // Seed a prior proof via the render route (the PATCH /issues schema strips
+ // unknown cover fields, so proofImage can only land here via render).
+ const proof = await request(app)
+ .post(`/api/pipeline/issues/${iss.body.id}/stages/comicPages/cover/render`)
+ .send({ coverScript: 'Hero stands atop the foundry' });
+ expect(proof.status).toBe(200);
+ const priorProofJobId = proof.body.cover.proofImage.jobId;
+
+ const r = await request(app)
+ .post(`/api/pipeline/issues/${iss.body.id}/stages/comicPages/cover/render`)
+ .send({ target: 'final', useProofAsBase: true });
+ expect(r.status).toBe(200);
+ expect(r.body.cover.finalImage.jobId).toBe(r.body.jobId);
+ expect(r.body.cover.finalImage.filename).toBeNull();
+ expect(r.body.cover.finalImage.fromProof).toBe(true);
+ // sanitizeRenderSlot only stamps fromProof on the final slot — proof
+ // records omit the field. Assert absence so a future schema regression
+ // that leaks fromProof onto proof slots fails loud.
+ expect(r.body.cover.proofImage.jobId).toBe(priorProofJobId);
+ expect(r.body.cover.proofImage).not.toHaveProperty('fromProof');
+ });
+
+ it('POST /issues/:id/stages/comicPages/pages/:pageIndex/render target=final + useProofAsBase=true persists onto pages[i].finalImage with fromProof:true, leaving the prior proof slot untouched', async () => {
+ const app = makeApp();
+ const ser = await request(app).post('/api/pipeline/series').send({ name: 'S' });
+ const iss = await request(app).post(`/api/pipeline/series/${ser.body.id}/issues`).send({ title: 'I' });
+ await request(app).patch(`/api/pipeline/issues/${iss.body.id}`).send({
+ stages: {
+ comicPages: {
+ pages: [{ panels: [{ description: 'p1', caption: '', dialogue: [], sfx: '' }] }],
+ },
+ },
+ });
+ // Seed a prior proof via the render route (default target = 'proof').
+ const proof = await request(app)
+ .post(`/api/pipeline/issues/${iss.body.id}/stages/comicPages/pages/0/render`)
+ .send({});
+ expect(proof.status).toBe(200);
+ const priorProofJobId = proof.body.stage.pages[0].proofImage.jobId;
+
+ const r = await request(app)
+ .post(`/api/pipeline/issues/${iss.body.id}/stages/comicPages/pages/0/render`)
+ .send({ target: 'final', useProofAsBase: true });
+ expect(r.status).toBe(200);
+ expect(r.body.stage.pages[0].finalImage.jobId).toBe(r.body.jobId);
+ expect(r.body.stage.pages[0].finalImage.filename).toBeNull();
+ expect(r.body.stage.pages[0].finalImage.fromProof).toBe(true);
+ expect(r.body.stage.pages[0].proofImage.jobId).toBe(priorProofJobId);
+ expect(r.body.stage.pages[0].proofImage).not.toHaveProperty('fromProof');
+ });
+
+ it('POST page+cover render schemas reject invalid `target` enum values with 400', async () => {
+ const app = makeApp();
+ const ser = await request(app).post('/api/pipeline/series').send({ name: 'S' });
+ const iss = await request(app).post(`/api/pipeline/series/${ser.body.id}/issues`).send({ title: 'I' });
+ // Zod enum on comicPageRenderSchema rejects before the service dispatches,
+ // so no pages-seeding is needed — validation happens on body parse.
+ const pageRes = await request(app)
+ .post(`/api/pipeline/issues/${iss.body.id}/stages/comicPages/pages/0/render`)
+ .send({ target: 'bogus' });
+ expect(pageRes.status).toBe(400);
+ const coverRes = await request(app)
+ .post(`/api/pipeline/issues/${iss.body.id}/stages/comicPages/cover/render`)
+ .send({ target: 'bogus' });
+ expect(coverRes.status).toBe(400);
+ });
+
// -----------------------
// Season routes (Phase 2 of Story Arc Planning)
// -----------------------