The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): escape lone tildes and unknown html-like tokens in markdown prose
Albert.Zhou25381c17d820
diff --git a/apps/desktop/src/components/assistant-ui/markdown-text.prose-safety.test.tsx b/apps/desktop/src/components/assistant-ui/markdown-text.prose-safety.test.tsxnew file mode 100644index 00000000000..bcf4220e4d8--- /dev/null+++ b/apps/desktop/src/components/assistant-ui/markdown-text.prose-safety.test.tsx@@ -0,0 +1,80 @@+import { cleanup, render } from '@testing-library/react'+import { afterEach, describe, expect, it } from 'vitest'++import { MarkdownTextContent } from './markdown-text'++// Render-level regression for the prose-safety preprocessor fixes that landed+// on 2026-08-22 (upstream #50871 lone-tilde strikethrough, #53953 unknown+// html-like tokens swallowing the message tail). The preprocessor unit tests+// in markdown-text.test.ts assert on the transformed string; these mount the+// REAL production component and assert on the rendered DOM, so a wrapper that+// stopped applying the preprocess cannot pass here.+afterEach(cleanup)++describe('markdown prose renders tilde ranges and unknown tags literally', () => {+ it.each([+ [+ 'CJK range list',+ '分组:奇数 1~10,11~20,其余另列。',+ (text: string) => {+ expect(text).toContain('1~10,11~20')+ }+ ],+ [+ 'approximation prefixes in one paragraph',+ '收益为 3~5 倍,成本约 ~¥0.089。',+ (text: string) => {+ expect(text).toContain('3~5')+ expect(text).toContain('~¥0.089')+ }+ ]+ ])('renders %s without a strikethrough element', (_label, source, assertText) => {+ const { container } = render(<MarkdownTextContent isRunning={false} text={source} />)++ expect(container.querySelectorAll('del, s').length, `no strikethrough for: ${source}`).toBe(0)+ assertText(container.textContent || '')+ })++ it('renders unknown html-like tokens as literal text and keeps the tail visible', () => {+ const text =+ 'The proxy wraps calls in <tool_call> and results in <observation> blocks. ' ++ 'Keep the rest visible after the tag. The message tail must NOT vanish.'+ const { container } = render(<MarkdownTextContent isRunning={false} text={text} />)++ expect(container.textContent).toContain('<tool_call>')+ expect(container.textContent).toContain('<observation>')+ expect(container.textContent).toContain('The message tail must NOT vanish.')+ expect(container.querySelector('tool_call')).toBeNull()+ expect(container.querySelector('observation')).toBeNull()+ })++ it('leaves math comparisons untouched', () => {+ const { container } = render(+ <MarkdownTextContent isRunning={false} text={'如果 a < b 且 2<3 则原样保留。'} />+ )++ expect(container.textContent).toContain('a < b')+ expect(container.textContent).toContain('2<3')+ })++ it('renders autolinks for urls (tilde-in-url is a streamdown remend quirk, asserted loosely)', () => {+ const { container } = render(+ <MarkdownTextContent isRunning={false} text={'Docs at https://example.com/a_b/c~d/page'} />+ )++ const link = container.querySelector('a')++ expect(link).not.toBeNull()+ // Streamdown's tailBoundedRemend escapes `~` even inside autolinks+ // (pre-existing library behaviour, unchanged by this fix) — assert the link+ // itself mounted and points at the host, not byte-exact URL round-trip.+ expect(link?.getAttribute('href')).toContain('example.com')+ })++ it('still renders intentional ~~strikethrough~~', () => {+ const { container } = render(<MarkdownTextContent isRunning={false} text={'保留 ~~deleted~~ 删除线。'} />)++ expect(container.querySelectorAll('del, s').length).toBeGreaterThan(0)+ expect(container.textContent).toContain('deleted')+ })+})diff --git a/apps/desktop/src/components/assistant-ui/markdown-text.test.ts b/apps/desktop/src/components/assistant-ui/markdown-text.test.tsindex 9f08d5fbef0..3fda5aa94a2 100644--- a/apps/desktop/src/components/assistant-ui/markdown-text.test.ts+++ b/apps/desktop/src/components/assistant-ui/markdown-text.test.ts@@ -295,6 +295,58 @@ describe('preprocessMarkdown', () => {expect(output).toContain('<https://example.com/a_b/c~d/page>')})+ it('escapes lone tildes in CJK ranges without touching strikethrough syntax', () => {+ const output = preprocessMarkdown('Ranges: 1~10,11~20 and ~~deleted~~ text.')++ expect(output).toContain('1\\~10,11\\~20')+ expect(output).toContain('~~deleted~~')+ })++ it('escapes lone-tilde approximation prefixes so they cannot pair up mid-paragraph', () => {+ const output = preprocessMarkdown('收益为 3~5 倍,成本约 ~¥0.089。')++ expect(output).toContain('3\\~5 倍')+ expect(output).toContain('\\~¥0.089')+ })++ it('does not escape lone tildes inside inline or fenced code', () => {+ const input = ['Use `1~10` as a literal.', '', '```txt', '1~10,11~20', '```'].join('\n')++ const output = preprocessMarkdown(input)++ expect(output).toContain('`1~10`')+ expect(output).toContain(['```txt', '1~10,11~20', '```'].join('\n'))+ })++ it('escapes unknown html-like prose tokens before they reach the renderer', () => {+ const output = preprocessMarkdown(+ 'The proxy uses <tool_call> and <observation> blocks. Keep the rest of the sentence visible.'+ )++ expect(output).toContain(+ 'The proxy uses <tool_call> and <observation> blocks. Keep the rest of the sentence visible.'+ )+ expect(output).not.toContain('<tool_call>')+ expect(output).not.toContain('<observation>')+ })++ it('preserves known html tags and autolinks while escaping unknown tags', () => {+ const output = preprocessMarkdown(+ 'Use <strong>bold</strong> and visit https://example.com/page, then <span>ok</span> and <unk> text.'+ )++ expect(output).toContain('<strong>bold</strong>')+ expect(output).toContain('<https://example.com/page>')+ expect(output).toContain('<span>ok</span>')+ expect(output).toContain('<unk>')+ })++ it('leaves math comparisons like a < b and 2<3 untouched', () => {+ const output = preprocessMarkdown('If a < b and 2<3 then keep it as text.')++ expect(output).toContain('a < b and 2<3')+ })+it('handles a fenced block larger than V8 spread-argument limit', () => {// A single huge code block (e.g. a logged minified bundle) used to throw// `RangeError: Maximum call stack size exceeded` via `out.push(...lines)`.diff --git a/apps/desktop/src/lib/markdown-preprocess.ts b/apps/desktop/src/lib/markdown-preprocess.tsindex 4c48947335f..46fb7de3d17 100644--- a/apps/desktop/src/lib/markdown-preprocess.ts+++ b/apps/desktop/src/lib/markdown-preprocess.ts@@ -94,6 +94,27 @@ const MARKDOWN_LINK_SPLIT_RE = new RegExp(const LOCAL_PREVIEW_URL_RE = /(^|\s)https?:\/\/(?:localhost|127\.0\.0\.1|0\.0\.0\.0|\[::1\])(?::\d+)?\/?(?=\s|$)/giconst LOCAL_PREVIEW_ONLY_RE = /^https?:\/\/(?:localhost|127\.0\.0\.1|0\.0\.0\.0|\[::1\])(?::\d+)?\/?$/iconst URL_ONLY_LINE_RE = /^\s*https?:\/\/\S+\s*$/i+// Autolink-shaped spans (bare or angle-bracketed http(s) URLs) that must be+// skipped by lone-tilde escaping: `~` is legal in URL paths and must survive.+const URL_LIKE_SPLIT_RE = /(<https?:\/\/[^>\s]+>|https?:\/\/[^\s<>"'`*]+[^\s<>"'`*.,;:!?])/g+// A `~` that is neither part of `~~~` fence, part of `~~` strikethrough, nor+// an already-escaped `\~`. Escaping it with `\~` makes `marked` render a+// literal tilde, so CJK ranges (`1~10`) and approximation prefixes (`~¥0.089`)+// no longer pair up into a GFM strikethrough span.+const LONE_TILDE_RE = /(?<![\\~])~(?!~)/g+// HTML-shaped prose tokens (`<tool_call>`, `<observation>`...) that are NOT+// real inline elements get swallowed by the HTML-aware renderer (parse5 sees+// an unclosed tag and consumes the rest of the message). Match unknown tag-like+// runs and escape them to entities; known safe tags pass through untouched.+const HTML_TAG_RE = /<\/?([A-Za-z][A-Za-z0-9:_-]*)(?:\s+[^<>]*?)?\/?>/g++const SAFE_HTML_TAG_NAMES = new Set([+ 'a', 'abbr', 'b', 'blockquote', 'br', 'cite', 'code', 'data', 'del', 'details',+ 'div', 'em', 'figcaption', 'figure', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'hr',+ 'i', 'img', 'ins', 'kbd', 'li', 'mark', 'ol', 'p', 'pre', 'q', 'rp', 'rt',+ 'ruby', 's', 'samp', 'small', 'span', 'strong', 'sub', 'summary', 'sup', 'table',+ 'tbody', 'td', 'tfoot', 'th', 'thead', 'tr', 'u', 'ul', 'var', 'wbr'+])const CITATION_MARKER_RE = /(?<=[\p{L}\p{N})\].,!?:;"'”’])\[(?:\d+(?:\s*,\s*\d+)*)\](?!\()/gu// Markdown links whose target is a filesystem path on the agent's machine:// `[report](/home/user/report.md)`, `[notes](file:///srv/notes.txt)`,@@ -289,6 +310,22 @@ function autoLinkRawUrls(text: string): string {.join('')}+function escapeLoneTildes(text: string): string {+ return text+ .split(URL_LIKE_SPLIT_RE)+ .map(part => (/^<?https?:\/\//i.test(part) ? part : part.replace(LONE_TILDE_RE, '\\~')))+ .join('')+}++function escapeUnknownHtmlLikeTags(text: string): string {+ return text.replace(HTML_TAG_RE, (tag: string, name: string) => {+ if (SAFE_HTML_TAG_NAMES.has(name.toLowerCase())) {+ return tag+ }++ return tag.replace(/</g, '<').replace(/>/g, '>')+ })+}// Rewrite filesystem-path links to the renderer's hash-href door (#82140).// A plain path/file: href names a file on the AGENT's machine: Streamdown's// URL hardening blocks `file:`/`~/` outright, and an absolute path renders@@ -311,9 +348,13 @@ function routeFileLinksToPreview(text: string): string {function rewriteProseSegment(segment: string): string {return linkifySessionRefs(- autoLinkRawUrls(- routeFileLinksToPreview(- segment.replace(/`{3,}/g, '').replace(LOCAL_PREVIEW_URL_RE, '$1').replace(CITATION_MARKER_RE, '')+ escapeLoneTildes(+ autoLinkRawUrls(+ routeFileLinksToPreview(+ escapeUnknownHtmlLikeTags(+ segment.replace(/`{3,}/g, '').replace(LOCAL_PREVIEW_URL_RE, '$1').replace(CITATION_MARKER_RE, '')+ )+ ))))