Skip to content

The all-in-one local AI studio for your desktop: chat, image and video generation and a coding agent in one free, open source app. Windows and Linux. No Docker, no terminal, no cloud required.

fix(tts): read-aloud cut Chinese and Japanese mid-word

David6d487e95c144
diff --git a/src/api/__tests__/tts-chunking.test.ts b/src/api/__tests__/tts-chunking.test.ts
new file mode 100644
index 00000000..ece29ebd
--- /dev/null
+++ b/src/api/__tests__/tts-chunking.test.ts
@@ -0,0 +1,87 @@
+/**
+ * chunkForTts — what read-aloud actually sends to the synthesizer.
+ *
+ * Each chunk becomes its OWN audio clip, played back to back, so a cut in the
+ * wrong place is audible: the listener hears half a word, a pause, then the
+ * other half. src/api/voice.ts had no tests at all.
+ *
+ * Measured against the version before this round: 200 Japanese sentences came
+ * out as ONE part (the splitter needed a space after 。, which CJK does not
+ * write) and the fallback cut landed inside a word.
+ */
+import { describe, it, expect } from 'vitest'
+import { chunkForTts } from '../voice'
+
+const MAX = 1400
+
+describe('sentence splitting works without spaces after the terminator', () => {
+ it('splits Japanese on 。 even though nothing follows it', () => {
+ const jp = 'これはテストです。'.repeat(200)
+ const chunks = chunkForTts(jp, MAX)
+
+ expect(chunks.length).toBeGreaterThan(1)
+ // Every chunk must end on a sentence boundary, never mid-word.
+ for (const c of chunks) {
+ expect(c.endsWith('。')).toBe(true)
+ }
+ expect(chunks.join('')).toBe(jp)
+ })
+
+ it('still splits Latin prose on the usual terminators', () => {
+ const en = 'This is a sentence. '.repeat(200)
+ const chunks = chunkForTts(en, MAX)
+ expect(chunks.length).toBeGreaterThan(1)
+ for (const c of chunks) expect(c.trim().endsWith('.')).toBe(true)
+ })
+
+ it('leaves short text in one piece and drops empty input', () => {
+ expect(chunkForTts('Kurz.', MAX)).toEqual(['Kurz.'])
+ expect(chunkForTts(' ', MAX)).toEqual([])
+ })
+})
+
+describe('the fallback cut for a run with no sentence end', () => {
+ it('does not cut a word in half when the text has spaces', () => {
+ const long = 'das ist ein sehr langer satz ohne satzzeichen '.repeat(60)
+ const chunks = chunkForTts(long, MAX)
+
+ expect(chunks.length).toBeGreaterThan(1)
+ for (const c of chunks) {
+ // A chunk that starts or ends mid-word is the audible defect.
+ expect(c.startsWith(' ')).toBe(false)
+ expect(c.endsWith(' ')).toBe(false)
+ }
+ // Rejoining with the spaces the split consumed gives the original back.
+ expect(chunks.join(' ').replace(/\s+/g, ' ')).toBe(long.trim().replace(/\s+/g, ' '))
+ })
+
+ it('never splits a surrogate pair', () => {
+ // Emoji sitting exactly on the boundary: a naive slice yields two lone
+ // surrogates, which are invalid in the JSON body the cloud TTS call sends.
+ const text = 'a'.repeat(MAX - 1) + '😀' + 'b'.repeat(50)
+ const chunks = chunkForTts(text, MAX)
+
+ for (const c of chunks) {
+ for (let i = 0; i < c.length; i++) {
+ const code = c.charCodeAt(i)
+ const isHigh = code >= 0xd800 && code <= 0xdbff
+ const isLow = code >= 0xdc00 && code <= 0xdfff
+ if (isHigh) {
+ const next = c.charCodeAt(i + 1)
+ expect(next >= 0xdc00 && next <= 0xdfff).toBe(true)
+ i++
+ } else {
+ expect(isLow).toBe(false)
+ }
+ }
+ }
+ expect(chunks.join('')).toContain('😀')
+ })
+
+ it('keeps every chunk within the limit', () => {
+ const long = 'これはテストです。'.repeat(400) + 'x'.repeat(3000)
+ for (const c of chunkForTts(long, MAX)) {
+ expect(c.length).toBeLessThanOrEqual(MAX)
+ }
+ })
+})
diff --git a/src/api/voice.ts b/src/api/voice.ts
index 08997e0a..de74c5b1 100644
--- a/src/api/voice.ts
+++ b/src/api/voice.ts
@@ -241,26 +241,60 @@ export async function transcribeAudioCloud(audioBlob: Blob): Promise<string> {
// boundaries (hard-splitting any single oversized run) so long messages read
// aloud instead of 400ing and silently degrading to the local/browser voice.
const TTS_MAX_CHARS = 1400;
+/** Last resort for a run with no sentence end in it: cut at `max`, but never
+ * through a surrogate pair (a split emoji becomes two lone surrogates, which
+ * is invalid in the JSON the cloud TTS request carries) and, where the text
+ * has spaces, never through a word. */
+function hardSlice(s: string, max: number): string[] {
+ const out: string[] = [];
+ let i = 0;
+ while (i < s.length) {
+ let end = Math.min(i + max, s.length);
+ if (end < s.length) {
+ const lead = s.charCodeAt(end - 1);
+ if (lead >= 0xd800 && lead <= 0xdbff) end -= 1; // keep the pair together
+ const ws = s.lastIndexOf(" ", end - 1);
+ // Only back off to a space if it does not shrink the chunk drastically —
+ // CJK has none, and a 60% floor keeps the clip count sane.
+ if (ws > i + max * 0.6) end = ws + 1;
+ }
+ const piece = s.slice(i, end).trim();
+ if (piece) out.push(piece);
+ i = end;
+ }
+ return out;
+}
+
export function chunkForTts(text: string, max = TTS_MAX_CHARS): string[] {
const clean = text.trim();
if (clean.length <= max) return clean ? [clean] : [];
- const parts = clean.split(/(?<=[.!?。!?\n])\s+/);
+ // Split AFTER a sentence terminator. This used to require whitespace to
+ // FOLLOW it (`\s+`), which never fires for CJK — Chinese and Japanese put no
+ // space after 。!?, so a long answer stayed a single part and fell into the
+ // blind slicer below: measured, 200 Japanese sentences came out as one part
+ // and the cut landed inside a word.
+ // Parts stay VERBATIM — the separator (a space in Latin prose, nothing in
+ // CJK) rides along at the head of the next part, so concatenating restores
+ // the original exactly. Joining with a space instead would insert one into
+ // Japanese where none belongs.
+ const parts = clean.split(/(?<=[.!?。!?\n])/).filter(Boolean);
const chunks: string[] = [];
let cur = "";
+ const flush = () => {
+ const t = cur.trim();
+ if (t) chunks.push(t);
+ cur = "";
+ };
for (const p of parts) {
if (p.length > max) {
- if (cur) { chunks.push(cur); cur = ""; }
- for (let i = 0; i < p.length; i += max) chunks.push(p.slice(i, i + max));
+ flush();
+ for (const piece of hardSlice(p, max)) chunks.push(piece);
continue;
}
- if ((cur ? cur.length + 1 + p.length : p.length) > max) {
- if (cur) chunks.push(cur);
- cur = p;
- } else {
- cur = cur ? `${cur} ${p}` : p;
- }
+ if (cur.length + p.length > max) flush();
+ cur += p;
}
- if (cur) chunks.push(cur);
+ flush();
return chunks;
}