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): comic-page rendering + parallel codex + character bible expansion (#216)

[._.]/ Adam Eivy450377923d51
diff --git a/client/src/components/media/MediaJobsQueue.jsx b/client/src/components/media/MediaJobsQueue.jsx
index 19e4060b21..c4a9fb7e9b 100644
--- a/client/src/components/media/MediaJobsQueue.jsx
+++ b/client/src/components/media/MediaJobsQueue.jsx
@@ -1,7 +1,7 @@
-import { useEffect, useState, useCallback } from 'react';
-import { ListOrdered, Image as ImageIcon, Film, X, RefreshCw, ChevronDown, ChevronRight, Trash2 } from 'lucide-react';
+import { useEffect, useMemo, useState, useCallback } from 'react';
+import { ListOrdered, Image as ImageIcon, Film, X, RefreshCw, ChevronDown, ChevronRight, Trash2, RotateCw, Zap, Pencil } from 'lucide-react';
import toast from '../ui/Toast';
-import { listMediaJobs, cancelMediaJob, cancelQueuedMediaJobs } from '../../services/apiMediaJobs.js';
+import { listMediaJobs, cancelMediaJob, cancelQueuedMediaJobs, deleteMediaJob, retryMediaJob, runMediaJobNow } from '../../services/apiMediaJobs.js';
const STATUS_BADGE = {
queued: 'bg-port-border text-port-text-muted',
@@ -13,14 +13,26 @@ const STATUS_BADGE = {
const KIND_ICON = { video: Film, image: ImageIcon };
+// Compact "engine / model" badge so a failed row tells the user *what* failed,
+// not just that it failed. Codex jobs carry `params.model`; local image/video
+// jobs carry `params.modelId`. Trims long HF repo paths to the tail segment.
+function modelLabel(params) {
+ if (!params) return null;
+ if (params.mode === 'codex') {
+ const m = (params.model || '').trim();
+ return m ? `codex / ${m}` : 'codex';
+ }
+ const id = (params.modelId || '').trim();
+ if (!id) return 'local';
+ const tail = id.includes('/') ? id.slice(id.lastIndexOf('/') + 1) : id;
+ return `local / ${tail}`;
+}
+
// Embeds the live render queue inline on the Image / Video gen pages so the
// user can watch in-flight jobs (and cancel them) without leaving the page.
-//
-// Props:
-// kind — 'image' | 'video' | undefined (no filter; shows both)
-// recentLimit — how many recent rows to show (default 5)
-// className — extra classes on the outer card
-export default function MediaJobsQueue({ kind, recentLimit = 5, className = '' }) {
+// Completed jobs are excluded from the recent reel — those render as preview
+// cards on the gen page already, so listing them here is duplicate noise.
+export default function MediaJobsQueue({ kind, recentLimit = 10, className = '' }) {
const [jobs, setJobs] = useState([]);
const [loading, setLoading] = useState(true);
const [showRecent, setShowRecent] = useState(false);
@@ -52,9 +64,49 @@ export default function MediaJobsQueue({ kind, recentLimit = 5, className = '' }
})
.catch((err) => toast.error(err?.message || 'Cancel failed'));
- const live = jobs.filter((j) => j.status === 'queued' || j.status === 'running');
- const recent = jobs.filter((j) => j.status !== 'queued' && j.status !== 'running').slice(0, recentLimit);
- const queuedCount = live.filter((j) => j.status === 'queued').length;
+ const { live, recent, queuedCount, failedCount } = useMemo(() => {
+ const liveJobs = [];
+ const recentJobs = [];
+ let queued = 0;
+ let failed = 0;
+ for (const j of jobs) {
+ if (j.status === 'queued' || j.status === 'running') {
+ liveJobs.push(j);
+ if (j.status === 'queued') queued += 1;
+ } else if ((j.status === 'failed' || j.status === 'canceled') && recentJobs.length < recentLimit) {
+ recentJobs.push(j);
+ if (j.status === 'failed') failed += 1;
+ }
+ }
+ return { live: liveJobs, recent: recentJobs, queuedCount: queued, failedCount: failed };
+ }, [jobs, recentLimit]);
+
+ // Accepts optional `overrides` so the inline Edit form can patch prompt /
+ // negativePrompt / model / dimensions before the re-enqueue. No overrides =
+ // same behavior as the plain Retry button.
+ const handleRetry = (id, overrides = null) => retryMediaJob(id, overrides)
+ .then(({ jobId }) => {
+ toast.success(`Re-queued as ${jobId.slice(0, 8)}${overrides ? ' (edited)' : ''}`);
+ // Optimistic: drop the original failed/canceled row immediately. The
+ // server's retry endpoint already prunes it from the archive, but the
+ // next 3s poll would otherwise leave the stale row + button visible.
+ setJobs((prev) => prev.filter((j) => j.id !== id));
+ fetchJobs();
+ })
+ .catch((err) => toast.error(err?.message || 'Retry failed'));
+
+ const handleRunNow = (id) => runMediaJobNow(id)
+ .then(() => {
+ toast.success('Started in parallel');
+ fetchJobs();
+ })
+ .catch((err) => toast.error(err?.message || 'Run-now failed'));
+
+ const handleDelete = (id) => deleteMediaJob(id)
+ .then(() => {
+ setJobs((prev) => prev.filter((j) => j.id !== id));
+ })
+ .catch((err) => toast.error(err?.message || 'Delete failed'));
const headerLabel = kind ? `${kind === 'image' ? 'Image' : 'Video'} Render Queue` : 'Render Queue';
const handleClearQueued = () => {
@@ -75,9 +127,7 @@ export default function MediaJobsQueue({ kind, recentLimit = 5, className = '' }
<div className="flex items-center gap-2 min-w-0">
<ListOrdered className="w-4 h-4 text-port-accent shrink-0" />
<h2 className="text-xs font-medium text-gray-400 uppercase tracking-wide truncate">{headerLabel}</h2>
- <span className="text-xs text-port-text-muted">
- {live.length} active{recent.length > 0 ? ` • ${recent.length} recent` : ''}
- </span>
+ <span className="text-xs text-port-text-muted">{formatCounts(live, recent, failedCount)}</span>
</div>
<div className="flex items-center gap-1 shrink-0">
{queuedCount > 0 && (
@@ -106,7 +156,7 @@ export default function MediaJobsQueue({ kind, recentLimit = 5, className = '' }
<div className="text-port-text-muted text-xs">No {kind || 'media'} renders queued.</div>
) : (
<div className="space-y-2">
- {live.map((j) => <JobRow key={j.id} job={j} onCancel={handleCancel} />)}
+ {live.map((j) => <JobRow key={j.id} job={j} onCancel={handleCancel} onRetry={handleRetry} onRunNow={handleRunNow} />)}
{recent.length > 0 && (
<button
@@ -115,19 +165,37 @@ export default function MediaJobsQueue({ kind, recentLimit = 5, className = '' }
className="flex items-center gap-1 text-xs text-gray-500 hover:text-gray-300 pt-1"
>
{showRecent ? <ChevronDown className="w-3 h-3" /> : <ChevronRight className="w-3 h-3" />}
- {showRecent ? 'Hide' : 'Show'} recent ({recent.length})
+ {showRecent ? 'Hide' : 'Show'} failed / canceled ({recent.length})
</button>
)}
- {showRecent && recent.map((j) => <JobRow key={j.id} job={j} onCancel={handleCancel} />)}
+ {showRecent && recent.map((j) => <JobRow key={j.id} job={j} onCancel={handleCancel} onRetry={handleRetry} onDelete={handleDelete} />)}
</div>
)}
</div>
);
}
-function JobRow({ job, onCancel }) {
+function formatCounts(live, recent, failedCount) {
+ const parts = [`${live.length} active`];
+ if (failedCount > 0) parts.push(`${failedCount} failed`);
+ const canceledCount = recent.length - failedCount;
+ if (canceledCount > 0) parts.push(`${canceledCount} canceled`);
+ return parts.join(' • ');
+}
+
+function JobRow({ job, onCancel, onRetry, onRunNow, onDelete }) {
const Icon = KIND_ICON[job.kind] || Film;
const canCancel = job.status === 'queued' || job.status === 'running';
+ const canRetry = (job.status === 'failed' || job.status === 'canceled') && typeof onRetry === 'function';
+ // Delete only on terminal rows — live jobs go through Cancel.
+ const canDelete = (job.status === 'failed' || job.status === 'canceled' || job.status === 'completed')
+ && typeof onDelete === 'function';
+ // Run-now is codex-only — GPU jobs serialize on the single MLX runtime.
+ const isQueuedCodex = job.status === 'queued' && job.kind === 'image' && job.params?.mode === 'codex';
+ const canRunNow = isQueuedCodex && typeof onRunNow === 'function';
+ // Inline edit form for retry-with-overrides.
+ const [editing, setEditing] = useState(false);
+ const canEdit = canRetry;
return (
<div className="bg-port-bg border border-port-border rounded p-2.5">
<div className="flex items-center justify-between gap-3">
@@ -137,6 +205,11 @@ function JobRow({ job, onCancel }) {
<div className="text-sm font-medium truncate">
<span className="font-mono">{job.id.slice(0, 8)}</span>
<span className="text-port-text-muted"> · {job.kind}</span>
+ {modelLabel(job.params) && (
+ <span className="text-port-text-muted" title={job.params.model || job.params.modelId || ''}>
+ {' · '}{modelLabel(job.params)}
+ </span>
+ )}
{job.position && job.status === 'queued' && (
<span className="text-port-text-muted"> · #{job.position} in queue</span>
)}
@@ -152,6 +225,16 @@ function JobRow({ job, onCancel }) {
{job.cancelRequested && (
<span className="text-xs text-port-warning" title="Cancellation requested — waiting for worker">cancelling…</span>
)}
+ {canRunNow && (
+ <button
+ onClick={() => onRunNow(job.id)}
+ className="flex items-center gap-1 px-2 py-1 bg-port-bg border border-port-border rounded text-xs text-gray-300 hover:text-port-warning hover:border-port-warning/50"
+ title="Run now — start in parallel with currently-running jobs (bypasses the configured codex parallel limit for this one job)"
+ >
+ <Zap className="w-3 h-3" />
+ <span>Run now</span>
+ </button>
+ )}
{canCancel && !job.cancelRequested && (
<button
onClick={() => onCancel(job.id)}
@@ -161,6 +244,36 @@ function JobRow({ job, onCancel }) {
<X className="w-3 h-3" />
</button>
)}
+ {canEdit && (
+ <button
+ onClick={() => setEditing((s) => !s)}
+ className={`flex items-center gap-1 px-2 py-1 bg-port-bg border rounded text-xs ${editing ? 'border-port-accent/60 text-port-accent' : 'border-port-border text-gray-500 hover:text-gray-300 hover:border-port-border'}`}
+ title="Edit prompt / config, then retry"
+ aria-label="Edit and retry"
+ >
+ <Pencil className="w-3 h-3" />
+ </button>
+ )}
+ {canRetry && (
+ <button
+ onClick={() => onRetry(job.id)}
+ className="flex items-center gap-1 px-2 py-1 bg-port-bg border border-port-border rounded text-xs text-gray-300 hover:text-port-accent hover:border-port-accent/50"
+ title="Re-queue this job with the same params"
+ >
+ <RotateCw className="w-3 h-3" />
+ <span>Retry</span>
+ </button>
+ )}
+ {canDelete && (
+ <button
+ onClick={() => onDelete(job.id)}
+ className="flex items-center gap-1 px-2 py-1 bg-port-bg border border-port-border rounded text-xs text-gray-500 hover:text-port-error hover:border-port-error/50"
+ title="Remove this row from the history"
+ aria-label="Delete from history"
+ >
+ <Trash2 className="w-3 h-3" />
+ </button>
+ )}
</div>
</div>
{job.status === 'failed' && job.error && (
@@ -171,6 +284,124 @@ function JobRow({ job, onCancel }) {
{job.startedAt && ` · started ${new Date(job.startedAt).toLocaleTimeString()}`}
{job.completedAt && ` · finished ${new Date(job.completedAt).toLocaleTimeString()}`}
</div>
+ {editing && (
+ <EditRetryForm
+ job={job}
+ onSubmit={(overrides) => {
+ setEditing(false);
+ onRetry(job.id, overrides);
+ }}
+ onCancel={() => setEditing(false)}
+ />
+ )}
</div>
);
}
+
+// Inline form for the Edit-and-retry flow. Shows the fields the server's
+// retry override schema accepts (prompt, negative, model, dimensions, steps)
+// and submits only the keys the user actually changed — leaving unchanged
+// fields out of the patch so the original job's values ride through.
+function EditRetryForm({ job, onSubmit, onCancel }) {
+ const p = job.params || {};
+ const isCodex = p.mode === 'codex';
+ const [prompt, setPrompt] = useState(p.prompt || '');
+ const [negativePrompt, setNegativePrompt] = useState(p.negativePrompt || '');
+ const [model, setModel] = useState(p.model || '');
+ const [modelId, setModelId] = useState(p.modelId || '');
+ const [width, setWidth] = useState(p.width ?? '');
+ const [height, setHeight] = useState(p.height ?? '');
+ const [steps, setSteps] = useState(p.steps ?? '');
+
+ const submit = (e) => {
+ e.preventDefault();
+ const overrides = {};
+ const trimEq = (a, b) => (a || '').trim() === (b || '').trim();
+ const numEq = (a, b) => (a === '' ? null : Number(a)) === (b ?? null);
+ if (!trimEq(prompt, p.prompt) && prompt.trim()) overrides.prompt = prompt.trim();
+ if (!trimEq(negativePrompt, p.negativePrompt)) overrides.negativePrompt = negativePrompt.trim();
+ if (isCodex && !trimEq(model, p.model)) overrides.model = model.trim();
+ if (!isCodex && !trimEq(modelId, p.modelId)) overrides.modelId = modelId.trim();
+ if (!numEq(width, p.width) && width !== '') overrides.width = Number(width);
+ if (!numEq(height, p.height) && height !== '') overrides.height = Number(height);
+ if (!numEq(steps, p.steps) && steps !== '') overrides.steps = Number(steps);
+ onSubmit(Object.keys(overrides).length ? overrides : null);
+ };
+
+ return (
+ <form onSubmit={submit} className="mt-3 pt-3 border-t border-port-border space-y-2">
+ <label className="block text-[10px] uppercase tracking-wide text-port-text-muted">Prompt</label>
+ <textarea
+ value={prompt}
+ onChange={(e) => setPrompt(e.target.value)}
+ rows={3}
+ className="w-full px-2 py-1.5 bg-port-bg border border-port-border rounded text-white text-xs"
+ maxLength={8000}
+ />
+ <label className="block text-[10px] uppercase tracking-wide text-port-text-muted">Negative prompt</label>
+ <textarea
+ value={negativePrompt}
+ onChange={(e) => setNegativePrompt(e.target.value)}
+ rows={2}
+ className="w-full px-2 py-1.5 bg-port-bg border border-port-border rounded text-white text-xs"
+ maxLength={8000}
+ />
+ <div className="grid grid-cols-2 sm:grid-cols-4 gap-2">
+ <div className="col-span-2">
+ <label className="block text-[10px] uppercase tracking-wide text-port-text-muted">{isCodex ? 'Codex model' : 'Model id'}</label>
+ <input
+ type="text"
+ value={isCodex ? model : modelId}
+ onChange={(e) => (isCodex ? setModel(e.target.value) : setModelId(e.target.value))}
+ placeholder={isCodex ? 'leave empty for default' : 'e.g. z-image-turbo-bf16'}
+ className="w-full px-2 py-1 bg-port-bg border border-port-border rounded text-white text-xs"
+ maxLength={200}
+ />
+ </div>
+ <div>
+ <label className="block text-[10px] uppercase tracking-wide text-port-text-muted">Width</label>
+ <input
+ type="number" min={64} max={4096} step={8}
+ value={width}
+ onChange={(e) => setWidth(e.target.value)}
+ className="w-full px-2 py-1 bg-port-bg border border-port-border rounded text-white text-xs"
+ />
+ </div>
+ <div>
+ <label className="block text-[10px] uppercase tracking-wide text-port-text-muted">Height</label>
+ <input
+ type="number" min={64} max={4096} step={8}
+ value={height}
+ onChange={(e) => setHeight(e.target.value)}
+ className="w-full px-2 py-1 bg-port-bg border border-port-border rounded text-white text-xs"
+ />
+ </div>
+ <div>
+ <label className="block text-[10px] uppercase tracking-wide text-port-text-muted">Steps</label>
+ <input
+ type="number" min={1} max={200} step={1}
+ value={steps}
+ onChange={(e) => setSteps(e.target.value)}
+ className="w-full px-2 py-1 bg-port-bg border border-port-border rounded text-white text-xs"
+ />
+ </div>
+ </div>
+ <div className="flex items-center justify-end gap-2 pt-1">
+ <button
+ type="button"
+ onClick={onCancel}
+ className="px-3 py-1 text-xs text-port-text-muted hover:text-white"
+ >
+ Cancel
+ </button>
+ <button
+ type="submit"
+ className="inline-flex items-center gap-1 px-3 py-1 bg-port-accent text-white text-xs rounded hover:bg-port-accent/90"
+ >
+ <RotateCw className="w-3 h-3" />
+ Retry with changes
+ </button>
+ </div>
+ </form>
+ );
+}
diff --git a/client/src/components/pipeline/stages/ComicPagesStage.jsx b/client/src/components/pipeline/stages/ComicPagesStage.jsx
index bcd7078ea8..7dbb629bb3 100644
--- a/client/src/components/pipeline/stages/ComicPagesStage.jsx
+++ b/client/src/components/pipeline/stages/ComicPagesStage.jsx
@@ -1,23 +1,30 @@
-/**
- * Comic Pages stage — assemble the visual side of the comic-book issue.
- *
- * MVP: structured list of pages, each with a list of panels. Each panel has
- * its own prompt + an "Enqueue image" button that hands off to the existing
- * image-gen pipeline (via /api/pipeline/issues/:id/stages/comicPages/visual).
- * Progress for each panel's image lands via the standard media-job SSE — for
- * the skeleton we just persist the jobId and show "queued"; deep progress
- * integration is deferred (see PLAN.md "Pipeline — Deferred").
- */
-
-import { useState } from 'react';
-import { Plus, Trash2, Sparkles, Loader2 } from 'lucide-react';
+import { useRef, useState } from 'react';
+import { Plus, Trash2, Sparkles, Loader2, Wand2, ImagePlus } from 'lucide-react';
import toast from '../../ui/Toast';
-import { generatePipelineVisualImage, updatePipelineIssue } from '../../../services/api';
+import { useArmedAction } from '../../../hooks/useArmedAction';
+import {
+ generatePipelineVisualImage,
+ generatePipelineComicPage,
+ updatePipelineIssue,
+ extractPipelineComicPages,
+} from '../../../services/api';
export default function ComicPagesStage({ issue, onStageUpdate }) {
const stage = issue.stages?.comicPages || { status: 'empty', pages: [] };
const [pages, setPages] = useState(stage.pages || []);
const [savingIdx, setSavingIdx] = useState(null);
+ // Per-page in-flight state. Codex can render multiple pages in parallel, so
+ // tracking a single index would flip the spinner off the wrong button when
+ // the first request finished while a second was still pending.
+ const [renderingPages, setRenderingPages] = useState(() => new Set());
+ const markRendering = (pi, on) => setRenderingPages((prev) => {
+ const next = new Set(prev);
+ if (on) next.add(pi); else next.delete(pi);
+ return next;
+ });
+ const [extracting, setExtracting] = useState(false);
+
+ const comicScriptReady = !!(issue.stages?.comicScript?.output || '').trim();
const persist = async (nextPages) => {
setPages(nextPages);
@@ -42,11 +49,69 @@ export default function ComicPagesStage({ issue, onStageUpdate }) {
: p);
persist(next);
};
+ // Ref tracks the latest pages array so onBlur's persist call doesn't read a
+ // stale render-scope value — onChange schedules a setPages, then onBlur fires
+ // synchronously in the same browser tick (before React re-renders), so without
+ // this the persisted snapshot would miss the user's last keystroke.
+ const pagesRef = useRef(pages);
+ pagesRef.current = pages;
const updatePanel = (pi, ni, patch) => {
const next = pages.map((p, i) => i === pi
? { ...p, panels: (p.panels || []).map((q, j) => j === ni ? { ...q, ...patch } : q) }
: p);
- setPages(next); // local-first; persist on blur via a dedicated save
+ pagesRef.current = next;
+ setPages(next);
+ };
+
+ const runExtract = async () => {
+ setExtracting(true);
+ const result = await extractPipelineComicPages(issue.id, { force: true }).catch((err) => {
+ toast.error(err.message || 'Page extraction failed');
+ return null;
+ });
+ setExtracting(false);
+ if (!result) return;
+ setPages(result.stage?.pages || []);
+ onStageUpdate?.('comicPages', result.stage, result.issue);
+ toast.success(`Extracted ${result.pageCount} page${result.pageCount === 1 ? '' : 's'} / ${result.panelCount} panel${result.panelCount === 1 ? '' : 's'}`);
+ };
+ const [extractArmed, fireExtract] = useArmedAction(runExtract);
+ const onExtractClick = () => {
+ // Nothing to clobber on a fresh stage — extract immediately. The two-click
+ // arm exists only to guard a destructive replace of existing pages.
+ if (pages.length === 0) {
+ runExtract();
+ return;
+ }
+ if (!extractArmed) {
+ toast.warning(`This will replace ${pages.length} existing page${pages.length === 1 ? '' : 's'}. Click again to confirm.`);
+ }
+ fireExtract();
+ };
+
+ const handleGeneratePage = async (pi) => {
+ const page = pages[pi];
+ const panelCount = page?.panels?.length || 0;
+ if (panelCount === 0) {
+ toast.error('Add at least one panel description first');
+ return;
+ }
+ markRendering(pi, true);
+ const result = await generatePipelineComicPage(issue.id, pi).catch((err) => {
+ toast.error(err.message || 'Failed to enqueue page render');
+ return null;
+ });
+ markRendering(pi, false);
+ if (!result) return;
+ if (result.issue) {
+ const next = result.issue.stages?.comicPages?.pages || [];
+ setPages(next);
+ onStageUpdate?.('comicPages', result.issue.stages.comicPages, result.issue);
+ } else {
+ const next = pages.map((p, i) => i === pi ? { ...p, imageJobId: result.jobId, prompt: result.prompt } : p);
+ setPages(next);
+ }
+ toast.success(`Queued ${result.mode} page render (${result.jobId.slice(0, 8)})`);
};
const handleGeneratePanel = async (pi, ni) => {
@@ -77,17 +142,29 @@ export default function ComicPagesStage({ issue, onStageUpdate }) {
<div>
<h2 className="text-lg font-semibold text-white">Comic Pages</h2>
<p className="text-xs text-gray-500 mt-1">
- Define pages and panels. Each panel's description becomes an image-gen prompt prefixed by the series style.
- Image progress lives in the existing media-job queue. Episode video / multi-panel composition stitching is deferred.
+ Define pages and panels. <strong className="text-gray-400">Generate page</strong> renders the entire page as one image — the recommended path for Codex / cloud image models. Per-panel renders are a fallback (smaller local models, or fine-tuning a single frame).
+ Image progress lives in the existing media-job queue.
</p>
</div>
- <button
- type="button"
- onClick={addPage}
- className="inline-flex items-center gap-2 px-3 py-2 rounded-lg bg-port-card border border-port-border text-white text-sm hover:border-port-accent/50"
- >
- <Plus size={14} /> Add page
- </button>
+ <div className="flex items-center gap-2 flex-wrap">
+ <button
+ type="button"
+ onClick={onExtractClick}
+ disabled={!comicScriptReady || extracting}
+ title={comicScriptReady ? 'Parse the comic script into pages and panels — descriptions go straight into image-gen prompts' : 'Generate the comic script first'}
+ className="inline-flex items-center gap-2 px-3 py-2 rounded-lg bg-port-card border border-port-border text-white text-sm hover:border-port-accent/50 disabled:opacity-40 disabled:cursor-not-allowed"
+ >
+ {extracting ? <Loader2 size={14} className="animate-spin" /> : <Wand2 size={14} />}
+ {extractArmed ? 'Click again to replace' : 'From comic script'}
+ </button>
+ <button
+ type="button"
+ onClick={addPage}
+ className="inline-flex items-center gap-2 px-3 py-2 rounded-lg bg-port-card border border-port-border text-white text-sm hover:border-port-accent/50"
+ >
+ <Plus size={14} /> Add page
+ </button>
+ </div>
</div>
{pages.length === 0 ? (
@@ -96,16 +173,35 @@ export default function ComicPagesStage({ issue, onStageUpdate }) {
<div className="space-y-4">
{pages.map((page, pi) => (
<div key={pi} className="p-3 bg-port-card border border-port-border rounded-lg">
- <div className="flex items-center justify-between mb-2">
+ <div className="flex items-center justify-between mb-2 gap-2 flex-wrap">
<span className="text-xs uppercase tracking-wider text-gray-500">Page {pi + 1}</span>
- <button
- type="button"
- onClick={() => removePage(pi)}
- className="text-gray-500 hover:text-port-error p-1"
- aria-label="Remove page"
- >
- <Trash2 size={14} />
- </button>
+ <div className="flex items-center gap-2">
+ <button
+ type="button"
+ onClick={() => handleGeneratePage(pi)}
+ disabled={renderingPages.has(pi) || !(page.panels?.length > 0)}
+ title="Render the entire page as one image — recommended for Codex / cloud image models. Local models will produce draft-quality results."
+ 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"
+ >
+ {renderingPages.has(pi)
+ ? <Loader2 size={12} className="animate-spin" />
+ : <ImagePlus size={12} />}
+ Generate page
+ </button>
+ {page.imageJobId ? (
+ <span className="text-[10px] text-gray-500 font-mono break-all" title="Last page render job">
+ page job {page.imageJobId.slice(0, 8)}
+ </span>
+ ) : null}
+ <button
+ type="button"
+ onClick={() => removePage(pi)}
+ className="text-gray-500 hover:text-port-error p-1"
+ aria-label="Remove page"
+ >
+ <Trash2 size={14} />
+ </button>
+ </div>
</div>
<ul className="space-y-2">
{(page.panels || []).map((panel, ni) => (
@@ -114,7 +210,7 @@ export default function ComicPagesStage({ issue, onStageUpdate }) {
<textarea
value={panel.description || ''}
onChange={(e) => updatePanel(pi, ni, { description: e.target.value })}
- onBlur={() => persist(pages)}
+ onBlur={() => persist(pagesRef.current)}
placeholder="Panel subject: wide shot, foundry crucible, dusk light, Lina silhouetted against the glow."
rows={2}
className="flex-1 px-2 py-1.5 bg-port-bg border border-port-border rounded text-white text-sm"
diff --git a/client/src/components/settings/ImageGenTab.jsx b/client/src/components/settings/ImageGenTab.jsx
index e6eced6faf..f73b08f63b 100644
--- a/client/src/components/settings/ImageGenTab.jsx
+++ b/client/src/components/settings/ImageGenTab.jsx
@@ -24,6 +24,13 @@ const CODEX_TOOL_ID = 'codex-imagegen';
const DEFAULT_TEST_PROMPT = 'a small cyberpunk fox sitting on a neon-lit rooftop at night, cinematic, highly detailed';
const normalizeUrl = (url) => (url || '').trim().replace(/\/+$/, '');
+// Fallback bounds used until /api/settings has been fetched once. The server
+// is the source of truth (returns `imageGen.codex.parallelLimitBounds` with
+// the real min/max/default), so these only matter for the first paint.
+const PARALLEL_FALLBACK = { min: 1, max: 10, default: 1 };
+const clampParallel = (n, bounds = PARALLEL_FALLBACK) =>
+ Math.max(bounds.min, Math.min(bounds.max, Math.floor(Number(n) || bounds.default)));
+
export function ImageGenTab() {
const [loading, setLoading] = useState(true);
const [saving, setSaving] = useState(false);
@@ -38,11 +45,16 @@ export function ImageGenTab() {
const [codexEnabled, setCodexEnabled] = useState(false);
const [codexPath, setCodexPath] = useState('');
const [codexModel, setCodexModel] = useState('');
+ const [codexParallelLimit, setCodexParallelLimit] = useState(1);
+ // Server-authoritative bounds for the parallel-limit input. Populated from
+ // /api/settings's `imageGen.codex.parallelLimitBounds`; falls back to local
+ // constants until the first fetch resolves.
+ const [parallelBounds, setParallelBounds] = useState(PARALLEL_FALLBACK);
// Snapshot of saved values so we can show the "dirty" state
const [saved, setSaved] = useState({
mode: 'external', sdapiUrl: '', pythonPath: '', exposeA1111: false,
- codexEnabled: false, codexPath: '', codexModel: '',
+ codexEnabled: false, codexPath: '', codexModel: '', codexParallelLimit: 1,
});
const [status, setStatus] = useState(null);
@@ -71,6 +83,11 @@ export function ImageGenTab() {
const cxEnabled = cx.enabled === true;
const cxPath = cx.codexPath || '';
const cxModel = cx.model || '';
+ const bounds = cx.parallelLimitBounds && Number.isFinite(cx.parallelLimitBounds.max)
+ ? cx.parallelLimitBounds
+ : PARALLEL_FALLBACK;
+ setParallelBounds(bounds);
+ const cxParallel = clampParallel(cx.parallelLimit, bounds);
setMode(m);
setSdapiUrl(url);
setPythonPath(py);
@@ -78,9 +95,11 @@ export function ImageGenTab() {
setCodexEnabled(cxEnabled);
setCodexPath(cxPath);
setCodexModel(cxModel);
+ setCodexParallelLimit(cxParallel);
setSaved({
mode: m, sdapiUrl: url, pythonPath: py, exposeA1111: expose,
codexEnabled: cxEnabled, codexPath: cxPath, codexModel: cxModel,
+ codexParallelLimit: cxParallel,
});
setToolRegistered(tools.some((t) => t.id === SDAPI_TOOL_ID));
setCodexToolRegistered(tools.some((t) => t.id === CODEX_TOOL_ID));
@@ -103,19 +122,21 @@ export function ImageGenTab() {
|| exposeA1111 !== saved.exposeA1111
|| codexEnabled !== saved.codexEnabled
|| codexPath !== saved.codexPath
- || codexModel !== saved.codexModel;
+ || codexModel !== saved.codexModel
+ || codexParallelLimit !== saved.codexParallelLimit;
const handleSave = async () => {
setSaving(true);
const url = normalizeUrl(sdapiUrl) || undefined;
const cxPath = codexPath?.trim() || undefined;
const cxModel = codexModel?.trim() || undefined;
+ const cxParallel = clampParallel(codexParallelLimit, parallelBounds);
const patch = {
imageGen: {
mode,
external: { sdapiUrl: url },
local: { pythonPath: pythonPath || undefined },
- codex: { enabled: codexEnabled, codexPath: cxPath, model: cxModel },
+ codex: { enabled: codexEnabled, codexPath: cxPath, model: cxModel, parallelLimit: cxParallel },
expose: { a1111: exposeA1111 },
// Keep the legacy field populated so anything still reading
// `imageGen.sdapiUrl` directly stays working.
@@ -131,7 +152,9 @@ export function ImageGenTab() {
setSaved({
mode, sdapiUrl: url || '', pythonPath, exposeA1111,
codexEnabled, codexPath: cxPath || '', codexModel: cxModel || '',
+ codexParallelLimit: cxParallel,
});
+ if (cxParallel !== codexParallelLimit) setCodexParallelLimit(cxParallel);
// Reflect the normalization back into the inputs so what the user
// sees matches what was saved.
if (cxPath !== codexPath) setCodexPath(cxPath || '');
@@ -405,6 +428,28 @@ export function ImageGenTab() {
/>
<p className="text-xs text-gray-500 mt-1">Passed as <code>codex exec -m &lt;model&gt;</code>. Leave empty to use Codex's default.</p>
</div>
+ <div>
+ <label className="block text-xs font-medium text-gray-400 mb-1">Parallel render limit</label>
+ <input
+ type="number"
+ min={parallelBounds.min}
+ max={parallelBounds.max}
+ step={1}
+ value={codexParallelLimit}
+ onChange={(e) => setCodexParallelLimit(clampParallel(e.target.value, parallelBounds))}
+ className="w-24 bg-port-bg border border-port-border rounded-lg px-3 py-2 text-sm text-white focus:outline-none focus:border-port-accent"
+ />
+ <p className="text-xs text-gray-500 mt-1">
+ How many Codex renders the queue runs in parallel. Default <code>{parallelBounds.default}</code>. Hard capped at <code>{parallelBounds.max}</code>.
+ Higher values let large batches finish faster but burn OpenAI credits non-linearly — a runaway {parallelBounds.max}-wide
+ batch can rack up real money in minutes.
+ {codexParallelLimit > Math.ceil(parallelBounds.max / 2) && (
+ <span className="block mt-1 text-port-warning">
+ ⚠️ {codexParallelLimit} concurrent renders can burn credits quickly during a long batch. Watch usage.
+ </span>
+ )}
+ </p>
+ </div>
</div>
)}
</div>
diff --git a/client/src/index.css b/client/src/index.css
index 63c39b07a0..ad27d11f98 100644
--- a/client/src/index.css
+++ b/client/src/index.css
@@ -670,6 +670,21 @@ html[data-port-theme-mode="day"] [class~="hover:text-green-400"]:hover { color:
html[data-port-theme-mode="day"] [class~="hover:text-emerald-400"]:hover { color: rgb(4 120 87) !important; }
html[data-port-theme-mode="day"] [class~="hover:text-teal-400"]:hover { color: rgb(15 118 110) !important; }
+/* hover variants of near-white utilities — without these, hover:text-white on a
+ * gray-on-light element flashes pure white-on-light and becomes unreadable
+ * (e.g. <summary>Summary</summary> in ArcCanvas). Mirrors the base remap above. */
+html[data-port-theme-mode="day"] [class~="hover:text-white"]:hover,
+html[data-port-theme-mode="day"] [class~="hover:text-zinc-50"]:hover,
+html[data-port-theme-mode="day"] [class~="hover:text-zinc-100"]:hover,
+html[data-port-theme-mode="day"] [class~="hover:text-neutral-50"]:hover,
+html[data-port-theme-mode="day"] [class~="hover:text-neutral-100"]:hover,
+html[data-port-theme-mode="day"] [class~="hover:text-gray-50"]:hover,
+html[data-port-theme-mode="day"] [class~="hover:text-gray-100"]:hover,
+html[data-port-theme-mode="day"] [class~="hover:text-slate-50"]:hover,
+html[data-port-theme-mode="day"] [class~="hover:text-slate-100"]:hover {
+ color: rgb(var(--port-text)) !important;
+}
+
/* === Lumen Glass Day === */
html[data-port-theme="lumen-glass-day"] :is(.bg-port-card, [class~="bg-port-card/50"]):is(.border, .rounded, .rounded-lg, .rounded-xl, .rounded-2xl) {
border-color: rgb(var(--port-border) / 0.22) !important;
diff --git a/client/src/pages/Pipeline.jsx b/client/src/pages/Pipeline.jsx
index f83314c049..878ee85578 100644
--- a/client/src/pages/Pipeline.jsx
+++ b/client/src/pages/Pipeline.jsx
@@ -76,7 +76,7 @@ export default function Pipeline() {
};
return (
- <div className="p-4 md:p-6 max-w-5xl">
+ <div>
<div className="flex items-center justify-between mb-6 flex-wrap gap-3">
<div className="flex items-center gap-3">
<WorkflowIcon className="w-6 h-6 text-port-accent" />
diff --git a/client/src/pages/PipelineIssue.jsx b/client/src/pages/PipelineIssue.jsx
index 4ee895763e..24d54f9313 100644
--- a/client/src/pages/PipelineIssue.jsx
+++ b/client/src/pages/PipelineIssue.jsx
@@ -143,7 +143,7 @@ export default function PipelineIssue() {
const StageComponent = STAGE_COMPONENTS[stageId];
return (
- <div className="flex flex-col h-full max-w-6xl">
+ <div className="flex flex-col h-full">
{/* Header */}
<div className="p-4 md:p-6 border-b border-port-border space-y-3">
<div className="flex items-center gap-3 flex-wrap text-sm">
diff --git a/client/src/pages/PipelineSeries.jsx b/client/src/pages/PipelineSeries.jsx
index 3cedef401b..fb406b8fac 100644
--- a/client/src/pages/PipelineSeries.jsx
+++ b/client/src/pages/PipelineSeries.jsx
@@ -95,7 +95,12 @@ export default function PipelineSeries() {
};
const handleAddCharacter = () => {
- patchSeries({ characters: [...(series.characters || []), { name: '', description: '' }] });
+ patchSeries({
+ characters: [
+ ...(series.characters || []),
+ { name: '', role: '', physicalDescription: '', personality: '', background: '' },
+ ],
+ });
};
const handleUpdateCharacter = (i, patch) => {
const next = [...series.characters];
@@ -130,7 +135,7 @@ export default function PipelineSeries() {
: 'grid grid-cols-1 lg:grid-cols-[360px_minmax(0,1fr)] gap-4 lg:gap-6';
return (
- <div className="p-4 md:p-6 space-y-4">
+ <div className="space-y-4">
<div className="flex items-center gap-3 flex-wrap">
<Link to="/pipeline" className="inline-flex items-center gap-1 text-sm text-gray-400 hover:text-white">
<ArrowLeft size={14} /> All Series
@@ -306,15 +311,22 @@ function BibleSidebar({ series, worlds, patchSeries, onAddCharacter, onUpdateCha
) : (
<ul className="space-y-2">
{series.characters.map((c, i) => (
- <li key={i} className="space-y-1">
+ <li key={i} className="space-y-1 pb-2 border-b border-port-border/40 last:border-b-0 last:pb-0">
<div className="flex gap-2 items-center">
<input
- value={c.name}
+ value={c.name || ''}
onChange={(e) => onUpdateCharacter(i, { name: e.target.value })}
placeholder="Name"
className="flex-1 px-2 py-1.5 bg-port-bg border border-port-border rounded text-white text-sm"
maxLength={200}
/>
+ <input
+ value={c.role || ''}
+ onChange={(e) => onUpdateCharacter(i, { role: e.target.value })}
+ placeholder="Role"
+ className="w-24 px-2 py-1.5 bg-port-bg border border-port-border rounded text-white text-xs"
+ maxLength={200}
+ />
<button
type="button"
onClick={() => onRemoveCharacter(i)}
@@ -324,11 +336,28 @@ function BibleSidebar({ series, worlds, patchSeries, onAddCharacter, onUpdateCha
<Trash2 size={12} />
</button>
</div>
- <input
- value={c.description}
- onChange={(e) => onUpdateCharacter(i, { description: e.target.value })}
- placeholder="Physical description + role"
- className="w-full px-2 py-1.5 bg-port-bg border border-port-border rounded text-white text-xs"
+ <textarea
+ value={c.physicalDescription || ''}
+ onChange={(e) => onUpdateCharacter(i, { physicalDescription: e.target.value })}
+ placeholder="Physical description — age, build, hair, eyes, wardrobe; drives image-gen"
+ rows={3}
+ className="w-full px-2 py-1.5 bg-port-bg border border-port-border rounded text-white text-xs resize-y"
+ maxLength={2000}
+ />
+ <textarea
+ value={c.personality || ''}
+ onChange={(e) => onUpdateCharacter(i, { personality: e.target.value })}
+ placeholder="Personality — temperament, voice, quirks"
+ rows={2}
+ className="w-full px-2 py-1.5 bg-port-bg border border-port-border rounded text-white text-xs resize-y"
+ maxLength={2000}
+ />
+ <textarea
+ value={c.background || ''}
+ onChange={(e) => onUpdateCharacter(i, { background: e.target.value })}
+ placeholder="Background — who they are, where they come from"
+ rows={2}
+ className="w-full px-2 py-1.5 bg-port-bg border border-port-border rounded text-white text-xs resize-y"
maxLength={2000}
/>
</li>
diff --git a/client/src/services/apiMediaJobs.js b/client/src/services/apiMediaJobs.js
index 09f2a2ceef..422f5e077e 100644
--- a/client/src/services/apiMediaJobs.js
+++ b/client/src/services/apiMediaJobs.js
@@ -11,6 +11,25 @@ export const getMediaJob = (id) => request(`/media-jobs/${encodeURIComponent(id)
export const cancelMediaJob = (id) => request(`/media-jobs/${encodeURIComponent(id)}/cancel`, { method: 'POST' });
+// Delete a terminal (failed / canceled / completed) job from the archive.
+// Live jobs are rejected with 409 — use cancelMediaJob for those.
+export const deleteMediaJob = (id) => request(`/media-jobs/${encodeURIComponent(id)}`, { method: 'DELETE' });
+
+// Re-enqueue a terminal job (typically `failed`) with the same kind/params/
+// owner. Optional `paramOverrides` patches user-facing fields (prompt,
+// model, dimensions, etc.) before the re-enqueue; non-listed params inherit
+// from the original job. Returns `{ jobId, position, status, retriedFrom }`.
+export const retryMediaJob = (id, paramOverrides = null) =>
+ request(`/media-jobs/${encodeURIComponent(id)}/retry`, {
+ method: 'POST',
+ body: paramOverrides ? JSON.stringify({ params: paramOverrides }) : undefined,
+ });
+
+// "Run now" — promote a queued Codex image job past the parallel limit and
+// start it immediately alongside the currently-running jobs. Only valid for
+// queued codex jobs; the server 400s for GPU jobs (single MLX runtime).
+export const runMediaJobNow = (id) => request(`/media-jobs/${encodeURIComponent(id)}/run-now`, { method: 'POST' });
+
// Bulk-cancel every queued (not running) job, optionally scoped to a kind.
// Returns { canceled: <count> }. Running jobs need per-id cancelMediaJob.
export const cancelQueuedMediaJobs = ({ kind } = {}) =>
diff --git a/client/src/services/apiPipeline.js b/client/src/services/apiPipeline.js
index bbde5e0426..2100be45fa 100644
--- a/client/src/services/apiPipeline.js
+++ b/client/src/services/apiPipeline.js
@@ -88,6 +88,25 @@ export const extractPipelineStoryboardScenes = (issueId, { from, providerOverrid
body: JSON.stringify({ from, providerOverride, force }),
});
+// Auto-fill the comicPages stage's pages[] by deterministically parsing the
+// issue's stages.comicScript.output (Marvel/DC-format markdown). Pass
+// `force: true` to replace existing hand-curated pages.
+export const extractPipelineComicPages = (issueId, { force } = {}) =>
+ request(`/pipeline/issues/${encodeURIComponent(issueId)}/stages/comicPages/extract-pages`, {
+ method: 'POST',
+ body: JSON.stringify({ force }),
+ });
+
+// Render a full comic page (multi-panel layout in one image) — the default
+// for cloud image models (Codex / Google), draft-quality for local models.
+// Server persists the returned jobId on stages.comicPages.pages[pageIndex].
+// Returns { jobId, mode, prompt, pageIndex, issue, stage }.
+export const generatePipelineComicPage = (issueId, pageIndex, opts = {}) =>
+ request(`/pipeline/issues/${encodeURIComponent(issueId)}/stages/comicPages/pages/${encodeURIComponent(pageIndex)}/render`, {
+ method: 'POST',
+ body: JSON.stringify(opts),
+ });
+
// ---- Seasons (Phase 2 of Story Arc Planning) ----
export const listPipelineSeasons = (seriesId) =>
request(`/pipeline/series/${encodeURIComponent(seriesId)}/seasons`);
diff --git a/data.sample/prompts/stages/pipeline-comic-script.md b/data.sample/prompts/stages/pipeline-comic-script.md
index 5196cc6a16..ee599c3bb4 100644
--- a/data.sample/prompts/stages/pipeline-comic-script.md
+++ b/data.sample/prompts/stages/pipeline-comic-script.md
@@ -10,7 +10,7 @@ You are a comics writer turning a prose draft into a publishable comic-book issu
### Characters
{{#series.characters}}
-- **{{name}}** — {{description}}
+- **{{name}}**{{#role}} ({{role}}){{/role}} — {{#physicalDescription}}{{physicalDescription}}{{/physicalDescription}}{{^physicalDescription}}{{description}}{{/physicalDescription}}{{#personality}} | personality: {{personality}}{{/personality}}{{#background}} | background: {{background}}{{/background}}
{{/series.characters}}
## This issue
diff --git a/data.sample/prompts/stages/pipeline-prose.md b/data.sample/prompts/stages/pipeline-prose.md
index a426e57e66..b2538c2318 100644
--- a/data.sample/prompts/stages/pipeline-prose.md
+++ b/data.sample/prompts/stages/pipeline-prose.md
@@ -12,7 +12,7 @@ You are a short-fiction author drafting one issue / episode of an ongoing series
### Characters
{{#series.characters}}
-- **{{name}}** — {{description}}
+- **{{name}}**{{#role}} ({{role}}){{/role}} — {{#physicalDescription}}{{physicalDescription}}{{/physicalDescription}}{{^physicalDescription}}{{description}}{{/physicalDescription}}{{#personality}} | personality: {{personality}}{{/personality}}{{#background}} | background: {{background}}{{/background}}
{{/series.characters}}
## This issue
diff --git a/data.sample/prompts/stages/pipeline-tv-script.md b/data.sample/prompts/stages/pipeline-tv-script.md
index 6e12002b32..233feb9b13 100644
--- a/data.sample/prompts/stages/pipeline-tv-script.md
+++ b/data.sample/prompts/stages/pipeline-tv-script.md
@@ -10,7 +10,7 @@ You are a TV writer adapting a prose draft into a single-episode teleplay in sta
### Characters
{{#series.characters}}
-- **{{name}}** — {{description}}
+- **{{name}}**{{#role}} ({{role}}){{/role}} — {{#physicalDescription}}{{physicalDescription}}{{/physicalDescription}}{{^physicalDescription}}{{description}}{{/physicalDescription}}{{#personality}} | personality: {{personality}}{{/personality}}{{#background}} | background: {{background}}{{/background}}
{{/series.characters}}
## This episode
diff --git a/ecosystem.config.cjs b/ecosystem.config.cjs
index eb6be2f7ca..6b6e219213 100644
--- a/ecosystem.config.cjs
+++ b/ecosystem.config.cjs
@@ -56,21 +56,25 @@ module.exports = {
...(pgMode === 'file' ? { MEMORY_BACKEND: 'file' } : {}),
PATH: process.env.PATH // Inherit PATH for git/node access in child processes
},
- watch: ['server'],
- watch_delay: 60000, // 1 min debounce before restarting on file changes
- // Defense in depth — `watch: ['server']` already scopes the watcher to
- // the server/ subtree, so writes to data/ at repo root don't fire it.
- // Belt + suspenders: explicitly ignore runtime data, logs, and the
- // tmpdir-style scratch paths a render might (mis)route into the tree.
- ignore_watch: [
- '**/node_modules',
- '**/*.test.js',
- '**/*package-lock*',
- '**/data/**',
- '**/logs/**',
- '**/.cache/**',
- '**/portos-stepwise-*/**',
- ],
+ // Filewatch is OFF for portos-server. The image gen path (codex / local
+ // MLX / external) writes lots of files: the rendered PNG, a sidecar
+ // metadata JSON, atomic-renamed media-jobs.json, plus per-job temp
+ // scratch. Even with `watch: ['server']` + a broad ignore_watch list,
+ // chokidar occasionally races on the atomic rename target (write to
+ // tmp → rename onto final path) and fires a change event for a path
+ // that the ignore globs *should* have excluded. The symptom in the
+ // wild is "SIGINT received" 5–30s after an image render completes,
+ // killing in-flight jobs.
+ //
+ // Code edits are picked up by a manual `pm2 restart ecosystem.config.cjs`
+ // — that's the documented workflow anyway (pm2 restart doesn't rebuild
+ // the client; you need npm run build / npm start). So losing the
+ // auto-restart-on-save behavior costs nothing in practice.
+ //
+ // To re-enable for ad-hoc dev work: flip this to `watch: ['server']`
+ // and add `'**/data/**'` (plus `'**/node_modules'`, `'**/logs/**'`,
+ // `'**/.cache/**'`, `'**/portos-stepwise-*/**'`) to `ignore_watch`.
+ watch: false,
max_memory_restart: '2G'
},
{
diff --git a/server/index.js b/server/index.js
index 4714b09620..8199468762 100644
--- a/server/index.js
+++ b/server/index.js
@@ -549,7 +549,17 @@ let shuttingDown = false;
const shutdown = async (signal) => {
if (shuttingDown) return;
shuttingDown = true;
- console.log(`🛑 Received ${signal} - shutting down gracefully`);
+ // Diagnostic context for the shutdown trigger. ppid tells us whether the
+ // signal came from PM2 (parent is the PM2 god process), a TTY (parent is
+ // the user's shell), or some external orchestrator. pm_* env vars are set
+ // by PM2 so their presence + a matching ppid is the smoking gun.
+ const pid = process.pid;
+ const ppid = process.ppid;
+ const tty = process.stdin.isTTY ? 'tty' : 'no-tty';
+ const pmId = process.env.pm_id ?? process.env.PM2_ID ?? '<not set>';
+ const pmExecPath = process.env.pm_exec_path ?? '<not set>';
+ console.log(`🛑 Received ${signal} - shutting down gracefully (pid=${pid} ppid=${ppid} ${tty} pm_id=${pmId})`);
+ if (pmExecPath !== '<not set>') console.log(` ↳ launched by PM2: pm_exec_path=${pmExecPath}`);
const forceExitTimer = setTimeout(() => {
console.error('⚠️ Graceful shutdown timed out, forcing exit');
diff --git a/server/lib/comicScriptParser.js b/server/lib/comicScriptParser.js
new file mode 100644
index 0000000000..2388d28337
--- /dev/null
+++ b/server/lib/comicScriptParser.js
@@ -0,0 +1,159 @@
+/**
+ * Pure parser for the Marvel/DC-format comic script the pipeline-comic-script
+ * stage produces (see data.sample/prompts/stages/pipeline-comic-script.md —
+ * data/ is gitignored; data.sample/ is the authoritative template, copied
+ * into data/ at setup time). Splits
+ * the markdown into a structured `{ pages: [{ panels: [...] }] }` shape so
+ * the comicPages stage UI can drop the LLM-authored panel descriptions
+ * directly into image-gen prompts without a second round-trip.
+ *
+ * Strict-but-tolerant: requires `## Page N` / `### Panel N` headers, then
+ * each panel's `**Description:** ...`, `**Caption:** ...`, `**Dialogue:** ...`,
+ * `**SFX:** ...` blocks per the template. "(none)" / empty values normalize
+ * to `''` for caption/sfx and `[]` for dialogue (never null) so downstream
+ * template renderers don't need null-guards. Unexpected text between panels
+ * is ignored.
+ */
+const PAGE_RE = /^##\s+Page\s+([\dIVX]+)\b/i;
+const PANEL_RE = /^###\s+Panel\s+([\dIVX]+)\b/i;
+const FIELD_RE = /^\*\*([A-Za-z][\w ]*?)\s*:\*\*\s*(.*)$/;
+
+const NONE_RE = /^\(\s*none\s*\)$/i;
+const isNoneValue = (s) => !s || NONE_RE.test(s.trim());
+
+const PANEL_LIMITS = Object.freeze({
+ PAGES_MAX: 200,
+ PANELS_PER_PAGE_MAX: 24,
+ DESCRIPTION_MAX: 4000,
+ CAPTION_MAX: 1000,
+ DIALOGUE_LINE_MAX: 1000,
+ DIALOGUE_ENTRIES_MAX: 24,
+ SFX_MAX: 200,
+});
+
+const trimTo = (s, max) => (typeof s === 'string' ? s.trim().slice(0, max) : '');
+
+/**
+ * Parse one panel body — the lines between this panel's header and the next
+ * panel/page header. Combines multi-line field values (Description often
+ * wraps), folds the Dialogue list into `[{ character, line }]`, and discards
+ * "(none)" markers.
+ */
+function parsePanelBody(lines) {
+ // Field collector: accumulate consecutive non-header lines under whichever
+ // **Field:** label was most recently opened. Captions can repeat
+ // (`**Caption:**` then `**Caption 2:**`), so concat them with newlines.
+ let activeField = null;
+ const fields = {}; // canonical key → joined string
+ for (const raw of lines) {
+ const line = raw ?? '';
+ const m = line.match(FIELD_RE);
+ if (m) {
+ const label = m[1].toLowerCase().replace(/\s+\d+$/, '').trim(); // "Caption 2" → "caption"
+ activeField = label;
+ const rest = (m[2] || '').trim();
+ if (fields[activeField] && rest) {
+ fields[activeField] = `${fields[activeField]}\n${rest}`;
+ } else {
+ fields[activeField] = rest || fields[activeField] || '';
+ }
+ } else if (activeField && line.trim()) {
+ fields[activeField] = fields[activeField]
+ ? `${fields[activeField]}\n${line.trim()}`
+ : line.trim();
+ }
+ }
+
+ const dialogue = [];
+ if (fields.dialogue && !isNoneValue(fields.dialogue)) {
+ for (const dl of fields.dialogue.split('\n')) {
+ const t = dl.trim();
+ if (!t) continue;
+ // Match: "- NAME: "line"" or "NAME: line" or "- NAME (whispered): "line""
+ const dm = t.match(/^[-*]?\s*([A-Z][A-Z0-9 '"&./()\-]*?):\s*"?(.+?)"?$/);
+ if (dm) {
+ dialogue.push({
+ character: trimTo(dm[1], 100),
+ line: trimTo(dm[2], PANEL_LIMITS.DIALOGUE_LINE_MAX),
+ });
+ if (dialogue.length >= PANEL_LIMITS.DIALOGUE_ENTRIES_MAX) break;
+ }
+ }
+ }
+
+ return {
+ description: trimTo(fields.description, PANEL_LIMITS.DESCRIPTION_MAX),
+ caption: isNoneValue(fields.caption) ? '' : trimTo(fields.caption, PANEL_LIMITS.CAPTION_MAX),
+ dialogue,
+ sfx: isNoneValue(fields.sfx) ? '' : trimTo(fields.sfx, PANEL_LIMITS.SFX_MAX),
+ };
+}
+
+/**
+ * @param {string} script markdown body from stages.comicScript.output
+ * @returns {{ pages: Array<{ panels: Array<{ description, caption, dialogue, sfx }> }> }}
+ */
+export function parseComicScript(script) {
+ if (typeof script !== 'string' || !script.trim()) return { pages: [] };
+
+ const lines = script.split(/\r?\n/);
+ const pages = [];
+ // Two-pointer cursor: when we hit a Page or Panel header, flush the current
+ // panel buffer (if any) into its page, then start a new buffer.
+ let currentPage = null;
+ let currentPanelLines = null;
+ let inAnyPanel = false;
+
+ const flushPanel = () => {
+ if (!inAnyPanel || !currentPage || !currentPanelLines) return;
+ const panel = parsePanelBody(currentPanelLines);
+ // Drop panels with no description — image-gen has nothing to render
+ // from them and they'd just add empty rows in the UI.
+ if (panel.description) {
+ // Wire-shape expected by ComicPagesStage.jsx: each panel needs
+ // imageJobId for the per-panel render slot.
+ currentPage.panels.push({ ...panel, imageJobId: null });
+ }
+ currentPanelLines = null;
+ inAnyPanel = false;
+ };
+
+ for (const line of lines) {
+ if (PAGE_RE.test(line)) {
+ flushPanel();
+ if (pages.length >= PANEL_LIMITS.PAGES_MAX) break;
+ currentPage = { panels: [] };
+ pages.push(currentPage);
+ continue;
+ }
+ if (PANEL_RE.test(line)) {
+ flushPanel();
+ // A panel header before any Page header is malformed; coerce into an
+ // implicit "Page 1" so the parser doesn't silently drop content.
+ if (!currentPage) {
+ currentPage = { panels: [] };
+ pages.push(currentPage);
+ }
+ if (currentPage.panels.length >= PANEL_LIMITS.PANELS_PER_PAGE_MAX) {
+ // Skip this panel — over the per-page cap — but keep scanning so a
+ // following page header is still respected.
+ currentPanelLines = null;
+ inAnyPanel = false;
+ continue;
+ }
+ currentPanelLines = [];
+ inAnyPanel = true;
+ continue;
+ }
+ if (inAnyPanel && currentPanelLines) {
+ currentPanelLines.push(line);
+ }
+ }
+ flushPanel();
+
+ // Drop pages that ended up empty (e.g. headers with no panels after them).
+ const filtered = pages.filter((p) => p.panels.length > 0);
+ return { pages: filtered };
+}
+
+export { PANEL_LIMITS };
diff --git a/server/lib/comicScriptParser.test.js b/server/lib/comicScriptParser.test.js
new file mode 100644
index 0000000000..443957b7e7
--- /dev/null
+++ b/server/lib/comicScriptParser.test.js
@@ -0,0 +1,83 @@
+import { describe, expect, it } from 'vitest';
+import { parseComicScript } from './comicScriptParser.js';
+
+const SAMPLE = `# Issue 1 — Bone Walker
+
+## Page 1
+
+### Panel 1
+**Description:** Wide establishing shot inside the curve of an enormous fossilized rib, lit by long slanting bars of morning sun.
+**Caption:** The titan died nine thousand years ago.
+**Dialogue:** (none)
+**SFX:** (none)
+
+### Panel 2
+**Description:** Tight close-up — a thumb-sized iridescent beetle picks its way along a stripe of sunlight on polished bone.
+**Caption:** No one has told the rib.
+**Dialogue:**
+- KESSA: "Beetle. If you had any **sense**, you'd stow away."
+**SFX:** "fmp"
+
+## Page 2
+
+### Panel 1
+**Description:** Large panel. The interior of the rib-colony seen from the catwalk.
+**Caption:** This is the inside of a dead god.
+**Caption 2:** It is also home.
+**Dialogue:** (none)
+**SFX:** (distant) "dum… dum-dum…"
+`;
+
+describe('parseComicScript', () => {
+ it('splits into pages and panels with descriptions', () => {
+ const { pages } = parseComicScript(SAMPLE);
+ expect(pages).toHaveLength(2);
+ expect(pages[0].panels).toHaveLength(2);
+ expect(pages[1].panels).toHaveLength(1);
+ expect(pages[0].panels[0].description).toMatch(/establishing shot/);
+ expect(pages[0].panels[0].imageJobId).toBeNull();
+ });
+
+ it('normalizes (none) to empty', () => {
+ const { pages } = parseComicScript(SAMPLE);
+ expect(pages[0].panels[0].caption).toMatch(/titan died/);
+ expect(pages[0].panels[0].sfx).toBe('');
+ expect(pages[0].panels[0].dialogue).toEqual([]);
+ });
+
+ it('parses dialogue list into character/line pairs', () => {
+ const { pages } = parseComicScript(SAMPLE);
+ expect(pages[0].panels[1].dialogue).toEqual([
+ { character: 'KESSA', line: 'Beetle. If you had any **sense**, you\'d stow away.' },
+ ]);
+ });
+
+ it('joins multi-line captions (Caption + Caption 2)', () => {
+ const { pages } = parseComicScript(SAMPLE);
+ expect(pages[1].panels[0].caption).toMatch(/inside of a dead god/);
+ expect(pages[1].panels[0].caption).toMatch(/also home/);
+ });
+
+ it('handles empty / non-string input', () => {
+ expect(parseComicScript('')).toEqual({ pages: [] });
+ expect(parseComicScript(null)).toEqual({ pages: [] });
+ expect(parseComicScript('# Just a title')).toEqual({ pages: [] });
+ });
+
+ it('drops panels with no description and pages with no panels', () => {
+ const script = `## Page 1
+
+### Panel 1
+**Caption:** floating header
+
+### Panel 2
+**Description:** Real panel.
+
+## Page 2
+`;
+ const { pages } = parseComicScript(script);
+ expect(pages).toHaveLength(1);
+ expect(pages[0].panels).toHaveLength(1);
+ expect(pages[0].panels[0].description).toMatch(/Real panel/);
+ });
+});
diff --git a/server/routes/mediaJobs.js b/server/routes/mediaJobs.js
index ce701fe6d9..d3ef2ecaf3 100644
--- a/server/routes/mediaJobs.js
+++ b/server/routes/mediaJobs.js
@@ -9,7 +9,7 @@ import { Router } from 'express';
import { z } from 'zod';
import { asyncHandler, ServerError } from '../lib/errorHandler.js';
import { validateRequest } from '../lib/validation.js';
-import { listJobs, getJob, cancelJob, cancelQueuedJobs, JOB_KINDS, JOB_STATUSES } from '../services/mediaJobQueue/index.js';
+import { listJobs, getJob, cancelJob, cancelQueuedJobs, enqueueJob, removeArchivedJob, runJobNow, JOB_KINDS, JOB_STATUSES } from '../services/mediaJobQueue/index.js';
const router = Router();
@@ -26,6 +26,11 @@ const listQuerySchema = z.object({
// the Render Queue UI actually renders (prompt, owner-supplied settings).
const PARAM_ALLOWLIST = new Set([
'prompt', 'negativePrompt', 'modelId',
+ // `model` is the codex-side counterpart to `modelId` (different field name
+ // because Codex passes a model string straight to the CLI, while local /
+ // video providers carry a registry-id). Without it the UI can't tell which
+ // codex model a failed job tried to use — the row would just say "codex".
+ 'model',
'width', 'height', 'numFrames', 'fps', 'steps', 'guidanceScale',
'seed', 'tiling', 'disableAudio', 'mode', 'imageStrength',
'cfgScale', 'guidance', 'quantize',
@@ -88,6 +93,128 @@ router.post('/:id/cancel', asyncHandler(async (req, res) => {
res.json(result);
}));
+// Params that point at multipart-staged temp files under PATHS.uploads. The
+// gen modules unlink these on completion/failure, so a job that ran is no
+// longer retryable from the persisted params alone (the files are gone, or
+// — worse — could collide with a fresh upload at the same path).
+const TEMP_UPLOAD_PARAMS = ['uploadedTempPath', 'uploadedTempPaths', 'audioFilePath'];
+function hasTempUploadParam(params) {
+ if (!params) return false;
+ return TEMP_UPLOAD_PARAMS.some((k) => {
+ const v = params[k];
+ if (Array.isArray(v)) return v.length > 0;
+ return typeof v === 'string' && v.length > 0;
+ });
+}
+
+// Whitelist of params the UI can edit on retry. Anything else (python paths,
+// session ids, internal flags) rides through unchanged from the original
+// job.params so a user can't escape the server's runtime config from the
+// retry path. Keep this set small and user-facing.
+//
+// String fields use a transform that collapses trimmed empty strings to
+// `undefined` — without that, an empty `modelId` (e.g. user cleared the
+// input) would override the original job's modelId with "" and the gen
+// would fail with "Unknown or unsupported model". Returning undefined makes
+// the override fall through to the original value at merge time.
+const emptyToUndef = (s) => {
+ const v = (s ?? '').trim();
+ return v.length > 0 ? v : undefined;
+};
+const RETRY_OVERRIDE_SCHEMA = z.object({
+ prompt: z.string().trim().min(1).max(8000).optional(),
+ negativePrompt: z.string().trim().max(8000).optional(),
+ model: z.string().max(200).optional().transform(emptyToUndef),
+ modelId: z.string().max(200).optional().transform(emptyToUndef),
+ width: z.number().int().min(64).max(4096).optional(),
+ height: z.number().int().min(64).max(4096).optional(),
+ steps: z.number().int().min(1).max(200).optional(),
+ guidance: z.number().min(0).max(30).optional(),
+ guidanceScale: z.number().min(0).max(30).optional(),
+ cfgScale: z.number().min(0).max(30).optional(),
+ seed: z.number().int().optional(),
+ numFrames: z.number().int().min(1).max(2000).optional(),
+ fps: z.number().int().min(1).max(120).optional(),
+}).partial();
+
+const retryBodySchema = z.object({
+ params: RETRY_OVERRIDE_SCHEMA.optional(),
+}).optional();
+
+// Re-enqueue a terminal job. Optional `body.params` overrides specific
+// user-facing fields (prompt, model, dimensions, etc.) so a user can edit
+// a failed job's config in the UI before retrying without losing the rest
+// of the original params. Non-listed params (interpreter paths, session ids)
+// always inherit from the original job.
+router.post('/:id/retry', asyncHandler(async (req, res) => {
+ const job = getJob(req.params.id);
+ if (!job) throw new ServerError('Not found', { status: 404, code: 'NOT_FOUND' });
+ if (job.status === 'queued' || job.status === 'running') {
+ throw new ServerError(
+ `Job is still ${job.status} — cancel it before retrying`,
+ { status: 409, code: 'JOB_NOT_TERMINAL' },
+ );
+ }
+ // Reject retry when the original job referenced a multipart-staged upload —
+ // the gen modules unlink those files on completion/failure, so re-enqueueing
+ // would either fail with a missing-file error or, worse, act on a stale path
+ // that's since been reused by a different upload.
+ if (hasTempUploadParam(job.params)) {
+ throw new ServerError(
+ 'Job referenced an uploaded file that has since been cleaned up — re-submit the original request with the file attached instead of retrying',
+ { status: 409, code: 'JOB_RETRY_TEMP_UPLOAD' },
+ );
+ }
+ const body = validateRequest(retryBodySchema, req.body ?? {}) ?? {};
+ // Strip undefined override values before merging — Zod's emptyToUndef
+ // transform turns "" → undefined for model/modelId, and a naive spread
+ // would still set those keys to undefined on the merged params (clobbering
+ // the original job's values). Filtering keeps unchanged fields intact.
+ const overrides = Object.fromEntries(
+ Object.entries(body.params ?? {}).filter(([, v]) => v !== undefined),
+ );
+ const params = { ...job.params, ...overrides };
+ const result = enqueueJob({ kind: job.kind, params, owner: job.owner });
+ // Drop the original failed/canceled row from archive — the new job inherits
+ // its work, and leaving both visible just lets users keep clicking Retry on
+ // the dead row and stacking duplicate jobs. If the prune returns false the
+ // archive doesn't have this id (unusual — getJob() found it above), so log
+ // a warning instead of silently masking duplicate history.
+ if (!removeArchivedJob(job.id)) {
+ console.log(`⚠️ media-job [${job.id.slice(0, 8)}] retry: archive prune found nothing to drop — old row may persist in /api/media-jobs`);
+ }
+ res.json({ ...result, retriedFrom: job.id });
+}));
+
+// Delete a terminal job from the failed/canceled archive. Live jobs
+// (queued/running) are rejected — those need cancel first. Returns 404 for
+// unknown ids so the UI can prune optimistically without worrying about a
+// race with another tab pruning the same row.
+router.delete('/:id', asyncHandler(async (req, res) => {
+ const job = getJob(req.params.id);
+ if (!job) throw new ServerError('Not found', { status: 404, code: 'NOT_FOUND' });
+ if (job.status === 'queued' || job.status === 'running') {
+ throw new ServerError(
+ `Job is still ${job.status} — cancel it before deleting`,
+ { status: 409, code: 'JOB_NOT_TERMINAL' },
+ );
+ }
+ const removed = removeArchivedJob(req.params.id);
+ if (!removed) throw new ServerError('Not found', { status: 404, code: 'NOT_FOUND' });
+ res.json({ ok: true });
+}));
+
+// Promote a queued Codex job past the lane's parallel limit. GPU jobs are
+// rejected — they serialize on the single MLX runtime.
+router.post('/:id/run-now', asyncHandler(async (req, res) => {
+ const result = runJobNow(req.params.id);
+ if (!result.ok) {
+ const status = result.code === 'NOT_FOUND' ? 404 : 400;
+ throw new ServerError(result.error || 'Run-now failed', { status, code: result.code });
+ }
+ res.json(result);
+}));
+
// Bulk-cancel every queued job (running jobs are left alone — they need a
// per-id POST to trigger the SIGTERM path). Optional ?kind=image|video filter.
const cancelQueuedSchema = z.object({ kind: z.enum(JOB_KINDS).optional() });
diff --git a/server/routes/mediaJobs.test.js b/server/routes/mediaJobs.test.js
new file mode 100644
index 0000000000..49d2eda9a2
--- /dev/null
+++ b/server/routes/mediaJobs.test.js
@@ -0,0 +1,219 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import express from 'express';
+import { request } from '../lib/testHelper.js';
+import { errorMiddleware } from '../lib/errorHandler.js';
+
+// Stub the queue so we control which jobs exist for the retry endpoint without
+// running the real worker. enqueueJob / cancelJob etc. are returned as vi.fn so
+// we can assert the route calls them with the right args.
+const jobStore = new Map();
+const stubs = {
+ enqueueJob: vi.fn(({ kind, params, owner }) => ({ jobId: 'new-job', position: 1, status: 'queued' })),
+ cancelJob: vi.fn(async (id) => (jobStore.has(id) ? { ok: true, status: 'canceled' } : { ok: false, code: 'NOT_FOUND' })),
+ cancelQueuedJobs: vi.fn(async () => ({ canceled: 0 })),
+ runJobNow: vi.fn(() => ({ ok: false, code: 'NOT_FOUND' })),
+ removeArchivedJob: vi.fn((id) => jobStore.delete(id)),
+};
+vi.mock('../services/mediaJobQueue/index.js', () => ({
+ JOB_KINDS: ['video', 'image'],
+ JOB_STATUSES: ['queued', 'running', 'completed', 'failed', 'canceled'],
+ listJobs: () => Array.from(jobStore.values()),
+ getJob: (id) => jobStore.get(id) || null,
+ enqueueJob: (...args) => stubs.enqueueJob(...args),
+ cancelJob: (...args) => stubs.cancelJob(...args),
+ cancelQueuedJobs: (...args) => stubs.cancelQueuedJobs(...args),
+ runJobNow: (...args) => stubs.runJobNow(...args),
+ removeArchivedJob: (...args) => stubs.removeArchivedJob(...args),
+}));
+
+const mediaJobsRouter = (await import('./mediaJobs.js')).default;
+
+function makeApp() {
+ const app = express();
+ app.use(express.json());
+ app.use('/api/media-jobs', mediaJobsRouter);
+ app.use(errorMiddleware);
+ return app;
+}
+
+describe('mediaJobs routes', () => {
+ beforeEach(() => {
+ jobStore.clear();
+ vi.clearAllMocks();
+ });
+
+ it('POST /:id/retry 404s for unknown id', async () => {
+ const r = await request(makeApp()).post('/api/media-jobs/nope/retry').send({});
+ expect(r.status).toBe(404);
+ });
+
+ it('POST /:id/retry 409s when the job is still running/queued', async () => {
+ jobStore.set('j-live', { id: 'j-live', kind: 'image', owner: null, status: 'running', params: {} });
+ const r = await request(makeApp()).post('/api/media-jobs/j-live/retry').send({});
+ expect(r.status).toBe(409);
+ expect(r.body.code || r.body.error).toMatch(/JOB_NOT_TERMINAL|cancel it/);
+ expect(stubs.enqueueJob).not.toHaveBeenCalled();
+ });
+
+ it('POST /:id/retry re-enqueues a terminal text-only job (no temp-upload params)', async () => {
+ jobStore.set('j-img', {
+ id: 'j-img', kind: 'image', owner: 'cd-1', status: 'failed',
+ params: { prompt: 'a cat', mode: 'codex' },
+ });
+ const r = await request(makeApp()).post('/api/media-jobs/j-img/retry').send({});
+ expect(r.status).toBe(200);
+ expect(r.body.jobId).toBe('new-job');
+ expect(r.body.retriedFrom).toBe('j-img');
+ expect(stubs.enqueueJob).toHaveBeenCalledWith({
+ kind: 'image', owner: 'cd-1', params: { prompt: 'a cat', mode: 'codex' },
+ });
+ // The original failed row is dropped from the archive so the UI doesn't
+ // keep a clickable Retry button next to a job whose work was already
+ // inherited by the freshly-enqueued one.
+ expect(stubs.removeArchivedJob).toHaveBeenCalledWith('j-img');
+ });
+
+ it('POST /:id/retry merges body.params overrides onto the original params', async () => {
+ jobStore.set('j-edit', {
+ id: 'j-edit', kind: 'image', owner: null, status: 'failed',
+ params: {
+ prompt: 'old prompt', negativePrompt: 'old neg',
+ mode: 'codex', model: 'gpt-image-1', width: 512, height: 512, steps: 30,
+ // a non-whitelisted internal field — must ride through unchanged
+ codexPath: '/usr/local/bin/codex',
+ },
+ });
+ const r = await request(makeApp())
+ .post('/api/media-jobs/j-edit/retry')
+ .send({ params: { prompt: 'new prompt', width: 1024, model: 'gpt-image-1' } });
+ expect(r.status).toBe(200);
+ // overridden fields take the new value; non-overridden fields inherit;
+ // non-whitelisted internal fields are preserved untouched.
+ expect(stubs.enqueueJob).toHaveBeenCalledWith({
+ kind: 'image', owner: null,
+ params: {
+ prompt: 'new prompt', negativePrompt: 'old neg',
+ mode: 'codex', model: 'gpt-image-1', width: 1024, height: 512, steps: 30,
+ codexPath: '/usr/local/bin/codex',
+ },
+ });
+ });
+
+ it('POST /:id/retry treats empty model/modelId override as "keep original" rather than clobbering with ""', async () => {
+ jobStore.set('j-clear', {
+ id: 'j-clear', kind: 'image', owner: null, status: 'failed',
+ params: { prompt: 'cat', modelId: 'sdxl-base', steps: 30 },
+ });
+ const r = await request(makeApp())
+ .post('/api/media-jobs/j-clear/retry')
+ .send({ params: { modelId: ' ', steps: 40 } });
+ expect(r.status).toBe(200);
+ const call = stubs.enqueueJob.mock.calls[0][0];
+ // modelId stays at the original — empty/whitespace override drops out.
+ expect(call.params.modelId).toBe('sdxl-base');
+ expect(call.params.steps).toBe(40);
+ });
+
+ it('POST /:id/retry rejects override fields outside the whitelist', async () => {
+ jobStore.set('j-bad', {
+ id: 'j-bad', kind: 'image', owner: null, status: 'failed',
+ params: { prompt: 'x', mode: 'codex' },
+ });
+ // pythonPath is not in the override schema; zod strips unknown keys, so
+ // the enqueue should still happen but pythonPath must NOT have leaked
+ // through.
+ const r = await request(makeApp())
+ .post('/api/media-jobs/j-bad/retry')
+ .send({ params: { prompt: 'x', pythonPath: '/tmp/evil' } });
+ expect(r.status).toBe(200);
+ const call = stubs.enqueueJob.mock.calls[0][0];
+ expect(call.params.pythonPath).toBeUndefined();
+ });
+
+ it('POST /:id/retry 409s with JOB_RETRY_TEMP_UPLOAD when the job referenced an uploadedTempPath', async () => {
+ jobStore.set('j-up', {
+ id: 'j-up', kind: 'video', owner: null, status: 'completed',
+ params: { prompt: 'foo', uploadedTempPath: '/data/uploads/staged-1.png' },
+ });
+ const r = await request(makeApp()).post('/api/media-jobs/j-up/retry').send({});
+ expect(r.status).toBe(409);
+ expect(r.body.code).toBe('JOB_RETRY_TEMP_UPLOAD');
+ expect(stubs.enqueueJob).not.toHaveBeenCalled();
+ });
+
+ it('POST /:id/retry rejects retries that referenced uploadedTempPaths (array) or audioFilePath', async () => {
+ jobStore.set('j-paths', {
+ id: 'j-paths', kind: 'video', owner: null, status: 'failed',
+ params: { prompt: 'x', uploadedTempPaths: ['/data/uploads/a.png'] },
+ });
+ jobStore.set('j-audio', {
+ id: 'j-audio', kind: 'video', owner: null, status: 'failed',
+ params: { prompt: 'x', audioFilePath: '/data/uploads/a.wav' },
+ });
+ const app = makeApp();
+ const r1 = await request(app).post('/api/media-jobs/j-paths/retry').send({});
+ const r2 = await request(app).post('/api/media-jobs/j-audio/retry').send({});
+ expect(r1.status).toBe(409);
+ expect(r1.body.code).toBe('JOB_RETRY_TEMP_UPLOAD');
+ expect(r2.status).toBe(409);
+ expect(r2.body.code).toBe('JOB_RETRY_TEMP_UPLOAD');
+ expect(stubs.enqueueJob).not.toHaveBeenCalled();
+ });
+
+ it('POST /:id/retry allows retry when uploadedTempPaths is an empty array', async () => {
+ jobStore.set('j-empty', {
+ id: 'j-empty', kind: 'video', owner: null, status: 'failed',
+ params: { prompt: 'x', uploadedTempPaths: [] },
+ });
+ const r = await request(makeApp()).post('/api/media-jobs/j-empty/retry').send({});
+ expect(r.status).toBe(200);
+ expect(stubs.enqueueJob).toHaveBeenCalledOnce();
+ });
+
+ it('POST /:id/run-now starts a queued Codex job past the parallel limit', async () => {
+ stubs.runJobNow.mockReturnValueOnce({ ok: true, status: 'running' });
+ const r = await request(makeApp()).post('/api/media-jobs/j-codex/run-now').send({});
+ expect(r.status).toBe(200);
+ expect(r.body.status).toBe('running');
+ expect(stubs.runJobNow).toHaveBeenCalledWith('j-codex');
+ });
+
+ it('POST /:id/run-now 400s for non-Codex (GPU) jobs', async () => {
+ stubs.runJobNow.mockReturnValueOnce({
+ ok: false, code: 'NOT_CODEX',
+ error: 'Only Codex image jobs can be run-now; GPU jobs serialize on the MLX runtime',
+ });
+ const r = await request(makeApp()).post('/api/media-jobs/j-gpu/run-now').send({});
+ expect(r.status).toBe(400);
+ expect(r.body.code).toBe('NOT_CODEX');
+ });
+
+ it('POST /:id/run-now 404s for unknown / not-queued ids', async () => {
+ // Default stub returns NOT_FOUND
+ const r = await request(makeApp()).post('/api/media-jobs/nope/run-now').send({});
+ expect(r.status).toBe(404);
+ expect(r.body.code).toBe('NOT_FOUND');
+ });
+
+ it('DELETE /:id removes a terminal job from the archive', async () => {
+ jobStore.set('j-old', { id: 'j-old', kind: 'image', owner: null, status: 'failed', params: {} });
+ const r = await request(makeApp()).delete('/api/media-jobs/j-old');
+ expect(r.status).toBe(200);
+ expect(r.body.ok).toBe(true);
+ expect(stubs.removeArchivedJob).toHaveBeenCalledWith('j-old');
+ });
+
+ it('DELETE /:id 409s for queued/running jobs', async () => {
+ jobStore.set('j-live', { id: 'j-live', kind: 'image', owner: null, status: 'running', params: {} });
+ const r = await request(makeApp()).delete('/api/media-jobs/j-live');
+ expect(r.status).toBe(409);
+ expect(r.body.code).toBe('JOB_NOT_TERMINAL');
+ expect(stubs.removeArchivedJob).not.toHaveBeenCalled();
+ });
+
+ it('DELETE /:id 404s for unknown ids', async () => {
+ const r = await request(makeApp()).delete('/api/media-jobs/nope');
+ expect(r.status).toBe(404);
+ expect(r.body.code).toBe('NOT_FOUND');
+ });
+});
diff --git a/server/routes/pipeline.js b/server/routes/pipeline.js
index 9387e30c0a..b215172a14 100644
--- a/server/routes/pipeline.js
+++ b/server/routes/pipeline.js
@@ -37,10 +37,11 @@ import * as seasonsSvc from '../services/pipeline/seasons.js';
import * as arcPlanner from '../services/pipeline/arcPlanner.js';
import { generateStage } from '../services/pipeline/textStages.js';
import * as autoRunner from '../services/pipeline/autoRunner.js';
-import { enqueueVisualImage } from '../services/pipeline/visualStages.js';
+import { enqueueVisualImage, enqueueVisualComicPage } from '../services/pipeline/visualStages.js';
import { startEpisodeVideoForIssue, ERR_NO_STORYBOARDS } from '../services/pipeline/episodeVideo.js';
import { ASPECT_RATIOS, QUALITIES } from '../lib/creativeDirectorPresets.js';
import { extractScenes, SOURCE_KIND } from '../lib/sceneExtractor.js';
+import { parseComicScript } from '../lib/comicScriptParser.js';
import { BIBLE_KIND } from '../lib/storyBible.js';
import { ARC_LIMITS, ARC_STATUSES, SEASON_STATUSES } from '../lib/storyArc.js';
@@ -229,6 +230,21 @@ const visualGenerateSchema = z.object({
guidance: z.number().min(0).max(30).optional(),
});
+// Full-comic-page render: same knobs as panel render minus `description` /
+// `slugline` (the prompt is built server-side from the page's panels[] so it
+// stays in sync with whatever the script-extractor produced).
+const comicPageRenderSchema = z.object({
+ negativePrompt: z.string().trim().max(2000).optional(),
+ extraStyle: z.string().trim().max(2000).optional(),
+ mode: z.enum(['local', 'codex']).optional(),
+ modelId: z.string().trim().max(64).optional(),
+ width: z.number().int().min(64).max(2048).optional(),
+ height: z.number().int().min(64).max(2048).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(),
+});
+
const episodeVideoSchema = z.object({
aspectRatio: z.enum(ASPECT_RATIOS).optional(),
quality: z.enum(QUALITIES).optional(),
@@ -248,6 +264,10 @@ const extractScenesSchema = z.object({
force: z.boolean().optional(),
});
+const extractComicPagesSchema = z.object({
+ force: z.boolean().optional(),
+});
+
// Source: `issueId` (pulls `stages.prose.output`) OR explicit `corpus` text.
// `parallel: true` runs the three bible kinds concurrently (~3× wall-clock
// speedup on HTTP-API providers like OpenAI/Anthropic/LM Studio HTTP).
@@ -588,6 +608,84 @@ router.post('/issues/:id/stages/storyboards/extract-scenes', asyncHandler(async
});
}));
+router.post('/issues/:id/stages/comicPages/extract-pages', asyncHandler(async (req, res) => {
+ const body = validateRequest(extractComicPagesSchema, req.body ?? {});
+ const issue = await issuesSvc.getIssue(req.params.id).catch((err) => { throw mapServiceError(err); });
+
+ const source = (issue.stages?.comicScript?.output || '').trim();
+ if (!source) {
+ throw new ServerError(
+ `Cannot extract pages — issue's comicScript stage is empty`,
+ { status: 400, code: 'PIPELINE_NO_SOURCE_FOR_PAGE_EXTRACT' },
+ );
+ }
+
+ const existing = Array.isArray(issue.stages?.comicPages?.pages) ? issue.stages.comicPages.pages : [];
+ if (existing.length > 0 && !body.force) {
+ throw new ServerError(
+ `Comic pages already has ${existing.length} page${existing.length === 1 ? '' : 's'} — pass { force: true } to replace`,
+ { status: 409, code: 'PIPELINE_COMIC_PAGES_NOT_EMPTY' },
+ );
+ }
+
+ const { pages } = parseComicScript(source);
+
+ const { issue: updatedIssue, stage } = await issuesSvc.updateStage(issue.id, 'comicPages', {
+ status: pages.length ? 'ready' : 'empty',
+ pages,
+ errorMessage: '',
+ });
+
+ const panelCount = pages.reduce((n, p) => n + (p.panels?.length || 0), 0);
+ res.json({
+ issue: updatedIssue,
+ stage,
+ pageCount: pages.length,
+ panelCount,
+ });
+}));
+
+// Render a full comic page (multi-panel layout in one image) — the
+// recommended default for cloud-class image models (Codex, Google Imagen);
+// local diffusion models can render this but tend to produce draft-quality
+// pages, so the per-panel `/visual` endpoint remains the fallback.
+//
+// Persists the returned jobId on stages.comicPages.pages[pageIndex].imageJobId
+// so the UI can show the page-level render alongside the per-panel renders.
+router.post('/issues/:id/stages/comicPages/pages/:pageIndex/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(comicPageRenderSchema, req.body ?? {});
+
+ // Validate the page exists up front so we skip the enqueue work entirely
+ // when the index is bad. The service also throws ServerError(404) for the
+ // same case (defense in depth — any other caller still gets a clean 404),
+ // but checking here avoids loading the bible context just to error out.
+ 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 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.
+ pages[pageIndex] = { ...pages[pageIndex], imageJobId: result.jobId, prompt: result.prompt };
+ const { issue: updatedIssue, stage } = await issuesSvc.updateStage(req.params.id, 'comicPages', {
+ status: 'edited',
+ pages,
+ });
+ res.json({ ...result, issue: updatedIssue, stage });
+}));
+
router.post('/issues/:id/stages/:stageId/visual', asyncHandler(async (req, res) => {
const { id, stageId } = req.params;
if (!issuesSvc.VISUAL_STAGE_IDS.includes(stageId)) {
diff --git a/server/routes/pipeline.test.js b/server/routes/pipeline.test.js
index e0b159a2e1..ca868462c9 100644
--- a/server/routes/pipeline.test.js
+++ b/server/routes/pipeline.test.js
@@ -62,6 +62,13 @@ vi.mock('../services/pipeline/visualStages.js', () => ({
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,
+ })),
}));
// The episode-video handoff creates a CD project; stub it so the route test
@@ -475,6 +482,164 @@ describe('pipeline routes', () => {
spy.mockRestore();
});
+ // ---- comicPages/extract-pages ----
+
+ it('POST /issues/:id/stages/comicPages/extract-pages 400s when comicScript is empty', async () => {
+ const app = makeApp();
+ const ser = await request(app).post('/api/pipeline/series').send({ name: 'S' });
+ const iss = await request(app).post(`/api/pipeline/series/${ser.body.id}/issues`).send({ title: 'I' });
+ const r = await request(app)
+ .post(`/api/pipeline/issues/${iss.body.id}/stages/comicPages/extract-pages`)
+ .send({});
+ expect(r.status).toBe(400);
+ expect(r.body.code || r.body.error).toMatch(/PIPELINE_NO_SOURCE_FOR_PAGE_EXTRACT|empty/i);
+ });
+
+ it('POST /issues/:id/stages/comicPages/extract-pages 409s when comicPages already has pages (no force)', async () => {
+ const app = makeApp();
+ const ser = await request(app).post('/api/pipeline/series').send({ name: 'S' });
+ const iss = await request(app).post(`/api/pipeline/series/${ser.body.id}/issues`).send({ title: 'I' });
+ await request(app).patch(`/api/pipeline/issues/${iss.body.id}`).send({
+ stages: {
+ comicScript: { status: 'ready', output: '## Page 1\n\n### Panel 1\n\n**Description:** x\n' },
+ comicPages: { pages: [{ panels: [{ description: 'pre-existing', caption: '', dialogue: [], sfx: '' }] }] },
+ },
+ });
+ const r = await request(app)
+ .post(`/api/pipeline/issues/${iss.body.id}/stages/comicPages/extract-pages`)
+ .send({});
+ expect(r.status).toBe(409);
+ expect(r.body.code || r.body.error).toMatch(/PIPELINE_COMIC_PAGES_NOT_EMPTY|force/i);
+ });
+
+ it('POST /issues/:id/stages/comicPages/extract-pages parses comicScript output and persists pages', async () => {
+ const app = makeApp();
+ const ser = await request(app).post('/api/pipeline/series').send({ name: 'S' });
+ const iss = await request(app).post(`/api/pipeline/series/${ser.body.id}/issues`).send({ title: 'I' });
+ const script = [
+ '## Page 1',
+ '',
+ '### Panel 1',
+ '',
+ '**Description:** A wide-shot of the foundry.',
+ '**Caption:** The city woke late.',
+ '**Dialogue:** ALICE: It\'s quiet.',
+ '**SFX:** (none)',
+ '',
+ '### Panel 2',
+ '',
+ '**Description:** Close on a hand.',
+ '**Caption:** (none)',
+ '**Dialogue:** (none)',
+ '**SFX:** TINK',
+ '',
+ '## Page 2',
+ '',
+ '### Panel 1',
+ '',
+ '**Description:** A door swings open.',
+ '**Caption:** (none)',
+ '**Dialogue:** (none)',
+ '**SFX:** (none)',
+ ].join('\n');
+ await request(app).patch(`/api/pipeline/issues/${iss.body.id}`).send({
+ stages: { comicScript: { status: 'ready', output: script } },
+ });
+ const r = await request(app)
+ .post(`/api/pipeline/issues/${iss.body.id}/stages/comicPages/extract-pages`)
+ .send({});
+ expect(r.status).toBe(200);
+ expect(r.body.pageCount).toBe(2);
+ expect(r.body.panelCount).toBe(3);
+ expect(r.body.stage.status).toBe('ready');
+ expect(r.body.stage.pages).toHaveLength(2);
+ expect(r.body.stage.pages[0].panels).toHaveLength(2);
+ // (none) sentinels normalized to '' / [] per the parser docstring
+ expect(r.body.stage.pages[0].panels[0].sfx).toBe('');
+ expect(r.body.stage.pages[0].panels[1].caption).toBe('');
+ expect(r.body.stage.pages[0].panels[1].dialogue).toEqual([]);
+ expect(r.body.stage.pages[0].panels[0].dialogue[0]).toEqual({ character: 'ALICE', line: 'It\'s quiet.' });
+ });
+
+ it('POST /issues/:id/stages/comicPages/extract-pages with force=true replaces existing pages', async () => {
+ const app = makeApp();
+ const ser = await request(app).post('/api/pipeline/series').send({ name: 'S' });
+ const iss = await request(app).post(`/api/pipeline/series/${ser.body.id}/issues`).send({ title: 'I' });
+ await request(app).patch(`/api/pipeline/issues/${iss.body.id}`).send({
+ stages: {
+ comicScript: { status: 'ready', output: '## Page 1\n\n### Panel 1\n\n**Description:** Fresh.\n**Caption:** (none)\n**Dialogue:** (none)\n**SFX:** (none)\n' },
+ comicPages: { pages: [{ panels: [{ description: 'stale' }] }] },
+ },
+ });
+ const r = await request(app)
+ .post(`/api/pipeline/issues/${iss.body.id}/stages/comicPages/extract-pages`)
+ .send({ force: true });
+ expect(r.status).toBe(200);
+ expect(r.body.pageCount).toBe(1);
+ expect(r.body.stage.pages[0].panels[0].description).toBe('Fresh.');
+ });
+
+ // ---- comicPages/pages/:pageIndex/render ----
+
+ it('POST /issues/:id/stages/comicPages/pages/:pageIndex/render 400s for a non-integer pageIndex', async () => {
+ const app = makeApp();
+ const ser = await request(app).post('/api/pipeline/series').send({ name: 'S' });
+ const iss = await request(app).post(`/api/pipeline/series/${ser.body.id}/issues`).send({ title: 'I' });
+ const r = await request(app)
+ .post(`/api/pipeline/issues/${iss.body.id}/stages/comicPages/pages/abc/render`)
+ .send({});
+ expect(r.status).toBe(400);
+ expect(r.body.code || r.body.error).toMatch(/PIPELINE_COMIC_PAGE_BAD_INDEX|integer/i);
+ });
+
+ it('POST /issues/:id/stages/comicPages/pages/:pageIndex/render persists imageJobId + prompt onto the target page', async () => {
+ const app = makeApp();
+ const ser = await request(app).post('/api/pipeline/series').send({ name: 'S' });
+ const iss = await request(app).post(`/api/pipeline/series/${ser.body.id}/issues`).send({ title: 'I' });
+ await request(app).patch(`/api/pipeline/issues/${iss.body.id}`).send({
+ stages: {
+ comicPages: {
+ pages: [
+ { panels: [{ description: 'p1', caption: '', dialogue: [], sfx: '' }] },
+ { panels: [{ description: 'p2', caption: '', dialogue: [], sfx: '' }] },
+ ],
+ },
+ },
+ });
+ const r = await request(app)
+ .post(`/api/pipeline/issues/${iss.body.id}/stages/comicPages/pages/1/render`)
+ .send({});
+ expect(r.status).toBe(200);
+ 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();
+ expect(r.body.stage.status).toBe('edited');
+ });
+
+ it('POST /issues/:id/stages/comicPages/pages/:pageIndex/render 404s when pageIndex is out of range', async () => {
+ // The service throws on out-of-range pageIndex; the route validates the
+ // page exists up front and returns 404 instead of letting the service
+ // bubble a generic Error.
+ const visualStages = await import('../services/pipeline/visualStages.js');
+ const app = makeApp();
+ const ser = await request(app).post('/api/pipeline/series').send({ name: 'S' });
+ const iss = await request(app).post(`/api/pipeline/series/${ser.body.id}/issues`).send({ title: 'I' });
+ await request(app).patch(`/api/pipeline/issues/${iss.body.id}`).send({
+ stages: { comicPages: { pages: [] } },
+ });
+ const r = await request(app)
+ .post(`/api/pipeline/issues/${iss.body.id}/stages/comicPages/pages/99/render`)
+ .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();
+ });
+
// -----------------------
// Season routes (Phase 2 of Story Arc Planning)
// -----------------------
diff --git a/server/routes/settings.js b/server/routes/settings.js
index dc41c51ce0..b7c0b6a1be 100644
--- a/server/routes/settings.js
+++ b/server/routes/settings.js
@@ -1,21 +1,50 @@
import { Router } from 'express';
import { getSettings, updateSettings } from '../services/settings.js';
+import {
+ setCodexParallelLimit,
+ CODEX_PARALLEL_MIN,
+ CODEX_PARALLEL_MAX,
+ CODEX_PARALLEL_DEFAULT,
+} from '../services/mediaJobQueue/index.js';
import { asyncHandler } from '../lib/errorHandler.js';
const router = Router();
+// Server-authoritative bounds the client UI can render directly so the form
+// clamp never drifts away from what the queue actually enforces. Stitched
+// under `imageGen.codex.parallelLimitBounds` since that's where the field
+// the bounds describe lives.
+const decorateBounds = (settings) => ({
+ ...settings,
+ imageGen: {
+ ...(settings.imageGen || {}),
+ codex: {
+ ...(settings.imageGen?.codex || {}),
+ parallelLimitBounds: {
+ min: CODEX_PARALLEL_MIN,
+ max: CODEX_PARALLEL_MAX,
+ default: CODEX_PARALLEL_DEFAULT,
+ },
+ },
+ },
+});
+
// GET /api/settings
router.get('/', asyncHandler(async (req, res) => {
const settings = await getSettings();
const { secrets, ...safe } = settings;
- res.json(safe);
+ res.json(decorateBounds(safe));
}));
// PUT /api/settings
router.put('/', asyncHandler(async (req, res) => {
const merged = await updateSettings(req.body);
+ // The queue caches codex.parallelLimit in-process; sync it from the
+ // merged value so a save takes effect without a restart and without
+ // re-reading the file.
+ setCodexParallelLimit(merged.imageGen?.codex?.parallelLimit ?? CODEX_PARALLEL_DEFAULT);
const { secrets, ...safe } = merged;
- res.json(safe);
+ res.json(decorateBounds(safe));
}));
export default router;
diff --git a/server/services/imageGen/codex.js b/server/services/imageGen/codex.js
index af0ff78f9b..0645613750 100644
--- a/server/services/imageGen/codex.js
+++ b/server/services/imageGen/codex.js
@@ -29,36 +29,72 @@ import { ServerError } from '../../lib/errorHandler.js';
import { imageGenEvents } from '../imageGenEvents.js';
import { broadcastSse, attachSseClient as attachSse, closeJobAfterDelay } from '../../lib/sseUtils.js';
-// 5 minutes — built-in `image_gen` typically returns in 30–90s, but xhigh
-// reasoning + a queued model can run longer. Bigger than the SD-API timeout
-// because we have no progress signal to short-circuit early on.
-const CODEX_TIMEOUT_MS = 5 * 60 * 1000;
+// 20 minutes — built-in `image_gen` typically returns in 30–90s, but with the
+// parallel codex lane several renders share OpenAI throughput and a single
+// generation can easily push past 5 minutes (xhigh reasoning, queued model,
+// or an over-subscribed batch). Env-overridable for power users who want a
+// tighter cap. Bigger than the SD-API timeout because there's no progress
+// signal to short-circuit early on. Keep this in rough sync with
+// WATCHDOG_CODEX_MS in mediaJobQueue/index.js so the queue's watchdog and
+// the child's wall-clock cap fire on a similar budget.
+const CODEX_TIMEOUT_MS = (() => {
+ const n = Number(process.env.CODEX_TIMEOUT_MS);
+ return Number.isFinite(n) && n > 0 ? n : 20 * 60 * 1000;
+})();
const DEFAULT_BIN = 'codex';
const codexImagesDir = (sessionId) =>
join(homedir(), '.codex', 'generated_images', sessionId);
-// Per-job clients: jobId -> { clients, status, lastPayload, ... }. Same
+// Per-job state — keyed by jobId so multiple codex renders can run in
+// parallel under the mediaJobQueue's configurable lane limit. Same client
// shape as imageGen/local.js so attachSseClient/broadcastSse just work.
const jobs = new Map();
-let activeProcess = null;
-let activeJob = null;
+const activeProcs = new Map();
+const activeJobs = new Map();
-export const getActiveJob = () => activeJob;
+// Returns the most-recently-started job — used by status surfaces and the
+// settings test-render; not safe for cancel routing under parallel use.
+export const getActiveJob = () => {
+ const entries = [...activeJobs.values()];
+ return entries.length ? entries[entries.length - 1] : null;
+};
export const attachSseClient = (jobId, res) => attachSse(jobs, jobId, res);
-export const cancel = () => {
- if (!activeProcess) return false;
- const proc = activeProcess;
+const sigtermWithEscalation = (id, proc) => {
proc.kill('SIGTERM');
setTimeout(() => {
- if (activeProcess === proc && proc.exitCode === null && proc.signalCode === null) {
+ if (activeProcs.get(id) === proc && proc.exitCode === null && proc.signalCode === null) {
console.log(`⚠️ codex child didn't exit on SIGTERM — escalating to SIGKILL`);
proc.kill('SIGKILL');
}
}, 5000);
+};
+
+// Cancel one specific codex render. jobId is required — with parallel codex
+// renders an "anonymous cancel" is genuinely destructive (would nuke every
+// in-flight render), so callers have to be explicit. Use `cancelAll()` for
+// the legacy "stop everything" path that the imageGen.cancel() dispatcher
+// wires up.
+export const cancel = (jobId) => {
+ if (!jobId) {
+ throw new Error("codex.cancel requires a jobId — use codex.cancelAll() to terminate every in-flight render");
+ }
+ const proc = activeProcs.get(jobId);
+ if (!proc) return false;
+ sigtermWithEscalation(jobId, proc);
+ return true;
+};
+
+// Bulk terminate every in-flight codex render. Only used by the imageGen
+// dispatcher's "cancel everything" route — the per-job mediaJobQueue path
+// always passes a specific jobId to `cancel()`.
+export const cancelAll = () => {
+ const entries = [...activeProcs.entries()];
+ if (entries.length === 0) return false;
+ for (const [id, proc] of entries) sigtermWithEscalation(id, proc);
return true;
};
@@ -87,15 +123,6 @@ export async function generateImage({ codexPath, model, prompt, width, height, n
if (!prompt?.trim()) {
throw new ServerError('Prompt is required', { status: 400, code: 'VALIDATION_ERROR' });
}
- // The mediaJobQueue serializes codex jobs in their own lane and passes
- // its job id in via `providedJobId`, so concurrent queued calls never reach
- // here while activeProcess is set. The 409 below is defense-in-depth for
- // legacy direct callers (voice tool, avatar route) that still bypass the
- // queue.
- if (activeProcess) {
- throw new ServerError('A Codex generation is already in progress — cancel it before starting another', { status: 409, code: 'IMAGE_GEN_BUSY' });
- }
-
await ensureDir(PATHS.images);
const jobId = providedJobId || randomUUID();
@@ -132,7 +159,7 @@ export async function generateImage({ codexPath, model, prompt, width, height, n
console.log(`🎨 Generating image [${jobId.slice(0, 8)}] codex: ${prompt.slice(0, 60)}…`);
imageGenEvents.emit('started', { generationId: jobId, totalSteps: 1 });
- activeJob = { ...meta, generationId: jobId, totalSteps: 1, step: 0, progress: 0, currentImage: null };
+ activeJobs.set(jobId, { ...meta, generationId: jobId, totalSteps: 1, step: 0, progress: 0, currentImage: null });
broadcastSse(job, { type: 'status', message: 'Spawning codex…' });
// generateImage returns a job descriptor synchronously; the actual codex
@@ -153,13 +180,13 @@ export async function generateImage({ codexPath, model, prompt, width, height, n
async function runCodex(job, jobId, bin, args, outputPath, filename, meta) {
const proc = spawn(bin, args, { shell: false, stdio: ['ignore', 'pipe', 'pipe'] });
- activeProcess = proc;
+ activeProcs.set(jobId, proc);
let sessionId = null;
let stderrTail = '';
const STDERR_TAIL_BYTES = 32 * 1024;
let timeoutTimer = setTimeout(() => {
- if (activeProcess === proc) {
+ if (activeProcs.get(jobId) === proc) {
console.log(`⏱️ codex timed out after ${CODEX_TIMEOUT_MS}ms [${jobId.slice(0, 8)}]`);
proc.kill('SIGTERM');
setTimeout(() => { if (proc.exitCode === null) proc.kill('SIGKILL'); }, 5000);
@@ -240,11 +267,8 @@ async function runCodex(job, jobId, bin, args, outputPath, filename, meta) {
const sidecar = join(PATHS.images, `${jobId}.metadata.json`);
await writeFile(sidecar, JSON.stringify({ ...meta, codexSessionId: sessionId }, null, 2)).catch(() => {});
job.status = 'complete';
- // Only clear if still ours — a userland cancel that started a
- // newer job could have replaced these references while our
- // harvest was running.
- if (activeProcess === proc) activeProcess = null;
- if (activeJob && activeJob.generationId === jobId) activeJob = null;
+ if (activeProcs.get(jobId) === proc) activeProcs.delete(jobId);
+ activeJobs.delete(jobId);
console.log(`✅ Image generated [${jobId.slice(0, 8)}]: ${filename} (codex)`);
const result = { filename, path: `/data/images/${filename}` };
broadcastSse(job, { type: 'complete', result });
@@ -265,12 +289,9 @@ const finalizeError = (job, jobId, proc, reason) => {
// both paths reach finalizeError. Without this guard, listeners would
// see duplicate 'failed' events.
if (job.status === 'error' || job.status === 'complete') return;
- // Clear activeProcess only if it's still the proc we own. Without
- // this, a single bad codexPath would permanently lock the provider
- // into 409 BUSY (the 'close' handler also clears it on success path).
- if (proc == null || activeProcess === proc) activeProcess = null;
+ if (proc == null || activeProcs.get(jobId) === proc) activeProcs.delete(jobId);
job.status = 'error';
- if (activeJob && activeJob.generationId === jobId) activeJob = null;
+ activeJobs.delete(jobId);
console.log(`❌ codex image generation failed [${jobId.slice(0, 8)}]: ${reason.split('\n')[0]}`);
broadcastSse(job, { type: 'error', error: reason });
imageGenEvents.emit('failed', { generationId: jobId, error: reason });
diff --git a/server/services/imageGen/codex.test.js b/server/services/imageGen/codex.test.js
index 2209f21b8f..ba624620cc 100644
--- a/server/services/imageGen/codex.test.js
+++ b/server/services/imageGen/codex.test.js
@@ -132,11 +132,15 @@ describe('codex provider — generateImage', () => {
await expect(codex.generateImage({ prompt: ' ' })).rejects.toThrow(/Prompt is required/);
});
- it('refuses concurrent generations (returns 409 ALREADY_RUNNING)', async () => {
- await codex.generateImage({ prompt: 'one' });
- await expect(codex.generateImage({ prompt: 'two' })).rejects.toThrow(/already in progress/);
- spawnCalls[0].child.exitCode = 1;
- spawnCalls[0].child.emit('close', 1, null);
+ it('allows concurrent generations (parallel codex lane)', async () => {
+ const a = await codex.generateImage({ prompt: 'one' });
+ const b = await codex.generateImage({ prompt: 'two' });
+ expect(a.jobId).not.toBe(b.jobId);
+ expect(spawnCalls.length).toBe(2);
+ for (const c of spawnCalls) {
+ c.child.exitCode = 1;
+ c.child.emit('close', 1, null);
+ }
await flush();
});
});
diff --git a/server/services/imageGen/index.js b/server/services/imageGen/index.js
index fff661a148..92ca40788d 100644
--- a/server/services/imageGen/index.js
+++ b/server/services/imageGen/index.js
@@ -124,12 +124,14 @@ export const attachSseClient = (jobId, res) => {
};
export const cancel = () => {
- // Each provider enforces its own single-job invariant independently, so
- // both can have a job in flight simultaneously. Cancel them all and
- // return whether anything was actually cancelled — short-circuiting on
- // the first hit would orphan a codex job whenever local is active.
+ // The "stop everything" dispatcher — invoked by routes/imageGen.js's
+ // `/cancel` fallback when no specific jobId or queue entry is targeted.
+ // local has at most one in-flight, codex can have N (parallel lane), so
+ // codex's bulk variant is the right one here. Return whether anything
+ // was actually cancelled — short-circuiting on the first hit would
+ // orphan a codex job whenever local is also active.
const localCancelled = local.cancel();
- const codexCancelled = codex.cancel();
+ const codexCancelled = codex.cancelAll();
return localCancelled || codexCancelled;
};
diff --git a/server/services/imageGenEvents.js b/server/services/imageGenEvents.js
index 2307c0dbd5..65b21e7a35 100644
--- a/server/services/imageGenEvents.js
+++ b/server/services/imageGenEvents.js
@@ -1,3 +1,12 @@
import { EventEmitter } from 'events';
export const imageGenEvents = new EventEmitter();
+// Each in-flight image job attaches ~6 listeners (progress/status/completed/
+// failed + 2 watchdog activity tracers). With CODEX_PARALLEL_MAX = 10 codex
+// renders in flight plus a concurrent local image render, that's 60+ live
+// listeners — well past Node's default cap of 10. Setting it to 0 disables
+// the leak warning entirely; the listener pairs are deterministically detached
+// in runJob's terminate() + final detach() so a real leak would surface as
+// memory growth in pm2 status, not as the warning. 200 leaves headroom for
+// short overlap during job churn.
+imageGenEvents.setMaxListeners(200);
diff --git a/server/services/mediaJobQueue/index.js b/server/services/mediaJobQueue/index.js
index d1678cedcf..634dc6fc4a 100644
--- a/server/services/mediaJobQueue/index.js
+++ b/server/services/mediaJobQueue/index.js
@@ -40,6 +40,9 @@ import {
} from '../../lib/sseUtils.js';
import { videoGenEvents } from '../videoGen/events.js';
import { imageGenEvents } from '../imageGenEvents.js';
+import { getSettings } from '../settings.js';
+
+const isCodexJob = (j) => j.kind === 'image' && j.params?.mode === 'codex';
const JOBS_FILE = join(PATHS.data, 'media-jobs.json');
const COMPLETED_TTL_MS = 24 * 60 * 60 * 1000;
@@ -54,6 +57,12 @@ const watchdogMs = (envValue, defaultMs) => {
};
const WATCHDOG_VIDEO_MS = watchdogMs(process.env.MEDIA_JOB_WATCHDOG_VIDEO_MS, 30 * 60 * 1000);
const WATCHDOG_IMAGE_MS = watchdogMs(process.env.MEDIA_JOB_WATCHDOG_IMAGE_MS, 5 * 60 * 1000);
+// Codex jobs are silent until completion — no per-step output to reset the
+// idle watchdog. With parallel codex renders sharing OpenAI throughput, a
+// single render can easily exceed 5 minutes wall-clock, so the image-kind
+// default trips false positives. 20 minutes covers a slow generation +
+// queueing delay, and is env-overridable when batch limits change.
+const WATCHDOG_CODEX_MS = watchdogMs(process.env.MEDIA_JOB_WATCHDOG_CODEX_MS, 20 * 60 * 1000);
// Returns true if `p` resolves strictly under PATHS.uploads. Shared by
// safeUnlinkUpload (cleanup) and the pre-gen sanitizer (Thread #1 guard).
@@ -105,16 +114,36 @@ function getGenModuleForJob(job) {
export const mediaJobEvents = new EventEmitter();
-// Live state. GPU jobs: at most one in `running` at a time. Codex image jobs
-// (`kind === 'image' && params.mode === 'codex'`) run in a separate concurrent
-// lane (`codexRunning`) because they don't share the MLX runtime. `queue`
-// holds pending jobs in submission order. `archive` holds recently-finished
-// jobs (visible for ~24h via /api/media-jobs?status=completed).
+// GPU lane: serialized — `running` holds at most one job (the MLX runtime can't
+// share VRAM). Codex lane: up to `codexParallelLimit` jobs in `codexRunning[]`
+// since each call shells out to its own external child process. `queue` is
+// shared submission order. `archive` is recently-finished jobs (~24h TTL),
+// including canceled ones so /api/media-jobs?status=canceled and the recent-
+// reel UI can still find them within the 24h window.
const queue = [];
let running = null;
-let codexRunning = null;
+const codexRunning = [];
const archive = [];
+export const CODEX_PARALLEL_MIN = 1;
+export const CODEX_PARALLEL_MAX = 10;
+export const CODEX_PARALLEL_DEFAULT = 1;
+let codexParallelLimit = CODEX_PARALLEL_DEFAULT;
+const clampParallel = (n) => {
+ const x = Number(n);
+ if (!Number.isFinite(x) || x < 1) return CODEX_PARALLEL_DEFAULT;
+ return Math.min(Math.floor(x), CODEX_PARALLEL_MAX);
+};
+export const getCodexParallelLimit = () => codexParallelLimit;
+export function setCodexParallelLimit(n) {
+ codexParallelLimit = clampParallel(n);
+ return codexParallelLimit;
+}
+export async function refreshCodexParallelLimit() {
+ const s = await getSettings();
+ return setCodexParallelLimit(s?.imageGen?.codex?.parallelLimit ?? CODEX_PARALLEL_DEFAULT);
+}
+
// jobId → entry consumed by lib/sseUtils.js#{broadcastSse,attachSseClient,
// closeJobAfterDelay}. Each entry carries `clients: []` and `lastPayload`,
// so we can hand it directly to those helpers. Survives the queued→running
@@ -128,7 +157,8 @@ let initPromise = null;
function findJob(jobId) {
if (running && running.id === jobId) return running;
- if (codexRunning && codexRunning.id === jobId) return codexRunning;
+ const codexHit = codexRunning.find((j) => j.id === jobId);
+ if (codexHit) return codexHit;
const inQueue = queue.find((j) => j.id === jobId);
if (inQueue) return inQueue;
return archive.find((j) => j.id === jobId) || null;
@@ -141,7 +171,7 @@ export function getJob(jobId) {
export function listJobs({ status, kind, owner } = {}) {
const all = [
...(running ? [running] : []),
- ...(codexRunning ? [codexRunning] : []),
+ ...codexRunning,
...queue,
...archive,
];
@@ -176,7 +206,7 @@ async function persistImpl() {
archive.push(...trimmedArchive);
const live = [
...(running ? [running] : []),
- ...(codexRunning ? [codexRunning] : []),
+ ...codexRunning,
...queue,
...archive,
];
@@ -192,6 +222,9 @@ export async function initMediaJobQueue() {
initPromise = (async () => {
// Once-at-boot: subsequent persist() calls assume the data dir exists.
await ensureDir(PATHS.data);
+ // Read the codex parallel limit before the worker starts so the first
+ // drain tick honors the user's configured value, not the default.
+ await refreshCodexParallelLimit().catch(() => {});
const data = await readJSONFile(JOBS_FILE, { jobs: [] });
const persistedJobs = Array.isArray(data?.jobs) ? data.jobs : [];
const restartedFailedIds = [];
@@ -209,8 +242,10 @@ export async function initMediaJobQueue() {
// multipart upload it staged into data/uploads would leak forever.
// safeUnlinkUpload constrains the delete to PATHS.uploads so we
// never delete a file the job merely referenced (gallery image,
- // prior render, etc).
+ // prior render, etc). audioFilePath is the same kind of staged
+ // upload (a2v/voice/video jobs) — needs the same cleanup.
safeUnlinkUpload(j.params?.uploadedTempPath);
+ safeUnlinkUpload(j.params?.audioFilePath);
for (const p of normalizeTempPaths(j.params?.uploadedTempPaths)) {
safeUnlinkUpload(p);
}
@@ -226,7 +261,6 @@ export async function initMediaJobQueue() {
// event report accurate slots. Positions are lane-scoped: Codex image
// jobs and GPU jobs each get their own counter so a queued Codex job
// behind a running GPU job is restored as position 1 (not position 2).
- const isCodexJob = (j) => j.kind === 'image' && j.params?.mode === 'codex';
let codexCounter = 0;
let gpuCounter = 0;
for (const q of queue) {
@@ -280,12 +314,21 @@ function startWorker() {
// flight be picked up immediately on the next 150 ms tick instead of having
// to wait for the entire GPU job to finish first.
function startLaneJob(job, { isCodex }) {
- queue.splice(queue.indexOf(job), 1);
+ // If the job isn't in the queue, it was already promoted (e.g. by a parallel
+ // runJobNow). Skip — promoting again would double-start the job and corrupt
+ // the lane (push it onto codexRunning/running twice). Silently splice(-1)
+ // would also lop the wrong job off the queue.
+ const idx = queue.indexOf(job);
+ if (idx < 0) {
+ console.log(`⚠️ media-job [${job.id.slice(0, 8)}] startLaneJob: already removed from queue, skipping`);
+ return;
+ }
+ queue.splice(idx, 1);
job.status = 'running';
job.startedAt = new Date().toISOString();
job.position = 1;
if (isCodex) {
- codexRunning = job;
+ codexRunning.push(job);
} else {
running = job;
}
@@ -313,10 +356,14 @@ function startLaneJob(job, { isCodex }) {
}
}
if (isCodex) {
- codexRunning = null;
+ const idx = codexRunning.indexOf(job);
+ if (idx >= 0) codexRunning.splice(idx, 1);
} else {
running = null;
}
+ // Archive every terminal job (completed / failed / canceled). The 24h
+ // TTL prune in persistImpl keeps the file from growing unbounded, and
+ // the UI's recent-reel cap (recentLimit) handles in-memory display.
archive.push(job);
recomputeQueuePositions();
persist().catch((e) => console.log(`⚠️ mediaJobQueue persist on ${label} done failed: ${e.message}`));
@@ -325,20 +372,60 @@ function startLaneJob(job, { isCodex }) {
async function drainLoop() {
while (true) {
- // Codex lane: concurrent with GPU lane.
- if (!codexRunning) {
- const nextCodex = queue.find((j) => j.kind === 'image' && j.params?.mode === 'codex');
- if (nextCodex) startLaneJob(nextCodex, { isCodex: true });
+ // Single queue scan, promote eligible codex jobs while there's room and a
+ // GPU job if the lane is open. Stops cleanly on an empty queue.
+ let gpuOpen = !running;
+ let codexSlots = codexParallelLimit - codexRunning.length;
+ if ((gpuOpen || codexSlots > 0) && queue.length > 0) {
+ for (const job of queue.slice()) {
+ if (isCodexJob(job)) {
+ if (codexSlots > 0) {
+ startLaneJob(job, { isCodex: true });
+ codexSlots -= 1;
+ }
+ } else if (gpuOpen) {
+ startLaneJob(job, { isCodex: false });
+ gpuOpen = false;
+ }
+ if (!gpuOpen && codexSlots <= 0) break;
+ }
}
+ await sleep(150);
+ }
+}
- // GPU lane: serialized — at most one video or local-image job at a time.
- if (!running) {
- const nextGpu = queue.find((j) => !(j.kind === 'image' && j.params?.mode === 'codex'));
- if (nextGpu) startLaneJob(nextGpu, { isCodex: false });
- }
+// Drop a job from the archive (e.g. after a successful retry — the old failed
+// row shouldn't keep cluttering the recent-reel UI now that a fresh job has
+// inherited its work). Returns true if removed, false if the id wasn't found
+// or was still live. Live jobs are deliberately left alone — the caller
+// should cancel them first.
+export function removeArchivedJob(jobId) {
+ const idx = archive.findIndex((j) => j.id === jobId);
+ if (idx < 0) return false;
+ archive.splice(idx, 1);
+ // End any SSE clients still attached within the SSE_CLEANUP_DELAY_MS grace
+ // window before dropping the entry — a bare `sseJobs.delete()` here would
+ // leave their HTTP responses dangling because closeJobAfterDelay's pending
+ // timer would find no entry to drain when it fires.
+ const sseEntry = sseJobs.get(jobId);
+ if (sseEntry) {
+ for (const c of sseEntry.clients) c.end();
+ sseJobs.delete(jobId);
+ }
+ persist().catch((e) => console.log(`⚠️ mediaJobQueue persist on archive prune failed: ${e.message}`));
+ return true;
+}
- await sleep(150);
+// "Run now" bypass — start a queued codex job immediately even if the lane is
+// at its limit. GPU jobs are rejected (single MLX runtime would OOM).
+export function runJobNow(jobId) {
+ const job = queue.find((j) => j.id === jobId);
+ if (!job) return { ok: false, code: 'NOT_FOUND', error: 'Job not found in queue' };
+ if (!isCodexJob(job)) {
+ return { ok: false, code: 'NOT_CODEX', error: 'Only Codex image jobs can be run-now; GPU jobs serialize on the MLX runtime' };
}
+ startLaneJob(job, { isCodex: true });
+ return { ok: true, status: 'running' };
}
// Recompute queue positions and notify each waiting SSE client of its new
@@ -347,12 +434,11 @@ async function drainLoop() {
// /:jobId/events would keep showing the position from its original enqueue
// frame even after the line ahead of it cleared.
function recomputeQueuePositions() {
- const isCodexJob = (j) => j.kind === 'image' && j.params?.mode === 'codex';
const codexJobs = queue.filter(isCodexJob);
const gpuJobs = queue.filter((j) => !isCodexJob(j));
codexJobs.forEach((q, i) => {
- const newPosition = i + 1 + (codexRunning ? 1 : 0);
+ const newPosition = i + 1 + codexRunning.length;
if (q.position !== newPosition) {
q.position = newPosition;
const entry = sseJobs.get(q.id);
@@ -528,9 +614,11 @@ async function runJob(job) {
// prose) regularly while it's actually working. Any non-noise line in
// imageGen/videoGen/local.js#handleLine emits 'activity' which resets
// lastActivityAt; only true hangs (process wedged, no output) trip it.
- const idleTimeoutMs = job.kind === 'video'
- ? WATCHDOG_VIDEO_MS * Math.max(1, Number(safeParams.chunks) || 1)
- : WATCHDOG_IMAGE_MS;
+ const idleTimeoutMs = (() => {
+ if (job.kind === 'video') return WATCHDOG_VIDEO_MS * Math.max(1, Number(safeParams.chunks) || 1);
+ if (isCodexJob(job)) return WATCHDOG_CODEX_MS;
+ return WATCHDOG_IMAGE_MS;
+ })();
let lastActivityAt = Date.now();
const onActivity = (e) => {
if (e?.generationId === job.id) lastActivityAt = Date.now();
@@ -565,7 +653,7 @@ async function runJob(job) {
const mod = await getGenModuleForJob(job);
if (job.status !== 'running') return;
console.log(`⏱️ media-job [${job.id.slice(0, 8)}] watchdog fired after ${idleFor}ms idle (limit ${idleTimeoutMs}ms) — marking failed`);
- if (mod?.cancel) mod.cancel();
+ if (mod?.cancel) mod.cancel(job.id);
handlers.failed({ error: `watchdog timeout: no runner output for ${Math.round(idleFor / 1000)}s (limit ${Math.round(idleTimeoutMs / 1000)}s)` });
} catch (err) {
// Don't take down the server over a watchdog tick that couldn't
@@ -595,8 +683,10 @@ async function runJob(job) {
// validation fail). Clean up multipart upload temp files the route
// handed us so they don't leak under data/uploads.
// safeUnlinkUpload constrains the delete to PATHS.uploads as
- // defense-in-depth against corrupted persisted params.
+ // defense-in-depth against corrupted persisted params. audioFilePath
+ // is the same kind of staged upload (a2v jobs) — clean it up too.
await safeUnlinkUpload(job.params?.uploadedTempPath);
+ await safeUnlinkUpload(job.params?.audioFilePath);
for (const p of normalizeTempPaths(job.params?.uploadedTempPaths)) {
await safeUnlinkUpload(p);
}
@@ -627,9 +717,9 @@ export function enqueueJob({ kind, params, owner = null }) {
// same lane occupies slot 1, then same-lane queued jobs follow. Codex
// jobs only count Codex ahead-of-them; GPU jobs only count GPU jobs.
position: (() => {
- const isCodex = kind === 'image' && params?.mode === 'codex';
- const laneQueue = queue.filter((j) => (j.kind === 'image' && j.params?.mode === 'codex') === isCodex);
- return laneQueue.length + (isCodex ? (codexRunning ? 1 : 0) : (running ? 1 : 0)) + 1;
+ const isCodex = isCodexJob({ kind, params });
+ const laneQueue = queue.filter((j) => isCodexJob(j) === isCodex);
+ return laneQueue.length + (isCodex ? codexRunning.length : (running ? 1 : 0)) + 1;
})(),
};
queue.push(job);
@@ -671,19 +761,20 @@ export async function cancelJob(jobId) {
// staged under PATHS.uploads. If we drop the job before it starts,
// runJob never gets a chance to delete it — clean up here so the
// uploads dir doesn't accumulate. safeUnlinkUpload constrains the
- // delete to PATHS.uploads.
+ // delete to PATHS.uploads. audioFilePath is the same kind of staged
+ // upload (a2v/voice/video jobs) and would otherwise leak when the user
+ // cancels before the job starts.
await safeUnlinkUpload(job.params?.uploadedTempPath);
+ await safeUnlinkUpload(job.params?.audioFilePath);
for (const p of normalizeTempPaths(job.params?.uploadedTempPaths)) {
await safeUnlinkUpload(p);
}
job.status = 'canceled';
- // Persist the cancel reason on the job so a late SSE reconnect (after
- // the live SSE entry was cleaned up) can synthesize the same terminal
- // payload from the archived state — without this, attachSseClient's
- // post-cleanup terminal frame would just say "Canceled" and lose the
- // more specific "Canceled before start" reason we just broadcast.
job.error = 'Canceled before start';
job.completedAt = new Date().toISOString();
+ // Archive so /api/media-jobs?status=canceled and the recent-reel UI
+ // can still find it within the 24h TTL. Mirrors the running-cancel path
+ // in startLaneJob's terminal handler.
archive.push(job);
// Removing a queued job shifts everyone behind it up one slot. Recompute
// + broadcast so clients still attached to those SSE streams see the new
@@ -700,16 +791,16 @@ export async function cancelJob(jobId) {
console.log(`🛑 media-job [${jobId.slice(0, 8)}] canceled (was queued)`);
return { ok: true, status: 'canceled' };
}
- // Check both the GPU slot and the Codex slot for a running-cancel.
- const runningJob = (running?.id === jobId ? running : null) ?? (codexRunning?.id === jobId ? codexRunning : null);
+ // Cancel-while-running — check the GPU slot and every parallel codex slot.
+ const runningJob = (running?.id === jobId ? running : null)
+ ?? codexRunning.find((j) => j.id === jobId)
+ ?? null;
if (runningJob) {
- // Flag the job so the dispatcher's `failed` handler treats the SIGTERM-
- // induced failure as `canceled` rather than `failed`. Without this the
- // job would land in archive with status='failed' and listing by
- // status='canceled' would be empty for running cancels.
+ // cancelRequested flips the dispatcher's `failed` handler into the
+ // `canceled` branch instead of marking it failed.
runningJob.cancelRequested = true;
const mod = await getGenModuleForJob(runningJob);
- if (mod?.cancel) mod.cancel();
+ if (mod?.cancel) mod.cancel(jobId);
console.log(`🛑 media-job [${jobId.slice(0, 8)}] cancel signal sent (was running)`);
return { ok: true, status: 'canceling' };
}
@@ -785,11 +876,16 @@ function sleep(ms) {
export function __resetForTests() {
queue.length = 0;
running = null;
- codexRunning = null;
+ // `codexRunning` is a const array — clear it in place rather than reassigning,
+ // which would throw TypeError and break `findJob()` (.find on null).
+ codexRunning.length = 0;
archive.length = 0;
sseJobs.clear();
workerStarted = false;
initPromise = null;
+ // Reset the lane limit too — a test that called setCodexParallelLimit(N)
+ // otherwise leaks N into subsequent tests and makes ordering matter.
+ codexParallelLimit = CODEX_PARALLEL_DEFAULT;
// Reset the persist chain so a leftover rejection from a previous test's
// ENOENT writes doesn't poison subsequent persist() calls.
persistChain = Promise.resolve();
diff --git a/server/services/mediaJobQueue/index.test.js b/server/services/mediaJobQueue/index.test.js
index e3723978ec..a25565c488 100644
--- a/server/services/mediaJobQueue/index.test.js
+++ b/server/services/mediaJobQueue/index.test.js
@@ -118,7 +118,7 @@ describe('mediaJobQueue', () => {
expect(mediaJobQueue.listJobs({ status: 'running' })).toHaveLength(1);
});
- it('cancelQueuedJobs drops every queued job, leaves running ones alone', async () => {
+ it('cancelQueuedJobs cancels every queued job, leaves running ones alone', async () => {
// Block the worker so subsequent enqueues stay queued.
let resolveBlocker;
stubs.generateVideo.mockImplementation(() => new Promise((r) => { resolveBlocker = r; }));
@@ -130,6 +130,8 @@ describe('mediaJobQueue', () => {
await flush();
// No filter: every queued job (a, b, c) cancels; running blocker is untouched.
+ // Canceled jobs are archived (not dropped) so they stay findable for the
+ // recent-reel UI and /api/media-jobs?status=canceled within the 24h TTL.
const r = await mediaJobQueue.cancelQueuedJobs();
expect(r.canceled).toBe(3);
expect(mediaJobQueue.getJob(a.jobId).status).toBe('canceled');
@@ -153,6 +155,7 @@ describe('mediaJobQueue', () => {
const r = await mediaJobQueue.cancelQueuedJobs({ kind: 'video' });
expect(r.canceled).toBe(1);
+ // Canceled jobs are archived (not dropped) — `v` is findable with status 'canceled'.
expect(mediaJobQueue.getJob(v.jobId).status).toBe('canceled');
// Image queued job is left in the queue (still 'queued', not canceled).
expect(mediaJobQueue.getJob(i.jobId).status).toBe('queued');
@@ -178,8 +181,11 @@ describe('mediaJobQueue', () => {
const result = await mediaJobQueue.cancelJob(target.jobId);
expect(result.ok).toBe(true);
expect(result.status).toBe('canceled');
- const job = mediaJobQueue.getJob(target.jobId);
- expect(job.status).toBe('canceled');
+ // Canceled jobs are archived (not dropped) so /api/media-jobs?status=canceled
+ // and the recent-reel UI can find them within the 24h TTL.
+ const archived = mediaJobQueue.getJob(target.jobId);
+ expect(archived).not.toBeNull();
+ expect(archived.status).toBe('canceled');
// Unblock the first one for cleanup.
videoGenEvents.emit('failed', { generationId: blocker.jobId, error: 'cleanup' });
@@ -563,6 +569,60 @@ describe('Codex lane', () => {
imageGenEvents.emit('failed', { generationId: codex2.jobId, error: 'cleanup' });
await flush();
});
+
+ it('runJobNow promotes a queued Codex job past the parallel limit', async () => {
+ // Pin the codex lane at limit=1 and saturate it with a running Codex job
+ // so the second one lands in the queue.
+ mediaJobQueue.setCodexParallelLimit(1);
+ stubs.generateImageCodex.mockImplementation(() => new Promise(() => {}));
+
+ const codex1 = mediaJobQueue.enqueueJob({
+ kind: 'image', params: { prompt: 'codex first', mode: 'codex' },
+ });
+ await waitFor(() => stubs.generateImageCodex.mock.calls.length === 1);
+
+ const codex2 = mediaJobQueue.enqueueJob({
+ kind: 'image', params: { prompt: 'codex second', mode: 'codex' },
+ });
+ expect(mediaJobQueue.getJob(codex2.jobId).status).toBe('queued');
+
+ const result = mediaJobQueue.runJobNow(codex2.jobId);
+ expect(result.ok).toBe(true);
+ expect(result.status).toBe('running');
+ // Both Codex jobs are now in-flight (lane size 2, above the limit of 1).
+ await waitFor(() => stubs.generateImageCodex.mock.calls.length === 2);
+ expect(mediaJobQueue.getJob(codex2.jobId).status).toBe('running');
+
+ imageGenEvents.emit('failed', { generationId: codex1.jobId, error: 'cleanup' });
+ imageGenEvents.emit('failed', { generationId: codex2.jobId, error: 'cleanup' });
+ await flush();
+ });
+
+ it('runJobNow rejects GPU (non-Codex) queued jobs with NOT_CODEX', async () => {
+ // Block the GPU lane with one running job and queue a second so we have a
+ // queued GPU job to attempt run-now on.
+ stubs.generateVideo.mockImplementation(() => new Promise(() => {}));
+ const v1 = mediaJobQueue.enqueueJob({ kind: 'video', params: { prompt: 'first' } });
+ await waitFor(() => stubs.generateVideo.mock.calls.length === 1);
+ const v2 = mediaJobQueue.enqueueJob({ kind: 'video', params: { prompt: 'second' } });
+ expect(mediaJobQueue.getJob(v2.jobId).status).toBe('queued');
+
+ const result = mediaJobQueue.runJobNow(v2.jobId);
+ expect(result.ok).toBe(false);
+ expect(result.code).toBe('NOT_CODEX');
+ // The queued GPU job stays queued — single MLX runtime can't double up.
+ expect(mediaJobQueue.getJob(v2.jobId).status).toBe('queued');
+
+ videoGenEvents.emit('failed', { generationId: v1.jobId, error: 'cleanup' });
+ videoGenEvents.emit('failed', { generationId: v2.jobId, error: 'cleanup' });
+ await flush();
+ });
+
+ it('runJobNow returns NOT_FOUND for an unknown id', () => {
+ const result = mediaJobQueue.runJobNow('does-not-exist');
+ expect(result.ok).toBe(false);
+ expect(result.code).toBe('NOT_FOUND');
+ });
});
describe('audioFilePath sanitization', () => {
diff --git a/server/services/pipeline/visualStages.js b/server/services/pipeline/visualStages.js
index 58e9321046..a038aef424 100644
--- a/server/services/pipeline/visualStages.js
+++ b/server/services/pipeline/visualStages.js
@@ -17,89 +17,197 @@ import { enqueueJob } from '../mediaJobQueue/index.js';
import { getSettings } from '../settings.js';
import { getSeries } from './series.js';
import { getIssue, VISUAL_STAGE_IDS } from './issues.js';
+import { getWorld } from '../worldBuilder.js';
+import { ServerError } from '../../lib/errorHandler.js';
import { buildScenePrompt, buildSettingByKey, matchSceneSetting } from '../../lib/scenePrompt.js';
+import { composeStyledPrompt } from '../../lib/composeStyledPrompt.js';
const SUPPORTED_MODES = new Set(['local', 'codex']);
-// Build a pipeline image-gen prompt; delegates to the shared `buildScenePrompt`
-// so Pipeline + Writers Room renders agree byte-for-byte.
-//
-// Pipeline storyboard scenes don't yet carry a per-scene `characters[]`
-// list — once the scene extractor (PLAN item 5) populates it, callers will
-// pass `matchedCharacters` to selectively inject the cast. Until then we
-// inject none, so a 30-character series doesn't pollute every render with
-// the entire bible.
-export function composeVisualPrompt({ series, description, slugline = '', extraStyle = '', settingByKey = null, matchedCharacters = [] }) {
- const worldStyle = [series?.styleNotes, extraStyle].map((s) => (s || '').trim()).filter(Boolean).join(', ');
+const stackStyle = (series, extraStyle) =>
+ [series?.styleNotes, extraStyle].map((s) => (s || '').trim()).filter(Boolean).join(', ');
+
+const applyWorldStyle = (prompt, world) => {
+ if (!world) return prompt;
+ return composeStyledPrompt(prompt, '', { prompt: world.stylePrompt, negativePrompt: '' }).prompt;
+};
+
+const resolveMode = (options, settings) => {
+ if (SUPPORTED_MODES.has(options.mode)) return options.mode;
+ const settingsMode = settings?.imageGen?.mode;
+ return SUPPORTED_MODES.has(settingsMode) ? settingsMode : 'local';
+};
+
+const loadBibleContext = async (issueId) => {
+ const issueChain = (async () => {
+ const issue = await getIssue(issueId);
+ const series = await getSeries(issue.seriesId);
+ const world = series.worldId ? await getWorld(series.worldId).catch(() => null) : null;
+ return { issue, series, world };
+ })();
+ const [chain, settings] = await Promise.all([issueChain, getSettings()]);
+ return { ...chain, settings };
+};
+
+const enqueueImageJob = ({ prompt, world, settings, options, mode, owner, logLine }) => {
+ // Merge user + world negatives — mirrors composeStyledPrompt's preset
+ // negative handling so the world's global negative-prompt terms stay in
+ // effect even when the caller supplies their own additions. Deduplicated
+ // by token so a user repeating a world negative doesn't double-weight it.
+ const userNeg = (options.negativePrompt || '').trim();
+ const worldNeg = (world?.negativePrompt || '').trim();
+ const negativeTokens = [userNeg, worldNeg]
+ .flatMap((s) => s.split(',').map((t) => t.trim()).filter(Boolean));
+ const negativePrompt = [...new Set(negativeTokens)].join(', ') || undefined;
+ const baseParams = {
+ prompt,
+ negativePrompt,
+ width: options.width,
+ height: options.height,
+ steps: options.steps,
+ guidance: options.guidance ?? options.cfgScale,
+ cfgScale: options.cfgScale,
+ };
+ const params = mode === 'codex'
+ ? { mode: 'codex', codexPath: settings.imageGen?.codex?.codexPath, model: settings.imageGen?.codex?.model, ...baseParams }
+ : { pythonPath: settings.imageGen?.local?.pythonPath || null, modelId: options.modelId, ...baseParams };
+ const { jobId } = enqueueJob({ kind: 'image', params, owner });
+ console.log(`${logLine} mode=${mode} jobId=${jobId.slice(0, 8)}`);
+ return jobId;
+};
+
+export function composeVisualPrompt({ series, description, slugline = '', extraStyle = '', settingByKey = null, matchedCharacters = [], world = null }) {
const map = settingByKey || buildSettingByKey(series?.settings);
- return buildScenePrompt(
+ const scenePrompt = buildScenePrompt(
series?.name || '',
{ visualPrompt: description || '', slugline },
matchedCharacters,
- worldStyle,
+ stackStyle(series, extraStyle),
matchSceneSetting(slugline, map),
);
+ return applyWorldStyle(scenePrompt, world);
+}
+
+export function composeComicPagePrompt({ series, world, page, pageNumber, extraStyle = '' }) {
+ const panels = Array.isArray(page?.panels) ? page.panels : [];
+ if (panels.length === 0) return '';
+
+ // Append a sentence-terminator unless the source text already ends in one —
+ // prose extracted from a script often carries its own `.`, `!`, or `?`, and
+ // double-punctuating like "...sunstreaming in.." is noisy in prompts. The
+ // optional trailing `"` covers the dialogue/caption case where we wrap the
+ // text in quotes — `KESSA: "...away."` should NOT become `KESSA: "...away.".`.
+ const endPunct = (s) => /[.!?]"?$/.test(s) ? s : `${s}.`;
+
+ const panelLines = panels.map((p, i) => {
+ const idx = i + 1;
+ const desc = (p.description || '').trim() || 'continuation of previous beat';
+ const parts = [`Panel ${idx}: ${endPunct(desc)}`];
+ if (p.caption && p.caption.trim()) parts.push(`Caption: "${endPunct(p.caption.trim())}"`);
+ if (Array.isArray(p.dialogue) && p.dialogue.length > 0) {
+ // Trim first so whitespace-only character / line fields don't pass the
+ // truthy guard and emit malformed `: ""` entries. Drop dialogue rows
+ // whose line is empty — they have nothing for the artist to render.
+ const dlg = p.dialogue
+ .map((d) => {
+ const character = (d.character || '').trim() || 'CHAR';
+ const line = (d.line || '').trim();
+ return line ? `${character}: "${line}"` : null;
+ })
+ .filter(Boolean)
+ .join(' / ');
+ if (dlg) parts.push(`Dialogue: ${endPunct(dlg)}`);
+ }
+ if (p.sfx && p.sfx.trim()) parts.push(`SFX: ${endPunct(p.sfx.trim())}`);
+ return parts.join(' ');
+ });
+
+ const styleStack = stackStyle(series, extraStyle);
+ const styleClause = styleStack ? ` Art style: ${styleStack}.` : '';
+ const seriesClause = series?.name ? ` from the series "${series.name}"` : '';
+
+ const layout = `A single full printable comic book page${seriesClause}, page ${pageNumber}. Render a balanced multi-panel comic page layout with ${panels.length} clearly bordered panel${panels.length === 1 ? '' : 's'} arranged for left-to-right, top-to-bottom reading. Include lettered speech balloons for dialogue, rectangular narration captions, and stylized SFX where indicated. Each panel must be visually distinct, with consistent character designs across panels.${styleClause}`;
+
+ return applyWorldStyle(`${layout}\n\n${panelLines.join('\n\n')}`, world);
}
/**
- * Enqueue one image render for a pipeline issue's visual stage. The caller
- * is responsible for recording the returned jobId on the issue's stage
- * artifact list (e.g. stages.comicPages.pages[i].panels[j].imageJobId).
+ * 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`.
*
- * `options.description` — required, the panel/scene subject text.
- * `options.modelId`, `options.width`, `options.height`, `options.steps`,
- * `options.guidance`, `options.negativePrompt` — optional overrides.
+ * Returns { jobId, mode, prompt, pageIndex }.
+ */
+export async function enqueueVisualComicPage(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 { issue, settings, series, world } = await loadBibleContext(issueId);
+ 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',
+ });
+ }
+ if (!Array.isArray(page.panels) || page.panels.length === 0) {
+ throw new ServerError('page has no panels — add at least one panel description before rendering', {
+ status: 400, code: 'PIPELINE_COMIC_PAGE_NO_PANELS',
+ });
+ }
+
+ const mode = resolveMode(options, settings);
+ // composeComicPagePrompt only returns '' when panels.length === 0, which is
+ // already rejected above. The "(continuation of previous beat)" placeholder
+ // covers panels with no description, so the prompt is non-empty by here.
+ const prompt = composeComicPagePrompt({
+ series, world, page, pageNumber: pageIndex + 1, extraStyle: options.extraStyle,
+ });
+
+ const jobId = enqueueImageJob({
+ prompt, world, settings, options, mode,
+ owner: `pipeline:${issueId}:comicPages:page${pageIndex}`,
+ logLine: `📄 Pipeline comic page — issue=${issueId.slice(0, 8)} page=${pageIndex + 1} panels=${page.panels.length}`,
+ });
+ return { jobId, mode, prompt, pageIndex };
+}
+
+/**
+ * Enqueue one image render for a pipeline issue's visual stage. The caller
+ * records the returned jobId on the issue's stage artifact list
+ * (e.g. stages.comicPages.pages[i].panels[j].imageJobId).
*
* Returns { jobId, mode, prompt }.
*/
export async function enqueueVisualImage(issueId, stageId, options = {}) {
if (!VISUAL_STAGE_IDS.includes(stageId)) {
- throw new Error(`enqueueVisualImage: not a visual stage: ${stageId}`);
+ throw new ServerError(`not a visual stage: ${stageId}`, {
+ status: 400, code: 'PIPELINE_VISUAL_BAD_STAGE',
+ });
}
- const [issue, settings] = await Promise.all([getIssue(issueId), getSettings()]);
- const series = await getSeries(issue.seriesId);
-
- const mode = SUPPORTED_MODES.has(options.mode) ? options.mode
- : (SUPPORTED_MODES.has(settings.imageGen?.mode) ? settings.imageGen.mode : 'local');
-
+ const { settings, series, world } = await loadBibleContext(issueId);
+ const mode = resolveMode(options, settings);
const prompt = composeVisualPrompt({
series,
description: options.description,
slugline: options.slugline,
extraStyle: options.extraStyle,
+ world,
});
- if (!prompt) throw new Error('enqueueVisualImage: prompt is empty (no description, no style)');
-
- const baseParams = {
- prompt,
- negativePrompt: options.negativePrompt || undefined,
- width: options.width,
- height: options.height,
- steps: options.steps,
- guidance: options.guidance ?? options.cfgScale,
- cfgScale: options.cfgScale,
- };
-
- const owner = `pipeline:${issueId}:${stageId}`;
-
- if (mode === 'codex') {
- const c = settings.imageGen?.codex || {};
- const { jobId } = enqueueJob({
- kind: 'image',
- params: { mode: 'codex', codexPath: c.codexPath, model: c.model, ...baseParams },
- owner,
+ if (!prompt) {
+ throw new ServerError('visual prompt is empty (no description, no style)', {
+ status: 400, code: 'PIPELINE_VISUAL_EMPTY_PROMPT',
});
- console.log(`🎬 Pipeline visual — issue=${issueId.slice(0, 8)} stage=${stageId} mode=codex jobId=${jobId.slice(0, 8)}`);
- return { jobId, mode, prompt };
}
- // mode === 'local'
- const pythonPath = settings.imageGen?.local?.pythonPath || null;
- const { jobId } = enqueueJob({
- kind: 'image',
- params: { pythonPath, modelId: options.modelId, ...baseParams },
- owner,
+ const jobId = enqueueImageJob({
+ prompt, world, settings, options, mode,
+ owner: `pipeline:${issueId}:${stageId}`,
+ logLine: `🎬 Pipeline visual — issue=${issueId.slice(0, 8)} stage=${stageId}`,
});
- console.log(`🎬 Pipeline visual — issue=${issueId.slice(0, 8)} stage=${stageId} mode=local jobId=${jobId.slice(0, 8)}`);
return { jobId, mode, prompt };
}
diff --git a/server/services/pipeline/visualStages.test.js b/server/services/pipeline/visualStages.test.js
new file mode 100644
index 0000000000..4492541e63
--- /dev/null
+++ b/server/services/pipeline/visualStages.test.js
@@ -0,0 +1,111 @@
+import { describe, expect, it } from 'vitest';
+import { composeComicPagePrompt } from './visualStages.js';
+
+const SERIES = {
+ name: 'Bone Walker',
+ styleNotes: 'gritty ink-wash, muted earthtones, heavy contrast',
+};
+
+const PAGE = {
+ panels: [
+ {
+ description: 'Wide establishing shot inside a fossilized rib, morning sun streaming in.',
+ caption: 'The titan died nine thousand years ago.',
+ dialogue: [],
+ sfx: '',
+ },
+ {
+ description: 'Tight close-up — a beetle picks its way along polished bone.',
+ caption: 'No one has told the rib.',
+ dialogue: [{ character: 'KESSA', line: "If you had any sense, you'd stow away." }],
+ sfx: 'fmp',
+ },
+ ],
+};
+
+describe('composeComicPagePrompt', () => {
+ it('returns empty string when page has no panels', () => {
+ expect(composeComicPagePrompt({ series: SERIES, page: { panels: [] }, pageNumber: 1 })).toBe('');
+ expect(composeComicPagePrompt({ series: SERIES, page: null, pageNumber: 1 })).toBe('');
+ });
+
+ it('builds a multi-panel page layout prompt with series name, style, panel count, and per-panel breakdown', () => {
+ const prompt = composeComicPagePrompt({ series: SERIES, page: PAGE, pageNumber: 1 });
+ expect(prompt).toMatch(/single full printable comic book page/i);
+ expect(prompt).toMatch(/"Bone Walker"/);
+ expect(prompt).toMatch(/page 1/i);
+ expect(prompt).toMatch(/2 clearly bordered panels/);
+ expect(prompt).toMatch(/Art style: gritty ink-wash/);
+ expect(prompt).toMatch(/Panel 1: Wide establishing shot/);
+ expect(prompt).toMatch(/Panel 2: Tight close-up/);
+ expect(prompt).toMatch(/Caption: "The titan died/);
+ expect(prompt).toMatch(/Dialogue: KESSA: "If you had any sense/);
+ expect(prompt).toMatch(/SFX: fmp/);
+ });
+
+ it('uses singular "panel" wording for a one-panel splash page', () => {
+ const splash = { panels: [{ description: 'Hero stands silhouetted against the sunrise.' }] };
+ const prompt = composeComicPagePrompt({ series: SERIES, page: splash, pageNumber: 5 });
+ expect(prompt).toMatch(/1 clearly bordered panel\b/);
+ expect(prompt).not.toMatch(/clearly bordered panels\b/);
+ });
+
+ it('skips empty caption / dialogue / sfx fields without leaving dangling labels', () => {
+ const sparse = {
+ panels: [
+ { description: 'A solitary frame.', caption: '', dialogue: [], sfx: '' },
+ ],
+ };
+ const prompt = composeComicPagePrompt({ series: SERIES, page: sparse, pageNumber: 1 });
+ expect(prompt).toMatch(/Panel 1: A solitary frame\./);
+ expect(prompt).not.toMatch(/Caption:/);
+ expect(prompt).not.toMatch(/Dialogue:/);
+ expect(prompt).not.toMatch(/SFX:/);
+ });
+
+ it('falls back to "continuation of previous beat" when a panel has no description', () => {
+ const noDesc = { panels: [{ description: '' }] };
+ const prompt = composeComicPagePrompt({ series: SERIES, page: noDesc, pageNumber: 1 });
+ expect(prompt).toMatch(/Panel 1: continuation of previous beat\./);
+ });
+
+ it('prepends world.stylePrompt when a world is provided', () => {
+ const world = { stylePrompt: 'cinematic ink illustration, dramatic lighting', negativePrompt: '' };
+ const prompt = composeComicPagePrompt({ series: SERIES, world, page: PAGE, pageNumber: 1 });
+ expect(prompt).toMatch(/cinematic ink illustration/);
+ });
+
+ it('appends extraStyle into the Art style clause', () => {
+ const prompt = composeComicPagePrompt({
+ series: SERIES,
+ page: PAGE,
+ pageNumber: 1,
+ extraStyle: 'aged paper texture',
+ });
+ expect(prompt).toMatch(/Art style: gritty ink-wash, muted earthtones, heavy contrast, aged paper texture/);
+ });
+
+ it('does not double-punctuate when description / caption / sfx already end in . ! ?', () => {
+ const page = {
+ panels: [{
+ description: 'Wide shot with morning sun streaming in.',
+ caption: 'No one has told the rib.',
+ dialogue: [{ character: 'KESSA', line: 'Move it!' }],
+ sfx: 'CRASH!',
+ }],
+ };
+ const prompt = composeComicPagePrompt({ series: SERIES, page, pageNumber: 1 });
+ // Each pre-terminated segment should keep its terminator, never `..` or `!.`.
+ expect(prompt).not.toMatch(/streaming in\.\./);
+ expect(prompt).not.toMatch(/has told the rib\.\."/);
+ expect(prompt).not.toMatch(/Move it!\."/);
+ expect(prompt).not.toMatch(/CRASH!\./);
+ });
+
+ it('still appends a terminator when the field has no sentence-end punctuation', () => {
+ const page = { panels: [{ description: 'A solitary frame', sfx: 'fmp' }] };
+ const prompt = composeComicPagePrompt({ series: SERIES, page, pageNumber: 1 });
+ expect(prompt).toMatch(/Panel 1: A solitary frame\./);
+ expect(prompt).toMatch(/SFX: fmp\./);
+ });
+});
diff --git a/server/services/videoGen/events.js b/server/services/videoGen/events.js
index 20b8fc02cf..bf2c009495 100644
--- a/server/services/videoGen/events.js
+++ b/server/services/videoGen/events.js
@@ -3,3 +3,7 @@ import { EventEmitter } from 'events';
// Bridge for video gen progress — server/services/socket.js subscribes
// and forwards as Socket.IO events `video-gen:started|progress|completed|failed`.
export const videoGenEvents = new EventEmitter();
+// Video runs serially (one MLX GPU job at a time) so the listener count is
+// bounded, but raise the cap anyway so short job-churn windows don't trip
+// the warning. See imageGenEvents.js for the longer rationale.
+videoGenEvents.setMaxListeners(50);