Skip to content

The agent that grows with you

refactor(desktop): sentence-queue fallback reuses cutSentences()

kshitijk4poord2fec0ea9913
diff --git a/apps/desktop/src/lib/speech-text.test.ts b/apps/desktop/src/lib/speech-text.test.ts
index c545f9c2532..1478f4a5c37 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 { IncrementalSpeechSentenceBuffer, sanitizeTextForSpeech } from './speech-text'
+import { cutSentences, IncrementalSpeechSentenceBuffer, sanitizeTextForSpeech } from './speech-text'
describe('sanitizeTextForSpeech', () => {
it('does not speak placeholders for fenced code blocks', () => {
@@ -248,3 +248,48 @@ describe('IncrementalSpeechSentenceBuffer', () => {
expect(buffer.append('</think> The public answer is ready. ')).toEqual(['The public answer is ready.'])
})
})
+
+describe('cutSentences', () => {
+ it('emits complete sentences and holds the incomplete tail', () => {
+ const { sentences, rest } = cutSentences('This is the first full sentence. And then it keeps goi', false)
+
+ expect(sentences).toEqual(['This is the first full sentence.'])
+ expect(rest).toBe('And then it keeps goi')
+ })
+
+ it('buffers too-short fragments instead of firing per abbreviation', () => {
+ const { sentences, rest } = cutSentences('e.g. it continues', false)
+
+ expect(sentences).toEqual([])
+ expect(rest).toBe('e.g. it continues')
+ })
+
+ it('flush drains everything including the tail', () => {
+ const { sentences, rest } = cutSentences('First complete sentence right here. tail bit', true)
+
+ expect(sentences).toEqual(['First complete sentence right here.', 'tail bit'])
+ expect(rest).toBe('')
+ })
+
+ it('handles CJK terminators', () => {
+ const { sentences } = cutSentences(
+ '这是一个完整的中文句子,它的长度足够超过最小句子门槛,所以会被切分出来。 下一句',
+ true
+ )
+
+ expect(sentences[0]).toContain('。')
+ expect(sentences).toHaveLength(2)
+ })
+
+ it('cuts a short CJK opener alone when the backend sends tts.streaming.min_len', () => {
+ const text = '记得,叫团团。 然后我们再说第二句话,这一句要长一些才行。 '
+
+ // Historical 24-char floor (older backend, no key): the opener rides with sentence two.
+ expect(cutSentences(text, false).sentences).toEqual(['记得,叫团团。 然后我们再说第二句话,这一句要长一些才行。'])
+ // tts.streaming.min_len = 6 (the CJK voice setup from #96927): spoken on its own.
+ expect(cutSentences(text, false, 6).sentences).toEqual([
+ '记得,叫团团。',
+ '然后我们再说第二句话,这一句要长一些才行。'
+ ])
+ })
+})
diff --git a/apps/desktop/src/lib/speech-text.ts b/apps/desktop/src/lib/speech-text.ts
index 79e6452201d..d24cf79c2f0 100644
--- a/apps/desktop/src/lib/speech-text.ts
+++ b/apps/desktop/src/lib/speech-text.ts
@@ -18,7 +18,6 @@ const THINKING_PREFIX_RE =
const 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,}:?$/
@@ -183,50 +182,85 @@ function normalizeLineBreaks(text: string): string {
.replace(SOFT_BREAK_RE, ' ')
}
-export class IncrementalSpeechSentenceBuffer {
- private buffer = ''
+// ---------------------------------------------------------------------------
+// Sentence cutter for the streaming TTS session — mirrors the server-side
+// SentenceChunker's contract: emit complete sentences as they form, hold
+// the incomplete tail, flush everything on finish.
+// ---------------------------------------------------------------------------
+
+const SENTENCE_CUT_RE = /[.!?…。!?]+["'”’)\]]*\s+/g
+const MIN_SENTENCE_CHARS = 24
+
+export function cutSentences(
+ buffer: string,
+ flush: boolean,
+ minSentenceChars?: null | number
+): { sentences: string[]; rest: string } {
+ // tts.streaming.min_len when the backend sends it (a 5–7 char CJK opener is a
+ // whole clause); the historical 24 for older backends without the key.
+ const minChars = minSentenceChars ?? MIN_SENTENCE_CHARS
+ const sentences: string[] = []
+ let rest = buffer
+ let start = 0
+
+ SENTENCE_CUT_RE.lastIndex = 0
+
+ let match = SENTENCE_CUT_RE.exec(buffer)
+
+ while (match) {
+ const end = match.index + match[0].length
+ const candidate = buffer.slice(start, end).trim()
+
+ // Too-short fragments ("e.g. ", "1. ") stay buffered so we don't fire a
+ // provider call per abbreviation — unless a later boundary extends them.
+ if (candidate.length >= minChars) {
+ sentences.push(candidate)
+ start = end
+ }
- constructor(private readonly minLength = 20) {}
+ match = SENTENCE_CUT_RE.exec(buffer)
+ }
- append(delta: string): string[] {
- this.buffer = (this.buffer + delta).replace(CLOSED_THINK_BLOCK_RE, '')
+ rest = buffer.slice(start)
- if (this.buffer.includes('<think') && !this.buffer.includes('</think>')) {
- return []
- }
+ if (flush) {
+ const tail = rest.trim()
- const sentences: string[] = []
- let searchStart = 0
+ if (tail) {
+ sentences.push(tail)
+ }
- while (true) {
- const match = SENTENCE_BOUNDARY_RE.exec(this.buffer.slice(searchStart))
+ rest = ''
+ }
- if (!match || match.index === undefined) {
- break
- }
+ return { sentences, rest }
+}
- const end = searchStart + match.index + match[0].length
- const head = this.buffer.slice(0, end).trim()
+/** Incremental wrapper over cutSentences() that also hides <think> blocks
+ * split across deltas. Used by the sync (non-streaming provider) fallback. */
+export class IncrementalSpeechSentenceBuffer {
+ private buffer = ''
- if (head.length < this.minLength) {
- searchStart = end
+ constructor(private readonly minSentenceChars?: null | number) {}
- continue
- }
+ append(delta: string): string[] {
+ this.buffer = (this.buffer + delta).replace(CLOSED_THINK_BLOCK_RE, '')
- sentences.push(head)
- this.buffer = this.buffer.slice(end)
- searchStart = 0
+ if (this.buffer.includes('<think') && !this.buffer.includes('</think>')) {
+ return []
}
+ const { sentences, rest } = cutSentences(this.buffer, false, this.minSentenceChars)
+ this.buffer = rest
+
return sentences
}
flush(): string[] {
- const tail = this.buffer.replace(CLOSED_THINK_BLOCK_RE, '').trim()
+ const { sentences } = cutSentences(this.buffer.replace(CLOSED_THINK_BLOCK_RE, ''), true, this.minSentenceChars)
this.buffer = ''
- return tail ? [tail] : []
+ return sentences
}
}
diff --git a/apps/desktop/src/lib/voice-client-direct.test.ts b/apps/desktop/src/lib/voice-client-direct.test.ts
index d788ec11434..6b82532b21f 100644
--- a/apps/desktop/src/lib/voice-client-direct.test.ts
+++ b/apps/desktop/src/lib/voice-client-direct.test.ts
@@ -4,7 +4,6 @@ import { setApiRequestConnection, setApiRequestProfile } from '@/hermes'
import {
clearVoiceClientConfigCache,
- cutSentences,
type DirectTtsConfig,
fetchVoiceClientConfig,
synthesizeSpeechClientDirect,
@@ -367,48 +366,3 @@ describe('transcriptFromOpenAiMultipartBody', () => {
expect(transcriptFromOpenAiMultipartBody('{"error":"nope"}')).toBe('{"error":"nope"}')
})
})
-
-describe('cutSentences', () => {
- it('emits complete sentences and holds the incomplete tail', () => {
- const { sentences, rest } = cutSentences('This is the first full sentence. And then it keeps goi', false)
-
- expect(sentences).toEqual(['This is the first full sentence.'])
- expect(rest).toBe('And then it keeps goi')
- })
-
- it('buffers too-short fragments instead of firing per abbreviation', () => {
- const { sentences, rest } = cutSentences('e.g. it continues', false)
-
- expect(sentences).toEqual([])
- expect(rest).toBe('e.g. it continues')
- })
-
- it('flush drains everything including the tail', () => {
- const { sentences, rest } = cutSentences('First complete sentence right here. tail bit', true)
-
- expect(sentences).toEqual(['First complete sentence right here.', 'tail bit'])
- expect(rest).toBe('')
- })
-
- it('handles CJK terminators', () => {
- const { sentences } = cutSentences(
- '这是一个完整的中文句子,它的长度足够超过最小句子门槛,所以会被切分出来。 下一句',
- true
- )
-
- expect(sentences[0]).toContain('。')
- expect(sentences).toHaveLength(2)
- })
-
- it('cuts a short CJK opener alone when the backend sends tts.streaming.min_len', () => {
- const text = '记得,叫团团。 然后我们再说第二句话,这一句要长一些才行。 '
-
- // Historical 24-char floor (older backend, no key): the opener rides with sentence two.
- expect(cutSentences(text, false).sentences).toEqual(['记得,叫团团。 然后我们再说第二句话,这一句要长一些才行。'])
- // tts.streaming.min_len = 6 (the CJK voice setup from #96927): spoken on its own.
- expect(cutSentences(text, false, 6).sentences).toEqual([
- '记得,叫团团。',
- '然后我们再说第二句话,这一句要长一些才行。'
- ])
- })
-})
diff --git a/apps/desktop/src/lib/voice-client-direct.ts b/apps/desktop/src/lib/voice-client-direct.ts
index 40da2e8c786..62fed48cbdc 100644
--- a/apps/desktop/src/lib/voice-client-direct.ts
+++ b/apps/desktop/src/lib/voice-client-direct.ts
@@ -378,57 +378,3 @@ export async function synthesizeSpeechClientDirect(tts: DirectTtsConfig, text: s
throw new Error(`Unknown TTS wire: ${(tts as { wire?: string }).wire}`)
}
-
-// ---------------------------------------------------------------------------
-// Sentence cutter for the streaming TTS session — mirrors the server-side
-// SentenceChunker's contract: emit complete sentences as they form, hold
-// the incomplete tail, flush everything on finish.
-// ---------------------------------------------------------------------------
-
-const SENTENCE_BOUNDARY_RE = /[.!?…。!?]+["'”’)\]]*\s+/g
-const MIN_SENTENCE_CHARS = 24
-
-export function cutSentences(
- buffer: string,
- flush: boolean,
- minSentenceChars?: null | number
-): { sentences: string[]; rest: string } {
- // tts.streaming.min_len when the backend sends it (a 5–7 char CJK opener is a
- // whole clause); the historical 24 for older backends without the key.
- const minChars = minSentenceChars ?? MIN_SENTENCE_CHARS
- const sentences: string[] = []
- let rest = buffer
- let start = 0
-
- SENTENCE_BOUNDARY_RE.lastIndex = 0
-
- let match = SENTENCE_BOUNDARY_RE.exec(buffer)
-
- while (match) {
- const end = match.index + match[0].length
- const candidate = buffer.slice(start, end).trim()
-
- // Too-short fragments ("e.g. ", "1. ") stay buffered so we don't fire a
- // provider call per abbreviation — unless a later boundary extends them.
- if (candidate.length >= minChars) {
- sentences.push(candidate)
- start = end
- }
-
- match = SENTENCE_BOUNDARY_RE.exec(buffer)
- }
-
- rest = buffer.slice(start)
-
- if (flush) {
- const tail = rest.trim()
-
- if (tail) {
- sentences.push(tail)
- }
-
- rest = ''
- }
-
- return { sentences, rest }
-}
diff --git a/apps/desktop/src/lib/voice-playback.ts b/apps/desktop/src/lib/voice-playback.ts
index 44a2c90b4b7..c97b4525ec4 100644
--- a/apps/desktop/src/lib/voice-playback.ts
+++ b/apps/desktop/src/lib/voice-playback.ts
@@ -3,7 +3,6 @@ import { resolveGatewayWsUrl } from '@hermes/shared'
import type { OwnerScope } from '@/api/client'
import { getApiRequestConnection, getApiRequestProfile, speakText } from '@/hermes'
import {
- cutSentences,
directTtsConfig,
type DirectTtsConfig,
synthesizeSpeechClientDirect
@@ -16,7 +15,7 @@ import {
type VoicePlaybackState
} from '@/store/voice-playback'
-import { sanitizeTextForSpeech } from './speech-text'
+import { cutSentences, sanitizeTextForSpeech } from './speech-text'
// Free Edge TTS occasionally hands back audio that never fires `playing`/`ended`
// nor `error` — leaving voice mode stuck "speaking" forever. Reject if playback