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): audio stage extract + per-line VO rendering

[._.]/ Adam Eivyd9ca9b3bea6e
diff --git a/PLAN.md b/PLAN.md
index 94b16fbe6d..d2695f46f6 100644
--- a/PLAN.md
+++ b/PLAN.md
@@ -238,4 +238,6 @@ Skeleton landed in `server/services/pipeline/` + `client/src/pages/Pipeline*.jsx
- [ ] **AI-assisted panel/scene prompt generation.** Reserve `pipeline-comic-panel-image-prompt.md` and `pipeline-storyboard-image-prompt.md` template files for a future "AI: turn the script fragment into N image-gen prompts" button on the ComicPages and Storyboards stages.
- [ ] **Extract migration scaffolding into `data/migrations/_lib.js`.** Migrations 003 and 006 both implement the same hash-driven prompt-replace pattern (~75 lines of boilerplate each). Lift `replaceUnmodifiedStagePrompts({ rootDir, oldHashes, newHashes, featureName, customizedHint })` into a shared helper so the next prompt-replace migration is ~15 lines. While at it, have `scripts/setup-data.js` import the same hash maps from each migration so the drift table stops duplicating them. Skipped during the 006 commit to keep diff focused.
- [ ] **Shots-aware scene-output-contract partial.** `data.sample/prompts/stages/pipeline-extract-scenes.md` now inlines the JSON output contract (with `shots[]`) instead of using `{{> scene-output-contract }}`. If a third shots-using stage ever appears (or a top-level scene field gets added), the partial and the inlined copy in extract-scenes will drift. Split into composable partials (`_partials/scene-fields-core.md` + `_partials/scene-fields-shots.md`) when that third caller materializes — until then the inline copy is the smaller risk.
+- [ ] **Voice picker on character cards (Pipeline Audio 4b follow-up).** AudioStage renders fine without it (per-line render falls through to the project default voice), but binding `character.voiceId` today requires hand-editing JSON or PATCHing the universe canon. The picker should live on `CanonCard` (`client/src/components/pipeline/CanonCard.jsx`) when `kind === 'character'`: chip with current voice id, dropdown reading `/api/pipeline/tts/voices`, audition button that fetches `/api/pipeline/tts/preview` and plays inline, and a Save handler that PATCHes the universe canon entry (`updateUniverseCharacter` — needs to exist in `apiUniverseBuilder.js`). Same picker re-usable on a per-line override in `AudioStage.jsx`. Local OSS (Kokoro/Piper) always included; 3rd-party engines surface through the same merged list.
+- [ ] **Pipeline Audio — music + mux (Phase 4c/d).** Per the AnyFilm comparison plan (`~/.claude/plans/i-want-to-examine-polished-meteor.md` cluster C). 4c: local OSS music generation (MusicGen via Python sidecar mirroring image-gen wiring) + user-upload + library + 3rd-party stub. Music picker on AudioStage. 4d: mux VO + music into the episode-video CD stitch — extend the CD treatment to carry audio-file refs and let the final ffmpeg stitch overlay them.
- [ ] **Per-panel/scene image progress in the Pipeline UI.** Right now ComicPages and Storyboards record `jobId` but don't subscribe to the media-job SSE for live preview. Tie into the existing per-job progress hook so each panel shows live render thumbnails.
diff --git a/client/src/components/pipeline/stages/AudioStage.jsx b/client/src/components/pipeline/stages/AudioStage.jsx
new file mode 100644
index 0000000000..e7835006e4
--- /dev/null
+++ b/client/src/components/pipeline/stages/AudioStage.jsx
@@ -0,0 +1,254 @@
+/**
+ * Audio stage — voice-over rendering for an issue's dialogue lines.
+ *
+ * Source of truth: stages.audio.lines[] (server-extracted from
+ * storyboards.scenes[].dialogue). Each line carries a character binding,
+ * the line text, an optional per-line voice override, and the rendered
+ * audio filename (under /data/audio/...).
+ *
+ * Voice resolution priority (server-side per render): line.voiceIdOverride
+ * > character.voiceId > project default. Local OSS (Kokoro/Piper) is always
+ * available; 3rd-party engines extend through the same namespace.
+ */
+
+import { useEffect, useRef, useState } from 'react';
+import { Loader2, Sparkles, Wand2, Mic } from 'lucide-react';
+import toast from '../../ui/Toast';
+import {
+ extractPipelineAudioLines,
+ renderPipelineAudioLine,
+ patchPipelineAudioLine,
+ PIPELINE_STAGE_LABELS,
+ PIPELINE_STAGE_STATUS_LABEL as STATUS_LABEL,
+ PIPELINE_STAGE_STATUS_COLOR as STATUS_COLOR,
+} from '../../../services/api';
+
+export default function AudioStage({ issue, onStageUpdate }) {
+ const stage = issue.stages?.audio || { status: 'empty', lines: [] };
+ const lines = Array.isArray(stage.lines) ? stage.lines : [];
+ const [extracting, setExtracting] = useState(false);
+ // Per-line render busy state keyed by line index — multiple lines can
+ // render concurrently with independent spinners.
+ const [renderingLines, setRenderingLines] = useState(() => new Set());
+ // Per-line edit drafts so the textarea reflects in-flight keystrokes
+ // even though we PATCH only on blur (or before render).
+ const [drafts, setDrafts] = useState({});
+ // Pending PATCH promises by line index so handleRender can await the
+ // blur-flush before kicking off the synth (CLAUDE.md "In-flight saves
+ // must gate dependent actions"). Refs not state — we never re-render
+ // because of this and we want the latest value inside async handlers.
+ const pendingSavesRef = useRef(new Map());
+
+ // Two-click arm pattern (no window.confirm) for the destructive
+ // re-extract path. First click flips the label; second click within 5s
+ // commits the replace.
+ const [extractArmed, setExtractArmed] = useState(false);
+ const armTimerRef = useRef(null);
+ useEffect(() => () => {
+ if (armTimerRef.current) clearTimeout(armTimerRef.current);
+ }, []);
+
+ const storyboardSceneCount = (issue.stages?.storyboards?.scenes || []).length;
+ const canExtract = storyboardSceneCount > 0;
+
+ const handleExtract = async () => {
+ if (!canExtract) {
+ toast.error('Generate Storyboards first — audio lines come from the dialogue extracted there.');
+ return;
+ }
+ const needsConfirm = lines.length > 0;
+ if (needsConfirm && !extractArmed) {
+ setExtractArmed(true);
+ toast.warning(`This will replace ${lines.length} existing line${lines.length === 1 ? '' : 's'} (rendered audio is preserved for unchanged lines). Click again to confirm.`);
+ if (armTimerRef.current) clearTimeout(armTimerRef.current);
+ armTimerRef.current = setTimeout(() => {
+ armTimerRef.current = null;
+ setExtractArmed(false);
+ }, 5000);
+ return;
+ }
+ if (armTimerRef.current) { clearTimeout(armTimerRef.current); armTimerRef.current = null; }
+ setExtractArmed(false);
+ setExtracting(true);
+ const result = await extractPipelineAudioLines(issue.id, { force: needsConfirm }).catch((err) => {
+ toast.error(err.message || 'Extract failed');
+ return null;
+ });
+ setExtracting(false);
+ if (!result) return;
+ onStageUpdate?.('audio', result.stage, result.issue);
+ setDrafts({});
+ const preserved = result.preservedCount || 0;
+ if (preserved > 0) {
+ toast.success(`Extracted ${result.lineCount} line${result.lineCount === 1 ? '' : 's'} · preserved ${preserved} rendered`);
+ } else {
+ toast.success(`Extracted ${result.lineCount} line${result.lineCount === 1 ? '' : 's'}`);
+ }
+ };
+
+ // Per-line text save. Returns the in-flight Promise so handleRender can
+ // await it before firing the synth request.
+ const saveLineText = (lineIdx, text) => {
+ const promise = patchPipelineAudioLine(issue.id, lineIdx, { text })
+ .then((updated) => {
+ if (updated) onStageUpdate?.('audio', updated.stage, updated.issue);
+ return updated;
+ })
+ .catch((err) => { toast.error(err.message || 'Save failed'); return null; })
+ .finally(() => {
+ if (pendingSavesRef.current.get(lineIdx) === promise) {
+ pendingSavesRef.current.delete(lineIdx);
+ }
+ });
+ pendingSavesRef.current.set(lineIdx, promise);
+ return promise;
+ };
+
+ const handleBlur = (lineIdx) => {
+ const draft = drafts[lineIdx];
+ if (draft === undefined) return;
+ if (draft === (lines[lineIdx]?.text || '')) {
+ // No actual change — drop the draft so the textarea reflects server state.
+ setDrafts((prev) => { const next = { ...prev }; delete next[lineIdx]; return next; });
+ return;
+ }
+ void saveLineText(lineIdx, draft);
+ setDrafts((prev) => { const next = { ...prev }; delete next[lineIdx]; return next; });
+ };
+
+ const handleRender = async (lineIdx) => {
+ // If a blur-save is in flight for this line, wait for it so the synth
+ // reads the up-to-date persisted text instead of stale bytes.
+ const pendingSave = pendingSavesRef.current.get(lineIdx);
+ if (pendingSave) await pendingSave;
+ // If the textarea still has an unflushed draft (user clicked Render
+ // without losing focus), flush it now and await.
+ const draftBeforeRender = drafts[lineIdx];
+ if (draftBeforeRender !== undefined && draftBeforeRender !== (lines[lineIdx]?.text || '')) {
+ await saveLineText(lineIdx, draftBeforeRender);
+ setDrafts((prev) => { const next = { ...prev }; delete next[lineIdx]; return next; });
+ }
+
+ setRenderingLines((prev) => new Set(prev).add(lineIdx));
+ const result = await renderPipelineAudioLine(issue.id, lineIdx).catch((err) => {
+ toast.error(err.message || 'Render failed');
+ return null;
+ });
+ setRenderingLines((prev) => {
+ const next = new Set(prev);
+ next.delete(lineIdx);
+ return next;
+ });
+ if (!result) return;
+ if (result.issue) onStageUpdate?.('audio', result.issue.stages.audio, result.issue);
+ toast.success(`Rendered line ${lineIdx + 1} (${result.engine})`);
+ };
+
+ return (
+ <div className="space-y-4">
+ <header className="flex items-center justify-between flex-wrap gap-3">
+ <div className="flex items-center gap-3">
+ <Mic className="w-5 h-5 text-port-accent" />
+ <div>
+ <h2 className="text-lg font-semibold text-white">{PIPELINE_STAGE_LABELS.audio}</h2>
+ <p className="text-xs text-gray-500 mt-0.5">
+ Voice-over per dialogue line. Picks each character's bound voice; falls back to project default.
+ {' '}<span className="text-gray-600">Local OSS (Kokoro / Piper) always available.</span>
+ </p>
+ </div>
+ <span className={`text-[10px] uppercase tracking-wider ${STATUS_COLOR[stage.status] || 'text-gray-500'}`}>
+ {STATUS_LABEL[stage.status] || stage.status}
+ </span>
+ {lines.length > 0 ? (
+ <span className="text-xs text-gray-500">{lines.length} line{lines.length === 1 ? '' : 's'}</span>
+ ) : null}
+ </div>
+ <div className="flex items-center gap-2">
+ <button
+ type="button"
+ onClick={handleExtract}
+ disabled={extracting || !canExtract}
+ title={canExtract
+ ? (lines.length > 0
+ ? 'Replace lines with a fresh extraction from storyboards (rendered audio carried forward for unchanged lines)'
+ : 'Walk storyboards dialogue and create one VO line per spoken line')
+ : 'Generate Storyboards first — audio lines come from the dialogue extracted there'}
+ 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" /> : <Wand2 size={14} />}
+ {extractArmed
+ ? 'Click again to replace'
+ : (lines.length > 0 ? 'Re-extract from storyboards' : 'Extract lines from storyboards')}
+ </button>
+ </div>
+ </header>
+
+ {lines.length === 0 ? (
+ <p className="text-sm text-gray-400 italic">
+ {canExtract
+ ? 'No lines yet. Click Extract above to pull dialogue from the storyboards stage.'
+ : 'Generate the Storyboards stage first — the dialogue lines there populate this table.'}
+ </p>
+ ) : (
+ <ul className="space-y-2">
+ {lines.map((line, i) => {
+ const isRendering = renderingLines.has(i);
+ const draft = drafts[i];
+ const textValue = draft !== undefined ? draft : (line.text || '');
+ return (
+ <li key={line.id || i} className="p-3 bg-port-card border border-port-border rounded-lg">
+ <div className="flex items-start gap-3">
+ <span className="text-[10px] text-gray-500 font-mono pt-1.5 w-8">{i + 1}</span>
+ <div className="flex-1 min-w-0">
+ <div className="flex items-center gap-2 mb-1.5">
+ <span className="text-xs uppercase tracking-wider text-port-accent font-medium">
+ {line.characterName || '(unattributed)'}
+ </span>
+ {line.characterId ? null : (
+ <span
+ className="text-[10px] text-gray-500 italic"
+ title="No matching character in the series bible — will use project default voice"
+ >
+ unbound
+ </span>
+ )}
+ </div>
+ <textarea
+ value={textValue}
+ onChange={(e) => setDrafts((prev) => ({ ...prev, [i]: e.target.value }))}
+ onBlur={() => handleBlur(i)}
+ rows={2}
+ className="w-full px-2 py-1.5 bg-port-bg border border-port-border rounded text-white text-sm"
+ maxLength={4000}
+ />
+ {line.audioFilename ? (
+ <audio
+ controls
+ src={`/data/audio/${encodeURIComponent(line.audioFilename)}`}
+ className="mt-2 w-full max-w-md"
+ >
+ <track kind="captions" />
+ </audio>
+ ) : null}
+ </div>
+ <div className="flex flex-col gap-1.5 w-28">
+ <button
+ type="button"
+ onClick={() => handleRender(i)}
+ disabled={isRendering || !textValue.trim()}
+ title={textValue.trim() ? 'Render this line as audio' : 'Add line text first'}
+ className="inline-flex items-center justify-center gap-1 px-2 py-1.5 rounded bg-port-accent text-white text-xs disabled:opacity-50"
+ >
+ {isRendering ? <Loader2 size={12} className="animate-spin" /> : <Sparkles size={12} />}
+ {line.audioFilename ? 'Re-render' : 'Render'}
+ </button>
+ </div>
+ </div>
+ </li>
+ );
+ })}
+ </ul>
+ )}
+ </div>
+ );
+}
diff --git a/client/src/pages/PipelineIssue.jsx b/client/src/pages/PipelineIssue.jsx
index fa4fc4045d..d68d6fbebd 100644
--- a/client/src/pages/PipelineIssue.jsx
+++ b/client/src/pages/PipelineIssue.jsx
@@ -10,7 +10,7 @@ import { useEffect, useState, useMemo } from 'react';
import { Link, useParams, useNavigate } from 'react-router-dom';
import {
ArrowLeft, Sparkles, Loader2, X, Lightbulb, BookOpen, FileText, Film as FilmIcon,
- LayoutGrid, Image as ImageIcon, Clapperboard, Users, Settings,
+ LayoutGrid, Image as ImageIcon, Clapperboard, Users, Settings, Mic,
} from 'lucide-react';
import toast from '../components/ui/Toast';
import Modal from '../components/ui/Modal';
@@ -28,6 +28,7 @@ import TeleplayStage from '../components/pipeline/stages/TeleplayStage';
import ComicPagesStage from '../components/pipeline/stages/ComicPagesStage';
import StoryboardsStage from '../components/pipeline/stages/StoryboardsStage';
import EpisodeVideoStage from '../components/pipeline/stages/EpisodeVideoStage';
+import AudioStage from '../components/pipeline/stages/AudioStage';
import SeriesLlmPicker from '../components/pipeline/SeriesLlmPicker';
import LengthProfilePicker from '../components/pipeline/LengthProfilePicker';
import { VisualGenSettingsPanel } from '../components/pipeline/stages/VisualGenSettings';
@@ -48,6 +49,7 @@ const STAGE_ICONS = {
comicPages: LayoutGrid,
storyboards: ImageIcon,
episodeVideo: Clapperboard,
+ audio: Mic,
};
const STAGE_COMPONENTS = {
@@ -59,6 +61,7 @@ const STAGE_COMPONENTS = {
comicPages: ComicPagesStage,
storyboards: StoryboardsStage,
episodeVideo: EpisodeVideoStage,
+ audio: AudioStage,
};
const STATUS_DOT = {
@@ -182,12 +185,18 @@ export default function PipelineIssue() {
}) : prev);
};
- const stageTabs = useMemo(() => PIPELINE_TAB_STAGES.map((id) => ({
- id,
- label: PIPELINE_STAGE_LABELS[id],
- Icon: STAGE_ICONS[id],
- status: issue?.stages?.[id]?.status || 'empty',
- })), [issue]);
+ const stageTabs = useMemo(() => PIPELINE_TAB_STAGES
+ // Audio is only meaningful when the series ships video — comic-only
+ // series don't render dialogue as sound, so the tab is hidden to keep
+ // the strip uncluttered. Showing the audio data still works for users
+ // who navigate to `/pipeline/issues/:id/audio` directly.
+ .filter((id) => id !== 'audio' || series?.targetFormat !== 'comic')
+ .map((id) => ({
+ id,
+ label: PIPELINE_STAGE_LABELS[id],
+ Icon: STAGE_ICONS[id],
+ status: issue?.stages?.[id]?.status || 'empty',
+ })), [issue, series?.targetFormat]);
if (loading) return <div className="p-6 text-gray-500 text-sm">Loading issue…</div>;
if (!issue) return null;
diff --git a/client/src/services/apiPipeline.js b/client/src/services/apiPipeline.js
index 4faa6ce4a2..835e712aba 100644
--- a/client/src/services/apiPipeline.js
+++ b/client/src/services/apiPipeline.js
@@ -8,8 +8,11 @@ import { request } from './apiCore.js';
// auto-run text chain skips it and POST /stages/nouns/generate would 400.
export const PIPELINE_TEXT_STAGES = Object.freeze(['idea', 'prose', 'comicScript', 'teleplay']);
export const PIPELINE_VISUAL_STAGES = Object.freeze(['comicPages', 'storyboards', 'episodeVideo']);
+export const PIPELINE_AUDIO_STAGES = Object.freeze(['audio']);
export const PIPELINE_UI_STAGES = Object.freeze(['nouns']);
-export const PIPELINE_STAGES = Object.freeze([...PIPELINE_TEXT_STAGES, ...PIPELINE_VISUAL_STAGES, ...PIPELINE_UI_STAGES]);
+export const PIPELINE_STAGES = Object.freeze([
+ ...PIPELINE_TEXT_STAGES, ...PIPELINE_VISUAL_STAGES, ...PIPELINE_AUDIO_STAGES, ...PIPELINE_UI_STAGES,
+]);
// Stages that appear as their own tab, in display order. `comicPages` is
// folded into the Comic Script tab (one merged page-by-page editor) — the
@@ -17,7 +20,7 @@ export const PIPELINE_STAGES = Object.freeze([...PIPELINE_TEXT_STAGES, ...PIPELI
// `nouns` is inserted between Prose and Comic Pages so the workflow reads
// Idea → Prose → Nouns → Comic → Teleplay → Storyboards → Episode Video.
export const PIPELINE_TAB_STAGES = Object.freeze([
- 'idea', 'prose', 'nouns', 'comicScript', 'teleplay', 'storyboards', 'episodeVideo',
+ 'idea', 'prose', 'nouns', 'comicScript', 'teleplay', 'storyboards', 'episodeVideo', 'audio',
]);
export const PIPELINE_STAGE_LABELS = Object.freeze({
@@ -31,6 +34,7 @@ export const PIPELINE_STAGE_LABELS = Object.freeze({
comicPages: 'Comic',
storyboards: 'Storyboards',
episodeVideo: 'Video',
+ audio: 'Audio',
});
export const PIPELINE_TARGET_FORMATS = Object.freeze(['comic', 'tv', 'comic+tv']);
@@ -332,3 +336,32 @@ export const cancelPipelineAutoRunText = (issueId) =>
export const pipelineAutoRunSseUrl = (issueId) =>
`/api/pipeline/issues/${encodeURIComponent(issueId)}/auto-run-text/progress`;
+
+// ---- Audio stage ----
+// Walks storyboards.scenes[].dialogue and populates stages.audio.lines[].
+// Pass { force: true } to replace existing lines wholesale (server defaults
+// to a 409 when lines[] is already populated so a stray click can't wipe
+// manual edits).
+export const extractPipelineAudioLines = (issueId, { force } = {}) =>
+ request(`/pipeline/issues/${encodeURIComponent(issueId)}/stages/audio/extract-lines`, {
+ method: 'POST',
+ body: JSON.stringify({ force }),
+ });
+
+// Render one VO line. Voice resolution priority (server-side): explicit
+// voiceId body param > line.voiceIdOverride > character.voiceId > system
+// default. Returns { issue, stage, lineIdx, filename, engine, voiceId }.
+export const renderPipelineAudioLine = (issueId, lineIdx, { voiceId } = {}) =>
+ request(`/pipeline/issues/${encodeURIComponent(issueId)}/stages/audio/lines/${encodeURIComponent(lineIdx)}/render`, {
+ method: 'POST',
+ body: JSON.stringify({ voiceId }),
+ });
+
+// Per-line edit (text or voice override). Narrow patch shape — the server
+// merges against the freshest persisted record inside the per-issue write
+// queue so two simultaneous blurs against different lines can't clobber.
+export const patchPipelineAudioLine = (issueId, lineIdx, patch) =>
+ request(`/pipeline/issues/${encodeURIComponent(issueId)}/stages/audio/lines/${encodeURIComponent(lineIdx)}`, {
+ method: 'PATCH',
+ body: JSON.stringify(patch),
+ });
diff --git a/server/index.js b/server/index.js
index df2dbf6b29..530194516b 100644
--- a/server/index.js
+++ b/server/index.js
@@ -474,6 +474,9 @@ app.use('/data/images', express.static(PATHS.images));
// can pull them by URL without going through an explicit download route.
app.use('/data/videos', express.static(PATHS.videos));
app.use('/data/video-thumbnails', express.static(PATHS.videoThumbnails));
+// Voice-over WAVs rendered by the pipeline audio stage — the AudioStage UI
+// pulls them inline via <audio src="/data/audio/<filename>">.
+app.use('/data/audio', express.static(PATHS.audio));
// Serve built client UI (production mode — no Vite dev server needed)
const CLIENT_DIST = join(__dirname, '..', 'client', 'dist');
diff --git a/server/routes/pipeline.js b/server/routes/pipeline.js
index 77d4fa71ed..2514f16534 100644
--- a/server/routes/pipeline.js
+++ b/server/routes/pipeline.js
@@ -58,7 +58,7 @@ import { ASPECT_RATIOS, QUALITIES } from '../lib/creativeDirectorPresets.js';
import { extractScenes, SOURCE_KIND } from '../lib/sceneExtractor.js';
import { listVisualStyles } from '../lib/visualStyles.js';
import { buildComicPdf, PAGE_SIZES, DEFAULT_PAGE_SIZE, ERR_NO_RENDERED_PAGES } from '../services/pipeline/comicPdf.js';
-import { listAllVoices, synthesizeToFile, parseVoiceId } from '../services/pipeline/audio.js';
+import { listAllVoices, synthesizeToFile, parseVoiceId, extractDialogueLines, resolveVoiceForLine } from '../services/pipeline/audio.js';
import { synthesize as synthesizeVoice } from '../services/voice/tts.js';
import { parseComicScript } from '../lib/comicScriptParser.js';
import {
@@ -533,6 +533,125 @@ router.post('/tts/synthesize', asyncHandler(async (req, res) => {
res.json(result);
}));
+// Walk the issue's storyboards.scenes[].dialogue and populate
+// stages.audio.lines[]. `force: true` replaces existing lines wholesale;
+// the default refuses overwrite when lines[] is already populated so a
+// stray click can't wipe a user's manual edits.
+const extractAudioLinesSchema = z.object({ force: z.boolean().optional() });
+router.post('/issues/:id/stages/audio/extract-lines', asyncHandler(async (req, res) => {
+ const body = validateRequest(extractAudioLinesSchema, req.body ?? {});
+ const issue = await issuesSvc.getIssue(req.params.id).catch((err) => { throw mapServiceError(err); });
+ const existingLines = issue.stages?.audio?.lines || [];
+ if (existingLines.length > 0 && !body.force) {
+ throw new ServerError(
+ `Audio stage already has ${existingLines.length} line${existingLines.length === 1 ? '' : 's'}. Pass force: true to replace.`,
+ { status: 409, code: 'PIPELINE_AUDIO_LINES_EXIST' },
+ );
+ }
+ const series = await seriesSvc.getSeries(issue.seriesId).catch((err) => { throw mapServiceError(err); });
+ // Carry forward already-rendered audio on re-extract when the same speaker
+ // + same line text appears in the fresh extraction — otherwise a small edit
+ // anywhere upstream would silently invalidate every previously-rendered WAV.
+ const { lines, preservedCount } = extractDialogueLines(issue, series, {
+ preserveFrom: existingLines,
+ });
+ const { issue: updatedIssue, stage } = await issuesSvc.updateStage(req.params.id, 'audio', {
+ status: lines.length ? 'ready' : 'empty',
+ lines,
+ errorMessage: '',
+ });
+ res.json({ issue: updatedIssue, stage, lineCount: lines.length, preservedCount });
+}));
+
+// Per-line edit endpoint. Replaces the prior whole-stage PATCH path so a
+// blur-save against line N can't clobber a concurrent edit against line M
+// — the server merges against the freshest persisted record inside the
+// per-issue write queue. Patch fields are intentionally narrow (text +
+// voiceIdOverride); the per-line audio fields are owned by the render path.
+const lineEditSchema = z.object({
+ text: z.string().max(4000).optional(),
+ voiceIdOverride: z.string().trim().max(200).nullable().optional(),
+});
+router.patch('/issues/:id/stages/audio/lines/:lineIdx', asyncHandler(async (req, res) => {
+ const lineIdx = Number(req.params.lineIdx);
+ if (!Number.isInteger(lineIdx) || lineIdx < 0) {
+ throw new ServerError('lineIdx must be a non-negative integer', {
+ status: 400, code: 'PIPELINE_AUDIO_BAD_INDEX',
+ });
+ }
+ const body = validateRequest(lineEditSchema, req.body ?? {});
+ if (Object.keys(body).length === 0) {
+ throw new ServerError('patch must include at least one field', {
+ status: 400, code: 'VALIDATION_ERROR',
+ });
+ }
+ const { issue: updatedIssue, stage } = await issuesSvc.updateStageWithLatest(
+ req.params.id,
+ 'audio',
+ (current) => {
+ const lines = Array.isArray(current?.lines) ? current.lines : [];
+ const line = lines[lineIdx];
+ if (!line) return {};
+ const next = { ...line };
+ if ('text' in body) next.text = body.text;
+ if ('voiceIdOverride' in body) next.voiceIdOverride = body.voiceIdOverride;
+ const nextLines = [...lines];
+ nextLines[lineIdx] = next;
+ return { status: 'edited', lines: nextLines };
+ },
+ ).catch((err) => { throw mapServiceError(err); });
+ res.json({ issue: updatedIssue, stage, lineIdx });
+}));
+
+// Render one VO line. Voice resolution priority:
+// 1. line.voiceIdOverride (explicit per-line override)
+// 2. character.voiceId (series character binding)
+// 3. (none → uses the configured default voice via synthesize())
+const lineRenderSchema = z.object({ voiceId: z.string().trim().max(200).optional() });
+router.post('/issues/:id/stages/audio/lines/:lineIdx/render', asyncHandler(async (req, res) => {
+ const lineIdx = Number(req.params.lineIdx);
+ if (!Number.isInteger(lineIdx) || lineIdx < 0) {
+ throw new ServerError('lineIdx must be a non-negative integer', {
+ status: 400, code: 'PIPELINE_AUDIO_BAD_INDEX',
+ });
+ }
+ const body = validateRequest(lineRenderSchema, req.body ?? {});
+ const issue = await issuesSvc.getIssue(req.params.id).catch((err) => { throw mapServiceError(err); });
+ const lines = issue.stages?.audio?.lines || [];
+ const line = lines[lineIdx];
+ if (!line) {
+ throw new ServerError(`lineIdx ${lineIdx} out of range (have ${lines.length})`, {
+ status: 404, code: 'PIPELINE_AUDIO_LINE_NOT_FOUND',
+ });
+ }
+ // Resolve voice via the shared priority chain (explicit > line override
+ // > character binding > project default). One source of truth, reused by
+ // the eventual "render all" flow + unit-tested for priority order.
+ const series = line.characterId
+ ? await seriesSvc.getSeries(issue.seriesId).catch(() => null)
+ : null;
+ const voiceId = resolveVoiceForLine(line, series, { explicit: body.voiceId });
+ const synthResult = await synthesizeToFile({ text: line.text, voiceId })
+ .catch((err) => { throw mapServiceError(err); });
+ const nextLines = [...lines];
+ nextLines[lineIdx] = {
+ ...line,
+ audioJobId: null,
+ audioFilename: synthResult.filename,
+ };
+ const { issue: updatedIssue, stage } = await issuesSvc.updateStage(req.params.id, 'audio', {
+ status: 'edited',
+ lines: nextLines,
+ errorMessage: '',
+ });
+ res.json({
+ issue: updatedIssue, stage, lineIdx,
+ filename: synthResult.filename,
+ engine: synthResult.engine,
+ voiceId: synthResult.voiceId || voiceId,
+ });
+}));
+
// =====================
// Series routes
// =====================
diff --git a/server/routes/pipeline.test.js b/server/routes/pipeline.test.js
index 51bba3b269..78102f7c83 100644
--- a/server/routes/pipeline.test.js
+++ b/server/routes/pipeline.test.js
@@ -139,6 +139,58 @@ vi.mock('../services/pipeline/episodeVideo.js', () => ({
})),
}));
+// Audio service mocks — avoid touching the real TTS pipeline + filesystem
+// while still exercising the route's voice-resolution + persist flow.
+vi.mock('../services/pipeline/audio.js', () => ({
+ listAllVoices: vi.fn(async () => [{ id: 'kokoro:af_heart', engine: 'kokoro', voice: 'af_heart', label: 'Heart' }]),
+ synthesizeToFile: vi.fn(async ({ voiceId }) => ({
+ filename: `vo-mock-${++uuidCounter}.wav`,
+ latencyMs: 5,
+ engine: 'kokoro',
+ voiceId: voiceId || null,
+ })),
+ parseVoiceId: vi.fn((v) => {
+ if (!v) return { engine: null, voice: null };
+ const m = v.match(/^([a-z]+):(.+)$/);
+ return m ? { engine: m[1], voice: m[2] } : { engine: null, voice: v };
+ }),
+ extractDialogueLines: vi.fn((issue) => {
+ const scenes = issue?.stages?.storyboards?.scenes || [];
+ const out = [];
+ let n = 1;
+ for (const s of scenes) {
+ for (const d of (s.dialogue || [])) {
+ if (!d?.line?.trim()) continue;
+ out.push({
+ id: `line-${String(n).padStart(3, '0')}`,
+ characterId: null,
+ characterName: d.character || null,
+ text: d.line,
+ voiceIdOverride: null,
+ audioJobId: null,
+ audioFilename: null,
+ });
+ n += 1;
+ }
+ }
+ return { lines: out, preservedCount: 0 };
+ }),
+ resolveVoiceForLine: vi.fn((line, series, { explicit } = {}) => {
+ if (explicit) return explicit;
+ if (line?.voiceIdOverride) return line.voiceIdOverride;
+ if (line?.characterId && series?.characters) {
+ const c = series.characters.find((x) => x?.id === line.characterId);
+ if (c?.voiceId) return c.voiceId;
+ }
+ return null;
+ }),
+}));
+vi.mock('../services/voice/tts.js', () => ({
+ synthesize: vi.fn(async () => ({ wav: Buffer.from('w'), latencyMs: 1, engine: 'kokoro' })),
+ listVoices: vi.fn(async () => ({ engine: 'kokoro', voices: [] })),
+ VALID_ENGINES: new Set(['kokoro', 'piper']),
+}));
+
const pipelineRouter = (await import('./pipeline.js')).default;
function makeApp() {
@@ -1169,4 +1221,93 @@ describe('pipeline routes', () => {
expect(r.body.issues[0].location).toBe('episode:3');
expect(volumeVerifySpy).toHaveBeenCalledWith(ser.body.id, 'sea-fake', expect.objectContaining({ providerOverride: 'anthropic' }));
});
+
+ describe('audio stage routes', () => {
+ async function seedIssueWithStoryboards(app) {
+ 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: {
+ storyboards: {
+ scenes: [{
+ slugline: 'INT. KITCHEN — NIGHT',
+ dialogue: [
+ { character: 'JEAN', line: 'I told you he was coming.' },
+ { character: 'DON CARLOS', line: 'Quiet now.' },
+ ],
+ }],
+ },
+ },
+ });
+ return iss.body;
+ }
+
+ it('POST /audio/extract-lines populates lines[] from storyboards dialogue', async () => {
+ const app = makeApp();
+ const iss = await seedIssueWithStoryboards(app);
+ const r = await request(app)
+ .post(`/api/pipeline/issues/${iss.id}/stages/audio/extract-lines`)
+ .send({});
+ expect(r.status).toBe(200);
+ expect(r.body.lineCount).toBe(2);
+ expect(r.body.stage.lines).toHaveLength(2);
+ expect(r.body.stage.lines[0].text).toMatch(/coming/);
+ });
+
+ it('POST /audio/extract-lines 409s on second call without force:true', async () => {
+ const app = makeApp();
+ const iss = await seedIssueWithStoryboards(app);
+ await request(app).post(`/api/pipeline/issues/${iss.id}/stages/audio/extract-lines`).send({});
+ const r = await request(app)
+ .post(`/api/pipeline/issues/${iss.id}/stages/audio/extract-lines`)
+ .send({});
+ expect(r.status).toBe(409);
+ });
+
+ it('POST /audio/extract-lines with force:true replaces existing lines', async () => {
+ const app = makeApp();
+ const iss = await seedIssueWithStoryboards(app);
+ await request(app).post(`/api/pipeline/issues/${iss.id}/stages/audio/extract-lines`).send({});
+ const r = await request(app)
+ .post(`/api/pipeline/issues/${iss.id}/stages/audio/extract-lines`)
+ .send({ force: true });
+ expect(r.status).toBe(200);
+ expect(r.body.lineCount).toBe(2);
+ });
+
+ it('POST /audio/lines/:idx/render persists audioFilename on the matching line', async () => {
+ const app = makeApp();
+ const iss = await seedIssueWithStoryboards(app);
+ await request(app).post(`/api/pipeline/issues/${iss.id}/stages/audio/extract-lines`).send({});
+ const r = await request(app)
+ .post(`/api/pipeline/issues/${iss.id}/stages/audio/lines/0/render`)
+ .send({});
+ expect(r.status).toBe(200);
+ expect(r.body.filename).toMatch(/^vo-mock-/);
+ expect(r.body.lineIdx).toBe(0);
+ expect(r.body.engine).toBe('kokoro');
+ // Refetch the issue and confirm the audio filename landed.
+ const issAfter = await request(app).get(`/api/pipeline/issues/${iss.id}`);
+ expect(issAfter.body.stages.audio.lines[0].audioFilename).toMatch(/^vo-mock-/);
+ });
+
+ it('POST /audio/lines/:idx/render 404s for out-of-range index', async () => {
+ const app = makeApp();
+ const iss = await seedIssueWithStoryboards(app);
+ await request(app).post(`/api/pipeline/issues/${iss.id}/stages/audio/extract-lines`).send({});
+ const r = await request(app)
+ .post(`/api/pipeline/issues/${iss.id}/stages/audio/lines/99/render`)
+ .send({});
+ expect(r.status).toBe(404);
+ });
+
+ it('POST /audio/lines/:idx/render 400s for non-integer index', async () => {
+ const app = makeApp();
+ const iss = await seedIssueWithStoryboards(app);
+ const r = await request(app)
+ .post(`/api/pipeline/issues/${iss.id}/stages/audio/lines/nope/render`)
+ .send({});
+ expect(r.status).toBe(400);
+ });
+ });
});
diff --git a/server/services/pipeline/audio.js b/server/services/pipeline/audio.js
index 2a00956528..869eeba929 100644
--- a/server/services/pipeline/audio.js
+++ b/server/services/pipeline/audio.js
@@ -77,6 +77,120 @@ export async function listAllVoices() {
* name (interpreted against the active engine). Empty / falsy `voiceId`
* uses the configured default voice.
*/
+/**
+ * Walk an issue's already-extracted storyboard scenes and emit a flat
+ * `lines[]` ready to write onto `stages.audio.lines`. The scene extractor
+ * already parsed dialogue into `{ character, line }` per scene, so we don't
+ * re-parse markdown here — we just flatten + bind each speaker to a series
+ * character (by name, case-insensitive) so the per-line render can resolve
+ * a voice id.
+ *
+ * Lines without a matching series character still get persisted (the user
+ * may want narrator / un-named-character lines synthesized via the project
+ * default voice); `characterId` stays null in that case.
+ */
+/**
+ * Voice resolution for a single VO line. Priority:
+ * 1. `explicit` (per-request body override)
+ * 2. `line.voiceIdOverride` (per-line override saved on the issue)
+ * 3. `character.voiceId` (series character binding by line.characterId)
+ * 4. `null` (caller falls through to the configured default voice)
+ *
+ * Pure function — no I/O — so the route, a future "render all" flow, and
+ * unit tests all use the same priority logic.
+ */
+export function resolveVoiceForLine(line, series, { explicit } = {}) {
+ if (typeof explicit === 'string' && explicit.trim()) return explicit.trim();
+ if (line?.voiceIdOverride) return line.voiceIdOverride;
+ if (line?.characterId) {
+ const char = (series?.characters || []).find((c) => c?.id === line.characterId);
+ if (char?.voiceId) return char.voiceId;
+ }
+ return null;
+}
+
+/**
+ * Strip parenthetical performance hints from a screenplay speaker label so
+ * character matching works on the bare name. Handles trailing single
+ * (`JEAN (O.S.)`), stacked trailing (`JEAN (O.S.)(angry)`), and leading
+ * (`(O.S.) JEAN`) parens — all three appear in real teleplays.
+ */
+function stripSpeakerParens(raw) {
+ if (typeof raw !== 'string') return '';
+ return raw
+ .replace(/^\s*\([^)]*\)\s*/, '')
+ .replace(/\s*\([^)]*\)\s*/g, ' ')
+ .trim();
+}
+
+export function extractDialogueLines(issue, series, { preserveFrom = [] } = {}) {
+ const scenes = Array.isArray(issue?.stages?.storyboards?.scenes)
+ ? issue.stages.storyboards.scenes
+ : [];
+ // First-registration wins so duplicate character names / aliased collisions
+ // resolve deterministically. Last-writer-wins on a Map would silently flip
+ // a binding when a later character shares a name.
+ const charactersByKey = new Map();
+ const rememberKey = (key, c) => {
+ if (key && !charactersByKey.has(key)) charactersByKey.set(key, c);
+ };
+ for (const c of (series?.characters || [])) {
+ if (!c || typeof c !== 'object') continue;
+ const name = typeof c.name === 'string' ? c.name.trim() : '';
+ if (!name) continue;
+ rememberKey(name.toLowerCase(), c);
+ if (Array.isArray(c.aliases)) {
+ for (const alias of c.aliases) {
+ if (typeof alias === 'string' && alias.trim()) rememberKey(alias.trim().toLowerCase(), c);
+ }
+ }
+ }
+
+ // Build a (speakerKey + text) → prior line index so re-extraction can carry
+ // forward rendered audio for lines that haven't changed. The match is
+ // intentionally strict — any edit to text or character invalidates the
+ // existing render.
+ const preservedByKey = new Map();
+ if (Array.isArray(preserveFrom)) {
+ for (const prev of preserveFrom) {
+ if (!prev || typeof prev !== 'object') continue;
+ if (!prev.audioFilename && !prev.audioJobId) continue;
+ const key = `${(prev.characterName || '').toLowerCase()}|${prev.text || ''}`;
+ if (!preservedByKey.has(key)) preservedByKey.set(key, prev);
+ }
+ }
+
+ const lines = [];
+ let preservedCount = 0;
+ let lineNumber = 1;
+ for (let sIdx = 0; sIdx < scenes.length; sIdx += 1) {
+ const scene = scenes[sIdx];
+ const dialogue = Array.isArray(scene?.dialogue) ? scene.dialogue : [];
+ for (let dIdx = 0; dIdx < dialogue.length; dIdx += 1) {
+ const d = dialogue[dIdx];
+ const text = typeof d?.line === 'string' ? d.line.trim() : '';
+ if (!text) continue;
+ const rawSpeaker = typeof d?.character === 'string' ? d.character.trim() : '';
+ const bareSpeaker = stripSpeakerParens(rawSpeaker);
+ const match = bareSpeaker ? charactersByKey.get(bareSpeaker.toLowerCase()) : null;
+ const preserveKey = `${rawSpeaker.toLowerCase()}|${text}`;
+ const carryover = preservedByKey.get(preserveKey);
+ if (carryover) preservedCount += 1;
+ lines.push({
+ id: `line-${String(lineNumber).padStart(3, '0')}`,
+ characterId: match?.id || null,
+ characterName: rawSpeaker || null,
+ text,
+ voiceIdOverride: carryover?.voiceIdOverride || null,
+ audioJobId: carryover?.audioJobId || null,
+ audioFilename: carryover?.audioFilename || null,
+ });
+ lineNumber += 1;
+ }
+ }
+ return { lines, preservedCount };
+}
+
export async function synthesizeToFile({ text, voiceId, signal } = {}) {
const trimmed = (text || '').trim();
if (!trimmed) {
diff --git a/server/services/pipeline/audio.test.js b/server/services/pipeline/audio.test.js
index e3f0e652fd..5e97180d81 100644
--- a/server/services/pipeline/audio.test.js
+++ b/server/services/pipeline/audio.test.js
@@ -23,7 +23,7 @@ vi.mock('../voice/tts.js', () => ({
VALID_ENGINES: new Set(['kokoro', 'piper']),
}));
-const { parseVoiceId, listAllVoices, synthesizeToFile } = await import('./audio.js');
+const { parseVoiceId, listAllVoices, synthesizeToFile, extractDialogueLines, resolveVoiceForLine } = await import('./audio.js');
beforeEach(async () => {
synthesizeMock.mockReset();
@@ -121,3 +121,173 @@ describe('synthesizeToFile', () => {
expect(passed).not.toHaveProperty('voice');
});
});
+
+describe('extractDialogueLines', () => {
+ const series = {
+ characters: [
+ { id: 'chr-jean', name: 'Jean', aliases: ['Jeanie'] },
+ { id: 'chr-don', name: 'Don Carlos' },
+ ],
+ };
+ const issueWithDialogue = {
+ stages: {
+ storyboards: {
+ scenes: [
+ {
+ slugline: 'INT. KITCHEN — NIGHT',
+ dialogue: [
+ { character: 'JEAN', line: 'I told you he was coming.' },
+ { character: 'DON CARLOS (whispered)', line: 'Quiet now.' },
+ { character: 'NARRATOR', line: 'Outside, the rain began.' },
+ ],
+ },
+ {
+ slugline: 'EXT. STREET — NIGHT',
+ dialogue: [
+ { character: 'Jeanie', line: 'You always do this.' },
+ { character: '', line: 'A scream — unattributed.' },
+ { character: 'X', line: ' ' }, // whitespace text → skip
+ ],
+ },
+ ],
+ },
+ },
+ };
+
+ it('flattens dialogue across scenes into a numbered lines[] list', () => {
+ const { lines, preservedCount } = extractDialogueLines(issueWithDialogue, series);
+ expect(lines.map((l) => l.id)).toEqual(['line-001', 'line-002', 'line-003', 'line-004', 'line-005']);
+ expect(lines).toHaveLength(5);
+ expect(preservedCount).toBe(0);
+ });
+
+ it('binds speakers to series characters case-insensitively, including aliases', () => {
+ const { lines } = extractDialogueLines(issueWithDialogue, series);
+ expect(lines[0].characterId).toBe('chr-jean');
+ expect(lines[1].characterId).toBe('chr-don'); // strip "(whispered)" parenthetical
+ expect(lines[2].characterId).toBe(null); // NARRATOR — no match
+ expect(lines[3].characterId).toBe('chr-jean'); // 'Jeanie' alias resolves
+ expect(lines[4].characterId).toBe(null); // empty speaker
+ });
+
+ it('preserves the raw speaker label (including parentheticals) on the line', () => {
+ const { lines } = extractDialogueLines(issueWithDialogue, series);
+ expect(lines[1].characterName).toBe('DON CARLOS (whispered)');
+ });
+
+ it('initializes voice + audio fields to null (per-line resolution happens at render time)', () => {
+ const { lines } = extractDialogueLines(issueWithDialogue, series);
+ for (const l of lines) {
+ expect(l.voiceIdOverride).toBe(null);
+ expect(l.audioJobId).toBe(null);
+ expect(l.audioFilename).toBe(null);
+ }
+ });
+
+ it('skips dialogue rows with empty / whitespace-only text', () => {
+ const { lines } = extractDialogueLines(issueWithDialogue, series);
+ // The "X" speaker with whitespace text in scene 2 is dropped.
+ expect(lines.find((l) => l.characterName === 'X')).toBeUndefined();
+ });
+
+ it('returns an empty list when no scenes or no dialogue', () => {
+ expect(extractDialogueLines({ stages: {} }, series).lines).toEqual([]);
+ expect(extractDialogueLines({ stages: { storyboards: { scenes: [] } } }, series).lines).toEqual([]);
+ expect(extractDialogueLines({ stages: { storyboards: { scenes: [{ slugline: 'INT.' }] } } }, series).lines).toEqual([]);
+ });
+
+ it('tolerates a series with no characters[] (everything stays unbound)', () => {
+ const { lines } = extractDialogueLines(issueWithDialogue, {});
+ expect(lines.length).toBeGreaterThan(0);
+ for (const l of lines) expect(l.characterId).toBe(null);
+ });
+
+ it('strips prefix + stacked parentheticals from speaker labels for character matching', () => {
+ const issue = {
+ stages: {
+ storyboards: {
+ scenes: [{
+ dialogue: [
+ { character: '(O.S.) JEAN', line: 'Behind the door.' },
+ { character: 'JEAN (O.S.)(angry)', line: 'I said GO.' },
+ ],
+ }],
+ },
+ },
+ };
+ const { lines } = extractDialogueLines(issue, series);
+ expect(lines).toHaveLength(2);
+ expect(lines[0].characterId).toBe('chr-jean');
+ expect(lines[1].characterId).toBe('chr-jean');
+ // characterName preserves the raw label so the UI can show performance hints.
+ expect(lines[0].characterName).toBe('(O.S.) JEAN');
+ expect(lines[1].characterName).toBe('JEAN (O.S.)(angry)');
+ });
+
+ it('preserves audioFilename + audioJobId for unchanged speaker+text on re-extract', () => {
+ const previous = [
+ { characterName: 'JEAN', text: 'I told you he was coming.', audioFilename: 'vo-keep-001.wav', audioJobId: 'job-keep' },
+ { characterName: 'NARRATOR', text: 'Outside, the rain began.', audioFilename: 'vo-keep-002.wav', audioJobId: null },
+ // Stale row — text changed → should NOT carry forward.
+ { characterName: 'DON CARLOS (whispered)', text: 'Different line.', audioFilename: 'vo-stale.wav' },
+ ];
+ const { lines, preservedCount } = extractDialogueLines(issueWithDialogue, series, { preserveFrom: previous });
+ // line-001 ("JEAN" / "I told you he was coming.") — same speaker + text → preserved.
+ expect(lines[0].audioFilename).toBe('vo-keep-001.wav');
+ expect(lines[0].audioJobId).toBe('job-keep');
+ // line-002 (DON CARLOS) — text differs → no carry.
+ expect(lines[1].audioFilename).toBe(null);
+ // line-003 (NARRATOR / "Outside, the rain began.") — same speaker + text → preserved.
+ expect(lines[2].audioFilename).toBe('vo-keep-002.wav');
+ expect(preservedCount).toBe(2);
+ });
+
+ it('first-name-wins for duplicate character names (no last-writer flip)', () => {
+ const seriesWithDup = {
+ characters: [
+ { id: 'chr-jean-first', name: 'Jean' },
+ { id: 'chr-jean-second', name: 'Jean' },
+ ],
+ };
+ const issue = {
+ stages: {
+ storyboards: { scenes: [{ dialogue: [{ character: 'JEAN', line: 'pick one.' }] }] },
+ },
+ };
+ const { lines } = extractDialogueLines(issue, seriesWithDup);
+ expect(lines[0].characterId).toBe('chr-jean-first');
+ });
+});
+
+describe('resolveVoiceForLine priority', () => {
+ const series = {
+ characters: [{ id: 'chr-1', name: 'Jean', voiceId: 'kokoro:af_heart' }],
+ };
+
+ it('explicit request override wins over everything else', () => {
+ const line = { characterId: 'chr-1', voiceIdOverride: 'kokoro:af_bella' };
+ expect(resolveVoiceForLine(line, series, { explicit: 'piper:en_GB-northern_english_male' }))
+ .toBe('piper:en_GB-northern_english_male');
+ });
+
+ it('line override wins over character binding', () => {
+ const line = { characterId: 'chr-1', voiceIdOverride: 'kokoro:af_bella' };
+ expect(resolveVoiceForLine(line, series)).toBe('kokoro:af_bella');
+ });
+
+ it('character.voiceId used when no override', () => {
+ const line = { characterId: 'chr-1', voiceIdOverride: null };
+ expect(resolveVoiceForLine(line, series)).toBe('kokoro:af_heart');
+ });
+
+ it('returns null when nothing resolves (caller falls through to default)', () => {
+ expect(resolveVoiceForLine({ characterId: null, voiceIdOverride: null }, series)).toBe(null);
+ expect(resolveVoiceForLine({ characterId: 'unknown', voiceIdOverride: null }, series)).toBe(null);
+ expect(resolveVoiceForLine({}, {})).toBe(null);
+ });
+
+ it('ignores whitespace-only explicit overrides', () => {
+ const line = { voiceIdOverride: 'kokoro:af_bella' };
+ expect(resolveVoiceForLine(line, series, { explicit: ' ' })).toBe('kokoro:af_bella');
+ });
+});
diff --git a/server/services/pipeline/issues.js b/server/services/pipeline/issues.js
index 55212cfa32..181a92c70d 100644
--- a/server/services/pipeline/issues.js
+++ b/server/services/pipeline/issues.js
@@ -88,10 +88,8 @@ export const VISUAL_STAGE_IDS = Object.freeze(['comicPages', 'storyboards', 'epi
export const AUDIO_STAGE_IDS = Object.freeze(['audio']);
export const STAGE_IDS = Object.freeze([...TEXT_STAGE_IDS, ...VISUAL_STAGE_IDS, ...AUDIO_STAGE_IDS]);
// Stages exposed to voice navigation ("next stage" / "previous stage" tools)
-// and the tab strip. Audio is intentionally excluded until the audio UI page
-// 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]);
+// and the tab strip. Includes audio now that the AudioStage UI is wired.
+export const NAVIGABLE_STAGE_IDS = Object.freeze([...TEXT_STAGE_IDS, ...VISUAL_STAGE_IDS, ...AUDIO_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
diff --git a/server/services/voice/tools.test.js b/server/services/voice/tools.test.js
index 5c4d4fe14a..d0ad10f5f4 100644
--- a/server/services/voice/tools.test.js
+++ b/server/services/voice/tools.test.js
@@ -699,8 +699,8 @@ describe('pipeline stage navigation tools', () => {
expect(ctx.sideEffects).toEqual([{ type: 'navigate', path: '/pipeline/issues/iss-abc/prose' }]);
});
- it('refuses to advance past episodeVideo (last stage)', async () => {
- const r = await dispatchTool('pipeline_next_stage', {}, makeCtx('/pipeline/issues/x/episodeVideo'));
+ it('refuses to advance past audio (last navigable stage)', async () => {
+ const r = await dispatchTool('pipeline_next_stage', {}, makeCtx('/pipeline/issues/x/audio'));
expect(r.ok).toBe(false);
expect(r.summary).toMatch(/last stage/);
});