The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(tts): silence identifier-dense tokens in both speech normalizers
Brooklyn Nicholson9b761903b94b
diff --git a/apps/desktop/src/lib/speech-text.identifier-corpus.test.ts b/apps/desktop/src/lib/speech-text.identifier-corpus.test.tsnew file mode 100644index 00000000000..63d566811d9--- /dev/null+++ b/apps/desktop/src/lib/speech-text.identifier-corpus.test.ts@@ -0,0 +1,60 @@+import { readFileSync } from 'node:fs'+import { resolve } from 'node:path'++import { describe, expect, it } from 'vitest'++import { sanitizeTextForSpeech } from './speech-text'++// The shared corpus both speech normalizers must agree on (#119207): the+// identical file is loaded by tests/tools/test_tts_identifier_speech.py, so+// the desktop (speech-text.ts) and gateway/CLI (tts_text_normalize.py)+// halves stay in lockstep. Policy: identifier-dense tokens are silence,+// never hardcoded English placeholder words (#86602); ordinary prose,+// emails, dates and ratios pass verbatim.+const corpusPath = resolve(__dirname, '../../../../tests/fixtures/identifier_speech_corpus.json')+const corpus = JSON.parse(readFileSync(corpusPath, 'utf8')) as {+ identifier_tokens: [string, string[], string[]][]+ pass_through_tokens: [string, string[], string[]][]+}++describe('sanitizeTextForSpeech identifier-dense tokens (#119207)', () => {+ it('silences identifier tokens while the prose around them survives', () => {+ for (const [text, mustNotContain, mustContain] of corpus.identifier_tokens) {+ const spoken = sanitizeTextForSpeech(text)+ for (const needle of mustNotContain) {+ expect(spoken, `${needle} leaked from ${text}`).not.toContain(needle)+ }+ for (const needle of mustContain) {+ expect(spoken, `${needle} lost from ${text}`).toContain(needle)+ }+ }+ })++ it('passes ordinary speech through untouched', () => {+ for (const [text, , mustContain] of corpus.pass_through_tokens) {+ const spoken = sanitizeTextForSpeech(text)+ for (const needle of mustContain) {+ expect(spoken, `${needle} lost from ${text}`).toContain(needle)+ }+ }+ })++ it('reads the issue repro: filenames never spell out character by character', () => {+ const spoken = sanitizeTextForSpeech(+ 'Saved peyton-sample-20260922.wav and peyton-sample-20260922.ogg.'+ )+ expect(spoken).not.toContain('.wav')+ expect(spoken).not.toContain('.ogg')+ expect(spoken).not.toContain('peyton')+ expect(spoken).toContain('Saved')+ })++ it('keeps code fences, links and MEDIA: tokens working alongside the new pass', () => {+ expect(sanitizeTextForSpeech('Here is code:\n```ts\nconst x = 1\n```\nDone.')).toBe(+ 'Here is code. Done.'+ )+ expect(sanitizeTextForSpeech('Use `git status` after the change.')).toBe(+ 'Use git status after the change.'+ )+ })+})diff --git a/apps/desktop/src/lib/speech-text.ts b/apps/desktop/src/lib/speech-text.tsindex 8504586f399..0c1cfde4b10 100644--- a/apps/desktop/src/lib/speech-text.ts+++ b/apps/desktop/src/lib/speech-text.ts@@ -18,6 +18,58 @@ const THINKING_PREFIX_RE =const URL_RE = /\bhttps?:\/\/\S+/gi+// --- Identifier-dense tokens (#119207) --------------------------------------+// Filenames with extensions, hashes, UUIDs, dense model/version IDs and paths+// are read character-by-character ("peyton-sample-20260922.wav" becomes+// "peyton dash sample dash two zero two six..."), making clean audio sound+// corrupted. They become silence, never a hardcoded English placeholder word+// (#86602: the reply may be in any language). Mirrored token-for-token by+// tools/tts_text_normalize.py (`prune_identifier_tokens_for_tts`) — keep both+// in lockstep and extend the shared corpus+// (tests/fixtures/identifier_speech_corpus.json) first.+const FILENAME_EXT_RE =+ /[\w.-]{0,60}\.(?:wav|ogg|mp3|flac|m4a|aac|py|pyc|ts|tsx|js|jsx|mjs|cjs|json|yaml|yml|toml|md|mdx|txt|csv|xlsx|xls|pdf|png|jpg|jpeg|gif|webp|svg|log|sql|sh|bash|zsh|rs|go|java|rb|php|html|css|lock|tar|gz|zip|db|sqlite|sqlite3|onnx|pt|bin|env|ini|conf|cfg|xml)\b/i+const UUID_RE = /[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}/+const HASH_PREFIX_HEX_RE = /\b(?:sha(?:-?256|-?512|-?1|3)?|blake2[ab]?|md5|crc32?)[:\s]+[0-9a-fA-F]{7,64}/gi+const HEX_RUN_RE = /[0-9a-fA-F]{7,64}/+const IDENTIFIER_TOKEN_RE = /[A-Za-z0-9_./~@-]+/g+const DATE_TOKEN_RE = /^\d{4}[-/]\d{1,2}(?:[-/]\d{1,2})?$/++function isDenseIdentifier(token: string): boolean {+ if (token.includes('@') || DATE_TOKEN_RE.test(token)) {+ return false // email addresses, dates ("2026-09-28", "2026/06/02")+ }+ if (/^(?:~\/|\.\.?\/|\/)/.test(token)) {+ return true // filesystem paths+ }+ if (token.includes('/') && (FILENAME_EXT_RE.test(token) || /\d/.test(token))) {+ return true // paths and dense model IDs ("meta-llama/Llama-3.3-70B-Instruct")+ }+ if (FILENAME_EXT_RE.test(token) || UUID_RE.test(token)) {+ return true+ }+ // Hex-hash runs ("73688014f78", "e3b0c442...") — digit-free runs+ // ("defaced") are legitimate words and stay.+ if (HEX_RUN_RE.test(token) && /\d/.test(token)) {+ return true+ }+ if (!/\d/.test(token)) {+ return false+ }+ const seps = ['_', '.', '/'].filter(char => token.includes(char)).length+ const hyphens = (token.match(/-/g) ?? []).length+ if (seps >= 2 || hyphens >= 2) {+ return true // v2.1.0-beta.3, Llama-3.3-70B, dated filename slugs+ }+ return token.includes('/') || (hyphens >= 1 && seps >= 1)+}++function pruneIdentifierTokens(text: string): string {+ return text+ .replace(HASH_PREFIX_HEX_RE, ' ')+ .replace(IDENTIFIER_TOKEN_RE, token => (isDenseIdentifier(token) ? ' ' : token))+}+const MARKDOWN_TABLE_DELIMITER_CELL_RE = /^:?-{3,}:?$/interface MarkdownTableRow {@@ -269,14 +321,20 @@ export function sanitizeTextForSpeech(text: string): string {// Unspeakable tokens are silence, never a placeholder word: an English// "code block omitted" / "link" is wrong for every non-English voice.- return normalizeLineBreaks(pre)+ // Identifier-dense tokens (filenames, hashes, model IDs, paths — #119207)+ // run AFTER code fences/inline code/links are consumed so their contents+ // are not double-processed, and AFTER URLs/MEDIA: tokens, which own+ // themselves.+ const withoutIdentifiers = pruneIdentifierTokens(normalizeLineBreaks(pre).replace(FENCED_CODE_RE, '').replace(THINKING_PREFIX_RE, ' ').replace(MARKDOWN_LINK_RE, '$1').replace(INLINE_CODE_RE, '$1').replace(URL_RE, '').replace(MEDIA_PATH_RE, '')- .replace(EMOJI_RE, ' ')+ .replace(EMOJI_RE, ' '))++ return withoutIdentifiers.replace(/^#{1,6}\s+/gm, '').replace(/[*_~>#]/g, '').replace(/^\s*[-+*]\s+/gm, '')diff --git a/tests/fixtures/identifier_speech_corpus.json b/tests/fixtures/identifier_speech_corpus.jsonnew file mode 100644index 00000000000..78758f04901--- /dev/null+++ b/tests/fixtures/identifier_speech_corpus.json@@ -0,0 +1,20 @@+{+ "description": "Identifier-dense tokens both speech normalizers must agree on (#119207). Unspeakable machine tokens become silence — never hardcoded English placeholder words (#86602). identifier_tokens: [text, mustNotContain[], mustContain[]] — prose around a replaced token must survive. pass_through_tokens: [text, mustContain[]] — ordinary speech must pass verbatim.",+ "identifier_tokens": [+ ["Saved peyton-sample-20260922.wav and peyton-sample-20260922.ogg.", ["peyton", "20260922", ".wav", ".ogg"], ["Saved", "and"]],+ ["The digest is sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 for the file.", ["e3b0c442", "7852b855", "sha256:"], ["The digest is", "for the file"]],+ ["Commit 73688014f78 landed.", ["73688014f78"], ["Commit", "landed"]],+ ["Trace id 550e8400-e29b-41d4-a716-446655440000 appears once.", ["550e8400", "446655440000"], ["Trace id", "appears once"]],+ ["Model meta-llama/Llama-3.3-70B-Instruct is large.", ["meta-llama/Llama-3.3-70B-Instruct", "70B"], ["Model", "is large"]],+ ["Config at ~/.config/hermes/config.yaml was read.", ["config.yaml", "~/.config"], ["Config at", "was read"]],+ ["Version v2.1.0-beta.3 shipped.", ["v2.1.0-beta.3"], ["Version", "shipped"]]+ ],+ "pass_through_tokens": [+ ["The samples played cleanly, so listen again.", [], ["The samples played cleanly, so listen again"]],+ ["Use git status after the change.", [], ["Use git status after the change"]],+ ["Email me at [email protected].", [], ["[email protected]"]],+ ["COVID-19 and well-known facts stay.", [], ["COVID-19", "well-known"]],+ ["Due 2026/06/02 and status N/A here.", [], ["2026/06/02", "N/A"]],+ ["The final score was 3:2.", [], ["3:2"]]+ ]+}diff --git a/tests/tools/test_tts_identifier_speech.py b/tests/tools/test_tts_identifier_speech.pynew file mode 100644index 00000000000..12d34db30ab--- /dev/null+++ b/tests/tools/test_tts_identifier_speech.py@@ -0,0 +1,69 @@+"""Identifier-to-speech normalization (#119207).++Both speech normalizers — tools/tts_text_normalize.py (gateway/CLI/TTS tool)+and apps/desktop/src/lib/speech-text.ts (Desktop read-aloud / auto-speak) —+must apply the same policy to identifier-dense tokens (filenames with+extensions, hashes, UUIDs, dense model/version IDs, paths): silence, never+hardcoded English placeholder words (#86602 — the reply may be in any+language). This suite pins the Python half against the shared corpus+(tests/fixtures/identifier_speech_corpus.json); the vitest suite in+apps/desktop runs the identical corpus, so the two implementations stay in+lockstep.+"""++import json+from pathlib import Path++from tools.tts_text_normalize import prepare_spoken_text++_CORPUS = Path(__file__).resolve().parent.parent / "fixtures" / "identifier_speech_corpus.json"+++def _cases() -> dict:+ return json.loads(_CORPUS.read_text())+++def test_identifier_tokens_become_silence_prose_survives():+ for text, must_not_contain, must_contain in _cases()["identifier_tokens"]:+ spoken = prepare_spoken_text(text)+ for needle in must_not_contain:+ assert needle not in spoken, f"{needle!r} leaked from {text!r} into {spoken!r}"+ for needle in must_contain:+ assert needle in spoken, f"{needle!r} lost from {text!r} -> {spoken!r}"+++def test_ordinary_speech_passes_through():+ for text, _unused, must_contain in _cases()["pass_through_tokens"]:+ spoken = prepare_spoken_text(text)+ for needle in must_contain:+ assert needle in spoken, f"{needle!r} lost from {text!r} -> {spoken!r}"+++def test_issue_repro_filenames_are_not_spoken():+ spoken = prepare_spoken_text(+ "Saved peyton-sample-20260922.wav and peyton-sample-20260922.ogg.")+ assert ".wav" not in spoken+ assert ".ogg" not in spoken+ assert "peyton" not in spoken+ assert "Saved" in spoken+++def test_hash_and_uuid_summaries_do_not_spell_out():+ spoken = prepare_spoken_text(+ "Commit 73688014f78 with trace 550e8400-e29b-41d4-a716-446655440000.")+ assert "73688014f78" not in spoken+ assert "550e8400" not in spoken+ assert "Commit" in spoken and "trace" in spoken+++def test_plain_words_with_hyphens_and_digits_stay_spoken():+ spoken = prepare_spoken_text("COVID-19 numbers and the well-known 7 habit stay.")+ assert "COVID-19" in spoken+ assert "well-known" in spoken+ assert "7" in spoken+++def test_dates_and_ratios_are_not_identifiers():+ spoken = prepare_spoken_text("Due 2026/06/02; the score was 3:2.")+ assert "2026/06/02" in spoken+ assert "3:2" in spokendiff --git a/tools/tts_text_normalize.py b/tools/tts_text_normalize.pyindex 978c08df791..511e7bd877b 100644--- a/tools/tts_text_normalize.py+++ b/tools/tts_text_normalize.py@@ -129,6 +129,63 @@ def normalize_symbols_for_tts(text: str) -> str:return _EMOJI_RE.sub("", _VARIATION_SELECTOR_RE.sub("", text))+# --- Identifier-dense tokens (#119207) ---------------------------------------+# Filenames with extensions, hashes, UUIDs, dense model/version IDs and paths+# are read character-by-character ("peyton-sample-20260922.wav" becomes+# "peyton dash sample dash two zero two six..."), making clean synthesized+# audio sound corrupted. They become silence, never a hardcoded English+# placeholder word (#86602: the reply may be in any language). Ordinary+# prose, dates, ratios and short hyphenated words (COVID-19, well-known)+# pass through untouched. Mirrored token-for-token by+# apps/desktop/src/lib/speech-text.ts — keep both in lockstep and extend the+# shared corpus (tests/fixtures/identifier_speech_corpus.json) first.++_FILENAME_EXT_RE = re.compile(+ r"[\w.-]{0,60}\.(?:wav|ogg|mp3|flac|m4a|aac|py|pyc|ts|tsx|js|jsx|mjs|cjs|json|yaml|yml|toml|"+ r"md|mdx|txt|csv|xlsx|xls|pdf|png|jpg|jpeg|gif|webp|svg|log|sql|sh|bash|zsh|rs|go|java|rb|php|"+ r"html|css|lock|tar|gz|zip|db|sqlite|sqlite3|onnx|pt|bin|env|ini|conf|cfg|xml)\b",+ re.IGNORECASE)+_UUID_RE = re.compile(r"[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}")+_HASH_PREFIX_HEX_RE = re.compile(+ r"\b(?:sha(?:-?256|-?512|-?1|3)?|blake2[ab]?|md5|crc32?)[:\s]+[0-9a-fA-F]{7,64}", re.IGNORECASE)+_HEX_RUN_RE = re.compile(r"(?<![0-9a-fA-F])[0-9a-fA-F]{7,64}(?![0-9a-fA-F])")+_IDENTIFIER_TOKEN_RE = re.compile(r"[A-Za-z0-9_./~@-]+")+_DATE_TOKEN_RE = re.compile(r"\d{4}[-/]\d{1,2}(?:[-/]\d{1,2})?")+++def _is_dense_identifier(token: str) -> bool:+ """True for a machine token a voice would spell out character by character."""+ if "@" in token or _DATE_TOKEN_RE.fullmatch(token):+ return False # email addresses, dates ("2026-09-28", "2026/06/02")+ if token.startswith(("~/", "./", "../", "/")):+ return True # filesystem paths+ if "/" in token and (_FILENAME_EXT_RE.search(token) or any(char.isdigit() for char in token)):+ return True # paths and dense model IDs ("meta-llama/Llama-3.3-70B-Instruct")+ if _FILENAME_EXT_RE.search(token) or _UUID_RE.search(token):+ return True+ # Hex-hash runs ("73688014f78", "e3b0c442...") — digit-free runs+ # ("defaced") are legitimate words and stay.+ if _HEX_RUN_RE.fullmatch(token) and re.search(r"\d", token):+ return True+ digits = any(char.isdigit() for char in token)+ if not digits:+ return False+ seps = sum(token.count(char) > 0 for char in "_./")+ hyphens = token.count("-")+ if seps >= 2 or hyphens >= 2:+ return True # v2.1.0-beta.3, Llama-3.3-70B, dated filename slugs+ return "/" in token or (hyphens >= 1 and seps >= 1)+++def prune_identifier_tokens_for_tts(text: str) -> str:+ """Silence identifier-dense tokens; keep ordinary prose verbatim."""+ if not text:+ return ""+ text = _HASH_PREFIX_HEX_RE.sub(" ", text)+ return _IDENTIFIER_TOKEN_RE.sub(+ lambda m: " " if _is_dense_identifier(m.group(0)) else m.group(0), text)++def smooth_whitespace_for_tts(text: str) -> str:"""Collapse visual formatting into calm spoken paragraphs. A _HEAD-marked heading folds intothe next content line as a lead-in ("Weather, It will be sunny."); a heading with no content@@ -172,7 +229,11 @@ def smooth_whitespace_for_tts(text: str) -> str:flush_pending()text = "\n".join(lines)for pattern, repl in ((r"\n{3,}", "\n\n"), (r"[ \t]{2,}", " "), (r"\s+([,.;:!?])", r"\1"),- (r"([,.;:!?])([A-Za-z])", r"\1 \2"), (r"\.{4,}", "...")):+ # A sentence mark only gains a space when NOT glued to+ # a word char on both sides — "[email protected]" is a+ # single token, not "example. com".+ (r"(?<![A-Za-z0-9])[,.;:!?](?=[A-Za-z])", r"\g<0> "),+ (r"\.{4,}", "...")):text = re.sub(pattern, repl, text)# Single-line text ("Here is the list:") skips the per-line pause pass, so close a# final colon here too -- never a digit-preceded one ("final score 3:2" is a ratio).@@ -221,10 +282,12 @@ def flatten_newlines_for_payload(text: str) -> str:def prepare_spoken_text(text: str, max_chars: int | None = 4000) -> str:"""Return a TTS-friendly script from assistant text (deterministic cleanup, not a rewrite).- Pipeline: non-spoken blocks > Markdown > symbols/units > line formatting into sentence- pauses > single line (for newline-sensitive providers), then ``max_chars``."""+ Pipeline: non-spoken blocks > Markdown > symbols/units > identifier-dense tokens >+ line formatting into sentence pauses > single line (for newline-sensitive providers),+ then ``max_chars``."""spoken = textfor step in (strip_nonspoken_blocks, strip_markdown_for_tts, normalize_symbols_for_tts,+ prune_identifier_tokens_for_tts,smooth_whitespace_for_tts, flatten_newlines_for_payload):spoken = step(spoken)if max_chars is not None and max_chars > 0 and len(spoken) > max_chars: