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 foundation + character voiceId binding

[._.]/ Adam Eivy8afc7e92e6e7
diff --git a/server/lib/fileUtils.js b/server/lib/fileUtils.js
index d45e51d329..51425ba1b6 100644
--- a/server/lib/fileUtils.js
+++ b/server/lib/fileUtils.js
@@ -66,6 +66,10 @@ export const PATHS = {
loras: join(__lib_dirname, '../../data/loras'),
videos: join(__lib_dirname, '../../data/videos'),
videoThumbnails: join(__lib_dirname, '../../data/video-thumbnails'),
+ // Persisted audio renders (voice-over lines, music). Kept distinct from
+ // the in-memory voice-agent synthesis path in services/voice/ — that path
+ // streams WAV over Socket.IO without ever touching disk.
+ audio: join(__lib_dirname, '../../data/audio'),
slashdo: join(__lib_dirname, '../../lib/slashdo')
};
diff --git a/server/lib/storyBible.js b/server/lib/storyBible.js
index d6edec366c..815ead5e3d 100644
--- a/server/lib/storyBible.js
+++ b/server/lib/storyBible.js
@@ -46,6 +46,10 @@ export const BIBLE_LIMITS = Object.freeze({
TAG_MAX: 60,
TAGS_PER_ENTRY_MAX: 12,
SOURCE_SERIES_ID_MAX: 64,
+ // Voice id namespace: `engine:voiceName` (e.g. `kokoro:af_heart`,
+ // `piper:en_GB-northern_english_male`). Caps generously since 3rd-party
+ // providers (ElevenLabs) use uuid-shaped voice ids.
+ VOICE_ID_MAX: 200,
});
// Canonical provenance vocabulary. `BIBLE_SOURCE.SERIES_EXTRACT` is the
@@ -90,7 +94,7 @@ export const BIBLE_KINDS = Object.freeze(Object.values(BIBLE_KIND));
// `existing<X>Json` prompt variable (bibleExtractor) and into the script
// stage's bibles context (evaluator). Excludes ids/timestamps/source/notes.
export const PROMPT_FIELDS = Object.freeze({
- [BIBLE_KIND.CHARACTER]: ['name', 'aliases', 'role', 'physicalDescription', 'personality', 'background', 'prompt', 'tags'],
+ [BIBLE_KIND.CHARACTER]: ['name', 'aliases', 'role', 'physicalDescription', 'personality', 'background', 'voiceId', 'prompt', 'tags'],
[BIBLE_KIND.SETTING]: ['name', 'slugline', 'description', 'palette', 'era', 'weather', 'recurringDetails', 'prompt', 'tags'],
[BIBLE_KIND.OBJECT]: ['name', 'aliases', 'description', 'significance', 'prompt', 'tags'],
});
@@ -189,6 +193,9 @@ export function sanitizeCharacter(raw, { idPrefix = DEFAULT_ID_PREFIX.character,
personality: trimTo(raw.personality, BIBLE_LIMITS.PERSONALITY_MAX),
background: trimTo(raw.background, BIBLE_LIMITS.BACKGROUND_MAX),
notes: trimTo(raw.notes, BIBLE_LIMITS.NOTES_MAX),
+ // Voice binding for VO synthesis (kokoro/piper local OSS, ElevenLabs
+ // when configured). null = use the project default at synth time.
+ voiceId: trimTo(raw.voiceId, BIBLE_LIMITS.VOICE_ID_MAX) || null,
imageRefs: cleanStringArray(raw.imageRefs, BIBLE_LIMITS.IMAGE_REF_MAX, BIBLE_LIMITS.IMAGE_REFS_PER_ENTRY_MAX),
firstAppearance: ensureFirstAppearance(raw.firstAppearance),
evidence: cleanStringArray(raw.evidence, BIBLE_LIMITS.EVIDENCE_ITEM_MAX, BIBLE_LIMITS.EVIDENCE_PER_ENTRY_MAX),
diff --git a/server/lib/validation.js b/server/lib/validation.js
index 8ef7a56909..46051c1af9 100644
--- a/server/lib/validation.js
+++ b/server/lib/validation.js
@@ -614,6 +614,10 @@ export const writersRoomAnalysisCreateSchema = z.object({
// other text fields tolerate '' so the writer can deliberately blank a field
// out and have the next analysis re-fill it.
const wrCharTextField = z.string().max(2000);
+// Voice id namespace shared by writers-room + pipeline character routes:
+// `engine:voiceName` (e.g. `kokoro:af_heart`). Nullable so a UI clear path
+// can null it explicitly.
+const wrVoiceIdField = z.string().trim().max(200).nullable();
export const writersRoomCharacterCreateSchema = z.object({
name: z.string().trim().min(1).max(200),
aliases: z.array(z.string().trim().min(1).max(200)).max(20).optional(),
@@ -622,6 +626,7 @@ export const writersRoomCharacterCreateSchema = z.object({
personality: wrCharTextField.optional(),
background: wrCharTextField.optional(),
notes: wrCharTextField.optional(),
+ voiceId: wrVoiceIdField.optional(),
}).strict();
export const writersRoomCharacterUpdateSchema = z.object({
name: z.string().trim().min(1).max(200).optional(),
@@ -631,6 +636,7 @@ export const writersRoomCharacterUpdateSchema = z.object({
personality: wrCharTextField.optional(),
background: wrCharTextField.optional(),
notes: wrCharTextField.optional(),
+ voiceId: wrVoiceIdField.optional(),
}).strict();
const wrSettingTextField = z.string().max(2000);
diff --git a/server/routes/pipeline.js b/server/routes/pipeline.js
index 8b723eae61..ba4e350ba1 100644
--- a/server/routes/pipeline.js
+++ b/server/routes/pipeline.js
@@ -52,6 +52,8 @@ 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 { synthesize as synthesizeVoice } from '../services/voice/tts.js';
import { parseComicScript } from '../lib/comicScriptParser.js';
import {
LENGTH_PROFILE_NAMES,
@@ -251,6 +253,16 @@ const visualStageInputSchema = stageInputSchema.extend({
visualStyleOverride: visualStyleRefSchema.optional(),
});
+// Audio stage payloads carry lines[] (voice-over per dialogue line) + a
+// nullable music descriptor. Light validation — the sanitizer in
+// services/pipeline/issues.js enforces per-line + per-music shape. Without
+// this arm in the union below, audio PATCHes silently fall through to the
+// base stageInputSchema and Zod strips lines[]/music.
+const audioStageInputSchema = stageInputSchema.extend({
+ lines: z.array(z.any()).max(1000).optional(),
+ music: z.any().nullable().optional(),
+});
+
const issuePatchSchema = z.object({
title: z.string().trim().min(1).max(issuesSvc.TITLE_MAX).optional(),
number: z.number().int().min(1).max(9999).optional(),
@@ -271,7 +283,9 @@ const issuePatchSchema = z.object({
// is a superset of stageInputSchema (those four are optional additions), so
// text-stage patches still validate. Z.union picks the first schema that
// succeeds — stageInputSchema first would silently strip the visual fields.
- stages: z.record(z.string(), z.union([visualStageInputSchema, stageInputSchema])).optional(),
+ // Union order matters: Zod picks the first arm that succeeds, so the
+ // more-specific schemas (visual, audio) must precede the bare base.
+ stages: z.record(z.string(), z.union([visualStageInputSchema, audioStageInputSchema, stageInputSchema])).optional(),
}).refine((p) => Object.keys(p).length > 0, { message: 'patch must include at least one field' });
const generateSchema = z.object({
@@ -438,6 +452,60 @@ router.get('/visual-styles', asyncHandler(async (_req, res) => {
res.json({ styles: listVisualStyles() });
}));
+// Merged voice list across every supported TTS engine (Kokoro + Piper today;
+// future ElevenLabs/etc. when added). Each voice is namespaced with
+// `engine:voiceName` so the character voice picker shows a single flat list.
+router.get('/tts/voices', asyncHandler(async (_req, res) => {
+ res.json({ voices: await listAllVoices() });
+}));
+
+// Audition a voice before binding it to a character. Returns the rendered
+// WAV inline so the picker can <audio> it without persisting anything. Body:
+// { voiceId, text? } — text defaults to a short generic sample.
+const ttsPreviewSchema = z.object({
+ voiceId: z.string().trim().min(1).max(200),
+ text: z.string().trim().max(500).optional(),
+});
+const DEFAULT_PREVIEW_TEXT = 'The morning fog burned off slow that day, and nothing felt quite the same after.';
+router.post('/tts/preview', asyncHandler(async (req, res) => {
+ const body = validateRequest(ttsPreviewSchema, req.body ?? {});
+ const { engine, voice } = parseVoiceId(body.voiceId);
+ const text = body.text || DEFAULT_PREVIEW_TEXT;
+ // Surface "unknown voice" + transient model-load failures as 400/503 with
+ // a useful message instead of asyncHandler's default 500.
+ let wav; let latencyMs; let usedEngine;
+ try {
+ ({ wav, latencyMs, engine: usedEngine } = await synthesizeVoice(text, {
+ ...(engine ? { engine } : {}),
+ ...(voice ? { voice } : {}),
+ }));
+ } catch (err) {
+ if (err?.message?.startsWith('unknown') || err?.code === 'UNKNOWN_VOICE') {
+ throw new ServerError(err.message, { status: 400, code: 'PIPELINE_AUDIO_UNKNOWN_VOICE' });
+ }
+ throw err;
+ }
+ res.setHeader('Content-Type', 'audio/wav');
+ res.setHeader('X-TTS-Latency-Ms', String(latencyMs));
+ res.setHeader('X-TTS-Engine', usedEngine);
+ res.send(wav);
+}));
+
+// Persist a one-off voice line to disk under PATHS.audio and return the
+// resulting filename. The audio stage's lines[] table calls this to render
+// individual dialogue lines; the bulk "render all dialogue" flow lands in
+// a follow-up. Mainly intended for the per-line Render button in the UI.
+const ttsSynthesizeSchema = z.object({
+ text: z.string().trim().min(1).max(4000),
+ voiceId: z.string().trim().max(200).optional(),
+});
+router.post('/tts/synthesize', asyncHandler(async (req, res) => {
+ const body = validateRequest(ttsSynthesizeSchema, req.body ?? {});
+ const result = await synthesizeToFile({ text: body.text, voiceId: body.voiceId })
+ .catch((err) => { throw mapServiceError(err); });
+ res.json(result);
+}));
+
// =====================
// Series routes
// =====================
diff --git a/server/routes/voice.js b/server/routes/voice.js
index d914cb6222..a038183964 100644
--- a/server/routes/voice.js
+++ b/server/routes/voice.js
@@ -11,14 +11,13 @@ import { asyncHandler, ServerError } from '../lib/errorHandler.js';
import { getVoiceConfig, updateVoiceConfig } from '../services/voice/config.js';
import { checkAll, invalidateHealthCache } from '../services/voice/health.js';
import { reconcile, verifyBinaries, verifyModels, downloadPiperVoice } from '../services/voice/bootstrap.js';
-import { synthesize, listVoices } from '../services/voice/tts.js';
+import { synthesize, listVoices, VALID_ENGINES } from '../services/voice/tts.js';
import { findPiperVoice } from '../services/voice/piper-voices.js';
import { speakProactive, HHMM_RE, MAX_PROACTIVE_TEXT_LEN } from '../services/voice/proactiveSpeech.js';
const router = Router();
-const VALID_TTS_ENGINES = new Set(['kokoro', 'piper']);
-const validEngine = (v) => VALID_TTS_ENGINES.has(v) ? v : undefined;
+const validEngine = (v) => VALID_ENGINES.has(v) ? v : undefined;
// Shared cap for every REST endpoint that turns a text payload into TTS
// audio (/test and /speak). Imported from proactiveSpeech.js so the
diff --git a/server/routes/voice.test.js b/server/routes/voice.test.js
index 3ae44a8557..da269f6b60 100644
--- a/server/routes/voice.test.js
+++ b/server/routes/voice.test.js
@@ -21,6 +21,7 @@ vi.mock('../services/voice/bootstrap.js', () => ({
vi.mock('../services/voice/tts.js', () => ({
synthesize: vi.fn(),
listVoices: vi.fn(),
+ VALID_ENGINES: new Set(['kokoro', 'piper']),
}));
vi.mock('../services/voice/piper-voices.js', () => ({
findPiperVoice: vi.fn(),
diff --git a/server/services/pipeline/audio.js b/server/services/pipeline/audio.js
new file mode 100644
index 0000000000..2a00956528
--- /dev/null
+++ b/server/services/pipeline/audio.js
@@ -0,0 +1,97 @@
+/**
+ * Pipeline audio helpers — voice ID namespace + thin wrappers around the
+ * existing voice-agent TTS (`server/services/voice/tts.js`) for pipeline
+ * artifacts that need to land on disk instead of streaming over Socket.IO.
+ *
+ * Provider strategy: **always-available local OSS first.** Kokoro and Piper
+ * ship in-process via ONNX/transformers.js — every install can render voice
+ * lines without network or API keys. Premium providers (ElevenLabs, etc.)
+ * add as sibling engines via `server/services/voice/tts.js`'s engine
+ * dispatch; the pipeline doesn't care which one rendered the bytes.
+ *
+ * Voice ID namespace: `engine:voiceName` — `kokoro:af_heart`,
+ * `piper:en_GB-northern_english_male`. A bare voice name without the
+ * `engine:` prefix is interpreted as the active engine's voice.
+ */
+
+import { writeFile } from 'fs/promises';
+import { join } from 'path';
+import { randomUUID } from 'crypto';
+import { PATHS, ensureDir } from '../../lib/fileUtils.js';
+import { synthesize, listVoices, VALID_ENGINES } from '../voice/tts.js';
+import { ServerError } from '../../lib/errorHandler.js';
+
+const VOICE_ID_RE = /^([a-z][a-z0-9-]*):(.+)$/i;
+
+/**
+ * Split a voice id into `{ engine, voice }`. Returns `{ engine: null, voice: id }`
+ * when no engine prefix is present so the caller can fall back to the active
+ * engine — same shape as the legacy single-engine code path.
+ */
+export function parseVoiceId(voiceId) {
+ if (typeof voiceId !== 'string' || !voiceId.trim()) return { engine: null, voice: null };
+ const trimmed = voiceId.trim();
+ const m = trimmed.match(VOICE_ID_RE);
+ if (!m) return { engine: null, voice: trimmed };
+ const engine = m[1].toLowerCase();
+ if (!VALID_ENGINES.has(engine)) return { engine: null, voice: trimmed };
+ return { engine, voice: m[2] };
+}
+
+/**
+ * List every voice exposed by every supported engine, namespaced with
+ * `engine:voiceName` so the character voice picker can present a single
+ * flat list across providers. Failures from one engine never block the
+ * others — a missing Piper binary, for instance, just drops piper voices
+ * from the list.
+ */
+export async function listAllVoices() {
+ const engines = [...VALID_ENGINES];
+ const results = await Promise.all(engines.map(async (engine) => {
+ try {
+ const { voices } = await listVoices(engine);
+ return voices.map((v) => ({
+ id: `${engine}:${v.name}`,
+ engine,
+ voice: v.name,
+ label: v.label || v.name,
+ // Carry through any metadata the engine surfaces (gender, language,
+ // accent, etc.) without locking the shape — the UI renders what's
+ // present.
+ ...v,
+ }));
+ } catch (err) {
+ console.warn(`⚠️ listAllVoices: ${engine} unavailable — ${err?.message || err}`);
+ return [];
+ }
+ }));
+ return results.flat();
+}
+
+/**
+ * Synthesize text to a WAV file under PATHS.audio and return the saved
+ * filename. The route layer + the audio stage line records correlate by
+ * filename, same convention as the image pipeline.
+ *
+ * `voiceId` may be the namespaced form (`kokoro:af_heart`) or a bare voice
+ * name (interpreted against the active engine). Empty / falsy `voiceId`
+ * uses the configured default voice.
+ */
+export async function synthesizeToFile({ text, voiceId, signal } = {}) {
+ const trimmed = (text || '').trim();
+ if (!trimmed) {
+ throw new ServerError('text is required', { status: 400, code: 'PIPELINE_AUDIO_EMPTY_TEXT' });
+ }
+ const { engine, voice } = parseVoiceId(voiceId);
+ const opts = { signal };
+ if (engine) opts.engine = engine;
+ if (voice) opts.voice = voice;
+
+ const { wav, latencyMs, engine: usedEngine } = await synthesize(trimmed, opts);
+ await ensureDir(PATHS.audio);
+ // UUID filename keeps two simultaneous renders from colliding; the line's
+ // audioJobId-or-audioFilename binding lives in stages.audio.lines[].
+ const filename = `vo-${randomUUID()}.wav`;
+ await writeFile(join(PATHS.audio, filename), wav);
+ return { filename, latencyMs, engine: usedEngine, voiceId: voice ? `${usedEngine}:${voice}` : null };
+}
diff --git a/server/services/pipeline/audio.test.js b/server/services/pipeline/audio.test.js
new file mode 100644
index 0000000000..e3f0e652fd
--- /dev/null
+++ b/server/services/pipeline/audio.test.js
@@ -0,0 +1,123 @@
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
+import { mkdir, rm, readFile } from 'fs/promises';
+import { join } from 'path';
+import { tmpdir } from 'os';
+
+const TEST_HOME = join(tmpdir(), `portos-audio-test-${process.pid}-${Date.now()}`);
+const FAKE_AUDIO_DIR = join(TEST_HOME, 'audio');
+
+vi.mock('../../lib/fileUtils.js', async () => {
+ const actual = await vi.importActual('../../lib/fileUtils.js');
+ return {
+ ...actual,
+ PATHS: { ...actual.PATHS, audio: FAKE_AUDIO_DIR },
+ ensureDir: vi.fn(async (dir) => mkdir(dir, { recursive: true })),
+ };
+});
+
+const synthesizeMock = vi.fn();
+const listVoicesMock = vi.fn();
+vi.mock('../voice/tts.js', () => ({
+ synthesize: (...a) => synthesizeMock(...a),
+ listVoices: (...a) => listVoicesMock(...a),
+ VALID_ENGINES: new Set(['kokoro', 'piper']),
+}));
+
+const { parseVoiceId, listAllVoices, synthesizeToFile } = await import('./audio.js');
+
+beforeEach(async () => {
+ synthesizeMock.mockReset();
+ listVoicesMock.mockReset();
+ await rm(TEST_HOME, { recursive: true, force: true }).catch(() => {});
+ await mkdir(TEST_HOME, { recursive: true });
+});
+
+afterEach(async () => {
+ await rm(TEST_HOME, { recursive: true, force: true }).catch(() => {});
+});
+
+describe('parseVoiceId', () => {
+ it('splits engine:voice pairs', () => {
+ expect(parseVoiceId('kokoro:af_heart')).toEqual({ engine: 'kokoro', voice: 'af_heart' });
+ expect(parseVoiceId('piper:en_GB-northern_english_male')).toEqual({
+ engine: 'piper', voice: 'en_GB-northern_english_male',
+ });
+ });
+
+ it('ignores unknown engine prefixes and treats the whole id as a bare voice name', () => {
+ expect(parseVoiceId('elevenlabs:Rachel')).toEqual({ engine: null, voice: 'elevenlabs:Rachel' });
+ });
+
+ it('treats unprefixed strings as a bare voice name', () => {
+ expect(parseVoiceId('af_heart')).toEqual({ engine: null, voice: 'af_heart' });
+ });
+
+ it('returns nulls for empty / whitespace / non-string inputs', () => {
+ expect(parseVoiceId('')).toEqual({ engine: null, voice: null });
+ expect(parseVoiceId(' ')).toEqual({ engine: null, voice: null });
+ expect(parseVoiceId(null)).toEqual({ engine: null, voice: null });
+ expect(parseVoiceId(undefined)).toEqual({ engine: null, voice: null });
+ expect(parseVoiceId(42)).toEqual({ engine: null, voice: null });
+ });
+});
+
+describe('listAllVoices', () => {
+ it('namespaces voices with engine: and merges across providers', async () => {
+ listVoicesMock.mockImplementation(async (engine) => {
+ if (engine === 'kokoro') return { engine, voices: [{ name: 'af_heart', label: 'Heart' }] };
+ if (engine === 'piper') return { engine, voices: [{ name: 'en_GB-northern_english_male' }] };
+ return { engine, voices: [] };
+ });
+ const voices = await listAllVoices();
+ expect(voices).toContainEqual(expect.objectContaining({
+ id: 'kokoro:af_heart', engine: 'kokoro', voice: 'af_heart',
+ }));
+ expect(voices).toContainEqual(expect.objectContaining({
+ id: 'piper:en_GB-northern_english_male', engine: 'piper',
+ }));
+ });
+
+ it('falls back gracefully when one engine throws', async () => {
+ listVoicesMock.mockImplementation(async (engine) => {
+ if (engine === 'kokoro') return { engine, voices: [{ name: 'af_heart' }] };
+ throw new Error('piper unavailable');
+ });
+ const voices = await listAllVoices();
+ expect(voices.length).toBe(1);
+ expect(voices[0].engine).toBe('kokoro');
+ });
+});
+
+describe('synthesizeToFile', () => {
+ it('rejects empty text with 400', async () => {
+ await expect(synthesizeToFile({ text: ' ', voiceId: 'kokoro:af_heart' }))
+ .rejects.toMatchObject({ status: 400 });
+ });
+
+ it('writes the rendered WAV to PATHS.audio and returns the filename', async () => {
+ synthesizeMock.mockResolvedValue({ wav: Buffer.from('FAKE-WAV-BYTES'), latencyMs: 123, engine: 'kokoro' });
+ const result = await synthesizeToFile({ text: 'hello there', voiceId: 'kokoro:af_heart' });
+ expect(result.filename).toMatch(/^vo-.*\.wav$/);
+ expect(result.engine).toBe('kokoro');
+ expect(result.latencyMs).toBe(123);
+ const written = await readFile(join(FAKE_AUDIO_DIR, result.filename));
+ expect(written.toString()).toBe('FAKE-WAV-BYTES');
+ });
+
+ it('passes engine + voice through to synthesize() when the id is namespaced', async () => {
+ synthesizeMock.mockResolvedValue({ wav: Buffer.from('w'), latencyMs: 1, engine: 'piper' });
+ await synthesizeToFile({ text: 'hi', voiceId: 'piper:en_GB-northern_english_male' });
+ expect(synthesizeMock).toHaveBeenCalledWith('hi', expect.objectContaining({
+ engine: 'piper',
+ voice: 'en_GB-northern_english_male',
+ }));
+ });
+
+ it('omits engine/voice when no voiceId is supplied (lets the configured default apply)', async () => {
+ synthesizeMock.mockResolvedValue({ wav: Buffer.from('w'), latencyMs: 1, engine: 'kokoro' });
+ await synthesizeToFile({ text: 'hi' });
+ const passed = synthesizeMock.mock.calls.at(-1)[1];
+ expect(passed).not.toHaveProperty('engine');
+ expect(passed).not.toHaveProperty('voice');
+ });
+});
diff --git a/server/services/pipeline/issues.js b/server/services/pipeline/issues.js
index 704c26081e..d3c2a6209a 100644
--- a/server/services/pipeline/issues.js
+++ b/server/services/pipeline/issues.js
@@ -81,7 +81,17 @@ export const ISSUES_PER_RESPONSE_MAX = 1000;
// in MVP.
export const TEXT_STAGE_IDS = Object.freeze(['idea', 'prose', 'comicScript', 'teleplay']);
export const VISUAL_STAGE_IDS = Object.freeze(['comicPages', 'storyboards', 'episodeVideo']);
-export const STAGE_IDS = Object.freeze([...TEXT_STAGE_IDS, ...VISUAL_STAGE_IDS]);
+// Audio is its own category — voice-over lines + music. Feature-gated on
+// series.targetFormat (only meaningful when the series ships video, not
+// comic-only). Kept separate from VISUAL_STAGE_IDS so the artifact shape
+// (`lines[]`, `music`) stays distinct from visual stages.
+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]);
export const STAGE_STATUSES = Object.freeze(['empty', 'generating', 'ready', 'edited', 'needs-review', 'error']);
export const ISSUE_STATUSES = Object.freeze(['draft', 'running', 'needs-review', 'shipped']);
@@ -184,10 +194,60 @@ const sanitizeVisualStage = (raw, stageId = null) => {
};
};
+// Audio stage shape — dialogue VO lines + optional background music. Each
+// line carries the source character + the actual line text + the render job
+// id + a server-stamped filename (the storyboards filename hook's pattern
+// will be extended to audio in a follow-up). `voiceIdOverride` lets a single
+// line use a different voice than the character's default (narrator V.O.,
+// flashback voice, etc.).
+const AUDIO_LINE_TEXT_MAX = 4000;
+const AUDIO_LINES_MAX = 1000;
+const AUDIO_FILENAME_MAX = 500;
+const AUDIO_LINE_ID_MAX = 80;
+const sanitizeAudioLine = (raw, i) => {
+ if (!raw || typeof raw !== 'object') return null;
+ const text = trimTo(raw.text, AUDIO_LINE_TEXT_MAX);
+ if (!text) return null;
+ const id = trimTo(raw.id, AUDIO_LINE_ID_MAX) || `line-${String(i + 1).padStart(3, '0')}`;
+ return {
+ id,
+ characterId: trimTo(raw.characterId, 80) || null,
+ characterName: trimTo(raw.characterName, 120) || null,
+ text,
+ voiceIdOverride: trimTo(raw.voiceIdOverride, 200) || null,
+ audioJobId: isStr(raw.audioJobId) && raw.audioJobId ? raw.audioJobId : null,
+ audioFilename: isStr(raw.audioFilename) && raw.audioFilename
+ ? raw.audioFilename.slice(0, AUDIO_FILENAME_MAX)
+ : null,
+ };
+};
+
+const MUSIC_SOURCES = new Set(['upload', 'library', 'gen']);
+const sanitizeMusicTrack = (raw) => {
+ if (!raw || typeof raw !== 'object') return null;
+ const source = MUSIC_SOURCES.has(raw.source) ? raw.source : null;
+ const trackFilename = trimTo(raw.trackFilename, AUDIO_FILENAME_MAX) || null;
+ const label = trimTo(raw.label, 200) || null;
+ if (!source && !trackFilename && !label) return null;
+ return { source, trackFilename, label };
+};
+
+const sanitizeAudioStage = (raw) => {
+ const base = sanitizeStage(raw);
+ return {
+ ...base,
+ lines: Array.isArray(raw?.lines)
+ ? raw.lines.slice(0, AUDIO_LINES_MAX).map(sanitizeAudioLine).filter(Boolean)
+ : [],
+ music: sanitizeMusicTrack(raw?.music),
+ };
+};
+
const sanitizeStages = (raw = {}) => {
const out = {};
for (const id of TEXT_STAGE_IDS) out[id] = sanitizeStage(raw[id]);
for (const id of VISUAL_STAGE_IDS) out[id] = sanitizeVisualStage(raw[id], id);
+ for (const id of AUDIO_STAGE_IDS) out[id] = sanitizeAudioStage(raw[id]);
return out;
};
@@ -494,6 +554,7 @@ export function updateStageWithLatest(issueId, stageId, computeFn) {
if (idx < 0) throw makeErr(`Issue not found: ${issueId}`, ERR_NOT_FOUND);
const cur = state.issues[idx];
const isVisual = VISUAL_STAGE_IDS.includes(stageId);
+ const isAudio = AUDIO_STAGE_IDS.includes(stageId);
const currentStage = cur.stages[stageId];
const patch = computeFn(currentStage);
// Empty-patch fast path: a computeFn that returns `{}` is a "decided not
@@ -508,7 +569,10 @@ export function updateStageWithLatest(issueId, stageId, computeFn) {
...patch,
updatedAt: new Date().toISOString(),
};
- const next = isVisual ? sanitizeVisualStage(merged, stageId) : sanitizeStage(merged);
+ let next;
+ if (isVisual) next = sanitizeVisualStage(merged, stageId);
+ else if (isAudio) next = sanitizeAudioStage(merged);
+ else next = sanitizeStage(merged);
const mergedIssue = sanitizeIssue({
...cur,
stages: { ...cur.stages, [stageId]: next },
diff --git a/server/services/pipeline/issues.test.js b/server/services/pipeline/issues.test.js
index d5b04be2ce..33e0d29cb1 100644
--- a/server/services/pipeline/issues.test.js
+++ b/server/services/pipeline/issues.test.js
@@ -331,4 +331,78 @@ describe('pipeline issues service', () => {
.rejects.toMatchObject({ code: svc.ERR_VALIDATION });
});
});
+
+ describe('audio stage sanitizer', () => {
+ const makeIssue = (audio) => svc.createIssue({
+ seriesId: 'ser-1',
+ title: 'Pilot',
+ stages: { audio },
+ });
+
+ it('seeds an empty audio stage by default', async () => {
+ const i = await svc.createIssue({ seriesId: 'ser-1', title: 'P' });
+ expect(i.stages.audio).toEqual({
+ status: 'empty', input: '', output: '', lastRunId: null,
+ errorMessage: '', updatedAt: null, lines: [], music: null,
+ });
+ });
+
+ it('round-trips lines[] with auto-assigned ids when omitted', async () => {
+ const i = await makeIssue({
+ status: 'edited',
+ lines: [
+ { text: 'Hello there.' },
+ { id: 'line-custom', text: 'Goodbye.', characterId: 'chr-1' },
+ ],
+ });
+ expect(i.stages.audio.lines).toHaveLength(2);
+ expect(i.stages.audio.lines[0].id).toBe('line-001');
+ expect(i.stages.audio.lines[1].id).toBe('line-custom');
+ expect(i.stages.audio.lines[1].characterId).toBe('chr-1');
+ });
+
+ it('drops lines without text (empty / whitespace / missing)', async () => {
+ const i = await makeIssue({
+ lines: [
+ { text: 'kept' },
+ { text: ' ' },
+ { text: '' },
+ { /* missing entirely */ },
+ null,
+ 'not-an-object',
+ { text: 'also kept' },
+ ],
+ });
+ expect(i.stages.audio.lines.map((l) => l.text)).toEqual(['kept', 'also kept']);
+ });
+
+ it('caps lines[] at 1000', async () => {
+ const huge = Array.from({ length: 1500 }, (_, n) => ({ text: `line ${n}` }));
+ const i = await makeIssue({ lines: huge });
+ expect(i.stages.audio.lines).toHaveLength(1000);
+ });
+
+ it('sanitizes music: drops unknown source, keeps allowed values', async () => {
+ const ok = await makeIssue({ music: { source: 'upload', trackFilename: 'bg.mp3', label: 'My track' } });
+ expect(ok.stages.audio.music).toEqual({
+ source: 'upload', trackFilename: 'bg.mp3', label: 'My track',
+ });
+
+ const bogus = await makeIssue({ music: { source: 'made-up' } });
+ // source allow-list dropped → only label/trackFilename matter; with both
+ // empty and source nulled, music falls to null entirely.
+ expect(bogus.stages.audio.music).toBe(null);
+ });
+
+ it('updateStage round-trips audio lines through the audio branch', async () => {
+ const i = await svc.createIssue({ seriesId: 'ser-1', title: 'P' });
+ const { stage } = await svc.updateStage(i.id, 'audio', {
+ status: 'edited',
+ lines: [{ id: 'line-001', text: 'fresh text', characterId: 'chr-9' }],
+ });
+ expect(stage.lines).toHaveLength(1);
+ expect(stage.lines[0].text).toBe('fresh text');
+ expect(stage.lines[0].characterId).toBe('chr-9');
+ });
+ });
});
diff --git a/server/services/voice/tools.js b/server/services/voice/tools.js
index d491a7d53f..4030c96a9a 100644
--- a/server/services/voice/tools.js
+++ b/server/services/voice/tools.js
@@ -3,7 +3,7 @@
// Add a new tool by pushing another entry onto TOOLS.
import { captureThought, getInboxLog } from '../brain.js';
-import { STAGE_IDS as PIPELINE_STAGE_IDS } from '../pipeline/issues.js';
+import { NAVIGABLE_STAGE_IDS as PIPELINE_STAGE_IDS } from '../pipeline/issues.js';
import { logDrink, getAlcoholSummary } from '../meatspaceAlcohol.js';
import { logNicotine, getNicotineSummary } from '../meatspaceNicotine.js';
import { addBodyEntry } from '../meatspaceHealth.js';
diff --git a/server/services/voice/tts.js b/server/services/voice/tts.js
index 2442c1758a..daa227622b 100644
--- a/server/services/voice/tts.js
+++ b/server/services/voice/tts.js
@@ -5,7 +5,10 @@ import { synthesizeKokoro, listKokoroVoices } from './tts-kokoro.js';
import { synthesizePiper, listPiperVoices } from './tts-piper.js';
import { findPiperVoice } from './piper-voices.js';
-const VALID_ENGINES = new Set(['kokoro', 'piper']);
+// Single source of truth for the supported TTS engine names. Imported by
+// routes/voice.js, routes/pipeline.js, and services/pipeline/audio.js so a
+// new engine (e.g. ElevenLabs) shows up in every consumer with one edit.
+export const VALID_ENGINES = new Set(['kokoro', 'piper']);
// Normalize `engine` against the allowlist so an invalid value can't silently
// produce Kokoro audio while the response reports `engine: 'elevenlabs'`.