diff --git a/apps/mobile/src/lib/markdownDocument.ts b/apps/mobile/src/lib/markdownDocument.ts index 4dd88d62fc475..82b384cb54d89 100644 --- a/apps/mobile/src/lib/markdownDocument.ts +++ b/apps/mobile/src/lib/markdownDocument.ts @@ -6,6 +6,7 @@ import { remarkKeepWindowsProsePaths } from "@t3tools/shared/markdownWindowsPath import { absoluteFilePathMatches, inlineCodeFilePathCandidate, + markdownWithSpacedPathDestinations, parseMarkdownFileLink, } from "@t3tools/shared/markdownLinks"; import { isWindowsAbsolutePath } from "@t3tools/shared/path"; @@ -559,7 +560,9 @@ function markdownWithImageParagraphs(markdown: string): string { // HTML wrappers can expose Markdown that wasn't in the first AST, so normalize them first. function normalizedMarkdown(markdown: string): string { - return markdownWithWindowsPathDestinations(markdownWithHtml(markdown)); + return markdownWithWindowsPathDestinations( + markdownWithSpacedPathDestinations(markdownWithHtml(markdown)).markdown, + ); } export function markdownForNativeParsing(markdown: string): string { diff --git a/apps/mobile/src/lib/markdownHtml.test.ts b/apps/mobile/src/lib/markdownHtml.test.ts index 383a43d0dcfc8..1ee7686609045 100644 --- a/apps/mobile/src/lib/markdownHtml.test.ts +++ b/apps/mobile/src/lib/markdownHtml.test.ts @@ -433,6 +433,24 @@ describe("Windows paths in native Markdown", () => { }); }); +it("links absolute paths with spaces in native Markdown", async () => { + const posix = "/home/user/Synced Folder/Project/Sheet.pdf"; + const windows = String.raw`C:\My Drive\.t3\a.html`; + const native = await parseMarkdown( + markdownForNativeRendering( + `[Sheet.pdf](${posix}) [a](${windows}) [run](/usr/bin/node server.js)`, + ENRICHED_INLINE_FILE_LINK_REGEX, + ), + ); + const urls: string[] = []; + const collect = (node: { attributes?: { url?: string }; children?: unknown[] }) => { + if (node.attributes?.url) urls.push(node.attributes.url); + node.children?.forEach((child) => collect(child as typeof node)); + }; + collect(native); + expect(urls).toEqual([posix, windows]); +}); + it("keeps backslashes in drive paths in mobile Markdown prose", () => { const path = String.raw`Saved to C:\Users\me\.t3\_build\shot.png and C:/work\.config.`; diff --git a/apps/web/src/markdown/wordsHast.test.ts b/apps/web/src/markdown/wordsHast.test.ts index c89ee264a546e..f41ef1cdd7870 100644 --- a/apps/web/src/markdown/wordsHast.test.ts +++ b/apps/web/src/markdown/wordsHast.test.ts @@ -289,6 +289,39 @@ describe("wordsHast", () => { expect(slices).toEqual(["[a](u)", "- [ ] task", "```sh\nls\n```", "- [b](./b.ts)"]); }); + it("links absolute paths with spaces, keeping positions in the message", () => { + const markdown = [ + "[Sheet.pdf](/home/user/Synced Folder/Sheet.pdf) and [a](C:\\My Drive\\x\\a.html)", + "", + "★ Insight ─────", + "[b](~/線性 代數/b.md) [run](/usr/bin/node server.js)", + "─────", + "", + "- [ ] task", + ].join("\n"); + const tree = wordsHast(markdown, { ...ASSISTANT, insights: true }); + const links: Array = []; + const visit = (node: Root | Element) => { + for (const child of node.children) { + if (child.type !== "element") continue; + if (child.tagName === "a" || child.tagName === "li") { + links.push([ + child.tagName === "a" ? decodeURIComponent(String(child.properties.href)) : undefined, + markdown.slice(child.position!.start.offset, child.position!.end.offset), + ]); + } + visit(child); + } + }; + visit(tree); + expect(links).toEqual([ + ["/home/user/Synced Folder/Sheet.pdf", "[Sheet.pdf](/home/user/Synced Folder/Sheet.pdf)"], + ["file:///C:/My Drive/x/a.html", "[a](C:\\My Drive\\x\\a.html)"], + ["~/線性 代數/b.md", "[b](~/線性 代數/b.md)"], + [undefined, "- [ ] task"], + ]); + }); + it("renders insight blocks as remarkAssistantInsights did", () => { for (const ending of ["\n", "\r\n", "\r"]) { expect( diff --git a/apps/web/src/markdown/wordsHast.ts b/apps/web/src/markdown/wordsHast.ts index 2cca96bb1b402..c673833c7b510 100644 --- a/apps/web/src/markdown/wordsHast.ts +++ b/apps/web/src/markdown/wordsHast.ts @@ -14,7 +14,10 @@ import { expandGithubEmojiAliases } from "@t3tools/client-runtime/pull-request-m import { resolveChangeRequestMediaUrl } from "@t3tools/client-runtime/pull-request-references"; import { expandIndentedCodeTabs } from "@t3tools/shared/markdownListIndentation"; import { GITHUB_ALERT_MARKER } from "@t3tools/shared/markdownGithubAlerts"; -import { absoluteFilePathMatches } from "@t3tools/shared/markdownLinks"; +import { + absoluteFilePathMatches, + markdownWithSpacedPathDestinations, +} from "@t3tools/shared/markdownLinks"; import { rehypeNormalizeLocalFileLinks, rehypePreserveImageSourceMeta, @@ -1262,8 +1265,9 @@ export function wordsHast(text: string, options: WordsHastOptions): Root { ? { skipHtml: true } : { escapeHtml: options.escapeHtml }), }; - const insights = options.insights ? insightSource(text, renderOptions) : null; - const source = insights?.source ?? text; + const spaced = markdownWithSpacedPathDestinations(text); + const insights = options.insights ? insightSource(spaced.markdown, renderOptions) : null; + const source = insights?.source ?? spaced.markdown; const tree = insights?.tree ?? parse(source, renderOptions); let documentDefinitions: string[] | undefined; const walk: Walk = { @@ -1290,7 +1294,19 @@ export function wordsHast(text: string, options: WordsHastOptions): Root { normalizeLocalFileLinks(tree as never); const hast = sanitizeChatHast(tree); if (walk.math.size > 0) restoreMath(hast, walk.math); - if (insights) restorePositions(hast, insights.toOriginal); + if (insights || spaced.inserted.length > 0) { + restorePositions(hast, (offset) => { + const unwrapped = insights ? insights.toOriginal(offset) : offset; + let low = 0; + let high = spaced.inserted.length; + while (low < high) { + const mid = (low + high) >> 1; + if (spaced.inserted[mid]! < unwrapped) low = mid + 1; + else high = mid; + } + return unwrapped - low; + }); + } if (extensions.footnotes) applyFootnoteMode(hast, extensions.footnotes); if (extensions.inert) makeInert(hast); if (extensions.preview) return flattenPreview(hast, extensions.preview); diff --git a/packages/shared/src/markdownLinks.test.ts b/packages/shared/src/markdownLinks.test.ts index 3cc2b186dca90..67466501596bc 100644 --- a/packages/shared/src/markdownLinks.test.ts +++ b/packages/shared/src/markdownLinks.test.ts @@ -4,6 +4,7 @@ import { serializeComposerFileLink } from "./composerTrigger.ts"; import { extractInlineCodeSpans, extractMarkdownLinkHrefs, + markdownWithSpacedPathDestinations, resolveMarkdownFileLinkTarget, } from "./markdownLinks.ts"; @@ -264,6 +265,66 @@ describe("extractInlineCodeSpans", () => { }); }); +// Agents write absolute paths with spaces as bare destinations, which CommonMark ends at the space. +const SPACED_PATH_LINKS: ReadonlyArray, string]> = [ + [ + "[Sheet.pdf](/home/user/Synced Folder/Project/Sheet.pdf)", + ["/home/user/Synced Folder/Project/Sheet.pdf"], + "[Sheet.pdf]()", + ], + [ + String.raw`[a](C:\My Drive\x\a.html) and [b](C:/My Drive/b.md:12)`, + [String.raw`C:\My Drive\x\a.html`, "C:/My Drive/b.md:12"], + String.raw`[a]() and [b]()`, + ], + [ + "[考試](~/線性 代數/考試 一.pdf)", + ["~/線性 代數/考試 一.pdf"], + "[考試](<~/線性 代數/考試 一.pdf>)", + ], + [ + '![plot](/Users/me/My Plots/plot (1).png "Plot") [dir](/Users/me/My Plots/)', + ["/Users/me/My Plots/plot (1).png", "/Users/me/My Plots/"], + '![plot]( "Plot") [dir]()', + ], + [ + "![v4](/Users/me/Library/Mobile Documents/iCloud~md~obsidian/Documents/My Vault/v4.png)", + ["/Users/me/Library/Mobile Documents/iCloud~md~obsidian/Documents/My Vault/v4.png"], + "![v4]()", + ], + ["[run](/usr/bin/node server.js)", [], "[run](/usr/bin/node server.js)"], + ["[a](/home/user/My Folder/a.pdf -v)", [], "[a](/home/user/My Folder/a.pdf -v)"], + [ + "[a](https://x.dev/a b.pdf) [b](docs/My Folder/b.md)", + [], + "[a](https://x.dev/a b.pdf) [b](docs/My Folder/b.md)", + ], + ['[a](/x/a.pdf "t") [b](/x/b.pdf)', ["/x/a.pdf", "/x/b.pdf"], '[a](/x/a.pdf "t") [b](/x/b.pdf)'], + [ + "[a]()", + ["/home/user/My Folder/a.pdf"], + "[a]()", + ], + [ + "`[a](/home/user/My Folder/a.pdf)`\n\n```\n[b](/home/user/My Folder/b.pdf)\n```", + [], + "`[a](/home/user/My Folder/a.pdf)`\n\n```\n[b](/home/user/My Folder/b.pdf)\n```", + ], + ["[a](/home/user/My\nFolder/a.pdf)", [], "[a](/home/user/My\nFolder/a.pdf)"], + ["[note] /home/user/My Folder/a.pdf)", [], "[note] /home/user/My Folder/a.pdf)"], +]; + +describe("markdownWithSpacedPathDestinations", () => { + it.each(SPACED_PATH_LINKS)("wraps spaced absolute paths in %j", (markdown, _hrefs, rewritten) => { + expect(markdownWithSpacedPathDestinations(markdown).markdown).toBe(rewritten); + }); + + it("stays linear on unclosed destinations", () => { + const markdown = "[a](/home/user/My Folder ".repeat(20_000); + expect(markdownWithSpacedPathDestinations(markdown).markdown).toBe(markdown); + }); +}); + describe("extractMarkdownLinkHrefs", () => { it.each([ ["[".repeat(32_000), []], @@ -398,6 +459,10 @@ describe("extractMarkdownLinkHrefs", () => { ])("ends bare destinations only at ASCII whitespace in %j", (markdown, hrefs) => { expect(extractMarkdownLinkHrefs(markdown)).toEqual(hrefs); }); + + it.each(SPACED_PATH_LINKS)("reads spaced absolute path destinations in %j", (markdown, hrefs) => { + expect(extractMarkdownLinkHrefs(markdown)).toEqual(hrefs); + }); }); describe("resolveMarkdownFileLinkTarget", () => { diff --git a/packages/shared/src/markdownLinks.ts b/packages/shared/src/markdownLinks.ts index 7397e940cd6ce..1ee9e94b1184e 100644 --- a/packages/shared/src/markdownLinks.ts +++ b/packages/shared/src/markdownLinks.ts @@ -39,7 +39,7 @@ const INLINE_CODE_WHITESPACE_PATTERN = /\s/; // must sit under a user root, and nothing after a bin folder counts. const SPACED_ABSOLUTE_PATH_ROOT_PATTERN = /^(?:\/|~\/|[A-Za-z]:[\\/]|\\\\)/; const SPACED_PATH_BODY_PATTERN = - /^(?:[\p{L}\p{M}\p{N}._$+@()[\]-]+(?: (?!-+\p{L})[\p{L}\p{M}\p{N}._$+@()[\]-]+)*(?:[\\/]|$))+$/u; + /^(?:[\p{L}\p{M}\p{N}._$+@~()[\]-]+(?: (?!-+\p{L})[\p{L}\p{M}\p{N}._$+@~()[\]-]+)*(?:[\\/]|$))+$/u; function isSpacedAbsoluteFilePath(text: string): boolean { const root = SPACED_ABSOLUTE_PATH_ROOT_PATTERN.exec(text)?.[0]; @@ -904,12 +904,60 @@ function blankCodeBlocks(text: string): string { return blanked + text.slice(copied); } +const SPACED_DESTINATION_ROOT_PATTERN = /^(?:\/|~\/|[A-Za-z]:[\\/])/; + +/** + * A bare destination CommonMark ends at a space, read up to its `)` when that whole text is + * clearly an absolute file path (`/home/user/Synced Folder/a.pdf`), optionally with a quoted + * title. The scan stops at a line end or the next `](`, so scans from successive links never + * overlap and the whole pass stays linear. + */ +function spacedPathDestination(markdown: string, start: number) { + if (markdown[start] !== "(") return null; + let hrefStart = start + 1; + while (markdown[hrefStart] === " " || markdown[hrefStart] === "\t") hrefStart++; + if (!SPACED_DESTINATION_ROOT_PATTERN.test(markdown.slice(hrefStart, hrefStart + 3))) return null; + const delimiter = /[()\n]|\]\(/g; + delimiter.lastIndex = hrefStart; + let depth = 0; + let close = -1; + for (let match = delimiter.exec(markdown); match; match = delimiter.exec(markdown)) { + if (match[0] === "(") { + if (depth === MAX_BARE_DESTINATION_PAREN_DEPTH) return null; + depth += 1; + } else if (match[0] === ")" && depth > 0) { + depth -= 1; + } else { + if (match[0] === ")") close = match.index; + break; + } + } + if (close === -1) return null; + let path = markdown.slice(hrefStart, close).trimEnd(); + const quote = path.at(-1); + if (quote === '"' || quote === "'") { + const opening = path.lastIndexOf(quote, path.length - 2); + if (opening <= 0 || !/[ \t]/.test(path[opening - 1]!)) return null; + path = path.slice(0, opening).trimEnd(); + } + if (!path.includes(" ") || !isSpacedAbsoluteFilePath(path)) return null; + return { hrefStart, hrefEnd: hrefStart + path.length, end: close + 1 }; +} + // Labels may nest balanced brackets (`[the [docs] guide](...)`), and the composer escapes them // (`[\[id\].tsx](...)`), so `\[` and `\]` never count. A blank line ends the paragraph and its labels. -export function extractMarkdownLinkHrefs(text: string): string[] { +function scanMarkdownLinkDestinations( + text: string, + visit: (destination: { hrefStart: number; hrefEnd: number; spaced: boolean }) => void, +) { const markdown = blankCodeBlocks(normalizeLoneCarriageReturns(text)); - const hrefs: string[] = []; - const scanDestination = markdownLinkDestinationScanner(markdown); + const bareDestination = markdownLinkDestinationScanner(markdown); + const scanDestination = (start: number) => { + const destination = bareDestination(start); + if (destination) return { ...destination, spaced: false }; + const spaced = spacedPathDestination(markdown, start); + return spaced && { ...spaced, spaced: true }; + }; const paragraphEnd = markdownRunEndFinder(markdown, /\n[ \t\r]*\n/g); // A code span closes at the next run of as many backticks in its paragraph. const closersByLength = new Map(); @@ -942,13 +990,44 @@ export function extractMarkdownLinkHrefs(text: string): string[] { // A link cannot contain a link, but it can contain an image. if (!image) openers.length = 0; bracket.lastIndex = destination.end; - const href = trimAscii(markdown.slice(destination.hrefStart, destination.hrefEnd)); - if (href) hrefs.push(href); + visit(destination); } } +} + +export function extractMarkdownLinkHrefs(text: string): string[] { + const hrefs: string[] = []; + scanMarkdownLinkDestinations(text, ({ hrefStart, hrefEnd }) => { + const href = trimAscii(text.slice(hrefStart, hrefEnd)); + if (href) hrefs.push(href); + }); return hrefs; } +/** + * Wraps bare link and image destinations that are absolute paths with spaces in `<…>`, so + * parsers link them as written. `inserted` holds the offsets of the added characters in the + * returned Markdown, for mapping source positions back. + */ +export function markdownWithSpacedPathDestinations(text: string): { + markdown: string; + inserted: number[]; +} { + const inserted: number[] = []; + if (!text.includes("](")) return { markdown: text, inserted }; + const parts: string[] = []; + let copied = 0; + scanMarkdownLinkDestinations(text, ({ hrefStart, hrefEnd, spaced }) => { + if (!spaced) return; + parts.push(text.slice(copied, hrefStart), "<", text.slice(hrefStart, hrefEnd), ">"); + inserted.push(hrefStart + inserted.length, hrefEnd + inserted.length + 1); + copied = hrefEnd; + }); + if (inserted.length === 0) return { markdown: text, inserted }; + parts.push(text.slice(copied)); + return { markdown: parts.join(""), inserted }; +} + export function resolveMarkdownFileLinkTarget( href: string | undefined, cwd?: string, diff --git a/packages/shared/src/markdownPipeline.test.ts b/packages/shared/src/markdownPipeline.test.ts index 769cc60015329..2e3cc42a00e78 100644 --- a/packages/shared/src/markdownPipeline.test.ts +++ b/packages/shared/src/markdownPipeline.test.ts @@ -613,6 +613,14 @@ it("keeps uppercase FILE link and image URLs by lowercasing the scheme before sa expect(chatMarkdownImageSources(markdown)).toHaveLength(4); }); +it("finds images whose bare absolute path destinations contain spaces", () => { + expect( + chatMarkdownImageSources( + String.raw`![plot](/Users/me/My Plots/plot.png) ![shot](C:\Users\First Last\shot.png)`, + ), + ).toEqual(["/Users/me/My%20Plots/plot.png", "C:%5CUsers%5CFirst%20Last%5Cshot.png"]); +}); + it("keeps raw and percent-encoded Windows drive file links through the shared Markdown sanitizer", () => { const processor = unified() .use(remarkParse) diff --git a/packages/shared/src/markdownPipeline.ts b/packages/shared/src/markdownPipeline.ts index f6ee212c19cf5..4479bce8cb4cf 100644 --- a/packages/shared/src/markdownPipeline.ts +++ b/packages/shared/src/markdownPipeline.ts @@ -29,6 +29,7 @@ import { import { remarkCodexDirectives } from "./codexMarkdownDirectives.ts"; import { absoluteFilePathMatches, + markdownWithSpacedPathDestinations, SCRIPT_PUNCTUATION, scriptPunctuationAfterAscii, } from "./markdownLinks.ts"; @@ -748,7 +749,9 @@ export function chatMarkdownImageSources(markdown: string): Array { } node.children?.forEach(visit); }; - visit(imageSourceProcessor.runSync(imageSourceProcessor.parse(markdown)) as ImageSourceNode); + // Clients render spaced path destinations as images, so guest media grants must read them too. + const source = markdownWithSpacedPathDestinations(markdown).markdown; + visit(imageSourceProcessor.runSync(imageSourceProcessor.parse(source)) as ImageSourceNode); return sources; }