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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat: read-aloud manuscript proofing with synced karaoke highlighting (#1304)
[._.]/ Adam Eivy04700ccc07d2
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 85ecedf2b3..63efffd95b 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -2,6 +2,8 @@## Added+- **[issue-1304] Read aloud — proof a manuscript section by ear with synced karaoke highlighting.** Reading prose aloud is one of the most effective proofing techniques: clunky rhythm, tongue-twisters, repeated words, and unnatural sentences are obvious to the ear and invisible to the eye. The Manuscript Editor gets a **Read aloud** button (in the header, next to Impact preview) that opens a read-along panel for the active section. It synthesizes the section's prose with the same local TTS engines that already voice storyboard dialogue (Kokoro/Piper — no new dependency, no network), splitting the text into sentence segments so it can **highlight each sentence as it's spoken** (karaoke-style) and let you click any sentence to jump there. Sync needs no word-level timestamps: the server measures each sentence's WAV duration and the client plays the segments back-to-back, driving the highlight + a progress bar from those durations. A pick-a-narrator-voice control (remembered across sessions) reuses the shared VoicePicker. Each sentence also carries a lightweight **"hard to say" scan** — over-long sentences, hard consonant clusters, alliteration runs, and a word repeated in close proximity get a wavy underline + hover tooltip so likely trouble-spots are visible before and while you listen. Narration is strictly **non-destructive** — it only reads the section's current text and never mutates the manuscript. New endpoint: `POST /api/pipeline/tts/narrate` (text → per-segment audio + duration + readability). (`server/services/pipeline/manuscriptNarration.js`, `server/services/pipeline/audio.js`, `server/routes/pipeline/audio.js`, `client/src/components/pipeline/manuscript/ManuscriptReadAloud.jsx`, `client/src/pages/PipelineManuscriptEditor.jsx`, `client/src/services/apiPipeline.js`) (#1304)+- **[issue-1354] Catalog cards show image thumbnails, generate art from a description, and a "Sync from Universes" button pulls in missing canon.** Three catalog gaps closed at once. (1) **Missing canon items** — characters/places/objects you add to a universe *after* the one-time setup never appeared in the Catalog, because canon→catalog promotion only ran once per install. A new **Sync from Universes** button on the Catalog page re-runs that promotion on demand (idempotent — already-catalogued items are skipped), so the catalog catches up to your universes in one click and the list refreshes with what was pulled in. (2) **Thumbnails** — each catalog card now shows the item's portrait (or its most recent reference image) as a thumbnail, falling back to a placeholder when there's no image, so the grid is scannable at a glance. (3) **Generate from description** — the catalog item editor's Media panel gets a **Generate** button that turns the item's description into an image via the same image-gen queue the universe canon uses; the first generated image becomes the item's portrait (and thumbnail), later ones attach as references. The button is disabled until the item has a description to render from. (#1354)- **[issue-1289] Ticking clock — model the countdown your reader is anticipating.** A story's "what is this building toward?" — an incoming storm, a deadline, a prophecy's hour — is now a first-class part of the series arc instead of something only implied. On the Arc Canvas you can turn on a **ticking clock**, name it, pick its kind (deadline / event / countdown / prophecy / bomb / custom), set where it's planted and where it's due, spell out the stakes if it runs out, and add **reminder beats** that keep it ticking in the reader's mind; it shows on the arc card and the Story Builder reader-map view with its plant→due span. The countdown is fed into arc generation so the AI reinforces it, and a new **Ticking-clock hygiene** editorial check flags a clock that's unnamed, has no stakes, has no plant/due span, is due before it's planted, or has no reminder beats to keep the reader from forgetting it through the long middle. (#1289)diff --git a/client/src/components/pipeline/manuscript/ManuscriptReadAloud.jsx b/client/src/components/pipeline/manuscript/ManuscriptReadAloud.jsxnew file mode 100644index 0000000000..57a55900b9--- /dev/null+++ b/client/src/components/pipeline/manuscript/ManuscriptReadAloud.jsx@@ -0,0 +1,299 @@+/**+ * Manuscript Read-Aloud — full-prose TTS proofing (#1304).+ *+ * Reading prose aloud surfaces clunky rhythm, tongue-twisters, repeated words,+ * and unnatural sentences that are invisible to the eye. This modal narrates the+ * active manuscript section with the local TTS engines (Kokoro/Piper, same path+ * as storyboard dialogue), highlighting each sentence karaoke-style as it plays.+ *+ * Sync: the server splits the prose into sentence segments and returns each+ * one's audio filename + measured duration. We play the segments back-to-back+ * via a single <audio> element and highlight the active sentence — no word-level+ * timestamps needed. Each segment also carries a "hard to say" readability scan;+ * flagged sentences get a wavy underline + tooltip so trouble-spots are visible+ * before/while listening.+ *+ * Non-destructive: narration never mutates the manuscript — it only reads the+ * section's current text.+ */++import { useEffect, useMemo, useRef, useState } from 'react';+import { Play, Pause, Square, Loader2, Volume2, AlertTriangle } from 'lucide-react';+import Modal from '../../ui/Modal';+import VoicePicker from '../../voice/VoicePicker';+import toast from '../../ui/Toast';+import { formatDurationMs } from '../../../utils/formatters';+import { narratePipelineProse } from '../../../services/api';+import { STAGE_LABEL } from './constants';++const NARRATOR_VOICE_KEY = 'portos.manuscript.narratorVoice';+const initialVoice = () => {+ if (typeof window === 'undefined') return '';+ return window.localStorage.getItem(NARRATOR_VOICE_KEY) || '';+};++export default function ManuscriptReadAloud({ open, onClose, section }) {+ const content = section?.content || '';+ const [voiceId, setVoiceId] = useState(initialVoice);+ const [segments, setSegments] = useState(null); // null = not synthesized yet+ const [loading, setLoading] = useState(false);+ // -1 = idle/no highlight; otherwise the segment currently cued.+ const [currentIndex, setCurrentIndex] = useState(-1);+ const [isPlaying, setIsPlaying] = useState(false);+ const [elapsedMs, setElapsedMs] = useState(0);++ const audioRef = useRef(null);+ const mountedRef = useRef(true);+ useEffect(() => () => { mountedRef.current = false; }, []);++ // Reset narration when the section being read changes or the modal closes —+ // stale segments belong to a different issue's prose.+ const resetNarration = () => {+ setSegments(null);+ setCurrentIndex(-1);+ setIsPlaying(false);+ setElapsedMs(0);+ };+ useEffect(() => { resetNarration(); }, [section?.issueId, section?.stageId]);+ useEffect(() => { if (!open) { setIsPlaying(false); } }, [open]);++ // Cumulative start offset (ms) per segment + total, for the progress bar.+ const { cumulative, totalMs } = useMemo(() => {+ const cum = [];+ let acc = 0;+ (segments || []).forEach((s) => { cum.push(acc); acc += s.durationMs || 0; });+ return { cumulative: cum, totalMs: acc };+ }, [segments]);++ const hardCount = useMemo(+ () => (segments || []).filter((s) => s.readability?.hard).length,+ [segments],+ );++ // Drive the <audio> element from (currentIndex, isPlaying). The src is bound+ // in JSX from currentIndex, so changing index reloads + plays from the start+ // of that segment; toggling isPlaying without an index change pauses/resumes.+ useEffect(() => {+ const audio = audioRef.current;+ if (!audio) return;+ if (currentIndex < 0) { audio.pause(); return; }+ if (isPlaying) audio.play().catch(() => {});+ else audio.pause();+ }, [currentIndex, isPlaying]);++ const runNarration = async () => {+ if (!content.trim()) {+ toast('There is no drafted prose to read aloud');+ return;+ }+ setLoading(true);+ const result = await narratePipelineProse(content, voiceId || undefined, { silent: true })+ .catch((err) => {+ toast.error(err.message || 'Failed to narrate');+ return null;+ });+ if (!mountedRef.current) return;+ setLoading(false);+ if (!result) return;+ const segs = Array.isArray(result.segments) ? result.segments : [];+ setSegments(segs);+ setElapsedMs(0);+ if (segs.length) { setCurrentIndex(0); setIsPlaying(true); }+ };++ const togglePlay = () => {+ if (!segments?.length) return;+ if (currentIndex < 0) { setCurrentIndex(0); setIsPlaying(true); return; }+ setIsPlaying((p) => !p);+ };++ const stop = () => {+ setIsPlaying(false);+ setCurrentIndex(-1);+ setElapsedMs(0);+ const audio = audioRef.current;+ if (audio) audio.currentTime = 0;+ };++ const jumpTo = (idx) => {+ setCurrentIndex(idx);+ setIsPlaying(true);+ };++ const onEnded = () => {+ if (currentIndex < (segments?.length || 0) - 1) {+ setCurrentIndex(currentIndex + 1);+ } else {+ setIsPlaying(false);+ setElapsedMs(totalMs);+ }+ };++ const onTimeUpdate = () => {+ const audio = audioRef.current;+ if (!audio || currentIndex < 0) return;+ setElapsedMs((cumulative[currentIndex] || 0) + audio.currentTime * 1000);+ };++ const changeVoice = (next) => {+ setVoiceId(next);+ if (typeof window !== 'undefined') window.localStorage.setItem(NARRATOR_VOICE_KEY, next || '');+ // Cached segments were synthesized with the prior voice — invalidate so the+ // next play re-synthesizes with the new narrator.+ resetNarration();+ };++ // Render the prose with each sentence wrapped in a span, preserving the exact+ // inter-sentence whitespace from the original text (the gaps between spans).+ const renderedProse = useMemo(() => {+ if (!segments?.length) return null;+ const nodes = [];+ let cursor = 0;+ segments.forEach((seg) => {+ if (seg.start > cursor) {+ nodes.push(<span key={`gap-${cursor}`}>{content.slice(cursor, seg.start)}</span>);+ }+ const active = seg.index === currentIndex;+ const reasons = seg.readability?.reasons || [];+ const hard = seg.readability?.hard;+ nodes.push(+ <span+ key={`seg-${seg.index}`}+ role="button"+ tabIndex={0}+ onClick={() => jumpTo(seg.index)}+ onKeyDown={(e) => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); jumpTo(seg.index); } }}+ title={hard ? `Hard to say: ${reasons.join('; ')}` : undefined}+ className={[+ 'cursor-pointer rounded transition-colors',+ active ? 'bg-port-accent/30 text-white' : 'hover:bg-port-border/40',+ hard ? 'underline decoration-wavy decoration-port-warning/70 underline-offset-2' : '',+ ].join(' ')}+ >+ {content.slice(seg.start, seg.end)}+ </span>,+ );+ cursor = seg.end;+ });+ if (cursor < content.length) {+ nodes.push(<span key={`gap-${cursor}`}>{content.slice(cursor)}</span>);+ }+ return nodes;+ }, [segments, content, currentIndex]);++ const currentSrc = (currentIndex >= 0 && segments?.[currentIndex])+ ? `/data/audio/${encodeURIComponent(segments[currentIndex].filename)}`+ : undefined;++ const progressPct = totalMs > 0 ? Math.min(100, (elapsedMs / totalMs) * 100) : 0;++ return (+ <Modal open={open} onClose={onClose} size="3xl" backdropClassName="bg-black/70 p-4" panelClassName="bg-port-card border border-port-border rounded-lg">+ <div className="flex flex-col max-h-[85vh]">+ <header className="flex items-center gap-2 px-4 py-3 border-b border-port-border">+ <Volume2 className="w-4 h-4 text-port-accent" />+ <h2 className="text-sm font-semibold text-white">+ Read aloud+ {section ? (+ <span className="text-gray-500 font-normal">+ {' '}— #{section.number} {section.title ? `· ${section.title}` : ''} ({STAGE_LABEL[section.stageId] || section.stageId})+ </span>+ ) : null}+ </h2>+ <button+ type="button"+ onClick={onClose}+ className="ml-auto text-gray-500 hover:text-white text-sm px-2"+ aria-label="Close read-aloud"+ >+ ✕+ </button>+ </header>++ <div className="px-4 py-3 border-b border-port-border space-y-2.5">+ <div className="flex items-end gap-3 flex-wrap">+ <div className="min-w-[220px]">+ <VoicePicker+ value={voiceId}+ onChange={changeVoice}+ label="Narrator voice"+ placeholder="Default voice"+ previewText="The morning fog burned off slow that day."+ disabled={loading}+ />+ </div>+ <div className="flex items-center gap-2">+ {!segments ? (+ <button+ type="button"+ onClick={runNarration}+ disabled={loading || !content.trim()}+ className="inline-flex items-center gap-1.5 px-3 py-1.5 rounded text-sm font-medium border bg-port-bg text-port-accent border-port-border hover:border-port-accent/40 disabled:opacity-40"+ >+ {loading ? <Loader2 size={14} className="animate-spin" /> : <Play size={14} />}+ {loading ? 'Synthesizing…' : 'Read aloud'}+ </button>+ ) : (+ <>+ <button+ type="button"+ onClick={togglePlay}+ className="inline-flex items-center gap-1.5 px-3 py-1.5 rounded text-sm font-medium border bg-port-bg text-port-accent border-port-border hover:border-port-accent/40"+ >+ {isPlaying ? <Pause size={14} /> : <Play size={14} />}+ {isPlaying ? 'Pause' : 'Play'}+ </button>+ <button+ type="button"+ onClick={stop}+ className="inline-flex items-center gap-1.5 px-2.5 py-1.5 rounded text-sm font-medium border bg-port-bg text-gray-400 border-port-border hover:text-white"+ >+ <Square size={13} /> Stop+ </button>+ </>+ )}+ </div>+ </div>++ {segments ? (+ <div className="space-y-1">+ <div className="h-1.5 w-full rounded bg-port-bg overflow-hidden">+ <div className="h-full bg-port-accent transition-[width] duration-150" style={{ width: `${progressPct}%` }} />+ </div>+ <div className="flex items-center justify-between text-[11px] text-gray-500">+ <span>+ {segments.length} sentence{segments.length === 1 ? '' : 's'}+ {currentIndex >= 0 ? ` · ${currentIndex + 1} of ${segments.length}` : ''}+ </span>+ <span>{formatDurationMs(elapsedMs)} / {formatDurationMs(totalMs)}</span>+ </div>+ {hardCount > 0 ? (+ <p className="flex items-center gap-1.5 text-[11px] text-port-warning">+ <AlertTriangle size={11} />+ {hardCount} possible trouble spot{hardCount === 1 ? '' : 's'} — underlined below; hover for why.+ </p>+ ) : null}+ </div>+ ) : null}+ </div>++ <div className="flex-1 overflow-y-auto px-5 py-4">+ {segments ? (+ <div className="whitespace-pre-wrap leading-relaxed text-[15px] text-gray-200">+ {renderedProse}+ </div>+ ) : (+ <div className="whitespace-pre-wrap leading-relaxed text-[15px] text-gray-400">+ {content.trim() ? content : <span className="italic text-gray-600">No drafted prose to read aloud yet.</span>}+ </div>+ )}+ </div>+ </div>++ {/* Hidden engine — playback is driven by the controls above. */}+ <audio ref={audioRef} src={currentSrc} onEnded={onEnded} onTimeUpdate={onTimeUpdate} className="hidden">+ <track kind="captions" />+ </audio>+ </Modal>+ );+}diff --git a/client/src/pages/PipelineManuscriptEditor.jsx b/client/src/pages/PipelineManuscriptEditor.jsxindex 34ed069617..b0419b02e3 100644--- a/client/src/pages/PipelineManuscriptEditor.jsx+++ b/client/src/pages/PipelineManuscriptEditor.jsx@@ -30,7 +30,7 @@import { useEffect, useMemo, useRef, useState } from 'react';import { Link, useParams, useNavigate, useSearchParams } from 'react-router-dom';import {- ArrowLeft, Loader2, Sparkles, FileText, Star, ClipboardCheck, Layers, PencilLine, BookOpen, GitCompare, X,+ ArrowLeft, Loader2, Sparkles, FileText, Star, ClipboardCheck, Layers, PencilLine, BookOpen, GitCompare, Volume2, X,} from 'lucide-react';import { formatManuscript } from '../lib/manuscriptFormat';import toast from '../components/ui/Toast';@@ -44,6 +44,7 @@ import AnnotatedManuscriptSection from '../components/pipeline/manuscript/Annotaimport ManuscriptCommentIndex from '../components/pipeline/manuscript/ManuscriptCommentIndex';import ManuscriptIssueTabs from '../components/pipeline/manuscript/ManuscriptIssueTabs';import ManuscriptImpactPreview from '../components/pipeline/manuscript/ManuscriptImpactPreview';+import ManuscriptReadAloud from '../components/pipeline/manuscript/ManuscriptReadAloud';import { MANUSCRIPT_TYPES, STAGE_LABEL } from '../components/pipeline/manuscript/constants';import {getPipelineSeries, updatePipelineSeries, getPipelineManuscript, getPipelineManuscriptReview,@@ -105,6 +106,7 @@ export default function PipelineManuscriptEditor() {// Which section (issueId) is in textarea edit mode in Review.const [editingIssueId, setEditingIssueId] = useState(null);const [showImpact, setShowImpact] = useState(false);+ const [showReadAloud, setShowReadAloud] = useState(false);// Per-comment fix-edit drafts, keyed by comment id and shared across every// place the card renders (sidebar reveal, in-context card, impact preview).const [fixDrafts, setFixDrafts] = useState({});@@ -655,6 +657,16 @@ export default function PipelineManuscriptEditor() {</button></div>+ <button+ type="button"+ onClick={() => setShowReadAloud(true)}+ disabled={!activeSection}+ title="Read this section aloud (TTS) with synced highlighting to catch clunky rhythm by ear"+ className="inline-flex items-center gap-1 px-2.5 py-1.5 rounded text-xs font-medium border bg-port-bg text-gray-300 border-port-border hover:border-port-accent/40 disabled:opacity-40"+ >+ <Volume2 size={13} /> Read aloud+ </button>+<buttontype="button"onClick={() => setShowImpact(true)}@@ -880,6 +892,12 @@ export default function PipelineManuscriptEditor() {fixDrafts={fixDrafts}onAccepted={applyAccepted}/>++ <ManuscriptReadAloud+ open={showReadAloud}+ onClose={() => setShowReadAloud(false)}+ section={activeSection}+ /></div>);}diff --git a/client/src/services/apiPipeline.js b/client/src/services/apiPipeline.jsindex fe59168528..e7c5a505c1 100644--- a/client/src/services/apiPipeline.js+++ b/client/src/services/apiPipeline.js@@ -736,6 +736,19 @@ export const previewPipelineTtsVoice = (voiceId, text) =>silent: true,});+// Narrate manuscript prose for read-aloud proofing (#1304). Splits the text+// into sentence segments, synthesizes each via the local TTS engines, and+// returns `{ segments: [{ index, text, start, end, filename, durationMs,+// readability }], voiceId, engine }` so the manuscript editor can play a+// karaoke-style read-along. Non-destructive. `options` lets the caller opt into+// silent mode when it owns its own error UI.+export const narratePipelineProse = (text, voiceId, options = {}) =>+ request('/pipeline/tts/narrate', {+ method: 'POST',+ body: JSON.stringify(voiceId ? { text, voiceId } : { text }),+ ...options,+ });+// 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 wipediff --git a/server/routes/pipeline/audio.js b/server/routes/pipeline/audio.jsindex 99d7000537..daa63ee667 100644--- a/server/routes/pipeline/audio.js+++ b/server/routes/pipeline/audio.js@@ -13,6 +13,7 @@ import * as issuesSvc from '../../services/pipeline/issues.js';import { getSeriesCanon } from '../../services/pipeline/seriesCanon.js';import { resolveSeriesLlmOverride } from '../../lib/seriesLlmOverride.js';import { listAllVoices, synthesizeToFile, parseVoiceId, extractDialogueLines, resolveVoiceForLine } from '../../services/pipeline/audio.js';+import { narrateProse } from '../../services/pipeline/manuscriptNarration.js';import { synthesize as synthesizeVoice } from '../../services/voice/tts.js';import {listMusicLibrary,@@ -89,6 +90,22 @@ router.post('/tts/synthesize', asyncHandler(async (req, res) => {res.json(result);}));+// Narrate arbitrary manuscript prose for read-aloud proofing (#1304). Splits+// the text into sentence segments, synthesizes each via the local TTS engines,+// and returns per-segment audio + duration + readability flags so the+// manuscript editor can play a karaoke-style read-along. Non-destructive — the+// WAVs land in PATHS.audio exactly like /tts/preview + the dialogue render.+const ttsNarrateSchema = z.object({+ text: z.string().trim().min(1).max(12000),+ voiceId: z.string().trim().max(200).optional(),+});+router.post('/tts/narrate', asyncHandler(async (req, res) => {+ const body = validateRequest(ttsNarrateSchema, req.body ?? {});+ const result = await narrateProse({ text: body.text, voiceId: body.voiceId })+ .catch((err) => { throw mapServiceError(err); });+ 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 adiff --git a/server/services/pipeline/audio.js b/server/services/pipeline/audio.jsindex 57e94d5d3a..58d3a65cef 100644--- a/server/services/pipeline/audio.js+++ b/server/services/pipeline/audio.js@@ -192,6 +192,41 @@ export function extractDialogueLines(issue, canon, { preserveFrom = [] } = {}) {return { lines, preservedCount };}+/**+ * Compute the playback duration (ms) of a PCM WAV buffer by reading its+ * canonical RIFF header — `data` chunk size ÷ `fmt ` byte rate. Used by the+ * narration timeline (karaoke-style highlight sync) where the client needs a+ * per-segment duration without decoding the audio itself.+ *+ * Pure + defensive: scans the sub-chunk list (the `fmt ` and `data` chunks+ * aren't guaranteed to be adjacent or first), and returns 0 for anything that+ * isn't a parseable WAV so a malformed buffer degrades to "unknown length"+ * instead of throwing into the synth path.+ */+export function wavDurationMs(buffer) {+ if (!Buffer.isBuffer(buffer) || buffer.length < 12) return 0;+ if (buffer.toString('ascii', 0, 4) !== 'RIFF' || buffer.toString('ascii', 8, 12) !== 'WAVE') return 0;+ let byteRate = 0;+ let dataSize = 0;+ let offset = 12;+ while (offset + 8 <= buffer.length) {+ const id = buffer.toString('ascii', offset, offset + 4);+ const size = buffer.readUInt32LE(offset + 4);+ const body = offset + 8;+ if (id === 'fmt ' && body + 16 <= buffer.length) {+ byteRate = buffer.readUInt32LE(body + 8);+ } else if (id === 'data') {+ // Clamp to the bytes actually present — a truncated stream can carry a+ // larger declared size than the buffer holds.+ dataSize = Math.min(size, buffer.length - body);+ }+ // Chunks are word-aligned: an odd size carries a trailing pad byte.+ offset = body + size + (size % 2);+ }+ if (!byteRate || !dataSize) return 0;+ return Math.round((dataSize / byteRate) * 1000);+}+export async function synthesizeToFile({ text, voiceId, signal } = {}) {const trimmed = (text || '').trim();if (!trimmed) {@@ -208,5 +243,11 @@ export async function synthesizeToFile({ text, voiceId, signal } = {}) {// 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 };+ return {+ filename,+ latencyMs,+ durationMs: wavDurationMs(wav),+ engine: usedEngine,+ voiceId: voice ? `${usedEngine}:${voice}` : null,+ };}diff --git a/server/services/pipeline/audio.test.js b/server/services/pipeline/audio.test.jsindex 39d3718811..445f785046 100644--- a/server/services/pipeline/audio.test.js+++ b/server/services/pipeline/audio.test.js@@ -24,7 +24,29 @@ tryReadFile: vi.fn().mockResolvedValue(null),VALID_ENGINES: new Set(['kokoro', 'piper']),}));-const { parseVoiceId, listAllVoices, synthesizeToFile, extractDialogueLines, resolveVoiceForLine } = await import('./audio.js');+const { parseVoiceId, listAllVoices, synthesizeToFile, extractDialogueLines, resolveVoiceForLine, wavDurationMs } = await import('./audio.js');++// Build a minimal canonical PCM WAV header for `dataBytes` of audio at the given+// sample rate / channels / bit depth, so duration math is exercised end-to-end.+function makeWav({ sampleRate = 24000, channels = 1, bitsPerSample = 16, dataBytes = 0 } = {}) {+ const byteRate = sampleRate * channels * (bitsPerSample / 8);+ const blockAlign = channels * (bitsPerSample / 8);+ const buf = Buffer.alloc(44 + dataBytes);+ buf.write('RIFF', 0, 'ascii');+ buf.writeUInt32LE(36 + dataBytes, 4);+ buf.write('WAVE', 8, 'ascii');+ buf.write('fmt ', 12, 'ascii');+ buf.writeUInt32LE(16, 16);+ buf.writeUInt16LE(1, 20); // PCM+ buf.writeUInt16LE(channels, 22);+ buf.writeUInt32LE(sampleRate, 24);+ buf.writeUInt32LE(byteRate, 28);+ buf.writeUInt16LE(blockAlign, 32);+ buf.writeUInt16LE(bitsPerSample, 34);+ buf.write('data', 36, 'ascii');+ buf.writeUInt32LE(dataBytes, 40);+ return buf;+}beforeEach(async () => {synthesizeMock.mockReset();@@ -121,6 +143,36 @@ describe('synthesizeToFile', () => {expect(passed).not.toHaveProperty('engine');expect(passed).not.toHaveProperty('voice');});++ it('returns the measured WAV duration (ms) for the narration timeline', async () => {+ // 24000 samples of 16-bit mono @ 24kHz = exactly 1 second.+ synthesizeMock.mockResolvedValue({ wav: makeWav({ dataBytes: 24000 * 2 }), latencyMs: 5, engine: 'kokoro' });+ const result = await synthesizeToFile({ text: 'one second please', voiceId: 'kokoro:af_heart' });+ expect(result.durationMs).toBe(1000);+ });+});++describe('wavDurationMs', () => {+ it('computes duration from the data chunk and byte rate', () => {+ expect(wavDurationMs(makeWav({ sampleRate: 24000, dataBytes: 24000 * 2 }))).toBe(1000);+ expect(wavDurationMs(makeWav({ sampleRate: 16000, dataBytes: 16000 * 2 }))).toBe(1000);+ // Half a second.+ expect(wavDurationMs(makeWav({ sampleRate: 24000, dataBytes: 24000 }))).toBe(500);+ });++ it('returns 0 for non-buffer / too-short / non-RIFF input', () => {+ expect(wavDurationMs(null)).toBe(0);+ expect(wavDurationMs(Buffer.alloc(4))).toBe(0);+ expect(wavDurationMs(Buffer.from('NOT-A-WAV-FILE-AT-ALL'))).toBe(0);+ });++ it('clamps a declared data size larger than the actual buffer', () => {+ const buf = makeWav({ sampleRate: 24000, dataBytes: 24000 * 2 });+ // Lie about the data size (claim 10x the bytes present) — duration must+ // reflect the bytes actually in the buffer, not the inflated header value.+ buf.writeUInt32LE(24000 * 2 * 10, 40);+ expect(wavDurationMs(buf)).toBe(1000);+ });});describe('extractDialogueLines', () => {diff --git a/server/services/pipeline/manuscriptNarration.js b/server/services/pipeline/manuscriptNarration.jsnew file mode 100644index 0000000000..1d5ece0f19--- /dev/null+++ b/server/services/pipeline/manuscriptNarration.js@@ -0,0 +1,219 @@+/**+ * Manuscript narration — full-prose "read aloud" proofing (#1304).+ *+ * Reading prose aloud is one of the most effective proofing techniques: clunky+ * rhythm, tongue-twisters, repeated words, and unnatural sentences are obvious+ * to the ear and invisible to the eye. PortOS already synthesizes storyboard+ * *dialogue* (`audio.js` → `synthesizeToFile`); this extends the same local TTS+ * engines (Kokoro/Piper) to arbitrary manuscript prose.+ *+ * Strategy — sentence-segmented synthesis for karaoke sync. Local TTS engines+ * return a WAV with no word-level timestamps, so we split the prose into+ * sentence segments, synthesize each one independently, and measure its WAV+ * duration. The client plays the segments back-to-back and highlights the+ * active sentence from those durations (no decoding, no timestamp metadata).+ * Each segment also carries a lightweight readability scan so likely+ * trouble-spots are marked before/while listening.+ *+ * Non-destructive: this never mutates the manuscript — the WAVs land in+ * PATHS.audio exactly like the dialogue render + voice preview paths.+ */++import { ServerError } from '../../lib/errorHandler.js';+import { synthesizeToFile } from './audio.js';++// Upper bound on sentences synthesized in one narrate call. A whole section can+// be thousands of words; synthesizing every sentence is sequential + slow, so+// cap it and tell the caller to narrate a smaller selection rather than hang.+export const MAX_NARRATION_SEGMENTS = 400;++// Abbreviations whose trailing period must NOT end a sentence — otherwise+// "Dr. Vane" or "U.S. Navy" split mid-phrase and the highlight stutters.+const ABBREVIATIONS = new Set([+ 'mr', 'mrs', 'ms', 'dr', 'prof', 'sr', 'jr', 'st', 'mt', 'vs', 'etc',+ 'e.g', 'i.e', 'a.m', 'p.m', 'no', 'vol', 'fig', 'gen', 'sgt', 'capt', 'lt',+]);++const isAbbreviation = (word) => {+ if (!word) return false;+ const w = word.toLowerCase().replace(/[^a-z.]/g, '');+ if (ABBREVIATIONS.has(w) || ABBREVIATIONS.has(w.replace(/\.$/, ''))) return true;+ // Single-letter initials ("J." in "J. R. R. Tolkien") and dotted acronyms+ // ("U.S.A.") — a lone capital before the period.+ return /^[a-z]\.?$/i.test(w);+};++/**+ * Split prose into sentence segments, preserving char offsets into the original+ * text so the client can reconstruct the section verbatim (inter-sentence+ * whitespace lives in the gaps between [start, end] spans). Pure, no I/O.+ *+ * @param {string} text+ * @returns {Array<{ text: string, start: number, end: number }>}+ */+export function splitProseIntoSentences(text) {+ if (typeof text !== 'string' || !text.trim()) return [];+ const segments = [];+ let cursor = 0; // start of the current pending sentence (incl. leading ws)+ let i = 0;+ const len = text.length;++ const push = (end) => {+ // Trim leading/trailing whitespace off the recorded span so the highlight+ // wraps the words, not the surrounding blank space.+ let s = cursor;+ let e = end;+ while (s < e && /\s/.test(text[s])) s += 1;+ while (e > s && /\s/.test(text[e - 1])) e -= 1;+ if (e > s) segments.push({ text: text.slice(s, e), start: s, end: e });+ cursor = end;+ };++ while (i < len) {+ const ch = text[i];+ if (ch === '.' || ch === '!' || ch === '?') {+ // Consume a run of terminators + trailing closing quotes/brackets.+ let j = i + 1;+ while (j < len && /[.!?]/.test(text[j])) j += 1;+ while (j < len && /["'”’)\]]/.test(text[j])) j += 1;+ const priorWord = text.slice(cursor, i + 1).trim().split(/\s+/).pop();+ const nextChar = text[j] || '';+ // A lowercase letter after the terminator marks a continuation, not a+ // boundary — a dialogue tag (`"Run!" she cried.`) or a trailing-off+ // ellipsis (`Wait... what?`). Find the next significant (non-space) char.+ let k = j;+ while (k < len && /\s/.test(text[k])) k += 1;+ const continuation = /[a-z]/.test(text[k] || '');+ let boundary;+ if (ch === '.') {+ // A period is a boundary only when followed by whitespace/end (so+ // "3.14" / "U.S.A" don't split), isn't a known abbreviation, and isn't+ // a lowercase continuation.+ boundary = (nextChar === '' || /\s/.test(nextChar)) && !isAbbreviation(priorWord) && !continuation;+ } else {+ boundary = !continuation;+ }+ if (boundary) { push(j); i = j; continue; }+ i = j;+ continue;+ }+ // A blank line (paragraph break) also ends the current sentence so prose+ // without terminal punctuation (poetry, fragments) still segments.+ if (ch === '\n' && /\n[ \t]*\n/.test(text.slice(i, i + 3))) {+ push(i);+ }+ i += 1;+ }+ if (cursor < len) push(len);+ return segments;+}++const HARD_CLUSTER_RE = /[bcdfghjklmnpqrstvwxz]{4,}/i;+const LONG_SENTENCE_WORDS = 40;++/**+ * Lightweight "hard to say" scan for a single sentence — marks likely+ * trouble-spots an author would catch by ear: over-long sentences, hard+ * consonant clusters / tongue-twisters, and a word repeated in close+ * proximity. Pure, deterministic, no I/O. Returns `{ hard, reasons }` where+ * `reasons` is a short list of human-readable labels for the UI tooltip.+ *+ * @param {string} sentence+ * @returns {{ hard: boolean, reasons: string[] }}+ */+export function analyzeSentenceReadability(sentence) {+ const reasons = [];+ if (typeof sentence !== 'string' || !sentence.trim()) return { hard: false, reasons };+ const words = sentence.trim().split(/\s+/);++ if (words.length >= LONG_SENTENCE_WORDS) {+ reasons.push(`long sentence (${words.length} words)`);+ }++ // Hard consonant clusters — 4+ consonants in a row, ignoring word breaks+ // within a single token (e.g. "twelfths", "strengths").+ const cluster = words.find((w) => HARD_CLUSTER_RE.test(w.replace(/[^a-z]/gi, '')));+ if (cluster) reasons.push('hard consonant cluster');++ // Alliteration spike — 3+ adjacent words sharing a first letter reads as a+ // tongue-twister aloud even when each word is fine on its own.+ const initials = words.map((w) => (w.match(/[a-z]/i)?.[0] || '').toLowerCase());+ let run = 1;+ for (let k = 1; k < initials.length; k += 1) {+ if (initials[k] && initials[k] === initials[k - 1]) {+ run += 1;+ if (run >= 3) { reasons.push('alliteration run'); break; }+ } else {+ run = 1;+ }+ }++ // A content word repeated within a 5-word window — the kind of echo the ear+ // catches instantly. Skip short/common function words.+ const norm = words.map((w) => w.toLowerCase().replace(/[^a-z]/g, ''));+ const STOP = new Set(['the', 'and', 'that', 'with', 'for', 'was', 'were', 'had', 'have', 'his', 'her', 'she', 'him', 'they', 'their', 'you', 'are', 'but', 'not', 'this', 'from', 'into', 'out', 'all', 'one']);+ for (let k = 0; k < norm.length; k += 1) {+ const w = norm[k];+ if (w.length < 4 || STOP.has(w)) continue;+ for (let m = k + 1; m <= k + 5 && m < norm.length; m += 1) {+ if (norm[m] === w) { reasons.push(`repeated word "${w}"`); k = norm.length; break; }+ }+ }++ return { hard: reasons.length > 0, reasons };+}++/**+ * Synthesize a manuscript section's prose into an ordered list of sentence+ * segments with per-segment audio + duration + readability flags. The client+ * stitches these into a karaoke read-along (highlight the active sentence,+ * scrub by segment).+ *+ * @param {object} args+ * @param {string} args.text prose to narrate+ * @param {string} [args.voiceId] namespaced narrator voice (e.g. kokoro:af_heart)+ * @param {AbortSignal} [args.signal]+ * @returns {Promise<{ segments: Array, voiceId: string|null, engine: string }>}+ */+export async function narrateProse({ text, voiceId, signal } = {}) {+ const trimmed = (text || '').trim();+ if (!trimmed) {+ throw new ServerError('text is required', { status: 400, code: 'PIPELINE_NARRATION_EMPTY_TEXT' });+ }+ const sentences = splitProseIntoSentences(text);+ if (sentences.length === 0) {+ throw new ServerError('no narratable sentences found', {+ status: 400, code: 'PIPELINE_NARRATION_NO_SENTENCES',+ });+ }+ if (sentences.length > MAX_NARRATION_SEGMENTS) {+ throw new ServerError(+ `Too long to narrate in one pass (${sentences.length} sentences, max ${MAX_NARRATION_SEGMENTS}) — narrate a smaller selection.`,+ { status: 413, code: 'PIPELINE_NARRATION_TOO_LONG' },+ );+ }++ let usedEngine = null;+ let usedVoiceId = null;+ const segments = [];+ // Sequential synthesis: the local engines run in-process and one model is+ // loaded at a time, so parallelizing would just thrash. Order matters anyway+ // — the client plays them back-to-back.+ for (let idx = 0; idx < sentences.length; idx += 1) {+ const seg = sentences[idx];+ const result = await synthesizeToFile({ text: seg.text, voiceId, signal });+ usedEngine = result.engine;+ usedVoiceId = result.voiceId || usedVoiceId;+ segments.push({+ index: idx,+ text: seg.text,+ start: seg.start,+ end: seg.end,+ filename: result.filename,+ durationMs: result.durationMs,+ readability: analyzeSentenceReadability(seg.text),+ });+ }++ return { segments, voiceId: usedVoiceId, engine: usedEngine };+}diff --git a/server/services/pipeline/manuscriptNarration.test.js b/server/services/pipeline/manuscriptNarration.test.jsnew file mode 100644index 0000000000..4beb02ea4b--- /dev/null+++ b/server/services/pipeline/manuscriptNarration.test.js@@ -0,0 +1,146 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';++const synthesizeToFileMock = vi.fn();+vi.mock('./audio.js', () => ({+ synthesizeToFile: (...a) => synthesizeToFileMock(...a),+}));++const {+ splitProseIntoSentences,+ analyzeSentenceReadability,+ narrateProse,+ MAX_NARRATION_SEGMENTS,+} = await import('./manuscriptNarration.js');++describe('splitProseIntoSentences', () => {+ it('returns [] for empty / non-string input', () => {+ expect(splitProseIntoSentences('')).toEqual([]);+ expect(splitProseIntoSentences(' ')).toEqual([]);+ expect(splitProseIntoSentences(null)).toEqual([]);+ expect(splitProseIntoSentences(42)).toEqual([]);+ });++ it('splits on terminal punctuation and preserves char offsets', () => {+ const text = 'The fog rolled in. She waited. Did he come?';+ const segs = splitProseIntoSentences(text);+ expect(segs.map((s) => s.text)).toEqual([+ 'The fog rolled in.',+ 'She waited.',+ 'Did he come?',+ ]);+ // Offsets reconstruct the original slice verbatim.+ segs.forEach((s) => expect(text.slice(s.start, s.end)).toBe(s.text));+ });++ it('does not split on common abbreviations', () => {+ const segs = splitProseIntoSentences('Dr. Vane met Mr. Poe today. They talked.');+ expect(segs).toHaveLength(2);+ expect(segs[0].text).toBe('Dr. Vane met Mr. Poe today.');+ expect(segs[1].text).toBe('They talked.');+ });++ it('does not split a decimal number or dotted acronym mid-token', () => {+ expect(splitProseIntoSentences('Pi is 3.14 today.').map((s) => s.text))+ .toEqual(['Pi is 3.14 today.']);+ });++ it('keeps trailing quotes/brackets with the sentence', () => {+ const segs = splitProseIntoSentences('"Run!" she cried. He froze.');+ expect(segs[0].text).toBe('"Run!" she cried.');+ expect(segs[1].text).toBe('He froze.');+ });++ it('treats a blank line as a sentence boundary even without punctuation', () => {+ const segs = splitProseIntoSentences('A fragment\n\nAnother fragment');+ expect(segs.map((s) => s.text)).toEqual(['A fragment', 'Another fragment']);+ });++ it('treats a lowercase continuation after a terminator as the same sentence', () => {+ // Ellipsis/interrobang followed by a lowercase word reads as one breath+ // aloud; the capitalized "No." starts a new sentence.+ const segs = splitProseIntoSentences('Wait... what?! No.');+ expect(segs.map((s) => s.text)).toEqual(['Wait... what?!', 'No.']);+ });++ it('captures a trailing sentence with no terminal punctuation', () => {+ const segs = splitProseIntoSentences('Done. And then');+ expect(segs.map((s) => s.text)).toEqual(['Done.', 'And then']);+ });+});++describe('analyzeSentenceReadability', () => {+ it('flags nothing for a clean short sentence', () => {+ const r = analyzeSentenceReadability('The cat sat on the mat.');+ expect(r.hard).toBe(false);+ expect(r.reasons).toEqual([]);+ });++ it('flags an over-long sentence', () => {+ const long = `${Array.from({ length: 45 }, (_, i) => `word${i}`).join(' ')}.`;+ const r = analyzeSentenceReadability(long);+ expect(r.hard).toBe(true);+ expect(r.reasons.some((x) => x.startsWith('long sentence'))).toBe(true);+ });++ it('flags hard consonant clusters', () => {+ const r = analyzeSentenceReadability('He grasped the twelfths quickly.');+ expect(r.reasons).toContain('hard consonant cluster');+ });++ it('flags alliteration runs', () => {+ const r = analyzeSentenceReadability('Sally sells seashells today.');+ expect(r.reasons).toContain('alliteration run');+ });++ it('flags a content word repeated in close proximity', () => {+ const r = analyzeSentenceReadability('The shadow crossed the shadow again.');+ expect(r.reasons.some((x) => x.includes('repeated word'))).toBe(true);+ });++ it('ignores repeated stop-words', () => {+ const r = analyzeSentenceReadability('The dog and the fox ran.');+ expect(r.reasons.some((x) => x.includes('repeated word'))).toBe(false);+ });++ it('returns hard:false for empty input', () => {+ expect(analyzeSentenceReadability('')).toEqual({ hard: false, reasons: [] });+ });+});++describe('narrateProse', () => {+ beforeEach(() => {+ synthesizeToFileMock.mockReset();+ let n = 0;+ synthesizeToFileMock.mockImplementation(async ({ voiceId }) => {+ n += 1;+ return { filename: `seg-${n}.wav`, durationMs: 1000 + n, engine: 'kokoro', voiceId: voiceId || 'kokoro:af_heart' };+ });+ });++ it('rejects empty text', async () => {+ await expect(narrateProse({ text: ' ' })).rejects.toMatchObject({ status: 400 });+ });++ it('synthesizes each sentence and returns per-segment audio + duration + readability', async () => {+ const result = await narrateProse({ text: 'First line. Second line.', voiceId: 'kokoro:af_heart' });+ expect(synthesizeToFileMock).toHaveBeenCalledTimes(2);+ expect(result.segments).toHaveLength(2);+ expect(result.segments[0]).toMatchObject({+ index: 0, text: 'First line.', filename: 'seg-1.wav', durationMs: 1001,+ });+ expect(result.segments[0].readability).toEqual({ hard: false, reasons: [] });+ expect(result.engine).toBe('kokoro');+ expect(result.voiceId).toBe('kokoro:af_heart');+ });++ it('passes the requested voiceId through to synthesis', async () => {+ await narrateProse({ text: 'Hello there.', voiceId: 'piper:lessac' });+ expect(synthesizeToFileMock).toHaveBeenCalledWith(expect.objectContaining({ voiceId: 'piper:lessac' }));+ });++ it('rejects prose with more than MAX_NARRATION_SEGMENTS sentences', async () => {+ const huge = Array.from({ length: MAX_NARRATION_SEGMENTS + 5 }, (_, i) => `Sentence ${i}.`).join(' ');+ await expect(narrateProse({ text: huge })).rejects.toMatchObject({ status: 413 });+ expect(synthesizeToFileMock).not.toHaveBeenCalled();+ });+});