Skip to content

The agent that grows with you

fix(desktop): raw-URL autolinker steps over markdown links (#49822)

brooklyn!c882636db2b0
diff --git a/apps/desktop/src/lib/markdown-preprocess.autolink.test.ts b/apps/desktop/src/lib/markdown-preprocess.autolink.test.ts
new file mode 100644
index 00000000000..6108b121247
--- /dev/null
+++ b/apps/desktop/src/lib/markdown-preprocess.autolink.test.ts
@@ -0,0 +1,122 @@
+import { tailBoundedRemend } from '@assistant-ui/react-streamdown'
+import remarkGfm from 'remark-gfm'
+import remarkParse from 'remark-parse'
+import { unified } from 'unified'
+import { describe, expect, it } from 'vitest'
+
+import { preprocessMarkdown } from './markdown-preprocess'
+
+/**
+ * The bare-URL autolinker wraps prose URLs in `<…>`. It must leave URLs that
+ * markdown syntax already owns alone: wrapping the label of `[url](url)`
+ * swallowed `](url)` into the href (#49822, #85234). Each case asserts the
+ * hrefs the renderer's parser actually produces from the preprocessed text.
+ */
+
+type MdNode = { children?: MdNode[]; identifier?: string; type: string; url?: string }
+
+// Every href the parser resolves, reference links included, in document order.
+function hrefs(markdown: string, prepare = preprocessMarkdown): string[] {
+ const tree = unified().use(remarkParse).use(remarkGfm).parse(prepare(markdown)) as MdNode
+ const definitions = new Map<string, string>()
+ const found: (() => string)[] = []
+
+ const walk = (node: MdNode) => {
+ if (node.type === 'definition') {
+ definitions.set(node.identifier ?? '', node.url ?? '')
+ } else if (node.type === 'link' || node.type === 'image') {
+ found.push(() => node.url ?? '')
+ } else if (node.type === 'linkReference' || node.type === 'imageReference') {
+ found.push(() => definitions.get(node.identifier ?? '') ?? '')
+ }
+
+ node.children?.forEach(walk)
+ }
+
+ walk(tree)
+
+ return found.map(resolve => resolve())
+}
+
+describe('preprocessMarkdown / raw-URL autolinking inside markdown links', () => {
+ it.each([
+ 'https://example.com',
+ 'http://example.com',
+ 'https://example.com:8080',
+ 'https://[email protected]',
+ 'https://example.com/page',
+ 'https://example.com?q=test',
+ 'https://example.com#test',
+ 'https://www.metodic.io/articles/whats-moving-in-facilitation-july-2026'
+ ])('keeps [url](url) intact for %s', url => {
+ const input = `[${url}](${url})`
+
+ expect(preprocessMarkdown(input)).toBe(input)
+ expect(hrefs(input)).toEqual([url])
+ })
+
+ it.each([
+ ['[see https://a.example/x for more](https://b.example/y)', ['https://b.example/y']],
+ ['[http://[::1]:8080/status](https://example.com/status)', ['https://example.com/status']],
+ ['[docs [https://example.com/path]](https://example.com/path)', ['https://example.com/path']],
+ ['[a\\]https://example.com/x](https://example.com/y)', ['https://example.com/y']],
+ ['[[inner](https://i.example) outer](https://o.example)', ['https://i.example', 'https://o.example']],
+ ['![https://example.com/a.png](https://example.com/a.png)', ['https://example.com/a.png']],
+ ['[https://x.example](https://x.example "https://x.example title")', ['https://x.example']],
+ ['[Foo](https://en.wikipedia.org/wiki/Foo_(bar))', ['https://en.wikipedia.org/wiki/Foo_(bar)']],
+ ['<https://example.com/a>', ['https://example.com/a']]
+ ])('keeps link labels and targets intact: %s', (input, expected) => {
+ expect(preprocessMarkdown(input)).toBe(input)
+ expect(hrefs(input)).toEqual(expected)
+ })
+
+ it('keeps full and collapsed reference links intact', () => {
+ const full = '[https://example.com/a][ref]\n\n[ref]: https://example.com/b'
+ const collapsed = '[https://example.com/a][]\n\n[https://example.com/a]: https://example.com/b'
+
+ expect(preprocessMarkdown(full)).toBe(full)
+ expect(hrefs(full)).toEqual(['https://example.com/b'])
+ expect(preprocessMarkdown(collapsed)).toBe(collapsed)
+ expect(hrefs(collapsed)).toEqual(['https://example.com/b'])
+ })
+
+ it('never wraps URLs in inline code or code fences', () => {
+ const input =
+ 'Try `[https://x.example](https://x.example)` or\n\n```md\n[https://x.example](https://x.example)\n```'
+
+ expect(preprocessMarkdown(input)).toBe(input)
+ })
+
+ it('still autolinks bare URLs sharing a line with a markdown link', () => {
+ const input = 'Docs https://a.example/x and [https://b.example/y](https://b.example/y).'
+
+ expect(hrefs(input)).toEqual(['https://a.example/x', 'https://b.example/y'])
+ })
+
+ it('never leaks link syntax into an href while the link streams in', () => {
+ const link = '[https://example.com/a](https://example.com/a)'
+ const streamed = (text: string) => tailBoundedRemend(preprocessMarkdown(text))
+
+ for (let end = 1; end <= link.length; end += 1) {
+ for (const url of hrefs(`See ${link.slice(0, end)}`, streamed)) {
+ expect(url).not.toMatch(/[\]()]|%5D/)
+ }
+ }
+ })
+})
+
+describe('preprocessMarkdown / bare-URL trailing punctuation', () => {
+ it.each([
+ ['Visit https://example.com/a.', 'https://example.com/a'],
+ ['Visit https://example.com/a, then', 'https://example.com/a'],
+ ['(see https://example.com/a)', 'https://example.com/a'],
+ ['(see https://example.com/a).', 'https://example.com/a'],
+ ['(see https://example.com/a.)', 'https://example.com/a'],
+ ['[https://example.com/a]', 'https://example.com/a'],
+ ['See https://en.wikipedia.org/wiki/Foo_(bar).', 'https://en.wikipedia.org/wiki/Foo_(bar)'],
+ ['(https://en.wikipedia.org/wiki/Foo_(bar))', 'https://en.wikipedia.org/wiki/Foo_(bar)'],
+ ['Host http://[2001:db8::1]:8080/status.', 'http://[2001:db8::1]:8080/status']
+ ])('%s links %s', (input, expected) => {
+ expect(hrefs(input)).toEqual([expected])
+ })
+})
diff --git a/apps/desktop/src/lib/markdown-preprocess.ts b/apps/desktop/src/lib/markdown-preprocess.ts
index 59ee564702b..2fe3cfa92a3 100644
--- a/apps/desktop/src/lib/markdown-preprocess.ts
+++ b/apps/desktop/src/lib/markdown-preprocess.ts
@@ -66,6 +66,29 @@ const HUGGING_DISPLAY_MATH_CLOSE_RE = /^([ \t]*(?:>[ \t]*)*[ \t]*)(\S[^\n]*?)\$\
// and keeps the emphasis run intact. Other trailing punctuation is still peeled
// off by the final `[^\s<>"'`*.,;:!?]` class.
const RAW_URL_RE = /https?:\/\/[^\s<>"'`*]+[^\s<>"'`*.,;:!?]/g
+const URL_TRAILING_PUNCTUATION = '.,;:!?'
+// Markdown that already owns the URLs inside it, which the bare-URL autolinker
+// steps over whole (#49822): inline links and images `[label](dest "title")`,
+// full and collapsed references `[label][ref]`, and the label + destination of
+// a definition `[ref]: url`. Labels may nest one bracket pair (an IPv6 host,
+// `[see [docs]]`) and destinations one paren pair (`…/wiki/Foo_(bar)`). A label
+// or inline target still streaming in (`[https://exa`, `[x](https://exa`) owns
+// the rest of its line, so the tail repair sees the link it is building instead
+// of a wrapped fragment. Only the outer group captures, so split() leaves the
+// owned spans at odd indices.
+const LINK_LABEL_BODY = String.raw`(?:[^[\]\\\n]|\\.|\[(?:[^[\]\\\n]|\\.)*\])*`
+const LINK_LABEL = String.raw`\[${LINK_LABEL_BODY}\]`
+
+const MARKDOWN_LINK_SPLIT_RE = new RegExp(
+ `(${[
+ String.raw`!?${LINK_LABEL}\((?:[^()\n]|\([^()\n]*\))*(?:\)|$)`,
+ String.raw`${LINK_LABEL}\[(?:[^[\]\\\n]|\\.)*\]`,
+ String.raw`^[ \t]{0,3}${LINK_LABEL}:[ \t]*\S*`,
+ String.raw`\[${LINK_LABEL_BODY}$`
+ ].join('|')})`,
+ 'gm'
+)
+
const LOCAL_PREVIEW_URL_RE = /(^|\s)https?:\/\/(?:localhost|127\.0\.0\.1|0\.0\.0\.0|\[::1\])(?::\d+)?\/?[^\s<>"'`]*/gi
const LOCAL_PREVIEW_ONLY_RE = /^https?:\/\/(?:localhost|127\.0\.0\.1|0\.0\.0\.0|\[::1\])(?::\d+)?\/?$/i
const URL_ONLY_LINE_RE = /^\s*https?:\/\/\S+\s*$/i
@@ -208,52 +231,62 @@ function isUrlOnlyBlock(lines: string[]): boolean {
return nonEmpty.length > 0 && nonEmpty.every(line => URL_ONLY_LINE_RE.test(line))
}
-// Strip only the *unbalanced* trailing `)` — the closing paren of a prose
-// wrapper like `(https://example.com/page)`, which the bare-URL matcher
-// greedily captures into the href. Parens that belong to the URL itself
-// (`…/wiki/Foo_(bar)`) stay intact. Track normal left-to-right pairing and
-// peel only a suffix made entirely of unmatched closing parens; this avoids
-// sacrificing a valid trailing pair when an earlier stray `)` exists.
-function trimUnbalancedTrailingParens(url: string): string {
+// Where a bare URL match really ends. Peels what the prose wrapped around it:
+// the `)` of `(see https://x)`, the `]` of `[https://x]`, and punctuation that
+// peel exposes (`(https://x.)`). A closer stays when an opener inside the URL
+// pairs with it, so `…/wiki/Foo_(bar)` and `http://[::1]/` keep theirs.
+function isPairedCloser(url: string, index: number): boolean {
+ const close = url[index]
+ const open = close === ')' ? '(' : '['
let depth = 0
- let unmatchedSuffixStart: number | null = null
-
- for (let index = 0; index < url.length; index += 1) {
- const char = url[index]
- if (char === '(') {
+ for (let cursor = 0; cursor < index; cursor += 1) {
+ if (url[cursor] === open) {
depth += 1
- unmatchedSuffixStart = null
- } else if (char === ')') {
- if (depth > 0) {
- depth -= 1
- unmatchedSuffixStart = null
- } else if (unmatchedSuffixStart === null) {
- unmatchedSuffixStart = index
- }
- } else {
- unmatchedSuffixStart = null
+ } else if (url[cursor] === close && depth > 0) {
+ depth -= 1
}
}
- return unmatchedSuffixStart === null ? url : url.slice(0, unmatchedSuffixStart)
+ return depth > 0
}
-function autoLinkRawUrls(text: string): string {
- return text.replace(RAW_URL_RE, (url: string, index: number) => {
- const previous = text[index - 1] || ''
- const beforePrevious = text[index - 2] || ''
+function bareUrlEnd(url: string): number {
+ let end = url.length
+
+ while (end > 0) {
+ const last = url[end - 1]
+ const strayCloser = (last === ')' || last === ']') && !isPairedCloser(url, end - 1)
- if (previous === '<' || (beforePrevious === ']' && previous === '(')) {
- return url
+ if (!strayCloser && !URL_TRAILING_PUNCTUATION.includes(last)) {
+ break
}
- const trimmed = trimUnbalancedTrailingParens(url)
+ end -= 1
+ }
+
+ return end
+}
- return `<${trimmed}>${url.slice(trimmed.length)}`
+function linkBareUrls(text: string): string {
+ return text.replace(RAW_URL_RE, (match: string, index: number) => {
+ if (text[index - 1] === '<') {
+ return match
+ }
+
+ const end = bareUrlEnd(match)
+
+ return `<${match.slice(0, end)}>${match.slice(end)}`
})
}
+function autoLinkRawUrls(text: string): string {
+ return text
+ .split(MARKDOWN_LINK_SPLIT_RE)
+ .map((part, index) => (index % 2 === 1 ? part : linkBareUrls(part)))
+ .join('')
+}
+
// 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