The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): stream sync TTS by sentence
embwl0xe39900cc91df
diff --git a/apps/desktop/src/app/chat/composer/hooks/use-voice-conversation-rearm.test.tsx b/apps/desktop/src/app/chat/composer/hooks/use-voice-conversation-rearm.test.tsxindex e993abc5730..dc41ee570b4 100644--- a/apps/desktop/src/app/chat/composer/hooks/use-voice-conversation-rearm.test.tsx+++ b/apps/desktop/src/app/chat/composer/hooks/use-voice-conversation-rearm.test.tsx@@ -7,7 +7,9 @@ import { useVoiceConversation } from './use-voice-conversation'const mocks = vi.hoisted(() => {let deferStreamStart = false+ let deferFallbackPlayback = falselet onSilence: null | (() => void) = null+ let resolveFallbackPlayback: null | ((played: boolean) => void) = nulllet resolveStreamStart: null | (() => void) = nulllet resolveSpeech: null | ((outcome: 'done' | 'fallback') => void) = nulllet streamAvailable = true@@ -20,6 +22,12 @@ const mocks = vi.hoisted(() => {const playSpeechText = vi.fn(() => {stopVoicePlayback()+ if (deferFallbackPlayback) {+ return new Promise<boolean>(resolve => {+ resolveFallbackPlayback = resolve+ })+ }+return Promise.resolve(true)})@@ -39,16 +47,25 @@ const mocks = vi.hoisted(() => {resolveStreamStart?.()resolveStreamStart = null},+ deferFallbackPlayback() {+ deferFallbackPlayback = true+ },deferStreamStart() {deferStreamStart = true},finishSpeech(outcome: 'done' | 'fallback') {resolveSpeech?.(outcome)},+ finishFallbackPlayback() {+ resolveFallbackPlayback?.(true)+ resolveFallbackPlayback = null+ },handle,playSpeechText,resetSpeechMocks() {+ deferFallbackPlayback = falsedeferStreamStart = false+ resolveFallbackPlayback = nullresolveStreamStart = nullresolveSpeech = nullstreamAvailable = true@@ -146,6 +163,36 @@ function renderRearmConversation(responseId: string, responseText: string) {)}+function renderIncrementalFallbackConversation() {+ let response: null | { id: string; pending: boolean; text: string } = null++ const hook = renderHook(+ ({ enabled }) =>+ useVoiceConversation({+ busy: false,+ consumePendingResponse: vi.fn(),+ enabled,+ onSubmit: async () => {+ response = { id: 'reply-edge', pending: true, text: 'The first sentence is ready. ' }+ },+ onTranscribeAudio: async () => 'Hello',+ pendingResponse: () => response+ }),+ { initialProps: { enabled: false } }+ )++ return {+ finishResponse() {+ response = {+ id: 'reply-edge',+ pending: false,+ text: 'The first sentence is ready. The second sentence is ready.'+ }+ },+ hook+ }+}+async function beginReply(hook: ReturnType<typeof renderRearmConversation>) {hook.rerender({ enabled: true })await waitFor(() => expect(mocks.handle.start).toHaveBeenCalledTimes(1))@@ -255,4 +302,62 @@ describe('useVoiceConversation playback rearm', () => {await waitFor(() => expect(mocks.handle.start).toHaveBeenCalledTimes(2))expect(hook.result.current.status).toBe('listening')})++ it('speaks completed fallback sentences before the response finishes', async () => {+ mocks.useFallbackSpeech()+ const { finishResponse, hook } = renderIncrementalFallbackConversation()++ await beginReply(hook)++ await waitFor(() =>+ expect(mocks.playSpeechText).toHaveBeenCalledWith('The first sentence is ready.', {+ source: 'voice-conversation'+ })+ )+ expect(mocks.handle.start).toHaveBeenCalledTimes(1)++ finishResponse()++ await waitFor(() =>+ expect(mocks.playSpeechText).toHaveBeenCalledWith('The second sentence is ready.', {+ source: 'voice-conversation'+ })+ )+ await waitFor(() => expect(mocks.handle.start).toHaveBeenCalledTimes(2))+ expect(hook.result.current.status).toBe('listening')+ })++ it('does not play the next fallback sentence or re-arm after Stop', async () => {+ mocks.useFallbackSpeech()+ mocks.deferFallbackPlayback()+ const { finishResponse, hook } = renderIncrementalFallbackConversation()++ await beginReply(hook)+ await waitFor(() => expect(mocks.playSpeechText).toHaveBeenCalledTimes(1))+ finishResponse()++ mocks.stopVoicePlayback()+ await act(async () => {+ mocks.finishFallbackPlayback()+ })++ await waitFor(() => expect(hook.result.current.status).toBe('idle'))+ expect(mocks.playSpeechText).toHaveBeenCalledTimes(1)+ expect(mocks.handle.start).toHaveBeenCalledTimes(1)+ })++ it('honors Stop while waiting for the next fallback sentence', async () => {+ mocks.useFallbackSpeech()+ const { finishResponse, hook } = renderIncrementalFallbackConversation()++ await beginReply(hook)+ await waitFor(() => expect(mocks.playSpeechText).toHaveBeenCalledTimes(1))++ mocks.stopVoicePlayback()+ await waitFor(() => expect(hook.result.current.status).toBe('idle'))+ finishResponse()++ expect(mocks.playSpeechText).toHaveBeenCalledTimes(1)+ expect(mocks.handle.start).toHaveBeenCalledTimes(1)+ })})diff --git a/apps/desktop/src/app/chat/composer/hooks/use-voice-conversation.ts b/apps/desktop/src/app/chat/composer/hooks/use-voice-conversation.tsindex 3ce46e438a1..cec90c14aea 100644--- a/apps/desktop/src/app/chat/composer/hooks/use-voice-conversation.ts+++ b/apps/desktop/src/app/chat/composer/hooks/use-voice-conversation.ts@@ -1,6 +1,7 @@import { useCallback, useEffect, useRef, useState } from 'react'import { useI18n } from '@/i18n'+import { IncrementalSpeechSentenceBuffer } from '@/lib/speech-text'import { startThinkingSound, stopThinkingSound } from '@/lib/thinking-sound'import { monitorSpeechDuringPlayback } from '@/lib/voice-barge-in'import {@@ -449,48 +450,123 @@ export function useVoiceConversation({[pendingResponse])- /** Whole-text fallback: wait for the reply to complete, then speak it. */+ /** Non-streaming providers still speak completed sentences during generation. */const awaitFallbackSpeech = useCallback((responseId: string) => {- const poll = () => {- if (responseIdRef.current !== responseId) {+ const sentenceBuffer = new IncrementalSpeechSentenceBuffer()+ const speechQueue: string[] = []+ let sourceLength = 0+ let responseFinished = false+ let playing = false+ let settled = false+ let pollTimer: number | null = null+ let ownedSequence = $voicePlayback.get().sequence++ const finishFallback = (barged: boolean, stopped = false) => {+ if (settled) {return}- const response = pendingResponse()+ settled = true- if (!response || response.id !== responseId) {- settleAfterSpeech(false)+ if (pollTimer !== null) {+ window.clearTimeout(pollTimer)+ }++ awaitingSpokenResponseRef.current = false+ settleAfterSpeech(barged, stopped)+ }+ const playNext = () => {+ if (settled || playing || responseIdRef.current !== responseId) {return}- if (response.pending || busyRef.current) {- window.setTimeout(poll, 250)+ if ($voicePlayback.get().sequence > ownedSequence) {+ finishFallback(false, true)++ return+ }++ const sentence = speechQueue.shift()++ if (!sentence) {+ if (responseFinished) {+ finishFallback(bargedRef.current)+ }return}- // The full-duplex monitor is normally already live (armed at submit);- // this is a safety net for read-aloud-style entries into the loop.ensureBargeMonitor()+ playing = true- const playback = playSpeechText(response.text, { ...ownerRef.current, source: 'voice-conversation' })- // playSpeechText performs its normal cleanup synchronously before- // returning. Capture the sequence after that internal increment so- // only a later, external stop suppresses the next listen cycle.- speechStartSequenceRef.current = $voicePlayback.get().sequence+ const playback = playSpeechText(sentence, { ...ownerRef.current, source: 'voice-conversation' })+ const sentenceStartSequence = $voicePlayback.get().sequence+ ownedSequence = sentenceStartSequence+ speechStartSequenceRef.current = sentenceStartSequence+ let playbackFailed = falsevoid playback- .catch(error => notifyError(error, voiceCopy.playbackFailed))+ .catch(error => {+ playbackFailed = true+ notifyError(error, voiceCopy.playbackFailed)+ }).finally(() => {- if (responseIdRef.current === responseId) {- awaitingSpokenResponseRef.current = false- settleAfterSpeech(bargedRef.current)+ if (settled || responseIdRef.current !== responseId) {+ return+ }++ playing = false++ if (playbackFailed) {+ finishFallback(bargedRef.current)++ return+ }++ const stopped = $voicePlayback.get().sequence > sentenceStartSequence++ if (bargedRef.current || stopped) {+ finishFallback(bargedRef.current, stopped && !bargedRef.current)++ return}++ playNext()})}+ const poll = () => {+ if (settled || responseIdRef.current !== responseId) {+ return+ }++ const response = pendingResponse()++ if (!response || response.id !== responseId) {+ finishFallback(false)++ return+ }++ if (response.text.length > sourceLength) {+ speechQueue.push(...sentenceBuffer.append(response.text.slice(sourceLength)))+ sourceLength = response.text.length+ }++ if (!response.pending && !busyRef.current && !responseFinished) {+ responseFinished = true+ speechQueue.push(...sentenceBuffer.flush())+ }++ playNext()++ if (!responseFinished) {+ pollTimer = window.setTimeout(poll, 150)+ }+ }+poll()},[ensureBargeMonitor, pendingResponse, settleAfterSpeech, voiceCopy.playbackFailed]@@ -503,6 +579,10 @@ export function useVoiceConversation({*/const openLiveSpeech = useCallback((responseId: string) => {+ if (responseIdRef.current === responseId) {+ return+ }+const sequenceBeforeStart = $voicePlayback.get().sequenceresponseIdRef.current = responseIddiff --git a/apps/desktop/src/lib/speech-text.test.ts b/apps/desktop/src/lib/speech-text.test.tsindex b22d7c28d42..c545f9c2532 100644--- a/apps/desktop/src/lib/speech-text.test.ts+++ b/apps/desktop/src/lib/speech-text.test.ts@@ -1,6 +1,6 @@import { describe, expect, it } from 'vitest'-import { sanitizeTextForSpeech } from './speech-text'+import { IncrementalSpeechSentenceBuffer, sanitizeTextForSpeech } from './speech-text'describe('sanitizeTextForSpeech', () => {it('does not speak placeholders for fenced code blocks', () => {@@ -225,3 +225,26 @@ After the table.`expect(sanitizeTextForSpeech(text)).toContain('Item | Value')})})++describe('IncrementalSpeechSentenceBuffer', () => {+ it('emits completed sentences while retaining the unfinished tail', () => {+ const buffer = new IncrementalSpeechSentenceBuffer()++ expect(buffer.append('The first sentence is ready. The second')).toEqual(['The first sentence is ready.'])+ expect(buffer.append(' sentence is ready too. ')).toEqual(['The second sentence is ready too.'])+ expect(buffer.flush()).toEqual([])+ })++ it('keeps short fragments with the following sentence', () => {+ const buffer = new IncrementalSpeechSentenceBuffer()++ expect(buffer.append('Hi! This longer sentence is ready. ')).toEqual(['Hi! This longer sentence is ready.'])+ })++ it('does not emit a reasoning block split across deltas', () => {+ const buffer = new IncrementalSpeechSentenceBuffer()++ expect(buffer.append('<think>Private reason.')).toEqual([])+ expect(buffer.append('</think> The public answer is ready. ')).toEqual(['The public answer is ready.'])+ })+})diff --git a/apps/desktop/src/lib/speech-text.ts b/apps/desktop/src/lib/speech-text.tsindex 70da4681296..79e6452201d 100644--- a/apps/desktop/src/lib/speech-text.ts+++ b/apps/desktop/src/lib/speech-text.ts@@ -17,6 +17,8 @@ const THINKING_PREFIX_RE =/^\s*(?:\([^)\n]{1,48}\)\s*)?(?:processing|thinking|reasoning|analyzing|pondering|contemplating|musing|cogitating|ruminating|deliberating|mulling|reflecting|computing|synthesizing|formulating|brainstorming)\.\.\.\s*/iconst URL_RE = /\bhttps?:\/\/\S+/gi+const CLOSED_THINK_BLOCK_RE = /<think[\s>][\s\S]*?<\/think>/g+const SENTENCE_BOUNDARY_RE = /(?<=[.!?])(?:\s|\n)|(?:\n\n)/const MARKDOWN_TABLE_DELIMITER_CELL_RE = /^:?-{3,}:?$/@@ -181,6 +183,53 @@ function normalizeLineBreaks(text: string): string {.replace(SOFT_BREAK_RE, ' ')}+export class IncrementalSpeechSentenceBuffer {+ private buffer = ''++ constructor(private readonly minLength = 20) {}++ append(delta: string): string[] {+ this.buffer = (this.buffer + delta).replace(CLOSED_THINK_BLOCK_RE, '')++ if (this.buffer.includes('<think') && !this.buffer.includes('</think>')) {+ return []+ }++ const sentences: string[] = []+ let searchStart = 0++ while (true) {+ const match = SENTENCE_BOUNDARY_RE.exec(this.buffer.slice(searchStart))++ if (!match || match.index === undefined) {+ break+ }++ const end = searchStart + match.index + match[0].length+ const head = this.buffer.slice(0, end).trim()++ if (head.length < this.minLength) {+ searchStart = end++ continue+ }++ sentences.push(head)+ this.buffer = this.buffer.slice(end)+ searchStart = 0+ }++ return sentences+ }++ flush(): string[] {+ const tail = this.buffer.replace(CLOSED_THINK_BLOCK_RE, '').trim()+ this.buffer = ''++ return tail ? [tail] : []+ }+}+export function sanitizeTextForSpeech(text: string): string {// Tables first: their right-align marker is a trailing colon (":-"), and// closing colons before the table detector runs would mangle it.