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

refactor: wrap comic page-render + refine-render as creative tools with route-level persistence (#2241)

Adam Eivybabd165bd068
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index fc2584bbe0..a2ff7e0ca9 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -116,6 +116,8 @@
- **[issue-2220] Creative render tools with route-level persistence (CDO Phase 2 slice).** The Creative Director orchestrator can now render comic-issue and volume (season) covers — `pipeline_renderComicCover`, `pipeline_renderComicBackCover`, `pipeline_renderVolumeCover`, `pipeline_renderVolumeBackCover` are registered creative tools. These render jobs need more than a bare enqueue: the media-job filename hook attaches the finished image only if the target cover slot already carries the returned `jobId`, and that slot write used to live in the route factory (`routes/pipeline/covers.js#makeCoverRenderHandler`), so wrapping the bare `enqueueComicCover`-style service in a tool would silently drop orchestrated covers. The enqueue+persist flow (build the in-flight render slot, script-gate, write it onto the record) now lives in shared service entry points — `renderComicCover` / `renderComicBackCover` (→ `stages.comicPages.{cover|backCover}` via the serialized `updateStageWithLatest` series write tail) and `renderVolumeCover` / `renderVolumeBackCover` (→ `series.seasons[].{cover|backCover}` via `updateSeasonOnSeries`) in `visualStages.js` — so the four cover-render routes and the four orchestrator tools share ONE code path. The persist keeps the script-gate semantics (absent `coverScript` preserves the persisted concept, empty string clears it) and serializes against a concurrent blur-save on the same record. Tools charge as `render` against the daily action budget. Cover render is the primary deliverable; wrapping the remaining route-persisted render actions (comic page render / refine-render) as tools stays tracked on #2220.
+- **[issue-2241] Creative comic-page render + refine-render tools with route-level persistence (CDO Phase 2 slice).** Completes the #2220 audit clause the covers slice (#2234) deferred: the Creative Director orchestrator can now render and refine full comic pages — `pipeline_renderComicPage` and `pipeline_refineComicPageRender` are registered creative tools. Like the covers, these need more than a bare enqueue — the media-job filename hook attaches the finished image only if `stages.comicPages.pages[pageIndex]`'s active variant slot already carries the returned `jobId`, and that slot write used to live in the route handler (`routes/pipeline/issues.js`), so wrapping the bare `enqueueVisualComicPage` / `refineComicPageRender` in a tool would silently drop orchestrated pages. The enqueue+persist flow now lives in shared service entry points — `renderComicPage` and `refineComicPageRender` (both persist onto `pages[pageIndex].{proofImage|finalImage}` through a shared `persistComicPageSlot` helper over the serialized `updateStageWithLatest` issue write tail) in `visualStages.js` — so the page render + refine-render routes and the two orchestrator tools share ONE code path, mirroring the `renderComicCover` / `makeCoverRenderHandler` structure exactly. The persist runs inside the write tail's compute step so a concurrent page edit or sibling render can't be reverted by a stale snapshot. Tools charge as `render` against the daily action budget. (`server/services/pipeline/visualStages.js`, `server/routes/pipeline/issues.js`, `server/services/creative/tools/pipeline.js`)
+
- **`getSettings()` now serves from an in-memory cache instead of re-reading settings.json on every call.** `getSettings()` is invoked 100+ times across the codebase (several per request), each previously doing a fresh filesystem read + JSON.parse of app-wide, rarely-changing data. It now memoizes the parsed settings, populated lazily on first read and refreshed off the `settings:updated` event that every `save()`/`updateSettings()`/`updateSettingsWith()` already emits — so app-driven writes keep the cache coherent while write paths still read fresh off disk inside their write queue for the read-merge-write, preserving write-ordering guarantees. Mirrors the existing `settings:updated`-invalidated cache in `sharing/annotationIdentity.js`. Alongside it, a few independent per-file read loops are now parallelized (`digital-twin-analysis.validateCompleteness`, editorial series-health's series+settings load) and hot page derivations memoized (`Review` grouping/sorting, `Tribe` care-queue), cutting redundant work on socket-driven re-renders.
- **Branch & PR reconciliation now runs on any managed app as a Chief-of-Staff scheduled task — not just PortOS.** The branch reconciler (finish this machine's unfinished local git work: delete fully-merged orphaned branches + their worktrees, open PRs for pushed-but-unopened work, resolve merge conflicts, drive the review loop, and auto-merge when a PR is green) used to be a PortOS-only feature with its own daily cron, `/api/branch-reconcile` route, `settings.branchReconcile` toggle, and a dedicated Settings tab — hardwired to the PortOS checkout. It is now a first-class per-app CoS task type, **`branch-reconcile`**, configured like every other improvement task (per-app enable, provider/model, cadence, cooldown, budget) under Chief of Staff → task scheduling. It runs `perpetual` (drain-until-done): each dispatch runs the deterministic, peer-safe cleanup + classification against the *app's* repo, dispatches the coordinator agent only while actionable in-flight branches remain, then parks on a daily recheck — so no agent is burned on a no-op run. A progress-signature convergence guard ensures the drain only re-dispatches when the actionable set actually *changed* since the last run (a branch advanced NEEDS_PR→IN_REVIEW→merged, or a new/removed branch): a cycle that leaves the same branches in the same states (a branch judged "not ready", a PR blocked on human review or red CI) parks instead of re-spawning an identical coordinator back-to-back. The peer-safety guarantee is unchanged (only local `refs/heads/` are ever touched; a federated peer's branch exists here only as a remote-tracking ref and is structurally invisible), and the per-behavior toggles (`cleanupMerged` / `openPr` / `resolveConflicts` / `autoMerge`) are now per-app task-metadata overrides. Off by default; enabling it on an app is the user's explicit consent to let it drive PRs on a schedule. The old dedicated scheduler, route, settings key, and Settings tab are removed; a migration (`scripts/migrations/170-branch-reconcile-to-cos-task.js`) carries a previously-enabled `branchReconcile` opt-in into the new task (cron→recheckCron, actions→per-app metadata) scoped to the PortOS app, and drops the dead settings key — so an install that had it on keeps reconciling instead of silently stopping. (`server/services/branchReconcile.js`, `server/services/cosTaskGenerator.js`, `server/services/taskSchedule.js`, `server/services/taskPromptDefaults/prompts.js`)
diff --git a/server/routes/pipeline.test.js b/server/routes/pipeline.test.js
index 273c863987..bbcb11b579 100644
--- a/server/routes/pipeline.test.js
+++ b/server/routes/pipeline.test.js
@@ -107,6 +107,48 @@ vi.mock('../services/pipeline/visualStages.js', async () => {
};
};
+ // Full-page render+persist. Enqueues then lands the in-flight slot on
+ // stages.comicPages.pages[pageIndex] through the real issue write tail (#2241)
+ // so the route tests exercise the persist end-to-end (mirrors renderComicPage).
+ const persistComicPage = async (issueId, options) => {
+ const pageIndex = options.pageIndex;
+ const variant = options?.target === 'final' ? 'final' : 'proof';
+ const jobId = `page-job-${++uuidCounter}`;
+ const prompt = `comic-page prompt for page ${pageIndex + 1}`;
+ const fromProof = variant === 'final' && options?.useProofAsBase === true;
+ const slotKey = slotKeyForVariant(variant);
+ const slotRecord = buildSlot({ slotKey, jobId, prompt, width: options?.width, height: options?.height, fromProof });
+ const { issue, stage } = await issuesSvc.updateStageWithLatest(issueId, 'comicPages', (current) => {
+ const pages = Array.isArray(current?.pages) ? current.pages : [];
+ const next = [...pages];
+ next[pageIndex] = { ...pages[pageIndex], [slotKey]: slotRecord };
+ return { status: 'edited', pages: next };
+ });
+ return { jobId, mode: 'local', prompt, pageIndex, variant, fromProof, issue, stage };
+ };
+
+ // Comic-page AI refine + i2i re-render (issue #1534) + persist (#2241). Lands
+ // the refined render on the matching variant slot via the real write tail.
+ const persistComicPageRefine = async (issueId, options) => {
+ const pageIndex = options.pageIndex;
+ const variant = options?.target === 'final' ? 'final' : 'proof';
+ const jobId = `page-refine-job-${++uuidCounter}`;
+ const prompt = `refined page prompt for page ${pageIndex + 1}`;
+ const slotKey = slotKeyForVariant(variant);
+ const slotRecord = buildSlot({ slotKey, jobId, prompt, width: options?.width, height: options?.height });
+ const { issue, stage } = await issuesSvc.updateStageWithLatest(issueId, 'comicPages', (current) => {
+ const pages = Array.isArray(current?.pages) ? current.pages : [];
+ const next = [...pages];
+ next[pageIndex] = { ...pages[pageIndex], [slotKey]: slotRecord };
+ return { status: 'edited', pages: next };
+ });
+ return {
+ jobId, mode: 'local', prompt, pageIndex, variant,
+ changes: ['warmed the lighting'], runId: 'run-mock-page-refine', providerId: 'mock-provider',
+ issue, stage,
+ };
+ };
+
const persistVolumeCover = async (seriesId, seasonId, target, scriptField, body) => {
const variant = body?.target === 'final' ? 'final' : 'proof';
const jobId = `vol-${target === 'cover' ? 'cover' : 'backcover'}-job-${++uuidCounter}`;
@@ -134,17 +176,10 @@ vi.mock('../services/pipeline/visualStages.js', async () => {
mode: 'local',
prompt: `style, ${opts.description}`,
})),
- enqueueVisualComicPage: vi.fn(async (_issueId, opts) => ({
- jobId: `page-job-${++uuidCounter}`,
- mode: 'local',
- // Match the real service contract: pageNumber is 1-based (pageIndex + 1).
- prompt: `comic-page prompt for page ${opts.pageIndex + 1}`,
- pageIndex: opts.pageIndex,
- // Forward proof/final variant + i2i flag so the route's slotKey + slot
- // record reflect the schema-validated body (target defaults to 'proof').
- variant: opts?.target === 'final' ? 'final' : 'proof',
- fromProof: opts?.target === 'final' && opts?.useProofAsBase === true,
- })),
+ // Full-page render+persist entry point (#2241) — enqueues AND lands the
+ // in-flight slot on stages.comicPages.pages[pageIndex] through the real issue
+ // write tail, driven through persistComicPage above.
+ renderComicPage: vi.fn((issueId, opts) => persistComicPage(issueId, opts)),
// Front cover render+persist. Lands the in-flight slot on
// stages.comicPages.cover through the real issue write tail (#2220).
renderComicCover: vi.fn((issueId, body) => persistComicCover(issueId, 'cover', 'coverScript', body || {})),
@@ -201,19 +236,10 @@ vi.mock('../services/pipeline/visualStages.js', async () => {
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',
- })),
+ // Comic-page AI refine + i2i re-render (issue #1534) + persist (#2241).
+ // Enqueues AND lands the refined render on the matching variant slot through
+ // the real write tail — variant defaults to 'proof' unless the body forces one.
+ refineComicPageRender: vi.fn((issueId, opts) => persistComicPageRefine(issueId, opts)),
};
});
@@ -1696,8 +1722,9 @@ describe('pipeline routes', () => {
.send({});
expect(r.status).toBe(404);
expect(r.body.code || r.body.error).toMatch(/PIPELINE_COMIC_PAGE_NOT_FOUND|out of range/i);
- // Enqueue is never reached when the page doesn't exist.
- expect(visualStages.enqueueVisualComicPage).not.toHaveBeenCalled();
+ // The render+persist service is never reached when the page doesn't exist
+ // (the route pre-validates the page index before dispatching).
+ expect(visualStages.renderComicPage).not.toHaveBeenCalled();
});
// ---- comicPages/cover/render ----
diff --git a/server/routes/pipeline/issues.js b/server/routes/pipeline/issues.js
index 922b220a7f..8bf0388747 100644
--- a/server/routes/pipeline/issues.js
+++ b/server/routes/pipeline/issues.js
@@ -21,7 +21,7 @@ import { generateStage } from '../../services/pipeline/textStages.js';
import * as autoRunner from '../../services/pipeline/autoRunner.js';
import {
enqueueVisualImage,
- enqueueVisualComicPage,
+ renderComicPage,
enqueueStoryboardSceneVideo,
enqueueStoryboardShotStartFrame,
refineComicPanelPrompt,
@@ -29,7 +29,6 @@ import {
refineStoryboardScenePrompt,
generateComicPanelImagePrompts,
generateStoryboardSceneImagePrompts,
- buildRenderSlot,
} from '../../services/pipeline/visualStages.js';
import { IMAGE_PROMPT_CANDIDATE_MAX } from '../../services/pipeline/refineHelpers.js';
import {
@@ -38,7 +37,7 @@ import {
} from '../../services/universeCanon.js';
import { getSeriesCanon } from '../../services/pipeline/seriesCanon.js';
import { startEpisodeVideoForIssue } from '../../services/pipeline/episodeVideo.js';
-import { COMIC_PAGE_VARIANTS, slotKeyForVariant } from '../../services/pipeline/owners.js';
+import { COMIC_PAGE_VARIANTS } from '../../services/pipeline/owners.js';
import { ASPECT_RATIOS, QUALITIES } from '../../lib/creativeDirectorPresets.js';
import { IMAGE_GEN_MODE } from '../../services/imageGen/modes.js';
import { extractScenes, scenesFromBeatSheet, SOURCE_KIND } from '../../lib/sceneExtractor.js';
@@ -878,38 +877,16 @@ router.post('/issues/:id/stages/comicPages/pages/:pageIndex/render', asyncHandle
);
}
- const result = await enqueueVisualComicPage(req.params.id, { pageIndex, ...body })
+ // renderComicPage enqueues AND persists the in-flight slot onto
+ // pages[pageIndex].{proofImage|finalImage} through the serialized issue write
+ // tail (#2241) — the same shared entry point the CDO orchestrator tool calls,
+ // so an orchestrated page completes exactly like a user-driven one. The
+ // persist runs inside updateStageWithLatest's computeFn so the slot lands on
+ // the freshest persisted pages array (a concurrent page edit or sibling
+ // render can't be reverted by a stale snapshot).
+ const result = await renderComicPage(req.params.id, { pageIndex, ...body })
.catch((err) => { throw mapServiceError(err); });
-
- // 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]) {
- 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 });
+ res.json(result);
}));
// AI prompt-refine + image-to-image re-render for a small correction to an
@@ -939,34 +916,14 @@ router.post('/issues/:id/stages/comicPages/pages/:pageIndex/refine-render', asyn
);
}
+ // refineComicPageRender adjusts the page's stored render prompt (LLM),
+ // re-renders i2i from the page's existing image, AND persists the new slot on
+ // the matching variant through the serialized issue write tail (#2241) — same
+ // shared code path the CDO orchestrator tool uses. A concurrent edit or
+ // sibling render can't be reverted by a stale snapshot.
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 });
+ res.json(result);
}));
// AI-driven prompt refinement for a single comic panel. Uses
diff --git a/server/services/creative/toolRegistry.test.js b/server/services/creative/toolRegistry.test.js
index 77e70c1f9d..977f9db323 100644
--- a/server/services/creative/toolRegistry.test.js
+++ b/server/services/creative/toolRegistry.test.js
@@ -66,6 +66,8 @@ vi.mock('../pipeline/visualStages.js', () => ({
renderComicBackCover: vi.fn(async () => ({ jobId: 'bcov1', variant: 'proof' })),
renderVolumeCover: vi.fn(async () => ({ jobId: 'vcov1', variant: 'proof' })),
renderVolumeBackCover: vi.fn(async () => ({ jobId: 'vbcov1', variant: 'proof' })),
+ renderComicPage: vi.fn(async () => ({ jobId: 'pg1', variant: 'proof', pageIndex: 0 })),
+ refineComicPageRender: vi.fn(async () => ({ jobId: 'pgr1', variant: 'proof', pageIndex: 0 })),
}));
vi.mock('../mediaJobQueue/index.js', () => ({ enqueueJob: vi.fn(() => ({ jobId: 'mj1' })) }));
vi.mock('../catalogDB.js', () => ({ listIngredients: vi.fn(async () => ({ items: [] })) }));
@@ -77,7 +79,7 @@ import { getDomainBudgetStatus, recordDomainUsage } from '../domainUsage.js';
import { createSeries } from '../pipeline/series.js';
import { generateStage } from '../pipeline/textStages.js';
import { startSeriesAutopilot } from '../pipeline/seriesAutopilot.js';
-import { renderComicCover, renderVolumeCover } from '../pipeline/visualStages.js';
+import { renderComicCover, renderVolumeCover, renderComicPage, refineComicPageRender } from '../pipeline/visualStages.js';
import { enqueueJob } from '../mediaJobQueue/index.js';
import {
CREATIVE_TOOLS,
@@ -286,6 +288,35 @@ describe('budget charging', () => {
await expect(dispatchCreativeTool('pipeline_renderComicCover', {})).rejects.toBeInstanceOf(z.ZodError);
expect(renderComicCover).not.toHaveBeenCalled();
});
+
+ // #2241 — the page-render + refine-render tools wrap the shared enqueue+persist
+ // service (renderComicPage / refineComicPageRender) so an orchestrated page
+ // completes like a user-driven one; they charge as renders.
+ it('dispatches pipeline_renderComicPage through the shared render+persist service and charges one render action', async () => {
+ setMode('execute');
+ const out = await dispatchCreativeTool('pipeline_renderComicPage', { issueId: 'i1', pageIndex: 2, target: 'final' });
+ expect(out).toMatchObject({ ok: true, tool: 'pipeline_renderComicPage', longRunning: true });
+ expect(renderComicPage).toHaveBeenCalledWith('i1', { pageIndex: 2, target: 'final' });
+ expect(recordDomainUsage).toHaveBeenCalledWith('cos', { actions: 1 });
+ });
+
+ it('dispatches pipeline_refineComicPageRender with issueId split from the refine options', async () => {
+ setMode('execute');
+ await dispatchCreativeTool('pipeline_refineComicPageRender', { issueId: 'i1', pageIndex: 0, instruction: 'warm the light' });
+ expect(refineComicPageRender).toHaveBeenCalledWith('i1', { pageIndex: 0, instruction: 'warm the light' });
+ });
+
+ it('rejects a page-render tool call missing pageIndex via the Zod gate', async () => {
+ setMode('execute');
+ await expect(dispatchCreativeTool('pipeline_renderComicPage', { issueId: 'i1' })).rejects.toBeInstanceOf(z.ZodError);
+ expect(renderComicPage).not.toHaveBeenCalled();
+ });
+
+ it('rejects a refine-render tool call missing its instruction via the Zod gate', async () => {
+ setMode('execute');
+ await expect(dispatchCreativeTool('pipeline_refineComicPageRender', { issueId: 'i1', pageIndex: 0 })).rejects.toBeInstanceOf(z.ZodError);
+ expect(refineComicPageRender).not.toHaveBeenCalled();
+ });
});
describe('wrapped-service self-rejection', () => {
diff --git a/server/services/creative/tools/pipeline.js b/server/services/creative/tools/pipeline.js
index ee7ad69211..9c745e8c67 100644
--- a/server/services/creative/tools/pipeline.js
+++ b/server/services/creative/tools/pipeline.js
@@ -14,6 +14,8 @@ import {
renderComicBackCover,
renderVolumeCover,
renderVolumeBackCover,
+ renderComicPage,
+ refineComicPageRender,
} from '../../pipeline/visualStages.js';
import { COST_FREE, COST_LLM, COST_RENDER } from './shared.js';
@@ -57,6 +59,60 @@ const coverRenderParamProps = {
useProofAsBase: { type: 'boolean', description: "For target=final: upscale off this slot's existing proof (i2i)." },
};
+// Page-render options mirror the route's comicPageRenderSchema
+// (routes/pipeline/issues.js): the shared cover knobs plus a `referencePage`
+// consistency-anchor and the per-render character-LoRA opt-out. Uses the same
+// enqueue+persist service the route does (#2241), so an orchestrated page
+// completes exactly like a user-driven one.
+const pageRenderOptionsShape = {
+ ...coverRenderOptionsShape,
+ referencePage: z.union([z.enum(['prior', 'next', 'auto', 'none']), z.number().int().min(0)]).optional(),
+ applyCharacterLoras: z.boolean().optional(),
+};
+
+const pageRenderParamProps = {
+ ...coverRenderParamProps,
+ referencePage: { type: 'string', description: "Consistency reference: 'auto' (chain off the prior page within a scene), 'none' (fresh), 'prior'/'next', or a 0-based page index." },
+ applyCharacterLoras: { type: 'boolean', description: 'Auto-apply trained character LoRAs (local mode). Defaults true.' },
+};
+
+// Refine-render options mirror the route's comicPageRefineSchema — a small i2i
+// correction driven by a free-text `instruction` against the page's existing
+// render. No `extraStyle`/`useProofAsBase`/`referencePage`/`applyCharacterLoras`
+// (a from-self refine renders the LLM-adjusted prompt verbatim, has no proof-vs-
+// final base choice, and does no fresh character matching).
+const pageRefineOptionsShape = {
+ providerId: z.string().max(80).optional(),
+ model: z.string().max(200).optional(),
+ target: z.enum(['proof', 'final']).optional(),
+ initImageStrength: z.number().min(0).max(1).optional(),
+ negativePrompt: z.string().max(2000).optional(),
+ mode: z.enum(['local', 'codex']).optional(),
+ modelId: z.string().max(64).optional(),
+ width: z.number().int().positive().optional(),
+ height: z.number().int().positive().optional(),
+ steps: z.number().int().min(1).max(150).optional(),
+ cfgScale: z.number().min(0).max(30).optional(),
+ guidance: z.number().min(0).max(30).optional(),
+ seed: z.number().int().min(0).optional(),
+};
+
+const pageRefineParamProps = {
+ providerId: { type: 'string', description: 'LLM provider id for the prompt-adjust step (defaults to the active provider).' },
+ model: { type: 'string', description: 'LLM model override for the prompt-adjust step.' },
+ target: { type: 'string', enum: ['proof', 'final'], description: 'Which rendered variant to refine; absent auto-picks (final when present, else proof).' },
+ initImageStrength: { type: 'number', description: 'i2i denoise (0-1); low preserves the page, just enough to apply the change.' },
+ negativePrompt: { type: 'string', description: 'Negative prompt tokens.' },
+ mode: { type: 'string', enum: ['local', 'codex'], description: 'Image-gen mode (defaults to the configured mode).' },
+ modelId: { type: 'string', description: 'Image model id override.' },
+ width: { type: 'integer', description: 'Render width in px.' },
+ height: { type: 'integer', description: 'Render height in px.' },
+ steps: { type: 'integer', description: 'Sampler steps.' },
+ cfgScale: { type: 'number', description: 'CFG scale.' },
+ guidance: { type: 'number', description: 'Guidance scale.' },
+ seed: { type: 'integer', description: 'Deterministic seed.' },
+};
+
export const PIPELINE_TOOLS = [
{
name: 'pipeline_createSeries',
@@ -197,4 +253,39 @@ export const PIPELINE_TOOLS = [
},
execute: ({ seriesId, seasonId, ...options }) => renderVolumeBackCover(seriesId, seasonId, options),
},
+ {
+ name: 'pipeline_renderComicPage',
+ description: "Enqueue AND persist a full comic-page render (multi-panel layout in one image) for a comic issue. Long-running: returns { jobId, ... }; the finished image attaches to stages.comicPages.pages[pageIndex] via the media-job filename hook. The page-level prompt is built server-side from the page's panels[].",
+ costClass: COST_RENDER,
+ longRunning: true,
+ schema: z.object({ issueId: z.string().min(1), pageIndex: z.number().int().min(0), ...pageRenderOptionsShape }),
+ parameters: {
+ type: 'object',
+ properties: {
+ issueId: { type: 'string', description: 'Comic issue id.' },
+ pageIndex: { type: 'integer', description: '0-based index of the page to render within stages.comicPages.pages.' },
+ ...pageRenderParamProps,
+ },
+ required: ['issueId', 'pageIndex'],
+ },
+ execute: ({ issueId, ...options }) => renderComicPage(issueId, options),
+ },
+ {
+ name: 'pipeline_refineComicPageRender',
+ description: "Enqueue AND persist a SMALL image-to-image correction to an already-rendered comic page: the LLM adjusts the page's stored render prompt per `instruction` and the page re-renders i2i from its own existing image. Long-running: the finished image attaches back to the matching variant slot via the filename hook. Requires an already-rendered page (else it rejects).",
+ costClass: COST_RENDER,
+ longRunning: true,
+ schema: z.object({ issueId: z.string().min(1), pageIndex: z.number().int().min(0), instruction: z.string().min(1).max(2000), ...pageRefineOptionsShape }),
+ parameters: {
+ type: 'object',
+ properties: {
+ issueId: { type: 'string', description: 'Comic issue id.' },
+ pageIndex: { type: 'integer', description: '0-based index of the page to refine within stages.comicPages.pages.' },
+ instruction: { type: 'string', description: 'Free-text description of the small change to apply (everything else is preserved).' },
+ ...pageRefineParamProps,
+ },
+ required: ['issueId', 'pageIndex', 'instruction'],
+ },
+ execute: ({ issueId, ...options }) => refineComicPageRender(issueId, options),
+ },
];
diff --git a/server/services/pipeline/visualStages.js b/server/services/pipeline/visualStages.js
index a25a76fed8..2d8e37b244 100644
--- a/server/services/pipeline/visualStages.js
+++ b/server/services/pipeline/visualStages.js
@@ -1079,6 +1079,57 @@ export async function enqueueVisualComicPage(issueId, options = {}) {
return { jobId, mode, prompt, pageIndex, variant, fromProof, fromReference, autoReference, referencePageIndex };
}
+/**
+ * Splice an in-flight render slot onto
+ * `stages.comicPages.pages[pageIndex].{proofImage|finalImage}` through
+ * `updateStageWithLatest` (the serialized issue write tail) so a concurrent
+ * page edit or sibling render that wrote between the enqueue and this persist
+ * can't be reverted by a stale snapshot. Shared by `renderComicPage` and
+ * `refineComicPageRender` — the filename hook only attaches the completed
+ * image when the target slot already carries the returned jobId (the reason
+ * this write must live behind the shared entry points, not only in the route).
+ *
+ * Returns { issue, stage } from the write tail.
+ */
+async function persistComicPageSlot(issueId, pageIndex, { variant, jobId, prompt, width, height, fromProof }) {
+ const slotKey = slotKeyForVariant(variant);
+ const slotRecord = buildRenderSlot({ slotKey, jobId, prompt, width, height, fromProof });
+ return updateStageWithLatest(issueId, '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 };
+ });
+}
+
+/**
+ * Enqueue + persist a full comic-page render in ONE service call — the shared
+ * entry point behind both the route handler and the CDO orchestrator tool
+ * (#2241, mirroring the #2234 cover treatment). The bare `enqueueVisualComicPage`
+ * only queues the job; the filename hook attaches the completed render ONLY if
+ * `pages[pageIndex]`'s active variant slot already carries the returned jobId,
+ * and that slot write used to live in the route handler. Extracting it here
+ * means the orchestrator gets orchestrated pages instead of silently dropping
+ * them. `options` mirrors the route body (target/useProofAsBase/referencePage,
+ * width/height, mode, …).
+ *
+ * Returns the enqueue result plus the persisted { issue, stage }.
+ */
+export async function renderComicPage(issueId, options = {}) {
+ const result = await enqueueVisualComicPage(issueId, options);
+ const { issue, stage } = await persistComicPageSlot(issueId, result.pageIndex, {
+ variant: result.variant, jobId: result.jobId, prompt: result.prompt,
+ width: options.width, height: options.height, fromProof: result.fromProof,
+ });
+ return { ...result, issue, stage };
+}
+
/**
* AI prompt-refine + image-to-image re-render for a SMALL correction to an
* already-rendered comic page (issue #1534). Unlike `enqueueVisualComicPage`
@@ -1199,7 +1250,10 @@ export async function refineComicPageRender(issueId, options = {}) {
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 };
+ const { issue: persistedIssue, stage } = await persistComicPageSlot(issueId, pageIndex, {
+ variant, jobId, prompt: refined, width: options.width, height: options.height,
+ });
+ return { jobId, mode, prompt: refined, pageIndex, variant, changes, runId, providerId, issue: persistedIssue, stage };
}
/**
diff --git a/server/services/pipeline/visualStages.test.js b/server/services/pipeline/visualStages.test.js
index ad64ab1f97..2406e34175 100644
--- a/server/services/pipeline/visualStages.test.js
+++ b/server/services/pipeline/visualStages.test.js
@@ -111,6 +111,7 @@ const {
renderComicBackCover,
renderVolumeCover,
renderVolumeBackCover,
+ renderComicPage,
enqueueStoryboardSceneVideo,
enqueueStoryboardShotStartFrame,
refineComicPanelPrompt,
@@ -764,6 +765,14 @@ describe('refineComicPageRender', () => {
initImageStrength: 0.35,
}),
}));
+
+ // #2241 — the refined render slot is persisted (enqueue+persist in one call)
+ // so the filename hook can attach the completed image; the slot carries the
+ // returned jobId + adjusted prompt on the proof variant.
+ expect(updateStageWithLatestMock).toHaveBeenCalledWith('iss-test', 'comicPages', expect.any(Function));
+ expect(result.stage.pages[0].proofImage).toMatchObject({
+ jobId: 'job-fake-1234', filename: null, prompt: 'refined prompt body',
+ });
});
it('honors target=final and an explicit initImageStrength', async () => {
@@ -1226,6 +1235,48 @@ describe('renderVolumeCover / renderVolumeBackCover (enqueue + persist)', () =>
});
});
+// #2241 — the page render+persist entry point behind BOTH the route handler and
+// the CDO orchestrator tool: enqueue the job AND write the in-flight slot onto
+// pages[pageIndex] the filename hook depends on (the bare enqueueVisualComicPage
+// alone silently dropped orchestrated pages).
+describe('renderComicPage (enqueue + persist)', () => {
+ it('enqueues then persists the proof slot onto stages.comicPages.pages[0].proofImage', async () => {
+ const result = await renderComicPage('iss-test', { pageIndex: 0, width: 832, height: 1216 });
+ expect(result.jobId).toBe('job-fake-1234');
+ expect(enqueueJobMock).toHaveBeenCalledTimes(1);
+ expect(updateStageWithLatestMock).toHaveBeenCalledWith('iss-test', 'comicPages', expect.any(Function));
+ expect(result.stage.pages[0].proofImage).toMatchObject({
+ jobId: 'job-fake-1234', filename: null, width: 832, height: 1216,
+ });
+ // proof slot must NOT carry the final-only fromProof flag
+ expect(result.stage.pages[0].proofImage).not.toHaveProperty('fromProof');
+ expect(result.stage.status).toBe('edited');
+ });
+
+ it('persists onto finalImage (with fromProof) when target=final + useProofAsBase', async () => {
+ getIssueMock.mockResolvedValueOnce({
+ ...structuredClone(mockIssue),
+ stages: {
+ ...mockIssue.stages,
+ comicPages: {
+ pages: [{
+ panels: [{ description: 'Panel 1 baseline.', dialogue: [], caption: '', sfx: '' }],
+ proofImage: { filename: 'page0-proof.png' },
+ }],
+ },
+ },
+ });
+ const result = await renderComicPage('iss-test', { pageIndex: 0, target: 'final', useProofAsBase: true });
+ expect(result.variant).toBe('final');
+ expect(result.stage.pages[0].finalImage).toMatchObject({ jobId: 'job-fake-1234', fromProof: true });
+ });
+
+ it('surfaces a 404 for an out-of-range pageIndex', async () => {
+ await expect(renderComicPage('iss-test', { pageIndex: 99 }))
+ .rejects.toThrow(/out of range|PIPELINE_COMIC_PAGE_NOT_FOUND/);
+ });
+});
+
describe('refineStoryboardScenePrompt', () => {
it('rejects a non-integer sceneIndex', async () => {
await expect(refineStoryboardScenePrompt('iss-test', 'nope')).rejects.toThrow(/non-negative integer/);