Open History to see the last commit
1import type { Element, Root } from "hast";
2import { toHtml } from "hast-util-to-html";
3import { describe, expect, it } from "vite-plus/test";
4import { serializeComposerFileLink } from "@t3tools/shared/composerTrigger";
5import { searchableMessageSegments } from "@t3tools/shared/threadFindText";
6import {
7 encodeMarkdownLinkBoundaryWhitespace,
8 extractMarkdownLinkHrefs,
9 isMarkdownFileLinkLabel,
10} from "@t3tools/shared/markdownLinks";
11โ
12import {
13 decodeMarkdownLinkEscapes,
14 renderCodexDirectivesForCopy,
15 renderCodexInlineDirectivesAsMarkdown,
16} from "./markdownText";
17import {
18 codexDirectiveSources,
19 markdownReferenceDefinitions,
20 markdownTree,
21 wordsHast,
22 type WordsHastOptions,
23} from "./wordsHast";
24โ
25const ASSISTANT: WordsHastOptions = {
26 math: false,
27 breaks: false,
28 escapeHtml: false,
29 insights: false,
30 extensions: {},
31};
32โ
33const wordsHtml = (markdown: string, options: Partial<WordsHastOptions> = {}) =>
34 toHtml(wordsHast(markdown, { ...ASSISTANT, ...options }));
35โ
36it.each([
37 [String.raw`/tmp/a\&b/index.ts`, "/tmp/a&b/index.ts"],
38 ["/tmp/a\&b/index.ts", String.raw`/tmp/a\&b/index.ts`],
39 [String.raw`C:\work\&b\index.ts`, String.raw`C:\work\&b\index.ts`],
40])("decodes link destination %s as the renderer does", (href, expected) => {
41 const markdown = `[index.ts](${href})`;
42 const paragraph = markdownTree(markdown).children[0] as Element;
43 const anchor = paragraph.children[0] as Element;
44 expect(decodeURIComponent(String(anchor.properties.href))).toBe(expected);
45 expect(decodeMarkdownLinkEscapes(extractMarkdownLinkHrefs(markdown)[0]!)).toBe(expected);
46});
47โ
48it.each([
49 "</tmp/one/a.ts >",
50 "</tmp/one/a&.ts\t>",
51 "< /tmp/one/b.ts >",
52 "</tmp/one/a% รฉ[๐] b.ts >",
53])("keys angle destination %s by the href the renderer writes", (destination) => {
54 const markdown = `[a](${destination})`;
55 const anchor = (markdownTree(markdown).children[0] as Element).children[0] as Element;
56 const href = extractMarkdownLinkHrefs(markdown)[0]!;
57 expect(encodeMarkdownLinkBoundaryWhitespace(decodeMarkdownLinkEscapes(href), false)).toBe(
58 anchor.properties.href,
59 );
60});
61โ
62// The chat's syntax in the shapes agents and review bots write it, and raw HTML, with the HTML
63// remark and the chat's plugins rendered for it before Words replaced them.
64const CASES: ReadonlyArray<readonly [markdown: string, html: string]> = [
65 [
66 '<ol start="3">\n<li><a href="https://example.com/a">Alpha</a>\n<li><a href="https://example.com/b">Beta</a>\n</ol>',
67 '<ol start="3" dir="ltr">\n<li><a href="https://example.com/a">Alpha</a>\n</li><li><a href="https://example.com/b">Beta</a>\n</li></ol>',
68 ],
69 [
70 '<ul><li>Outer<ul><li><div><p><a href="https://example.com/a">Alpha</a><li>Beta</ul><li>Next</ul>',
71 '<ul dir="ltr"><li>Outer<ul><li><div><p><a href="https://example.com/a">Alpha</a></p></div></li><li>Beta</li></ul></li><li>Next</li></ul>',
72 ],
73 [
74 "<ul><li><blockquote><li>quoted</li></blockquote><li>next</ul>",
75 '<ul dir="ltr"><li><blockquote><li>quoted</li></blockquote></li><li>next</li></ul>',
76 ],
77 [
78 "| a | b |\n|:-|-:|\n| `x \\| y` | **2** |\n| 3 |",
79 '<table dir="ltr">\n<thead>\n<tr>\n<th align="left">a</th>\n<th align="right">b</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td align="left"><code data-inline-code="" dir="ltr">x | y</code></td>\n<td align="right"><strong>2</strong></td>\n</tr>\n<tr>\n<td align="left">3</td>\n<td align="right"></td>\n</tr>\n</tbody>\n</table>',
80 ],
81 [
82 "a | b\n--- | ---\n1 | 2\n\nnot a table",
83 '<table dir="ltr">\n<thead>\n<tr>\n<th>a</th>\n<th>b</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td>1</td>\n<td>2</td>\n</tr>\n</tbody>\n</table>\n<p dir="ltr">not a table</p>',
84 ],
85 [
86 "- [ ] open\n- [x] done\n- [X] spaced",
87 '<ul class="contains-task-list" dir="ltr">\n<li class="task-list-item"><input type="checkbox" disabled> open</li>\n<li class="task-list-item"><input type="checkbox" checked disabled> done</li>\n<li class="task-list-item"><input type="checkbox" checked disabled> spaced</li>\n</ul>',
88 ],
89 [
90 "- [ ] open\n\n- [x] done",
91 '<ul class="contains-task-list" dir="ltr">\n<li class="task-list-item">\n<p><input type="checkbox" disabled> open</p>\n</li>\n<li class="task-list-item">\n<p><input type="checkbox" checked disabled> done</p>\n</li>\n</ul>',
92 ],
93 [
94 "See www.example.com/a_(b), https://x.dev/path?q=1. and me@example.com!",
95 '<p dir="ltr">See <span class="has-[[data-slot=context-chip-label]]:whitespace-nowrap"><a href="http://www.example.com/a_(b)">www.example.com/a_(b)</a>,</span> <span class="has-[[data-slot=context-chip-label]]:whitespace-nowrap"><a href="https://x.dev/path?q=1">https://x.dev/path?q=1</a>.</span> and <span class="has-[[data-slot=context-chip-label]]:whitespace-nowrap"><a href="mailto:me@example.com">me@example.com</a>!</span></p>',
96 ],
97 [
98 "**ๅทฒ่ฟๅๆป้จๅทฅไฝใ**ๆฎ็พ่็คพๆฅ้\n\n**่ฑไผ่พพๅฎฃๅธๆขๅคๅ
ถๆป่ฃใCEO ๅ่ฃไบ่ๅกใ**ๅ
ฌๅธไบ็พๅฝๅฝๅฐๆถ้ด11ๆ23ๆฅๅๅธๅ
ฌๅ",
99 '<p dir="ltr"><strong>ๅทฒ่ฟๅๆป้จๅทฅไฝใ</strong>ๆฎ็พ่็คพๆฅ้</p>\n<p dir="ltr"><strong>่ฑไผ่พพๅฎฃๅธๆขๅคๅ
ถๆป่ฃใCEO ๅ่ฃไบ่ๅกใ</strong>ๅ
ฌๅธไบ็พๅฝๅฝๅฐๆถ้ด11ๆ23ๆฅๅๅธๅ
ฌๅ</p>',
100 ],
101 [
102 "See https://x.com/dimasike_ and ๅฏไปฅ็ไบ๏ผ**http://localhost:18780**๏ผๅทฒ้ๅฏ๏ผใ",
103 '<p dir="ltr">See <a href="https://x.com/dimasike_">https://x.com/dimasike_</a> and ๅฏไปฅ็ไบ๏ผ<strong><a href="http://localhost:18780">http://localhost:18780</a></strong>๏ผๅทฒ้ๅฏ๏ผใ</p>',
104 ],
105 [
106 "Angle <https://angle.dev> and (https://paren.dev/x)",
107 '<p dir="ltr">Angle <a href="https://angle.dev">https://angle.dev</a> and (<span class="has-[[data-slot=context-chip-label]]:whitespace-nowrap"><a href="https://paren.dev/x">https://paren.dev/x</a>)</span></p>',
108 ],
109 [
110 "Footnote[^1] and again[^1], unknown[^2].\n\n[^1]: The note\n continues.",
111 '<p dir="ltr">Footnote<sup><a href="#user-content-fn-1" id="user-content-user-content-fnref-1" data-footnote-ref="" aria-describedby="user-content-footnote-label">1</a></sup> and again<sup><a href="#user-content-fn-1" id="user-content-user-content-fnref-1-2" data-footnote-ref="" aria-describedby="user-content-footnote-label">1</a></sup>, unknown[^2].</p>\n<section data-footnotes="" class="footnotes" dir="ltr"><h2 class="sr-only" id="user-content-footnote-label">Footnotes</h2>\n<ol>\n<li id="user-content-user-content-fn-1">\n<p>The note\ncontinues. <a href="#user-content-fnref-1" data-footnote-backref="" aria-label="Back to reference 1" class="data-footnote-backref">โฉ</a> <a href="#user-content-fnref-1-2" data-footnote-backref="" aria-label="Back to reference 1-2" class="data-footnote-backref">โฉ<sup>2</sup></a></p>\n</li>\n</ol>\n</section>',
112 ],
113 [
114 "> [!NOTE]\n> An alert\n\n> [!warning] lower\n> case",
115 '<blockquote data-alert="note" dir="ltr">\n<p>An alert</p>\n</blockquote>\n<blockquote dir="ltr">\n<p>[!warning] lower\ncase</p>\n</blockquote>',
116 ],
117 [
118 "- wide\n- [x](./x.ts) items\n\ntext\n\n- loose\n\n- items",
119 '<ul dir="ltr">\n<li>wide</li>\n<li><a href="./x.ts">x</a> items</li>\n</ul>\n<p dir="ltr">text</p>\n<ul dir="ltr">\n<li>\n<p>loose</p>\n</li>\n<li>\n<p>items</p>\n</li>\n</ul>',
120 ],
121 [
122 '- :codex-file-citation{path="src/a.ts"}\n- :codex-followup[Run tests]{prompt="Run tests"}',
123 '<ul dir="ltr">\n<li><a href="src/a.ts">a.ts</a></li>\n<li><span>Run tests</span></li>\n</ul>',
124 ],
125 [
126 "> [!TIP]**joined**",
127 '<blockquote dir="ltr">\n<p>[!TIP]<strong>joined</strong></p>\n</blockquote>',
128 ],
129 [
130 "1. one\r\n2. two\r\n\r\n loose\r\n",
131 '<ol dir="ltr">\n<li>\n<p>one</p>\n</li>\n<li>\n<p>two</p>\n<p>loose</p>\n</li>\n</ol>',
132 ],
133 [
134 "© 😀 &bogus; � \\& *a **b** c*",
135 '<p dir="ltr">ยฉ ๐ &bogus; ๏ฟฝ & <em>a <strong>b</strong> c</em></p>',
136 ],
137 [
138 "Hard \nbreak\\\nand `` code ` span ``",
139 '<p dir="ltr">Hard<br>\nbreak<br>\nand <code data-inline-code="" dir="ltr">code ` span</code></p>',
140 ],
141 [
142 '[ref] and [Ref][] and [x][REF]\n\n[ref]: /url "title"',
143 '<p dir="ltr"><a href="/url">ref</a> and <a href="/url">Ref</a> and <a href="/url">x</a></p>',
144 ],
145 [
146 "Open [a.ts](./a.ts) and /Users/me/b.ts:3. Run `src/b.ts`.",
147 '<p dir="ltr">Open <a href="./a.ts">a.ts</a> and <span class="has-[[data-slot=context-chip-label]]:whitespace-nowrap"><a href="/Users/me/b.ts:3">/Users/me/b.ts:3</a>.</span> Run <span class="has-[[data-slot=context-chip-label]]:whitespace-nowrap"><code data-inline-code="" dir="ltr">src/b.ts</code>.</span></p>',
148 ],
149 [
150 "[a](CURSOR://file/Users/me/a.md:3) [b](vscode://file/C:/a.ts) [c](cursor://anysphere.x/p)",
151 '<p dir="ltr"><a href="cursor://file/Users/me/a.md:3">a</a> <a href="vscode://file/C:/a.ts">b</a> <a href="cursor://anysphere.x/p">c</a></p>',
152 ],
153 [
154 "\n\nText\n",
155 '<p dir="ltr"><img src="https://x.dev/1.png" alt="one"><br>\n<img src="https://x.dev/2.png" alt="two"><br>\nText<br>\n<img src="https://x.dev/3.png" alt="three"></p>',
156 ],
157 [
158 'Read :codex-file-citation[a.ts]{path="src/a.ts" line_range_start="3"} and [x :codex-file-citation[b]{path="b.ts"}](u).',
159 '<p dir="ltr">Read <a href="src/a.ts#L3">a.ts</a> and <span class="has-[[data-slot=context-chip-label]]:whitespace-nowrap"><a href="u">x :codex-file-citation[b]{path="b.ts"}</a>.</span></p>',
160 ],
161 [
162 ':codex-followup[Ask]{prompt="go"} and :codex-followup[No prompt]{label="x"} stay apart.',
163 '<p dir="ltr"><span>Ask</span> and :codex-followup[No prompt]{label="x"} stay apart.</p>',
164 ],
165 [
166 '::artifact-template{artifact_kind="document" display_name="Doc" skill_directory="/s" skill_name="artifact-template-doc"}\n\n::artifact-template{bad="x"}',
167 '<div data-codex-artifact-template="true" data-artifact-kind="document" data-display-name="Doc" data-skill-directory="/s" data-skill-name="artifact-template-doc"></div>\n<p dir="ltr">::artifact-template{bad="x"}</p>',
168 ],
169 [
170 "[file](C:\\work\\a.ts) and C:\\Users\\me\\.t3\\shot.png and \\*kept\\*",
171 '<p dir="ltr"><a href="file:///C:/work/a.ts">file</a> and C:\\Users\\me\\.t3\\shot.png and *kept*</p>',
172 ],
173 [
174 '```ts title="a.ts"\nconst a = 1;\n```',
175 '<pre><code class="language-ts" data-code-meta="title="a.ts"">const a = 1;\n</code></pre>',
176 ],
177 [
178 "Cost ~5 and ~~gone~~ in an answer.",
179 '<p dir="ltr">Cost ~5 and <del>gone</del> in an answer.</p>',
180 ],
181 [
182 "<details>\n<summary>More</summary>\n\nHidden **bold**\n\n</details>",
183 '<details dir="ltr">\n<summary>More</summary>\n<p>Hidden <strong>bold</strong></p>\n</details>',
184 ],
185 [
186 'Inline <sup>1</sup> and <img src="a.png" alt="x"> html',
187 '<p dir="ltr">Inline <sup>1</sup> and <img src="a.png" alt="x"> html</p>',
188 ],
189 [
190 '<picture><source media="(prefers-color-scheme: dark)" srcset="d.png"><source media="(prefers-color-scheme: light)" srcset="l.png"><img src="l.png" alt="x"></picture>',
191 '<p><picture><img src="l.png" alt="x" data-dark-src="d.png" data-light-src="l.png" data-standalone></picture></p>',
192 ],
193 [
194 '# H\n\n<picture>\n<source media="(prefers-color-scheme: dark)" srcset="d.png">\n<img src="l.png" alt="x">\n</picture>\n\nP',
195 '<h1 id="user-content-h" dir="ltr">H</h1>\n<picture>\n\n<img src="l.png" alt="x" data-dark-src="d.png" data-standalone>\n</picture>\n<p dir="ltr">P</p>',
196 ],
197 [
198 "<details>\n<summary>โ ๏ธ Outside diff (3)</summary><blockquote>\n\n**a**\n\n</blockquote></details>",
199 '<details dir="ltr">\n<summary>โ ๏ธ Outside diff (3)</summary><blockquote>\n<p><strong>a</strong></p>\n</blockquote></details>',
200 ],
201 [
202 '<div align="center"><img width="837" src="https://x.dev/a.png" title="t" /></div>\n\nafter',
203 '<div align="center"><img width="837" src="https://x.dev/a.png" data-markdown-title="t" data-standalone></div>\n<p dir="ltr">after</p>',
204 ],
205 [
206 'Text <sup>[1](#n)</sup> <sub>x</sub> <br> <a href="https://x.dev" target="_blank">link</a>',
207 '<p dir="ltr">Text <sup><a href="#n">1</a></sup> <sub>x</sub> <br> <a href="https://x.dev">link</a></p>',
208 ],
209 ["<!-- hidden -->\nVisible <!-- inline --> text", '\n<p dir="ltr">Visible text</p>'],
210 [
211 '<custom-tag>kept text</custom-tag> and <a href="javascript:x">bad</a>',
212 '<p dir="ltr">kept text and <a>bad</a></p>',
213 ],
214 [
215 "> <details>\n> <summary>quoted</summary>\n>\n> body\n> </details>",
216 '<blockquote dir="ltr">\n<details>\n<summary>quoted</summary>\n<p>body</p>\n</details>\n</blockquote>',
217 ],
218 [
219 '<h3 id="x">Raw heading</h3>\n\n## Markdown heading',
220 '<h3 id="user-content-x" dir="ltr">Raw heading</h3>\n<h2 id="user-content-markdown-heading" dir="ltr">Markdown heading</h2>',
221 ],
222];
223โ
224describe("wordsHast", () => {
225 it.each(CASES)("renders %j as the remark pipeline did", (markdown, html) => {
226 expect(wordsHtml(markdown)).toBe(html);
227 });
228โ
229 it("uses document reference definitions in recovered items and search text", () => {
230 const markdown = "- Read [the guide][guide].\n\n[guide]: https://example.com/guide";
231 const normal = markdown.replace("- ", "- ");
232 expect(wordsHtml(markdown)).toBe(wordsHtml(normal));
233 expect(wordsHtml(markdown)).toContain('<a href="https://example.com/guide">the guide</a>');
234 const segments = (text: string) =>
235 searchableMessageSegments({ role: "assistant", text, streaming: false });
236 expect(segments(markdown)).toEqual(segments(normal));
237 expect(segments(markdown)?.join("")).toBe("Read the guide.");
238 });
239โ
240 it("keeps Setext headings in wide-indented items in rendered and searchable text", () => {
241 const markdown = "- **bold**\n ---";
242 const html = wordsHtml(markdown);
243 expect({
244 html,
245 segments: searchableMessageSegments({ role: "assistant", text: markdown, streaming: false }),
246 }).toEqual({
247 html: wordsHtml("- **bold**\n ---"),
248 segments: ["bold"],
249 });
250 expect(html).toMatch(/<h2\b[^>]*><strong>bold<\/strong><\/h2>/);
251 });
252โ
253 it("keeps a recovered item's own reference definition ahead of the document's", () => {
254 const markdown =
255 "- Read [the guide][guide].\n\n [guide]: https://example.com/local\n\n[guide]: https://example.com/document";
256 expect(wordsHtml(markdown)).toContain('<a href="https://example.com/local">the guide</a>');
257 });
258โ
259 it("handles CR-only and CRLF line endings for list item indented code and looseness", () => {
260 expect(wordsHtml("-\r code")).toBe(wordsHtml("-\n code"));
261 expect(wordsHtml("-\r code")).toContain("<pre><code>");
262 expect(wordsHtml("- a\r\r- b")).toBe(wordsHtml("- a\n\n- b"));
263 expect(wordsHtml("- a\r\n- b")).toBe(wordsHtml("- a\n- b"));
264 });
265โ
266 it("breaks soft lines as remark-breaks did", () => {
267 const markdown = "one\ntwo **three\nfour**\n\n- item\n next\n - sub\n\n```\nkept\nlines\n```";
268 expect(wordsHtml(markdown, { breaks: true })).toBe(
269 '<p dir="ltr">one<br>\ntwo <strong>three<br>\nfour</strong></p>\n<ul dir="ltr">\n<li>item<br>\nnext\n<ul>\n<li>sub</li>\n</ul>\n</li>\n</ul>\n<pre><code>kept\nlines\n</code></pre>',
270 );
271 const rawHtml =
272 '<p align="center">\n <img src="https://x.dev/a.png" width="400">\n</p>\n\n<ul>\n<li>\none\ntwo\n</li>\n</ul>';
273 expect(wordsHtml(rawHtml, { breaks: true })).toBe(
274 '<p align="center">\n <img src="https://x.dev/a.png" width="400" data-standalone>\n</p>\n<ul dir="ltr">\n<li>\none\ntwo\n</li>\n</ul>',
275 );
276 });
277โ
278 it("keeps the composer's tildes and list numbers in user messages", () => {
279 const markdown = "Install as ~/a/x, then (~/b.md). ~one~ ~~two~~\n\n3. three\n5. five";
280 expect(wordsHtml(markdown, { extensions: { userMessage: true } })).toBe(
281 '<p dir="ltr">Install as ~/a/x, then (~/b.md). ~one~ <del>two</del></p>\n<ol start="3" dir="ltr">\n<li>three</li>\n<li value="5">five</li>\n</ol>',
282 );
283 // Typed indentation past a wide list marker counts from where the item's text starts.
284 expect(
285 wordsHtml("- wide\n continued", {
286 breaks: true,
287 extensions: { userMessage: true, leadingWhitespace: true },
288 }),
289 ).toBe(
290 '<ul dir="ltr">\n<li>wide<br>\n<span data-leading-whitespace=""> </span>continued</li>\n</ul>',
291 );
292 // The tab after five spaces only reaches column 8, so `bar` sits two columns past `foo`.
293 expect(
294 wordsHtml("- \tfoo\n bar", {
295 breaks: true,
296 extensions: { userMessage: true, leadingWhitespace: true },
297 }),
298 ).toBe(
299 '<ul dir="ltr">\n<li>foo<br>\n<span data-leading-whitespace=""> </span>bar</li>\n</ul>',
300 );
301 });
302โ
303 it("gives elements the source positions components read", () => {
304 // A wide item's text is parsed again on its own, so its link has no place in the message.
305 const markdown = "รฉ [a](u)\n\n- [ ] task\n\n```sh\nls\n```\n\n- [b](./b.ts)";
306 const tree = wordsHast(markdown, ASSISTANT);
307 const slices: string[] = [];
308 const visit = (node: Root | Element) => {
309 for (const child of node.children) {
310 if (child.type !== "element") continue;
311 if (child.position) {
312 slices.push(markdown.slice(child.position.start.offset, child.position.end.offset));
313 }
314 visit(child);
315 }
316 };
317 visit(tree);
318 expect(slices).toEqual(["[a](u)", "- [ ] task", "```sh\nls\n```", "- [b](./b.ts)"]);
319 });
320โ
321 it("renders insight blocks as remarkAssistantInsights did", () => {
322 for (const ending of ["\n", "\r\n", "\r"]) {
323 expect(
324 wordsHtml(["โ
Insight โโโโโ", "Cache is warm.", "โโโโโ", "After."].join(ending), {
325 insights: true,
326 }),
327 ).toBe(
328 '<blockquote data-alert="insight" dir="ltr">\n<p>Cache is warm.</p>\n</blockquote>\n<p dir="ltr">After.</p>',
329 );
330 }
331 const markdown =
332 "Intro\n\n`โ
Insight โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ`\n- one\n- two\n`โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ`\n\nAfter\n\n```\nโ
Insight โโโโโ\n```";
333 expect(wordsHtml(markdown, { insights: true })).toBe(
334 '<p dir="ltr">Intro</p>\n<blockquote data-alert="insight" dir="ltr">\n<ul>\n<li>one</li>\n<li>two</li>\n</ul>\n</blockquote>\n<p dir="ltr">After</p>\n<pre><code>โ
Insight โโโโโ\n</code></pre>',
335 );
336 // Code in a list, an HTML block and a quote's lazy line are not where an insight opens.
337 expect(
338 wordsHtml(
339 "- x\n ```\n โ
Insight โโโโโ\n ```\n\n<div>\nโ
Insight โโโโโ\n</div>\n\n> q\nโ
Insight โโโโโ",
340 {
341 insights: true,
342 },
343 ),
344 ).toBe(
345 '<ul dir="ltr">\n<li>x\n<pre><code>โ
Insight โโโโโ\n</code></pre>\n</li>\n</ul>\n<div dir="ltr">\nโ
Insight โโโโโ\n</div>\n<blockquote dir="ltr">\n<p>q\nโ
Insight โโโโโ</p>\n</blockquote>',
346 );
347 // An opening inside an HTML comment is dropped with it, so it opens nothing.
348 expect(
349 wordsHtml("<!--\nโ
Insight โโโ\n-->\n\nโ
Insight โโโ\nreal insight\nโโโ\n\nAfter", {
350 insights: true,
351 }),
352 ).toBe(
353 '\n<blockquote data-alert="insight" dir="ltr">\n<p>real insight</p>\n</blockquote>\n<p dir="ltr">After</p>',
354 );
355 expect(wordsHtml("<!--\nโ
Insight โโโ\n-->\n\nVisible text", { insights: true })).toBe(
356 '\n<p dir="ltr">Visible text</p>',
357 );
358 const plain = "โ
Insight โโโ\nThe note\nโโโ";
359 for (const text of [plain, `\uFEFF${plain}`]) {
360 expect(wordsHtml(text, { insights: true })).toBe(
361 '<blockquote data-alert="insight" dir="ltr">\n<p>The note</p>\n</blockquote>',
362 );
363 expect(searchableMessageSegments({ role: "assistant", text, streaming: false })).toEqual([
364 "The note",
365 ]);
366 }
367 const multiline = "โ
Insight โโโ\nfirst line\nsecond line\nโโโ";
368 const multilineSegments = (text: string) =>
369 searchableMessageSegments({ role: "assistant", text, streaming: false });
370 expect(multilineSegments(`\uFEFF${multiline}`)).toEqual(multilineSegments(multiline));
371 expect(multilineSegments(multiline)).toHaveLength(2);
372 // Only one leading BOM is metadata; a second stays text, so `#` opens no heading.
373 expect(
374 searchableMessageSegments({
375 role: "assistant",
376 text: `\uFEFF\uFEFF# heading\nnext\n\n${plain}`,
377 streaming: false,
378 }),
379 ).toEqual(["\uFEFF# heading", " next", "The note"]);
380 // What follows an opening keeps its offsets in the message, which components slice.
381 const insight =
382 "[x](./x.ts)\n\nโ
Insight โโโโโ\nSee [a](./a.ts)\n```sh\nls\n```\nโโโโโ\n\n[y](./y.ts)\n\nโ
Insight โโโโโ\n[z](./z.ts)\nโโโโโ";
383 const tree = wordsHast(insight, { ...ASSISTANT, insights: true });
384 const sliced: string[] = [];
385 const visit = (node: Root | Element) => {
386 for (const child of node.children) {
387 if (child.type !== "element") continue;
388 if (child.tagName === "a" || child.tagName === "pre") {
389 sliced.push(insight.slice(child.position!.start.offset, child.position!.end.offset));
390 }
391 visit(child);
392 }
393 };
394 visit(tree);
395 expect(sliced).toEqual([
396 "[x](./x.ts)",
397 "[a](./a.ts)",
398 "```sh\nls\n```",
399 "[y](./y.ts)",
400 "[z](./z.ts)",
401 ]);
402 });
403โ
404 it("shows raw HTML as its text when asked", () => {
405 expect(wordsHtml("a <b>x</b> and <https://a.dev>", { escapeHtml: true })).toBe(
406 '<p dir="ltr">a <b>x</b> and <a href="https://a.dev">https://a.dev</a></p>',
407 );
408 });
409โ
410 it.each(["tfoot", "tbody"])(
411 "keeps an explicit %s outside implicit table row groups",
412 (section) => {
413 const first = "<tr><td>One</td></tr>";
414 const explicit = `<${section}><tr><td>Total</td></tr></${section}>`;
415 const last = "<tr><td>Two</td></tr>";
416 expect(wordsHtml(`<table>${first}${explicit}</table>`)).toBe(
417 `<table dir="ltr"><tbody>${first}</tbody>${explicit}</table>`,
418 );
419 expect(wordsHtml(`<table>${first}\n${last}${explicit}${last}</table>`)).toBe(
420 `<table dir="ltr"><tbody>${first}\n${last}</tbody>${explicit}<tbody>${last}</tbody></table>`,
421 );
422 },
423 );
424โ
425 it("flattens a preview to one line of text and math, within its length", () => {
426 const preview = { fallback: "Thinking", maxLength: 24 };
427 const options = { math: true, extensions: { preview } };
428 expect(wordsHtml("# Plan\n\n- **one** <b>x</b>\n- `two` $a$", options)).toMatch(
429 /^Plan one x two <span[^>]* data-markdown-math="inline"[^>]*><svg [^>]*aria-label="a"/,
430 );
431 expect(wordsHtml("x".repeat(30), options)).toBe("x".repeat(24));
432 expect(wordsHtml("<!-- only -->", options)).toBe("Thinking");
433 expect(
434 wordsHtml("Checked the cache first[^1] and it was stale.\n\n[^1]: Redis TTL is 60s.", {
435 ...options,
436 extensions: { preview: { ...preview, maxLength: 120 } },
437 }),
438 ).toBe("Checked the cache first and it was stale.");
439 });
440โ
441 it("makes a saved file's Markdown inert", () => {
442 expect(
443 wordsHtml(
444 "[a](https://x.dev)  `c` <img src=y>\n\n```mermaid\nA\n```",
445 {
446 extensions: { inert: true },
447 },
448 ),
449 ).toBe('<p dir="ltr">a b c </p>\n<pre><code class="language-text">A\n</code></pre>');
450 });
451โ
452 it("links a change request's references and resolves its root-relative media", () => {
453 const autolinks = (text: string) =>
454 [...text.matchAll(/#(\d+)/g)].map((match) => ({
455 index: match.index,
456 text: match[0],
457 label: match[0],
458 url: `https://forge.dev/o/r/pull/${match[1]}`,
459 kind: "reference" as const,
460 }));
461 const html = wordsHtml("See #12 and `#13`.\n\n", {
462 extensions: { changeRequest: { repositoryUrl: "https://forge.dev/o/r", autolinks } },
463 });
464 expect(html).toContain(
465 '<a href="https://forge.dev/o/r/pull/12" data-pull-request-autolink="reference">#12</a>',
466 );
467 expect(html).toContain('<code data-inline-code="" dir="ltr">#13</code>');
468 expect(html).toContain('src="https://forge.dev/api/attachments/1"');
469 });
470โ
471 it("renders math as SVG, and keeps money as text", () => {
472 const html = toHtml(
473 wordsHast("Costs $34.58 and $15.00, and $x^2 \\text{ for } n$ is math.\n\n$$\na\n$$", {
474 ...ASSISTANT,
475 math: true,
476 }),
477 );
478 expect(html).toContain("Costs $34.58 and $15.00, and ");
479 expect(html.match(/<svg /g)).toHaveLength(2);
480 expect(html).toContain('aria-label="x^2 \\text{ for } n"');
481 expect(html).toContain('style="white-space:pre"> for </text>');
482 });
483โ
484 it("lays out inline math left to right inside a right-to-left paragraph", () => {
485 const hast = wordsHast("ืืงืืืขืื ืื $e$, $i$ ื-$\\pi$.", { ...ASSISTANT, math: true });
486 const paragraph = hast.children[0] as Element;
487 expect(paragraph.properties.dir).toBe("rtl");
488 const directions: Array<unknown> = [];
489 const visit = (node: Element, ltr: boolean) => {
490 const own = ltr || node.properties.dir === "ltr";
491 if (node.tagName === "svg") return void directions.push(own);
492 for (const child of node.children) if (child.type === "element") visit(child, own);
493 };
494 for (const child of paragraph.children) if (child.type === "element") visit(child, false);
495 expect(directions).toEqual([true, true, true]);
496 });
497โ
498 it("keeps control bytes, blank lines, unclosed blocks, shell vars, and table dollars intact in math", () => {
499 const options = { ...ASSISTANT, math: true };
500 expect(toHtml(wordsHast("Pasted: $a\u001bb + c$", options))).toContain("<svg ");
501 expect(toHtml(wordsHast("$$\na = 1 \\\\\n\nb = 2\n$$", options))).toContain("<svg ");
502 expect(toHtml(wordsHast("$$\n\\frac{a}{b}", options))).toBe(
503 '<p dir="ltr">$$\n\\frac{a}{b}</p>',
504 );
505 expect(toHtml(wordsHast("```math\nx^2", options))).toBe(
506 '<pre><code class="language-math">x^2\n</code></pre>',
507 );
508 expect(toHtml(wordsHast("Set $HOME,$PATH and $FOO to `$BAR`.", options))).toBe(
509 '<p dir="ltr">Set $HOME,$PATH and $FOO to <span class="has-[[data-slot=context-chip-label]]:whitespace-nowrap"><code data-inline-code="" dir="ltr">$BAR</code>.</span></p>',
510 );
511 expect(
512 toHtml(
513 wordsHast("| [a](https://example.com/$x) | `$x` | y$ |\n| --- | --- | --- |", options),
514 ),
515 ).toContain("<table ");
516 });
517โ
518 it.each([
519 [
520 "Status \ncontinues",
521 '<p dir="ltr">Status <img src="https://x.dev/b.png" alt="badge">\ncontinues</p>',
522 '<p dir="ltr">Status <img src="https://x.dev/b.png" alt="badge"><br>\ncontinues</p>',
523 ],
524 [
525 "**Label**\n[](https://x.dev)\ncontinues",
526 '<p dir="ltr"><strong>Label</strong><br>\n<a href="https://x.dev"><img src="https://x.dev/b.png" alt="shot"></a><br>\ncontinues</p>',
527 '<p dir="ltr"><strong>Label</strong><br>\n<a href="https://x.dev"><img src="https://x.dev/b.png" alt="shot"></a><br>\ncontinues</p>',
528 ],
529 [
530 "**Shot** (dark)  ",
531 '<p dir="ltr"><strong>Shot</strong> (dark)<br>\n<img src="https://x.dev/a.png" alt="a"> <img src="https://x.dev/b.png" alt="b"></p>',
532 '<p dir="ltr"><strong>Shot</strong> (dark)<br>\n<img src="https://x.dev/a.png" alt="a"> <img src="https://x.dev/b.png" alt="b"></p>',
533 ],
534 [
535 "**A favicon ** stays inline",
536 '<p dir="ltr"><strong>A favicon <img src="https://x.dev/i.png" alt="i"></strong> stays inline</p>',
537 '<p dir="ltr"><strong>A favicon <img src="https://x.dev/i.png" alt="i"></strong> stays inline</p>',
538 ],
539 [
540 'Status\n<img src="https://x.dev/b.png" />\ncontinues',
541 '<p dir="ltr">Status\n<img src="https://x.dev/b.png">\ncontinues</p>',
542 '<p dir="ltr">Status<br>\n<img src="https://x.dev/b.png"><br>\ncontinues</p>',
543 ],
544 [
545 "Hard \nbreak and a\\\nbackslash",
546 '<p dir="ltr">Hard<br>\nbreak and a<br>\nbackslash</p>',
547 '<p dir="ltr">Hard<br>\nbreak and a<br>\nbackslash</p>',
548 ],
549 ])(
550 "breaks lines next to images and hard breaks as remark did: %j",
551 (markdown, html, withBreaks) => {
552 expect(wordsHtml(markdown)).toBe(html);
553 expect(wordsHtml(markdown, { breaks: true })).toBe(withBreaks);
554 },
555 );
556โ
557 it("reads raw HTML attributes as an HTML parser does", () => {
558 expect(wordsHtml('<a href="https://x.dev/?q=1©=2&b">x</a>')).toContain(
559 'href="https://x.dev/?q=1&copy=2&b"',
560 );
561 const fold = (attributes: string) =>
562 wordsHast(
563 `<details ${attributes}>\n<summary>Example</summary>\nHidden\n</details>`,
564 ASSISTANT,
565 ).children[0];
566 const closed = fold("data-label=hello\u00a0open");
567 expect(closed).toMatchObject({ tagName: "details" });
568 expect(closed).not.toHaveProperty("properties.open");
569 expect(fold('data-label=hello\u00a0world\tOPEN="false"')).toMatchObject({
570 tagName: "details",
571 properties: { open: true },
572 });
573 });
574โ
575 it("treats only Words' own directives as directives", () => {
576 const forged =
577 '<span data-directive="codex-followup" data-attributes="null">Ask</span> and <div data-directive="artifact-template" data-attributes="[1]"></div>';
578 expect(wordsHtml(forged)).toBe('<p dir="ltr"><span>Ask</span> and </p><div></div><p></p>');
579 // Raw HTML can write a source position too, even the one Words gave a real directive.
580 const positioned = `<span data-directive="codex-file-citation" data-attributes='{"path":"/etc/passwd"}' data-sourcepos="0-5">x</span>`;
581 expect(wordsHtml(positioned)).toBe('<p dir="ltr"><span>x</span></p>');
582 const real = ':codex-file-citation[a]{path="a.ts"}';
583 expect(
584 wordsHtml(
585 `${real} <span data-directive="codex-file-citation" data-attributes='{"path":"/etc/passwd"}' data-sourcepos="0-${real.length}">x</span>`,
586 ),
587 ).not.toContain("/etc/passwd");
588 });
589โ
590 it("reads a directive's label as written", () => {
591 expect(
592 codexDirectiveSources(':codex-followup[pick {a} or [b]]{prompt="go"}').map(
593 (directive) => directive.label,
594 ),
595 ).toEqual(["pick {a} or [b]"]);
596 });
597โ
598 it.each([
599 'Before :codex-followup{prompt="Look at [foo]"} after',
600 'Before :codex-followup[<!-- x -->]{prompt="go"} after',
601 'Before :codex-followup[:codex-file-citation{path="aaaaaaaaaaaaaaaaaaaaaaaa.ts"}]{prompt="go"} after',
602 ])("copies a follow-up without a visible label as written: %s", (markdown) => {
603 expect(renderCodexDirectivesForCopy(markdown)).toBe(markdown);
604 });
605โ
606 it.each([
607 [
608 ':codex-followup[try :codex-followup[inner]{prompt="i"} then]{prompt="o"} end',
609 "try inner then end",
610 ],
611 [
612 '๐ :codex-followup[[see :codex-file-citation[a]{path="a.ts"}][ref]]{prompt="o"} and :codex-followup[again]{prompt="a"} end\n\n[ref]: https://x.dev',
613 '๐ [see :codex-file-citation[a]{path="a.ts"}][ref] and again end\n\n[ref]: https://x.dev',
614 ],
615 [
616 ':codex-followup[ read :codex-file-citation[a]{path="a.ts"} then]{prompt="o"} end',
617 " read [a.ts](<a.ts>) then end",
618 ],
619 [
620 ':codex-followup[read :codex-file-citation[a]{path="a.ts"}] end',
621 ':codex-followup[read :codex-file-citation[a]{path="a.ts"}] end',
622 ],
623 [
624 ':codex-followup[read :codex-file-citation[a]{path="a.ts"}]{prompt=" "} end',
625 ':codex-followup[read :codex-file-citation[a]{path="a.ts"}]{prompt=" "} end',
626 ],
627 [
628 "Before :codex-followup[[Guide](https://example.com/a]b)]{prompt=go} after",
629 "Before [Guide](https://example.com/a]b) after",
630 ],
631 [
632 "Before :codex-followup[**[Guide](https://example.com/a]b)**]{prompt=go} after",
633 "Before **[Guide](https://example.com/a]b)** after",
634 ],
635 ])("copies nested directives without losing surrounding text: %s", (markdown, expected) => {
636 expect(renderCodexDirectivesForCopy(markdown)).toBe(expected);
637 expect(renderCodexInlineDirectivesAsMarkdown(markdown)).toBe(expected);
638 });
639โ
640 it.each([
641 ["# Title\n[a]: https://x.dev", ["[a]: <https://x.dev>"]],
642 ["See [^note].\n\n[^note]: https://x.dev", []],
643 ["\uFEFF[docs]: https://example.com/guide", ["[docs]: <https://example.com/guide>"]],
644 ["intro\n\n\uFEFF[docs]: https://example.com/guide", []],
645 ['> [a]:\n> https://x.dev "The\n> guide"', ['[a]: <https://x.dev> "The guide"']],
646 ["> [user\n> guide]: https://x.dev", ["[user guide]: <https://x.dev>"]],
647 ["> > [user\r\n> > guide]: https://x.dev", ["[user guide]: <https://x.dev>"]],
648 ["- [a]: https://x.dev\n\n[A]: https://second.dev", ["[a]: <https://x.dev>"]],
649 ["<div>\n[a]: https://x.dev\n</div>", []],
650 ["- ```\n [a]: https://x.dev\n ```", []],
651 ["text\n[a]: https://x.dev", []],
652 ["[doc]: https://example.com\n\nSee [doc].\n\n```js\nx", ["[doc]: <https://example.com>"]],
653 ["[a]: https://x.dev\n\n<!--\nunclosed", ["[a]: <https://x.dev>"]],
654 ["[not\n```\ndef]: x\n```\n\n[a]: https://x.dev", ["[a]: <https://x.dev>"]],
655 ])("finds the reference definitions in %j as Words reads them", (markdown, definitions) => {
656 expect(markdownReferenceDefinitions(markdown)).toEqual(definitions);
657 });
658โ
659 it.each([
660 ["https://example.com/?x=1&copy;", "a &copy; &quot; &#65;"],
661 ["https://example.com/?x=1&#65;", "a &amp; b"],
662 ])("preserves the reference destination and title when reserializing %s", (url, title) => {
663 const content = "Read [ref] and ![alt][ref].";
664 const markdown = `${content}\n\n[ref]: ${url} "${title}"`;
665 const definitions = markdownReferenceDefinitions(markdown);
666 expect(wordsHtml(`${content}\n\n${definitions.join("\n")}`)).toBe(wordsHtml(markdown));
667 });
668โ
669 it("keeps authored SVG and ids out of the math it restores", () => {
670 const html = wordsHtml(
671 '<svg width="99999" viewBox="0 0 1 1"><rect x="0" y="0" width="1" height="1"/></svg> <svg data-sourcepos="0-3" height="99999"></svg> <span id="t3-math-0">kept</span> $x$',
672 { math: true },
673 );
674 expect(html).not.toContain("99999");
675 expect(html).toContain("kept");
676 expect(html.match(/<svg /g)).toHaveLength(1);
677 });
678โ
679 it("keeps only math's own SVG elements and attributes", () => {
680 const html = toHtml(
681 wordsHast(
682 '<svg onload="x()" style="position:fixed;display:inline"><a href="javascript:x()"><text x="1">t</text></a><script>x()</script></svg> $y$',
683 { ...ASSISTANT, math: true },
684 ),
685 );
686 expect(html).not.toMatch(/onload|javascript|position|<a |<script/);
687 expect(html).toContain('aria-label="y"');
688 });
689โ
690 it.each([
691 ["notes/[TODO].md", "[TODO].md"],
692 ["notes/~~draft~~.md", "~~draft~~.md"],
693 ["notes/[TODO].md", "[TODO].md"],
694 ])("renders sent composer file mention %s with literal basename %s", (path, basename) => {
695 const tree = wordsHast(serializeComposerFileLink(path), {
696 ...ASSISTANT,
697 math: true,
698 extensions: { userMessage: true },
699 });
700 const paragraph = tree.children[0] as Element;
701 const anchor = paragraph.children[0] as Element;
702 expect(anchor.tagName).toBe("a");
703 expect(anchor.children).toEqual([{ type: "text", value: basename }]);
704 expect(isMarkdownFileLinkLabel(basename, String(anchor.properties.href))).toBe(true);
705 });
706โ
707 it("supports chunked footnote modes (omit, omit-seeded, only)", () => {
708 const chunk0 = toHtml(
709 wordsHast("[^a]: .\n[^b]: .\n\nFirst[^a].", {
710 ...ASSISTANT,
711 extensions: { footnotes: "omit" },
712 }),
713 );
714 expect(chunk0).toContain('href="#user-content-fn-1"');
715 expect(chunk0).toContain('id="user-content-user-content-fnref-1"');
716 expect(chunk0).not.toContain("data-footnotes");
717โ
718 const chunk1 = toHtml(
719 wordsHast("[^a]: .\n[^b]: .\n\n[^a]\n\nSecond[^b] and repeat[^a].", {
720 ...ASSISTANT,
721 extensions: { footnotes: "omit-seeded" },
722 }),
723 );
724 expect(chunk1).toContain('href="#user-content-fn-2"');
725 expect(chunk1).toContain('id="user-content-user-content-fnref-2"');
726 expect(chunk1).toContain('href="#user-content-fn-1"');
727 expect(chunk1).toContain('id="user-content-user-content-fnref-1-2"');
728 expect(chunk1).not.toContain("data-footnotes");
729 expect(chunk1.match(/<p /g)).toHaveLength(1);
730โ
731 const section = toHtml(
732 wordsHast(
733 "[^a] [^b] [^a]\n\n[^a]: First note with [^c].\n\n[^b]: Second note.\n\n[^c]: Nested note.",
734 {
735 ...ASSISTANT,
736 extensions: { footnotes: "only" },
737 },
738 ),
739 );
740 expect(section).toMatch(/^<section data-footnotes=""/);
741 expect(section).toContain("First note with");
742 expect(section).toContain("Second note.");
743 expect(section).toContain("Nested note.");
744 expect(section).toContain('href="#user-content-fnref-1-2"');
745 expect(section).toContain('id="user-content-user-content-fn-3"');
746โ
747 // Only drops a synthetic footnote-only seed paragraph, never an earlier non-seed paragraph.
748 const preserved = toHtml(
749 wordsHast("[^a]: .\n\n[ ]: pending\n\n[^a]\n\nBody[^a].", {
750 ...ASSISTANT,
751 extensions: { footnotes: "omit-seeded" },
752 }),
753 );
754 expect(preserved).toContain("[ ]: pending");
755 expect(preserved).toContain('id="user-content-user-content-fnref-1-2"');
756 expect(preserved).not.toContain('id="user-content-user-content-fnref-1"');
757 });
758});