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

ChatMarkdown.test.tsx

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