[PR #1142] [CLOSED] feat(tts): stream audio per sentence as the model generates #4942

Closed
opened 2026-10-22 04:11:54 +07:00 by bsakaguchi · 0 comments
Owner

📋 Pull Request Information

Original PR: https://github.com/Pasta-Devs/Marinara-Engine/pull/1142
Author: @etherious1804
Created: 5/24/2026
Status: ❌ Closed

Base: staging ← Head: feat/tts-streaming-autoplay


📝 Commits (2)

  • 0954666 fix(tts): apply playback rate client-side for local OAI-compatible servers
  • efdf859 feat(tts): stream audio per sentence as the model generates

📊 Changes

8 files changed (+720 additions, -26 deletions)

View changed files

📝 packages/client/src/components/chat/ChatArea.tsx (+35 -2)
📝 packages/client/src/components/chat/ChatMessage.tsx (+52 -23)
📝 packages/client/src/components/panels/settings/TTSConfigCard.tsx (+13 -0)
➕ packages/client/src/hooks/use-streaming-tts.ts (+368 -0)
➕ packages/client/src/lib/sentence-chunker.ts (+205 -0)
📝 packages/client/src/lib/tts-dialogue.ts (+26 -0)
📝 packages/client/src/lib/tts-service.ts (+12 -1)
📝 packages/shared/src/types/tts.ts (+9 -0)

📄 Description

Linked issue

Closes #1138

Why this change

When auto-play is enabled, Marinara today waits for isStreaming to flip false before dispatching the entire reply to TTS. For local TTS providers (mlx-audio Chatterbox, openedai-speech, etc.) where synthesis is much slower than cloud APIs, this means the user waits the full generate time before hearing any audio. With a 30-second roleplay reply on a local M-series box, time-to-first-audio is 30+ seconds — the assistant has finished writing before it even starts speaking.

The information needed to start TTS much earlier is already available in the chat store: streamBuffers updates token-by-token as the LLM streams. We can split on sentence boundaries and dispatch each completed sentence as it arrives, then play the resulting clips sequentially. Time-to-first-audio drops to ~1-2 seconds (the time for the model to produce the first sentence plus one TTS round-trip).

What changed

Client — new streaming-TTS hook

  • packages/client/src/hooks/use-streaming-tts.ts: new useStreamingTTS hook subscribes to the chat store, runs a sentence chunker against the growing stream buffer, and dispatches ttsService.generateAudio per completed sentence. Audio fetches run in parallel; playback is serialized through a chained promise so order is preserved. Aborts cleanly on user-cancel (the existing chat-abort signal is forwarded, plus a local AbortController fires on stopSession). Per-audio AbortListener is bounded to that element's playback lifetime so long replies don't pile up 50+ listeners on a single signal.
  • The hook exports a module-level stopStreamingTTS() / isStreamingTTSActive() / subscribeStreamingTTSActive() trio so any UI surface can interrupt or observe the active session — the per-message speaker icon hooks into this.

Client — sentence chunker

  • packages/client/src/lib/sentence-chunker.ts: new module. Maintains a cursor + highWaterMark over the growing buffer; extractNewSentences emits each completed sentence as soon as a sentence-ending punctuation + whitespace appears. Multi-dot ellipses (.., ...) are explicitly NOT treated as sentence ends (continuations, not terminators). Known abbreviations (Mr., Dr., etc.) are skipped. The high-water mark prevents replay if the server later emits a content_replace SSE event that rewinds the buffer to a common prefix (used to strip character commands at end-of-stream).

Client — stop affordance on speaker icons

  • packages/client/src/components/chat/ChatMessage.tsx: every speaker icon subscribes to the streaming-TTS active state. While a session is active, the icon flips to VolumeX, shows "Stop streaming narration" as tooltip, and clicking any icon halts playback. The chat's generation-abort signal only fires while the LLM is streaming; without this affordance there's no way to interrupt audio after natural completion.

Wiring

  • packages/client/src/components/chat/ChatArea.tsx: invokes useStreamingTTS when the chat is in a mode that supports autoplay and ttsConfig.autoplayStreaming is on. The legacy "speak the whole reply at end-of-stream" path is gated on if (cfg.autoplayStreaming) return; so the reply isn't spoken twice.
  • packages/client/src/components/panels/settings/TTSConfigCard.tsx: adds the "Stream as the model generates" toggle under TTS settings (default off — no behavior change for existing users).
  • packages/shared/src/types/tts.ts: adds autoplayStreaming?: boolean to TTSConfig.

Known limitation

The speaker icon does not visually flip back to "play" after natural stream completion — it stays in stop-state until a new stream starts. Click-to-stop continues to function (clicking a stuck stop-icon is a safe no-op since there's nothing to stop). Will track in a follow-up; not blocking.

Dependency

Includes #1141 (client-side playback rate) as a base commit so the streaming-TTS path can honor the speed slider too. Once #1141 merges, this PR's diff will shrink to just the streaming TTS changes.

Validation

  • pnpm check passes locally

  • Container (Docker / Podman) built and ran without issue

  • Ran the app, clicked through the changes manually

  • Checked edge cases (light + dark mode, mobile viewport, empty states, error paths)

  • Above manual verification completed (describe below)

  • Read and followed CONTRIBUTING.md

Manual verification notes

Generated PR — unchecked boxes are left for the merger to confirm manually per the repo's AI-PR guidance.

What was verified on the branch (against a running Marinara dev server, local mlx-audio TTS, local Gemma 4 26B LLM, Roleplay mode with autoplay + streaming-TTS toggle on):

  • Streaming TTS fires per sentence during a long reply — first audio audible within ~1-2 seconds of model start.
  • Pressing any speaker icon mid-stream halts audio (the chained playback queue stops at the current element).
  • Regenerating a response correctly starts a fresh streaming-TTS session for the new reply (verified after fixing the cursor initialization race against setStreaming(true) → clearStreamBuffer()).
  • Ellipses like "But tell me, human..." don't cause mid-sentence cuts; the chunker waits for a real terminator.
  • Local Gemma's end-of-stream content_replace (strips character commands) no longer replays the cleaned tail — the high-water mark guards against re-emission.

To verify in browser:

  • Enable "Stream as the model generates" in TTS settings, autoplay on, Roleplay mode.
  • Send a message and confirm audio starts before the model finishes writing.
  • Mid-stream, click the speaker icon on the streaming message — audio stops.
  • Disable the toggle — behavior reverts to the existing "speak after stream ends" path.

Docs and release impact

  • No docs changes needed
  • Updated docs (README / CONTRIBUTING / android/README / CHANGELOG) as needed
  • Version/release files updated (only if this PR includes a version bump)

UI evidence (if applicable)

No new UI surface beyond the toggle in TTS settings. The speaker-icon swap (Volume2 ↔ VolumeX + sky-blue tint while streaming) is in-place, no new components.

🤖 Generated with Claude Code


🔄 This issue represents a GitHub Pull Request. It cannot be merged through Gitea due to API limitations.

## 📋 Pull Request Information **Original PR:** https://github.com/Pasta-Devs/Marinara-Engine/pull/1142 **Author:** [@etherious1804](https://github.com/etherious1804) **Created:** 5/24/2026 **Status:** ❌ Closed **Base:** `staging` ← **Head:** `feat/tts-streaming-autoplay` --- ### 📝 Commits (2) - [`0954666`](https://github.com/Pasta-Devs/Marinara-Engine/commit/09546664294536995d2917c56babf6bcb6f50370) fix(tts): apply playback rate client-side for local OAI-compatible servers - [`efdf859`](https://github.com/Pasta-Devs/Marinara-Engine/commit/efdf8598af03c5a7dbce351a5b49d2b2a899b89e) feat(tts): stream audio per sentence as the model generates ### 📊 Changes **8 files changed** (+720 additions, -26 deletions) <details> <summary>View changed files</summary> 📝 `packages/client/src/components/chat/ChatArea.tsx` (+35 -2) 📝 `packages/client/src/components/chat/ChatMessage.tsx` (+52 -23) 📝 `packages/client/src/components/panels/settings/TTSConfigCard.tsx` (+13 -0) ➕ `packages/client/src/hooks/use-streaming-tts.ts` (+368 -0) ➕ `packages/client/src/lib/sentence-chunker.ts` (+205 -0) 📝 `packages/client/src/lib/tts-dialogue.ts` (+26 -0) 📝 `packages/client/src/lib/tts-service.ts` (+12 -1) 📝 `packages/shared/src/types/tts.ts` (+9 -0) </details> ### 📄 Description ## Linked issue Closes #1138 ## Why this change When auto-play is enabled, Marinara today waits for `isStreaming` to flip false before dispatching the entire reply to TTS. For local TTS providers (mlx-audio Chatterbox, openedai-speech, etc.) where synthesis is much slower than cloud APIs, this means the user waits the *full* generate time before hearing any audio. With a 30-second roleplay reply on a local M-series box, time-to-first-audio is 30+ seconds — the assistant has finished writing before it even starts speaking. The information needed to start TTS much earlier is already available in the chat store: `streamBuffers` updates token-by-token as the LLM streams. We can split on sentence boundaries and dispatch each completed sentence as it arrives, then play the resulting clips sequentially. Time-to-first-audio drops to ~1-2 seconds (the time for the model to produce the first sentence plus one TTS round-trip). ## What changed **Client — new streaming-TTS hook** - `packages/client/src/hooks/use-streaming-tts.ts`: new `useStreamingTTS` hook subscribes to the chat store, runs a sentence chunker against the growing stream buffer, and dispatches `ttsService.generateAudio` per completed sentence. Audio fetches run in parallel; playback is serialized through a chained promise so order is preserved. Aborts cleanly on user-cancel (the existing chat-abort signal is forwarded, plus a local AbortController fires on `stopSession`). Per-audio AbortListener is bounded to that element's playback lifetime so long replies don't pile up 50+ listeners on a single signal. - The hook exports a module-level `stopStreamingTTS()` / `isStreamingTTSActive()` / `subscribeStreamingTTSActive()` trio so any UI surface can interrupt or observe the active session — the per-message speaker icon hooks into this. **Client — sentence chunker** - `packages/client/src/lib/sentence-chunker.ts`: new module. Maintains a `cursor` + `highWaterMark` over the growing buffer; `extractNewSentences` emits each completed sentence as soon as a sentence-ending punctuation + whitespace appears. Multi-dot ellipses (`..`, `...`) are explicitly NOT treated as sentence ends (continuations, not terminators). Known abbreviations (`Mr.`, `Dr.`, etc.) are skipped. The high-water mark prevents replay if the server later emits a `content_replace` SSE event that rewinds the buffer to a common prefix (used to strip character commands at end-of-stream). **Client — stop affordance on speaker icons** - `packages/client/src/components/chat/ChatMessage.tsx`: every speaker icon subscribes to the streaming-TTS active state. While a session is active, the icon flips to `VolumeX`, shows "Stop streaming narration" as tooltip, and clicking any icon halts playback. The chat's generation-abort signal only fires *while* the LLM is streaming; without this affordance there's no way to interrupt audio after natural completion. **Wiring** - `packages/client/src/components/chat/ChatArea.tsx`: invokes `useStreamingTTS` when the chat is in a mode that supports autoplay and `ttsConfig.autoplayStreaming` is on. The legacy "speak the whole reply at end-of-stream" path is gated on `if (cfg.autoplayStreaming) return;` so the reply isn't spoken twice. - `packages/client/src/components/panels/settings/TTSConfigCard.tsx`: adds the **"Stream as the model generates"** toggle under TTS settings (default off — no behavior change for existing users). - `packages/shared/src/types/tts.ts`: adds `autoplayStreaming?: boolean` to `TTSConfig`. ## Known limitation The speaker icon does **not** visually flip back to "play" after natural stream completion — it stays in stop-state until a new stream starts. Click-to-stop continues to function (clicking a stuck stop-icon is a safe no-op since there's nothing to stop). Will track in a follow-up; not blocking. ## Dependency Includes #1141 (client-side playback rate) as a base commit so the streaming-TTS path can honor the speed slider too. Once #1141 merges, this PR's diff will shrink to just the streaming TTS changes. ## Validation - [x] `pnpm check` passes locally - [ ] Container (Docker / Podman) built and ran without issue - [ ] Ran the app, clicked through the changes manually - [ ] Checked edge cases (light + dark mode, mobile viewport, empty states, error paths) - [ ] Above manual verification completed (describe below) - [ ] Read and followed `CONTRIBUTING.md` ### Manual verification notes > Generated PR — unchecked boxes are left for the merger to confirm manually per the repo's AI-PR guidance. **What was verified on the branch (against a running Marinara dev server, local mlx-audio TTS, local Gemma 4 26B LLM, Roleplay mode with autoplay + streaming-TTS toggle on):** - Streaming TTS fires per sentence during a long reply — first audio audible within ~1-2 seconds of model start. - Pressing any speaker icon mid-stream halts audio (the chained playback queue stops at the current element). - Regenerating a response correctly starts a fresh streaming-TTS session for the new reply (verified after fixing the cursor initialization race against `setStreaming(true) → clearStreamBuffer()`). - Ellipses like `"But tell me, human..."` don't cause mid-sentence cuts; the chunker waits for a real terminator. - Local Gemma's end-of-stream `content_replace` (strips character commands) no longer replays the cleaned tail — the high-water mark guards against re-emission. **To verify in browser:** - Enable "Stream as the model generates" in TTS settings, autoplay on, Roleplay mode. - Send a message and confirm audio starts before the model finishes writing. - Mid-stream, click the speaker icon on the streaming message — audio stops. - Disable the toggle — behavior reverts to the existing "speak after stream ends" path. ## Docs and release impact - [x] No docs changes needed - [ ] Updated docs (README / CONTRIBUTING / android/README / CHANGELOG) as needed - [ ] Version/release files updated (only if this PR includes a version bump) ## UI evidence (if applicable) No new UI surface beyond the toggle in TTS settings. The speaker-icon swap (Volume2 ↔ VolumeX + sky-blue tint while streaming) is in-place, no new components. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --- <sub>🔄 This issue represents a GitHub Pull Request. It cannot be merged through Gitea due to API limitations.</sub>
bsakaguchi 2026-10-22 04:11:54 +07:00
Sign in to join this conversation.
No milestone
No project
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set.

Reference
Pasta-Devs/Marinara-Engine#4942
No description provided.