Skip to content

The agent that grows with you

fix(desktop): keep URLs inside Markdown code un-chipped

Austin Pickettddb56d0aa126
diff --git a/apps/desktop/src/app/chat/composer/url-refs.test.ts b/apps/desktop/src/app/chat/composer/url-refs.test.ts
index 2b62eff2117..65aa9c3f3ed 100644
--- a/apps/desktop/src/app/chat/composer/url-refs.test.ts
+++ b/apps/desktop/src/app/chat/composer/url-refs.test.ts
@@ -52,6 +52,70 @@ describe('linkifyUrls', () => {
expect(linkifyUrls('@url:`https://example.dev`')).toBe('@url:`https://example.dev`')
})
+ // #74741: a URL inside a fenced block is verbatim payload (a stack trace, a
+ // log line, a command), not prose to chip.
+ it('preserves a URL inside a fenced code block verbatim', () => {
+ const text = [
+ '```',
+ 'android.content.ActivityNotFoundException: No Activity found to handle Intent { act=android.intent.action.VIEW dat=https://google.com/... (has extras) }',
+ '```'
+ ].join('\n')
+
+ expect(linkifyUrls(text)).toBe(text)
+ })
+
+ it('preserves links inside fenced code while rewriting surrounding prose', () => {
+ const text = [
+ 'before https://before.dev',
+ '```ini',
+ 'endpoint=https://code.dev/api',
+ '```',
+ 'after https://after.dev'
+ ].join('\n')
+
+ expect(linkifyUrls(text)).toBe(
+ [
+ 'before @url:`https://before.dev`',
+ '```ini',
+ 'endpoint=https://code.dev/api',
+ '```',
+ 'after @url:`https://after.dev`'
+ ].join('\n')
+ )
+ })
+
+ it('preserves links inside tilde-fenced code', () => {
+ const text = ['~~~yaml', 'endpoint: https://code.dev/api', '~~~'].join('\n')
+
+ expect(linkifyUrls(text)).toBe(text)
+ })
+
+ it('preserves links inside inline code while rewriting surrounding prose', () => {
+ expect(linkifyUrls('see https://before.dev then `curl https://code.dev/api` and https://after.dev')).toBe(
+ 'see @url:`https://before.dev` then `curl https://code.dev/api` and @url:`https://after.dev`'
+ )
+ })
+
+ it('supports arbitrary backtick runs around inline code', () => {
+ const text = 'run ``curl ` https://code.dev/api`` now'
+
+ expect(linkifyUrls(text)).toBe(text)
+ })
+
+ it('preserves links in unfinished code while the user is composing it', () => {
+ const unfinishedFence = ['```sh', 'curl https://code.dev/api'].join('\n')
+ const unfinishedInline = 'run `curl https://code.dev/api'
+
+ expect(linkifyUrls(unfinishedFence)).toBe(unfinishedFence)
+ expect(linkifyUrls(unfinishedInline)).toBe(unfinishedInline)
+ })
+
+ it('rewrites prose links after an escaped unmatched backtick', () => {
+ expect(linkifyUrls('show \\` literally, then visit https://example.dev/api')).toBe(
+ 'show \\` literally, then visit @url:`https://example.dev/api`'
+ )
+ })
+
it('leaves text without a scheme alone', () => {
expect(linkifyUrls('example.dev/a and src/foo.ts')).toBe('example.dev/a and src/foo.ts')
})
@@ -201,4 +265,46 @@ describe('chipTypedUrlOnSpace', () => {
editor.remove()
})
+
+ it('does not chip a link typed inside an unfinished fenced code block', () => {
+ const text = ['```sh', 'curl https://code.dev/api'].join('\n')
+ const { editor, event } = spaceOn(text, text.length)
+
+ expect(chipTypedUrlOnSpace(event)).toBe(false)
+ expect(composerPlainText(editor)).toBe(text)
+
+ editor.remove()
+ })
+
+ it('does not chip a link typed inside an unfinished inline code span', () => {
+ const text = 'run `curl https://code.dev/api'
+ const { editor, event } = spaceOn(text, text.length)
+
+ expect(chipTypedUrlOnSpace(event)).toBe(false)
+ expect(composerPlainText(editor)).toBe(text)
+
+ editor.remove()
+ })
+
+ it('still chips a link typed after a completed code block', () => {
+ const text = ['```', 'https://code.dev/api', '```', 'see https://example.dev/api'].join('\n')
+ const { editor, event } = spaceOn(text, text.length)
+
+ expect(chipTypedUrlOnSpace(event)).toBe(true)
+ expect(composerPlainText(editor)).toBe(
+ ['```', 'https://code.dev/api', '```', 'see @url:`https://example.dev/api` '].join('\n')
+ )
+
+ editor.remove()
+ })
+
+ it('chips a prose link typed after an escaped unmatched backtick', () => {
+ const text = 'show \\` literally, then visit https://example.dev/api'
+ const { editor, event } = spaceOn(text, text.length)
+
+ expect(chipTypedUrlOnSpace(event)).toBe(true)
+ expect(composerPlainText(editor)).toBe('show \\` literally, then visit @url:`https://example.dev/api` ')
+
+ editor.remove()
+ })
})
diff --git a/apps/desktop/src/app/chat/composer/url-refs.ts b/apps/desktop/src/app/chat/composer/url-refs.ts
index e0a9306acfa..a292412bafe 100644
--- a/apps/desktop/src/app/chat/composer/url-refs.ts
+++ b/apps/desktop/src/app/chat/composer/url-refs.ts
@@ -20,6 +20,109 @@ const URL_RE = /https?:\/\/[^\s<>[\]{}"'`]+/gi
const EXACT_URL_RE = /^https?:\/\/[^\s<>[\]{}"'`]+$/i
const TYPED_URL_RE = /(?:^|\s)(https?:\/\/[^\s<>[\]{}"'`]+)$/i
+/** A half-open `[start, end)` span of the draft text. */
+interface TextRange {
+ end: number
+ start: number
+}
+
+const containsIndex = (ranges: TextRange[], index: number) =>
+ ranges.some(range => index >= range.start && index < range.end)
+
+/** A backtick run preceded by an odd number of backslashes is escaped prose, not
+ * a code delimiter (`\`` reads literally). */
+function isEscaped(text: string, index: number) {
+ let backslashes = 0
+
+ for (let cursor = index - 1; cursor >= 0 && text[cursor] === '\\'; cursor -= 1) {
+ backslashes += 1
+ }
+
+ return backslashes % 2 === 1
+}
+
+/** Markdown fenced code blocks (``` or ~~~), including an unfinished block while
+ * the user is still composing one. */
+function fencedCodeRanges(text: string) {
+ const ranges: TextRange[] = []
+ let opening: { marker: string; start: number } | undefined
+
+ for (const match of text.matchAll(/^[ \t]{0,3}(`{3,}|~{3,})([^\r\n]*)(?:\r?\n|$)/gm)) {
+ const marker = match[1]
+ const tail = match[2]
+
+ if (!opening) {
+ // Backticks in a backtick fence's info string are invalid Markdown, so a
+ // stray run must not turn the rest of the draft into protected code.
+ if (marker[0] === '`' && tail.includes('`')) {
+ continue
+ }
+
+ opening = { marker, start: match.index ?? 0 }
+
+ continue
+ }
+
+ // A closing fence is the same character, at least as long, with nothing but
+ // whitespace after it.
+ if (marker[0] === opening.marker[0] && marker.length >= opening.marker.length && tail.trim() === '') {
+ ranges.push({ end: (match.index ?? 0) + match[0].length, start: opening.start })
+ opening = undefined
+ }
+ }
+
+ if (opening) {
+ ranges.push({ end: text.length, start: opening.start })
+ }
+
+ return ranges
+}
+
+/** Markdown inline code spans outside fences, including an unfinished span while
+ * the user is still composing one. Runs pair up by matching backtick length, so
+ * `` `a ` b` `` stays one span. */
+function inlineCodeRanges(text: string, fenced: TextRange[]) {
+ const ranges: TextRange[] = []
+
+ const markers = Array.from(text.matchAll(/`+/g)).filter(marker => {
+ const index = marker.index ?? 0
+
+ return !containsIndex(fenced, index) && !isEscaped(text, index)
+ })
+
+ let markerIndex = 0
+
+ while (markerIndex < markers.length) {
+ const opening = markers[markerIndex]
+
+ const closingIndex = markers.findIndex(
+ (candidate, index) => index > markerIndex && candidate[0].length === opening[0].length
+ )
+
+ if (closingIndex === -1) {
+ ranges.push({ end: text.length, start: opening.index ?? 0 })
+
+ break
+ }
+
+ const closing = markers[closingIndex]
+
+ ranges.push({ end: (closing.index ?? 0) + closing[0].length, start: opening.index ?? 0 })
+ markerIndex = closingIndex + 1
+ }
+
+ return ranges
+}
+
+/** The spans of `text` Markdown renders as code — fenced blocks plus inline
+ * spans. A URL inside one is verbatim payload (a stack trace, a log line, a
+ * command), not prose to chip, so the recognizer must leave it alone. */
+function markdownCodeRanges(text: string) {
+ const fenced = fencedCodeRanges(text)
+
+ return [...fenced, ...inlineCodeRanges(text, fenced)]
+}
+
/** A URL at the end of a sentence carries the punctuation that ended it. */
function splitUrlTail(raw: string) {
let url = raw.replace(/[,.;:!?]+$/, '')
@@ -40,12 +143,17 @@ const hasHost = (url: string) => /^https?:\/\/[^/\s]/i.test(url)
export function linkifyUrls(text: string) {
REF_RE.lastIndex = 0
- const fenced = Array.from(text.matchAll(REF_RE)).map(match => {
+ // URLs inside an existing `@url:` directive or a Markdown code span are not
+ // prose to chip — the directive is already a reference, and code is verbatim
+ // payload the user pasted (a stack trace, a command, a log line).
+ const protectedRanges = Array.from(text.matchAll(REF_RE)).map(match => {
const start = match.index ?? 0
return { end: start + match[0].length, start }
})
+ protectedRanges.push(...markdownCodeRanges(text))
+
let out = ''
let cursor = 0
@@ -53,7 +161,7 @@ export function linkifyUrls(text: string) {
const start = match.index ?? 0
const { url } = splitUrlTail(match[0])
- if (!hasHost(url) || fenced.some(span => start >= span.start && start < span.end)) {
+ if (!hasHost(url) || containsIndex(protectedRanges, start)) {
continue
}
@@ -142,13 +250,24 @@ export function chipTypedUrlOnSpace(event: KeyboardEvent<HTMLDivElement>) {
}
const before = textBeforeCaret(editor)
- const match = before ? TYPED_URL_RE.exec(before) : null
+
+ if (!before) {
+ return false
+ }
+
+ const match = TYPED_URL_RE.exec(before)
const token = match?.[1]
if (!token) {
return false
}
+ // A link typed inside a code block or span is verbatim payload, not prose —
+ // chipping it would rewrite code the user is authoring.
+ if (containsIndex(markdownCodeRanges(before), before.length - token.length)) {
+ return false
+ }
+
const { trailing, url } = splitUrlTail(token)
if (!hasHost(url)) {