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): generate all beat sheets across a volume sequentially

[._.]/ Adam Eivy64b34f0f8211
diff --git a/client/src/components/pipeline/ArcCanvas.jsx b/client/src/components/pipeline/ArcCanvas.jsx
index c269eaf0d5..468da30615 100644
--- a/client/src/components/pipeline/ArcCanvas.jsx
+++ b/client/src/components/pipeline/ArcCanvas.jsx
@@ -23,11 +23,11 @@
* responsive without a refetch.
*/
-import { useMemo, useState } from 'react';
+import { useEffect, useMemo, useRef, useState } from 'react';
import { Link } from 'react-router-dom';
import {
Plus, Trash2, Loader2, Sparkles, ShieldCheck, ChevronRight, ChevronDown,
- ChevronsUpDown, AlertCircle, Wand2, Info,
+ ChevronsUpDown, AlertCircle, Wand2, Info, ListChecks, X,
} from 'lucide-react';
import toast from '../ui/Toast';
import { timeAgo } from '../../utils/formatters';
@@ -39,7 +39,9 @@ import {
verifyPipelineVolume,
resolvePipelineArcIssues,
listPipelineIssues, updatePipelineSeries,
+ startPipelineVolumeBeats, cancelPipelineVolumeBeats,
} from '../../services/api';
+import { usePipelineVolumeBeatsProgress } from '../../hooks/usePipelineVolumeBeatsProgress';
import SeriesLlmPicker from './SeriesLlmPicker';
import { ArcShapePicker, ArcShapeSparkline, getStoryShape } from './StoryShapes';
@@ -531,6 +533,65 @@ function SeasonRow({ series, season, seasons, issues, onSeriesUpdate, onIssuesUp
const [editing, setEditing] = useState(false);
const [verifying, setVerifying] = useState(false);
const [verifyIssues, setVerifyIssues] = useState(null);
+ // Volume beat-sheet bulk run — `active` gates SSE subscription; the latest
+ // frame drives the per-issue label on the button.
+ const [beatsActive, setBeatsActive] = useState(false);
+ const [beatsStarting, setBeatsStarting] = useState(false);
+ const { latest: beatsLatest } = usePipelineVolumeBeatsProgress(series.id, season.id, { enabled: beatsActive });
+
+ // Stable ref over the parent's setter — `handleIssuesUpdate` in
+ // PipelineSeries is re-allocated every render, so depending on it would
+ // re-run this effect on every parent update.
+ const onIssuesUpdateRef = useRef(onIssuesUpdate);
+ onIssuesUpdateRef.current = onIssuesUpdate;
+
+ // Refresh issues + toast when the run lands on a terminal frame and tear
+ // the SSE subscription down. Per-issue frames just drive the button
+ // label — refetching the whole list per issue would cost N+1 reads per
+ // run for no benefit (the button already shows live ordinal/total).
+ useEffect(() => {
+ if (!beatsActive || !beatsLatest) return;
+ const type = beatsLatest.type;
+ if (type !== 'complete' && type !== 'canceled' && type !== 'error') return;
+ setBeatsActive(false);
+ listPipelineIssues(series.id)
+ .then((refreshed) => onIssuesUpdateRef.current(refreshed))
+ .catch(() => null);
+ if (type === 'complete') {
+ const n = beatsLatest.generated || 0;
+ const s = beatsLatest.skipped || 0;
+ const e = beatsLatest.errored || 0;
+ const parts = [`${n} generated`];
+ if (s) parts.push(`${s} skipped`);
+ if (e) parts.push(`${e} errored`);
+ (e > 0 ? toast.error : toast.success)(`Volume ${season.number} beat sheets — ${parts.join(', ')}`);
+ } else if (type === 'canceled') {
+ toast.success(`Volume ${season.number} beat-sheet run canceled`);
+ } else {
+ toast.error(beatsLatest.error || 'Beat-sheet run failed');
+ }
+ }, [beatsActive, beatsLatest, series.id, season.number]);
+
+ const startBeats = async (mode) => {
+ setBeatsStarting(true);
+ const result = await startPipelineVolumeBeats(series.id, season.id, {
+ mode,
+ providerOverride: series.llm?.provider || undefined,
+ modelOverride: series.llm?.model || undefined,
+ }).catch((err) => {
+ toast.error(err.message || 'Failed to start beat-sheet run');
+ return null;
+ });
+ setBeatsStarting(false);
+ if (!result) return;
+ setBeatsActive(true);
+ };
+
+ const cancelBeats = async () => {
+ await cancelPipelineVolumeBeats(series.id, season.id).catch((err) => {
+ toast.error(err.message || 'Cancel failed');
+ });
+ };
const hasArc = !!series.arc;
const hasEpisodes = issues.length > 0;
@@ -680,6 +741,11 @@ function SeasonRow({ series, season, seasons, issues, onSeriesUpdate, onIssuesUp
onGenerateEpisodes={runGenerateEpisodes}
onValidateVolume={runVerifyVolume}
onIssuesUpdate={onIssuesUpdate}
+ beatsActive={beatsActive}
+ beatsStarting={beatsStarting}
+ beatsLatest={beatsLatest}
+ onStartBeats={startBeats}
+ onCancelBeats={cancelBeats}
/>
</>
) : null}
@@ -792,12 +858,27 @@ function SeasonEditor({ series, season, seasons, onSeriesUpdate }) {
);
}
+// Volume beat-sheet runner frame → button label. Keyed on the SSE frame's
+// `type` field; see server/services/pipeline/volumeBeatsRunner.js for the
+// frame shapes.
+const BEATS_FRAME_LABELS = {
+ start: (f) => `Starting (${f.total} issues)…`,
+ 'issue:start': (f) => `Generating ${f.ordinal}/${f.total} — ${f.issueTitle || `#${f.issueNumber}`}`,
+ 'issue:complete': (f) => `${f.ordinal}/${f.total} done`,
+ 'issue:skip': (f) => `Skipped ${f.ordinal}/${f.total}`,
+ 'issue:error': (f) => `Error on ${f.ordinal}/${f.total}`,
+};
+
function SeasonActions({
series, season, hasArc, hasEpisodes, generatingEpisodes,
verifying, onGenerateEpisodes, onValidateVolume, onIssuesUpdate,
+ beatsActive, beatsStarting, beatsLatest, onStartBeats, onCancelBeats,
}) {
const [adding, setAdding] = useState(false);
const [newTitle, setNewTitle] = useState('');
+ // Inline mode picker — surfaces only when the user clicks the button
+ // (per Ask each time choice for skip-existing vs regenerate-all).
+ const [beatsModePicker, setBeatsModePicker] = useState(false);
const seasonHasContext = !!(season.logline?.trim() || season.synopsis?.trim());
const handleAdd = async (e) => {
@@ -831,6 +912,19 @@ function SeasonActions({
? 'Add or generate at least one issue / episode first'
: null;
+ // Generate-all-beats needs episodes to iterate over; the per-issue
+ // generator handles the "no arc context" case gracefully so we don't gate
+ // on hasArc here.
+ const beatsDisabledReason = !hasEpisodes
+ ? 'Add or generate at least one issue / episode first'
+ : null;
+
+ // Human-readable status string for the in-flight button label. Terminal
+ // frames (complete/canceled/error) are absorbed by the parent useEffect.
+ const beatsLabel = beatsActive && beatsLatest
+ ? (BEATS_FRAME_LABELS[beatsLatest.type]?.(beatsLatest) ?? null)
+ : (beatsStarting ? 'Starting…' : null);
+
return (
<>
<div className="px-3 pb-2 pt-2 border-t border-port-border/50 flex items-center gap-2 flex-wrap">
@@ -884,6 +978,26 @@ function SeasonActions({
{generatingEpisodes ? <Loader2 size={12} className="animate-spin" /> : <Wand2 size={12} />}
Generate issues / episodes (LLM)
</button>
+ <button
+ type="button"
+ onClick={() => setBeatsModePicker((v) => !v)}
+ disabled={!!beatsDisabledReason || beatsActive || beatsStarting}
+ title={beatsDisabledReason || `Generate beat sheets for every issue in volume ${season.number} sequentially`}
+ className="inline-flex items-center gap-1 px-2 py-1 rounded text-xs text-gray-300 hover:text-white border border-port-border bg-port-bg hover:border-port-accent/40 disabled:opacity-40 disabled:hover:text-gray-300"
+ >
+ {beatsStarting || beatsActive ? <Loader2 size={12} className="animate-spin" /> : <ListChecks size={12} />}
+ Generate beat sheets
+ </button>
+ {beatsActive ? (
+ <button
+ type="button"
+ onClick={onCancelBeats}
+ className="inline-flex items-center gap-1 px-2 py-1 rounded text-xs text-port-warning hover:text-white border border-port-warning/40 bg-port-bg hover:bg-port-warning/10"
+ title="Stop the run after the current issue finishes"
+ >
+ <X size={12} /> Stop
+ </button>
+ ) : null}
<button
type="button"
onClick={onValidateVolume}
@@ -897,6 +1011,45 @@ function SeasonActions({
</>
)}
</div>
+ {beatsModePicker && !beatsActive && !beatsStarting ? (
+ <div className="mx-3 mb-2 p-2 border border-port-border rounded bg-port-bg/60 text-xs space-y-2">
+ <p className="text-gray-300">
+ Generate beat sheets for every issue in volume {season.number}, one at a time.
+ Each prompt picks up the prior issue's freshly-written beats.
+ </p>
+ <div className="flex items-center gap-2 flex-wrap">
+ <button
+ type="button"
+ onClick={() => { setBeatsModePicker(false); onStartBeats('skip-existing'); }}
+ className="inline-flex items-center gap-1 px-2 py-1 rounded bg-port-accent text-white hover:bg-port-accent/80"
+ title="Only generate for issues that don't already have a beat sheet"
+ >
+ Skip issues with beats
+ </button>
+ <button
+ type="button"
+ onClick={() => { setBeatsModePicker(false); onStartBeats('regenerate-all'); }}
+ className="inline-flex items-center gap-1 px-2 py-1 rounded border border-port-warning/40 text-port-warning hover:bg-port-warning/10"
+ title="Overwrite every issue's existing beat sheet"
+ >
+ Regenerate all
+ </button>
+ <button
+ type="button"
+ onClick={() => setBeatsModePicker(false)}
+ className="text-gray-400 hover:text-white px-2"
+ >
+ Cancel
+ </button>
+ </div>
+ </div>
+ ) : null}
+ {beatsLabel ? (
+ <div className="px-3 pb-2 text-xs text-gray-400 flex items-center gap-2">
+ <Loader2 size={12} className="animate-spin" />
+ {beatsLabel}
+ </div>
+ ) : null}
{!adding ? (
<div className="px-3 pb-3">
<VerifyScopeHint scope={VERIFY_VOLUME_SCOPE} />
diff --git a/client/src/hooks/usePipelineAutoRunProgress.js b/client/src/hooks/usePipelineAutoRunProgress.js
index d83a19a6e2..fe688f864e 100644
--- a/client/src/hooks/usePipelineAutoRunProgress.js
+++ b/client/src/hooks/usePipelineAutoRunProgress.js
@@ -1,59 +1,11 @@
-import { useEffect, useRef, useState } from 'react';
import { pipelineAutoRunSseUrl } from '../services/api';
+import { useSseProgress } from './useSseProgress';
/**
- * Subscribe to the auto-run-text SSE stream for a pipeline issue. Returns the
- * stream of progress frames as `frames` (in order) and a `latest` convenience
- * pointer. The hook tears down the EventSource on unmount or when the issueId
- * changes.
- *
- * Frame shapes (see server/services/pipeline/autoRunner.js#broadcast):
- * { type: 'start', runId, stages }
- * { type: 'stage:start', stage }
- * { type: 'stage:complete', stage, status, length }
- * { type: 'skip', stage, reason }
- * { type: 'complete', runId, completedAt }
- * { type: 'canceled', runId, completedAt }
- * { type: 'error', runId, error, failedAt }
+ * Subscribe to the auto-run-text SSE stream for a pipeline issue. Frame
+ * shapes are documented in server/services/pipeline/autoRunner.js#broadcast.
*/
export function usePipelineAutoRunProgress(issueId, { enabled = true } = {}) {
- const [frames, setFrames] = useState([]);
- const [latest, setLatest] = useState(null);
- const [isOpen, setIsOpen] = useState(false);
- const esRef = useRef(null);
-
- useEffect(() => {
- if (!issueId || !enabled) return undefined;
- setFrames([]);
- setLatest(null);
- setIsOpen(false);
-
- const url = pipelineAutoRunSseUrl(issueId);
- const es = new EventSource(url);
- esRef.current = es;
-
- es.onopen = () => setIsOpen(true);
- es.onmessage = (evt) => {
- const data = JSON.parse(evt.data);
- setFrames((prev) => [...prev, data]);
- setLatest(data);
- if (data?.type === 'complete' || data?.type === 'canceled' || data?.type === 'error') {
- // Server closes the stream after the cleanup window. Drop the client
- // ourselves so the browser doesn't keep retrying.
- es.close();
- }
- };
- es.onerror = () => {
- // EventSource auto-retries on transient disconnects; only mark closed
- // when readyState is CLOSED (terminal).
- if (es.readyState === EventSource.CLOSED) setIsOpen(false);
- };
-
- return () => {
- es.close();
- esRef.current = null;
- };
- }, [issueId, enabled]);
-
- return { frames, latest, isOpen, close: () => esRef.current?.close() };
+ const url = issueId ? pipelineAutoRunSseUrl(issueId) : null;
+ return useSseProgress(url, { enabled });
}
diff --git a/client/src/hooks/usePipelineVolumeBeatsProgress.js b/client/src/hooks/usePipelineVolumeBeatsProgress.js
new file mode 100644
index 0000000000..7885d14867
--- /dev/null
+++ b/client/src/hooks/usePipelineVolumeBeatsProgress.js
@@ -0,0 +1,11 @@
+import { pipelineVolumeBeatsSseUrl } from '../services/api';
+import { useSseProgress } from './useSseProgress';
+
+/**
+ * Subscribe to the volume beat-sheet SSE stream. Frame shapes are documented
+ * in server/services/pipeline/volumeBeatsRunner.js.
+ */
+export function usePipelineVolumeBeatsProgress(seriesId, seasonId, { enabled = true } = {}) {
+ const url = seriesId && seasonId ? pipelineVolumeBeatsSseUrl(seriesId, seasonId) : null;
+ return useSseProgress(url, { enabled });
+}
diff --git a/client/src/hooks/useSseProgress.js b/client/src/hooks/useSseProgress.js
new file mode 100644
index 0000000000..aad3515a34
--- /dev/null
+++ b/client/src/hooks/useSseProgress.js
@@ -0,0 +1,50 @@
+import { useEffect, useRef, useState } from 'react';
+
+const TERMINAL_TYPES = new Set(['complete', 'canceled', 'error']);
+
+/**
+ * Subscribe to a server-side EventSource stream of JSON-payload progress
+ * frames. Used by both the per-issue auto-runner and the per-volume
+ * beat-sheet runner — any new SSE-job hook should wrap this rather than
+ * re-implement the lifecycle.
+ *
+ * The stream is torn down on unmount, when `url` changes, when `enabled`
+ * flips false, or when a terminal frame (type === 'complete' / 'canceled'
+ * / 'error') arrives.
+ */
+export function useSseProgress(url, { enabled = true } = {}) {
+ const [frames, setFrames] = useState([]);
+ const [latest, setLatest] = useState(null);
+ const [isOpen, setIsOpen] = useState(false);
+ const esRef = useRef(null);
+
+ useEffect(() => {
+ if (!url || !enabled) return undefined;
+ setFrames([]);
+ setLatest(null);
+ setIsOpen(false);
+
+ const es = new EventSource(url);
+ esRef.current = es;
+
+ es.onopen = () => setIsOpen(true);
+ es.onmessage = (evt) => {
+ const data = JSON.parse(evt.data);
+ setFrames((prev) => [...prev, data]);
+ setLatest(data);
+ if (TERMINAL_TYPES.has(data?.type)) {
+ es.close();
+ }
+ };
+ es.onerror = () => {
+ if (es.readyState === EventSource.CLOSED) setIsOpen(false);
+ };
+
+ return () => {
+ es.close();
+ esRef.current = null;
+ };
+ }, [url, enabled]);
+
+ return { frames, latest, isOpen, close: () => esRef.current?.close() };
+}
diff --git a/client/src/services/apiPipeline.js b/client/src/services/apiPipeline.js
index 1e7a830f63..4faa6ce4a2 100644
--- a/client/src/services/apiPipeline.js
+++ b/client/src/services/apiPipeline.js
@@ -299,6 +299,25 @@ export const resolvePipelineArcIssues = (seriesId, { findings, providerOverride,
body: JSON.stringify({ findings, providerOverride, modelOverride }),
});
+// ---- Volume beat-sheet bulk generator ----
+// Sequential idea-stage run across every issue in a volume. `mode` is
+// 'skip-existing' (default) or 'regenerate-all'. Returns
+// { runId, alreadyRunning, sseUrl } — subscribe via pipelineVolumeBeatsSseUrl
+// to stream per-issue progress.
+export const startPipelineVolumeBeats = (seriesId, seasonId, { mode, providerOverride, modelOverride } = {}) =>
+ request(`/pipeline/series/${encodeURIComponent(seriesId)}/seasons/${encodeURIComponent(seasonId)}/generate-beats`, {
+ method: 'POST',
+ body: JSON.stringify({ mode, providerOverride, modelOverride }),
+ });
+
+export const cancelPipelineVolumeBeats = (seriesId, seasonId) =>
+ request(`/pipeline/series/${encodeURIComponent(seriesId)}/seasons/${encodeURIComponent(seasonId)}/generate-beats/cancel`, {
+ method: 'POST',
+ });
+
+export const pipelineVolumeBeatsSseUrl = (seriesId, seasonId) =>
+ `/api/pipeline/series/${encodeURIComponent(seriesId)}/seasons/${encodeURIComponent(seasonId)}/generate-beats/progress`;
+
// ---- Auto-run text chain ----
export const startPipelineAutoRunText = (issueId, opts = {}) =>
request(`/pipeline/issues/${encodeURIComponent(issueId)}/auto-run-text`, {
diff --git a/server/routes/pipeline.js b/server/routes/pipeline.js
index ba4e350ba1..99b3012d2d 100644
--- a/server/routes/pipeline.js
+++ b/server/routes/pipeline.js
@@ -37,6 +37,7 @@ 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 * as volumeBeatsRunner from '../services/pipeline/volumeBeatsRunner.js';
import {
enqueueVisualImage,
enqueueVisualComicPage,
@@ -84,6 +85,19 @@ const mapServiceError = (err) => {
return err;
};
+// gpt-image-2 (codex backend) caps at 3840px per edge and 8,294,400 total
+// pixels. Mirror that ceiling for every pipeline image-gen route. Local
+// mflux can render up to 3840 in principle but is impractically slow past
+// ~2048 — the UI's `compatible: ['codex']` filter on the 4K presets keeps
+// those out of the local picker. The validator is shared because the cap
+// and refinement message must stay identical across schemas.
+const MAX_IMAGE_EDGE = 3840;
+const MAX_IMAGE_PIXELS = 8_294_400;
+const imageEdge = z.number().int().min(64).max(MAX_IMAGE_EDGE).optional();
+const refineImagePixelCap = (d) =>
+ !(d.width && d.height) || d.width * d.height <= MAX_IMAGE_PIXELS;
+const PIXEL_CAP_MESSAGE = `Total pixels (width × height) must be ≤ ${MAX_IMAGE_PIXELS.toLocaleString()}`;
+
// ---- Series schemas ----
// Bible entry shape is owned by the canonical schemas in `server/lib/validation.js`
@@ -302,13 +316,13 @@ const visualGenerateSchema = z.object({
extraStyle: z.string().trim().max(2000).optional(),
mode: z.enum(['local', 'codex']).optional(),
modelId: z.string().trim().max(64).optional(),
- width: z.number().int().min(64).max(2048).optional(),
- height: z.number().int().min(64).max(2048).optional(),
+ width: imageEdge,
+ height: imageEdge,
steps: z.number().int().min(1).max(150).optional(),
cfgScale: z.number().min(0).max(30).optional(),
guidance: z.number().min(0).max(30).optional(),
seed: z.number().int().min(0).optional(),
-});
+}).refine(refineImagePixelCap, { message: PIXEL_CAP_MESSAGE, path: ['width'] });
// Comic-issue front cover render. Accepts an optional `coverScript`
// override (otherwise the route reads it from stages.comicPages.cover.script);
@@ -322,13 +336,23 @@ const comicCoverRenderSchema = z.object({
extraStyle: z.string().trim().max(2000).optional(),
mode: z.enum(['local', 'codex']).optional(),
modelId: z.string().trim().max(64).optional(),
- width: z.number().int().min(64).max(2048).optional(),
- height: z.number().int().min(64).max(2048).optional(),
+ width: imageEdge,
+ height: imageEdge,
steps: z.number().int().min(1).max(150).optional(),
cfgScale: z.number().min(0).max(30).optional(),
guidance: z.number().min(0).max(30).optional(),
seed: z.number().int().min(0).optional(),
-});
+ // Proof vs Final render variant. Each variant lands in its own slot
+ // (cover.proofImage / cover.finalImage) so the user can keep a fast
+ // proof for layout decisions and a hi-res final for the PDF.
+ target: z.enum(['proof', 'final']).optional().default('proof'),
+ // When the user likes the proof and wants the final to preserve its
+ // composition, set this to true — the server will pass the proof image
+ // as the init image for the final render at low denoise strength.
+ // Codex backend silently ignores it (gpt-image-2's $imagegen tool has
+ // no init-image input); local + external honor it.
+ useProofAsBase: z.boolean().optional().default(false),
+}).refine(refineImagePixelCap, { message: PIXEL_CAP_MESSAGE, path: ['width'] });
// 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
@@ -338,13 +362,16 @@ const comicPageRenderSchema = z.object({
extraStyle: z.string().trim().max(2000).optional(),
mode: z.enum(['local', 'codex']).optional(),
modelId: z.string().trim().max(64).optional(),
- width: z.number().int().min(64).max(2048).optional(),
- height: z.number().int().min(64).max(2048).optional(),
+ width: imageEdge,
+ height: imageEdge,
steps: z.number().int().min(1).max(150).optional(),
cfgScale: z.number().min(0).max(30).optional(),
guidance: z.number().min(0).max(30).optional(),
seed: z.number().int().min(0).optional(),
-});
+ // See comicCoverRenderSchema for the proof/final semantics.
+ target: z.enum(['proof', 'final']).optional().default('proof'),
+ useProofAsBase: z.boolean().optional().default(false),
+}).refine(refineImagePixelCap, { message: PIXEL_CAP_MESSAGE, path: ['width'] });
const episodeVideoSchema = z.object({
aspectRatio: z.enum(ASPECT_RATIOS).optional(),
@@ -419,6 +446,14 @@ const arcVerifySchema = z.object(providerOverrideShape);
// Volume / season verify shares the same provider/model override shape.
const volumeVerifySchema = z.object(providerOverrideShape);
+// Volume beat-sheets bulk generator. `mode` defaults to skip-existing so a
+// rerun on a partially-expanded volume only fills empty slots; the explicit
+// 'regenerate-all' is the "blow away every beat sheet" path.
+const volumeBeatsGenerateSchema = z.object({
+ ...providerOverrideShape,
+ mode: z.enum(volumeBeatsRunner.VOLUME_BEATS_MODES).optional().default('skip-existing'),
+});
+
// Auto-resolve verification findings. `findings` empty/omitted = re-verify
// first then resolve everything; otherwise the LLM only addresses the
// caller-supplied subset (per-finding "Resolve" buttons).
@@ -771,6 +806,40 @@ router.post('/series/:id/seasons/:seasonId/verify', asyncHandler(async (req, res
res.json(result);
}));
+// Sequential beat-sheet (idea stage) generator for every issue in a volume.
+// Runs serially so each issue's prompt sees the prior issue's freshly-written
+// beats via buildIdeaContextAugment; SSE streams per-issue progress. Pairs
+// naturally with the volume verify pass — generate-then-validate is the
+// expected workflow.
+router.post('/series/:id/seasons/:seasonId/generate-beats', asyncHandler(async (req, res) => {
+ const body = validateRequest(volumeBeatsGenerateSchema, req.body ?? {});
+ const result = await volumeBeatsRunner.startVolumeBeatsRun(
+ req.params.id,
+ req.params.seasonId,
+ {
+ mode: body.mode,
+ providerId: body.providerOverride,
+ model: body.modelOverride,
+ },
+ ).catch((err) => { throw mapServiceError(err); });
+ res.json({
+ ...result,
+ sseUrl: `/api/pipeline/series/${req.params.id}/seasons/${req.params.seasonId}/generate-beats/progress`,
+ });
+}));
+
+router.get('/series/:id/seasons/:seasonId/generate-beats/progress', (req, res) => {
+ const attached = volumeBeatsRunner.attachClient(req.params.seasonId, res);
+ if (!attached) {
+ res.status(404).json({ error: 'No active beat-sheet run for this volume' });
+ }
+});
+
+router.post('/series/:id/seasons/:seasonId/generate-beats/cancel', asyncHandler(async (req, res) => {
+ const canceled = volumeBeatsRunner.cancelVolumeBeatsRun(req.params.seasonId);
+ res.json({ canceled });
+}));
+
// Auto-resolve verification findings. Persists the LLM's patched arc + season
// outlines in one call. Per-episode issue records are not touched.
router.post('/series/:id/arc/resolve-issues', asyncHandler(async (req, res) => {
diff --git a/server/services/pipeline/autoRunner.js b/server/services/pipeline/autoRunner.js
index 3194131999..bf9b203ee4 100644
--- a/server/services/pipeline/autoRunner.js
+++ b/server/services/pipeline/autoRunner.js
@@ -18,7 +18,7 @@
import { randomUUID } from 'crypto';
import { broadcastSse, attachSseClient, closeJobAfterDelay } from '../../lib/sseUtils.js';
import { generateStage } from './textStages.js';
-import { getIssue, updateIssue } from './issues.js';
+import { getIssue, updateIssue, isStageReady } from './issues.js';
import { startEpisodeVideoForIssue, ERR_NO_STORYBOARDS } from './episodeVideo.js';
// runs: Map<issueId, { runId, clients[], lastPayload, cancelRequested, startedAt }>
@@ -141,11 +141,7 @@ export async function startAutoRunTextStages(issueId, options = {}) {
async function runStageIfNeeded(issueId, stageId, options) {
const issue = await getIssue(issueId);
- const cur = issue.stages?.[stageId];
- // Skip if the user has already populated this stage and we aren't forced.
- // 'edited' = user typed into the editor; 'ready' = LLM filled and user
- // hasn't asked to rerun. Both are good — fall through to the next stage.
- if (!options.force && cur && (cur.status === 'ready' || cur.status === 'edited') && cur.output) {
+ if (!options.force && isStageReady(issue.stages?.[stageId])) {
broadcast(issueId, { type: 'skip', stage: stageId, reason: 'already populated' });
return;
}
diff --git a/server/services/pipeline/issues.js b/server/services/pipeline/issues.js
index d3c2a6209a..560cf8e1cb 100644
--- a/server/services/pipeline/issues.js
+++ b/server/services/pipeline/issues.js
@@ -92,6 +92,16 @@ export const STAGE_IDS = Object.freeze([...TEXT_STAGE_IDS, ...VISUAL_STAGE_IDS,
// lands so voice users don't navigate to an empty route. The audio stage
// itself is still a valid write target via STAGE_IDS.
export const NAVIGABLE_STAGE_IDS = Object.freeze([...TEXT_STAGE_IDS, ...VISUAL_STAGE_IDS]);
+
+// "This stage has usable content and shouldn't be regenerated by default."
+// `edited` = user typed into the editor; `ready` = LLM filled and the user
+// hasn't asked to rerun. Both are good — auto-runners skip past them unless
+// `force` is set. Defined here so every coordinator agrees on the predicate.
+export function isStageReady(stage) {
+ if (!stage) return false;
+ if (stage.status !== 'ready' && stage.status !== 'edited') return false;
+ return !!(stage.output && stage.output.trim());
+}
export const STAGE_STATUSES = Object.freeze(['empty', 'generating', 'ready', 'edited', 'needs-review', 'error']);
export const ISSUE_STATUSES = Object.freeze(['draft', 'running', 'needs-review', 'shipped']);
diff --git a/server/services/pipeline/issues.test.js b/server/services/pipeline/issues.test.js
index 33e0d29cb1..40a219a68f 100644
--- a/server/services/pipeline/issues.test.js
+++ b/server/services/pipeline/issues.test.js
@@ -306,6 +306,26 @@ describe('pipeline issues service', () => {
await expect(svc.deleteIssue(i.id)).rejects.toMatchObject({ code: svc.ERR_NOT_FOUND });
});
+ describe('isStageReady', () => {
+ it('returns true for ready/edited stages with non-empty output', () => {
+ expect(svc.isStageReady({ status: 'ready', output: 'beats' })).toBe(true);
+ expect(svc.isStageReady({ status: 'edited', output: 'user typed' })).toBe(true);
+ });
+ it('returns false for empty/whitespace output regardless of status', () => {
+ expect(svc.isStageReady({ status: 'ready', output: '' })).toBe(false);
+ expect(svc.isStageReady({ status: 'ready', output: ' ' })).toBe(false);
+ });
+ it('returns false for non-terminal statuses', () => {
+ expect(svc.isStageReady({ status: 'error', output: 'partial' })).toBe(false);
+ expect(svc.isStageReady({ status: 'generating', output: 'mid' })).toBe(false);
+ expect(svc.isStageReady({ status: 'empty', output: '' })).toBe(false);
+ });
+ it('returns false for null/undefined stage', () => {
+ expect(svc.isStageReady(null)).toBe(false);
+ expect(svc.isStageReady(undefined)).toBe(false);
+ });
+ });
+
describe('insertIssueWithId', () => {
it('preserves the caller-supplied id', async () => {
const i = await svc.insertIssueWithId({ id: 'iss-fixed-xyz', seriesId: 'ser-1', title: 'Imported' });
diff --git a/server/services/pipeline/volumeBeatsRunner.js b/server/services/pipeline/volumeBeatsRunner.js
new file mode 100644
index 0000000000..c784fa80ee
--- /dev/null
+++ b/server/services/pipeline/volumeBeatsRunner.js
@@ -0,0 +1,190 @@
+/**
+ * Pipeline — Volume Beat-Sheet Runner
+ *
+ * Runs the idea stage sequentially across every issue in a volume so each
+ * generation picks up the prior issue's freshly-persisted beats via
+ * `buildIdeaContextAugment` (which re-reads neighbors per call). Parallel
+ * generation would defeat that — the second issue's prompt would still see
+ * the first issue's *synopsis* instead of its newly-written beats.
+ *
+ * Mirrors `autoRunner.js`: per-volume in-memory record keyed by `seasonId`,
+ * SSE progress to attached clients, cancel flag checked between issues.
+ *
+ * Two modes:
+ * - 'skip-existing' (default): issues whose idea stage is ready/edited with
+ * output stay untouched; only empty/error/draft slots are filled.
+ * - 'regenerate-all': overwrites every issue's beat sheet.
+ *
+ * Frame shapes broadcast over SSE:
+ * { type: 'start', runId, seasonId, total, planned: [issueIds] }
+ * { type: 'issue:skip', issueId, ordinal, total, reason }
+ * { type: 'issue:start', issueId, issueNumber, issueTitle, ordinal, total }
+ * { type: 'issue:complete',issueId, ordinal, total, status, length, runId }
+ * { type: 'issue:error', issueId, ordinal, total, error }
+ * { type: 'complete', runId, generated, skipped, errored, completedAt }
+ * { type: 'canceled', runId, completedAt }
+ * { type: 'error', runId, error, failedAt }
+ */
+
+import { randomUUID } from 'crypto';
+import { broadcastSse, attachSseClient, closeJobAfterDelay } from '../../lib/sseUtils.js';
+import { generateStage } from './textStages.js';
+import { listIssues, isStageReady } from './issues.js';
+import { getSeries } from './series.js';
+import { compareIssuesByPosition } from './arcPlanner.js';
+import { getSeason } from './seasons.js';
+
+// runs: Map<seasonId, { runId, clients[], lastPayload, cancelRequested, startedAt }>
+const runs = new Map();
+
+export const VOLUME_BEATS_MODES = Object.freeze(['skip-existing', 'regenerate-all']);
+
+export function isVolumeBeatsRunActive(seasonId) {
+ return runs.has(seasonId);
+}
+
+export function attachClient(seasonId, res) {
+ return attachSseClient(runs, seasonId, res);
+}
+
+export function cancelVolumeBeatsRun(seasonId) {
+ const run = runs.get(seasonId);
+ if (!run) return false;
+ run.cancelRequested = true;
+ return true;
+}
+
+function broadcast(seasonId, payload) {
+ const run = runs.get(seasonId);
+ if (!run) return;
+ broadcastSse(run, payload);
+}
+
+/**
+ * Kick off the volume beat-sheet chain. Returns the runId immediately;
+ * progress lands via SSE. Idempotent when a run is in flight for this volume.
+ */
+export async function startVolumeBeatsRun(seriesId, seasonId, options = {}) {
+ if (runs.has(seasonId)) {
+ return { runId: runs.get(seasonId).runId, alreadyRunning: true };
+ }
+ // Validate scope up front — bad ids should 404 before we kick off, not
+ // surface as a deferred SSE error frame.
+ await getSeries(seriesId);
+ await getSeason(seriesId, seasonId);
+
+ const mode = VOLUME_BEATS_MODES.includes(options.mode) ? options.mode : 'skip-existing';
+ const runId = randomUUID();
+ const record = {
+ runId,
+ clients: [],
+ lastPayload: null,
+ cancelRequested: false,
+ startedAt: new Date().toISOString(),
+ };
+ runs.set(seasonId, record);
+
+ (async () => {
+ // Outer try/catch is the one permitted boundary — without it an LLM
+ // rejection would surface as an unhandledRejection and kill the process.
+ try {
+ const all = await listIssues({ seriesId });
+ const volumeIssues = all
+ .filter((i) => i.seasonId === seasonId)
+ .sort(compareIssuesByPosition);
+
+ broadcast(seasonId, {
+ type: 'start',
+ runId,
+ seasonId,
+ mode,
+ total: volumeIssues.length,
+ planned: volumeIssues.map((i) => i.id),
+ });
+
+ let generated = 0;
+ let skipped = 0;
+ let errored = 0;
+
+ for (let idx = 0; idx < volumeIssues.length; idx += 1) {
+ if (record.cancelRequested) break;
+ const ordinal = idx + 1;
+ const total = volumeIssues.length;
+ const issue = volumeIssues[idx];
+
+ if (mode === 'skip-existing' && isStageReady(issue.stages?.idea)) {
+ skipped += 1;
+ broadcast(seasonId, {
+ type: 'issue:skip',
+ issueId: issue.id,
+ issueNumber: issue.number,
+ issueTitle: issue.title,
+ ordinal,
+ total,
+ reason: 'beats already present',
+ });
+ continue;
+ }
+
+ broadcast(seasonId, {
+ type: 'issue:start',
+ issueId: issue.id,
+ issueNumber: issue.number,
+ issueTitle: issue.title,
+ ordinal,
+ total,
+ });
+
+ // Per-issue catch so one bad issue doesn't abort the rest of the
+ // chain — we surface the error frame and move on. The stage record
+ // is already marked 'error' inside generateStage's own catch.
+ try {
+ const { stage, runId: stageRunId } = await generateStage(issue.id, 'idea', {
+ providerId: options.providerId,
+ model: options.model,
+ });
+ generated += 1;
+ broadcast(seasonId, {
+ type: 'issue:complete',
+ issueId: issue.id,
+ ordinal,
+ total,
+ status: stage.status,
+ length: stage.output?.length || 0,
+ runId: stageRunId,
+ });
+ } catch (err) {
+ errored += 1;
+ broadcast(seasonId, {
+ type: 'issue:error',
+ issueId: issue.id,
+ ordinal,
+ total,
+ error: (err?.message || String(err)).slice(0, 500),
+ });
+ }
+ }
+
+ broadcast(seasonId, {
+ type: record.cancelRequested ? 'canceled' : 'complete',
+ runId,
+ generated,
+ skipped,
+ errored,
+ completedAt: new Date().toISOString(),
+ });
+ console.log(`✅ Pipeline volume-beats ${record.cancelRequested ? 'canceled' : 'complete'} — season=${seasonId.slice(0, 8)} runId=${runId.slice(0, 8)} generated=${generated} skipped=${skipped} errored=${errored}`);
+ } catch (err) {
+ const message = (err?.message || String(err)).slice(0, 1000);
+ console.error(`❌ Pipeline volume-beats failed — season=${seasonId.slice(0, 8)} ${message}`);
+ broadcast(seasonId, { type: 'error', runId, error: message, failedAt: new Date().toISOString() });
+ } finally {
+ closeJobAfterDelay(runs, seasonId);
+ }
+ })();
+
+ return { runId, alreadyRunning: false };
+}
+
+// Export internals for tests.
+export const __testing = { runs };
diff --git a/server/services/pipeline/volumeBeatsRunner.test.js b/server/services/pipeline/volumeBeatsRunner.test.js
new file mode 100644
index 0000000000..fb917bab63
--- /dev/null
+++ b/server/services/pipeline/volumeBeatsRunner.test.js
@@ -0,0 +1,229 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+const fileStore = new Map();
+
+vi.mock('../../lib/fileUtils.js', () => ({
+ PATHS: { data: '/mock/data' },
+ ensureDir: vi.fn().mockResolvedValue(undefined),
+ atomicWrite: vi.fn(async (path, data) => { fileStore.set(path, data); }),
+ readJSONFile: vi.fn(async (path, fallback) => (fileStore.has(path) ? fileStore.get(path) : fallback)),
+}));
+
+let uuidCounter = 0;
+vi.mock('crypto', async () => {
+ const actual = await vi.importActual('crypto');
+ return { ...actual, randomUUID: () => `uuid-${++uuidCounter}` };
+});
+
+// Inline generator that writes ready beats without making an LLM call —
+// we're testing the coordinator, not the prompt.
+const generated = [];
+vi.mock('./textStages.js', async () => {
+ const issuesSvc = await import('./issues.js');
+ return {
+ generateStage: vi.fn(async (issueId, stageId, _opts) => {
+ generated.push({ issueId, stageId });
+ const { issue, stage } = await issuesSvc.updateStage(issueId, stageId, {
+ status: 'ready',
+ output: `BEATS-${issueId.slice(0, 6)}`,
+ lastRunId: `run-${issueId.slice(0, 6)}`,
+ });
+ return { issue, stage, runId: `run-${issueId.slice(0, 6)}` };
+ }),
+ };
+});
+
+const seriesSvc = await import('./series.js');
+const issuesSvc = await import('./issues.js');
+const seasonsSvc = await import('./seasons.js');
+const runner = await import('./volumeBeatsRunner.js');
+
+const waitFor = async (predicate, { timeoutMs = 1500, intervalMs = 5 } = {}) => {
+ const start = Date.now();
+ while (Date.now() - start < timeoutMs) {
+ if (predicate()) return;
+ await new Promise((r) => setTimeout(r, intervalMs));
+ }
+ throw new Error('waitFor: predicate never became true');
+};
+
+async function seed({ issueCount = 3 } = {}) {
+ const series = await seriesSvc.createSeries({ name: 'S', logline: 'L', premise: 'P' });
+ const season = await seasonsSvc.createSeason(series.id, { title: 'V1', number: 1 });
+ const issues = [];
+ for (let i = 1; i <= issueCount; i += 1) {
+ const created = await issuesSvc.createIssue({
+ seriesId: series.id,
+ title: `Issue ${i}`,
+ seasonId: season.id,
+ arcPosition: i,
+ });
+ issues.push(created);
+ }
+ return { series, season, issues };
+}
+
+describe('pipeline volume beat-sheet runner', () => {
+ beforeEach(() => {
+ fileStore.clear();
+ uuidCounter = 0;
+ generated.length = 0;
+ runner.__testing.runs.clear();
+ vi.clearAllMocks();
+ });
+
+ it('runs idea stage sequentially across every issue in volume order', async () => {
+ const { series, season, issues } = await seed({ issueCount: 3 });
+ const { runId, alreadyRunning } = await runner.startVolumeBeatsRun(series.id, season.id);
+ expect(runId).toBeTruthy();
+ expect(alreadyRunning).toBe(false);
+
+ await waitFor(() => {
+ const run = runner.__testing.runs.get(season.id);
+ return run?.lastPayload?.type === 'complete';
+ });
+
+ expect(generated).toHaveLength(3);
+ expect(generated.map((g) => g.issueId)).toEqual(issues.map((i) => i.id));
+ expect(generated.every((g) => g.stageId === 'idea')).toBe(true);
+ });
+
+ it("skip-existing mode skips issues whose idea stage has output (status: 'ready' / 'edited')", async () => {
+ const { series, season, issues } = await seed({ issueCount: 3 });
+ await issuesSvc.updateStage(issues[1].id, 'idea', { status: 'ready', output: 'PREFILLED-BEATS' });
+ await issuesSvc.updateStage(issues[2].id, 'idea', { status: 'edited', output: 'USER-EDITED-BEATS' });
+
+ await runner.startVolumeBeatsRun(series.id, season.id);
+ await waitFor(() => {
+ const run = runner.__testing.runs.get(season.id);
+ return run?.lastPayload?.type === 'complete';
+ });
+
+ expect(generated.map((g) => g.issueId)).toEqual([issues[0].id]);
+ const terminal = runner.__testing.runs.get(season.id).lastPayload;
+ expect(terminal.generated).toBe(1);
+ expect(terminal.skipped).toBe(2);
+ });
+
+ it('regenerate-all mode overwrites every issue regardless of existing beats', async () => {
+ const { series, season, issues } = await seed({ issueCount: 3 });
+ await issuesSvc.updateStage(issues[1].id, 'idea', { status: 'ready', output: 'PREFILLED' });
+
+ await runner.startVolumeBeatsRun(series.id, season.id, { mode: 'regenerate-all' });
+ await waitFor(() => {
+ const run = runner.__testing.runs.get(season.id);
+ return run?.lastPayload?.type === 'complete';
+ });
+
+ expect(generated.map((g) => g.issueId)).toEqual(issues.map((i) => i.id));
+ const terminal = runner.__testing.runs.get(season.id).lastPayload;
+ expect(terminal.generated).toBe(3);
+ expect(terminal.skipped).toBe(0);
+ });
+
+ it("skip-existing does NOT skip 'error' / 'empty' issues — those need a retry", async () => {
+ const { series, season, issues } = await seed({ issueCount: 3 });
+ await issuesSvc.updateStage(issues[0].id, 'idea', { status: 'error', errorMessage: 'previous failure' });
+ await issuesSvc.updateStage(issues[1].id, 'idea', { status: 'ready', output: 'GOOD' });
+
+ await runner.startVolumeBeatsRun(series.id, season.id);
+ await waitFor(() => {
+ const run = runner.__testing.runs.get(season.id);
+ return run?.lastPayload?.type === 'complete';
+ });
+
+ const ids = generated.map((g) => g.issueId);
+ expect(ids).toContain(issues[0].id);
+ expect(ids).toContain(issues[2].id);
+ expect(ids).not.toContain(issues[1].id);
+ });
+
+ it('per-issue error does not abort the rest of the chain', async () => {
+ const { series, season, issues } = await seed({ issueCount: 3 });
+ const textStages = await import('./textStages.js');
+ textStages.generateStage.mockImplementation(async (issueId, stageId) => {
+ generated.push({ issueId, stageId });
+ if (issueId === issues[1].id) {
+ throw new Error('LLM said no');
+ }
+ const { issue, stage } = await issuesSvc.updateStage(issueId, stageId, {
+ status: 'ready', output: `O-${issueId.slice(0, 6)}`, lastRunId: `r-${issueId.slice(0, 6)}`,
+ });
+ return { issue, stage, runId: `r-${issueId.slice(0, 6)}` };
+ });
+
+ await runner.startVolumeBeatsRun(series.id, season.id);
+ await waitFor(() => {
+ const run = runner.__testing.runs.get(season.id);
+ return run?.lastPayload?.type === 'complete';
+ });
+
+ expect(generated.map((g) => g.issueId)).toEqual(issues.map((i) => i.id));
+ const terminal = runner.__testing.runs.get(season.id).lastPayload;
+ expect(terminal.generated).toBe(2);
+ expect(terminal.errored).toBe(1);
+ });
+
+ it('returns alreadyRunning=true on concurrent start for the same volume', async () => {
+ const { series, season } = await seed();
+ const textStages = await import('./textStages.js');
+ textStages.generateStage.mockImplementation(async (issueId, stageId) => {
+ generated.push({ issueId, stageId });
+ await new Promise((r) => setTimeout(r, 25));
+ const { issue, stage } = await issuesSvc.updateStage(issueId, stageId, {
+ status: 'ready', output: 'O', lastRunId: 'r',
+ });
+ return { issue, stage, runId: 'r' };
+ });
+
+ const first = await runner.startVolumeBeatsRun(series.id, season.id);
+ const second = await runner.startVolumeBeatsRun(series.id, season.id);
+ expect(second.alreadyRunning).toBe(true);
+ expect(second.runId).toBe(first.runId);
+ await waitFor(() => {
+ const run = runner.__testing.runs.get(season.id);
+ return run?.lastPayload?.type === 'complete';
+ });
+ });
+
+ it('cancelVolumeBeatsRun stops the chain between issues', async () => {
+ const { series, season } = await seed({ issueCount: 4 });
+ const textStages = await import('./textStages.js');
+ textStages.generateStage.mockImplementation(async (issueId, stageId) => {
+ generated.push({ issueId, stageId });
+ await new Promise((r) => setTimeout(r, 50));
+ const { issue, stage } = await issuesSvc.updateStage(issueId, stageId, {
+ status: 'ready', output: 'O', lastRunId: 'r',
+ });
+ return { issue, stage, runId: 'r' };
+ });
+
+ runner.startVolumeBeatsRun(series.id, season.id);
+ await waitFor(() => generated.length >= 1);
+ runner.cancelVolumeBeatsRun(season.id);
+ await waitFor(() => {
+ const run = runner.__testing.runs.get(season.id);
+ const t = run?.lastPayload?.type;
+ return t === 'canceled' || t === 'complete' || t === 'error';
+ });
+ expect(generated.length).toBeLessThan(4);
+ expect(runner.__testing.runs.get(season.id).lastPayload.type).toBe('canceled');
+ });
+
+ it('emits a start frame with the planned issue ids and total', async () => {
+ const { series, season, issues } = await seed({ issueCount: 2 });
+ await runner.startVolumeBeatsRun(series.id, season.id);
+
+ await waitFor(() => {
+ const run = runner.__testing.runs.get(season.id);
+ return run?.lastPayload?.type === 'complete';
+ });
+
+ // The first broadcast frame is the start frame — we can't replay it
+ // directly (lastPayload is the most recent), but we can validate the
+ // count of issues processed matches the seed.
+ const terminal = runner.__testing.runs.get(season.id).lastPayload;
+ expect(terminal.generated + terminal.skipped + terminal.errored).toBe(issues.length);
+ });
+
+});