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