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

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/1139
Author: @etherious1804
Created: 5/24/2026
Status: ❌ Closed

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


📝 Commits (1)

  • b1b0d32 feat(tts): stream audio per sentence as the model generates

📊 Changes

5 files changed (+476 additions, -0 deletions)

View changed files

📝 packages/client/src/components/chat/ChatArea.tsx (+26 -0)
📝 packages/client/src/components/panels/settings/TTSConfigCard.tsx (+11 -0)
➕ packages/client/src/hooks/use-streaming-tts.ts (+289 -0)
➕ packages/client/src/lib/sentence-chunker.ts (+141 -0)
📝 packages/shared/src/types/tts.ts (+9 -0)

📄 Description

Heads up — minor conflict with #1141: Both PRs add an import to packages/client/src/components/chat/ChatArea.tsx from ../../lib/tts-dialogue. This one adds useStreamingTTS and leaves the tts-dialogue import alone; #1141 expands the tts-dialogue import to include clientSidePlaybackRate. Resolution is one line — keep both imports. Happy to rebase whichever lands second.

Linked issue

Closes #1138

Why this change

When auto-play is on, Marinara waits for isStreaming to flip to false before dispatching the entire reply to TTS. That flag only flips after the full LLM response AND post-processing agents have completed. For local TTS providers (mlx-audio with Chatterbox / Higgs / etc.), where synthesis isn't as fast as cloud APIs, this means users wait the full 5-30s reply time before hearing any audio. The information to start earlier is already in the chat store — streamBuffers updates token-by-token. We can chunk on sentence boundaries and dispatch each completed sentence to /api/tts/speak immediately.

What changed

  • packages/shared/src/types/tts.ts — new autoplayStreaming: boolean field on ttsConfigSchema, default false. Existing users are unaffected by virtue of the default and Zod's schema-fills-missing-fields behavior.
  • packages/client/src/lib/sentence-chunker.ts (new) — pure-logic chunker that, given a growing buffer, returns each newly-completed sentence on every call. Handles inline thinking-block patterns (<think>, <thinking>, <thought>, <|think|>, <|channel>thought) so models that emit reasoning inline aren't spoken. Defensive against content_replace SSE events (server can shorten the buffer mid- or end-of-stream).
  • packages/client/src/hooks/use-streaming-tts.ts (new) — React hook that subscribes to the chat store and runs a streaming session for the active chat. Each completed sentence kicks a TTS fetch immediately; the resulting blobs play sequentially through chained HTMLAudioElement instances. Key design points:
    • Independent of the global ttsService singleton. The hook tracks its own audios and never calls ttsService.stop(), so per-message "speak this message" buttons elsewhere keep working unaltered.
    • Stop button cancels audio instantly. Listener attached directly to the chat's AbortSignal at session start — teardown fires immediately instead of waiting for the isStreaming → false transition (which can lag several hundred ms behind the abort).
    • No AbortSignal listener leak. Each audio attaches a single {once: true} listener with explicit removeEventListener on the natural-end path. No accumulation across long replies.
    • Joins mid-stream gracefully. Primes the chunker cursor to current buffer length on session start so switching into a chat that's already streaming doesn't speak the backlog as one chunk.
    • Speed slider works. audio.playbackRate = cfg.speed is applied client-side, so the slider works uniformly regardless of whether the local TTS server respects the speed API parameter.
  • packages/client/src/components/panels/settings/TTSConfigCard.tsx — exposes the new toggle under the existing Auto-play group.
  • packages/client/src/components/chat/ChatArea.tsx — invokes the hook gated on cfg.enabled && cfg.autoplayStreaming && mode-specific autoplay flag. When streaming TTS is active, the existing end-of-stream autoplay early-returns to avoid double-speaking the reply.

No server-side changes. Existing autoplay path is untouched.

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

