The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): trim trailing punctuation from bare MEDIA tag captures and reject degenerate paths
Brooklyn Nicholson7327624d3500
diff --git a/apps/desktop/src/lib/chat-messages/parts.capture.test.ts b/apps/desktop/src/lib/chat-messages/parts.capture.test.tsnew file mode 100644index 00000000000..878bd8e3b64--- /dev/null+++ b/apps/desktop/src/lib/chat-messages/parts.capture.test.ts@@ -0,0 +1,39 @@+// Regression for #84361: the bare-word capture branch absorbed trailing+// sentence punctuation (`open MEDIA:/tmp/a.pdf.` captured `/tmp/a.pdf.`) and+// accepted degenerate captures (a lone quote, `...`, a bare word with neither+// a path separator nor a file extension), rendering dead file links.+import { describe, expect, it } from 'vitest'++import { mediaTagValues, renderMediaTags } from './parts'++const card = (path: string) => `[File: ${path.split(/[/\\]/).pop()}](#media:${encodeURIComponent(path)})`++describe('MEDIA tag capture validity', () => {+ it('does not absorb trailing sentence punctuation from a bare capture', () => {+ expect(renderMediaTags('open MEDIA:/tmp/a.pdf.')).toBe(`open ${card('/tmp/a.pdf')}.`)+ expect(renderMediaTags('MEDIA:/tmp/report.pdf!')).toBe(`${card('/tmp/report.pdf')}!`)+ expect(mediaTagValues('open MEDIA:/tmp/a.pdf.')).toEqual(['/tmp/a.pdf'])+ })++ it('keeps punctuation that is INSIDE a quoted capture', () => {+ // mediaTagValues returns raw values quotes-intact; renderMediaTags strips.+ expect(mediaTagValues("MEDIA:'/tmp/stop!.md'")).toEqual(["'/tmp/stop!.md'"])+ expect(renderMediaTags("MEDIA:'/tmp/stop!.md'")).toBe(card('/tmp/stop!.md'))+ expect(renderMediaTags('MEDIA:"/tmp/a b.md." x')).toBe(`${card('/tmp/a b.md.')} x`)+ })++ it('leaves degenerate captures as plain text instead of a dead link', () => {+ // A lone apostrophe, ellipsis, or bare word: neither a path separator nor+ // a file extension — not a deliverable the app can open.+ expect(mediaTagValues('MEDIA:...')).toEqual([])+ expect(mediaTagValues("MEDIA:'")).toEqual([])+ expect(mediaTagValues('MEDIA:download')).toEqual([])+ expect(renderMediaTags('MEDIA:...')).toBe('MEDIA:...')+ expect(renderMediaTags('MEDIA:download')).toBe('MEDIA:download')+ })++ it('still links relative paths with a file extension', () => {+ expect(mediaTagValues('MEDIA:report.md prose')).toEqual(['report.md'])+ expect(renderMediaTags('MEDIA:report.md prose')).toBe(`${card('report.md')} prose`)+ })+})diff --git a/apps/desktop/src/lib/chat-messages/parts.ts b/apps/desktop/src/lib/chat-messages/parts.tsindex 625991342ba..55eba577ccc 100644--- a/apps/desktop/src/lib/chat-messages/parts.ts+++ b/apps/desktop/src/lib/chat-messages/parts.ts@@ -94,13 +94,28 @@ const _MEDIA_PATH_ANCHORED = `(?:~/|/|[A-Za-z]:[/\\\\])\\S+?(?:[^\\S\\n]+\\S+?)*// closer is not swallowed. Apostrophes stay legal inside the path.const _MEDIA_PATH_BARE = '[^\\s`"]+'+// Sentence punctuation that can trail a bare capture when the tag sits in+// prose (`open MEDIA:/tmp/a.pdf.`).+const _MEDIA_TRAILING_PUNCTUATION = '.,;:!?'++/**+ * Whether a capture can name a real deliverable: a path separator, or a dot+ * with file content after it (an extension or a dotfile — `report.md`,+ * `.env`, `../a.png`). Anything else (`...`, a lone quote, a bare English+ * word) renders as prose: a dead `#media:` link for a non-path is worse+ * than no link (#84361).+ */+function isPlausibleMediaPath(value: string): boolean {+ return value.includes('/') || value.includes('\\') || /\.[^.]/.test(value)+}+const MEDIA_LINE_RE = new RegExp(- `(^|\\n)[\\t ]*[\`"']?MEDIA:\\s*(?<line>\`[^\`\\n]+\`|"[^"\\n]+"|'[^'\\n]+'|${_MEDIA_PATH_ANCHORED}|${_MEDIA_PATH_BARE})[\`"']?[\\t ]*(\\n|$)`,+ `(^|\\n)[\\t ]*[\`"']?MEDIA:\\s*(?<line>\`[^\`\n]+\`|"[^"\n]+"|'[^'\n]+'|${_MEDIA_PATH_ANCHORED}|${_MEDIA_PATH_BARE})[\`"']?[\\t ]*(\\n|$)`,'g')const MEDIA_TAG_RE = new RegExp(- `[\`"']?MEDIA:\\s*(?<inline>\`[^\`\\n]+\`|"[^"\\n]+"|'[^'\\n]+'|${_MEDIA_PATH_ANCHORED}|${_MEDIA_PATH_BARE})[\`"']?`,+ `[\`"']?MEDIA:\\s*(?<inline>\`[^\`\n]+\`|"[^"\n]+"|'[^'\n]+'|${_MEDIA_PATH_ANCHORED}|${_MEDIA_PATH_BARE})[\`"']?`,'g')@@ -119,24 +134,75 @@ function unquoteMediaPath(value: string): string {return last === '`' || last === '"' ? trimmed.slice(0, -1) : trimmed}-function mediaLink(value: string): string {- const path = unquoteMediaPath(value)+/**+ * Split a bare (unquoted) capture into its path and the sentence punctuation+ * that trailed it in prose: `open MEDIA:/tmp/a.pdf.` captures `/tmp/a.pdf.` —+ * the period belongs to the sentence, not the path. Punctuation is only+ * prose while what precedes it still names a path, so an ellipsis+ * (`MEDIA:...`) is never split into a degenerate capture. Quoted captures are+ * exempt (quotes are the documented escape hatch for odd names:+ * `MEDIA:'/tmp/stop!.md'` keeps its `!`).+ */+function splitTrailingPunctuation(value: string): { path: string; punctuation: string } {+ let end = value.length++ while (end > 0 && _MEDIA_TRAILING_PUNCTUATION.includes(value[end - 1] ?? '')) {+ if (!isPlausibleMediaPath(value.slice(0, end - 1))) {+ break+ }++ end -= 1+ }++ return { path: value.slice(0, end), punctuation: value.slice(end) }+}++function mediaLink(value: string): string | null {+ const raw = value.trim()+ const quote = raw[0]+ const quoted = quote && quote === raw.at(-1) && ['"', "'", '`'].includes(quote)- return `[${mediaDisplayLabel(path)}](${mediaMarkdownHref(path)})`+ // Quoted captures are the escape hatch for odd names — punctuation inside+ // the quotes is part of the path, so only a BARE capture is split.+ const { path, punctuation } = quoted+ ? { path: unquoteMediaPath(raw), punctuation: '' }+ : splitTrailingPunctuation(unquoteMediaPath(raw))++ return isPlausibleMediaPath(path)+ ? `[${mediaDisplayLabel(path)}](${mediaMarkdownHref(path)})${punctuation}`+ : null}export function renderMediaTags(text: string): string {return text.replace(MEDIA_LINE_RE,- (_match, lead: string, value: string, trailer: string) => `${lead}${mediaLink(value)}${trailer}`+ (match, lead: string, value: string, trailer: string) => {+ const link = mediaLink(value)++ return link ? `${lead}${link}${trailer}` : match+ })- .replace(MEDIA_TAG_RE, (_match, value: string) => mediaLink(value))+ .replace(MEDIA_TAG_RE, (match, value: string) => mediaLink(value) ?? match)}-/** Raw `MEDIA:` values in `text`, quotes intact — the one parser Artifacts and chat share. */+/** Raw `MEDIA:` values in `text`, quotes intact — the one parser Artifacts and chat share.+ * Bare captures shed trailing sentence punctuation (same rule as+ * {@link renderMediaTags}); degenerate non-path captures are dropped. */export function mediaTagValues(text: string): string[] {- return [...text.matchAll(MEDIA_TAG_RE)].map(match => match[1] ?? '')+ return [...text.matchAll(MEDIA_TAG_RE)]+ .map(match => match[1] ?? '')+ .flatMap(value => {+ const { path, punctuation } = splitTrailingPunctuation(unquoteMediaPath(value))++ if (!isPlausibleMediaPath(path)) {+ return []+ }++ // Bare captures shed the prose punctuation (it trails the raw value+ // too); quoted captures keep every character inside their quotes.+ return [punctuation ? value.slice(0, -punctuation.length || undefined) : value]+ })}export function assistantTextPart(text: string, timestamp?: number): ChatMessagePart {diff --git a/apps/desktop/src/lib/media.remote.test.ts b/apps/desktop/src/lib/media.remote.test.tsindex 314b72770bc..e9d3f02c9e7 100644--- a/apps/desktop/src/lib/media.remote.test.ts+++ b/apps/desktop/src/lib/media.remote.test.ts@@ -53,6 +53,27 @@ describe('mediaExternalUrl', () => {$connection.set({ mode: 'remote', baseUrl: 'https://gw' } as never)expect(mediaExternalUrl('/tmp/a.png')).toBe('file:///tmp/a.png')})++ // #84361: the raw `file://${path}` concat broke on URL-structural+ // characters — `#`/`?` truncated the path at the fragment/query boundary+ // and a stray `%` made the main process's fileURLToPath throw.+ it('escapes URL-structural characters so the whole path survives the round trip', () => {+ $connection.set({ mode: 'local' } as never)++ const roundTrip = (fileUrl: string): string => {+ const parsed = new URL(fileUrl)++ return decodeURIComponent(parsed.pathname)+ }++ expect(mediaExternalUrl('/tmp/Report #2.pdf')).toBe('file:///tmp/Report %232.pdf')+ expect(mediaExternalUrl('/tmp/a?b.pdf')).toBe('file:///tmp/a%3Fb.pdf')+ expect(mediaExternalUrl('/tmp/100%.pdf')).toBe('file:///tmp/100%25.pdf')++ for (const path of ['/tmp/Report #2.pdf', '/tmp/a?b.pdf', '/tmp/100%.pdf', '/tmp/café.png']) {+ expect(roundTrip(mediaExternalUrl(path))).toBe(path)+ }+ })})describe('mediaGatewayStreamUrl', () => {diff --git a/apps/desktop/src/lib/media.ts b/apps/desktop/src/lib/media.tsindex 8fd0f6d3800..3fe026a7e26 100644--- a/apps/desktop/src/lib/media.ts+++ b/apps/desktop/src/lib/media.ts@@ -79,6 +79,24 @@ export function mediaMarkdownHref(path: string): string {return `#media:${encodeURIComponent(path)}`}+/**+ * Escape only the URL-structural characters in a filesystem path so the+ * WHATWG parser (and Node's `fileURLToPath` in the main process) keeps the+ * whole path: a raw `#`/`?` is parsed as fragment/query and truncates the+ * path, and a raw `%` that isn't a valid hex escape makes decoding throw.+ * Spaces, unicode, Windows drive letters and a leading `~/` stay literal for+ * the main process to expand (#84361).+ */+export function pathToLocalFileUrl(path: string): string {+ if (/^file:/i.test(path)) {+ return path+ }++ const escaped = path.replace(/%/g, '%25').replace(/#/g, '%23').replace(/\?/g, '%3F')++ return `file://${escaped}`+}+export function isInlineMediaSrc(path: string): boolean {return /^(?:https?|data):/i.test(path)}@@ -233,7 +251,7 @@ export function mediaExternalUrl(path: string): string {}}- return /^file:/i.test(path) ? path : `file://${path}`+ return /^file:/i.test(path) ? path : pathToLocalFileUrl(path)}// Remote gateway audio/video is proxied by the Electron main process. OAuth