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

ChatMarkdown.test.tsx

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