Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

ChatMarkdown.test.tsx

669 lines23.8 KB

1import { EnvironmentId } from "@t3tools/contracts";
2import { act, type ComponentProps, type ReactNode } from "react";
3import { renderToStaticMarkup } from "react-dom/server";
4import { create, type ReactTestRenderer } from "react-test-renderer";
5import { describe, expect, it, vi } from "vite-plus/test";
6​
7import { getSyntaxHighlighterPromise } from "../lib/syntaxHighlighting";
8import { Button } from "./ui/button";
9import { setMarkdownTaskChecked } from "./files/filePreviewMode";
10​
11vi.mock("@effect/atom-react", () => ({ useAtomValue: () => null }));
12vi.mock("../hooks/useTheme", () => ({ useTheme: () => ({ resolvedTheme: "dark" }) }));
13vi.mock("../hooks/useSettings", async (importOriginal) => {
14 const actual = await importOriginal<typeof import("../hooks/useSettings")>();
15 const settings = actual.getClientSettings();
16 return {
17 ...actual,
18 useClientSettings: (select?: (value: typeof settings) => unknown) =>
19 select ? select(settings) : settings,
20 };
21});
22vi.mock("./ui/tooltip", async () => {
23 const { cloneElement, isValidElement } = await import("react");
24 return {
25 Tooltip: ({ children }: { children: ReactNode }) => <>{children}</>,
26 TooltipTrigger({
27 render,
28 children,
29 }: ComponentProps<typeof import("./ui/tooltip").TooltipTrigger>) {
30 if (!isValidElement(render)) return <>{children}</>;
31 return children === undefined ? render : cloneElement(render, undefined, children);
32 },
33 TooltipPopup: () => null,
34 };
35});
36vi.mock("../state/use-atom-query-runner", () => ({ useAtomQueryRunner: () => vi.fn() }));
37vi.mock("../state/use-atom-command", () => ({ useAtomCommand: () => vi.fn() }));
38vi.mock("../state/session", async (importOriginal) => ({
39 ...(await importOriginal<typeof import("../state/session")>()),
40 usePreparedConnection: () => ({ _tag: "Loading" }),
41}));
42vi.mock("../state/entities", () => ({
43 readThreadShell: () => null,
44 useProjects: () => [],
45}));
46vi.mock("../remoteOpen", () => ({
47 useRemoteOpenResolution: () => ({ state: { mode: "local-exec" }, isResolved: true }),
48}));
49vi.mock("../editorPreferences", () => ({
50 useOpenInPreferredEditor: () => vi.fn(),
51 usePreferredEditor: () => [null, vi.fn()],
52}));
53vi.mock("~/lib/openPullRequestLink", () => ({
54 findProjectForChangeRequest: () => undefined,
55 matchesLinkedPullRequestUrl: () => false,
56 parseChangeRequestUrl: () => null,
57 useOpenChangeRequestLink: () => vi.fn(),
58}));
59​
60import ChatMarkdown, {
61 canUseMarkdownFileShellActions,
62 hasMarkdownFilePrimaryAction,
63 orderedListGutterStyle,
64 shouldUseMarkdownFileBrowserPrimaryAction,
65} from "./ChatMarkdown";
66​
67function codeButton(renderer: ReactTestRenderer, label: string) {
68 const button = renderer.root
69 .findAllByType(Button)
70 .find((instance) => instance.props["aria-label"] === label);
71 if (!button) throw new Error(`Missing code button: ${label}`);
72 return button.props as ComponentProps<typeof Button>;
74​
75describe("ChatMarkdown streaming", () => {
76 it("preserves code controls and details without highlighting an unchanged fence again", async () => {
77 const highlighter = await getSyntaxHighlighterPromise("text");
78 const highlight = vi.spyOn(highlighter, "codeToHtml");
79 const writeText = vi.fn(async (_text: string) => {});
80 vi.stubGlobal("navigator", { clipboard: { writeText } });
81 vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
82 vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] });
83 let renderer: ReactTestRenderer | undefined;
84 const text = [
85 "```text",
86 "First code block",
87 "```",
88 "",
89 "<details><summary>More</summary>",
90 "",
91 "Details content",
92 "",
93 "</details>",
94 "",
95 "Streaming reply",
96 ].join("\n");
97​
98 try {
99 await act(async () => {
100 renderer = create(<ChatMarkdown cwd="/tmp/project" text={text} isStreaming />);
101 });
102 const mounted = renderer!;
103 const codeBlock = mounted.root.findByProps({ "data-language": "text" });
104 const initialWrap = codeBlock.props["data-wrap"] === "true";
105 const wrap = codeButton(mounted, initialWrap ? "Disable line wrap" : "Wrap lines");
106 const copy = codeButton(mounted, "Copy code");
107 await act(async () => {
108 wrap.onClick?.({} as Parameters<NonNullable<typeof wrap.onClick>>[0]);
109 copy.onClick?.({} as Parameters<NonNullable<typeof copy.onClick>>[0]);
110 });
111​
112 const detailsButton = mounted.root.find(
113 (instance) =>
114 instance.type === "button" && instance.props["data-markdown-details-summary"] === "",
115 );
116 await act(async () => {
117 detailsButton.props.onClick({ nativeEvent: new Event("click") });
118 });
119 const details = mounted.root.findByProps({ "data-markdown-details": "" });
120 expect(details.props["data-markdown-details-open"]).toBe("true");
121 expect(writeText).toHaveBeenCalledWith("First code block\n");
122 expect(highlight).toHaveBeenCalledTimes(1);
123​
124 for (let index = 0; index < 10; index += 1) {
125 await act(async () => {
126 mounted.update(<ChatMarkdown cwd="/tmp/project" text={`${text} ${index}`} isStreaming />);
127 });
128 }
129​
130 expect(highlight).toHaveBeenCalledTimes(1);
131 expect(mounted.root.findByProps({ "data-language": "text" })).toBe(codeBlock);
132 expect(codeBlock.props["data-wrap"]).toBe(String(!initialWrap));
133 expect(mounted.root.findByProps({ "data-markdown-details": "" })).toBe(details);
134 expect(details.props["data-markdown-details-open"]).toBe("true");
135 await act(async () => {
136 mounted.update(
137 <ChatMarkdown
138 cwd="/tmp/project"
139 text={text.replace("First code block", "Updated code block")}
140 isStreaming
141 />,
142 );
143 });
144 const copyUpdated = codeButton(mounted, "Copied");
145 await act(async () => {
146 copyUpdated.onClick?.({} as Parameters<NonNullable<typeof copyUpdated.onClick>>[0]);
147 });
148 expect(writeText).toHaveBeenLastCalledWith("Updated code block\n");
149 expect(highlight).toHaveBeenCalledTimes(2);
150 } finally {
151 await act(async () => renderer?.unmount());
152 vi.useRealTimers();
153 vi.unstubAllGlobals();
154 vi.restoreAllMocks();
155 }
156 });
157​
158 it("edits the current task text and marker after reusing a renderer", async () => {
159 vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
160 let renderer: ReactTestRenderer | undefined;
161 let editedText: string | undefined;
162 const message = (text: string) => (
163 <ChatMarkdown
164 cwd="/tmp/project"
165 text={text}
166 onTaskListChange={({ markerOffset, checked }) => {
167 editedText = setMarkdownTaskChecked(text, markerOffset, checked);
168 renderer!.update(message(editedText));
169 }}
170 />
171 );
172​
173 try {
174 await act(async () => {
175 renderer = create(message("- [ ] First\n- [ ] Second"));
176 });
177 const mounted = renderer!;
178 const originalInput = mounted.root.findAllByType("input")[1]!;
179 await act(async () => {
180 mounted.update(message("- [ ] A longer first task\n- [ ] Second"));
181 });
182​
183 const input = mounted.root.findAllByType("input")[1]!;
184 const listItem = mounted.root.findAllByType("li")[1]!;
185 const { onChange } = input.props as ComponentProps<"input">;
186 if (!onChange) throw new Error("Task checkbox has no edit handler");
187 await act(async () => {
188 onChange({
189 currentTarget: {
190 checked: true,
191 closest: () => ({
192 dataset: { taskMarkerOffset: String(listItem.props["data-task-marker-offset"]) },
193 }),
194 },
195 } as unknown as Parameters<typeof onChange>[0]);
196 });
197​
198 expect(input).toBe(originalInput);
199 expect(editedText).toBe("- [ ] A longer first task\n- [x] Second");
200 expect(mounted.root.findAllByType("input")[1]!.props.checked).toBe(true);
201 } finally {
202 await act(async () => renderer?.unmount());
203 vi.unstubAllGlobals();
204 }
205 });
206});
207​
208describe("canUseMarkdownFileShellActions", () => {
209 const environmentId = EnvironmentId.make("environment-1");
210​
211 it("allows editor and file manager actions for local environments", () => {
212 expect(canUseMarkdownFileShellActions(environmentId, "local-exec", true)).toBe(true);
213 });
214​
215 it("hides shell actions until the environment mode is resolved", () => {
216 expect(canUseMarkdownFileShellActions(environmentId, "local-exec", false)).toBe(false);
217 });
218​
219 it("hides editor and file manager actions for remote environments", () => {
220 expect(canUseMarkdownFileShellActions(environmentId, "remote-links", true)).toBe(false);
221 expect(canUseMarkdownFileShellActions(environmentId, "remote-unavailable", true)).toBe(false);
222 });
223​
224 it("hides shell actions when no environment owns the markdown", () => {
225 expect(canUseMarkdownFileShellActions(null, "local-exec", true)).toBe(false);
226 });
227});
228​
229describe("hasMarkdownFilePrimaryAction", () => {
230 it("keeps the chip interactive when an editor, browser, or panel can open it", () => {
231 expect(
232 hasMarkdownFilePrimaryAction({
233 canOpenInEditor: true,
234 canOpenInBrowser: false,
235 canOpenInPanel: false,
236 }),
237 ).toBe(true);
238 expect(
239 hasMarkdownFilePrimaryAction({
240 canOpenInEditor: false,
241 canOpenInBrowser: true,
242 canOpenInPanel: false,
243 }),
244 ).toBe(true);
245 expect(
246 hasMarkdownFilePrimaryAction({
247 canOpenInEditor: false,
248 canOpenInBrowser: false,
249 canOpenInPanel: true,
250 }),
251 ).toBe(true);
252 });
253​
254 it("removes the link affordance when no primary action can open the file", () => {
255 expect(
256 hasMarkdownFilePrimaryAction({
257 canOpenInEditor: false,
258 canOpenInBrowser: false,
259 canOpenInPanel: false,
260 }),
261 ).toBe(false);
262 });
263});
264​
265describe("ChatMarkdown file option chips", () => {
266 it("keeps the fallback button text selectable", () => {
267 const html = renderToStaticMarkup(
268 <ChatMarkdown cwd="/tmp/project" text="[Source](/tmp/project/src/main.ts)" />,
269 );
270​
271 expect(html).toContain("<button");
272 expect(html).toContain('aria-haspopup="menu"');
273 expect(html).toContain("select-text");
274 });
275​
276 it.each([true, false])(
277 "renders Codex file citations as file chips with parseRawHtml=%s",
278 (parseRawHtml) => {
279 const html = renderToStaticMarkup(
280 <ChatMarkdown
281 cwd="/tmp/project"
282 text={
283 'Created :codex-file-citation{path="/tmp/project/outputs/report.xlsx" purpose="output"}.'
284 }
285 lineBreaks={!parseRawHtml}
286 parseRawHtml={parseRawHtml}
287 />,
288 );
289​
290 expect(html).not.toContain("codex-file-citation");
291 expect(html).toContain("chat-markdown-file-link");
292 expect(html).toContain(
293 'data-markdown-copy="[report.xlsx](/tmp/project/outputs/report.xlsx)"',
294 );
295 expect(html).toContain("report.xlsx");
296 },
297 );
298​
299 it("leaves an unfinished streaming citation visible until it is complete", () => {
300 const html = renderToStaticMarkup(
301 <ChatMarkdown
302 cwd="/tmp/project"
303 text={'Created :codex-file-citation{path="/tmp/project/outputs/report.xlsx"'}
304 isStreaming
305 />,
306 );
307​
308 expect(html).toContain(":codex-file-citation");
309 expect(html).not.toContain("chat-markdown-file-link");
310 });
311​
312 it("leaves malformed and similarly named file directives literal", () => {
313 for (const text of [
314 ':codex-file-citation{purpose="output"}',
315 ':codex-file-citation-extra{path="/tmp/project/outputs/report.xlsx"}',
316 ]) {
317 const html = renderToStaticMarkup(<ChatMarkdown cwd="/tmp/project" text={text} />);
318​
319 expect(html).toContain(text.replaceAll('"', "&quot;"));
320 expect(html).not.toContain("chat-markdown-file-link");
321 }
322 });
323​
324 it("preserves Codex file citation examples inside code", () => {
325 const directive = ':codex-file-citation{path="/tmp/project/outputs/report.xlsx"}';
326 const html = renderToStaticMarkup(
327 <ChatMarkdown
328 cwd="/tmp/project"
329 text={`Example: \`${directive}\`\n\n\`\`\`text\n${directive}\n\`\`\``}
330 />,
331 );
332​
333 expect(html.match(/:codex-file-citation/g)).toHaveLength(2);
334 expect(html).not.toContain("chat-markdown-file-link");
335 });
336​
337 it("preserves escaped Codex file citations as literal text", () => {
338 const html = renderToStaticMarkup(
339 <ChatMarkdown
340 cwd="/tmp/project"
341 text={'Example: \\:codex-file-citation{path="/tmp/project/outputs/report.xlsx"}'}
342 />,
343 );
344​
345 expect(html).toContain(":codex-file-citation");
346 expect(html).not.toContain("chat-markdown-file-link");
347 });
348​
349 it("does not create a nested link for citations inside link text", () => {
350 const directive = ':codex-file-citation{path="/tmp/project/outputs/report.xlsx"}';
351 const html = renderToStaticMarkup(
352 <ChatMarkdown cwd="/tmp/project" text={`[See ${directive}](https://example.com)`} />,
353 );
354 const renderedText = html.replace(/<[^>]+>/g, "");
355​
356 expect(renderedText).toContain("codex-file-citation");
357 expect(html).not.toContain("chat-markdown-file-link");
358 });
359​
360 it("renders file citations created by over-indented list recovery", () => {
361 const html = renderToStaticMarkup(
362 <ChatMarkdown
363 cwd="/tmp/project"
364 text={'- Created :codex-file-citation{path="/tmp/project/outputs/report.xlsx"}'}
365 />,
366 );
367​
368 expect(html).not.toContain("<pre>");
369 expect(html).toContain("Created ");
370 expect(html).toContain("chat-markdown-file-link");
371 expect(html).toContain("report.xlsx");
372 });
373​
374 it("disambiguates Codex citations with the same basename", () => {
375 const html = renderToStaticMarkup(
376 <ChatMarkdown
377 cwd="/tmp/project"
378 text={
379 'Changed :codex-file-citation{path="/tmp/project/src/index.ts"} and :codex-file-citation{path="/tmp/project/test/index.ts"}.'
380 }
381 />,
382 );
383​
384 expect(html).toContain("index.ts · project/src");
385 expect(html).toContain("index.ts · project/test");
386 });
387​
388 it("preserves rejected citations created by over-indented list recovery", () => {
389 const malformedHtml = renderToStaticMarkup(
390 <ChatMarkdown
391 cwd="/tmp/project"
392 text={'Leading text before list.\n\n- Bad :codex-file-citation{purpose="output"}'}
393 />,
394 );
395 const nestedLinkHtml = renderToStaticMarkup(
396 <ChatMarkdown
397 cwd="/tmp/project"
398 text={
399 'Leading text before list.\n\n- [Bad :codex-file-citation{path="/tmp/project/report.xlsx"}](https://example.com)'
400 }
401 />,
402 );
403 const nestedLinkText = nestedLinkHtml.replace(/<[^>]+>/g, "");
404​
405 expect(malformedHtml).toContain(
406 "<li>Bad :codex-file-citation{purpose=&quot;output&quot;}</li>",
407 );
408 expect(nestedLinkText).toContain(
409 "Bad :codex-file-citation{path=&quot;/tmp/project/report.xlsx&quot;}",
410 );
411 });
412});
413​
414const ARTIFACT_TEMPLATE_DIRECTIVE =
415 '::artifact-template{skill_name="artifact-template-hello-world" skill_directory="/Users/test/.codex/skills/artifact-template-hello-world" display_name="Hello World" artifact_kind="document"}';
416​
417describe("ChatMarkdown artifact-template cards", () => {
418 it.each([true, false])("renders the Codex result card with parseRawHtml=%s", (parseRawHtml) => {
419 const html = renderToStaticMarkup(
420 <ChatMarkdown
421 cwd="/tmp/project"
422 text={ARTIFACT_TEMPLATE_DIRECTIVE}
423 parseRawHtml={parseRawHtml}
424 onUseArtifactTemplate={() => undefined}
425 />,
426 );
427​
428 expect(html).not.toContain("::artifact-template");
429 expect(html).toContain("chat-markdown-artifact-template");
430 expect(html).toContain('data-artifact-kind="document"');
431 expect(html).toContain('data-markdown-copy="Hello World (Document template)\n\n"');
432 expect(html).toContain('data-skill-name="artifact-template-hello-world"');
433 expect(html).toContain("Hello World");
434 expect(html).toContain("Document template");
435 expect(html).toContain("Use template");
436 expect(html).not.toContain("<p><div");
437 });
438​
439 it("renders a passive card outside a composer-backed timeline", () => {
440 const html = renderToStaticMarkup(
441 <ChatMarkdown cwd="/tmp/project" text={ARTIFACT_TEMPLATE_DIRECTIVE} />,
442 );
443​
444 expect(html).toContain("chat-markdown-artifact-template");
445 expect(html).not.toContain("Use template");
446 });
447​
448 it("leaves malformed and unfinished artifact-template directives literal", () => {
449 const malformed =
450 '::artifact-template{skill_name="artifact-template-hello-world" display_name="Hello World" artifact_kind="document"}';
451 const unfinished = ARTIFACT_TEMPLATE_DIRECTIVE.slice(0, -1);
452​
453 for (const text of [malformed, unfinished]) {
454 const html = renderToStaticMarkup(<ChatMarkdown cwd="/tmp/project" text={text} />);
455 expect(html).toContain("::artifact-template");
456 expect(html).not.toContain("chat-markdown-artifact-template");
457 }
458 });
459​
460 it("leaves escaped and similarly named artifact-template directives literal", () => {
461 for (const text of [
462 `\\${ARTIFACT_TEMPLATE_DIRECTIVE}`,
463 ARTIFACT_TEMPLATE_DIRECTIVE.replace("::artifact-template", "::artifact-template-extra"),
464 ]) {
465 const html = renderToStaticMarkup(<ChatMarkdown cwd="/tmp/project" text={text} />);
466​
467 expect(html).toContain("::artifact-template");
468 expect(html).not.toContain("chat-markdown-artifact-template");
469 }
470 });
471​
472 it("preserves artifact-template examples inside code", () => {
473 const html = renderToStaticMarkup(
474 <ChatMarkdown
475 cwd="/tmp/project"
476 text={`\`${ARTIFACT_TEMPLATE_DIRECTIVE}\`\n\n\`\`\`text\n${ARTIFACT_TEMPLATE_DIRECTIVE}\n\`\`\``}
477 />,
478 );
479​
480 expect(html.match(/::artifact-template/g)).toHaveLength(2);
481 expect(html).not.toContain("chat-markdown-artifact-template");
482 });
483});
484​
485describe("shouldUseMarkdownFileBrowserPrimaryAction", () => {
486 it("uses the browser when it is the only available primary action", () => {
487 expect(
488 shouldUseMarkdownFileBrowserPrimaryAction({
489 iconPath: "/tmp/report.html",
490 canOpenInEditor: false,
491 canOpenInBrowser: true,
492 canOpenInPanel: false,
493 }),
494 ).toBe(true);
495 });
496​
497 it("preserves the normal editor and panel defaults for HTML files", () => {
498 expect(
499 shouldUseMarkdownFileBrowserPrimaryAction({
500 iconPath: "/tmp/report.html",
501 canOpenInEditor: true,
502 canOpenInBrowser: true,
503 canOpenInPanel: false,
504 }),
505 ).toBe(false);
506 expect(
507 shouldUseMarkdownFileBrowserPrimaryAction({
508 iconPath: "/tmp/report.html",
509 canOpenInEditor: false,
510 canOpenInBrowser: true,
511 canOpenInPanel: true,
512 }),
513 ).toBe(false);
514 });
515​
516 it("continues to open PDF files in the browser by default", () => {
517 expect(
518 shouldUseMarkdownFileBrowserPrimaryAction({
519 iconPath: "/tmp/report.pdf",
520 canOpenInEditor: true,
521 canOpenInBrowser: true,
522 canOpenInPanel: true,
523 }),
524 ).toBe(true);
525 });
526});
527​
528describe("orderedListGutterStyle", () => {
529 it("leaves the default gutter alone for single-digit lists", () => {
530 expect(orderedListGutterStyle(9, undefined)).toBeUndefined();
531 });
532​
533 it("widens the gutter for two-digit lists", () => {
534 expect(orderedListGutterStyle(99, undefined)).toEqual({ "--list-gutter": "3ch" });
535 });
536​
537 it("widens the gutter for a two-digit list that starts above 1", () => {
538 // start=50 + 49 items => last marker is "98", still two digits.
539 expect(orderedListGutterStyle(49, 50)).toEqual({ "--list-gutter": "3ch" });
540 });
541​
542 it("widens the gutter once the last marker reaches three digits", () => {
543 // item 100 is the bug from #6512: a 100-item list starting at 1.
544 expect(orderedListGutterStyle(100, undefined)).toEqual({ "--list-gutter": "4ch" });
545 });
546​
547 it("accounts for a non-default start attribute", () => {
548 // start=95 + 9 items => last marker is "103", three digits.
549 expect(orderedListGutterStyle(9, 95)).toEqual({ "--list-gutter": "4ch" });
550 expect(orderedListGutterStyle(5, "999995")).toEqual({ "--list-gutter": "7ch" });
551 });
552​
553 it("scales further for four-digit markers", () => {
554 expect(orderedListGutterStyle(1000, undefined)).toEqual({ "--list-gutter": "5ch" });
555 });
556​
557 it("uses the widest marker and includes a negative start's minus sign", () => {
558 expect(orderedListGutterStyle(1001, -1000)).toEqual({ "--list-gutter": "6ch" });
559 expect(orderedListGutterStyle(3, -15)).toEqual({ "--list-gutter": "4ch" });
560 expect(orderedListGutterStyle(3, -5)).toEqual({ "--list-gutter": "3ch" });
561 });
562​
563 it("treats a missing/zero item count as a single item", () => {
564 expect(orderedListGutterStyle(0, undefined)).toBeUndefined();
565 expect(orderedListGutterStyle(0, 100)).toEqual({ "--list-gutter": "4ch" });
566 });
567});
568​
569describe("ChatMarkdown Windows file links", () => {
570 const environmentId = EnvironmentId.make("env-windows");
571​
572 it.each([true, false])("preserves drive paths with parseRawHtml=%s", (parseRawHtml) => {
573 const html = renderToStaticMarkup(
574 <ChatMarkdown
575 cwd="C:/Users/shawn/project"
576 environmentId={environmentId}
577 text="[Open](C:/Users/shawn/project/src/main.ts)"
578 lineBreaks={!parseRawHtml}
579 parseRawHtml={parseRawHtml}
580 />,
581 );
582​
583 expect(html).toContain('href="C:/Users/shawn/project/src/main.ts"');
584 expect(html).toContain("chat-markdown-file-link");
585 });
586​
587 it.each([true, false])("normalizes backslashes with parseRawHtml=%s", (parseRawHtml) => {
588 const html = renderToStaticMarkup(
589 <ChatMarkdown
590 cwd="C:/Users/shawn/project"
591 environmentId={environmentId}
592 text={String.raw`[Open](C:\Users\shawn\project\src\main.ts)`}
593 lineBreaks={!parseRawHtml}
594 parseRawHtml={parseRawHtml}
595 />,
596 );
597​
598 expect(html).toContain('href="C:/Users/shawn/project/src/main.ts"');
599 expect(html).toContain("chat-markdown-file-link");
600 });
601​
602 it.each([true, false])(
603 "distinguishes same-named backslash paths with parseRawHtml=%s",
604 (parseRawHtml) => {
605 const html = renderToStaticMarkup(
606 <ChatMarkdown
607 cwd="C:/Users/shawn/project"
608 environmentId={environmentId}
609 text={String.raw`[Source](C:\Users\shawn\project\src\index.ts) and [Test](C:\Users\shawn\project\test\index.ts)`}
610 lineBreaks={!parseRawHtml}
611 parseRawHtml={parseRawHtml}
612 />,
613 );
614​
615 expect(html).toContain("index.ts · project/src");
616 expect(html).toContain("index.ts · project/test");
617 },
618 );
619​
620 it.each([true, false])(
621 "does not disambiguate the same file in links and inline code with parseRawHtml=%s",
622 (parseRawHtml) => {
623 const path = String.raw`C:\Users\shawn\project\src\main.ts`;
624 const html = renderToStaticMarkup(
625 <ChatMarkdown
626 cwd="C:/Users/shawn/project"
627 environmentId={environmentId}
628 text={`[Source](${path}) and \`${path}\``}
629 lineBreaks={!parseRawHtml}
630 parseRawHtml={parseRawHtml}
631 />,
632 );
633​
634 expect(html.match(/chat-markdown-file-link/g)).toHaveLength(2);
635 expect(html).not.toContain("main.ts ·");
636 },
637 );
638​
639 it.each([true, false])("preserves reference links with parseRawHtml=%s", (parseRawHtml) => {
640 const html = renderToStaticMarkup(
641 <ChatMarkdown
642 cwd="C:/Users/shawn/project"
643 environmentId={environmentId}
644 text={"[Open][source]\n\n[source]: C:/Users/shawn/project/src/main.ts"}
645 lineBreaks={!parseRawHtml}
646 parseRawHtml={parseRawHtml}
647 />,
648 );
649​
650 expect(html).toContain('href="C:/Users/shawn/project/src/main.ts"');
651 expect(html).toContain("chat-markdown-file-link");
652 });
653​
654 it.each([true, false])("still rejects unsafe schemes with parseRawHtml=%s", (parseRawHtml) => {
655 const html = renderToStaticMarkup(
656 <ChatMarkdown
657 cwd="C:/Users/shawn/project"
658 environmentId={environmentId}
659 text="[unsafe](javascript:alert(1)) and [unknown](d:alert(1))"
660 lineBreaks={!parseRawHtml}
661 parseRawHtml={parseRawHtml}
662 />,
663 );
664​
665 expect(html).not.toContain("javascript:");
666 expect(html).not.toContain("d:alert");
667 expect(html).not.toContain("chat-markdown-file-link");
668 });
669});