Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions apps/web/src/components/ChatMarkdown.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import {
CHAT_MARKDOWN_REMARK_PLUGINS,
CHAT_MARKDOWN_REMARK_PLUGINS_WITH_BREAKS,
CHAT_MARKDOWN_REHYPE_PLUGINS,
decodeMarkdownLinkEscapes,
remarkAssistantInsights,
} from "@t3tools/shared/markdownPipeline";
import { useAtomValue } from "@effect/atom-react";
Expand Down Expand Up @@ -471,6 +472,7 @@ function fileLinkSourcesKey(
): string {
const hrefs = extractMarkdownLinkHrefs(renderCodexInlineDirectivesAsMarkdown(text))
.filter((href) => !parseComposerContextHref(href))
.map(decodeMarkdownLinkEscapes)
.map(normalizeMarkdownLinkHrefKey)
.filter((href) => resolveMarkdownFileLinkMeta(href, cwd, imageBaseDir ?? cwd));
const spans = extractInlineCodeSpans(text).filter((span) =>
Expand Down
15 changes: 15 additions & 0 deletions packages/shared/src/markdownLinks.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -162,6 +162,21 @@ describe("extractMarkdownLinkHrefs", () => {
])("extracts links from incomplete and nested text", (markdown, hrefs) => {
expect(extractMarkdownLinkHrefs(markdown)).toEqual(hrefs);
});

it.each([
[
"[a](/x/app/(a)/page.tsx) [b](/x/app/(b)/page.tsx)",
["/x/app/(a)/page.tsx", "/x/app/(b)/page.tsx"],
],
['[a](/tmp/a(1).txt "title") after', ["/tmp/a(1).txt"]],
["[a](a(b(c))d) [b](ok)", ["a(b(c))d", "ok"]],
["[a](x\\)y) [b](x\\(y)", ["x\\)y", "x\\(y"]],
["[a](unclosed(paren) [b](ok)", ["ok"]],
["[a](" + "(".repeat(32) + "x" + ")".repeat(32) + ")", ["(".repeat(32) + "x" + ")".repeat(32)]],
["[a](" + "(".repeat(33) + "x" + ")".repeat(33) + ") [b](ok)", ["ok"]],
])("keeps balanced parentheses in a destination like the parser: %s", (markdown, hrefs) => {
expect(extractMarkdownLinkHrefs(markdown)).toEqual(hrefs);
});
});

describe("resolveMarkdownFileLinkTarget", () => {
Expand Down
29 changes: 26 additions & 3 deletions packages/shared/src/markdownLinks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -383,10 +383,33 @@ function markdownLinkTailScanner(markdown: string) {
};
}

// micromark's own nesting limit. It also keeps link scanning linear: a scan only runs past another
// link's opening parenthesis while that parenthesis counts toward this depth.
const MAX_BARE_DESTINATION_PAREN_DEPTH = 32;

function bareMarkdownLinkDestinationEnd(markdown: string, start: number): number | null {
const delimiter = /[\s()\\]/g;
delimiter.lastIndex = start;
let depth = 0;
while (true) {
const index = delimiter.exec(markdown)?.index ?? markdown.length;
const char = markdown[index];
if (char === "\\") {
if (/[()\\]/.test(markdown[index + 1] ?? "")) delimiter.lastIndex = index + 2;
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
} else if (char === "(") {
if (depth === MAX_BARE_DESTINATION_PAREN_DEPTH) return null;
depth += 1;
} else if (char === ")" && depth > 0) {
depth -= 1;
} else {
return depth === 0 ? index : null;
}
}
}

function markdownLinkDestinationScanner(markdown: string) {
const whitespaceEnd = markdownRunEndFinder(markdown, /\S/g);
const angleEnd = markdownRunEndFinder(markdown, /[>\n]/g);
const bareEnd = markdownRunEndFinder(markdown, /[\s)]/g);
// Separate caches keep scans moving forward when angle destinations fall back to bare ones.
const angleTail = markdownLinkTailScanner(markdown);
const bareTail = markdownLinkTailScanner(markdown);
Expand All @@ -400,8 +423,8 @@ function markdownLinkDestinationScanner(markdown: string) {
if (end !== null) return { hrefStart: hrefStart + 1, hrefEnd, end };
}
}
const hrefEnd = bareEnd(hrefStart);
if (hrefEnd === hrefStart) return null;
const hrefEnd = bareMarkdownLinkDestinationEnd(markdown, hrefStart);
if (hrefEnd === null || hrefEnd === hrefStart) return null;
const end = bareTail(hrefEnd);
return end === null ? null : { hrefStart, hrefEnd, end };
};
Expand Down
19 changes: 19 additions & 0 deletions packages/shared/src/markdownPipeline.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ import {
isWindowsDrivePathHref,
normalizeMarkdownLinkDestination,
} from "./markdownLinks.ts";
import { isWindowsAbsolutePath } from "./path.ts";
import { THREAD_LINK_PROTOCOL } from "./threadLinks.ts";

