The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(tts): keep file links and code-block placeholders out of speech
Ricardo Mendes25f7bac31827
diff --git a/apps/desktop/src/lib/speech-text.test.ts b/apps/desktop/src/lib/speech-text.test.tsindex 5af35ce4ce5..cc69efb9a8b 100644--- a/apps/desktop/src/lib/speech-text.test.ts+++ b/apps/desktop/src/lib/speech-text.test.ts@@ -3,9 +3,12 @@ import { describe, expect, it } from 'vitest'import { sanitizeTextForSpeech } from './speech-text'describe('sanitizeTextForSpeech', () => {- it('summarizes fenced code blocks instead of reading them literally', () => {+ it('does not speak placeholders for fenced code blocks', () => {+ // The "code block omitted" summary used to be read aloud as English text+ // (#86602). Code that can't be spoken should be silence, not a sentence.+ // The "here is code:" colon also closes: the voice never waits on it.expect(sanitizeTextForSpeech('Here is code:\n```ts\nconst x = 1\n```\nDone.')).toBe(- 'Here is code: code block omitted Done.'+ 'Here is code. Done.')})@@ -42,6 +45,43 @@ Second sentence.`expect(sanitizeTextForSpeech(text)).toBe('First sentence. Second sentence.')})+ it('does not speak MEDIA file-link tokens', () => {+ // Rendering shows these as "Open inference-server-shopping-list.xlsx";+ // the hyphenated slug + odd extension made the voice loop ("eeeeee").+ const text = 'The files are below.\nMEDIA:/Users/ricardo/Documents/inference-server-shopping-list.xlsx\nBye.'++ expect(sanitizeTextForSpeech(text)).toBe('The files are below. Bye.')+ })++ it('does not speak a placeholder word for URLs', () => {+ // Used to say the English word "link" (#86602); URLs are silence now.+ expect(sanitizeTextForSpeech('See https://example.com/a-huge-page for details')).toBe(+ 'See for details'+ )+ })++ it('keeps ~~strike~~ readable instead of speaking tildes', () => {+ expect(sanitizeTextForSpeech('This ~~is~~ old.')).toBe('This is old.')+ })++ it('closes a colon orphaned when its file link is stripped', () => {+ // Inline form: "below: MEDIA:/path" on one line. The link is stripped+ // mid-line, orphaning the colon at the end of the text. It must close.+ expect(sanitizeTextForSpeech('The file is below: MEDIA:/tmp/x.py')).toBe('The file is below.')+ })++ it('closes a colon that a code block used to follow', () => {+ // The real repro: "one line added to the regex list:" then a code fence.+ // The voice hit the colon, found a wall of punctuation, and stuttered.+ expect(+ sanitizeTextForSpeech('One line added to the regex list:\n```ts\nconst x = 1\n```\nBye.')+ ).toBe('One line added to the regex list. Bye.')+ })++ it('closes a colon that ends the speakable text', () => {+ expect(sanitizeTextForSpeech('The regex list:')).toBe('The regex list.')+ })+it.each([['markdown emphasis', '**First sentence.**\n\nSecond sentence.', 'First sentence. Second sentence.'],['a closing quote', '“First sentence.”\n\nSecond sentence.', '“First sentence.” Second sentence.'],diff --git a/apps/desktop/src/lib/speech-text.ts b/apps/desktop/src/lib/speech-text.tsindex fa3e7a5ebf7..25ed2c51c56 100644--- a/apps/desktop/src/lib/speech-text.ts+++ b/apps/desktop/src/lib/speech-text.ts@@ -1,13 +1,15 @@const EMOJI_RE = /(?:[\u{1F000}-\u{1FAFF}\u{2600}-\u{27BF}]|[\u{FE0F}\u{200D}]|[\u{E0020}-\u{E007F}])+/guconst FENCED_CODE_RE = /```[\s\S]*?(?:```|$)/g-const CODE_BLOCK_SUMMARY = ' code block omitted 'const INLINE_CODE_RE = /`([^`]+)`/gconst MARKDOWN_LINK_RE = /\[([^\]]+)\]\(([^)]+)\)/gconst PARAGRAPH_BREAK_RE = /[ \t]*\n{2,}[ \t]*/gconst PUNCTUATED_PARAGRAPH_BREAK_RE = /([.!?])([*_~`>"'’”)}\]]*)[ \t]*\n{2,}[ \t]*/gconst SOFT_BREAK_RE = /[ \t]*\n[ \t]*/g+const MEDIA_PATH_RE = /MEDIA:\S+/g+const LINE_FINAL_COLON_RE = /:\s*$/gm+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*/i@@ -152,16 +154,27 @@ function normalizeLineBreaks(text: string): string {}export function sanitizeTextForSpeech(text: string): string {- return normalizeLineBreaks(stripMarkdownTables(text))- .replace(FENCED_CODE_RE, CODE_BLOCK_SUMMARY)+ // Tables first: their right-align marker is a trailing colon (":-"), and+ // closing colons before the table detector runs would mangle it.+ const withoutTables = stripMarkdownTables(String(text))++ // Close line-final colons BEFORE newlines are flattened: "the regex list:"+ // followed by a code block keeps its colon if this runs after the flatten,+ // and the voice hangs on it. Closing early turns it into "the regex list.".+ const pre = withoutTables.replace(LINE_FINAL_COLON_RE, '.')++ return normalizeLineBreaks(pre)+ .replace(FENCED_CODE_RE, '').replace(THINKING_PREFIX_RE, ' ').replace(MARKDOWN_LINK_RE, '$1').replace(INLINE_CODE_RE, '$1')- .replace(URL_RE, ' link ')+ .replace(URL_RE, '')+ .replace(MEDIA_PATH_RE, '').replace(EMOJI_RE, ' ').replace(/^#{1,6}\s+/gm, '').replace(/[*_~>#]/g, '').replace(/^\s*[-+*]\s+/gm, '')+ .replace(/:\s*$/, '.') // colon orphaned when its link/code was stripped.replace(/\s+/g, ' ').trim()}diff --git a/tests/tools/test_tts_text_normalize.py b/tests/tools/test_tts_text_normalize.pyindex 7e439cfff81..13fd0575483 100644--- a/tests/tools/test_tts_text_normalize.py+++ b/tests/tools/test_tts_text_normalize.py@@ -47,3 +47,31 @@ def test_prepare_spoken_text_polish_edge_cases():assert "and/or" in prepare_spoken_text("choose and/or option")assert "N/A" in prepare_spoken_text("status N/A here")assert "2026/06/02" in prepare_spoken_text("due 2026/06/02 ok")+++def test_prepare_spoken_text_strips_media_file_links():+ # "Open inference-server-shopping-list.xlsx" style tokens must never reach+ # the voice: hyphenated slugs + odd extensions make TTS loop ("eeeeee").+ raw = "The files are below.\nMEDIA:/Users/ricardo.mendes/Documents/inference-server-shopping-list.xlsx\nBye."+ spoken = prepare_spoken_text(raw)+ assert "MEDIA" not in spoken+ assert "shopping-list" not in spoken+ assert "xlsx" not in spoken+ assert "below" in spoken+ assert "Bye" in spoken+++def test_prepare_spoken_text_closes_trailing_colons():+ # "the regex list:" + a now-removed raw token would leave the voice hanging+ # on an open colon-pause (the "aaaa" stutter). Close it with a period.+ spoken = prepare_spoken_text("Here is the list:\nMEDIA:/tmp/x.py\nMore text")+ assert "list:" not in spoken+ assert "list." in spoken+++def test_prepare_spoken_text_closes_colon_on_single_line():+ # Multi-line text gets colons closed per line; single-line text reaches the+ # end-of-text rule instead.+ assert prepare_spoken_text("Here is the list:") == "Here is the list."+ # ...but a digit-preceded colon is a ratio and must stay intact.+ assert prepare_spoken_text("Final score 3:2") == "Final score 3:2"diff --git a/tools/tts_text_normalize.py b/tools/tts_text_normalize.pyindex 6aa5ca53741..a520563366c 100644--- a/tools/tts_text_normalize.py+++ b/tools/tts_text_normalize.py@@ -30,6 +30,10 @@ _MD_LIST_ITEM_RE = re.compile(r"^\s*(?:[-*+]|\d+[.)])\s+", flags=re.MULTILINE)_MD_HR_RE = re.compile(r"^\s*[-*_]{3,}\s*$", flags=re.MULTILINE)_MD_TABLE_PIPE_RE = re.compile(r"\s*\|\s*")_URL_RE = re.compile(r"https?://\S+")+# Local file links ("MEDIA:/Users/me/file.xlsx") are click targets on screen, not+# speech: voices loop on the hyphenated slug ("eeeeee"). The token is silence; the+# assistant's prose already says "the files are below".+_MEDIA_PATH_RE = re.compile(r"MEDIA:\S+")_DEGREE_UNITS = (("C", "Celsius"), ("F", "Fahrenheit"))# Unit suffix (regex, after a digit) -> spoken word; km/h variants before the bare "m".@@ -60,6 +64,7 @@ def strip_markdown_for_tts(text: str) -> str:text = _MD_IMAGE_RE.sub(lambda m: f" {m.group(1)} " if m.group(1) else " ", text)text = _MD_LINK_RE.sub(r"\1", text)text = _URL_RE.sub("", text)+ text = _MEDIA_PATH_RE.sub(" ", text)text = _MD_INLINE_CODE_RE.sub(r"\1", text)text = _MD_BOLD_RE.sub(r"\1", text)text = _MD_UNDERSCORE_BOLD_RE.sub(r"\1", text)@@ -154,14 +159,23 @@ def smooth_whitespace_for_tts(text: str) -> str:if pending_heading is not None:line = f"{pending_heading.rstrip('.:;,')}, {line}"pending_heading = None- if add_sentence_pauses and line[-1] not in ".!?;:":- line += "."+ if add_sentence_pauses:+ if line[-1] in ":;":+ # A trailing colon promises a continuation ("the list:"); the raw+ # token after it (file link, code fence) is already gone from+ # speech, so the voice would hang on the open pause. Close it.+ line = line.rstrip(":;").rstrip() + "."+ elif line[-1] not in ".!?":+ line += "."lines.append(line)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,}", "...")):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).+ text = re.sub(r"([^0-9])(?:[:;]\s*)+$", r"\1.", text)return text.strip()@@ -198,6 +212,9 @@ def flatten_newlines_for_payload(text: str) -> str:for pattern, repl in ((r"\n{2,}", ". "), (r"(?<=[.!?;:,])\n", " "), (r"\n", ". "), (r"\.\s*\.", "."),(r"[ \t]{2,}", " ")):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).+ text = re.sub(r"([^0-9])(?:[:;]\s*)+$", r"\1.", text)return text.strip()