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: re-render and accept as spoken for individual manuscript narration sentences (#10258)

[._.]/ Adam Eivyf15e685065b6
diff --git a/client/src/components/pipeline/manuscript/ManuscriptReadAloud.jsx b/client/src/components/pipeline/manuscript/ManuscriptReadAloud.jsx
index 35b4c9a217..3c70344560 100644
--- a/client/src/components/pipeline/manuscript/ManuscriptReadAloud.jsx
+++ b/client/src/components/pipeline/manuscript/ManuscriptReadAloud.jsx
@@ -24,8 +24,8 @@ import VoicePicker from '../../voice/VoicePicker';
import toast from '../../ui/Toast';
import ProgressBar from '../../ui/ProgressBar';
import { formatDurationMs } from '../../../utils/formatters';
-import { countLinesNeedingListen } from '../SpokenCheckChip';
-import { narratePipelineProse } from '../../../services/api';
+import SpokenCheckChip, { countLinesNeedingListen } from '../SpokenCheckChip';
+import { acceptNarrationSegmentSpeech, narratePipelineProse, rerenderNarrationSegment } from '../../../services/api';
import { STAGE_LABEL } from './constants';
import { clickableProps, onActivateKeyDown } from '../../../lib/a11yKeyboard';
import { safeReadStorage, safeWriteStorage } from '../../../lib/safeStorage';
@@ -43,6 +43,8 @@ export default function ManuscriptReadAloud({ open, onClose, section }) {
const [currentIndex, setCurrentIndex] = useState(-1);
const [isPlaying, setIsPlaying] = useState(false);
const [elapsedMs, setElapsedMs] = useState(0);
+ // Segment index being re-rendered / re-scored (one at a time), or null.
+ const [busyIndex, setBusyIndex] = useState(null);
const audioRef = useRef(null);
// Gates the post-synthesis state writes so a narration that resolves after the
@@ -81,6 +83,10 @@ export default function ManuscriptReadAloud({ open, onClose, section }) {
}, [segments]);
const listenCount = useMemo(() => countLinesNeedingListen(segments), [segments]);
+ const mismatchedSegments = useMemo(
+ () => (segments || []).filter((s) => s.verification?.status === 'mismatch'),
+ [segments],
+ );
const hardCount = useMemo(
() => (segments || []).filter((s) => s.readability?.hard).length,
[segments],
@@ -130,6 +136,49 @@ export default function ManuscriptReadAloud({ open, onClose, section }) {
if (segs.length && openRef.current) { setCurrentIndex(0); setIsPlaying(true); }
};
+ // Merge a per-segment update into the cached segments by index.
+ const patchSegment = (index, patch) => {
+ setSegments((prev) => (prev ? prev.map((seg) => (seg.index === index ? { ...seg, ...patch } : seg)) : prev));
+ };
+
+ // Re-synthesize one sentence (honoring any accepted spelling) and re-check it.
+ const rerenderSegment = async (seg) => {
+ setBusyIndex(seg.index);
+ const reqContent = content;
+ const result = await rerenderNarrationSegment(
+ reqContent.slice(seg.start, seg.end), voiceId || undefined, seg.expectedSpeech, { silent: true },
+ ).catch((err) => {
+ toast.error(err.message || 'Failed to re-render sentence');
+ return null;
+ });
+ if (!mountedRef.current) return;
+ setBusyIndex(null);
+ if (!result || contentRef.current !== reqContent) return;
+ patchSegment(seg.index, {
+ filename: result.filename,
+ durationMs: result.durationMs,
+ verification: result.verification,
+ });
+ };
+
+ // "Accept as spoken": what speech-to-text heard becomes the expected read.
+ const acceptSegment = async (seg) => {
+ const heard = seg.verification?.heard;
+ if (!heard) return;
+ setBusyIndex(seg.index);
+ const reqContent = content;
+ const result = await acceptNarrationSegmentSpeech(
+ reqContent.slice(seg.start, seg.end), heard, heard, { silent: true },
+ ).catch((err) => {
+ toast.error(err.message || 'Failed to accept as spoken');
+ return null;
+ });
+ if (!mountedRef.current) return;
+ setBusyIndex(null);
+ if (!result || contentRef.current !== reqContent) return;
+ patchSegment(seg.index, { expectedSpeech: result.expectedSpeech, verification: result.verification });
+ };
+
const togglePlay = () => {
if (!segments?.length) return;
if (currentIndex < 0) { setCurrentIndex(0); setIsPlaying(true); return; }
@@ -312,6 +361,28 @@ export default function ManuscriptReadAloud({ open, onClose, section }) {
{listenCount} of {segments.length} sentence{segments.length === 1 ? '' : 's'} need a listen — speech-to-text heard something different from the text.
</p>
) : null}
+ {mismatchedSegments.length > 0 ? (
+ <ul className="max-h-32 overflow-y-auto space-y-1" aria-label="Sentences that need a listen">
+ {mismatchedSegments.map((seg) => (
+ <li key={seg.index} className="text-[11px] text-gray-400 flex items-center gap-2 flex-wrap">
+ <button
+ type="button"
+ onClick={() => jumpTo(seg.index)}
+ className="truncate max-w-[16rem] text-left underline decoration-dotted hover:text-white"
+ title={content.slice(seg.start, seg.end)}
+ >
+ {content.slice(seg.start, seg.end)}
+ </button>
+ <SpokenCheckChip
+ verification={seg.verification}
+ busy={busyIndex !== null}
+ onRerender={() => rerenderSegment(seg)}
+ onAccept={() => acceptSegment(seg)}
+ />
+ </li>
+ ))}
+ </ul>
+ ) : null}
{hardCount > 0 ? (
<p className="flex items-center gap-1.5 text-[11px] text-port-warning">
<AlertTriangle size={11} />
diff --git a/client/src/components/pipeline/manuscript/ManuscriptReadAloud.test.jsx b/client/src/components/pipeline/manuscript/ManuscriptReadAloud.test.jsx
new file mode 100644
index 0000000000..6b4655f7c3
--- /dev/null
+++ b/client/src/components/pipeline/manuscript/ManuscriptReadAloud.test.jsx
@@ -0,0 +1,59 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { render, screen, fireEvent, waitFor } from '@testing-library/react';
+
+const api = vi.hoisted(() => ({
+ narratePipelineProse: vi.fn(),
+ rerenderNarrationSegment: vi.fn(),
+ acceptNarrationSegmentSpeech: vi.fn(),
+}));
+vi.mock('../../../services/api', () => api);
+vi.mock('../../voice/VoicePicker', () => ({ default: () => null }));
+vi.mock('../../ui/Toast', () => ({ default: Object.assign(vi.fn(), { error: vi.fn() }) }));
+
+import ManuscriptReadAloud from './ManuscriptReadAloud';
+
+const CONTENT = 'The AI woke. Dawn came.';
+const segment = (index, start, end, verification) => ({
+ index, text: CONTENT.slice(start, end), start, end, filename: `s${index}.wav`, durationMs: 500,
+ verification, readability: { hard: false, reasons: [] },
+});
+
+describe('ManuscriptReadAloud segment review', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ window.HTMLMediaElement.prototype.play = vi.fn(() => Promise.resolve());
+ window.HTMLMediaElement.prototype.pause = vi.fn();
+ api.narratePipelineProse.mockResolvedValue({
+ segments: [
+ segment(0, 0, 12, { status: 'mismatch', similarity: 0.4, heard: 'The ay eye woke' }),
+ segment(1, 13, 23, { status: 'matched', similarity: 1, heard: 'Dawn came' }),
+ ],
+ });
+ });
+
+ const open = async () => {
+ render(<ManuscriptReadAloud open onClose={() => {}} section={{ content: CONTENT, number: 1, stageId: 'draft' }} />);
+ fireEvent.click(screen.getByText('Read aloud', { selector: 'button' }));
+ await screen.findByText(/need a listen/);
+ };
+
+ it('accepts a misheard sentence as spoken and clears it from the review list', async () => {
+ api.acceptNarrationSegmentSpeech.mockResolvedValue({
+ expectedSpeech: 'The ay eye woke', verification: { status: 'matched', similarity: 1, heard: 'The ay eye woke' },
+ });
+ await open();
+ fireEvent.click(screen.getByText('Accept as spoken'));
+ await waitFor(() => expect(screen.queryByText(/need a listen/)).not.toBeInTheDocument());
+ expect(api.acceptNarrationSegmentSpeech).toHaveBeenCalledWith('The AI woke.', 'The ay eye woke', 'The ay eye woke', { silent: true });
+ });
+
+ it('re-renders a misheard sentence with fresh audio and its new check', async () => {
+ api.rerenderNarrationSegment.mockResolvedValue({
+ filename: 'fresh.wav', durationMs: 600, verification: { status: 'matched', similarity: 1, heard: 'The AI woke' },
+ });
+ await open();
+ fireEvent.click(screen.getByText('Re-render'));
+ await waitFor(() => expect(screen.queryByText(/need a listen/)).not.toBeInTheDocument());
+ expect(api.rerenderNarrationSegment).toHaveBeenCalledWith('The AI woke.', undefined, undefined, { silent: true });
+ });
+});
diff --git a/client/src/services/apiPipeline.js b/client/src/services/apiPipeline.js
index 486e49d9d2..f52fba6076 100644
--- a/client/src/services/apiPipeline.js
+++ b/client/src/services/apiPipeline.js
@@ -1051,6 +1051,21 @@ export const narratePipelineProse = (text, voiceId, options = {}) =>
...options,
});
+// Per-segment narration review (#10258). Re-render one sentence (fresh audio +
+// spoken-text check) and re-score its heard text against an accepted spelling.
+export const rerenderNarrationSegment = (text, voiceId, expectedSpeech, options = {}) =>
+ request('/pipeline/tts/narrate/segment', {
+ method: 'POST',
+ body: JSON.stringify({ text, ...(voiceId ? { voiceId } : {}), ...(expectedSpeech ? { expectedSpeech } : {}) }),
+ ...options,
+ });
+export const acceptNarrationSegmentSpeech = (text, heard, expectedSpeech, options = {}) =>
+ request('/pipeline/tts/narrate/segment', {
+ method: 'PATCH',
+ body: JSON.stringify({ text, heard, expectedSpeech }),
+ ...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 wipe
diff --git a/server/routes/pipeline.test.js b/server/routes/pipeline.test.js
index 11f7d915ff..ee695efeac 100644
--- a/server/routes/pipeline.test.js
+++ b/server/routes/pipeline.test.js
@@ -2877,6 +2877,63 @@ describe('pipeline routes', () => {
});
});
+ describe('narration segment review (#10258)', () => {
+ // Same stub shape as renderWithVerification: transcribe + compareSpeech.
+ const stubVerifiedSynth = async () => {
+ const audio = await import('../services/pipeline/audio.js');
+ audio.synthesizeToFile.mockImplementationOnce(async ({ text, expectedSpeech }) => {
+ const heard = await transcribeMock(Buffer.from('w'), { prompt: '' }).catch(() => null);
+ return {
+ filename: `vo-mock-${++uuidCounter}.wav`, durationMs: 900, latencyMs: 1, engine: 'kokoro', voiceId: 'kokoro:af_heart',
+ verification: heard
+ ? { ...compareSpeech(expectedSpeech || text, heard.text), heard: heard.text }
+ : { status: 'unverified', similarity: null, heard: '' },
+ };
+ });
+ };
+
+ it('re-renders a mismatched segment, then accepts what was heard as spoken', async () => {
+ const app = makeApp();
+ const text = 'The AI woke at dawn.';
+ transcribeMock.mockResolvedValueOnce({ text: 'The ay eye woke at dawn' });
+ await stubVerifiedSynth();
+ const rerender = await request(app).post('/api/pipeline/tts/narrate/segment').send({ text, voiceId: 'kokoro:af_heart' });
+ expect(rerender.status).toBe(200);
+ expect(rerender.body).toMatchObject({ durationMs: 900, engine: 'kokoro', verification: { status: 'mismatch', heard: 'The ay eye woke at dawn' } });
+ expect(rerender.body.filename).toMatch(/^vo-mock-/);
+
+ const accepted = await request(app).patch('/api/pipeline/tts/narrate/segment')
+ .send({ text, heard: 'The ay eye woke at dawn', expectedSpeech: 'The ay eye woke at dawn' });
+ expect(accepted.status).toBe(200);
+ expect(accepted.body).toMatchObject({ expectedSpeech: 'The ay eye woke at dawn', verification: { status: 'matched', similarity: 1 } });
+
+ // The next re-render compares against the accepted spelling.
+ transcribeMock.mockResolvedValueOnce({ text: 'The ay eye woke at dawn' });
+ await stubVerifiedSynth();
+ const again = await request(app).post('/api/pipeline/tts/narrate/segment')
+ .send({ text, expectedSpeech: 'The ay eye woke at dawn' });
+ expect(again.body.verification.status).toBe('matched');
+ });
+
+ it('leaves the segment unverified, and the render succeeds, when STT is down', async () => {
+ const app = makeApp();
+ transcribeMock.mockRejectedValueOnce(new Error('connect ECONNREFUSED'));
+ await stubVerifiedSynth();
+ const r = await request(app).post('/api/pipeline/tts/narrate/segment').send({ text: 'Plain sentence.' });
+ expect(r.status).toBe(200);
+ expect(r.body.verification).toEqual({ status: 'unverified', similarity: null, heard: '' });
+
+ const rescored = await request(app).patch('/api/pipeline/tts/narrate/segment')
+ .send({ text: 'Plain sentence.', heard: '', expectedSpeech: 'Plain sentence' });
+ expect(rescored.body.verification.status).toBe('unverified');
+ });
+
+ it('rejects a segment re-render with no text', async () => {
+ const r = await request(makeApp()).post('/api/pipeline/tts/narrate/segment').send({ text: ' ' });
+ expect(r.status).toBe(400);
+ });
+ });
+
it('keeps local voice profile provenance out of the federated issue record', async () => {
const audio = await import('../services/pipeline/audio.js');
const profiles = await import('../services/voice/profiles.js');
diff --git a/server/routes/pipeline/audio.js b/server/routes/pipeline/audio.js
index 6d9c21cc37..712ea77f4c 100644
--- a/server/routes/pipeline/audio.js
+++ b/server/routes/pipeline/audio.js
@@ -117,6 +117,49 @@ router.post('/tts/narrate', asyncHandler(async (req, res) => {
res.json(result);
}));
+// Re-render ONE narration segment (#10258). Narration segments are client-held
+// (the read-aloud modal never persists them), so this is stateless: the client
+// sends the segment text back and gets fresh audio + a fresh spoken-text check.
+// `expectedSpeech` is the user's accepted recognizer spelling for the segment.
+const ttsNarrateSegmentSchema = z.object({
+ text: z.string().trim().min(1).max(4000),
+ voiceId: z.string().trim().max(200).optional(),
+ expectedSpeech: z.string().trim().max(4000).nullable().optional(),
+});
+router.post('/tts/narrate/segment', asyncHandler(async (req, res) => {
+ const body = validateRequest(ttsNarrateSegmentSchema, req.body ?? {});
+ const result = await synthesizeToFile({
+ text: body.text,
+ voiceId: body.voiceId,
+ expectedSpeech: body.expectedSpeech || undefined,
+ }).catch((err) => { throw mapServiceError(err); });
+ res.json({
+ filename: result.filename,
+ durationMs: result.durationMs,
+ verification: result.verification,
+ engine: result.engine,
+ voiceId: result.voiceId || null,
+ });
+}));
+
+// "Accept as spoken" for a narration segment: re-score the segment's stored
+// `heard` text against a new `expectedSpeech` target. No STT call — mirrors the
+// audio-line PATCH. A segment with nothing heard stays `unverified`.
+const ttsNarrateSegmentRescoreSchema = z.object({
+ text: z.string().trim().min(1).max(4000),
+ heard: z.string().max(4000),
+ expectedSpeech: z.string().trim().max(4000).nullable().optional(),
+});
+router.patch('/tts/narrate/segment', asyncHandler(async (req, res) => {
+ const body = validateRequest(ttsNarrateSegmentRescoreSchema, req.body ?? {});
+ const expectedSpeech = body.expectedSpeech || null;
+ if (!body.heard.trim()) {
+ return res.json({ expectedSpeech, verification: { status: 'unverified', similarity: null, heard: '' } });
+ }
+ const { status, similarity } = compareSpeech(expectedSpeech || body.text, body.heard);
+ res.json({ expectedSpeech, verification: { status, similarity, heard: body.heard } });
+}));
+
// 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