export { remarkEnableOrderedListNumbers } from "./markdownOrderedListNumbers.ts";
Expand Down Expand Up @@ -867,3 +868,21 @@ export function chatMarkdownImageSources(markdown: string): Array<string> {
visit(imageSourceProcessor.runSync(imageSourceProcessor.parse(markdown)) as ImageSourceNode);
return sources;
}

const linkDestinationProcessor = unified().use(remarkParse).use(remarkKeepWindowsPaths);

// An angle destination cannot hold an unescaped `<` or `>`, or end on a lone backslash.
const ANGLE_DESTINATION_CONTENT = /^(?:[^\\<>]|\\.)*$/;

/** Reads a destination from `extractMarkdownLinkHrefs` as the renderer's parser does. */
export function decodeMarkdownLinkEscapes(href: string): string {
// Only the parser knows character references, so destinations that may have one go through it.
if (href.includes("&")) {
// The extractor drops angle brackets, and only that form keeps an unmatched `)` in the path.
const destination = ANGLE_DESTINATION_CONTENT.test(href) ? `<${href}>` : href;
const paragraph = linkDestinationProcessor.parse(`[](${destination})`).children[0];
const link = paragraph?.type === "paragraph" ? paragraph.children[0] : undefined;
if (link?.type === "link") return link.url;
}
return isWindowsAbsolutePath(href) ? href : href.replace(/\\([!-/:-@[-`{-~])/g, "$1");
}
35 changes: 35 additions & 0 deletions packages/shared/src/threadFindText.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,41 @@ it("searches displayed prose and file-chip labels without hidden paths", () => {
"label main.ts · L3:C2",
]);
expect(assistantSegments("[label](src/main.ts#L3C2)")).toEqual(["label"]);
for (const text of [
"[a](/repo/app/(a)/page.tsx) and [b](/repo/app/(b)/page.tsx)",
String.raw`[a](/repo/app/\(a\)/page.tsx) and [b](/repo/app/\(b\)/page.tsx)`,
]) {
expect(assistantSegments(text, "/repo")).toEqual([
"a page.tsx · app/(a) and b page.tsx · app/(b)",
]);
}
expect(
assistantSegments(
String.raw`[a](C:\repo\.a\page.tsx) and [b](C:\repo\.b\page.tsx)`,
String.raw`C:\repo`,
),
).toEqual(["a page.tsx · repo/.a and b page.tsx · repo/.b"]);
expect(
assistantSegments(
String.raw`[a](C:\repo\.a\x&amp;y\page.tsx) and [b](C:\repo\.b\x&amp;y\page.tsx)`,
String.raw`C:\repo`,
),
).toEqual(["a page.tsx · .a/x&y and b page.tsx · .b/x&y"]);
expect(
assistantSegments("[a](/repo/a&amp;b/page.tsx) and [b](/repo/c&amp;d/page.tsx)", "/repo"),
).toEqual(["a page.tsx · repo/a&b and b page.tsx · repo/c&d"]);
expect(
assistantSegments("[a](</repo/a&b)/page.tsx>) and [b](</repo/c&d)/page.tsx>)", "/repo"),
).toEqual(["a page.tsx · repo/a&b) and b page.tsx · repo/c&d)"]);
expect(
assistantSegments("[a](/repo/a&b>c/page.tsx) and [b](/repo/c&d>e/page.tsx)", "/repo"),
).toEqual(["a page.tsx · repo/a&b>c and b page.tsx · repo/c&d>e"]);
expect(
assistantSegments(
String.raw`[a](</repo/a\<b &amp;c/page.tsx>) and [b](</repo/d\<e &amp;f/page.tsx>)`,
"/repo",
),
).toEqual(["a page.tsx · repo/a<b &c and b page.tsx · repo/d<e &f"]);
});

it("keeps fence paths literal and indexes file-chip labels in user messages", () => {
Expand Down
5 changes: 4 additions & 1 deletion packages/shared/src/threadFindText.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ import {
CHAT_MARKDOWN_REMARK_PLUGINS,
CHAT_MARKDOWN_REMARK_PLUGINS_WITH_BREAKS,
CHAT_USER_MARKDOWN_REMARK_PLUGINS,
decodeMarkdownLinkEscapes,
} from "./markdownPipeline.ts";

// Inline wrappers (including Shiki token spans) must not split a search phrase.
Expand Down Expand Up @@ -130,7 +131,9 @@ function markdownThreadFindText(
: processor;
const tree = renderer.runSync(renderer.parse(markdown), markdown);
const paths = [
...extractMarkdownLinkHrefs(renderCodexInlineDirectivesAsMarkdown(markdown)),
...extractMarkdownLinkHrefs(renderCodexInlineDirectivesAsMarkdown(markdown)).map(
decodeMarkdownLinkEscapes,
),
...extractInlineCodeSpans(markdown).flatMap((span) => inlineCodeFilePathCandidate(span) ?? []),
].flatMap((href) => {
const target = resolveMarkdownFileLinkTarget(href, cwd);
Expand Down
Loading