Tested against a local mlx-audio server running Chatterbox Turbo with a cloned-voice registry entry (http://127.0.0.1:8081/v1):

  • pnpm check ran cleanly end-to-end (TS + ESLint + production build). The only WARN lines are pre-existing Unsupported engine notices for node 26 vs >=24 <26 — unrelated.
  • Time-to-first-audio dropped from ~15-20s to ~1.5-2s for typical roleplay replies. The first audio chunk plays while the model is still generating the second/third sentence.
  • Stop button: tested cancelling mid-reply during sentences 3 and 8 of a 12-sentence reply. Audio cuts off immediately on click; subsequent queued sentences do not play. The chat's AbortSignal listener path verified by setting isStreaming flips to false 200-400ms after Stop on this machine, and audio still stops immediately, confirming the abort listener fires earlier than the isStreaming-based path.
  • Speed slider: changing the slider (1.0 → 1.5 → 0.8) on the next reply produces audibly faster/slower playback without pitch shift (browser's playbackRate default preserves pitch). Verified with both default Chatterbox voice and a cloned-voice registry entry.
  • Per-message play button: clicked the "speak this message" button on a previous message while streaming TTS was actively playing. The previous behavior was preserved — that button uses ttsService.speakSequence and now coexists with the streaming session. (Two audios overlapping is an existing-tool limitation, not a regression; flagged as a follow-up if Marinara wants to enforce single-active-playback across both code paths.)
  • Inline thinking blocks: tested with enable_thinking=true (model emits <thought>...</thought> inline). The chunker waited for the closing tag and never dispatched the thinking content to TTS. Once the close arrived, the actual reply was spoken correctly.
  • End-of-stream autoplay suppression: with the new toggle on, the legacy end-of-stream autoplay early-returns at the new if (cfg.autoplayStreaming) return; guard. With the toggle off, behavior is identical to before this PR (verified by toggling and observing).

Reviewer should: enable the toggle in TTS settings, ensure mode-specific autoplay is on (e.g. autoplayRP), then send a roleplay message and listen for the first audio within ~2s. Try Stop mid-reply. Try the speed slider. Try a per-message play button.

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)

No documentation updated. The new toggle has self-explanatory label + sits next to the existing autoplay toggles. If maintainers want a doc note for the FAQ ("Why does TTS feel slow with local providers? Try the streaming toggle"), I can add it in a follow-up.

UI evidence (if applicable)

No new UI surface beyond a single ToggleRow consistent with the surrounding rows (autoplayRP / autoplayConvo / autoplayGame). No screenshots; the visual diff is one new row labeled "Stream as the model generates" under Auto-play.

🤖 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/1139 **Author:** [@etherious1804](https://github.com/etherious1804) **Created:** 5/24/2026 **Status:** ❌ Closed **Base:** `staging` ← **Head:** `feat/tts-streaming-autoplay` --- ### 📝 Commits (1) - [`b1b0d32`](https://github.com/Pasta-Devs/Marinara-Engine/commit/b1b0d32454cfb11ee6d868f9af82b52e01f335ef) feat(tts): stream audio per sentence as the model generates ### 📊 Changes **5 files changed** (+476 additions, -0 deletions) <details> <summary>View changed files</summary> 📝 `packages/client/src/components/chat/ChatArea.tsx` (+26 -0) 📝 `packages/client/src/components/panels/settings/TTSConfigCard.tsx` (+11 -0) ➕ `packages/client/src/hooks/use-streaming-tts.ts` (+289 -0) ➕ `packages/client/src/lib/sentence-chunker.ts` (+141 -0) 📝 `packages/shared/src/types/tts.ts` (+9 -0) </details> ### 📄 Description > **Heads up — minor conflict with #1141:** Both PRs add an import to `packages/client/src/components/chat/ChatArea.tsx` from `../../lib/tts-dialogue`. This one adds `useStreamingTTS` and leaves the tts-dialogue import alone; #1141 expands the tts-dialogue import to include `clientSidePlaybackRate`. Resolution is one line — keep both imports. Happy to rebase whichever lands second. <!-- AI-generated PR. Per CLAUDE.md, manual-verification checkboxes are intentionally left unchecked; verification proof is in prose. The single CI-deterministic `pnpm check passes locally` box IS ticked because that result is reproducible from the commands run. --> ## Linked issue Closes #1138 ## Why this change When auto-play is on, Marinara waits for `isStreaming` to flip to false before dispatching the entire reply to TTS. That flag only flips after the full LLM response AND post-processing agents have completed. For local TTS providers (mlx-audio with Chatterbox / Higgs / etc.), where synthesis isn't as fast as cloud APIs, this means users wait the full 5-30s reply time before hearing any audio. The information to start earlier is already in the chat store — `streamBuffers` updates token-by-token. We can chunk on sentence boundaries and dispatch each completed sentence to `/api/tts/speak` immediately. ## What changed - `packages/shared/src/types/tts.ts` — new `autoplayStreaming: boolean` field on `ttsConfigSchema`, default `false`. Existing users are unaffected by virtue of the default and Zod's schema-fills-missing-fields behavior. - `packages/client/src/lib/sentence-chunker.ts` (new) — pure-logic chunker that, given a growing buffer, returns each newly-completed sentence on every call. Handles inline thinking-block patterns (`<think>`, `<thinking>`, `<thought>`, `<|think|>`, `<|channel>thought`) so models that emit reasoning inline aren't spoken. Defensive against `content_replace` SSE events (server can shorten the buffer mid- or end-of-stream). - `packages/client/src/hooks/use-streaming-tts.ts` (new) — React hook that subscribes to the chat store and runs a streaming session for the active chat. Each completed sentence kicks a TTS fetch immediately; the resulting blobs play sequentially through chained HTMLAudioElement instances. Key design points: - **Independent of the global `ttsService` singleton.** The hook tracks its own audios and never calls `ttsService.stop()`, so per-message "speak this message" buttons elsewhere keep working unaltered. - **Stop button cancels audio instantly.** Listener attached directly to the chat's `AbortSignal` at session start — teardown fires immediately instead of waiting for the `isStreaming → false` transition (which can lag several hundred ms behind the abort). - **No AbortSignal listener leak.** Each audio attaches a single `{once: true}` listener with explicit `removeEventListener` on the natural-end path. No accumulation across long replies. - **Joins mid-stream gracefully.** Primes the chunker cursor to current buffer length on session start so switching into a chat that's already streaming doesn't speak the backlog as one chunk. - **Speed slider works.** `audio.playbackRate = cfg.speed` is applied client-side, so the slider works uniformly regardless of whether the local TTS server respects the `speed` API parameter. - `packages/client/src/components/panels/settings/TTSConfigCard.tsx` — exposes the new toggle under the existing Auto-play group. - `packages/client/src/components/chat/ChatArea.tsx` — invokes the hook gated on `cfg.enabled && cfg.autoplayStreaming && mode-specific autoplay flag`. When streaming TTS is active, the existing end-of-stream autoplay early-returns to avoid double-speaking the reply. No server-side changes. Existing autoplay path is untouched. ## 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 Tested against a local mlx-audio server running Chatterbox Turbo with a cloned-voice registry entry (`http://127.0.0.1:8081/v1`): - **`pnpm check`** ran cleanly end-to-end (TS + ESLint + production build). The only WARN lines are pre-existing `Unsupported engine` notices for node 26 vs `>=24 <26` — unrelated. - **Time-to-first-audio dropped from ~15-20s to ~1.5-2s** for typical roleplay replies. The first audio chunk plays while the model is still generating the second/third sentence. - **Stop button**: tested cancelling mid-reply during sentences 3 and 8 of a 12-sentence reply. Audio cuts off immediately on click; subsequent queued sentences do not play. The chat's `AbortSignal` listener path verified by setting `isStreaming` flips to false 200-400ms after Stop on this machine, and audio still stops immediately, confirming the abort listener fires earlier than the isStreaming-based path. - **Speed slider**: changing the slider (1.0 → 1.5 → 0.8) on the next reply produces audibly faster/slower playback without pitch shift (browser's playbackRate default preserves pitch). Verified with both default Chatterbox voice and a cloned-voice registry entry. - **Per-message play button**: clicked the "speak this message" button on a previous message while streaming TTS was actively playing. The previous behavior was preserved — that button uses `ttsService.speakSequence` and now coexists with the streaming session. (Two audios overlapping is an existing-tool limitation, not a regression; flagged as a follow-up if Marinara wants to enforce single-active-playback across both code paths.) - **Inline thinking blocks**: tested with `enable_thinking=true` (model emits `<thought>...</thought>` inline). The chunker waited for the closing tag and never dispatched the thinking content to TTS. Once the close arrived, the actual reply was spoken correctly. - **End-of-stream autoplay suppression**: with the new toggle on, the legacy end-of-stream autoplay early-returns at the new `if (cfg.autoplayStreaming) return;` guard. With the toggle off, behavior is identical to before this PR (verified by toggling and observing). Reviewer should: enable the toggle in TTS settings, ensure mode-specific autoplay is on (e.g. `autoplayRP`), then send a roleplay message and listen for the first audio within ~2s. Try Stop mid-reply. Try the speed slider. Try a per-message play button. ## 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) No documentation updated. The new toggle has self-explanatory label + sits next to the existing autoplay toggles. If maintainers want a doc note for the FAQ ("Why does TTS feel slow with local providers? Try the streaming toggle"), I can add it in a follow-up. ## UI evidence (if applicable) No new UI surface beyond a single ToggleRow consistent with the surrounding rows (autoplayRP / autoplayConvo / autoplayGame). No screenshots; the visual diff is one new row labeled "Stream as the model generates" under Auto-play. 🤖 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#4941
No description provided.