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