Skip to content
TypeScript

fix(chat): repair unclosed local file links in assistant responses (#15520)

maria0ce43a4eea2f
diff --git a/apps/mobile/src/features/threads/ThreadFeed.tsx b/apps/mobile/src/features/threads/ThreadFeed.tsx
index 0f55d36c011..9d824d006c6 100644
--- a/apps/mobile/src/features/threads/ThreadFeed.tsx
+++ b/apps/mobile/src/features/threads/ThreadFeed.tsx
@@ -10,6 +10,7 @@ import { KeyboardAwareLegendList } from "@legendapp/list/keyboard";
import { useViewabilityAmount, type LegendListRef } from "@legendapp/list/react-native";
import { scopeThreadRef } from "@t3tools/client-runtime/environment";
import { resolveUserMessagePresentation } from "@t3tools/client-runtime/user-message";
+import { repairMarkdownFileLinks } from "@t3tools/client-runtime/repair-markdown-file-links";
import { canForkProjectedAssistantItem } from "@t3tools/client-runtime/state/thread-workflows";
import {
type OrchestrationMessageContext,
@@ -907,7 +908,17 @@ const AssistantMarkdownContent = memo(function AssistantMarkdownContent(props: {
readonly skills?: ReadonlyArray<SelectableMarkdownSkill> | undefined;
}) {
const segments = useMemo(
- () => splitCodexArtifactTemplateMarkdown(props.markdown),
+ () =>
+ splitCodexArtifactTemplateMarkdown(props.markdown).map((segment) =>
+ segment.kind === "markdown"
+ ? {
+ ...segment,
+ markdown: renderCodexFileCitationsAsMarkdown(
+ repairMarkdownFileLinks(segment.markdown),
+ ),
+ }
+ : segment,
+ ),
[props.markdown],
);
@@ -923,7 +934,7 @@ const AssistantMarkdownContent = memo(function AssistantMarkdownContent(props: {
}
if (segment.markdown.trim().length === 0) return null;
- const markdown = renderCodexFileCitationsAsMarkdown(segment.markdown);
+ const markdown = segment.markdown;
return hasNativeSelectableMarkdownText() ? (
<SelectableMarkdownText
key={`markdown:${segment.sourceOffset}`}
diff --git a/apps/web/src/components/chat/MessagesTimeline.tsx b/apps/web/src/components/chat/MessagesTimeline.tsx
index 45940bca888..3dbf5c8de28 100644
--- a/apps/web/src/components/chat/MessagesTimeline.tsx
+++ b/apps/web/src/components/chat/MessagesTimeline.tsx
@@ -35,6 +35,7 @@ import { parseScopedThreadKey, scopeThreadRef } from "@t3tools/client-runtime/en
import { useAtomValue } from "@effect/atom-react";
import { environmentThreadDetails } from "../../state/threads";
import { resolveUserMessagePresentation } from "@t3tools/client-runtime/user-message";
+import { repairMarkdownFileLinks } from "@t3tools/client-runtime/repair-markdown-file-links";
import { Link } from "@tanstack/react-router";
import { canForkProjectedAssistantItem } from "@t3tools/client-runtime/state/thread-workflows";
import { notificationChildThreadId } from "@t3tools/client-runtime/state/thread-execution";
@@ -2494,6 +2495,7 @@ function AttemptFoldTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "at
function AssistantTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "message" }> }) {
const ctx = use(TimelineRowCtx);
const messageText = row.message.text || (row.message.streaming ? "" : "(empty response)");
+ const renderedText = useMemo(() => repairMarkdownFileLinks(messageText), [messageText]);
return (
<>
@@ -2507,7 +2509,7 @@ function AssistantTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "mess
listRef={ctx.listRef}
>
<ChatMarkdown
- text={messageText}
+ text={renderedText}
cwd={ctx.markdownCwd}
threadRef={ctx.threadRef ?? undefined}
isStreaming={Boolean(row.message.streaming)}
diff --git a/packages/client-runtime/package.json b/packages/client-runtime/package.json
index b812495cb3e..3983df3e109 100644
--- a/packages/client-runtime/package.json
+++ b/packages/client-runtime/package.json
@@ -55,6 +55,10 @@
"types": "./src/markdownLinks.ts",
"default": "./src/markdownLinks.ts"
},
+ "./repair-markdown-file-links": {
+ "types": "./src/repairMarkdownFileLinks.ts",
+ "default": "./src/repairMarkdownFileLinks.ts"
+ },
"./media-reference": {
"types": "./src/mediaReference.ts",
"default": "./src/mediaReference.ts"
diff --git a/packages/client-runtime/src/markdownLinks.test.ts b/packages/client-runtime/src/markdownLinks.test.ts
index b6e52e4534a..2be85a9333f 100644
--- a/packages/client-runtime/src/markdownLinks.test.ts
+++ b/packages/client-runtime/src/markdownLinks.test.ts
@@ -1,4 +1,6 @@
import { describe, expect, it } from "vite-plus/test";
+import remarkParse from "remark-parse";
+import { unified } from "unified";
import {
fileBasename,
@@ -9,6 +11,116 @@ import {
splitFilePathPosition,
workspaceRelativeFilePath,
} from "./markdownLinks.ts";
+import { repairMarkdownFileLinks } from "./repairMarkdownFileLinks.ts";
+import {
+ renderCodexDirectivesForCopy,
+ renderCodexFileCitationsAsMarkdown,
+ splitCodexArtifactTemplateMarkdown,
+} from "./codexMarkdownDirectives.ts";
+
+describe("repairMarkdownFileLinks", () => {
+ it.each([
+ "CONTRIBUTING.md",
+ "local/path/file.md",
+ "docs/My Folder/file.md",
+ "./scripts/deploy",
+ "~/notes/today.md",
+ "/home/me/My Folder/file.md",
+ "/tmp/reports/",
+ "C:\\Users\\me\\My Folder\\file.md",
+ "file:///home/me/file.md",
+ "src/main.ts:12:5",
+ ])("repairs a complete local destination: %s", (path) => {
+ const source = `- [file](<${path})`;
+ const rendered = repairMarkdownFileLinks(source);
+ expect(rendered).toBe(`- [file](<${path}>)`);
+ expect(unified().use(remarkParse).parse(rendered).children[0]).toMatchObject({
+ type: "list",
+ children: [{ children: [{ children: [{ type: "link" }] }] }],
+ });
+ expect(repairMarkdownFileLinks(rendered)).toBe(rendered);
+ });
+
+ it.each([
+ "ordinary prose",
+ "[file](<CONTRIBUTING.md>)",
+ "[site](<https://example.com/docs)",
+ "[route](</chat/settings)",
+ "[prose](<not a file)",
+ "[file](<src/main.ts",
+ "[file](<src/main.ts>",
+ "[file](<./file(one).md)",
+ "[file](<./file.md))",
+ "[file](<./file)name.md)",
+ "[file](<./file\\).md)",
+ "![image](<./file.png)",
+ "\\\\![image](<./file.png)",
+ "\\\\\\\\![image](<./file.png)",
+ "\\[file](<./file.md)",
+ "\\\\\\[file](<./file.md)",
+ "`[file](<./file.md)`",
+ "``[file](<./file.md)``",
+ "```md\n[file](<./file.md)\n```",
+ "~~~md\n[file](<./file.md)\n~~~",
+ " [file](<./file.md)",
+ "<div>\n[file](<./file.md)\n</div>",
+ "HTML <span>[file](<./file.md)</span>",
+ '<span title="[file](<./file.md)">text</span>',
+ "[outer [file](<./file.md)](https://example.com)",
+ "[outer [file](<./file.md)][ref]\n\n[ref]: https://example.com",
+ '[ref]: ./file.md "[file](<./other.md)"',
+ ':codex-file-citation{path="./[file](<./other.md)" purpose="output"}',
+ ':codex-file-citation{path="./[file](<./other.md)',
+ '::artifact-template{skill_name="artifact-template-example" skill_directory="/tmp/skills/example" display_name="[file](<./file.md)" artifact_kind="document"}',
+ '::artifact-template{display_name="[file](<./file.md)',
+ ])("preserves protected or uncertain syntax: %s", (source) => {
+ expect(repairMarkdownFileLinks(source)).toBe(source);
+ });
+
+ it("uses CommonMark backslash parity for link openers", () => {
+ expect(repairMarkdownFileLinks("\\\\[file](<./file.md)")).toBe("\\\\[file](<./file.md>)");
+ expect(repairMarkdownFileLinks("\\\\\\\\[file](<./file.md)")).toBe(
+ "\\\\\\\\[file](<./file.md>)",
+ );
+ expect(repairMarkdownFileLinks("\\![file](<./file.md)")).toBe("\\![file](<./file.md>)");
+ });
+
+ it("repairs ordinary segments after splitting mobile artifacts and preserves copy source", () => {
+ const link = "[file](<./file.md)";
+ const template =
+ '::artifact-template{skill_name="artifact-template-example" skill_directory="/tmp/skills/example" display_name="[file](<./file.md)" artifact_kind="document"}';
+ const citation = ':codex-file-citation{path="./report.md"}';
+ const source = `${link}\n\n${template}\n\n${citation}`;
+ const segments = splitCodexArtifactTemplateMarkdown(source);
+ const rendered = segments.map((segment) =>
+ segment.kind === "markdown"
+ ? {
+ ...segment,
+ markdown: renderCodexFileCitationsAsMarkdown(repairMarkdownFileLinks(segment.markdown)),
+ }
+ : segment,
+ );
+ expect(rendered[0]).toEqual({
+ kind: "markdown",
+ markdown: `${link.slice(0, -1)}>)\n\n`,
+ sourceOffset: 0,
+ });
+ expect(rendered[1]).toEqual(segments[1]);
+ expect(rendered[1]).toMatchObject({
+ kind: "artifact-template",
+ sourceOffset: link.length + 2,
+ template: { displayName: link, skillName: "artifact-template-example" },
+ });
+ expect(rendered[2]).toEqual({
+ kind: "markdown",
+ sourceOffset: source.indexOf("\n\n" + citation),
+ markdown: "\n\n[report.md](<./report.md>)",
+ });
+ expect(renderCodexDirectivesForCopy(source)).toBe(
+ `${link}\n\n${link} (Document template)\n\n[report.md](<./report.md>)`,
+ );
+ });
+});
describe("isMarkdownFileLinkLabel", () => {
it.each([
diff --git a/packages/client-runtime/src/repairMarkdownFileLinks.ts b/packages/client-runtime/src/repairMarkdownFileLinks.ts
new file mode 100644
index 00000000000..9c863ee26f9
--- /dev/null
+++ b/packages/client-runtime/src/repairMarkdownFileLinks.ts
@@ -0,0 +1,84 @@
+import remarkParse from "remark-parse";
+import { unified } from "unified";
+
+import { remarkCodexDirectives } from "./codexMarkdownDirectives.ts";
+import { parseMarkdownFileLink } from "./markdownLinks.ts";
+
+const parser = unified().use(remarkParse).use(remarkCodexDirectives).freeze();
+const CANDIDATE = /\[[^[\]\r\n]*\]\([ \t]*<([^<>()\r\n]+)\)/g;
+const PROTECTED = new Set([
+ "code",
+ "inlineCode",
+ "html",
+ "link",
+ "image",
+ "linkReference",
+ "imageReference",
+ "definition",
+ "textDirective",
+ "leafDirective",
+ "containerDirective",
+]);
+
+function isEscaped(source: string, offset: number): boolean {
+ let backslashes = 0;
+ while (offset > 0 && source[--offset] === "\\") backslashes += 1;
+ return backslashes % 2 === 1;
+}
+
+/** Closes only complete, unambiguous local-file destinations for assistant rendering. */
+export function repairMarkdownFileLinks(markdown: string): string {
+ if (!/\]\([ \t]*</.test(markdown)) return markdown;
+ const candidates = Array.from(markdown.matchAll(CANDIDATE)).filter((match) => {
+ const start = match.index;
+ const close = start + match[0].length - 1;
+ return (
+ !isEscaped(markdown, start) &&
+ !(markdown[start - 1] === "!" && !isEscaped(markdown, start - 1)) &&
+ !isEscaped(markdown, close) &&
+ (close + 1 === markdown.length || /[\s.,;:!?}\]*_~]/.test(markdown[close + 1] ?? "")) &&
+ parseMarkdownFileLink(match[1] ?? "") !== null
+ );
+ });
+ if (candidates.length === 0) return markdown;
+
+ const protectedRanges: Array<{ start: number; end: number }> = [];
+ interface Node {
+ type: string;
+ position?:
+ | { start: { offset?: number | undefined }; end: { offset?: number | undefined } }
+ | undefined;
+ children?: Node[] | undefined;
+ }
+ const visit = (node: Node, paragraph?: Node) => {
+ const containingParagraph = node.type === "paragraph" ? node : paragraph;
+ const sourceStart = node.position?.start.offset;
+ const sourceEnd = node.position?.end.offset;
+ const unfinishedDirective =
+ (node.type === "textDirective" && markdown[sourceEnd ?? -1] === "{") ||
+ (node.type === "text" &&
+ markdown.slice(sourceStart, sourceEnd).includes("::artifact-template{"));
+ if (PROTECTED.has(node.type) || unfinishedDirective) {
+ // Inline HTML and unfinished directive attributes can span separate text nodes.
+ const protectedNode =
+ node.type === "html" || unfinishedDirective ? (containingParagraph ?? node) : node;
+ const start = protectedNode.position?.start.offset;
+ const end = protectedNode.position?.end.offset;
+ if (start !== undefined && end !== undefined) protectedRanges.push({ start, end });
+ return;
+ }
+ node.children?.forEach((child) => visit(child, containingParagraph));
+ };
+ visit(parser.parse(markdown));
+
+ let rendered = "";
+ let cursor = 0;
+ for (const match of candidates) {
+ const start = match.index;
+ const end = start + match[0].length;
+ if (protectedRanges.some((range) => start < range.end && end > range.start)) continue;
+ rendered += markdown.slice(cursor, end - 1) + ">";
+ cursor = end - 1;
+ }
+ return rendered + markdown.slice(cursor);
+}