fix: special characters in markdown links

This commit is contained in:
Yash Singh committed 2026-05-28 12:28:24 -05:00
1 parent 4f0f24f055
commit 03a2e2729a
4 files changed
+189 -78

No files matched your search

@@ -34,8 +34,7 @@ describe("ChatMarkdown", () => {
});
it("rewrites file uri hrefs into direct paths before rendering", async () => {
const filePath =
"/Users/yashsingh/p/sco/claude-code-extract/src/utils/permissions/PermissionRule.ts";
const filePath = "/Users/lol/p/sco/claude-code-extract/src/utils/permissions/PermissionRule.ts";
const screen = await render(
<ChatMarkdown text={`[PermissionRule.ts](file://${filePath})`} cwd="/repo/project" />,
);
@@ -56,8 +55,7 @@ describe("ChatMarkdown", () => {
});
it("keeps line anchors working after rewriting file uri hrefs", async () => {
const filePath =
"/Users/yashsingh/p/sco/claude-code-extract/src/utils/permissions/PermissionRule.ts";
const filePath = "/Users/lol/p/sco/claude-code-extract/src/utils/permissions/PermissionRule.ts";
const screen = await render(
<ChatMarkdown text={`[PermissionRule.ts:1](file://${filePath}#L1)`} cwd="/repo/project" />,
);
@@ -77,9 +75,89 @@ describe("ChatMarkdown", () => {
}
});
it("opens markdown file links containing parentheses and square brackets", async () => {
const filePath = "/Users/lol/p/t3code/apps/web/src/routes/(chat)/[threadId].tsx";
const screen = await render(<ChatMarkdown text={`[route](${filePath})`} cwd="/repo/project" />);
try {
const link = page.getByRole("link", { name: "[threadId].tsx" });
await expect.element(link).toBeInTheDocument();
await link.click();
await vi.waitFor(() => {
expect(openInPreferredEditorMock).toHaveBeenCalledWith(expect.anything(), filePath);
});
} finally {
await screen.unmount();
}
});
it("opens encoded markdown file links containing parentheses and square brackets", async () => {
const targetPath = "/repo/project/apps/web/src/routes/(chat)/[threadId].tsx";
const screen = await render(
<ChatMarkdown
text="[route](apps/web/src/routes/%28chat%29/%5BthreadId%5D.tsx)"
cwd="/repo/project"
/>,
);
try {
const link = page.getByRole("link", { name: "[threadId].tsx" });
await expect.element(link).toBeInTheDocument();
await link.click();
await vi.waitFor(() => {
expect(openInPreferredEditorMock).toHaveBeenCalledWith(expect.anything(), targetPath);
});
} finally {
await screen.unmount();
}
});
it("opens angle-bracketed markdown file links", async () => {
const filePath = "/Users/lol/p/t3code/apps/web/src/routes/(chat)/My Route [thread].tsx";
const screen = await render(
<ChatMarkdown text={`[route](<${filePath}>)`} cwd="/repo/project" />,
);
try {
const link = page.getByRole("link", { name: "My Route [thread].tsx" });
await expect.element(link).toBeInTheDocument();
await link.click();
await vi.waitFor(() => {
expect(openInPreferredEditorMock).toHaveBeenCalledWith(expect.anything(), filePath);
});
} finally {
await screen.unmount();
}
});
it("opens Windows drive markdown file links", async () => {
const targetPath = "D:/Users/lol/t3code/apps/web/src/routes/(chat)/[threadId].tsx:42";
const screen = await render(
<ChatMarkdown text={`[route](${targetPath})`} cwd="/repo/project" />,
);
try {
const link = page.getByRole("link", { name: "[threadId].tsx · L42" });
await expect.element(link).toBeInTheDocument();
await link.click();
await vi.waitFor(() => {
expect(openInPreferredEditorMock).toHaveBeenCalledWith(expect.anything(), targetPath);
});
} finally {
await screen.unmount();
}
});
it("shows column information inline when present", async () => {
const filePath =
"/Users/yashsingh/p/sco/claude-code-extract/src/utils/permissions/PermissionRule.ts";
const filePath = "/Users/lol/p/sco/claude-code-extract/src/utils/permissions/PermissionRule.ts";
const screen = await render(
<ChatMarkdown text={`[PermissionRule.ts](file://${filePath}#L1C7)`} cwd="/repo/project" />,
);
@@ -103,8 +181,8 @@ describe("ChatMarkdown", () => {
});
it("disambiguates duplicate file basenames inline", async () => {
const firstPath = "/Users/yashsingh/p/t3code/apps/web/src/components/chat/MessagesTimeline.tsx";
const secondPath = "/Users/yashsingh/p/t3code/apps/web/src/components/MessagesTimeline.tsx";
const firstPath = "/Users/lol/p/t3code/apps/web/src/components/chat/MessagesTimeline.tsx";
const secondPath = "/Users/lol/p/t3code/apps/web/src/components/MessagesTimeline.tsx";
const screen = await render(
<ChatMarkdown
text={`See [MessagesTimeline.tsx](file://${firstPath}) and [MessagesTimeline.tsx](file://${secondPath}).`}
+65 -49
View File
@@ -29,8 +29,8 @@ import { fnv1a32 } from "../lib/diffRendering";
import { LRUCache } from "../lib/lruCache";
import { useTheme } from "../hooks/useTheme";
import {
normalizeMarkdownLinkDestination,
resolveMarkdownFileLinkMeta,
resolveMarkdownFileLinkTarget,
rewriteMarkdownFileUriHref,
} from "../markdown-links";
import { readLocalApi } from "../localApi";
@@ -286,11 +286,20 @@ interface MarkdownFileLinkProps {
className?: string | undefined;
}
const MARKDOWN_LINK_HREF_PATTERN = /\[[^\]]*]\(([^)\s]+)(?:\s+["'][^"']*["'])?\)/g;
const MARKDOWN_FILE_LINK_CLASS_NAME =
"chat-markdown-file-link relative top-[2px] max-w-full no-underline";
const MARKDOWN_FILE_LINK_ICON_CLASS_NAME = "chat-markdown-file-link-icon size-3.5 shrink-0";
const MARKDOWN_FILE_LINK_LABEL_CLASS_NAME = "chat-markdown-file-link-label truncate";
const FILE_LINK_PARENT_SUFFIX_DATA_ATTR = "data-file-link-parent-suffix";
interface MarkdownAstNode {
type?: string;
url?: string;
children?: MarkdownAstNode[];
data?: {
hProperties?: Record<string, unknown>;
};
}
function pathParentSegments(path: string): string[] {
const normalized = path.replaceAll("\\", "/");
@@ -352,19 +361,42 @@ function buildFileLinkParentSuffixByPath(filePaths: ReadonlyArray<string>): Map<
return suffixByPath;
}
function extractMarkdownLinkHrefs(text: string): string[] {
const hrefs: string[] = [];
for (const match of text.matchAll(MARKDOWN_LINK_HREF_PATTERN)) {
const href = match[1]?.trim();
if (!href) continue;
hrefs.push(href);
}
return hrefs;
}
function createFileLinkDisambiguationPlugin(cwd: string | undefined) {
return () => (tree: MarkdownAstNode) => {
const fileLinks: Array<{
node: MarkdownAstNode;
meta: NonNullable<ReturnType<typeof resolveMarkdownFileLinkMeta>>;
}> = [];
function normalizeMarkdownLinkHrefKey(href: string): string {
const normalizedHref = normalizeMarkdownLinkDestination(href);
return rewriteMarkdownFileUriHref(normalizedHref) ?? normalizedHref;
const visit = (node: MarkdownAstNode) => {
if (node.type === "link" && typeof node.url === "string") {
const meta = resolveMarkdownFileLinkMeta(node.url, cwd);
if (meta) {
fileLinks.push({ node, meta });
}
}
for (const child of node.children ?? []) {
visit(child);
}
};
visit(tree);
const suffixByPath = buildFileLinkParentSuffixByPath(
fileLinks.map((fileLink) => fileLink.meta.filePath),
);
for (const { node, meta } of fileLinks) {
const parentSuffix = suffixByPath.get(meta.filePath);
if (!parentSuffix) continue;
node.data = {
...node.data,
hProperties: {
...node.data?.hProperties,
[FILE_LINK_PARENT_SUFFIX_DATA_ATTR]: parentSuffix,
},
};
}
};
}
const MarkdownFileLink = memo(function MarkdownFileLink({
@@ -520,28 +552,16 @@ function ChatMarkdown({
}: ChatMarkdownProps) {
const { resolvedTheme } = useTheme();
const diffThemeName = resolveDiffThemeName(resolvedTheme);
const markdownFileLinkMetaByHref = useMemo(() => {
const metaByHref = new Map<
string,
NonNullable<ReturnType<typeof resolveMarkdownFileLinkMeta>>
>();
for (const href of extractMarkdownLinkHrefs(text)) {
const normalizedHref = normalizeMarkdownLinkHrefKey(href);
if (metaByHref.has(normalizedHref)) continue;
const meta = resolveMarkdownFileLinkMeta(normalizedHref, cwd);
if (meta) {
metaByHref.set(normalizedHref, meta);
}
}
return metaByHref;
}, [cwd, text]);
const fileLinkParentSuffixByPath = useMemo(() => {
const filePaths = [...markdownFileLinkMetaByHref.values()].map((meta) => meta.filePath);
return buildFileLinkParentSuffixByPath(filePaths);
}, [markdownFileLinkMetaByHref]);
const markdownUrlTransform = useCallback((href: string) => {
return rewriteMarkdownFileUriHref(href) ?? defaultUrlTransform(href);
}, []);
const remarkPlugins = useMemo(() => [remarkGfm, createFileLinkDisambiguationPlugin(cwd)], [cwd]);
const markdownUrlTransform = useCallback(
(href: string) => {
return (
rewriteMarkdownFileUriHref(href) ??
(resolveMarkdownFileLinkTarget(href, cwd) ? href : defaultUrlTransform(href))
);
},
[cwd],
);
const markdownComponents = useMemo<Components>(
() => ({
p({ node: _node, children, ...props }) {
@@ -551,15 +571,18 @@ function ChatMarkdown({
return <li {...props}>{renderSkillInlineMarkdownChildren(children, skills)}</li>;
},
a({ node: _node, href, ...props }) {
const normalizedHref = href ? normalizeMarkdownLinkHrefKey(href) : "";
const fileLinkMeta = normalizedHref ? markdownFileLinkMetaByHref.get(normalizedHref) : null;
const fileLinkMeta = href ? resolveMarkdownFileLinkMeta(href, cwd) : null;
if (!fileLinkMeta) {
return <a {...props} href={href} target="_blank" rel="noopener noreferrer" />;
}
const parentSuffix = fileLinkParentSuffixByPath.get(fileLinkMeta.filePath);
const anchorProps = props as typeof props & Record<string, unknown>;
const parentSuffix =
typeof anchorProps[FILE_LINK_PARENT_SUFFIX_DATA_ATTR] === "string"
? anchorProps[FILE_LINK_PARENT_SUFFIX_DATA_ATTR]
: undefined;
const labelParts = [fileLinkMeta.basename];
if (typeof parentSuffix === "string" && parentSuffix.length > 0) {
if (parentSuffix) {
labelParts.push(parentSuffix);
}
if (fileLinkMeta.line) {
@@ -602,20 +625,13 @@ function ChatMarkdown({
);
},
}),
[
diffThemeName,
fileLinkParentSuffixByPath,
isStreaming,
markdownFileLinkMetaByHref,
resolvedTheme,
skills,
],
[diffThemeName, cwd, isStreaming, resolvedTheme, skills],
);
return (
<div className="chat-markdown w-full min-w-0 text-sm leading-relaxed text-foreground/80">
<ReactMarkdown
remarkPlugins={[remarkGfm]}
remarkPlugins={remarkPlugins}
components={markdownComponents}
urlTransform={markdownUrlTransform}
>
+23 -14
View File
@@ -6,6 +6,14 @@ import {
rewriteMarkdownFileUriHref,
} from "./markdown-links";
describe("normalizeMarkdownLinkDestination", () => {
it("unescapes markdown punctuation when normalizing destinations", () => {
expect(
resolveMarkdownFileLinkTarget("apps/web/src/routes/\\(chat\\)/\\[id\\].tsx", "/repo"),
).toBe("/repo/apps/web/src/routes/(chat)/[id].tsx");
});
});
describe("rewriteMarkdownFileUriHref", () => {
it("rewrites file uri hrefs into direct path hrefs", () => {
expect(rewriteMarkdownFileUriHref("file:///Users/julius/project/src/main.ts#L42")).toBe(
@@ -26,12 +34,6 @@ describe("rewriteMarkdownFileUriHref", () => {
),
).toBe("D:/Programme/t3code/apps/web/src/components/chat/OpenInPicker.tsx#L69");
});
it("unwraps angle-bracketed file uri hrefs", () => {
expect(
rewriteMarkdownFileUriHref(" <file:///D:/Programme/t3code/apps/web/src/markdown-links.ts> "),
).toBe("D:/Programme/t3code/apps/web/src/markdown-links.ts");
});
});
describe("resolveMarkdownFileLinkTarget", () => {
@@ -59,6 +61,21 @@ describe("resolveMarkdownFileLinkTarget", () => {
);
});
it("resolves relative paths with route group and dynamic segment characters", () => {
expect(
resolveMarkdownFileLinkTarget("apps/web/src/routes/(chat)/[threadId].tsx", "/repo/project"),
).toBe("/repo/project/apps/web/src/routes/(chat)/[threadId].tsx");
});
it("resolves encoded route group and dynamic segment characters", () => {
expect(
resolveMarkdownFileLinkTarget(
"apps/web/src/routes/%28chat%29/%5BthreadId%5D.tsx",
"/repo/project",
),
).toBe("/repo/project/apps/web/src/routes/(chat)/[threadId].tsx");
});
it("maps #L line anchors to editor line suffixes", () => {
expect(resolveMarkdownFileLinkTarget("/Users/julius/project/src/main.ts#L42C7")).toBe(
"/Users/julius/project/src/main.ts:42:7",
@@ -106,14 +123,6 @@ describe("resolveMarkdownFileLinkTarget", () => {
).toBe("D:/Programme/t3code/apps/web/src/components/chat/OpenInPicker.tsx:69");
});
it("resolves angle-bracketed windows drive paths", () => {
expect(
resolveMarkdownFileLinkTarget(
"</D:/Programme/t3code/apps/web/src/components/ChatMarkdown.tsx:1>",
),
).toBe("D:/Programme/t3code/apps/web/src/components/ChatMarkdown.tsx:1");
});
it("does not treat app routes as file links", () => {
expect(resolveMarkdownFileLinkTarget("/chat/settings")).toBeNull();
});
+15 -7
View File
@@ -5,8 +5,6 @@ const WINDOWS_DRIVE_PATH_PATTERN = /^[A-Za-z]:[\\/]/;
const WINDOWS_UNC_PATH_PATTERN = /^\\\\/;
const EXTERNAL_SCHEME_PATTERN = /^([A-Za-z][A-Za-z0-9+.-]*):(.*)$/;
const RELATIVE_PATH_PREFIX_PATTERN = /^(~\/|\.{1,2}\/)/;
const RELATIVE_FILE_PATH_PATTERN = /^[A-Za-z0-9._-]+(?:\/[A-Za-z0-9._-]+)+(?::\d+){0,2}$/;
const RELATIVE_FILE_NAME_PATTERN = /^[A-Za-z0-9._-]+\.[A-Za-z0-9_-]+(?::\d+){0,2}$/;
const POSITION_SUFFIX_PATTERN = /:\d+(?::\d+)?$/;
const POSITION_ONLY_PATTERN = /^\d+(?::\d+)?$/;
const POSIX_FILE_ROOT_PREFIXES = [
@@ -39,12 +37,10 @@ function safeDecode(value: string): string {
}
}
function unwrapMarkdownLinkDestination(value: string): string {
return value.startsWith("<") && value.endsWith(">") ? value.slice(1, -1) : value;
}
const MARKDOWN_ESCAPE_PATTERN = /\\([!"#$%&'()*+,\-./:;<=>?@[\\\]^_`{|}~])/g;
export function normalizeMarkdownLinkDestination(value: string): string {
return unwrapMarkdownLinkDestination(value.trim());
return value.trim().replace(MARKDOWN_ESCAPE_PATTERN, "$1");
}
function stripSearchAndHash(value: string): { path: string; hash: string } {
@@ -112,7 +108,19 @@ function isLikelyPathCandidate(path: string): boolean {
if (WINDOWS_DRIVE_PATH_PATTERN.test(path) || WINDOWS_UNC_PATH_PATTERN.test(path)) return true;
if (RELATIVE_PATH_PREFIX_PATTERN.test(path)) return true;
if (path.startsWith("/")) return looksLikePosixFilesystemPath(path);
return RELATIVE_FILE_PATH_PATTERN.test(path) || RELATIVE_FILE_NAME_PATTERN.test(path);
const { path: actualPath } = splitPathAndPosition(path);
if (actualPath.length === 0) return false;
if (["\0", "\r", "\n", '"', "'", "`", "<", ">"].some((char) => actualPath.includes(char))) {
return false;
}
const normalizedPath = actualPath.replaceAll("\\", "/");
const segments = normalizedPath.split("/");
if (segments.length > 1) {
return segments.every((segment) => segment.length > 0);
}
return /\.[A-Za-z0-9_-]+$/.test(actualPath);
}
function isRelativePath(path: string): boolean {