Skip to content

Commit af28467

Browse files
fix(mobile): reference links resolve across folds and artifact cards in chat replies (#36304)
1 parent 96a4d2f commit af28467

3 files changed

Lines changed: 137 additions & 11 deletions

File tree

‎apps/mobile/src/features/threads/ThreadFeed.tsx‎

Lines changed: 21 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -150,6 +150,7 @@ import { scopedThreadKey } from "../../lib/scopedEntities";
150150
import { copyTextWithHaptic } from "../../lib/copyTextWithHaptic";
151151
import { downloadAndShareAttachment } from "../../lib/attachmentDownload";
152152
import { splitMarkdownDetails } from "../../lib/markdownDetails";
153+
import { markdownReferenceDefinitions, withReferenceDefinitions } from "../../lib/markdownDocument";
153154
import { hasWideMarkdownBlock } from "../../lib/wideMarkdownBlocks";
154155
import {
155156
SelectableMarkdownText,
@@ -1174,22 +1175,29 @@ const AssistantMarkdownContent = memo(function AssistantMarkdownContent(props: {
11741175
// Folds split first, so an artifact card inside a fold stays inside it.
11751176
function AssistantMarkdownBlocks(props: {
11761177
readonly markdown: string;
1178+
/** The reply's reference definitions, passed down by the enclosing fold. */
1179+
readonly definitions?: ReadonlyArray<string> | undefined;
11771180
readonly markdownStyles: MarkdownStyleSet;
11781181
readonly linkHandlers: MarkdownLinkHandlers;
11791182
readonly onUseArtifactTemplate?: ((template: CodexArtifactTemplate) => void) | undefined;
11801183
readonly renderImage: MarkdownImageRenderer;
11811184
readonly skills?: ReadonlyArray<SelectableMarkdownSkill> | undefined;
11821185
readonly models: ReturnType<typeof useModelMentions>;
11831186
}) {
1184-
const blocks = useMemo(
1185-
() =>
1186-
splitMarkdownDetails(props.markdown).map((block) =>
1187-
block.kind === "details"
1188-
? block
1189-
: { ...block, segments: splitCodexArtifactTemplateMarkdown(block.markdown) },
1190-
),
1191-
[props.markdown],
1192-
);
1187+
const { blocks, definitions } = useMemo(() => {
1188+
const blocks = splitMarkdownDetails(props.markdown).map((block) =>
1189+
block.kind === "details"
1190+
? block
1191+
: { ...block, segments: splitCodexArtifactTemplateMarkdown(block.markdown) },
1192+
);
1193+
const [first] = blocks;
1194+
// A reply rendered as one document resolves its own references; skip the extra parse.
1195+
const whole = blocks.length === 1 && first?.kind === "markdown" && first.segments.length === 1;
1196+
return {
1197+
blocks,
1198+
definitions: props.definitions ?? (whole ? [] : markdownReferenceDefinitions(props.markdown)),
1199+
};
1200+
}, [props.markdown, props.definitions]);
11931201
return blocks.map((block) => {
11941202
if (block.kind === "details") {
11951203
return (
@@ -1198,7 +1206,7 @@ function AssistantMarkdownBlocks(props: {
11981206
summary={block.summary}
11991207
initiallyOpen={block.open}
12001208
>
1201-
<AssistantMarkdownBlocks {...props} markdown={block.body} />
1209+
<AssistantMarkdownBlocks {...props} markdown={block.body} definitions={definitions} />
12021210
</MarkdownDetailsFold>
12031211
);
12041212
}
@@ -1217,7 +1225,9 @@ function AssistantMarkdownBlocks(props: {
12171225
return (
12181226
<SelectableMarkdownText
12191227
key={`markdown:${offset}`}
1220-
markdown={renderCodexInlineDirectivesAsMarkdown(segment.markdown)}
1228+
markdown={renderCodexInlineDirectivesAsMarkdown(
1229+
withReferenceDefinitions(segment.markdown, definitions),
1230+
)}
12211231
skills={props.skills}
12221232
models={props.models}
12231233
textStyle={props.markdownStyles.nativeTextStyle}

‎apps/mobile/src/lib/markdownDetails.test.ts‎

Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,33 @@
11
import { describe, expect, it } from "vite-plus/test";
22

33
import { splitMarkdownDetails } from "./markdownDetails";
4+
import {
5+
markdownForNativeParsing,
6+
markdownReferenceDefinitions,
7+
withReferenceDefinitions,
8+
} from "./markdownDocument";
9+
import { parseMarkdown } from "react-native-enriched-markdown/src/web/parseMarkdown";
10+
11+
type NativeNode = Awaited<ReturnType<typeof parseMarkdown>>;
12+
13+
/** Where the native parser sends each link and image in one rendered fragment of a reply. */
14+
async function referenceDestinations(reply: string, pick: number) {
15+
const segment = splitMarkdownDetails(reply)[pick];
16+
const fragment = segment?.kind === "details" ? segment.body : (segment?.markdown ?? "");
17+
const urls: Array<string | undefined> = [];
18+
const visit = (node: NativeNode) => {
19+
if (node.type === "Link" || node.type === "Image") urls.push(node.attributes?.url);
20+
node.children?.forEach(visit);
21+
};
22+
visit(
23+
await parseMarkdown(
24+
markdownForNativeParsing(
25+
withReferenceDefinitions(fragment, markdownReferenceDefinitions(reply)),
26+
),
27+
),
28+
);
29+
return urls;
30+
}
431

532
describe("splitMarkdownDetails", () => {
633
// regression: #28059 mobile chat showed every <details> fold open
@@ -78,3 +105,57 @@ describe("splitMarkdownDetails", () => {
78105
).toMatchObject([{ kind: "details", open: false }]);
79106
});
80107
});
108+
109+
describe("withReferenceDefinitions", () => {
110+
it("resolves a fragment's references from the whole reply, its own definitions first", async () => {
111+
const fold = "\n\n<details><summary>A</summary>a</details>\n\n";
112+
for (const [reply, pick, expected] of [
113+
// Into a fold, with an escaped label and a Windows destination kept as written.
114+
[
115+
"<details>\n<summary>A</summary>\n\n[config][c] ![B][a\\]b]\n\n</details>\n\n[c]: C:\\work\\.t3\\settings.json\n[a\\]b]: https://example.com/a",
116+
0,
117+
["C:\\work\\.t3\\settings.json", "https://example.com/a"],
118+
],
119+
// Out of a fold.
120+
[
121+
"See [d].\n\n<details>\n<summary>A</summary>\n\n[d]: https://example.com\n\n</details>",
122+
0,
123+
["https://example.com"],
124+
],
125+
// A quoted definition that wraps onto continuation lines.
126+
[`See [d].${fold}> [d]:\n> https://example.com\n> "Title"`, 0, ["https://example.com"]],
127+
// A definition the compact HTML block hides from the reply's parse, with a label that wraps.
128+
[
129+
"See [the\n doc].\n\n<details><summary>A</summary>a</details>\n[The Doc]: https://example.com",
130+
0,
131+
["https://example.com"],
132+
],
133+
// A literal ">" in a wrapped label is part of the label, not a quote marker.
134+
[
135+
`[part rest] and [part > rest]${fold}[part\n > rest]: https://example.com/a\n\n[part rest]: https://example.com/b`,
136+
0,
137+
["https://example.com/b", "https://example.com/a"],
138+
],
139+
// A fragment's own definition wins, however the parser equates the two labels.
140+
[
141+
"[ x ]: https://outside.example\n\n<details>\n<summary>S</summary>\n\nSee [x].\n\n[X]: https://inside.example\n\n</details>",
142+
1,
143+
["https://inside.example"],
144+
],
145+
[
146+
"[SS]: https://outside.example\n\n<details>\n<summary>S</summary>\n\nSee [SS].\n\n[\u00df]: https://inside.example\n\n</details>",
147+
1,
148+
["https://inside.example"],
149+
],
150+
] as const) {
151+
expect(await referenceDestinations(reply, pick)).toEqual(expected);
152+
}
153+
});
154+
155+
it("leaves a fragment with nothing to resolve as written", () => {
156+
expect(withReferenceDefinitions("See [d].", [])).toBe("See [d].");
157+
expect(withReferenceDefinitions("Plain text.", ["[d]: https://example.com"])).toBe(
158+
"Plain text.",
159+
);
160+
});
161+
});

‎apps/mobile/src/lib/markdownDocument.ts‎

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -284,6 +284,41 @@ export function markdownWithHtml(markdown: string): string {
284284
return applyMarkdownEdits(markdown, edits);
285285
}
286286

287+
/** Reference definitions as authored, one line each, so a Windows destination keeps its backslashes. */
288+
export function markdownReferenceDefinitions(markdown: string): string[] {
289+
if (!markdown.includes("]:")) return [];
290+
// Flattened as the renderer does it: a raw HTML block hides the definitions inside it.
291+
const flattened = markdownWithHtml(markdown);
292+
const definitions: string[] = [];
293+
const visit = (node: MarkdownNode, quotes: number) => {
294+
if (node.type === "definition") {
295+
// A wrapped definition drops its indent and the enclosing quotes' markers, not a literal ">".
296+
const wrap = new RegExp(`(?:\\r\\n|\\r|\\n)(?:[ \\t]*>){0,${quotes}}[ \\t]*`, "g");
297+
definitions.push(
298+
flattened.slice(node.position?.start.offset, node.position?.end.offset).replace(wrap, " "),
299+
);
300+
}
301+
if (!("children" in node)) return;
302+
for (const child of node.children) visit(child, quotes + (node.type === "blockquote" ? 1 : 0));
303+
};
304+
visit(parser.parse(flattened), 0);
305+
return definitions;
306+
}
307+
308+
/**
309+
* A reply split into folds and cards renders each fragment as its own document, so each one
310+
* carries the reply's definitions. The first definition of a label wins, so the fragment's own
311+
* lead: the renderer then prefers them by its own label matching, with none reimplemented here.
312+
*/
313+
export function withReferenceDefinitions(
314+
fragment: string,
315+
replyDefinitions: ReadonlyArray<string>,
316+
): string {
317+
if (replyDefinitions.length === 0 || !fragment.includes("[")) return fragment;
318+
const definitions = new Set([...markdownReferenceDefinitions(fragment), ...replyDefinitions]);
319+
return `${[...definitions].join("\n")}\n\n${fragment}`;
320+
}
321+
287322
// Start only at the beginning of a backtick run to avoid retrying every suffix.
288323
const INLINE_CODE_SPAN = /(?<!`)`+([^`\r\n]+)`+/g;
289324

0 commit comments

Comments
 (0)