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