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: merged Comic Pages tab + Codex transcript extractor + per-issue LLM picker

[._.]/ Adam Eivy586810377a82
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index bf20f0a4ac..170a35024d 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -2,6 +2,34 @@
## Added
+- **Pipeline Issue — merged Comic Pages tab.** Comic Script + Comic Pages are
+ now one tab labeled *Comic Pages*. Each row is a per-page editable markdown
+ textarea on the left and the rendered full-page comic image on the right.
+ Generating from prose auto-splits the script into pages. Panels are still
+ parsed internally so the image prompt stays high-quality, but the
+ panel-level UI is gone — the user only sees pages. A new
+ `PATCH /pipeline/issues/:id/stages/comicPages/pages/:pageIndex` endpoint
+ accepts an edited `rawText` and re-parses panels. The comic-script parser
+ now emits a per-page `rawText` slice; legacy pages without one fall back to
+ reconstructing markdown from their structured panels, so existing series
+ don't lose data.
+
+- **LLM provider+model picker on issue pages.** The `SeriesLlmPicker` from
+ the arc header is now also rendered at the top of every issue stage page
+ (idea / prose / comic / TV script / etc.), bound to the same `series.llm`
+ field. Idea generation, prose generation, comic-script generation, and
+ auto-run-text all thread the choice into their `providerId` / `model`
+ payloads. Changing the provider on one page updates it everywhere.
+
+- **Codex CLI assistant-reply extractor.** New `server/lib/codexAssistantExtract.js`
+ carves out just the assistant reply from Codex's full session transcript
+ (banner + metadata + echoed prompt + `codex\n<reply>` + `tokens used: ...`
+ footer). Applied unconditionally in `stageRunner.js` — idempotent for
+ non-Codex providers. Text stages no longer ship the whole transcript in
+ their output; JSON stages get a cleaner walker input as a side benefit.
+ Fixes prior runs where comicScript / prose / idea outputs captured the
+ banner + echoed prompt alongside the real response.
+
- **Pipeline Issue — answer-and-refine flow for beat-sheet open questions.**
The idea stage prompt now tells the LLM to commit to decisive choices
rather than hedging — `## Open questions` is OPTIONAL and only used when
diff --git a/client/src/components/pipeline/ArcCanvas.jsx b/client/src/components/pipeline/ArcCanvas.jsx
index 8328f163a9..3dcfc17773 100644
--- a/client/src/components/pipeline/ArcCanvas.jsx
+++ b/client/src/components/pipeline/ArcCanvas.jsx
@@ -23,7 +23,7 @@
* responsive without a refetch.
*/
-import { useEffect, useMemo, useState } from 'react';
+import { useMemo, useState } from 'react';
import { Link } from 'react-router-dom';
import {
Plus, Trash2, Loader2, Sparkles, ShieldCheck, ChevronRight, ChevronDown,
@@ -38,8 +38,8 @@ import {
generatePipelineArcOverview, generatePipelineSeasonEpisodes, verifyPipelineArc,
resolvePipelineArcIssues,
listPipelineIssues, updatePipelineSeries,
- getProviders,
} from '../../services/api';
+import SeriesLlmPicker from './SeriesLlmPicker';
const ISSUE_STATUS_COLORS = {
draft: 'text-gray-400 bg-gray-700/30',
@@ -115,17 +115,6 @@ function ArcHeader({ series, onSeriesUpdate, onIssuesUpdate, onFlushPending }) {
// Which finding indexes have an in-flight per-finding resolve. Lets the row
// show its own spinner without blocking the rest of the page.
const [resolvingIdx, setResolvingIdx] = useState(new Set());
- const [providers, setProviders] = useState([]);
- const [activeProviderId, setActiveProviderId] = useState(null);
-
- useEffect(() => {
- getProviders()
- .then((data) => {
- setProviders(data?.providers || []);
- setActiveProviderId(data?.activeProvider || null);
- })
- .catch(() => { /* dropdowns just show "Active provider" fallback */ });
- }, []);
const llmOverride = useMemo(() => ({
providerOverride: series.llm?.provider || undefined,
@@ -221,58 +210,16 @@ function ArcHeader({ series, onSeriesUpdate, onIssuesUpdate, onFlushPending }) {
const generateBtnLabel = arc ? 'Regenerate arc' : 'Generate arc';
- const providerLabel = (id) => providers.find((p) => p.id === id)?.name || id || '—';
- const providerModels = useMemo(() => {
- const p = providers.find((x) => x.id === series.llm?.provider)
- || providers.find((x) => x.id === activeProviderId);
- return p?.models || [];
- }, [providers, activeProviderId, series.llm?.provider]);
-
- // Save on change rather than waiting for a "Save" button — verify / resolve /
- // episode-gen all read series.llm at request time, so a delayed save would
- // run a generation against a stale choice.
- const saveLlm = async (next) => {
- const updated = await updatePipelineSeries(series.id, { llm: next }).catch((err) => {
- toast.error(err.message || 'Failed to save provider choice');
- return null;
- });
- if (updated) onSeriesUpdate(updated);
- };
-
return (
<section className="bg-port-card border border-port-border rounded-lg p-4 space-y-3">
<div className="flex items-center justify-between flex-wrap gap-2">
<h2 className="text-xs uppercase tracking-wider text-gray-500">Series arc</h2>
<div className="flex items-center gap-2 flex-wrap">
- {/* Bind to `?? ''` (NOT `|| activeProviderId || ''`) — unset must
- select the "Active provider" empty option, otherwise the dropdown
- would silently pin the active provider as if the user had chosen it. */}
- <select
- value={series.llm?.provider ?? ''}
- onChange={(e) => saveLlm({ provider: e.target.value || null, model: null })}
+ <SeriesLlmPicker
+ series={series}
+ onSeriesUpdate={onSeriesUpdate}
disabled={!!running}
- title="AI provider for arc generate / verify / resolve / episode generation"
- className="bg-port-bg border border-port-border rounded px-2 py-1.5 text-white text-xs disabled:opacity-40"
- >
- <option value="">Active provider ({providerLabel(activeProviderId)})</option>
- {providers.map((p) => (
- <option key={p.id} value={p.id}>{p.name}</option>
- ))}
- </select>
- <select
- value={series.llm?.model || ''}
- onChange={(e) => saveLlm({ ...(series.llm || {}), model: e.target.value || null })}
- disabled={!!running || providerModels.length === 0}
- title="Model for arc operations"
- className="bg-port-bg border border-port-border rounded px-2 py-1.5 text-white text-xs disabled:opacity-40 max-w-[180px]"
- >
- <option value="">Default model</option>
- {providerModels.map((m) => {
- const id = typeof m === 'string' ? m : m.id;
- const label = typeof m === 'string' ? m : (m.name || m.id);
- return <option key={id} value={id}>{label}</option>;
- })}
- </select>
+ />
<button
type="button"
onClick={runGenerate}
diff --git a/client/src/components/pipeline/SeriesLlmPicker.jsx b/client/src/components/pipeline/SeriesLlmPicker.jsx
new file mode 100644
index 0000000000..8f292bacf7
--- /dev/null
+++ b/client/src/components/pipeline/SeriesLlmPicker.jsx
@@ -0,0 +1,71 @@
+import { useEffect, useMemo, useState } from 'react';
+import { getProviders, updatePipelineSeries } from '../../services/api';
+import toast from '../ui/Toast';
+
+/**
+ * Two-select provider+model picker bound to `series.llm`. Saves on change so
+ * the choice applies to every subsequent LLM call on this series (arc, idea,
+ * prose, scripts, auto-run). Mirrors the World Builder `world.llm` picker.
+ */
+export default function SeriesLlmPicker({ series, onSeriesUpdate, disabled = false }) {
+ const [providers, setProviders] = useState([]);
+ const [activeProviderId, setActiveProviderId] = useState(null);
+
+ useEffect(() => {
+ getProviders()
+ .then((data) => {
+ setProviders(data?.providers || []);
+ setActiveProviderId(data?.activeProvider || null);
+ })
+ .catch(() => { /* dropdowns just show the "Active provider" fallback */ });
+ }, []);
+
+ const providerLabel = (id) => providers.find((p) => p.id === id)?.name || id || '—';
+ const providerModels = useMemo(() => {
+ const p = providers.find((x) => x.id === series.llm?.provider)
+ || providers.find((x) => x.id === activeProviderId);
+ return p?.models || [];
+ }, [providers, activeProviderId, series.llm?.provider]);
+
+ const saveLlm = async (next) => {
+ const updated = await updatePipelineSeries(series.id, { llm: next }).catch((err) => {
+ toast.error(err.message || 'Failed to save provider choice');
+ return null;
+ });
+ if (updated) onSeriesUpdate(updated);
+ };
+
+ return (
+ <div className="flex items-center gap-2 flex-wrap">
+ {/* Bind to `?? ''` (NOT `|| activeProviderId || ''`) — unset must select
+ the "Active provider" empty option, otherwise the dropdown would
+ silently pin the active provider as if the user had chosen it. */}
+ <select
+ value={series.llm?.provider ?? ''}
+ onChange={(e) => saveLlm({ provider: e.target.value || null, model: null })}
+ disabled={disabled}
+ title="AI provider — applies to every LLM operation on this series"
+ className="bg-port-bg border border-port-border rounded px-2 py-1.5 text-white text-xs disabled:opacity-40"
+ >
+ <option value="">Active provider ({providerLabel(activeProviderId)})</option>
+ {providers.map((p) => (
+ <option key={p.id} value={p.id}>{p.name}</option>
+ ))}
+ </select>
+ <select
+ value={series.llm?.model || ''}
+ onChange={(e) => saveLlm({ ...(series.llm || {}), model: e.target.value || null })}
+ disabled={disabled || providerModels.length === 0}
+ title="Model"
+ className="bg-port-bg border border-port-border rounded px-2 py-1.5 text-white text-xs disabled:opacity-40 max-w-[180px]"
+ >
+ <option value="">Default model</option>
+ {providerModels.map((m) => {
+ const id = typeof m === 'string' ? m : m.id;
+ const label = typeof m === 'string' ? m : (m.name || m.id);
+ return <option key={id} value={id}>{label}</option>;
+ })}
+ </select>
+ </div>
+ );
+}
diff --git a/client/src/components/pipeline/stages/ComicScriptStage.jsx b/client/src/components/pipeline/stages/ComicScriptStage.jsx
index 3653c19fd0..c8d0f58862 100644
--- a/client/src/components/pipeline/stages/ComicScriptStage.jsx
+++ b/client/src/components/pipeline/stages/ComicScriptStage.jsx
@@ -1,12 +1,279 @@
-import TextStagePanel from './TextStagePanel';
+/**
+ * Merged Comic Script + Comic Pages editor. The full markdown still lives on
+ * `stages.comicScript.output` and the parsed page records still live on
+ * `stages.comicPages.pages[]` — this component just folds them into one
+ * page-by-page view: each page is an editable markdown slice on the left and
+ * a full-page render on the right. Panels are still parsed internally so the
+ * render prompt stays high-quality, but they're never shown.
+ */
+
+import { useEffect, useMemo, useState } from 'react';
+import { Loader2, Sparkles, ImageIcon, Save, Trash2, ChevronDown, ChevronRight } from 'lucide-react';
+import toast from '../../ui/Toast';
+import {
+ generatePipelineStage,
+ extractPipelineComicPages,
+ generatePipelineComicPage,
+ updatePipelineComicPage,
+ updatePipelineIssue,
+ PIPELINE_STAGE_LABELS,
+ PIPELINE_STAGE_STATUS_LABEL as STATUS_LABEL,
+ PIPELINE_STAGE_STATUS_COLOR as STATUS_COLOR,
+} from '../../../services/api';
+import MediaJobThumb from '../MediaJobThumb';
+
+// Reconstructs a page's markdown from its parsed `panels[]`. Used as a
+// fallback for pages persisted BEFORE the parser started preserving rawText —
+// without it those pages would render as empty textareas, and a Save click
+// would PATCH an empty rawText and silently wipe the panels.
+function panelsToMarkdown(panels, pageNumber) {
+ const lines = [`## Page ${pageNumber}`, ''];
+ (panels || []).forEach((p, i) => {
+ lines.push(`### Panel ${i + 1}`);
+ if (p.description) lines.push(`**Description:** ${p.description}`);
+ if (p.caption) lines.push(`**Caption:** ${p.caption}`);
+ if (Array.isArray(p.dialogue) && p.dialogue.length) {
+ lines.push('**Dialogue:**');
+ for (const d of p.dialogue) {
+ const line = (d.line || '').trim();
+ if (line) lines.push(`- ${(d.character || 'CHAR').trim() || 'CHAR'}: "${line}"`);
+ }
+ }
+ if (p.sfx) lines.push(`**SFX:** ${p.sfx}`);
+ lines.push('');
+ });
+ return lines.join('\n').trim();
+}
+
+export default function ComicScriptStage({ issue, series, onStageUpdate }) {
+ const script = issue.stages?.comicScript || { status: 'empty', output: '' };
+ const comicPages = issue.stages?.comicPages || { status: 'empty', pages: [] };
+ const pages = Array.isArray(comicPages.pages) ? comicPages.pages : [];
+ const hasScript = !!(script.output || '').trim();
+
+ const [localGenerating, setLocalGenerating] = useState(false);
+ const [serverGenerating, setServerGenerating] = useState(script.status === 'generating');
+ // Sync with auto-run status pushed in from outside this component.
+ useEffect(() => { setServerGenerating(script.status === 'generating'); }, [script.status]);
+ const generating = localGenerating || serverGenerating;
+ const [extracting, setExtracting] = useState(false);
+ const [showSource, setShowSource] = useState(false);
+
+ const overrides = {
+ providerId: series?.llm?.provider || undefined,
+ model: series?.llm?.model || undefined,
+ };
+
+ // Re-generate the comic script from prose and immediately split it into
+ // pages. Auto-extract follows generate so the user never sees the raw
+ // concatenated markdown unless they expand the source-details panel.
+ const handleGenerate = async () => {
+ setLocalGenerating(true);
+ const result = await generatePipelineStage(issue.id, 'comicScript', overrides)
+ .catch((err) => { toast.error(err.message || 'Generation failed'); return null; });
+ if (!result) { setLocalGenerating(false); return; }
+ onStageUpdate?.('comicScript', result.stage);
+ const extracted = await extractPipelineComicPages(issue.id, { force: true })
+ .catch((err) => { toast.error(`Page split failed: ${err.message}`); return null; });
+ setLocalGenerating(false);
+ if (extracted) {
+ onStageUpdate?.('comicPages', extracted.stage);
+ toast.success(`Generated and split into ${extracted.pageCount} page${extracted.pageCount === 1 ? '' : 's'}`);
+ }
+ };
+
+ const handleExtract = async () => {
+ setExtracting(true);
+ const extracted = await extractPipelineComicPages(issue.id, { force: pages.length > 0 })
+ .catch((err) => { toast.error(err.message || 'Page split failed'); return null; });
+ setExtracting(false);
+ if (extracted) {
+ onStageUpdate?.('comicPages', extracted.stage);
+ toast.success(`Split into ${extracted.pageCount} page${extracted.pageCount === 1 ? '' : 's'}`);
+ }
+ };
+
+ return (
+ <div className="space-y-4">
+ <header className="flex items-center justify-between gap-3 flex-wrap">
+ <div className="flex items-center gap-3">
+ <h2 className="text-lg font-semibold text-white">{PIPELINE_STAGE_LABELS.comicScript}</h2>
+ <span className={`text-[10px] uppercase tracking-wider ${STATUS_COLOR[script.status] || 'text-gray-500'}`}>
+ {STATUS_LABEL[script.status] || script.status}
+ </span>
+ {pages.length > 0 ? (
+ <span className="text-xs text-gray-500">{pages.length} page{pages.length === 1 ? '' : 's'}</span>
+ ) : null}
+ </div>
+ <div className="flex items-center gap-2">
+ {hasScript && pages.length === 0 ? (
+ <button
+ type="button"
+ onClick={handleExtract}
+ disabled={extracting}
+ className="inline-flex items-center gap-2 px-3 py-1.5 rounded-lg bg-port-card border border-port-border text-white text-sm hover:border-port-accent/50 disabled:opacity-40"
+ >
+ {extracting ? <Loader2 size={14} className="animate-spin" /> : <Sparkles size={14} />}
+ Split into pages
+ </button>
+ ) : null}
+ <button
+ type="button"
+ onClick={handleGenerate}
+ disabled={generating || extracting}
+ className="inline-flex items-center gap-2 px-3 py-1.5 rounded-lg bg-port-accent text-white text-sm font-medium disabled:opacity-50"
+ title="Re-adapt the prose into a fresh comic script and split it into pages"
+ >
+ {generating ? <Loader2 size={14} className="animate-spin" /> : <Sparkles size={14} />}
+ {hasScript ? 'Re-generate pages' : 'Generate pages'}
+ </button>
+ </div>
+ </header>
+
+ {pages.length === 0 && !hasScript ? (
+ <p className="text-sm text-gray-400 italic">
+ Generate the prose stage first, then click <em>Generate pages</em>. The LLM adapts the prose into a Marvel/DC-format script and we split it into editable pages.
+ </p>
+ ) : null}
+
+ {pages.length === 0 && hasScript ? (
+ <p className="text-sm text-gray-400 italic">
+ Script generated but no pages parsed. Click <em>Split into pages</em> above.
+ </p>
+ ) : null}
+
+ <ul className="space-y-4">
+ {pages.map((page, pi) => (
+ <PageRow
+ key={pi}
+ issue={issue}
+ pageIndex={pi}
+ page={page}
+ onStageUpdate={onStageUpdate}
+ />
+ ))}
+ </ul>
+
+ {hasScript ? (
+ <details
+ className="rounded border border-port-border bg-port-card/40"
+ open={showSource}
+ onToggle={(e) => setShowSource(e.currentTarget.open)}
+ >
+ <summary className="px-3 py-2 text-xs uppercase tracking-wider text-gray-500 cursor-pointer flex items-center gap-2 hover:text-white">
+ {showSource ? <ChevronDown size={12} /> : <ChevronRight size={12} />}
+ Full comic script (markdown source)
+ </summary>
+ <pre className="px-3 py-2 text-xs text-gray-300 whitespace-pre-wrap font-mono border-t border-port-border">
+ {script.output}
+ </pre>
+ </details>
+ ) : null}
+ </div>
+ );
+}
+
+function PageRow({ issue, pageIndex, page, onStageUpdate }) {
+ const rawText = useMemo(
+ () => page.rawText || panelsToMarkdown(page.panels, pageIndex + 1),
+ [page.rawText, page.panels, pageIndex],
+ );
+ const [draft, setDraft] = useState(rawText);
+ const [saving, setSaving] = useState(false);
+ const [rendering, setRendering] = useState(false);
+ // Sync local edits with parent updates (re-extract / re-render persist).
+ useEffect(() => { setDraft(rawText); }, [rawText]);
+ const dirty = draft !== rawText;
+
+ const handleSave = async () => {
+ setSaving(true);
+ const res = await updatePipelineComicPage(issue.id, pageIndex, { rawText: draft })
+ .catch((err) => { toast.error(err.message || 'Save failed'); return null; });
+ setSaving(false);
+ if (res) {
+ onStageUpdate?.('comicPages', res.stage);
+ toast.success(`Page ${pageIndex + 1} saved (${res.page?.panels?.length || 0} panel${res.page?.panels?.length === 1 ? '' : 's'} parsed)`);
+ }
+ };
+
+ const handleRender = async () => {
+ setRendering(true);
+ const res = await generatePipelineComicPage(issue.id, pageIndex, {})
+ .catch((err) => { toast.error(err.message || 'Render failed'); return null; });
+ setRendering(false);
+ if (res) {
+ onStageUpdate?.('comicPages', res.stage);
+ toast.success(`Page ${pageIndex + 1} render queued`);
+ }
+ };
+
+ const handleDelete = async () => {
+ const next = (issue.stages?.comicPages?.pages || []).filter((_, i) => i !== pageIndex);
+ const patched = await updatePipelineIssue(issue.id, {
+ stages: { comicPages: { status: next.length ? 'edited' : 'empty', pages: next } },
+ }).catch((err) => { toast.error(err.message || 'Delete failed'); return null; });
+ if (patched) {
+ onStageUpdate?.('comicPages', patched.stages.comicPages, patched);
+ toast.success(`Page ${pageIndex + 1} deleted`);
+ }
+ };
-export default function ComicScriptStage(props) {
return (
- <TextStagePanel
- {...props}
- stageId="comicScript"
- generateLabel="Adapt to comic script"
- outputPlaceholder="Page → panel → description / caption / dialogue / SFX. Marvel/DC house format. Generated from the prose stage; iterate freely without re-running."
- />
+ <li className="rounded-lg border border-port-border bg-port-card/40">
+ <div className="flex items-center justify-between gap-2 px-3 py-2 border-b border-port-border">
+ <div className="flex items-center gap-2">
+ <span className="text-xs uppercase tracking-wider text-gray-500">Page {pageIndex + 1}</span>
+ <span className="text-[10px] text-gray-600">{page.panels?.length || 0} panel{page.panels?.length === 1 ? '' : 's'}</span>
+ {dirty ? <span className="text-[10px] text-port-warning">unsaved</span> : null}
+ </div>
+ <div className="flex items-center gap-1">
+ <button
+ type="button"
+ onClick={handleSave}
+ disabled={!dirty || saving}
+ className="inline-flex items-center gap-1 px-2 py-1 rounded text-xs bg-port-bg border border-port-border text-white hover:border-port-accent/50 disabled:opacity-40"
+ >
+ {saving ? <Loader2 size={12} className="animate-spin" /> : <Save size={12} />}
+ Save
+ </button>
+ <button
+ type="button"
+ onClick={handleRender}
+ disabled={rendering || dirty}
+ className="inline-flex items-center gap-1 px-2 py-1 rounded text-xs bg-port-accent text-white font-medium disabled:opacity-40"
+ title={dirty ? 'Save changes before rendering' : 'Queue a full-page render for this page'}
+ >
+ {rendering ? <Loader2 size={12} className="animate-spin" /> : <ImageIcon size={12} />}
+ Render
+ </button>
+ <button
+ type="button"
+ onClick={handleDelete}
+ className="p-1 text-gray-500 hover:text-port-error"
+ aria-label={`Delete page ${pageIndex + 1}`}
+ title="Delete page"
+ >
+ <Trash2 size={12} />
+ </button>
+ </div>
+ </div>
+ <div className="grid md:grid-cols-2 gap-3 p-3">
+ <textarea
+ value={draft}
+ onChange={(e) => setDraft(e.target.value)}
+ rows={18}
+ spellCheck={false}
+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded text-white text-xs font-mono leading-relaxed"
+ placeholder={`## Page ${pageIndex + 1}\n\n### Panel 1\n**Description:** ...`}
+ />
+ <div className="flex items-center justify-center bg-port-bg border border-port-border rounded min-h-[200px]">
+ {page.imageJobId ? (
+ <MediaJobThumb jobId={page.imageJobId} label={`Page ${pageIndex + 1}`} size="md" />
+ ) : (
+ <span className="text-xs text-gray-500 italic">No render yet — click <em>Render</em>.</span>
+ )}
+ </div>
+ </div>
+ </li>
);
}
diff --git a/client/src/components/pipeline/stages/IdeaStage.jsx b/client/src/components/pipeline/stages/IdeaStage.jsx
index 10ecd74fbe..0c5fb851cb 100644
--- a/client/src/components/pipeline/stages/IdeaStage.jsx
+++ b/client/src/components/pipeline/stages/IdeaStage.jsx
@@ -30,7 +30,7 @@ ${block}`;
}
export default function IdeaStage(props) {
- const { issue, onStageUpdate } = props;
+ const { issue, series, onStageUpdate } = props;
const output = issue.stages?.idea?.output || '';
const seedInput = issue.stages?.idea?.input || '';
const questions = useMemo(() => parseOpenQuestions(output), [output]);
@@ -41,11 +41,14 @@ export default function IdeaStage(props) {
setRefining(true);
const qa = questions.map((q, i) => ({ q, a: (answers[i] || '').trim() }));
const augmented = buildRefinementSeed(seedInput, qa);
- const result = await generatePipelineStage(issue.id, 'idea', { seedInput: augmented })
- .catch((err) => {
- toast.error(err.message || 'Refinement failed');
- return null;
- });
+ const result = await generatePipelineStage(issue.id, 'idea', {
+ seedInput: augmented,
+ providerId: series?.llm?.provider || undefined,
+ model: series?.llm?.model || undefined,
+ }).catch((err) => {
+ toast.error(err.message || 'Refinement failed');
+ return null;
+ });
setRefining(false);
if (!result) return;
onStageUpdate?.('idea', result.stage);
diff --git a/client/src/components/pipeline/stages/TextStagePanel.jsx b/client/src/components/pipeline/stages/TextStagePanel.jsx
index 07ad2a07fe..c57368c80a 100644
--- a/client/src/components/pipeline/stages/TextStagePanel.jsx
+++ b/client/src/components/pipeline/stages/TextStagePanel.jsx
@@ -8,29 +8,17 @@
import { useEffect, useState } from 'react';
import { Loader2, Sparkles, Save } from 'lucide-react';
import toast from '../../ui/Toast';
-import { generatePipelineStage, updatePipelineIssue, PIPELINE_STAGE_LABELS } from '../../../services/api';
+import {
+ generatePipelineStage, updatePipelineIssue,
+ PIPELINE_STAGE_LABELS,
+ PIPELINE_STAGE_STATUS_LABEL as STATUS_LABEL,
+ PIPELINE_STAGE_STATUS_COLOR as STATUS_COLOR,
+} from '../../../services/api';
import { useAsyncAction } from '../../../hooks/useAsyncAction';
-const STATUS_LABEL = {
- empty: 'Not started',
- generating: 'Generating…',
- ready: 'Ready',
- edited: 'Edited',
- 'needs-review': 'Needs review',
- error: 'Error',
-};
-
-const STATUS_COLOR = {
- empty: 'text-gray-500',
- generating: 'text-port-accent',
- ready: 'text-port-success',
- edited: 'text-port-warning',
- 'needs-review': 'text-port-warning',
- error: 'text-port-error',
-};
-
export default function TextStagePanel({
issue,
+ series,
stageId,
onStageUpdate,
seedPlaceholder,
@@ -55,7 +43,11 @@ export default function TextStagePanel({
}, [stage.output, stage.input, stage.status, stage.lastRunId]);
const [runGenerate, localGenerating] = useAsyncAction(
- () => generatePipelineStage(issue.id, stageId, { seedInput: draftInput }),
+ () => generatePipelineStage(issue.id, stageId, {
+ seedInput: draftInput,
+ providerId: series?.llm?.provider || undefined,
+ model: series?.llm?.model || undefined,
+ }),
{ errorMessage: `Failed to generate ${stageId}` },
);
const generating = localGenerating || serverGenerating;
diff --git a/client/src/pages/PipelineIssue.jsx b/client/src/pages/PipelineIssue.jsx
index 24d54f9313..e9fe81eab7 100644
--- a/client/src/pages/PipelineIssue.jsx
+++ b/client/src/pages/PipelineIssue.jsx
@@ -16,7 +16,7 @@ import toast from '../components/ui/Toast';
import {
getPipelineIssue, getPipelineSeries,
startPipelineAutoRunText, cancelPipelineAutoRunText,
- PIPELINE_STAGES, PIPELINE_STAGE_LABELS,
+ PIPELINE_STAGES, PIPELINE_TAB_STAGES, PIPELINE_STAGE_LABELS,
} from '../services/api';
import { usePipelineAutoRunProgress } from '../hooks/usePipelineAutoRunProgress';
import IdeaStage from '../components/pipeline/stages/IdeaStage';
@@ -26,6 +26,7 @@ import TVScriptStage from '../components/pipeline/stages/TVScriptStage';
import ComicPagesStage from '../components/pipeline/stages/ComicPagesStage';
import StoryboardsStage from '../components/pipeline/stages/StoryboardsStage';
import EpisodeVideoStage from '../components/pipeline/stages/EpisodeVideoStage';
+import SeriesLlmPicker from '../components/pipeline/SeriesLlmPicker';
const STAGE_ICONS = {
idea: Lightbulb,
@@ -59,7 +60,10 @@ const STATUS_DOT = {
export default function PipelineIssue() {
const { issueId, stage: stageParam } = useParams();
const navigate = useNavigate();
- const stageId = PIPELINE_STAGES.includes(stageParam) ? stageParam : 'idea';
+ // `comicPages` URL still routes (folded into the Comic Script tab below);
+ // we redirect those to `comicScript` since the merged editor lives there.
+ const requested = PIPELINE_STAGES.includes(stageParam) ? stageParam : 'idea';
+ const stageId = requested === 'comicPages' ? 'comicScript' : requested;
const [issue, setIssue] = useState(null);
const [series, setSeries] = useState(null);
@@ -101,7 +105,11 @@ export default function PipelineIssue() {
const handleAutoRun = async (opts = {}) => {
setAutoRunStarting(true);
- const res = await startPipelineAutoRunText(issueId, opts).catch((err) => {
+ const res = await startPipelineAutoRunText(issueId, {
+ providerId: series?.llm?.provider || undefined,
+ model: series?.llm?.model || undefined,
+ ...opts,
+ }).catch((err) => {
toast.error(err.message || 'Failed to start auto-run');
return null;
});
@@ -130,7 +138,7 @@ export default function PipelineIssue() {
}) : prev);
};
- const stageTabs = useMemo(() => PIPELINE_STAGES.map((id) => ({
+ const stageTabs = useMemo(() => PIPELINE_TAB_STAGES.map((id) => ({
id,
label: PIPELINE_STAGE_LABELS[id],
Icon: STAGE_ICONS[id],
@@ -164,7 +172,14 @@ export default function PipelineIssue() {
<div className="flex items-center justify-between gap-3 flex-wrap">
<h1 className="text-xl font-bold text-white truncate">#{issue.number} — {issue.title}</h1>
- <div className="flex items-center gap-2">
+ <div className="flex items-center gap-2 flex-wrap">
+ {series ? (
+ <SeriesLlmPicker
+ series={series}
+ onSeriesUpdate={setSeries}
+ disabled={autoRunStarting || autoRunActive}
+ />
+ ) : null}
{autoRunActive && (
<button
type="button"
diff --git a/client/src/services/apiPipeline.js b/client/src/services/apiPipeline.js
index 4ca444eeff..73d6781498 100644
--- a/client/src/services/apiPipeline.js
+++ b/client/src/services/apiPipeline.js
@@ -5,10 +5,19 @@ export const PIPELINE_TEXT_STAGES = Object.freeze(['idea', 'prose', 'comicScript
export const PIPELINE_VISUAL_STAGES = Object.freeze(['comicPages', 'storyboards', 'episodeVideo']);
export const PIPELINE_STAGES = Object.freeze([...PIPELINE_TEXT_STAGES, ...PIPELINE_VISUAL_STAGES]);
+// Stages that appear as their own tab. `comicPages` is folded into the Comic
+// Script tab (one merged page-by-page editor) — the data still flows through
+// the comicPages routes, the tab is just hidden.
+export const PIPELINE_TAB_STAGES = Object.freeze(
+ PIPELINE_STAGES.filter((id) => id !== 'comicPages'),
+);
+
export const PIPELINE_STAGE_LABELS = Object.freeze({
idea: 'Idea',
prose: 'Prose',
- comicScript: 'Comic Script',
+ // `comicScript` stage now owns the merged Comic Pages editor — the
+ // standalone Comic Pages tab is hidden via PIPELINE_TAB_STAGES below.
+ comicScript: 'Comic Pages',
tvScript: 'TV Script',
comicPages: 'Comic Pages',
storyboards: 'Storyboards',
@@ -17,6 +26,24 @@ export const PIPELINE_STAGE_LABELS = Object.freeze({
export const PIPELINE_TARGET_FORMATS = Object.freeze(['comic', 'tv', 'comic+tv']);
+export const PIPELINE_STAGE_STATUS_LABEL = Object.freeze({
+ empty: 'Not started',
+ generating: 'Generating…',
+ ready: 'Ready',
+ edited: 'Edited',
+ 'needs-review': 'Needs review',
+ error: 'Error',
+});
+
+export const PIPELINE_STAGE_STATUS_COLOR = Object.freeze({
+ empty: 'text-gray-500',
+ generating: 'text-port-accent',
+ ready: 'text-port-success',
+ edited: 'text-port-warning',
+ 'needs-review': 'text-port-warning',
+ error: 'text-port-error',
+});
+
// ---- Series ----
export const listPipelineSeries = () => request('/pipeline/series');
export const getPipelineSeries = (id) => request(`/pipeline/series/${encodeURIComponent(id)}`);
@@ -112,6 +139,15 @@ export const generatePipelineComicPage = (issueId, pageIndex, opts = {}) =>
body: JSON.stringify(opts),
});
+// Patch one comic page's raw markdown — the server re-parses panels from the
+// edited rawText so subsequent renders still get a structured prompt.
+// Returns { issue, stage, page }.
+export const updatePipelineComicPage = (issueId, pageIndex, { rawText } = {}) =>
+ request(`/pipeline/issues/${encodeURIComponent(issueId)}/stages/comicPages/pages/${encodeURIComponent(pageIndex)}`, {
+ method: 'PATCH',
+ body: JSON.stringify({ rawText }),
+ });
+
// Render a single storyboard scene as a video clip (one t2v call against
// the scene's existing description + style). Independent of the
// episode-video stitch — use this when you want to preview a scene before
diff --git a/server/lib/codexAssistantExtract.js b/server/lib/codexAssistantExtract.js
new file mode 100644
index 0000000000..d034e400d3
--- /dev/null
+++ b/server/lib/codexAssistantExtract.js
@@ -0,0 +1,17 @@
+// Codex CLI echoes its full session transcript (banner + metadata + echoed
+// prompt + `\ncodex\n<reply>` + token footer). JSON stages survive because the
+// parser skips non-JSON chunks; text stages don't, so this helper carves out
+// just the assistant reply. Idempotent for non-Codex output.
+export function extractCodexAssistant(text) {
+ if (typeof text !== 'string' || !text) return text;
+ if (!text.startsWith('OpenAI Codex v')) return text;
+
+ const codexIdx = text.indexOf('\ncodex\n');
+ if (codexIdx < 0) return text;
+ let response = text.slice(codexIdx + '\ncodex\n'.length);
+
+ const tokensIdx = response.lastIndexOf('\ntokens used');
+ if (tokensIdx > 0) response = response.slice(0, tokensIdx);
+
+ return response.trim();
+}
diff --git a/server/lib/codexAssistantExtract.test.js b/server/lib/codexAssistantExtract.test.js
new file mode 100644
index 0000000000..d601caab48
--- /dev/null
+++ b/server/lib/codexAssistantExtract.test.js
@@ -0,0 +1,70 @@
+import { describe, it, expect } from 'vitest';
+import { extractCodexAssistant } from './codexAssistantExtract.js';
+
+describe('extractCodexAssistant', () => {
+ it('returns text unchanged when there is no Codex banner', () => {
+ const claudeOutput = 'Here is the comic script:\n\n## Page 1\n\nPanel 1...';
+ expect(extractCodexAssistant(claudeOutput)).toBe(claudeOutput);
+ });
+
+ it('carves out the assistant reply between the prompt echo and the token footer', () => {
+ const full = `OpenAI Codex v0.128.0 (research preview)
+--------
+workdir: /repo
+model: gpt-5
+provider: openai
+--------
+user
+# Pipeline — Comic-Book Script
+
+You are a comics writer...
+
+Return ONLY the script.
+
+codex
+# Issue 1 — The Harvest Market
+
+## Page 1
+
+### Panel 1
+**Description:** Wide establishing shot...
+
+tokens used: 12345
+`;
+ const out = extractCodexAssistant(full);
+ expect(out.startsWith('# Issue 1 — The Harvest Market')).toBe(true);
+ expect(out).not.toContain('OpenAI Codex v');
+ expect(out).not.toContain('You are a comics writer');
+ expect(out).not.toContain('tokens used');
+ });
+
+ it('handles missing token-stats footer (response runs to EOF)', () => {
+ const full = `OpenAI Codex v0.125.0 (research preview)
+--------
+workdir: /repo
+--------
+user
+prompt body
+
+codex
+The assistant reply with no trailing token line.`;
+ const out = extractCodexAssistant(full);
+ expect(out).toBe('The assistant reply with no trailing token line.');
+ });
+
+ it('returns input untouched when the `codex` marker is missing (truncated run)', () => {
+ const truncated = `OpenAI Codex v0.125.0 (research preview)
+--------
+workdir: /repo
+--------
+user
+prompt body`;
+ expect(extractCodexAssistant(truncated)).toBe(truncated);
+ });
+
+ it('returns empty / non-string input unchanged', () => {
+ expect(extractCodexAssistant('')).toBe('');
+ expect(extractCodexAssistant(null)).toBe(null);
+ expect(extractCodexAssistant(undefined)).toBe(undefined);
+ });
+});
diff --git a/server/lib/comicScriptParser.js b/server/lib/comicScriptParser.js
index 2388d28337..b30969406e 100644
--- a/server/lib/comicScriptParser.js
+++ b/server/lib/comicScriptParser.js
@@ -91,27 +91,26 @@ function parsePanelBody(lines) {
/**
* @param {string} script markdown body from stages.comicScript.output
- * @returns {{ pages: Array<{ panels: Array<{ description, caption, dialogue, sfx }> }> }}
+ * @returns {{ pages: Array<{ rawText, panels: Array<{ description, caption, dialogue, sfx }> }> }}
+ *
+ * `rawText` carries the markdown slice from the page's `## Page N` header to
+ * (not including) the next page header. The merged Comic tab uses this for
+ * per-page editing while panels remain the source for the image prompt.
*/
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 currentRawLines = 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;
@@ -121,22 +120,22 @@ export function parseComicScript(script) {
for (const line of lines) {
if (PAGE_RE.test(line)) {
flushPanel();
+ if (currentPage && currentRawLines) currentPage.rawText = currentRawLines.join('\n').trim();
if (pages.length >= PANEL_LIMITS.PAGES_MAX) break;
- currentPage = { panels: [] };
+ currentPage = { panels: [], rawText: '' };
+ currentRawLines = [line];
pages.push(currentPage);
continue;
}
+ if (currentRawLines) currentRawLines.push(line);
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: [] };
+ currentPage = { panels: [], rawText: '' };
+ currentRawLines = [line];
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;
@@ -150,8 +149,8 @@ export function parseComicScript(script) {
}
}
flushPanel();
+ if (currentPage && currentRawLines) currentPage.rawText = currentRawLines.join('\n').trim();
- // 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 };
}
diff --git a/server/lib/stageRunner.js b/server/lib/stageRunner.js
index 75b4b820b7..593b17bd64 100644
--- a/server/lib/stageRunner.js
+++ b/server/lib/stageRunner.js
@@ -18,6 +18,7 @@ import { ServerError } from './errorHandler.js';
import { findBalancedBlocks, tryParseWithRepair } from './jsonExtract.js';
import { resolveEffectiveModel, runPromptThroughProvider } from './promptRunner.js';
import { stripCodeFences } from './aiProvider.js';
+import { extractCodexAssistant } from './codexAssistantExtract.js';
import { getActiveProvider, getProviderById } from '../services/providers.js';
import { buildPrompt, getStage } from '../services/promptService.js';
import { createRun } from '../services/runner.js';
@@ -203,10 +204,11 @@ export async function runStagedLLM(stageName, variables, options = {}) {
const { text } = await runPromptThroughProvider({
provider, model: effectiveModel, prompt, source: options.source || 'staged-llm', runId,
});
- // Pass the prompt down so extractJson can strip any echoed copy of
- // it before walking — Codex CLI echoes stdin to stdout, and stage
- // prompts often contain fenced JSON schema examples that would
- // otherwise parse-and-win over the model's actual response.
- const content = options.returnsJson ? extractJson(text, { promptToStrip: prompt }) : text;
+ // Codex CLI dumps the full transcript (banner + metadata + echoed prompt +
+ // `codex\n<reply>` + token-stats footer). Carve out the assistant reply
+ // before either parsing JSON or returning text. Idempotent for non-Codex
+ // providers — returns input unchanged when the banner isn't present.
+ const cleaned = extractCodexAssistant(text);
+ const content = options.returnsJson ? extractJson(cleaned, { promptToStrip: prompt }) : cleaned;
return { content, model: effectiveModel || null, providerId: provider.id, runId };
}
diff --git a/server/routes/pipeline.js b/server/routes/pipeline.js
index 9f9e93e202..756f5eafe5 100644
--- a/server/routes/pipeline.js
+++ b/server/routes/pipeline.js
@@ -294,6 +294,10 @@ const extractComicPagesSchema = z.object({
force: z.boolean().optional(),
});
+const comicPagePatchSchema = z.object({
+ rawText: z.string().max(40000),
+});
+
// 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).
@@ -748,6 +752,43 @@ router.post('/issues/:id/stages/comicPages/extract-pages', asyncHandler(async (r
});
}));
+// Per-page rawText patch — re-parses panels from the edited markdown so a
+// subsequent render still gets a structured prompt. Page's `imageJobId` is
+// preserved so the user doesn't lose an in-flight render after a save.
+router.patch('/issues/:id/stages/comicPages/pages/:pageIndex', 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(comicPagePatchSchema, req.body ?? {});
+ 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 { pages: reparsed } = parseComicScript(body.rawText);
+ const fresh = reparsed[0] || { panels: [], rawText: body.rawText };
+ pages[pageIndex] = {
+ ...pages[pageIndex],
+ rawText: fresh.rawText || body.rawText,
+ panels: fresh.panels.map((p, i) => ({
+ ...p,
+ // Preserve in-flight per-panel jobIds when the panel survived the re-parse.
+ imageJobId: pages[pageIndex].panels?.[i]?.imageJobId ?? p.imageJobId ?? null,
+ })),
+ };
+ const { issue: updatedIssue, stage } = await issuesSvc.updateStage(req.params.id, 'comicPages', {
+ status: 'edited',
+ pages,
+ });
+ res.json({ issue: updatedIssue, stage, page: pages[pageIndex] });
+}));
+
// 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