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(pipeline): proof + final comic-page renders with i2i upscale from proof

[._.]/ Adam Eivy4b47f2fd5b9f
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index a60416b988..dfe8ae6b63 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -2,6 +2,35 @@
## Added
+- **Comic pages + cover: proof vs final renders, with i2i upscale from
+ proof.** Each comic page (and the cover) now carries two render slots —
+ `proofImage` (fast layout render) and `finalImage` (hi-res print render).
+ The UI exposes two render buttons per row plus a "from proof" checkbox
+ that, when ticked for the final render, passes the proof's PNG as the
+ i2i init image (denoise strength `0.25` by default) so the larger
+ canvas preserves panel layout / character placement instead of redrawing
+ from scratch. Codex (gpt-image-2 `$imagegen`) has no init-image input,
+ so the checkbox disables with an explanatory tooltip when codex is the
+ active backend — picking it anyway falls back to a full redraw with a
+ server-side warning. PDF assembly reads `finalImage → proofImage →
+ legacy filename` so the print bundle always uses the best available
+ resolution per page. Schema caps lifted from 2048 to 3840 per edge with
+ a total pixel cap of 8,294,400 (gpt-image-2's hard ceiling) across
+ `imageGen.js` + the three pipeline render schemas, and three new codex-
+ only presets land in `imageGenResolutions.js`: `3840×2160` (4K
+ landscape), `2160×3840` (4K portrait, comic-page default), `2880×2880`
+ (4K square). Owner format extended to `pipeline:<id>:comicPages:<target>:<variant>`;
+ the filename hook routes completions to the right slot and migrates any
+ legacy in-flight job into the new shape on landing, so upgrade is
+ zero-friction. Files: `client/src/lib/imageGenResolutions.js`,
+ `client/src/components/pipeline/stages/ComicScriptStage.jsx`,
+ `server/routes/imageGen.js`, `server/routes/pipeline.js`,
+ `server/services/pipeline/{owners,visualStages,comicPagesFilenameHook,
+ comicPdf,issues}.js`, `server/services/imageGen/codex.js`. Tests:
+ 10 `owners.test.js` cases for the variant suffix + legacy parsing; 2
+ `pipeline.test.js` render assertions migrated to the new slot shape; 1
+ `visualStages.test.js` owner-string assertion bumped.
+
- **Story shape is now load-bearing across arc planning.** The Vonnegut
shape picker on the series arc was previously decorative — picked, rendered
as a sparkline, then ignored by every LLM prompt. Now the picked shape (or
diff --git a/PLAN.md b/PLAN.md
index eebb602de6..94b16fbe6d 100644
--- a/PLAN.md
+++ b/PLAN.md
@@ -123,6 +123,8 @@ The dgrauet/ltx-2-mlx runtime ships with FFLF (true keyframe interpolation), aud
- [ ] **Multi-reference image editing for FLUX.2** — UI on the Image Gen page that accepts 2+ reference images plus an edit prompt (e.g. "put the subject from image A into the scene from image B"). When this lands, swap the model registry's 9B entry to [`black-forest-labs/FLUX.2-klein-9B-kv`](https://huggingface.co/black-forest-labs/FLUX.2-klein-9B-kv) — KV-cache optimization gives up to 2.5× speedup on multi-reference workflows. Work involves: schema for multi-image payload (`referenceImages: [...]`), client multi-uploader, server FormData parsing, and adapting `flux2_macos.py` to call the multi-reference pipeline API. Separately-gated repo on HF — user must request access.
- [ ] **World Builder Phase 2 — external SD-API + per-bucket model overrides.** The shipped batch render only supports local mflux + Codex. Wire the existing external SD-API providers (Together, Replicate, Fal) into the world-builder batch path so high-end renders are practical, and let each bucket pick its own model (e.g. characters → SDXL portrait LoRA, environments → Flux-pro). Single touchpoint: `server/services/worldBuilder.js#compileBatchPrompts` + `worldBuilderCollectionHook.js`. (Surfaced from PR #211 follow-ups.)
- [ ] **Unify VideoGen.jsx RESOLUTIONS with the shared image-gen list** — `client/src/pages/VideoGen.jsx:54` defines its own private `RESOLUTIONS` array + finds-by-w/h block, duplicating the pattern in `client/src/lib/imageGenResolutions.js`. Move VideoGen's presets into a shared `client/src/lib/videoGenResolutions.js` (or extend `imageGenResolutions.js` with a `media: 'image' | 'video'` field) so the dropdown + custom-fallback logic only lives in one place. Surfaced during the codex hi-res / per-backend filter work — `filterResolutions(mode, runner)` is exactly the helper VideoGen will want once mlx-video models gain runner-specific size constraints.
+- [ ] **Promote `resolveGalleryImage` to `server/lib/fileUtils.js`.** The basename + `resolvePath` + `startsWith(imagesRoot)` security check is reimplemented in 5 places: `server/routes/videoGen.js:169-180` (the most complete version, includes `statSync.isFile()`), `server/routes/imageGen.js:160-166`, `server/services/pipeline/visualStages.js#resolveProofInitImage`, `server/services/creativeDirector/sceneRunner.js:155`, `server/services/imageGen/local.js:279`. Promote `resolveGalleryImage(name)` into `fileUtils.js` (lives next to `PATHS`) and migrate all five sites — the new `resolveProofInitImage` becomes a thin wrapper that maps the `null` return to the `PIPELINE_COMIC_PROOF_*` ServerError variants. Bonus: pick up the `isFile()` symlink-following defense that the four non-videoGen sites are missing. Surfaced from the /simplify pass on the proof/final feature.
+- [ ] **Route-level tests for `target: 'final'` and `useProofAsBase: true`.** The proof/final feature added route schema fields `target` (proof|final) and `useProofAsBase` (boolean) on `comicPageRenderSchema` + `comicCoverRenderSchema`. Existing `routes/pipeline.test.js` only exercises the default (no `target` → proof slot). Add: (1) a `target: 'final', useProofAsBase: false` test asserting `cover.finalImage.jobId` lands while `proofImage` is preserved untouched, (2) a `target: 'final', useProofAsBase: true` test with no prior proofImage asserting `PIPELINE_COMIC_PROOF_MISSING` surfaces as 400, (3) a happy-path i2i test verifying `initImagePath` reaches the enqueue mock when proofImage.filename is present. Surfaced from the /simplify pass on the proof/final feature.
- [ ] **Extract `useSwipeNav` hook + `lib/clipboard.js`** — `MediaLightbox.jsx` hand-rolls touch-swipe nav (SWIPE_MIN_PX / TAP_MAX_PX / horizontal-dominant guard) and `navigator.clipboard.writeText` is inlined across 8+ call sites (`ExportTab`, `EditAppModal`, `NextActionBanner`, `JiraReports`, `RapidReader`, `Shell`, `RunsHistoryPage`, `MediaLightbox`). Extract once a second swipe consumer appears; clipboard can move now (`copy(text, label)` with the existing "insecure context" toast). Surfaced from the lightbox full-screen pass.
- [ ] **Route `MediaLightbox` settings drawer through `components/Drawer.jsx`** — In full-screen mode the lightbox renders a hand-rolled aside (`absolute top-0 right-0 bottom-0 w-full sm:w-96 z-20`) that is exactly the project's existing `Drawer` component. Skipped during the simplify pass because `Drawer`'s flat Esc handler conflicts with the lightbox's layered Escape cascade (drawer → fullscreen → close); reconcile by either lifting the cascade above `Drawer` or letting `Drawer` accept a no-op-Esc prop.
- [ ] **Extract `<ModelSelect>` component for the active+Legacy optgroup pattern** — `client/src/pages/VideoGen.jsx` and `client/src/pages/CreativeDirector.jsx` both render an identical "filter(!deprecated).map + optgroup('Legacy') + filter(deprecated).map" block (differ only in `m.name` vs `m.name || m.id`). Extract `client/src/components/ModelSelect.jsx` taking `{ models, value, onChange, labelOf?, disabled? }` and convert both sites. ~30 LOC removal, and any future model dropdown picks up the deprecated-grouping for free. Surfaced from the LTX-deprecate /simplify pass.
diff --git a/client/src/components/pipeline/stages/ComicScriptStage.jsx b/client/src/components/pipeline/stages/ComicScriptStage.jsx
index b3bd268466..b688b85797 100644
--- a/client/src/components/pipeline/stages/ComicScriptStage.jsx
+++ b/client/src/components/pipeline/stages/ComicScriptStage.jsx
@@ -9,7 +9,7 @@
import { useCallback, useEffect, useMemo, useState } from 'react';
import { useSearchParams } from 'react-router-dom';
-import { Loader2, Sparkles, ImageIcon, Save, Trash2, ChevronDown, ChevronRight, Settings as SettingsIcon, FileDown } from 'lucide-react';
+import { Loader2, Sparkles, ImageIcon, Save, Trash2, ChevronDown, ChevronRight, Settings as SettingsIcon, FileDown, Layers } from 'lucide-react';
import toast from '../../ui/Toast';
import {
generatePipelineStage,
@@ -37,6 +37,91 @@ import {
pipelineImageCfgToRenderOpts,
} from '../../../lib/pipelineImageDefaults';
+// Legacy records (pre-proof/final split) carry `imageJobId`/`filename` at
+// the record root; surface those as the proof slot so the UI keeps showing
+// the old render until the user re-renders into the new shape.
+const getProofSlot = (rec) => {
+ if (!rec) return null;
+ if (rec.proofImage?.jobId || rec.proofImage?.filename) return rec.proofImage;
+ if (rec.imageJobId || rec.filename) {
+ return { jobId: rec.imageJobId || null, filename: rec.filename || null };
+ }
+ return null;
+};
+
+const getFinalSlot = (rec) => (rec?.finalImage?.jobId || rec?.finalImage?.filename ? rec.finalImage : null);
+
+// Whichever slot the user should see as "rendered" for PDF-readiness math
+// and the lightbox preview — final wins over proof when both exist.
+const getPreferredSlot = (rec) => getFinalSlot(rec) || getProofSlot(rec);
+
+// 5s grace window for stale-jobId staleness: if MediaJobThumb never reports
+// a real status (job archive expired before this session), stop treating the
+// unresolved 'unknown' as in-flight so the render button isn't permanently
+// disabled.
+function useSlotInFlight(slot) {
+ const [status, setStatus] = useState('unknown');
+ const [expired, setExpired] = useState(false);
+ useEffect(() => {
+ setStatus('unknown');
+ setExpired(false);
+ if (!slot?.jobId) return undefined;
+ const t = setTimeout(() => setExpired(true), 5000);
+ return () => clearTimeout(t);
+ }, [slot?.jobId]);
+ const inFlight = !!slot?.jobId
+ && status !== 'completed' && status !== 'failed' && status !== 'canceled'
+ && !(status === 'unknown' && expired);
+ return { inFlight, setStatus };
+}
+
+// Tooltip text for the "Render final" button — picks the first applicable
+// reason from a precedence chain so the user always sees the most specific
+// blocker. `dirtyMsg` is page-only; the cover row passes null.
+function finalButtonTooltip({ gated, inFlight, needsProof, dirty, dirtyMsg, defaultMsg }) {
+ if (gated) return 'Saving settings…';
+ if (dirty) return dirtyMsg;
+ if (inFlight) return 'Final render in progress…';
+ if (needsProof) return 'Render the proof first — "from proof" needs a completed proof image to use as the i2i base.';
+ return defaultMsg;
+}
+
+// Shared proof/final thumb cell — used by both the cover row and the per-
+// page row. Header shows the variant label + WxH; body shows the
+// MediaJobThumb (or an empty-state hint when the slot is unpopulated).
+function RenderSlotThumb({
+ slot, label, emptyHint, thumbLabel, size = 'md',
+ onStatus, onFilename, onPreview, fillFromProofLabel = false,
+}) {
+ return (
+ <div className="flex flex-col bg-port-bg border border-port-border rounded p-1.5">
+ <div className="flex items-center justify-between mb-1">
+ <span className="text-[10px] uppercase tracking-wider text-gray-500">
+ {label}{fillFromProofLabel && slot?.fromProof ? ' (from proof)' : ''}
+ </span>
+ {slot?.width && slot?.height ? (
+ <span className="text-[10px] text-gray-600">{slot.width}×{slot.height}</span>
+ ) : null}
+ </div>
+ <div className="flex-1 flex items-center justify-center overflow-hidden">
+ {slot?.jobId ? (
+ <MediaJobThumb
+ jobId={slot.jobId}
+ label={thumbLabel}
+ size={size}
+ onStatus={onStatus}
+ onFilename={onFilename}
+ onPreview={onPreview}
+ fallbackFilename={slot.filename || null}
+ />
+ ) : (
+ <span className="text-[10px] text-gray-500 italic">{emptyHint}</span>
+ )}
+ </div>
+ </div>
+ );
+}
+
// Reconstructs a page's markdown from its parsed `panels[]`. Used as a
// fallback for pages persisted BEFORE the parser started preserving rawText —
// without it those pages would render as empty textareas, and a Save click
@@ -102,8 +187,12 @@ export default function ComicScriptStage({ issue, series, onStageUpdate, actions
const pageList = Array.isArray(comicPages.pages) ? comicPages.pages : [];
return pageList
.map((p, idx) => {
- if (!p.imageJobId) return null;
- const filename = filenameByJobId[p.imageJobId];
+ // Prefer the hi-res final when present; fall back to proof (or legacy)
+ // so users still see something while the final renders or before they
+ // upgrade a page to a final render.
+ const slot = getPreferredSlot(p);
+ if (!slot?.jobId) return null;
+ const filename = slot.filename || filenameByJobId[slot.jobId];
if (!filename) return null;
return buildPageItem(idx, p, filename);
})
@@ -165,34 +254,24 @@ export default function ComicScriptStage({ issue, series, onStageUpdate, actions
// Front cover lives on stages.comicPages.cover so it persists alongside the
// page renders. The textarea owns a draft string separate from the persisted
// value so keystrokes don't round-trip until blur.
- const cover = comicPages.cover || { script: '', imageJobId: null, prompt: null };
+ const cover = comicPages.cover || { script: '', proofImage: null, finalImage: null };
+ const coverProof = getProofSlot(cover);
+ const coverFinal = getFinalSlot(cover);
const [draftCoverScript, setDraftCoverScript] = useState(cover.script || '');
useEffect(() => { setDraftCoverScript(cover.script || ''); }, [cover.script]);
- const [renderingCover, setRenderingCover] = useState(false);
- // Mirror PageRow's job-status pattern: start 'unknown' so we treat any
- // existing jobId as in-flight until MediaJobThumb reports back.
- const [coverJobStatus, setCoverJobStatus] = useState('unknown');
- // `unknown` means the GET /media-jobs/:id is still in-flight OR the job
- // archive has expired (404). After a short grace period, stop treating an
- // unresolved `unknown` as in-flight so a stale imageJobId (job archived,
- // page reloaded) doesn't permanently disable "Render cover". The 5-second
- // window comfortably outlasts any LAN round-trip while being short enough
- // that an actual expired-archive case doesn't frustrate the user.
- const [coverUnknownExpired, setCoverUnknownExpired] = useState(false);
- // Reset both whenever the jobId changes so a freshly-queued job gets a
- // clean slate and is immediately treated as in-flight.
- useEffect(() => {
- setCoverJobStatus('unknown');
- setCoverUnknownExpired(false);
- if (!cover.imageJobId) return undefined;
- const t = setTimeout(() => setCoverUnknownExpired(true), 5000);
- return () => clearTimeout(t);
- }, [cover.imageJobId]);
- const coverJobInFlight = !!cover.imageJobId
- && coverJobStatus !== 'completed'
- && coverJobStatus !== 'failed'
- && coverJobStatus !== 'canceled'
- && !(coverJobStatus === 'unknown' && coverUnknownExpired);
+ const [renderingCoverProof, setRenderingCoverProof] = useState(false);
+ const [renderingCoverFinal, setRenderingCoverFinal] = useState(false);
+ const [useProofForCoverFinal, setUseProofForCoverFinal] = useState(true);
+ const { inFlight: coverProofInFlight, setStatus: setCoverProofStatus } = useSlotInFlight(coverProof);
+ const { inFlight: coverFinalInFlight, setStatus: setCoverFinalStatus } = useSlotInFlight(coverFinal);
+
+ // Codex CLI's `$imagegen` has no init-image input, so the "use proof as
+ // base" upscale path can't preserve composition there. Disable the
+ // checkbox + show a tooltip when codex is the active backend.
+ const i2iSupported = imageCfg.mode !== 'codex';
+ const i2iDisabledReason = i2iSupported
+ ? null
+ : 'Codex (gpt-image-2) does not support image-to-image. Switch backend in the image-gen settings to use the proof as a base.';
const persistCoverScript = async (nextScript) => {
// Only send the script text. Never clear imageJobId/prompt from the blur
@@ -209,21 +288,26 @@ export default function ComicScriptStage({ issue, series, onStageUpdate, actions
if (updated) onStageUpdate?.('comicPages', updated.stages.comicPages, updated);
};
- const handleRenderCover = async () => {
- setRenderingCover(true);
+ const handleRenderCover = async (target) => {
+ const setFlight = target === 'final' ? setRenderingCoverFinal : setRenderingCoverProof;
+ setFlight(true);
+ const useProofAsBase = target === 'final' && useProofForCoverFinal && i2iSupported;
const result = await generatePipelineComicCover(issue.id, {
coverScript: draftCoverScript || '',
...renderOpts,
+ target,
+ useProofAsBase,
}, { silent: true }).catch((err) => {
- toast.error(err.message || 'Failed to render cover');
+ toast.error(err.message || `Failed to render ${target} cover`);
return null;
});
- setRenderingCover(false);
+ setFlight(false);
if (!result) return;
if (result.issue) {
onStageUpdate?.('comicPages', result.issue.stages.comicPages, result.issue);
}
- toast.success(`Queued ${result.mode} cover render (${result.jobId.slice(0, 8)})`);
+ const suffix = useProofAsBase ? ' (from proof)' : '';
+ toast.success(`Queued ${result.mode} ${target} cover render${suffix} (${result.jobId.slice(0, 8)})`);
};
const overrides = {
@@ -260,8 +344,11 @@ export default function ComicScriptStage({ issue, series, onStageUpdate, actions
}
};
- const pdfRenderedCount = pages.filter((p) => p?.filename).length
- + (comicPages.cover?.filename ? 1 : 0);
+ // Count any page/cover that has a final OR proof slot with a filename — the
+ // PDF assembly's fallback chain prefers final, then proof, then legacy.
+ const isRendered = (rec) => !!getPreferredSlot(rec)?.filename;
+ const pdfRenderedCount = pages.filter(isRendered).length
+ + (isRendered(comicPages.cover) ? 1 : 0);
const pdfTotal = pages.length + (comicPages.cover ? 1 : 0);
const pdfReady = pdfRenderedCount > 0;
@@ -348,32 +435,55 @@ export default function ComicScriptStage({ issue, series, onStageUpdate, actions
</p>
) : null}
- <div className="p-3 bg-port-card border border-port-border rounded-lg">
- <div className="flex items-center justify-between mb-2 gap-2 flex-wrap">
+ <div className="p-3 bg-port-card border border-port-border rounded-lg space-y-2">
+ <div className="flex items-center justify-between gap-2 flex-wrap">
<span className="text-xs uppercase tracking-wider text-gray-500">Cover</span>
- <div className="flex items-center gap-2">
+ <div className="flex items-center gap-2 flex-wrap">
<button
type="button"
- onClick={handleRenderCover}
- disabled={renderingCover || coverJobInFlight || actionsGated}
+ onClick={() => handleRenderCover('proof')}
+ disabled={renderingCoverProof || coverProofInFlight || actionsGated}
title={actionsGated
? 'Saving settings…'
- : coverJobInFlight
- ? 'Cover render in progress…'
- : 'Render the issue\'s front cover — series masthead + issue number tag + your cover concept.'}
+ : coverProofInFlight
+ ? 'Proof render in progress…'
+ : 'Render a fast proof cover at the configured size — series masthead + issue number tag + your cover concept.'}
+ className="inline-flex items-center gap-1.5 px-3 py-1.5 rounded-lg bg-port-accent text-white text-xs font-medium hover:bg-port-accent/90 disabled:opacity-40 disabled:cursor-not-allowed"
+ >
+ {(renderingCoverProof || coverProofInFlight) ? <Loader2 size={12} className="animate-spin" /> : <ImageIcon size={12} />}
+ Render proof
+ </button>
+ <label
+ className={`flex items-center gap-1 text-[11px] text-gray-400 ${i2iSupported ? 'cursor-pointer' : 'cursor-not-allowed opacity-60'}`}
+ title={i2iDisabledReason || 'Use the proof image as the base for the final render — preserves composition.'}
+ >
+ <input
+ type="checkbox"
+ checked={i2iSupported && useProofForCoverFinal}
+ onChange={(e) => setUseProofForCoverFinal(e.target.checked)}
+ disabled={!i2iSupported}
+ className="rounded"
+ />
+ from proof
+ </label>
+ <button
+ type="button"
+ onClick={() => handleRenderCover('final')}
+ disabled={
+ renderingCoverFinal || coverFinalInFlight || actionsGated
+ || (i2iSupported && useProofForCoverFinal && !coverProof?.filename)
+ }
+ title={finalButtonTooltip({
+ gated: actionsGated,
+ inFlight: coverFinalInFlight,
+ needsProof: i2iSupported && useProofForCoverFinal && !coverProof?.filename,
+ defaultMsg: 'Render the hi-res final cover at the configured size. Tick "from proof" to upscale the proof rather than redraw it.',
+ })}
className="inline-flex items-center gap-1.5 px-3 py-1.5 rounded-lg bg-port-accent text-white text-xs font-medium hover:bg-port-accent/90 disabled:opacity-40 disabled:cursor-not-allowed"
>
- {(renderingCover || coverJobInFlight) ? <Loader2 size={12} className="animate-spin" /> : <ImageIcon size={12} />}
- Render cover
+ {(renderingCoverFinal || coverFinalInFlight) ? <Loader2 size={12} className="animate-spin" /> : <Layers size={12} />}
+ Render final
</button>
- {cover.imageJobId ? (
- <div className="flex items-center gap-2">
- <MediaJobThumb jobId={cover.imageJobId} label="Cover" size="md" onStatus={setCoverJobStatus} fallbackFilename={cover.filename || null} />
- <span className="text-[10px] text-gray-500 font-mono break-all" title="Last cover render job">
- {cover.imageJobId.slice(0, 8)}
- </span>
- </div>
- ) : null}
</div>
</div>
<textarea
@@ -387,6 +497,25 @@ export default function ComicScriptStage({ issue, series, onStageUpdate, actions
className="w-full px-2 py-1.5 bg-port-bg border border-port-border rounded text-white text-sm"
maxLength={8000}
/>
+ {(coverProof || coverFinal) ? (
+ <div className="grid grid-cols-2 gap-2">
+ <RenderSlotThumb
+ slot={coverProof}
+ label="Proof"
+ thumbLabel="Proof"
+ emptyHint="No proof yet."
+ onStatus={setCoverProofStatus}
+ />
+ <RenderSlotThumb
+ slot={coverFinal}
+ label="Final"
+ thumbLabel="Final"
+ emptyHint="No final yet."
+ onStatus={setCoverFinalStatus}
+ fillFromProofLabel
+ />
+ </div>
+ ) : null}
</div>
<ul className="space-y-4">
@@ -397,6 +526,8 @@ export default function ComicScriptStage({ issue, series, onStageUpdate, actions
pageIndex={pi}
page={page}
renderOpts={renderOpts}
+ i2iSupported={i2iSupported}
+ i2iDisabledReason={i2iDisabledReason}
onStageUpdate={onStageUpdate}
onPreview={openPreview}
onFilenameKnown={onFilenameKnown}
@@ -434,30 +565,35 @@ export default function ComicScriptStage({ issue, series, onStageUpdate, actions
);
}
-function PageRow({ issue, pageIndex, page, renderOpts = {}, onStageUpdate, onPreview, onFilenameKnown }) {
+function PageRow({
+ issue, pageIndex, page, renderOpts = {},
+ i2iSupported = true, i2iDisabledReason = null,
+ onStageUpdate, onPreview, onFilenameKnown,
+}) {
const rawText = useMemo(
() => page.rawText || panelsToMarkdown(page.panels, pageIndex + 1),
[page.rawText, page.panels, pageIndex],
);
const [draft, setDraft] = useState(rawText);
const [saving, setSaving] = useState(false);
- const [rendering, setRendering] = useState(false);
+ const [renderingProof, setRenderingProof] = useState(false);
+ const [renderingFinal, setRenderingFinal] = useState(false);
+ const [useProofForFinal, setUseProofForFinal] = useState(true);
// Sync local edits with parent updates (re-extract / re-render persist).
useEffect(() => { setDraft(rawText); }, [rawText]);
const dirty = draft !== rawText;
- // Job status comes from MediaJobThumb via callback so we don't double-
- // subscribe to the same socket events. Treat 'unknown' (pre-hydration)
- // as in-flight when a jobId exists — avoids a brief re-enable flash
- // after page reload while the GET /media-jobs/:id catches up.
- const [jobStatus, setJobStatus] = useState('unknown');
- const jobInFlight = !!page.imageJobId
- && jobStatus !== 'completed'
- && jobStatus !== 'failed'
- && jobStatus !== 'canceled';
- const onJobFilename = useCallback((filename) => {
- if (page.imageJobId) onFilenameKnown?.(page.imageJobId, filename);
- }, [page.imageJobId, onFilenameKnown]);
+ const proofSlot = getProofSlot(page);
+ const finalSlot = getFinalSlot(page);
+ const { inFlight: proofInFlight, setStatus: setProofStatus } = useSlotInFlight(proofSlot);
+ const { inFlight: finalInFlight, setStatus: setFinalStatus } = useSlotInFlight(finalSlot);
+
+ const onProofFilename = useCallback((filename) => {
+ if (proofSlot?.jobId) onFilenameKnown?.(proofSlot.jobId, filename);
+ }, [proofSlot?.jobId, onFilenameKnown]);
+ const onFinalFilename = useCallback((filename) => {
+ if (finalSlot?.jobId) onFilenameKnown?.(finalSlot.jobId, filename);
+ }, [finalSlot?.jobId, onFilenameKnown]);
const handleSave = async () => {
setSaving(true);
@@ -470,14 +606,20 @@ function PageRow({ issue, pageIndex, page, renderOpts = {}, onStageUpdate, onPre
}
};
- const handleRender = async () => {
- setRendering(true);
- const res = await generatePipelineComicPage(issue.id, pageIndex, renderOpts)
- .catch((err) => { toast.error(err.message || 'Render failed'); return null; });
- setRendering(false);
+ const handleRender = async (target) => {
+ const setFlight = target === 'final' ? setRenderingFinal : setRenderingProof;
+ setFlight(true);
+ const useProofAsBase = target === 'final' && useProofForFinal && i2iSupported;
+ const res = await generatePipelineComicPage(issue.id, pageIndex, {
+ ...renderOpts,
+ target,
+ useProofAsBase,
+ }).catch((err) => { toast.error(err.message || 'Render failed'); return null; });
+ setFlight(false);
if (res) {
onStageUpdate?.('comicPages', res.stage);
- toast.success(`Page ${pageIndex + 1} render queued (${res.mode || renderOpts.mode || 'local'})`);
+ const suffix = useProofAsBase ? ' (from proof)' : '';
+ toast.success(`Page ${pageIndex + 1} ${target}${suffix} render queued (${res.mode || renderOpts.mode || 'local'})`);
}
};
@@ -492,15 +634,17 @@ function PageRow({ issue, pageIndex, page, renderOpts = {}, onStageUpdate, onPre
}
};
+ const finalNeedsProof = i2iSupported && useProofForFinal && !proofSlot?.filename;
+
return (
<li className="rounded-lg border border-port-border bg-port-card/40">
- <div className="flex items-center justify-between gap-2 px-3 py-2 border-b border-port-border">
+ <div className="flex items-center justify-between gap-2 px-3 py-2 border-b border-port-border flex-wrap">
<div className="flex items-center gap-2">
<span className="text-xs uppercase tracking-wider text-gray-500">Page {pageIndex + 1}</span>
<span className="text-[10px] text-gray-600">{page.panels?.length || 0} panel{page.panels?.length === 1 ? '' : 's'}</span>
{dirty ? <span className="text-[10px] text-port-warning">unsaved</span> : null}
</div>
- <div className="flex items-center gap-1">
+ <div className="flex items-center gap-1 flex-wrap">
<button
type="button"
onClick={handleSave}
@@ -512,17 +656,47 @@ function PageRow({ issue, pageIndex, page, renderOpts = {}, onStageUpdate, onPre
</button>
<button
type="button"
- onClick={handleRender}
- disabled={rendering || dirty || jobInFlight}
+ onClick={() => handleRender('proof')}
+ disabled={renderingProof || dirty || proofInFlight}
className="inline-flex items-center gap-1 px-2 py-1 rounded text-xs bg-port-accent text-white font-medium disabled:opacity-40"
title={dirty
? 'Save changes before rendering'
- : jobInFlight
- ? 'Render in progress…'
- : 'Queue a full-page render for this page'}
+ : proofInFlight
+ ? 'Proof render in progress…'
+ : 'Queue a fast proof render at the configured size'}
>
- {(rendering || jobInFlight) ? <Loader2 size={12} className="animate-spin" /> : <ImageIcon size={12} />}
- Render
+ {(renderingProof || proofInFlight) ? <Loader2 size={12} className="animate-spin" /> : <ImageIcon size={12} />}
+ Proof
+ </button>
+ <label
+ className={`flex items-center gap-1 text-[11px] text-gray-400 px-1 ${i2iSupported ? 'cursor-pointer' : 'cursor-not-allowed opacity-60'}`}
+ title={i2iDisabledReason || 'Use the proof image as the base for the final render — preserves panel layout.'}
+ >
+ <input
+ type="checkbox"
+ checked={i2iSupported && useProofForFinal}
+ onChange={(e) => setUseProofForFinal(e.target.checked)}
+ disabled={!i2iSupported}
+ className="rounded"
+ />
+ from proof
+ </label>
+ <button
+ type="button"
+ onClick={() => handleRender('final')}
+ disabled={renderingFinal || dirty || finalInFlight || finalNeedsProof}
+ className="inline-flex items-center gap-1 px-2 py-1 rounded text-xs bg-port-accent text-white font-medium disabled:opacity-40"
+ title={finalButtonTooltip({
+ gated: false,
+ inFlight: finalInFlight,
+ needsProof: finalNeedsProof,
+ dirty,
+ dirtyMsg: 'Save changes before rendering',
+ defaultMsg: 'Queue a hi-res final render. Tick "from proof" to upscale the proof rather than redraw it.',
+ })}
+ >
+ {(renderingFinal || finalInFlight) ? <Loader2 size={12} className="animate-spin" /> : <Layers size={12} />}
+ Final
</button>
<button
type="button"
@@ -544,20 +718,28 @@ function PageRow({ issue, pageIndex, page, renderOpts = {}, onStageUpdate, onPre
className="w-full px-3 py-2 bg-port-bg border border-port-border rounded text-white text-xs font-mono leading-relaxed"
placeholder={`## Page ${pageIndex + 1}\n\n### Panel 1\n**Description:** ...`}
/>
- <div className="flex items-center justify-center bg-port-bg border border-port-border rounded min-h-[200px] overflow-hidden">
- {page.imageJobId ? (
- <MediaJobThumb
- jobId={page.imageJobId}
- label={`Page ${pageIndex + 1}`}
- size="fill"
- onPreview={(filename) => onPreview?.(pageIndex, filename, page)}
- onStatus={setJobStatus}
- onFilename={onJobFilename}
- fallbackFilename={page.filename || null}
- />
- ) : (
- <span className="text-xs text-gray-500 italic">No render yet — click <em>Render</em>.</span>
- )}
+ <div className="grid grid-cols-2 gap-2 min-h-[200px]">
+ <RenderSlotThumb
+ slot={proofSlot}
+ label="Proof"
+ thumbLabel={`Page ${pageIndex + 1} (proof)`}
+ emptyHint="No proof yet"
+ size="fill"
+ onStatus={setProofStatus}
+ onFilename={onProofFilename}
+ onPreview={(filename) => onPreview?.(pageIndex, filename, page)}
+ />
+ <RenderSlotThumb
+ slot={finalSlot}
+ label="Final"
+ thumbLabel={`Page ${pageIndex + 1} (final)`}
+ emptyHint="No final yet"
+ size="fill"
+ onStatus={setFinalStatus}
+ onFilename={onFinalFilename}
+ onPreview={(filename) => onPreview?.(pageIndex, filename, page)}
+ fillFromProofLabel
+ />
</div>
</div>
</li>
diff --git a/client/src/lib/imageGenResolutions.js b/client/src/lib/imageGenResolutions.js
index f9b255c531..8a412a927b 100644
--- a/client/src/lib/imageGenResolutions.js
+++ b/client/src/lib/imageGenResolutions.js
@@ -24,6 +24,13 @@ export const RESOLUTIONS = [
{ label: '1536×1536 (hi-res square)', w: 1536, h: 1536, compatible: ['codex', RUNNER_FAMILIES.FLUX2] },
{ label: '1024×1536 (hi-res portrait)', w: 1024, h: 1536, compatible: ['codex', RUNNER_FAMILIES.FLUX2] },
{ label: '1536×1024 (hi-res landscape)', w: 1536, h: 1024, compatible: ['codex', RUNNER_FAMILIES.FLUX2] },
+ // gpt-image-2 final-render presets: hard ceiling is each edge ≤ 3840 and
+ // total ≤ 8,294,400 pixels. All three below sit exactly at the pixel cap
+ // — pick aspect by shape. Codex-only because mflux/diffusers are too slow
+ // at this resolution to be practical (and the smaller models degrade).
+ { label: '3840×2160 (4K landscape)', w: 3840, h: 2160, compatible: ['codex'] },
+ { label: '2160×3840 (4K portrait — comic page)', w: 2160, h: 3840, compatible: ['codex'] },
+ { label: '2880×2880 (4K square)', w: 2880, h: 2880, compatible: ['codex'] },
];
// Flux 1 (mflux/diffusers, `dev` / `schnell`) has no `runner` field — it's
diff --git a/server/lib/validation.js b/server/lib/validation.js
index 46051c1af9..3976e17921 100644
--- a/server/lib/validation.js
+++ b/server/lib/validation.js
@@ -4,6 +4,19 @@ import { ASPECT_RATIOS, QUALITIES, PROJECT_STATUSES, SCENE_STATUSES } from './cr
import { WORK_KINDS, WORK_STATUSES, ANALYSIS_KINDS } from './writersRoomPresets.js';
import { ALL_STYLE_IDS, STYLE_ID } from './writersRoomStylePresets.js';
+// gpt-image-2 (codex backend) caps at 3840px per edge and 8,294,400 total
+// pixels. Mirror the ceiling for every image-gen route. Local mflux can
+// render up to 3840 in principle but is impractically slow past ~2048 — the
+// UI's `compatible: ['codex']` filter on the 4K presets keeps those out of
+// the local picker. Shared so the cap and refinement message stay identical
+// across schemas.
+export const MAX_IMAGE_EDGE = 3840;
+export const MAX_IMAGE_PIXELS = 8_294_400;
+export const imageEdgeSchema = z.number().int().min(64).max(MAX_IMAGE_EDGE).optional();
+export const refineImagePixelCap = (d) =>
+ !(d.width && d.height) || d.width * d.height <= MAX_IMAGE_PIXELS;
+export const PIXEL_CAP_MESSAGE = `Total pixels (width × height) must be ≤ ${MAX_IMAGE_PIXELS.toLocaleString()}`;
+
// =============================================================================
// AGENT PERSONALITY SCHEMAS
// =============================================================================
diff --git a/server/routes/imageGen.js b/server/routes/imageGen.js
index fcdc373874..aef6c5bccf 100644
--- a/server/routes/imageGen.js
+++ b/server/routes/imageGen.js
@@ -15,7 +15,9 @@ import { existsSync } from 'fs';
import { copyFile, unlink } from 'fs/promises';
import { randomUUID } from 'crypto';
import { asyncHandler, ServerError } from '../lib/errorHandler.js';
-import { validateRequest } from '../lib/validation.js';
+import {
+ validateRequest, imageEdgeSchema, refineImagePixelCap, PIXEL_CAP_MESSAGE,
+} from '../lib/validation.js';
import { optionalUpload } from '../lib/multipart.js';
import * as imageGen from '../services/imageGen/index.js';
import { local, IMAGE_GEN_MODES } from '../services/imageGen/index.js';
@@ -47,8 +49,8 @@ const generateSchema = z.object({
// `imageGen.mode` from settings.json.
mode: z.enum(IMAGE_GEN_MODES).optional(),
modelId: z.string().max(64).optional(),
- width: z.number().int().min(64).max(2048).optional(),
- height: z.number().int().min(64).max(2048).optional(),
+ width: imageEdgeSchema,
+ height: imageEdgeSchema,
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(),
@@ -66,7 +68,7 @@ const generateSchema = z.object({
// upload. Strength: 0.0 = ignore source, 1.0 = max influence.
initImageFile: z.string().max(256).regex(/^[^/\\]+\.(png|jpg|jpeg|webp)$/i, 'init image must be a basename ending in png/jpg/jpeg/webp').optional(),
initImageStrength: z.number().min(0).max(1).optional(),
-});
+}).refine(refineImagePixelCap, { message: PIXEL_CAP_MESSAGE, path: ['width'] });
// JSON callers (SDAPI bridge, avatar route, the Imagine page's old payload
// shape) skip the parser entirely; FormData callers get req.file + string
diff --git a/server/routes/pipeline.js b/server/routes/pipeline.js
index 99b3012d2d..77d4fa71ed 100644
--- a/server/routes/pipeline.js
+++ b/server/routes/pipeline.js
@@ -30,6 +30,9 @@ import {
characterBibleCreateSchema,
settingBibleCreateSchema,
objectBibleCreateSchema,
+ imageEdgeSchema,
+ refineImagePixelCap,
+ PIXEL_CAP_MESSAGE,
} from '../lib/validation.js';
import * as seriesSvc from '../services/pipeline/series.js';
import * as issuesSvc from '../services/pipeline/issues.js';
@@ -46,9 +49,11 @@ import {
enqueueStoryboardShotStartFrame,
refineComicPanelPrompt,
refineStoryboardScenePrompt,
+ buildRenderSlot,
} from '../services/pipeline/visualStages.js';
import { refineCharacterDescription } from '../services/pipeline/nounRefine.js';
import { startEpisodeVideoForIssue, ERR_NO_STORYBOARDS } from '../services/pipeline/episodeVideo.js';
+import { COMIC_PAGE_VARIANTS, slotKeyForVariant } from '../services/pipeline/owners.js';
import { ASPECT_RATIOS, QUALITIES } from '../lib/creativeDirectorPresets.js';
import { extractScenes, SOURCE_KIND } from '../lib/sceneExtractor.js';
import { listVisualStyles } from '../lib/visualStyles.js';
@@ -85,19 +90,6 @@ const mapServiceError = (err) => {
return err;
};
-// gpt-image-2 (codex backend) caps at 3840px per edge and 8,294,400 total
-// pixels. Mirror that ceiling for every pipeline image-gen route. Local
-// mflux can render up to 3840 in principle but is impractically slow past
-// ~2048 — the UI's `compatible: ['codex']` filter on the 4K presets keeps
-// those out of the local picker. The validator is shared because the cap
-// and refinement message must stay identical across schemas.
-const MAX_IMAGE_EDGE = 3840;
-const MAX_IMAGE_PIXELS = 8_294_400;
-const imageEdge = z.number().int().min(64).max(MAX_IMAGE_EDGE).optional();
-const refineImagePixelCap = (d) =>
- !(d.width && d.height) || d.width * d.height <= MAX_IMAGE_PIXELS;
-const PIXEL_CAP_MESSAGE = `Total pixels (width × height) must be ≤ ${MAX_IMAGE_PIXELS.toLocaleString()}`;
-
// ---- Series schemas ----
// Bible entry shape is owned by the canonical schemas in `server/lib/validation.js`
@@ -316,8 +308,8 @@ const visualGenerateSchema = z.object({
extraStyle: z.string().trim().max(2000).optional(),
mode: z.enum(['local', 'codex']).optional(),
modelId: z.string().trim().max(64).optional(),
- width: imageEdge,
- height: imageEdge,
+ width: imageEdgeSchema,
+ height: imageEdgeSchema,
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(),
@@ -336,8 +328,8 @@ const comicCoverRenderSchema = z.object({
extraStyle: z.string().trim().max(2000).optional(),
mode: z.enum(['local', 'codex']).optional(),
modelId: z.string().trim().max(64).optional(),
- width: imageEdge,
- height: imageEdge,
+ width: imageEdgeSchema,
+ height: imageEdgeSchema,
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(),
@@ -345,7 +337,7 @@ const comicCoverRenderSchema = z.object({
// Proof vs Final render variant. Each variant lands in its own slot
// (cover.proofImage / cover.finalImage) so the user can keep a fast
// proof for layout decisions and a hi-res final for the PDF.
- target: z.enum(['proof', 'final']).optional().default('proof'),
+ target: z.enum(COMIC_PAGE_VARIANTS).optional().default('proof'),
// When the user likes the proof and wants the final to preserve its
// composition, set this to true — the server will pass the proof image
// as the init image for the final render at low denoise strength.
@@ -362,14 +354,14 @@ const comicPageRenderSchema = z.object({
extraStyle: z.string().trim().max(2000).optional(),
mode: z.enum(['local', 'codex']).optional(),
modelId: z.string().trim().max(64).optional(),
- width: imageEdge,
- height: imageEdge,
+ width: imageEdgeSchema,
+ height: imageEdgeSchema,
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(),
// See comicCoverRenderSchema for the proof/final semantics.
- target: z.enum(['proof', 'final']).optional().default('proof'),
+ target: z.enum(COMIC_PAGE_VARIANTS).optional().default('proof'),
useProofAsBase: z.boolean().optional().default(false),
}).refine(refineImagePixelCap, { message: PIXEL_CAP_MESSAGE, path: ['width'] });
@@ -1103,20 +1095,29 @@ router.post('/issues/:id/stages/comicPages/cover/render', asyncHandler(async (re
const result = await enqueueComicCover(req.params.id, body)
.catch((err) => { throw mapServiceError(err); });
- // Persist coverScript + jobId + prompt back onto the issue so the UI
- // shows the in-flight render on reload, even if the user navigates away.
- const nextCover = {
- script: result.coverScript || '',
- imageJobId: result.jobId,
- prompt: result.prompt,
- // Clear the prior render's filename so the UI doesn't show the stale
- // image while the new job is in flight. The comic-pages filename hook
- // re-stamps it on completion.
- filename: null,
- };
- const { issue: updatedIssue, stage } = await issuesSvc.updateStage(req.params.id, 'comicPages', {
- cover: nextCover,
+ // Seed the in-flight render into the matching slot. The filename hook
+ // stamps `filename` on completion; `filename: null` here lets the UI
+ // render an "in-flight" thumb without showing the previous render's
+ // image while the new job is running.
+ const slotKey = slotKeyForVariant(result.variant);
+ const slotRecord = buildRenderSlot({
+ slotKey, jobId: result.jobId, prompt: result.prompt,
+ width: body.width, height: body.height, fromProof: result.fromProof,
});
+ const { issue: updatedIssue, stage } = await issuesSvc.updateStageWithLatest(
+ req.params.id,
+ 'comicPages',
+ (currentStage) => {
+ const currentCover = currentStage?.cover || {};
+ return {
+ cover: {
+ ...currentCover,
+ script: result.coverScript || '',
+ [slotKey]: slotRecord,
+ },
+ };
+ },
+ ).catch((err) => { throw mapServiceError(err); });
res.json({ ...result, cover: stage.cover, issue: updatedIssue, stage });
}));
@@ -1152,20 +1153,21 @@ router.post('/issues/:id/stages/comicPages/pages/:pageIndex/render', asyncHandle
const result = await enqueueVisualComicPage(req.params.id, { pageIndex, ...body })
.catch((err) => { throw mapServiceError(err); });
- // Persist the jobId on the page so a reload still shows the in-flight render.
- // The splice happens inside updateStageWithLatest's computeFn so it lands on
- // the freshest persisted pages array — a concurrent page edit or sibling
- // page's render that wrote between our enqueue and persist would otherwise
- // be reverted by the stale snapshot above.
+ // The splice happens inside updateStageWithLatest's computeFn so the
+ // slot lands on the freshest persisted pages array — a concurrent page
+ // edit or sibling render that wrote between our enqueue and persist
+ // would otherwise be reverted by a stale snapshot.
+ const slotKey = slotKeyForVariant(result.variant);
+ const slotRecord = buildRenderSlot({
+ slotKey, jobId: result.jobId, prompt: result.prompt,
+ width: body.width, height: body.height, fromProof: result.fromProof,
+ });
const { issue: updatedIssue, stage } = await issuesSvc.updateStageWithLatest(
req.params.id,
'comicPages',
(currentStage) => {
const currentPages = Array.isArray(currentStage?.pages) ? currentStage.pages : [];
if (!currentPages[pageIndex]) {
- // Page was deleted between enqueue and persist (unlikely but possible).
- // Throw 404 — the queued render job will surface as orphaned in the
- // media-jobs queue, which the UI can clean up.
throw new ServerError(
`pageIndex ${pageIndex} out of range — comicPages has ${currentPages.length} page${currentPages.length === 1 ? '' : 's'}`,
{ status: 404, code: 'PIPELINE_COMIC_PAGE_NOT_FOUND' },
@@ -1174,11 +1176,7 @@ router.post('/issues/:id/stages/comicPages/pages/:pageIndex/render', asyncHandle
const nextPages = [...currentPages];
nextPages[pageIndex] = {
...currentPages[pageIndex],
- imageJobId: result.jobId,
- prompt: result.prompt,
- // Clear the prior render's filename so the UI doesn't show the stale
- // image while the new job is in flight. The hook re-stamps on completion.
- filename: null,
+ [slotKey]: slotRecord,
};
return { status: 'edited', pages: nextPages };
},
diff --git a/server/routes/pipeline.test.js b/server/routes/pipeline.test.js
index def19ab002..51bba3b269 100644
--- a/server/routes/pipeline.test.js
+++ b/server/routes/pipeline.test.js
@@ -97,6 +97,18 @@ vi.mock('../services/pipeline/visualStages.js', () => ({
issue: { id: issueId, stages: { storyboards: { scenes: [] } } },
stage: { scenes: [] },
})),
+ // Pure helper used by the route to construct the in-flight slot record.
+ // Kept inline (not vi.fn) so the route's call-site logic is exercised
+ // without forcing every test to thread a mock implementation through.
+ buildRenderSlot: ({ slotKey, jobId, prompt, width, height, fromProof = false, filename = null }) => ({
+ jobId,
+ filename,
+ prompt: prompt || null,
+ width: width ?? null,
+ height: height ?? null,
+ createdAt: new Date().toISOString(),
+ ...(slotKey === 'finalImage' ? { fromProof } : {}),
+ }),
refineComicPanelPrompt: vi.fn(async (issueId, pi, ni) => ({
panel: { description: 'refined panel body' },
page: { panels: [] },
@@ -819,10 +831,13 @@ describe('pipeline routes', () => {
expect(r.body.jobId).toMatch(/^page-job-/);
// pageNumber is pageIndex + 1, so /pages/1/render renders the *2nd* page.
expect(r.body.prompt).toMatch(/page 2/);
- expect(r.body.stage.pages[1].imageJobId).toBe(r.body.jobId);
- expect(r.body.stage.pages[1].prompt).toBe(r.body.prompt);
- // Other page untouched
- expect(r.body.stage.pages[0].imageJobId).toBeUndefined();
+ // No explicit target → defaults to proof (per the route schema).
+ // The render lands on pages[1].proofImage, not the legacy imageJobId slot.
+ expect(r.body.stage.pages[1].proofImage.jobId).toBe(r.body.jobId);
+ expect(r.body.stage.pages[1].proofImage.prompt).toBe(r.body.prompt);
+ expect(r.body.stage.pages[1].proofImage.filename).toBeNull();
+ // Other page untouched — has no slot record either.
+ expect(r.body.stage.pages[0].proofImage).toBeFalsy();
expect(r.body.stage.status).toBe('edited');
});
@@ -858,13 +873,15 @@ describe('pipeline routes', () => {
expect(r.status).toBe(200);
expect(r.body.jobId).toMatch(/^cover-job-/);
expect(r.body.prompt).toBe('cover art prompt');
- // Persistence: stages.comicPages.cover must carry script, imageJobId, prompt.
+ // Persistence: cover carries the user's script + the proof slot
+ // record. No `target` in the request → defaults to 'proof' per schema.
expect(r.body.cover.script).toBe('Hero stands atop the foundry, smoke rising');
- expect(r.body.cover.imageJobId).toBe(r.body.jobId);
- expect(r.body.cover.prompt).toBe(r.body.prompt);
+ expect(r.body.cover.proofImage.jobId).toBe(r.body.jobId);
+ expect(r.body.cover.proofImage.prompt).toBe(r.body.prompt);
+ expect(r.body.cover.proofImage.filename).toBeNull();
// Top-level issue + stage are also returned.
expect(r.body.issue.id).toBe(iss.body.id);
- expect(r.body.stage.cover.imageJobId).toBe(r.body.jobId);
+ expect(r.body.stage.cover.proofImage.jobId).toBe(r.body.jobId);
});
it('POST /issues/:id/stages/comicPages/cover/render 404s for an unknown issue', async () => {
diff --git a/server/services/imageGen/codex.js b/server/services/imageGen/codex.js
index 07a17be140..05f61d79f6 100644
--- a/server/services/imageGen/codex.js
+++ b/server/services/imageGen/codex.js
@@ -119,10 +119,23 @@ export async function checkConnection({ codexPath } = {}) {
const SESSION_ID_RE = /^session id:\s*([0-9a-f-]{36})/im;
-export async function generateImage({ codexPath, model, prompt, width, height, negativePrompt, jobId: providedJobId = null }) {
+export async function generateImage({
+ codexPath, model, prompt, width, height, negativePrompt,
+ // Accepted (and ignored) so the pipeline's "use proof as base" upscale path
+ // doesn't reject when codex is the active backend. The `$imagegen` skill in
+ // the Codex CLI has no init-image input; this surface is local-only. Logged
+ // so the degraded behavior is visible — a final render kicked off with
+ // useProofAsBase=true against codex will be a full redraw at the larger
+ // size, not an i2i upscale that preserves the proof's composition.
+ initImagePath, initImageStrength: _initImageStrength,
+ jobId: providedJobId = null,
+}) {
if (!prompt?.trim()) {
throw new ServerError('Prompt is required', { status: 400, code: 'VALIDATION_ERROR' });
}
+ if (initImagePath) {
+ console.log(`⚠️ codex generateImage: ignoring initImagePath (gpt-image-2 $imagegen has no init-image input — falling back to full redraw)`);
+ }
await ensureDir(PATHS.images);
const jobId = providedJobId || randomUUID();
diff --git a/server/services/pipeline/comicPagesFilenameHook.js b/server/services/pipeline/comicPagesFilenameHook.js
index c3d97bf809..3645a5da1f 100644
--- a/server/services/pipeline/comicPagesFilenameHook.js
+++ b/server/services/pipeline/comicPagesFilenameHook.js
@@ -7,30 +7,92 @@
* enqueueVisualImage's owner string doesn't encode page/panel position,
* so the hook can't locate the target. Encode position into that owner
* before extending this hook to panels.
+ *
+ * `parsed.variant` ('proof' | 'final') routes the completion to the right
+ * slot. Legacy in-flight jobs (no variant in the owner) parse as 'proof'
+ * and land via the legacy-jobId fallback below.
*/
-import { parseComicPagesOwner } from './owners.js';
+import { parseComicPagesOwner, slotKeyForVariant } from './owners.js';
import { createFilenameHook } from './filenameHookFactory.js';
+import { buildRenderSlot } from './visualStages.js';
+
+// Slot record for a legacy in-flight completion (job enqueued before the
+// proof/final split). `job.params` carries the originally-requested width
+// and height; the rest of the slot shape matches what the new route writes
+// at enqueue time.
+const legacySlotRecord = (slotKey, job, filename, legacyPrompt) =>
+ buildRenderSlot({
+ slotKey,
+ jobId: job.id,
+ filename,
+ prompt: legacyPrompt,
+ width: job.params?.width,
+ height: job.params?.height,
+ });
const hook = createFilenameHook({
name: 'comicPages',
stageId: 'comicPages',
parseOwner: parseComicPagesOwner,
applyFilename: (currentStage, parsed, job, filename) => {
+ const slotKey = slotKeyForVariant(parsed.variant);
if (parsed.target === 'cover') {
- // Only stamp if THIS job is still the cover's active render — a
- // re-render that landed between enqueue and this event would
- // otherwise be overwritten with the older filename.
const cover = currentStage?.cover;
- if (!cover || cover.imageJobId !== job.id) return null;
- return { patch: { cover: { ...cover, filename } }, label: 'cover' };
+ if (!cover) return null;
+ // New shape: the route stamped { jobId, …, filename: null } into
+ // cover[slotKey] at enqueue. Only stamp the filename if THIS job is
+ // still the slot's active render — a re-render that landed between
+ // enqueue and this event would otherwise be overwritten with the
+ // older filename.
+ if (cover[slotKey]?.jobId === job.id) {
+ return {
+ patch: { cover: { ...cover, [slotKey]: { ...cover[slotKey], filename } } },
+ label: `cover.${slotKey}`,
+ };
+ }
+ // Legacy shape — pre-split job that wrote cover.imageJobId. Stamp
+ // the result into the matching new slot AND clear the legacy
+ // imageJobId/filename so the UI reads exclusively from the slot.
+ if (cover.imageJobId === job.id) {
+ return {
+ patch: {
+ cover: {
+ ...cover,
+ [slotKey]: legacySlotRecord(slotKey, job, filename, cover.prompt),
+ imageJobId: null,
+ filename: null,
+ },
+ },
+ label: `cover.${slotKey} (migrated)`,
+ };
+ }
+ return null;
}
const pages = Array.isArray(currentStage?.pages) ? currentStage.pages : [];
const page = pages[parsed.pageIndex];
- if (!page || page.imageJobId !== job.id) return null;
+ if (!page) return null;
const nextPages = [...pages];
- nextPages[parsed.pageIndex] = { ...page, filename };
- return { patch: { pages: nextPages }, label: `page${parsed.pageIndex}` };
+ if (page[slotKey]?.jobId === job.id) {
+ nextPages[parsed.pageIndex] = {
+ ...page,
+ [slotKey]: { ...page[slotKey], filename },
+ };
+ return { patch: { pages: nextPages }, label: `page${parsed.pageIndex}.${slotKey}` };
+ }
+ if (page.imageJobId === job.id) {
+ // Same migration pattern as cover, but pages have a pass-through
+ // sanitizer — divergent legacy field names would be missed here, so
+ // the clear is inlined for visibility rather than hidden in a helper.
+ nextPages[parsed.pageIndex] = {
+ ...page,
+ [slotKey]: legacySlotRecord(slotKey, job, filename, page.prompt),
+ imageJobId: null,
+ filename: null,
+ };
+ return { patch: { pages: nextPages }, label: `page${parsed.pageIndex}.${slotKey} (migrated)` };
+ }
+ return null;
},
});
diff --git a/server/services/pipeline/comicPdf.js b/server/services/pipeline/comicPdf.js
index af6856307e..bade369bf1 100644
--- a/server/services/pipeline/comicPdf.js
+++ b/server/services/pipeline/comicPdf.js
@@ -1,8 +1,9 @@
/**
* Assemble a print-ready PDF from a comic issue's rendered cover + pages.
- * Filenames come from `stages.comicPages.cover.filename` and
- * `stages.comicPages.pages[].filename`, stamped by the comic-pages filename
- * hook at media-job completion. Pages without a filename are skipped — the
+ * Filenames come from each record's proof/final slot (or legacy `filename`
+ * for records that predate the split): finalImage > proofImage > legacy
+ * filename. The comic-pages filename hook stamps each slot's filename at
+ * media-job completion. Pages without any rendered slot are skipped — the
* route surfaces "X of Y rendered" to the user before download.
*/
@@ -83,14 +84,31 @@ export async function buildComicPdf(issueId, opts = {}) {
const includeCover = opts.includeCover !== false;
const includeColophon = opts.includeColophon !== false;
+ // Read-fallback chain for each cover/page filename:
+ // 1. finalImage.filename — the hi-res print-ready render (preferred)
+ // 2. proofImage.filename — the fast layout render
+ // 3. legacy `filename` — pre-proof/final split records
+ // The user can keep iterating on the proof while the final is in flight,
+ // and the PDF will still assemble — just at whichever resolution is
+ // currently available.
+ const pickRenderedFilename = (record) => {
+ if (!record) return null;
+ return record.finalImage?.filename
+ || record.proofImage?.filename
+ || (typeof record.filename === 'string' && record.filename ? record.filename : null);
+ };
+
const comicPages = issue.stages?.comicPages || {};
const cover = includeCover ? comicPages.cover : null;
const pages = Array.isArray(comicPages.pages) ? comicPages.pages : [];
- const renderedPages = pages.filter((p) => p && typeof p.filename === 'string' && p.filename);
const targets = [];
- if (cover?.filename) targets.push(cover.filename);
- for (const p of renderedPages) targets.push(p.filename);
+ const coverFilename = pickRenderedFilename(cover);
+ if (coverFilename) targets.push(coverFilename);
+ for (const p of pages) {
+ const name = pickRenderedFilename(p);
+ if (name) targets.push(name);
+ }
if (targets.length === 0) {
throw makeErr('Issue has no rendered pages or cover yet', ERR_NO_RENDERED_PAGES);
}
diff --git a/server/services/pipeline/issues.js b/server/services/pipeline/issues.js
index 560cf8e1cb..55212cfa32 100644
--- a/server/services/pipeline/issues.js
+++ b/server/services/pipeline/issues.js
@@ -162,19 +162,60 @@ const sanitizeGenConfig = (raw) => {
const COVER_SCRIPT_MAX = 8000;
const COVER_PROMPT_MAX = 16_000;
+const RENDER_FILENAME_MAX = 500;
+
+// Proof vs final render slot — each cover/page can have one of each. Stored
+// as a structured record so the UI/PDF can pick the right resolution without
+// re-rendering, and so the i2i "use proof as base" path has a stable
+// filename to read for the final render's init image.
+//
+// `final` slots additionally carry `fromProof: boolean` so the UI can show
+// "(upscaled from proof)" provenance.
+const sanitizeRenderSlot = (raw, { isFinal = false } = {}) => {
+ if (!raw || typeof raw !== 'object') return null;
+ const jobId = isStr(raw.jobId) && raw.jobId ? raw.jobId : null;
+ const filename = isStr(raw.filename) && raw.filename
+ ? raw.filename.slice(0, RENDER_FILENAME_MAX)
+ : null;
+ const prompt = trimTo(raw.prompt, COVER_PROMPT_MAX) || null;
+ const width = Number.isFinite(raw.width) ? Math.max(0, Math.floor(raw.width)) : null;
+ const height = Number.isFinite(raw.height) ? Math.max(0, Math.floor(raw.height)) : null;
+ const createdAt = isStr(raw.createdAt) ? raw.createdAt : null;
+ // Empty slot — drop it so the persisted JSON stays clean.
+ if (!jobId && !filename) return null;
+ const out = { jobId, filename, prompt, width, height, createdAt };
+ if (isFinal) out.fromProof = raw.fromProof === true;
+ return out;
+};
+
const sanitizeCover = (raw) => {
if (!raw || typeof raw !== 'object') return null;
const script = trimTo(raw.script, COVER_SCRIPT_MAX);
+ // Legacy fields — pre-proof/final split. Preserved so existing data still
+ // displays via the UI/PDF read-fallback chain (final → proof → legacy).
+ // New renders write to proofImage/finalImage; the filename hook migrates
+ // any in-flight legacy job's completion into the new slots on landing.
const imageJobId = isStr(raw.imageJobId) && raw.imageJobId ? raw.imageJobId : null;
const prompt = trimTo(raw.prompt, COVER_PROMPT_MAX);
- // `filename` is stamped by the comic-pages filename hook on image-gen
- // completion. It survives the 24h media-job archive TTL so the UI can
- // still render the cover after the job record expires.
const filename = isStr(raw.filename) && raw.filename ? raw.filename : null;
- if (!script && !imageJobId && !prompt && !filename) return null;
- return { script, imageJobId, prompt: prompt || null, filename };
+ const proofImage = sanitizeRenderSlot(raw.proofImage);
+ const finalImage = sanitizeRenderSlot(raw.finalImage, { isFinal: true });
+ if (!script && !imageJobId && !prompt && !filename && !proofImage && !finalImage) return null;
+ return {
+ script,
+ imageJobId,
+ prompt: prompt || null,
+ filename,
+ proofImage,
+ finalImage,
+ };
};
+// Page records (pages[]) are pass-through in sanitizeVisualStage's array
+// slice, so the new proofImage/finalImage fields survive there without an
+// explicit sanitizer. If pages ever gets a deep sanitizer, route slot
+// records through sanitizeRenderSlot the same way the cover does.
+
const sanitizeVisualStage = (raw, stageId = null) => {
// Visual stages keep arbitrary structured artifact lists. Sanitize the
// wrapper but pass through known shapes.
diff --git a/server/services/pipeline/owners.js b/server/services/pipeline/owners.js
index ac1ffeb3fc..bb8fd3b1c7 100644
--- a/server/services/pipeline/owners.js
+++ b/server/services/pipeline/owners.js
@@ -10,23 +10,40 @@
const PREFIX = 'pipeline';
-export function buildComicPagesOwner({ issueId, target, pageIndex }) {
- if (target === 'cover') return `${PREFIX}:${issueId}:comicPages:cover`;
- if (target === 'page') return `${PREFIX}:${issueId}:comicPages:page${pageIndex}`;
+// Comic-pages owners encode (issue, target, variant). `variant` distinguishes
+// the proof render from the high-resolution final; legacy owners without a
+// variant suffix parse as proof so in-flight jobs at upgrade time still land.
+export const COMIC_PAGE_VARIANTS = /** @type {const} */ (['proof', 'final']);
+
+// Single source of truth for variant → slot-key. Used by the routes (writing
+// the in-flight job's slot), the filename hook (stamping the completed
+// filename), and the UI to pick which slot to read.
+export const slotKeyForVariant = (variant) =>
+ (variant === 'final' ? 'finalImage' : 'proofImage');
+
+export function buildComicPagesOwner({ issueId, target, pageIndex, variant = 'proof' }) {
+ if (!COMIC_PAGE_VARIANTS.includes(variant)) {
+ throw new Error(`buildComicPagesOwner: unknown variant "${variant}"`);
+ }
+ if (target === 'cover') return `${PREFIX}:${issueId}:comicPages:cover:${variant}`;
+ if (target === 'page') return `${PREFIX}:${issueId}:comicPages:page${pageIndex}:${variant}`;
throw new Error(`buildComicPagesOwner: unknown target "${target}"`);
}
-const COMIC_PAGES_RE = /^pipeline:([^:]+):comicPages:(cover|page(\d+))$/;
+// Suffix `(:proof|:final)?` is optional so legacy owners still parse. New
+// jobs always include the variant; old jobs default to 'proof' below.
+const COMIC_PAGES_RE = /^pipeline:([^:]+):comicPages:(cover|page(\d+))(?::(proof|final))?$/;
export function parseComicPagesOwner(owner) {
if (typeof owner !== 'string') return null;
const m = owner.match(COMIC_PAGES_RE);
if (!m) return null;
- const [, issueId, kind, pageIdxStr] = m;
- if (kind === 'cover') return { issueId, target: 'cover' };
+ const [, issueId, kind, pageIdxStr, variantMatch] = m;
+ const variant = variantMatch || 'proof';
+ if (kind === 'cover') return { issueId, target: 'cover', variant };
const pageIndex = Number(pageIdxStr);
if (!Number.isInteger(pageIndex) || pageIndex < 0) return null;
- return { issueId, target: 'page', pageIndex };
+ return { issueId, target: 'page', pageIndex, variant };
}
// Per-shot start-frame renders inside the storyboards stage. Scene-level
diff --git a/server/services/pipeline/owners.test.js b/server/services/pipeline/owners.test.js
index 8aea4fb64d..b974197c0f 100644
--- a/server/services/pipeline/owners.test.js
+++ b/server/services/pipeline/owners.test.js
@@ -5,20 +5,40 @@ import {
} from './owners.js';
describe('pipeline owner strings', () => {
- it('round-trips a cover owner', () => {
- const owner = buildComicPagesOwner({ issueId: 'iss-abc', target: 'cover' });
- expect(owner).toBe('pipeline:iss-abc:comicPages:cover');
- expect(parseComicPagesOwner(owner)).toEqual({ issueId: 'iss-abc', target: 'cover' });
+ it('round-trips a cover proof owner', () => {
+ const owner = buildComicPagesOwner({ issueId: 'iss-abc', target: 'cover', variant: 'proof' });
+ expect(owner).toBe('pipeline:iss-abc:comicPages:cover:proof');
+ expect(parseComicPagesOwner(owner)).toEqual({ issueId: 'iss-abc', target: 'cover', variant: 'proof' });
});
- it('round-trips a page owner', () => {
+ it('round-trips a cover final owner', () => {
+ const owner = buildComicPagesOwner({ issueId: 'iss-abc', target: 'cover', variant: 'final' });
+ expect(owner).toBe('pipeline:iss-abc:comicPages:cover:final');
+ expect(parseComicPagesOwner(owner)).toEqual({ issueId: 'iss-abc', target: 'cover', variant: 'final' });
+ });
+
+ it('round-trips a page owner — default variant is proof', () => {
const owner = buildComicPagesOwner({ issueId: 'iss-xyz', target: 'page', pageIndex: 7 });
- expect(owner).toBe('pipeline:iss-xyz:comicPages:page7');
- expect(parseComicPagesOwner(owner)).toEqual({ issueId: 'iss-xyz', target: 'page', pageIndex: 7 });
+ expect(owner).toBe('pipeline:iss-xyz:comicPages:page7:proof');
+ expect(parseComicPagesOwner(owner)).toEqual({ issueId: 'iss-xyz', target: 'page', pageIndex: 7, variant: 'proof' });
+ });
+
+ it('round-trips a page final owner', () => {
+ const owner = buildComicPagesOwner({ issueId: 'iss-xyz', target: 'page', pageIndex: 2, variant: 'final' });
+ expect(owner).toBe('pipeline:iss-xyz:comicPages:page2:final');
+ expect(parseComicPagesOwner(owner)).toEqual({ issueId: 'iss-xyz', target: 'page', pageIndex: 2, variant: 'final' });
+ });
+
+ it('legacy owners without a variant suffix default to proof on parse', () => {
+ expect(parseComicPagesOwner('pipeline:iss-old:comicPages:cover'))
+ .toEqual({ issueId: 'iss-old', target: 'cover', variant: 'proof' });
+ expect(parseComicPagesOwner('pipeline:iss-old:comicPages:page3'))
+ .toEqual({ issueId: 'iss-old', target: 'page', pageIndex: 3, variant: 'proof' });
});
- it('builder throws on unknown target', () => {
+ it('builder throws on unknown target or variant', () => {
expect(() => buildComicPagesOwner({ issueId: 'iss-1', target: 'panel' })).toThrow();
+ expect(() => buildComicPagesOwner({ issueId: 'iss-1', target: 'cover', variant: 'sketch' })).toThrow();
});
it('parser returns null for unmatched strings', () => {
@@ -27,6 +47,7 @@ describe('pipeline owner strings', () => {
expect(parseComicPagesOwner('not-a-pipeline-owner')).toBeNull();
expect(parseComicPagesOwner('pipeline:iss:storyboards:scene0')).toBeNull();
expect(parseComicPagesOwner('pipeline:iss:comicPages:pageNaN')).toBeNull();
+ expect(parseComicPagesOwner('pipeline:iss:comicPages:cover:sketch')).toBeNull();
});
it('round-trips a storyboards shot owner', () => {
diff --git a/server/services/pipeline/visualStages.js b/server/services/pipeline/visualStages.js
index 19e35262ad..556e5811c0 100644
--- a/server/services/pipeline/visualStages.js
+++ b/server/services/pipeline/visualStages.js
@@ -23,10 +23,12 @@
* path drives the Creative Director scene runner end-to-end.
*/
+import { basename, join, resolve as resolvePath, sep as PATH_SEP } from 'node:path';
import { enqueueJob } from '../mediaJobQueue/index.js';
import { getSettings } from '../settings.js';
import { getSeries } from './series.js';
import { getIssue, updateStage, VISUAL_STAGE_IDS } from './issues.js';
+import { PATHS } from '../../lib/fileUtils.js';
import { buildComicPagesOwner, buildStoryboardsShotOwner } from './owners.js';
import { getUniverse } from '../universeBuilder.js';
import { ServerError } from '../../lib/errorHandler.js';
@@ -81,6 +83,55 @@ const resolveMode = (options, settings) => {
return 'local';
};
+// Defensive fallback — an unrecognized value must never land in the final
+// slot, even if a future client bypasses the route schema.
+const resolveVariant = (target) => (target === 'final' ? 'final' : 'proof');
+
+// Shape for a fresh in-flight render slot — used by both route handlers
+// (cover + page) and the filename hook's legacy-migration path. `filename`
+// starts null; the comic-pages filename hook stamps it on job completion.
+// `fromProof` is omitted for the proof slot and required for the final slot.
+export const buildRenderSlot = ({ slotKey, jobId, prompt, width, height, fromProof = false, filename = null }) => ({
+ jobId,
+ filename,
+ prompt: prompt || null,
+ width: width ?? null,
+ height: height ?? null,
+ createdAt: new Date().toISOString(),
+ ...(slotKey === 'finalImage' ? { fromProof } : {}),
+});
+
+// Default denoise strength for the "use proof as base" upscale path. Low
+// enough to preserve composition (panel layout, character placement),
+// high enough to let the model add the extra detail the larger canvas
+// affords. Tweakable per-call via options.initImageStrength.
+const PROOF_AS_BASE_DEFAULT_STRENGTH = 0.25;
+
+// Resolve a stored proof filename (e.g. "abc123.png") to an absolute path
+// under PATHS.images, enforcing the gallery prefix. Skips existsSync — the
+// downstream image-gen runner reads the path and will surface a clear error
+// if the file vanished between enqueue and exec; an existsSync here would
+// add a TOCTOU race for no real benefit.
+const resolveProofInitImage = (proofImage, label) => {
+ const name = proofImage?.filename;
+ if (typeof name !== 'string' || !name) {
+ throw new ServerError(
+ `Cannot use proof as base for ${label}: no proof render available yet — render the proof first.`,
+ { status: 400, code: 'PIPELINE_COMIC_PROOF_MISSING' },
+ );
+ }
+ const candidate = join(PATHS.images, basename(name));
+ const imagesRoot = resolvePath(PATHS.images) + PATH_SEP;
+ const resolved = resolvePath(candidate);
+ if (!resolved.startsWith(imagesRoot)) {
+ throw new ServerError(
+ `Proof image path escaped the gallery for ${label}: ${name}`,
+ { status: 400, code: 'PIPELINE_COMIC_PROOF_NOT_FOUND' },
+ );
+ }
+ return resolved;
+};
+
const loadBibleContext = async (issueId) => {
const issueChain = (async () => {
const issue = await getIssue(issueId);
@@ -115,6 +166,13 @@ const enqueueImageJob = ({ prompt, world, settings, options, mode, owner, logLin
cfgScale: options.cfgScale,
// Honored by local mflux + diffusers runners; codex picks its own.
...(Number.isFinite(options.seed) ? { seed: options.seed } : {}),
+ // i2i upscale path: when the caller passes an init image (e.g.
+ // "use proof as base" for a final render) we forward it to the local
+ // image-gen runner. Codex silently ignores both fields — its
+ // `$imagegen` skill has no init-image input — so a codex-backend
+ // final render with useProofAsBase=true degrades to a full redraw.
+ ...(options.initImagePath ? { initImagePath: options.initImagePath } : {}),
+ ...(Number.isFinite(options.initImageStrength) ? { initImageStrength: options.initImageStrength } : {}),
};
const params = mode === 'codex'
? { mode: 'codex', codexPath: settings.imageGen?.codex?.codexPath, model: settings.imageGen?.codex?.model, ...baseParams }
@@ -227,10 +285,16 @@ export function composeComicCoverPrompt({
* Enqueue a comic-issue front-cover image render. Builds a cover-art
* prompt (series masthead + issue-number tag + user's cover concept) and
* hands it to the image-gen queue. Caller records the returned jobId on
- * `stages.comicPages.cover.imageJobId`.
+ * the appropriate variant slot (cover.proofImage / cover.finalImage)
+ * based on `options.target` ('proof' | 'final', default 'proof').
*
- * Returns the resolved coverScript alongside { jobId, mode, prompt } so
- * the route can persist it without a second read of the issue file.
+ * When `options.useProofAsBase` is set and target='final', resolves the
+ * existing proof image to an absolute path under PATHS.images and passes
+ * it through as `initImagePath` so the local i2i runner can preserve
+ * the proof's composition while rendering at the larger size.
+ *
+ * Returns { jobId, mode, prompt, coverScript, variant, fromProof } so the
+ * route can construct the slot record without re-reading the issue file.
*/
export async function enqueueComicCover(issueId, options = {}) {
const { issue, settings, series, world } = await loadBibleContext(issueId);
@@ -239,16 +303,25 @@ export async function enqueueComicCover(issueId, options = {}) {
? options.coverScript
: (cover?.script || '');
const mode = resolveMode(options, settings);
+ const variant = resolveVariant(options.target);
+ const fromProof = variant === 'final' && options.useProofAsBase === true;
+ const initImagePath = fromProof
+ ? resolveProofInitImage(cover?.proofImage, 'cover')
+ : null;
+ const initImageStrength = fromProof
+ ? (Number.isFinite(options.initImageStrength) ? options.initImageStrength : PROOF_AS_BASE_DEFAULT_STRENGTH)
+ : undefined;
const prompt = composeComicCoverPrompt({
series, world, issue, coverScript,
extraStyle: composeExtraStyle(series, issue, 'comicPages', options.extraStyle),
});
const jobId = enqueueImageJob({
- prompt, world, settings, options, mode,
- owner: buildComicPagesOwner({ issueId, target: 'cover' }),
- logLine: `🎨 Pipeline comic cover — issue=${issueId.slice(0, 8)} number=${issue.number || 1}`,
+ prompt, world, settings, mode,
+ options: { ...options, initImagePath, initImageStrength },
+ owner: buildComicPagesOwner({ issueId, target: 'cover', variant }),
+ logLine: `🎨 Pipeline comic cover — issue=${issueId.slice(0, 8)} number=${issue.number || 1} variant=${variant}${fromProof ? ' (from proof)' : ''}`,
});
- return { jobId, mode, prompt, coverScript };
+ return { jobId, mode, prompt, coverScript, variant, fromProof };
}
export function composeComicPagePrompt({
@@ -339,10 +412,15 @@ export function composeComicPagePrompt({
/**
* Enqueue a full-comic-page image render. Builds a structured page-level
* prompt from `issue.stages.comicPages.pages[pageIndex].panels[]` and hands
- * it to the image-gen queue. Caller records the returned jobId on
- * `pages[pageIndex].imageJobId`.
+ * it to the image-gen queue. Caller records the returned jobId on the
+ * appropriate variant slot (`pages[pageIndex].proofImage` /
+ * `pages[pageIndex].finalImage`) based on `options.target`.
+ *
+ * When `options.useProofAsBase` is set and target='final', resolves the
+ * page's existing proof image and passes it as initImagePath so the local
+ * i2i runner can preserve panel layout while upscaling.
*
- * Returns { jobId, mode, prompt, pageIndex }.
+ * Returns { jobId, mode, prompt, pageIndex, variant, fromProof }.
*/
export async function enqueueVisualComicPage(issueId, options = {}) {
const pageIndex = Number(options.pageIndex);
@@ -366,6 +444,14 @@ export async function enqueueVisualComicPage(issueId, options = {}) {
}
const mode = resolveMode(options, settings);
+ const variant = resolveVariant(options.target);
+ const fromProof = variant === 'final' && options.useProofAsBase === true;
+ const initImagePath = fromProof
+ ? resolveProofInitImage(page.proofImage, `page ${pageIndex + 1}`)
+ : null;
+ const initImageStrength = fromProof
+ ? (Number.isFinite(options.initImageStrength) ? options.initImageStrength : PROOF_AS_BASE_DEFAULT_STRENGTH)
+ : undefined;
// Build a free-text haystack from every panel's prose (description +
// caption + sfx). Dialogue lines feed character matching via CAPS names
@@ -409,11 +495,12 @@ export async function enqueueVisualComicPage(issueId, options = {}) {
});
const jobId = enqueueImageJob({
- prompt, world, settings, options, mode,
- owner: buildComicPagesOwner({ issueId, target: 'page', pageIndex }),
- logLine: `📄 Pipeline comic page — issue=${issueId.slice(0, 8)} page=${pageIndex + 1} panels=${page.panels.length}`,
+ prompt, world, settings, mode,
+ options: { ...options, initImagePath, initImageStrength },
+ owner: buildComicPagesOwner({ issueId, target: 'page', pageIndex, variant }),
+ logLine: `📄 Pipeline comic page — issue=${issueId.slice(0, 8)} page=${pageIndex + 1} panels=${page.panels.length} variant=${variant}${fromProof ? ' (from proof)' : ''}`,
});
- return { jobId, mode, prompt, pageIndex };
+ return { jobId, mode, prompt, pageIndex, variant, fromProof };
}
/**
diff --git a/server/services/pipeline/visualStages.test.js b/server/services/pipeline/visualStages.test.js
index ff393bbc02..76364b5c9c 100644
--- a/server/services/pipeline/visualStages.test.js
+++ b/server/services/pipeline/visualStages.test.js
@@ -509,7 +509,7 @@ describe('enqueueComicCover', () => {
expect(result.prompt).toMatch(/issue-number tag reading "#5"/);
expect(enqueueJobMock).toHaveBeenCalledWith(expect.objectContaining({
kind: 'image',
- owner: 'pipeline:iss-test:comicPages:cover',
+ owner: 'pipeline:iss-test:comicPages:cover:proof',
params: expect.objectContaining({
pythonPath: '/usr/bin/python3',
prompt: expect.stringContaining('Cover concept:'),