Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat([issue-1534]): AI prompt-refine + image-to-image re-render for comic pages
[._.]/ Adam Eivy8d01e2133ef6
diff --git a/client/src/components/pipeline/stages/ComicScriptStage.jsx b/client/src/components/pipeline/stages/ComicScriptStage.jsxindex e8756f8ba8..b2e36c9134 100644--- a/client/src/components/pipeline/stages/ComicScriptStage.jsx+++ b/client/src/components/pipeline/stages/ComicScriptStage.jsx@@ -19,6 +19,7 @@ import {generatePipelineComicBackCover,generatePipelineComicCoverConcepts,updatePipelineComicPage,+ refinePipelineComicPageRender,updatePipelineIssue,PIPELINE_STAGE_LABELS,PIPELINE_STAGE_STATUS_LABEL as STATUS_LABEL,@@ -803,6 +804,12 @@ function PageRow({const [renderingProof, setRenderingProof] = useState(false);const [renderingFinal, setRenderingFinal] = useState(false);const [useProofForFinal, setUseProofForFinal] = useState(true);+ // Per-page "Refine" (#1534): a free-text small correction that adjusts the+ // page's stored render prompt and re-renders image-to-image from the existing+ // page image. `refineChanges` surfaces the AI's "what changed" bullets inline.+ const [refineText, setRefineText] = useState('');+ const [refining, setRefining] = useState(false);+ const [refineChanges, setRefineChanges] = useState([]);// Consistency reference: re-render this page using an adjacent page's image as// a reference so a continuing scene keeps incidental/un-described characters +// environment consistent. '' = none, 'prior' = previous page, 'next' = next.@@ -870,9 +877,34 @@ function PageRow({}};+ const handleRefine = async () => {+ const instruction = refineText.trim();+ if (!instruction) return;+ setRefining(true);+ // Refine reads the stored render prompt + existing image server-side, so it+ // is independent of unsaved script edits — but gate on in-flight renders so+ // the i2i base isn't a half-written slot.+ const res = await refinePipelineComicPageRender(issue.id, pageIndex, {+ ...renderOpts,+ instruction,+ }).catch((err) => { toast.error(err.message || 'Refine failed'); return null; });+ setRefining(false);+ if (res) {+ onStageUpdate?.('comicPages', res.stage);+ setRefineChanges(res.changes || []);+ setRefineText('');+ toast.success(`Page ${pageIndex + 1} ${res.variant} refine queued (${res.mode || renderOpts.mode || IMAGE_GEN_MODE.LOCAL})`);+ }+ };+// A selected reference render uses the adjacent page (not this page's proof)// as its base, so it doesn't need a proof to exist — only proof-as-base does.const finalNeedsProof = useProofForFinal && !refPage && !proofSlot?.filename;+ // The Refine control only makes sense once the page has a rendered image to+ // correct (final preferred, else proof). Block it while a render is in flight+ // so we don't i2i off a slot that's mid-write.+ const hasRender = !!(finalSlot?.filename || proofSlot?.filename);+ const refineDisabled = refining || proofInFlight || finalInFlight || !refineText.trim();return (<li className="rounded-lg border border-port-border bg-port-card/40">@@ -986,6 +1018,44 @@ function PageRow({</ul></div>) : null}+ {hasRender ? (+ <div className="px-3 pt-2">+ <div className="flex items-center gap-2">+ <Wand2 size={12} className="text-port-accent shrink-0" />+ <input+ type="text"+ value={refineText}+ onChange={(e) => setRefineText(e.target.value)}+ onKeyDown={(e) => {+ if (e.key === 'Enter' && !refineDisabled) { e.preventDefault(); handleRefine(); }+ }}+ placeholder="Small fix to the rendered page — e.g. 'warm the lighting', 'remove the extra signage text'"+ aria-label={`Refine instruction for page ${pageIndex + 1}`}+ className="flex-1 px-2 py-1 bg-port-bg border border-port-border rounded text-white text-xs"+ maxLength={2000}+ />+ <button+ type="button"+ onClick={handleRefine}+ disabled={refineDisabled}+ className="inline-flex items-center gap-1 px-2 py-1 rounded text-xs bg-port-card border border-port-border text-port-accent hover:text-white hover:border-port-accent/50 disabled:opacity-40 disabled:cursor-not-allowed"+ title={(proofInFlight || finalInFlight)+ ? 'Wait for the in-flight render to finish'+ : 'Adjust the render prompt and re-render image-to-image from the existing page image — applies only the requested change, preserving the rest of the page'}+ >+ {refining ? <Loader2 size={12} className="animate-spin" /> : <Wand2 size={12} />}+ Refine+ </button>+ </div>+ {refineChanges.length ? (+ <ul className="mt-1 pl-6 space-y-0.5 list-disc">+ {refineChanges.map((c, i) => (+ <li key={i} className="text-[11px] text-gray-400">{c}</li>+ ))}+ </ul>+ ) : null}+ </div>+ ) : null}<div className="grid md:grid-cols-2 gap-3 p-3"><textareavalue={draft}diff --git a/client/src/services/apiPipeline.js b/client/src/services/apiPipeline.jsindex efb97175d3..bd6f458881 100644--- a/client/src/services/apiPipeline.js+++ b/client/src/services/apiPipeline.js@@ -221,6 +221,20 @@ export const generatePipelineComicPage = (issueId, pageIndex, opts = {}) =>body: JSON.stringify(opts),});+// AI prompt-refine + image-to-image re-render for a small correction to an+// already-rendered comic page (issue #1534). `opts.instruction` is the user's+// free-text change; the server adjusts the page's stored render prompt and+// re-renders i2i from the page's existing image, persisting the new jobId ++// adjusted prompt on the matching variant slot. Pass `target` ('proof'|'final')+// to force a variant; absent → server refines the final render when present,+// else the proof. Returns { jobId, mode, prompt, pageIndex, variant, changes,+// runId, providerId, issue, stage }.+export const refinePipelineComicPageRender = (issueId, pageIndex, opts = {}) =>+ request(`/pipeline/issues/${encodeURIComponent(issueId)}/stages/comicPages/pages/${encodeURIComponent(pageIndex)}/refine-render`, {+ method: 'POST',+ body: JSON.stringify(opts),+ });+// Render the issue's front cover. Pass `coverScript` to render a not-yet-// saved concept (the route persists it back to stages.comicPages.cover so// the next reload reflects what was rendered). Server folds in seriesdiff --git a/data.reference/prompts/stage-config.json b/data.reference/prompts/stage-config.jsonindex a0beea202c..987070831f 100644--- a/data.reference/prompts/stage-config.json+++ b/data.reference/prompts/stage-config.json@@ -436,6 +436,13 @@"returnsJson": true,"variables": []},+ "pipeline-comic-page-refine-render": {+ "name": "Pipeline — Comic Page Refine Render",+ "description": "Apply a small author correction to an already-rendered comic page's render prompt for an image-to-image re-render — changes only what the instruction asks and preserves the rest of the page (no redraw from the comic script).",+ "model": "default",+ "returnsJson": true,+ "variables": []+ },"universe-character-expand": {"name": "Universe — Expand Character Profile","description": "Flesh out blank fields on one universe canon character — novelist depth (motivations / likes / mannerisms / relationships) plus graphic-novelist visual fields (silhouette / palette / expressions / props / hand gestures). Preserves populated fields and stays distinct from peer characters.",diff --git a/data.reference/prompts/stages/pipeline-comic-page-refine-render.md b/data.reference/prompts/stages/pipeline-comic-page-refine-render.mdnew file mode 100644index 0000000000..a3f2402526--- /dev/null+++ b/data.reference/prompts/stages/pipeline-comic-page-refine-render.md@@ -0,0 +1,49 @@+# Pipeline — Comic Page Refine Render++You are an image-prompt editor. A full comic page has **already been rendered** from the prompt below. The author wants a **small correction** to that existing image — NOT a redraw. Apply the author's instruction to the page's current render prompt, changing **only** what the instruction calls for and leaving everything else identical.++The corrected prompt will re-render the page **image-to-image from the existing page image** at a low denoise, so the panel layout, composition, and lettering are preserved — only the requested change should move.++## Series++- **Title:** {{series.name}}+- **Tone / style:** {{series.styleNotes}}++{{> bible-deference }}++## Episode++- **Number:** {{issue.number}}+- **Title:** {{issue.title}}+- **Page:** {{pageNumber}}++## Current render prompt++```+{{currentPrompt}}+```++## Author's requested change++```+{{instruction}}+```++## Rules++- Apply **only** the requested change. Preserve every other detail of the current prompt verbatim — characters, setting, panel breakdown, dialogue / caption / SFX lettering instructions, layout, and style clauses.+- Do **not** re-imagine the page or rewrite it from scratch. This is a surgical edit to an existing prompt, not a fresh adaptation of the script.+- Do **not** drop the page-layout or balloon-lettering instructions already in the prompt — they keep the re-render consistent with the original page.+- If the instruction is ambiguous, make the smallest reasonable interpretation that changes the least.+- Keep the result a single coherent image-gen prompt the diffusion model can read top-to-bottom.++## Output++Return ONLY valid JSON. `prompt` is the **full** adjusted render prompt (the entire prompt with the change applied — not just the changed fragment).++```json+{+ "prompt": "<the full adjusted page render prompt>",+ "changes": ["<short bullet of what changed>", "..."]+}+```diff --git a/scripts/migrations/100-seed-comic-page-refine-render-stage.js b/scripts/migrations/100-seed-comic-page-refine-render-stage.jsnew file mode 100644index 0000000000..c9f92649ed--- /dev/null+++ b/scripts/migrations/100-seed-comic-page-refine-render-stage.js@@ -0,0 +1,88 @@+/**+ * Seed the `pipeline-comic-page-refine-render` stage into existing installs.+ *+ * Mirrors `091-seed-image-prompt-stages.js`: copies the `.md` template from+ * `data.reference/prompts/stages/` and merges its stage-config entry into+ * `data/prompts/stage-config.json`.+ *+ * Why this exists: the prompt ships in `data.reference/` and is wired to the+ * comic-page "Refine" action (`refineComicPageRender` in+ * `server/services/pipeline/visualStages.js`, issue #1534). Boot runs migrations+ * (server/index.js) but NOT `setup-data.js`, so an install that upgrades by+ * pulling + `pm2 restart` (rather than running `update.sh`) would never receive+ * it — `buildPrompt('pipeline-comic-page-refine-render')` then throws "Stage not+ * found" the first time the user clicks "Refine".+ *+ * First-shipment seed: copy only when the file is missing (never clobber a+ * customized install) and merge the stage-config key only when absent. No MD5+ * hashing — there is no prior shipped-via-migration baseline to upgrade from.+ * NOTE: a FUTURE edit to the `.md` must add `ACCEPTED_OLD_MD5` / `NEW_SHIPPED_MD5`+ * exports (see migration 003) so `setup-data.js`'s `buildPromptDriftTables`+ * sweep can auto-update other installs.+ */++import { access, copyFile, mkdir, readFile, writeFile, constants } from 'fs/promises';+import { dirname, join } from 'path';++const FILENAME = 'pipeline-comic-page-refine-render.md';+const STAGE_KEY = 'pipeline-comic-page-refine-render';++export default {+ async up({ rootDir }) {+ const stagesDir = join(rootDir, 'data', 'prompts', 'stages');+ await mkdir(stagesDir, { recursive: true });++ // 1) Seed the `.md` template when missing.+ const dataPath = join(stagesDir, FILENAME);+ const samplePath = join(rootDir, 'data.reference', 'prompts', 'stages', FILENAME);+ const exists = await access(dataPath, constants.F_OK).then(() => true, () => false);+ if (exists) {+ console.log(`📝 comic-page refine stage: ${FILENAME} already present`);+ } else {+ const sampleExists = await access(samplePath, constants.F_OK).then(() => true, () => false);+ if (!sampleExists) {+ console.warn(`⚠️ comic-page refine stage: sample missing for ${FILENAME} — skipping copy`);+ } else {+ try {+ await copyFile(samplePath, dataPath);+ console.log(`✅ seeded ${FILENAME}`);+ } catch (err) {+ console.warn(`⚠️ comic-page refine stage: copy failed for ${FILENAME}: ${err.message}`);+ }+ }+ }++ // 2) Merge the stage-config entry when absent.+ const installedConfigPath = join(rootDir, 'data', 'prompts', 'stage-config.json');+ const sampleConfigPath = join(rootDir, 'data.reference', 'prompts', 'stage-config.json');+ const sampleConfigExists = await access(sampleConfigPath, constants.F_OK).then(() => true, () => false);+ if (!sampleConfigExists) {+ console.warn('⚠️ comic-page refine stage: data.reference stage-config.json missing — cannot resolve entry; skipping config write');+ return;+ }+ try {+ const sample = JSON.parse(await readFile(sampleConfigPath, 'utf8'));+ const installedExists = await access(installedConfigPath, constants.F_OK).then(() => true, () => false);+ const installed = installedExists+ ? JSON.parse(await readFile(installedConfigPath, 'utf8'))+ : { stages: {} };+ installed.stages = installed.stages || {};++ if (installed.stages[STAGE_KEY]) {+ console.log(`📝 comic-page refine stage-config: ${STAGE_KEY} already present`);+ return;+ }+ if (!sample?.stages?.[STAGE_KEY]) {+ console.warn(`⚠️ comic-page refine stage: sample stage-config missing ${STAGE_KEY} — skipping`);+ return;+ }+ installed.stages[STAGE_KEY] = sample.stages[STAGE_KEY];+ await mkdir(dirname(installedConfigPath), { recursive: true });+ await writeFile(installedConfigPath, JSON.stringify(installed, null, 2) + '\n', 'utf8');+ const action = installedExists ? 'merged' : 'created';+ console.log(`📝 comic-page refine stage-config (${action}): ${STAGE_KEY} added`);+ } catch (err) {+ console.warn(`⚠️ comic-page refine stage: stage-config merge failed: ${err.message}`);+ }+ },+};diff --git a/scripts/migrations/100-seed-comic-page-refine-render-stage.test.js b/scripts/migrations/100-seed-comic-page-refine-render-stage.test.jsnew file mode 100644index 0000000000..9b353bc5a3--- /dev/null+++ b/scripts/migrations/100-seed-comic-page-refine-render-stage.test.js@@ -0,0 +1,105 @@+import { describe, it, expect, beforeEach, afterEach } from 'vitest';+import { mkdtempSync, rmSync, mkdirSync, writeFileSync, readFileSync, existsSync } from 'fs';+import { tmpdir } from 'os';+import { join, dirname } from 'path';+import { fileURLToPath } from 'url';++import migration from './100-seed-comic-page-refine-render-stage.js';++// scripts/migrations/<this> → ../.. is the repo root (matches _testHelpers.js).+const repoRoot = join(dirname(fileURLToPath(import.meta.url)), '..', '..');++// First-shipment seed migration (mirrors 091) — no MD5 bookkeeping, so the+// seed/no-clobber behavior is asserted directly here.+const FILENAME = 'pipeline-comic-page-refine-render.md';+const STAGE_KEY = 'pipeline-comic-page-refine-render';+const SHIPPED_BODY = '# Comic page refine render\n\nshipped body\n';++describe('migration 100 — seed comic-page refine-render stage', () => {+ let rootDir;+ let stagesDir;+ let refStagesDir;+ let installedConfigPath;++ const seedReference = ({ withConfig = true } = {}) => {+ writeFileSync(join(refStagesDir, FILENAME), SHIPPED_BODY);+ if (withConfig) {+ const refConfigPath = join(rootDir, 'data.reference', 'prompts', 'stage-config.json');+ writeFileSync(+ refConfigPath,+ JSON.stringify({+ stages: {+ [STAGE_KEY]: { name: STAGE_KEY, description: `${STAGE_KEY} desc`, model: 'default', returnsJson: true, variables: [] },+ },+ }, null, 2) + '\n',+ );+ }+ };++ beforeEach(() => {+ rootDir = mkdtempSync(join(tmpdir(), 'migration-100-'));+ stagesDir = join(rootDir, 'data', 'prompts', 'stages');+ refStagesDir = join(rootDir, 'data.reference', 'prompts', 'stages');+ installedConfigPath = join(rootDir, 'data', 'prompts', 'stage-config.json');+ mkdirSync(stagesDir, { recursive: true });+ mkdirSync(refStagesDir, { recursive: true });+ });++ afterEach(() => {+ rmSync(rootDir, { recursive: true, force: true });+ });++ it('seeds the .md template and merges the stage-config entry on a fresh install', async () => {+ seedReference();++ await expect(migration.up({ rootDir })).resolves.not.toThrow();++ expect(readFileSync(join(stagesDir, FILENAME), 'utf8')).toBe(SHIPPED_BODY);+ const installed = JSON.parse(readFileSync(installedConfigPath, 'utf8'));+ expect(installed.stages[STAGE_KEY]).toMatchObject({ name: STAGE_KEY, returnsJson: true });+ });++ it('is idempotent and never clobbers a customized .md or an existing stage-config entry', async () => {+ seedReference();+ const customBody = '# CUSTOMIZED — do not overwrite\n';+ writeFileSync(join(stagesDir, FILENAME), customBody);+ writeFileSync(+ installedConfigPath,+ JSON.stringify({ stages: { [STAGE_KEY]: { name: 'user-tuned', model: 'custom' } } }, null, 2) + '\n',+ );++ await migration.up({ rootDir });++ // .md untouched; config entry preserved verbatim.+ expect(readFileSync(join(stagesDir, FILENAME), 'utf8')).toBe(customBody);+ const installed = JSON.parse(readFileSync(installedConfigPath, 'utf8'));+ expect(installed.stages[STAGE_KEY]).toEqual({ name: 'user-tuned', model: 'custom' });+ });++ it('merges the stage-config entry alongside pre-existing unrelated stages', async () => {+ seedReference();+ writeFileSync(+ installedConfigPath,+ JSON.stringify({ stages: { 'some-other-stage': { name: 'other' } } }, null, 2) + '\n',+ );++ await migration.up({ rootDir });++ const installed = JSON.parse(readFileSync(installedConfigPath, 'utf8'));+ expect(installed.stages['some-other-stage']).toEqual({ name: 'other' });+ expect(installed.stages[STAGE_KEY]).toMatchObject({ name: STAGE_KEY });+ });++ it('does not throw when the data.reference sample is missing', async () => {+ await expect(migration.up({ rootDir })).resolves.not.toThrow();+ expect(existsSync(join(stagesDir, FILENAME))).toBe(false);+ });++ it('matches the live shipped stage-config key (drift catch)', () => {+ const refConfig = JSON.parse(+ readFileSync(join(repoRoot, 'data.reference', 'prompts', 'stage-config.json'), 'utf8'),+ );+ expect(refConfig.stages[STAGE_KEY], `stage-config missing ${STAGE_KEY}`).toBeTruthy();+ expect(existsSync(join(repoRoot, 'data.reference', 'prompts', 'stages', FILENAME))).toBe(true);+ });+});diff --git a/server/routes/pipeline.test.js b/server/routes/pipeline.test.jsindex 0aa79be294..aee0f5aca6 100644--- a/server/routes/pipeline.test.js+++ b/server/routes/pipeline.test.js@@ -179,6 +179,19 @@ vi.mock('../services/pipeline/visualStages.js', () => ({changes: ['mock change'],providerId: 'mock-provider',})),+ // Comic-page AI refine + i2i re-render (issue #1534). Returns the shape the+ // route lands on the matching variant slot via slotKeyForVariant ++ // buildRenderSlot — variant defaults to 'proof' unless the body forces one.+ refineComicPageRender: vi.fn(async (_issueId, opts) => ({+ jobId: `page-refine-job-${++uuidCounter}`,+ mode: 'local',+ prompt: `refined page prompt for page ${opts.pageIndex + 1}`,+ pageIndex: opts.pageIndex,+ variant: opts?.target === 'final' ? 'final' : 'proof',+ changes: ['warmed the lighting'],+ runId: 'run-mock-page-refine',+ providerId: 'mock-provider',+ })),}));// The episode-video handoff creates a CD project; stub it so the route test@@ -825,6 +838,49 @@ describe('pipeline routes', () => {expect(r.body.changes).toEqual(['mock change']);});+ it('POST /issues/:id/stages/comicPages/pages/:p/refine-render persists the refined render on the proof slot', async () => {+ const app = makeApp();+ const ser = await request(app).post('/api/pipeline/series').send({ name: 'S', universeId: 'u-test' });+ 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: '' }] }] } },+ });+ const r = await request(app)+ .post(`/api/pipeline/issues/${iss.body.id}/stages/comicPages/pages/0/refine-render`)+ .send({ instruction: 'warm the lighting' });+ expect(r.status).toBe(200);+ expect(r.body.runId).toBe('run-mock-page-refine');+ expect(r.body.changes).toEqual(['warmed the lighting']);+ // Default variant proof → lands on the proofImage slot with the adjusted prompt.+ expect(r.body.stage.pages[0].proofImage.jobId).toBe(r.body.jobId);+ expect(r.body.stage.pages[0].proofImage.prompt).toBe(r.body.prompt);+ expect(r.body.stage.pages[0].proofImage.filename).toBeNull();+ });++ it('POST /issues/:id/stages/comicPages/pages/:p/refine-render with target=final lands on the final slot', async () => {+ const app = makeApp();+ const ser = await request(app).post('/api/pipeline/series').send({ name: 'S', universeId: 'u-test' });+ 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: '' }] }] } },+ });+ const r = await request(app)+ .post(`/api/pipeline/issues/${iss.body.id}/stages/comicPages/pages/0/refine-render`)+ .send({ instruction: 'remove extra signage', target: 'final' });+ expect(r.status).toBe(200);+ expect(r.body.stage.pages[0].finalImage.jobId).toBe(r.body.jobId);+ });++ it('POST /issues/:id/stages/comicPages/pages/:p/refine-render 400s without an instruction', async () => {+ const app = makeApp();+ const ser = await request(app).post('/api/pipeline/series').send({ name: 'S', universeId: 'u-test' });+ const iss = await request(app).post(`/api/pipeline/series/${ser.body.id}/issues`).send({ title: 'I' });+ const r = await request(app)+ .post(`/api/pipeline/issues/${iss.body.id}/stages/comicPages/pages/0/refine-render`)+ .send({});+ expect(r.status).toBe(400);+ });+it('POST /issues/:id/stages/storyboards/scenes/:index/refine-prompt returns the refined scene', async () => {const app = makeApp();const ser = await request(app).post('/api/pipeline/series').send({ name: 'S', universeId: 'u-test' });diff --git a/server/routes/pipeline/issues.js b/server/routes/pipeline/issues.jsindex 4ada435316..ff1f98dd83 100644--- a/server/routes/pipeline/issues.js+++ b/server/routes/pipeline/issues.js@@ -25,6 +25,7 @@ import {enqueueStoryboardSceneVideo,enqueueStoryboardShotStartFrame,refineComicPanelPrompt,+ refineComicPageRender,refineStoryboardScenePrompt,generateComicPanelImagePrompts,generateStoryboardSceneImagePrompts,@@ -239,6 +240,34 @@ const comicPageRenderSchema = z.object({applyCharacterLoras: z.boolean().optional().default(true),}).refine(refineImagePixelCap, { message: PIXEL_CAP_MESSAGE, path: ['width'] });+// Per-page "Refine" — a small image-to-image correction to an already-rendered+// page (issue #1534). `instruction` is the user's free-text change; the LLM+// adjusts the page's stored render prompt and the page re-renders i2i from its+// own existing image. The render-tuning fields mirror comicPageRenderSchema,+// minus the compose-from-source-only `useProofAsBase` / `referencePage` /+// `applyCharacterLoras` (a from-self refine has no proof-vs-final base choice+// and no fresh character matching). `target` selects which rendered variant to+// refine; absent → server auto-picks (final when present, else proof).+const comicPageRefineSchema = z.object({+ instruction: z.string().trim().min(1).max(2000),+ providerId: z.string().trim().max(80).optional(),+ model: z.string().trim().max(200).optional(),+ target: z.enum(COMIC_PAGE_VARIANTS).optional(),+ // i2i denoise — low preserves the page, just enough to apply the change.+ initImageStrength: z.number().min(0).max(1).optional(),+ negativePrompt: z.string().trim().max(2000).optional(),+ // No `extraStyle`: the refine renders the LLM-adjusted prompt verbatim and+ // skips composeComicPagePrompt, so a style suffix would be silently dropped.+ mode: z.enum([IMAGE_GEN_MODE.LOCAL, IMAGE_GEN_MODE.CODEX]).optional(),+ modelId: z.string().trim().max(64).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(),+ seed: z.number().int().min(0).optional(),+}).refine(refineImagePixelCap, { message: PIXEL_CAP_MESSAGE, path: ['width'] });+const episodeVideoSchema = z.object({aspectRatio: z.enum(ASPECT_RATIOS).optional(),quality: z.enum(QUALITIES).optional(),@@ -828,6 +857,63 @@ router.post('/issues/:id/stages/comicPages/pages/:pageIndex/render', asyncHandleres.json({ ...result, issue: updatedIssue, stage });}));+// AI prompt-refine + image-to-image re-render for a small correction to an+// already-rendered comic page (issue #1534). The service adjusts the page's+// stored render prompt per the user's instruction and re-renders i2i from the+// page's existing image; the new jobId + adjusted prompt land on the matching+// variant slot — same persist path as /render, so a concurrent edit or sibling+// render can't be reverted by a stale snapshot.+router.post('/issues/:id/stages/comicPages/pages/:pageIndex/refine-render', asyncHandler(async (req, res) => {+ const pageIndex = Number(req.params.pageIndex);+ if (!Number.isInteger(pageIndex) || pageIndex < 0) {+ throw new ServerError('pageIndex must be a non-negative integer', {+ status: 400, code: 'PIPELINE_COMIC_PAGE_BAD_INDEX',+ });+ }+ const body = validateRequest(comicPageRefineSchema, req.body ?? {});++ // Validate the page exists up front so a bad index skips the bible load + LLM+ // refine entirely (mirrors the /render route's pre-flight). The service also+ // 404s before the LLM call — this just fails faster and more cheaply.+ const issue = await issuesSvc.getIssue(req.params.id).catch((err) => { throw mapServiceError(err); });+ const pages = Array.isArray(issue.stages?.comicPages?.pages) ? issue.stages.comicPages.pages : [];+ if (!pages[pageIndex]) {+ throw new ServerError(+ `pageIndex ${pageIndex} out of range — comicPages has ${pages.length} page${pages.length === 1 ? '' : 's'}`,+ { status: 404, code: 'PIPELINE_COMIC_PAGE_NOT_FOUND' },+ );+ }++ const result = await refineComicPageRender(req.params.id, { pageIndex, ...body })+ .catch((err) => { throw mapServiceError(err); });++ const slotKey = slotKeyForVariant(result.variant);+ const slotRecord = buildRenderSlot({+ slotKey, jobId: result.jobId, prompt: result.prompt,+ width: body.width, height: body.height,+ });+ const { issue: updatedIssue, stage } = await issuesSvc.updateStageWithLatest(+ req.params.id,+ 'comicPages',+ (currentStage) => {+ const currentPages = Array.isArray(currentStage?.pages) ? currentStage.pages : [];+ if (!currentPages[pageIndex]) {+ 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' },+ );+ }+ const nextPages = [...currentPages];+ nextPages[pageIndex] = {+ ...currentPages[pageIndex],+ [slotKey]: slotRecord,+ };+ return { status: 'edited', pages: nextPages };+ },+ ).catch((err) => { throw mapServiceError(err); });+ res.json({ ...result, issue: updatedIssue, stage });+}));+// AI-driven prompt refinement for a single comic panel. Uses// pipeline-comic-panel-image-prompt stage to elaborate the panel's existing// description into a richer image-gen prompt, then persists the result ondiff --git a/server/services/pipeline/visualStages.js b/server/services/pipeline/visualStages.jsindex c28fad719e..29f76ce67b 100644--- a/server/services/pipeline/visualStages.js+++ b/server/services/pipeline/visualStages.js@@ -192,6 +192,15 @@ const resolveProofInitImage = (proofImage, label) => {// reference as an `-i` attachment (reference mode), where strength is moot.const REFERENCE_PAGE_DEFAULT_STRENGTH = 0.8;+// Default denoise for the per-page "Refine" image-to-image correction (issue+// #1534). The page is re-rendered FROM ITS OWN existing image, so this is a+// low strength: preserve the panel layout / composition / lettering and move+// only enough pixels to honor the small requested change. Higher than+// proof-as-base's 0.25 (which merely upscales) because a refine must actually+// apply an edit; far below the reference path's 0.8 (which mostly follows a+// fresh prompt). Tweakable per-call via options.initImageStrength.+const REFINE_RENDER_DEFAULT_STRENGTH = 0.35;+// Resolve an adjacent page's rendered image to a gallery path for use as a// consistency reference. Prefers the final render, falls back to the proof.// Throws a clear 400 when that page hasn't been rendered yet.@@ -918,6 +927,116 @@ export async function enqueueVisualComicPage(issueId, options = {}) {return { jobId, mode, prompt, pageIndex, variant, fromProof, fromReference, referencePageIndex };}+/**+ * AI prompt-refine + image-to-image re-render for a SMALL correction to an+ * already-rendered comic page (issue #1534). Unlike `enqueueVisualComicPage`+ * (which composes a fresh prompt from the page's panels and re-renders from+ * source), this:+ *+ * 1. Takes the page's CURRENT render prompt (stored on the proof/final slot)+ * plus the user's free-text instruction, and asks the LLM to ADJUST that+ * prompt to reflect the instruction — never regenerating from the comic+ * script. Everything not called out by the instruction is preserved.+ * 2. Re-renders image-to-image using the page's EXISTING output image as the+ * init base at a low denoise, so the panel layout / composition / lettering+ * survive and only the requested change moves.+ *+ * The base image (and the slot the refined render lands back on) is the page's+ * final render when present, else its proof; `options.target` forces a variant.+ * This is the common "page is mostly right, needs a tweak" case where a full+ * re-render from the script would throw away everything good about the current+ * output.+ *+ * Returns { jobId, mode, prompt, pageIndex, variant, changes, runId, providerId }.+ */+export async function refineComicPageRender(issueId, options = {}) {+ const pageIndex = Number(options.pageIndex);+ if (!Number.isInteger(pageIndex) || pageIndex < 0) {+ throw new ServerError('pageIndex must be a non-negative integer', {+ status: 400, code: 'PIPELINE_COMIC_PAGE_BAD_INDEX',+ });+ }+ const instruction = (options.instruction || '').trim();+ if (!instruction) {+ throw new ServerError('instruction is required — describe the small change to apply', {+ status: 400, code: 'PIPELINE_COMIC_REFINE_NO_INSTRUCTION',+ });+ }++ const { issue, settings, series, world } = await loadBibleContext(issueId);+ assertStageUnlocked(issue, 'comicPages');+ const pages = Array.isArray(issue.stages?.comicPages?.pages) ? issue.stages.comicPages.pages : [];+ const page = pages[pageIndex];+ if (!page) {+ throw new ServerError(`page index ${pageIndex} out of range (have ${pages.length})`, {+ status: 404, code: 'PIPELINE_COMIC_PAGE_NOT_FOUND',+ });+ }++ // Resolve which rendered variant to refine: an explicit target wins; else+ // prefer the final render, falling back to the proof. The refined render+ // lands back on that SAME slot (the user is correcting that image).+ const variant = options.target+ ? resolveVariant(options.target)+ : (page.finalImage?.filename ? 'final' : 'proof');+ const baseSlot = variant === 'final' ? page.finalImage : page.proofImage;+ const baseFilename = baseSlot?.filename;+ if (!baseFilename) {+ throw new ServerError(+ `Cannot refine page ${pageIndex + 1}'s ${variant} render: it has no rendered image yet — render the page first.`,+ { status: 400, code: 'PIPELINE_COMIC_REFINE_NO_RENDER' },+ );+ }+ // The stored slot prompt is what we adjust — refusing to fall back to a+ // recomposed-from-script prompt is the whole point (a surgical edit, not a+ // redraw). A legacy slot without a persisted prompt must be re-rendered once+ // through `/render` (which stamps the prompt) before it can be refined.+ const currentPrompt = (baseSlot.prompt || '').trim();+ if (!currentPrompt) {+ throw new ServerError(+ `Cannot refine page ${pageIndex + 1}'s ${variant} render: its stored render prompt is missing — re-render the page first.`,+ { status: 400, code: 'PIPELINE_COMIC_REFINE_NO_PROMPT' },+ );+ }+ const initImagePath = resolveGalleryImage(baseFilename, { mustExist: false });+ if (!initImagePath) {+ throw new ServerError(+ `Existing page image path escaped the gallery for page ${pageIndex + 1}: ${baseFilename}`,+ { status: 400, code: 'PIPELINE_COMIC_REFINE_NOT_FOUND' },+ );+ }++ // Ask the LLM to apply the instruction to the existing prompt. resultField+ // 'prompt' + runPromptRefine's validation guarantees a non-empty string back;+ // `changes` is the short "what I changed" bullet list the UI surfaces.+ const { refined, changes, runId, providerId } = await runPromptRefine({+ templateName: 'pipeline-comic-page-refine-render',+ variables: {+ series: seriesBibleCtx(series),+ issue: issueCtx(issue),+ pageNumber: pageIndex + 1,+ currentPrompt: currentPrompt.slice(0, 16_000),+ instruction: instruction.slice(0, 2000),+ },+ options,+ source: 'pipeline-comic-page-refine-render',+ logTag: `Pipeline comic page refine — issue=${issueId.slice(0, 8)} page=${pageIndex + 1} variant=${variant}`,+ });++ const mode = resolveMode(options, settings);+ const initImageStrength = Number.isFinite(options.initImageStrength)+ ? Math.min(Math.max(options.initImageStrength, 0), 1)+ : REFINE_RENDER_DEFAULT_STRENGTH;++ const jobId = enqueueImageJob({+ prompt: refined, world, settings, mode,+ options: { ...options, initImagePath, initImageStrength },+ owner: buildComicPagesOwner({ issueId, target: 'page', pageIndex, variant }),+ logLine: `🪄 Pipeline comic page refine — issue=${issueId.slice(0, 8)} page=${pageIndex + 1} variant=${variant} strength=${initImageStrength}`,+ });+ return { jobId, mode, prompt: refined, pageIndex, variant, changes, runId, providerId };+}+/*** Validate per-scene wardrobe picks at the request boundary. The generic* visual-image route accepts `characterAppearances` ([{ characterId,diff --git a/server/services/pipeline/visualStages.test.js b/server/services/pipeline/visualStages.test.jsindex ef7f2e2ce0..f1e8ddaaf4 100644--- a/server/services/pipeline/visualStages.test.js+++ b/server/services/pipeline/visualStages.test.js@@ -91,6 +91,7 @@ const {enqueueStoryboardSceneVideo,enqueueStoryboardShotStartFrame,refineComicPanelPrompt,+ refineComicPageRender,refineStoryboardScenePrompt,generateComicPanelImagePrompts,generateStoryboardSceneImagePrompts,@@ -600,6 +601,123 @@ describe('refineComicPanelPrompt', () => {});});+describe('refineComicPageRender', () => {+ // A comicPages stage with page 0 already rendered (proof slot carries a+ // filename + stored prompt — the two things a from-self refine needs).+ const issueWithRenderedPage = (slots) => ({+ ...structuredClone(mockIssue),+ stages: {+ ...mockIssue.stages,+ comicPages: {+ pages: [{+ panels: [{ description: 'Panel 1 baseline.', dialogue: [], caption: '', sfx: '' }],+ ...slots,+ }],+ },+ },+ });++ it('rejects a non-integer pageIndex', async () => {+ await expect(refineComicPageRender('iss-test', { pageIndex: 'nope', instruction: 'x' }))+ .rejects.toThrow(/non-negative integer/);+ });++ it('rejects an empty instruction', async () => {+ await expect(refineComicPageRender('iss-test', { pageIndex: 0, instruction: ' ' }))+ .rejects.toThrow(/instruction is required/);+ });++ it('returns 404 when the page does not exist', async () => {+ await expect(refineComicPageRender('iss-test', { pageIndex: 99, instruction: 'warm the light' }))+ .rejects.toThrow(/out of range|PIPELINE_COMIC_PAGE_NOT_FOUND/);+ });++ it('rejects when the page has no rendered image to refine', async () => {+ getIssueMock.mockResolvedValueOnce(issueWithRenderedPage({}));+ await expect(refineComicPageRender('iss-test', { pageIndex: 0, instruction: 'warm the light' }))+ .rejects.toThrow(/no rendered image yet|PIPELINE_COMIC_REFINE_NO_RENDER/);+ });++ it('rejects when the rendered slot has no stored prompt to adjust', async () => {+ getIssueMock.mockResolvedValueOnce(issueWithRenderedPage({+ proofImage: { jobId: 'j1', filename: 'page0-proof.png', prompt: '' },+ }));+ await expect(refineComicPageRender('iss-test', { pageIndex: 0, instruction: 'warm the light' }))+ .rejects.toThrow(/stored render prompt is missing|PIPELINE_COMIC_REFINE_NO_PROMPT/);+ });++ it('happy path: adjusts the proof prompt and enqueues an i2i render from the existing image', async () => {+ getIssueMock.mockResolvedValueOnce(issueWithRenderedPage({+ proofImage: { jobId: 'j1', filename: 'page0-proof.png', prompt: 'original page prompt' },+ }));++ const result = await refineComicPageRender('iss-test', { pageIndex: 0, instruction: 'warm the lighting' });++ // Variant defaults to proof (no final exists); LLM-adjusted prompt + meta.+ expect(result.variant).toBe('proof');+ expect(result.prompt).toBe('refined prompt body');+ expect(result.runId).toBe('run-abc12345');+ expect(result.changes).toEqual(['tightened the framing']);++ // The refine template — NOT the from-script page compose — is run, and it+ // is fed the current prompt + the user instruction.+ expect(runStagedLLMMock).toHaveBeenCalledWith(+ 'pipeline-comic-page-refine-render',+ expect.objectContaining({ currentPrompt: 'original page prompt', instruction: 'warm the lighting', pageNumber: 1 }),+ expect.objectContaining({ returnsJson: true }),+ );++ // The render is image-to-image from the page's own image at the default+ // refine denoise.+ expect(enqueueJobMock).toHaveBeenCalledWith(expect.objectContaining({+ kind: 'image',+ params: expect.objectContaining({+ prompt: 'refined prompt body',+ initImagePath: expect.stringContaining('page0-proof.png'),+ initImageStrength: 0.35,+ }),+ }));+ });++ it('honors target=final and an explicit initImageStrength', async () => {+ getIssueMock.mockResolvedValueOnce(issueWithRenderedPage({+ proofImage: { jobId: 'j1', filename: 'page0-proof.png', prompt: 'proof prompt' },+ finalImage: { jobId: 'j2', filename: 'page0-final.png', prompt: 'final prompt' },+ }));++ const result = await refineComicPageRender('iss-test', {+ pageIndex: 0, instruction: 'remove the extra signage text', target: 'final', initImageStrength: 0.2,+ });++ expect(result.variant).toBe('final');+ expect(runStagedLLMMock).toHaveBeenCalledWith(+ 'pipeline-comic-page-refine-render',+ expect.objectContaining({ currentPrompt: 'final prompt' }),+ expect.anything(),+ );+ expect(enqueueJobMock).toHaveBeenCalledWith(expect.objectContaining({+ params: expect.objectContaining({+ initImagePath: expect.stringContaining('page0-final.png'),+ initImageStrength: 0.2,+ }),+ }));+ });++ it('auto-prefers the final render as the refine base when both slots exist', async () => {+ getIssueMock.mockResolvedValueOnce(issueWithRenderedPage({+ proofImage: { jobId: 'j1', filename: 'page0-proof.png', prompt: 'proof prompt' },+ finalImage: { jobId: 'j2', filename: 'page0-final.png', prompt: 'final prompt' },+ }));++ const result = await refineComicPageRender('iss-test', { pageIndex: 0, instruction: 'tweak' });++ expect(result.variant).toBe('final');+ expect(enqueueJobMock).toHaveBeenCalledWith(expect.objectContaining({+ params: expect.objectContaining({ initImagePath: expect.stringContaining('page0-final.png') }),+ }));+ });+});+describe('generateComicPanelImagePrompts', () => {it('reuses the panel validation (404 on a missing panel)', async () => {await expect(generateComicPanelImagePrompts('iss-test', 0, 99, { count: 2 }))