Open History to see the last commit
1// @vitest-environment jsdom
2
3import { EnvironmentId, type AuthEnvironmentScope } from "@t3tools/contracts";
4import { act, type ComponentProps, type ReactNode } from "react";
5import { renderToStaticMarkup } from "react-dom/server";
6import { create, type ReactTestRenderer } from "react-test-renderer";
7import { describe, expect, it, vi } from "vite-plus/test";
8
9import { getSyntaxHighlighterPromise } from "../lib/syntaxHighlighting";
10import { GitHubIcon } from "./Icons";
11import { Button } from "./ui/button";
12import { setMarkdownTaskChecked } from "./files/filePreviewMode";
13
14vi.mock("@effect/atom-react", () => ({ useAtomValue: () => null }));
15vi.mock("../hooks/useTheme", () => ({ useTheme: () => ({ resolvedTheme: "dark" }) }));
16vi.mock("../hooks/useSettings", async (importOriginal) => {
17 const actual = await importOriginal<typeof import("../hooks/useSettings")>();
18 const settings = actual.getClientSettings();
19 return {
20 ...actual,
21 useClientSettings: (select?: (value: typeof settings) => unknown) =>
22 select ? select(settings) : settings,
23 };
24});
25vi.mock("./ui/tooltip", async () => {
26 const { cloneElement, isValidElement } = await import("react");
27 return {
28 Tooltip: ({ children }: { children: ReactNode }) => <>{children}</>,
29 TooltipTrigger({
30 render,
31 children,
32 }: ComponentProps<typeof import("./ui/tooltip").TooltipTrigger>) {
33 if (!isValidElement(render)) return <>{children}</>;
34 return children === undefined ? render : cloneElement(render, undefined, children);
35 },
36 TooltipPopup: () => null,
37 };
38});
39vi.mock("../state/use-atom-query-runner", () => ({ useAtomQueryRunner: () => vi.fn() }));
40vi.mock("../state/use-atom-command", () => ({ useAtomCommand: () => vi.fn() }));
41vi.mock("../state/session", async (importOriginal) => {
42 const actual = await importOriginal<typeof import("../state/session")>();
43 const { AuthStandardClientScopes } = await import("@t3tools/contracts");
44 const grantedScopes = new Set<AuthEnvironmentScope>(AuthStandardClientScopes);
45 const hasScope = (environmentId: EnvironmentId | null, scope: AuthEnvironmentScope) =>
46 environmentId !== null && grantedScopes.has(scope);
47 return {
48 ...actual,
49 useEnvironmentScope: hasScope,
50 readEnvironmentScope: hasScope,
51 usePreparedConnection: () => ({ _tag: "Loading" }),
52 };
53});
54vi.mock("../state/entities", () => ({
55 readThreadShell: () => null,
56 useProjects: () => [],
57 useServerConfigs: () => new Map(),
58}));
59vi.mock("../remoteOpen", () => ({
60 useRemoteOpenResolution: () => ({ state: { mode: "local-exec" }, isResolved: true }),
61}));
62vi.mock("../editorPreferences", () => ({
63 useOpenInPreferredEditor: () => vi.fn(),
64 usePreferredEditor: () => [null, vi.fn()],
65}));
66vi.mock("~/lib/openPullRequestLink", () => ({
67 findProjectOnChangeRequestHost: () => undefined,
68 parseChangeRequestUrl: () => null,
69 resolvePullRequestPreviewTarget: () => null,
70 useOpenChangeRequestLink: () => vi.fn(),
71}));
72
73import ChatMarkdown, {
74 canUseMarkdownFileShellActions,
75 hasMarkdownFilePrimaryAction,
76 shouldUseMarkdownFileBrowserPrimaryAction,
77} from "./ChatMarkdown";
78
79function codeButton(renderer: ReactTestRenderer, label: string) {
80 const button = renderer.root
81 .findAllByType(Button)
82 .find((instance) => instance.props["aria-label"] === label);
83 if (!button) throw new Error(`Missing code button: ${label}`);
84 return button.props as ComponentProps<typeof Button>;
85}
86
87describe("ChatMarkdown bare anchor placeholders", () => {
88 it.each(["<A>", "<a>", "<a >", "<a/>", "<A/>", "<a />"])(
89 "preserves unmatched %s without linking later blocks",
90 (token) => {
91 const text = `- **"From ${token}"** appears in the header.\n\n- **Tests:** cover inheritance.\n\nThe deferred move continues on B.\n\nSee <a href="https://example.com">the link</a>.`;
92 const document = new DOMParser().parseFromString(
93 renderToStaticMarkup(<ChatMarkdown cwd="/tmp/project" text={text} />),
94 "text/html",
95 );
96
97 expect(document.querySelector("strong")?.textContent).toBe(`"From ${token}"`);
98 expect([...document.querySelectorAll("a")].map((link) => link.textContent)).toEqual([
99 "the link",
100 ]);
101 expect(document.querySelectorAll("li")).toHaveLength(2);
102 expect(
103 [...document.querySelectorAll("p")].map((paragraph) => paragraph.textContent),
104 ).toContain("The deferred move continues on B.");
105 },
106 );
107
108 it.each(["</a> ", "<div>more</div>\n</a>"])(
109 "preserves a paired anchor closing in the raw block %s",
110 (closing) => {
111 const document = new DOMParser().parseFromString(
112 renderToStaticMarkup(
113 <ChatMarkdown cwd="/tmp/project" text={`See <a>label\n\n${closing}\n\nfinish`} />,
114 ),
115 "text/html",
116 );
117 expect(document.querySelector("p")?.textContent).toBe("See label");
118 },
119 );
120
121 it("preserves a paired anchor after comment-looking raw text", () => {
122 const document = new DOMParser().parseFromString(
123 renderToStaticMarkup(
124 <ChatMarkdown cwd="/tmp/project" text="See <a>label<script><!-- </script> --></a>" />,
125 ),
126 "text/html",
127 );
128 expect(document.querySelector("p")?.textContent).toBe("See label -->");
129 });
130
131 it.each(["<!-- </a> -->", '<div title="</a>">more</div>', '<script>"</a>"</script>'])(
132 "ignores apparent closing anchors inside %s",
133 (html) => {
134 const document = new DOMParser().parseFromString(
135 renderToStaticMarkup(
136 <ChatMarkdown cwd="/tmp/project" text={`Before <A>.\n\n${html}\n\nAfter.`} />,
137 ),
138 "text/html",
139 );
140 expect(document.querySelector("p")?.textContent).toBe("Before <A>.");
141 expect(document.querySelectorAll("a")).toHaveLength(0);
142 },
143 );
144
145 it("preserves paired HTML anchors, details, markdown links, and inline code", () => {
146 const text =
147 'Bare <a>label</a>, <a id="section"></a>, `<A>`, and [docs](https://example.com).\n\n<details><summary>More</summary>Details</details>';
148 const document = new DOMParser().parseFromString(
149 renderToStaticMarkup(<ChatMarkdown cwd="/tmp/project" text={text} />),
150 "text/html",
151 );
152
153 expect([...document.querySelectorAll("a")].map((link) => link.textContent)).toEqual([
154 "label",
155 "",
156 "docs",
157 ]);
158 expect(document.querySelector("code")?.textContent).toBe("<A>");
159 expect(document.querySelector("[data-markdown-details]")?.textContent).toContain("More");
160 });
161});
162
163describe("ChatMarkdown context references", () => {
164 it("renders text and image references through the chip renderer, with readable fallback", async () => {
165 vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
166 let renderer: ReactTestRenderer | undefined;
167 const text =
168 "See [Terminal output](t3-context://v1/terminal/term-1) and .";
169 try {
170 await act(async () => {
171 renderer = create(
172 <ChatMarkdown
173 cwd={undefined}
174 text={text}
175 renderContextReference={({ kind, label }) => (
176 <button>
177 {kind}: {label}
178 </button>
179 )}
180 />,
181 );
182 });
183 expect(
184 renderer!.root.findAllByType("button").map((button) => button.children.join("")),
185 ).toEqual(["terminal: Terminal output", "image: Error image"]);
186 expect(renderer!.root.findAllByType("img")).toHaveLength(0);
187 expect(renderer!.root.findAllByType("a")).toHaveLength(0);
188 await act(async () => {
189 renderer!.update(<ChatMarkdown cwd={undefined} text={text} />);
190 });
191 expect(renderer!.root.findAllByType("span").map((span) => span.children.join(""))).toEqual([
192 "Terminal output",
193 "Error image",
194 ]);
195 expect(renderer!.root.findAllByType("img")).toHaveLength(0);
196 } finally {
197 await act(async () => {
198 renderer?.unmount();
199 });
200 vi.unstubAllGlobals();
201 }
202 });
203
204 it("reads formatted context labels through nested markup instead of the context id", async () => {
205 vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
206 let renderer: ReactTestRenderer | undefined;
207 const seen: Array<string> = [];
208 try {
209 await act(async () => {
210 renderer = create(
211 <ChatMarkdown
212 cwd={undefined}
213 text="See [**Bold** `code`](t3-context://v1/terminal/term-1)."
214 renderContextReference={({ kind, label }) => {
215 seen.push(`${kind}: ${label}`);
216 return <button>{label}</button>;
217 }}
218 />,
219 );
220 });
221 expect(seen).toEqual(["terminal: Bold code"]);
222 } finally {
223 await act(async () => {
224 renderer?.unmount();
225 });
226 vi.unstubAllGlobals();
227 }
228 });
229});
230
231describe("ChatMarkdown favicon privacy", () => {
232 it("suppresses private link images while preserving public links across updates", async () => {
233 vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
234 let renderer: ReactTestRenderer | undefined;
235 const markdown = (url: string) => <ChatMarkdown cwd="/tmp/project" text={`[Link](${url})`} />;
236 try {
237 await act(async () => {
238 renderer = create(markdown("https://example.com"));
239 });
240 expect(renderer!.root.findAllByType("img").map((image) => image.props.src)).toEqual([
241 "https://www.google.com/s2/favicons?domain=example.com&sz=32",
242 ]);
243 for (const url of ["http://192.168.1.10:8080", "http://localhost:3000", "http://home.arpa"]) {
244 await act(async () => {
245 renderer!.update(markdown(url));
246 });
247 expect(renderer!.root.findAllByType("img")).toHaveLength(0);
248 }
249 await act(async () => {
250 renderer!.update(markdown("https://example.com"));
251 });
252 expect(renderer!.root.findAllByType("img")).toHaveLength(1);
253 // GitHub links draw the brand mark in currentColor instead of fetching a favicon.
254 await act(async () => {
255 renderer!.update(markdown("https://github.com/pingdotgg/t3code/pull/1"));
256 });
257 expect(renderer!.root.findAllByType("img")).toHaveLength(0);
258 expect(renderer!.root.findAllByType(GitHubIcon)).toHaveLength(1);
259 } finally {
260 await act(async () => {
261 renderer?.unmount();
262 });
263 vi.unstubAllGlobals();
264 }
265 });
266});
267
268describe("ChatMarkdown streaming", () => {
269 it("runs only a complete single-line shell block after a click", async () => {
270 vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
271 const onRunShellCommand = vi.fn();
272 let renderer: ReactTestRenderer | undefined;
273 const message = (text: string, isStreaming = false) => (
274 <ChatMarkdown
275 cwd="/tmp/project"
276 text={text}
277 isStreaming={isStreaming}
278 onRunShellCommand={onRunShellCommand}
279 />
280 );
281 try {
282 await act(async () => {
283 renderer = create(message("```bash\necho hello\n```", true));
284 });
285 const mounted = renderer!;
286 expect(
287 mounted.root
288 .findAllByType(Button)
289 .some((button) => button.props["aria-label"] === "Run in terminal"),
290 ).toBe(false);
291
292 await act(async () => {
293 mounted.update(message("```bash\necho hello\n```"));
294 });
295 await act(async () => {
296 codeButton(mounted, "Run in terminal").onClick?.({} as never);
297 });
298 expect(onRunShellCommand).toHaveBeenCalledExactlyOnceWith("echo hello");
299
300 for (const text of [
301 "~~~bash\necho tilde\n~~~",
302 "> ```bash\n> echo quote\n> ```",
303 "````bash\necho four\n````",
304 ]) {
305 await act(async () => {
306 mounted.update(message(text));
307 });
308 expect(codeButton(mounted, "Run in terminal")).toBeDefined();
309 }
310
311 for (const text of [
312 "```bash\necho one\necho two\n```",
313 "```typescript\necho hello\n```",
314 "```bash\n\n```",
315 "```bash\necho hello\n\n```",
316 "```bash\necho hello\\\n```",
317 "```bash\necho safe \u202e#\n```",
318 "```bash\necho incomplete",
319 "~~~bash\necho incomplete",
320 "````bash\necho incomplete\n```",
321 '<pre><code class="language-bash">echo html</code></pre>',
322 ]) {
323 await act(async () => {
324 mounted.update(message(text));
325 });
326 expect(
327 mounted.root
328 .findAllByType(Button)
329 .some((button) => button.props["aria-label"] === "Run in terminal"),
330 ).toBe(false);
331 }
332 } finally {
333 await act(async () => renderer?.unmount());
334 vi.unstubAllGlobals();
335 }
336 });
337
338 it("does not retokenize completed lines when streaming finishes", async () => {
339 const highlighter = await getSyntaxHighlighterPromise("typescript");
340 const highlight = vi.spyOn(highlighter, "codeToHast");
341 vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
342 let renderer: ReactTestRenderer | undefined;
343 const text = "```typescript\nconst completed = 1;\nconst current = 2;";
344 try {
345 await act(async () => {
346 renderer = create(<ChatMarkdown cwd="/tmp/project" text={text} isStreaming />);
347 });
348 expect(highlight).toHaveBeenCalled();
349 highlight.mockClear();
350 await act(async () => {
351 renderer!.update(<ChatMarkdown cwd="/tmp/project" text={text + "\n```"} />);
352 });
353 expect(highlight.mock.calls.every(([code]) => !code.includes("const completed"))).toBe(true);
354 } finally {
355 await act(async () => renderer?.unmount());
356 vi.unstubAllGlobals();
357 vi.restoreAllMocks();
358 }
359 });
360
361 it("recovers highlighting after a failed fence changes without resetting its controls", async () => {
362 const highlighter = await getSyntaxHighlighterPromise("text");
363 const codeToHast = highlighter.codeToHast.bind(highlighter);
364 let fail = true;
365 vi.spyOn(highlighter, "codeToHast").mockImplementation((...args) => {
366 if (fail) throw new Error("Temporary highlighter failure");
367 return codeToHast(...args);
368 });
369 vi.spyOn(console, "error").mockImplementation(() => {});
370 vi.spyOn(console, "warn").mockImplementation(() => {});
371 vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
372 let renderer: ReactTestRenderer | undefined;
373
374 try {
375 await act(async () => {
376 renderer = create(
377 <ChatMarkdown cwd="/tmp/project" text={"```text\ninitial\n```"} isStreaming />,
378 );
379 });
380 const mounted = renderer!;
381 const codeBlock = mounted.root.findByProps({ "data-language": "text" });
382 const initialWrap = codeBlock.props["data-wrap"] === "true";
383 const wrap = codeButton(mounted, initialWrap ? "Disable line wrap" : "Wrap lines");
384 await act(async () => {
385 wrap.onClick?.({} as Parameters<NonNullable<typeof wrap.onClick>>[0]);
386 });
387 expect(mounted.root.findAllByProps({ className: "chat-markdown-shiki" })).toHaveLength(0);
388
389 fail = false;
390 await act(async () => {
391 mounted.update(
392 <ChatMarkdown cwd="/tmp/project" text={"```text\nrecovered\n```"} isStreaming />,
393 );
394 });
395 expect(mounted.root.findAllByProps({ className: "chat-markdown-shiki" })).toHaveLength(1);
396 expect(mounted.root.findByProps({ "data-language": "text" })).toBe(codeBlock);
397 expect(codeBlock.props["data-wrap"]).toBe(String(!initialWrap));
398 } finally {
399 await act(async () => renderer?.unmount());
400 vi.unstubAllGlobals();
401 vi.restoreAllMocks();
402 }
403 });
404
405 it("preserves code controls and details without highlighting an unchanged fence again", async () => {
406 const highlighter = await getSyntaxHighlighterPromise("text");
407 const highlight = vi.spyOn(highlighter, "codeToHast");
408 const writeText = vi.fn(async (_text: string) => {});
409 vi.stubGlobal("navigator", { clipboard: { writeText } });
410 vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
411 vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] });
412 let renderer: ReactTestRenderer | undefined;
413 const text = [
414 "```text",
415 "First code block",
416 "```",
417 "",
418 "<details><summary>More</summary>",
419 "",
420 "Details content",
421 "",
422 "</details>",
423 "",
424 "Streaming reply",
425 ].join("\n");
426
427 try {
428 await act(async () => {
429 renderer = create(<ChatMarkdown cwd="/tmp/project" text={text} isStreaming />);
430 });
431 const mounted = renderer!;
432 const codeBlock = mounted.root.findByProps({ "data-language": "text" });
433 const initialWrap = codeBlock.props["data-wrap"] === "true";
434 const wrap = codeButton(mounted, initialWrap ? "Disable line wrap" : "Wrap lines");
435 const copy = codeButton(mounted, "Copy code");
436 await act(async () => {
437 wrap.onClick?.({} as Parameters<NonNullable<typeof wrap.onClick>>[0]);
438 copy.onClick?.({} as Parameters<NonNullable<typeof copy.onClick>>[0]);
439 });
440
441 const detailsButton = mounted.root.find(
442 (instance) =>
443 instance.type === "button" && instance.props["data-markdown-details-summary"] === "",
444 );
445 await act(async () => {
446 detailsButton.props.onClick({ nativeEvent: new Event("click") });
447 });
448 const details = mounted.root.findByProps({ "data-markdown-details": "" });
449 expect(details.props["data-markdown-details-open"]).toBe("true");
450 expect(writeText).toHaveBeenCalledWith("First code block\n");
451 expect(highlight).toHaveBeenCalledTimes(1);
452
453 for (let index = 0; index < 10; index += 1) {
454 await act(async () => {
455 mounted.update(<ChatMarkdown cwd="/tmp/project" text={`${text} ${index}`} isStreaming />);
456 });
457 }
458
459 expect(highlight).toHaveBeenCalledTimes(1);
460 expect(mounted.root.findByProps({ "data-language": "text" })).toBe(codeBlock);
461 expect(codeBlock.props["data-wrap"]).toBe(String(!initialWrap));
462 expect(mounted.root.findByProps({ "data-markdown-details": "" })).toBe(details);
463 expect(details.props["data-markdown-details-open"]).toBe("true");
464 await act(async () => {
465 mounted.update(
466 <ChatMarkdown
467 cwd="/tmp/project"
468 text={text.replace("First code block", "Updated code block")}
469 isStreaming
470 />,
471 );
472 });
473 const copyUpdated = codeButton(mounted, "Copied");
474 await act(async () => {
475 copyUpdated.onClick?.({} as Parameters<NonNullable<typeof copyUpdated.onClick>>[0]);
476 });
477 expect(writeText).toHaveBeenLastCalledWith("Updated code block\n");
478 expect(highlight).toHaveBeenCalledTimes(2);
479 } finally {
480 await act(async () => renderer?.unmount());
481 vi.useRealTimers();
482 vi.unstubAllGlobals();
483 vi.restoreAllMocks();
484 }
485 });
486
487 it("edits the current task text and marker after reusing a renderer", async () => {
488 vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
489 let renderer: ReactTestRenderer | undefined;
490 let editedText: string | undefined;
491 const message = (text: string) => (
492 <ChatMarkdown
493 cwd="/tmp/project"
494 text={text}
495 onTaskListChange={({ markerOffset, checked }) => {
496 editedText = setMarkdownTaskChecked(text, markerOffset, checked);
497 renderer!.update(message(editedText));
498 }}
499 />
500 );
501
502 try {
503 await act(async () => {
504 renderer = create(message("- [ ] First\n- [ ] Second"));
505 });
506 const mounted = renderer!;
507 const originalInput = mounted.root.findAllByType("input")[1]!;
508 await act(async () => {
509 mounted.update(message("- [ ] A longer first task\n- [ ] Second"));
510 });
511
512 const input = mounted.root.findAllByType("input")[1]!;
513 const listItem = mounted.root.findAllByType("li")[1]!;
514 const { onChange } = input.props as ComponentProps<"input">;
515 if (!onChange) throw new Error("Task checkbox has no edit handler");
516 await act(async () => {
517 onChange({
518 currentTarget: {
519 checked: true,
520 closest: () => ({
521 dataset: { taskMarkerOffset: String(listItem.props["data-task-marker-offset"]) },
522 }),
523 },
524 } as unknown as Parameters<typeof onChange>[0]);
525 });
526
527 expect(input).toBe(originalInput);
528 expect(editedText).toBe("- [ ] A longer first task\n- [x] Second");
529 expect(mounted.root.findAllByType("input")[1]!.props.checked).toBe(true);
530 } finally {
531 await act(async () => renderer?.unmount());
532 vi.unstubAllGlobals();
533 }
534 });
535});
536
537describe("canUseMarkdownFileShellActions", () => {
538 const environmentId = EnvironmentId.make("environment-1");
539
540 it("allows editor and file manager actions for local environments", () => {
541 expect(canUseMarkdownFileShellActions(environmentId, "local-exec", true)).toBe(true);
542 });
543
544 it("hides shell actions until the environment mode is resolved", () => {
545 expect(canUseMarkdownFileShellActions(environmentId, "local-exec", false)).toBe(false);
546 });
547
548 it("hides editor and file manager actions for remote environments", () => {
549 expect(canUseMarkdownFileShellActions(environmentId, "remote-links", true)).toBe(false);
550 expect(canUseMarkdownFileShellActions(environmentId, "remote-unavailable", true)).toBe(false);
551 });
552
553 it("hides shell actions when no environment owns the markdown", () => {
554 expect(canUseMarkdownFileShellActions(null, "local-exec", true)).toBe(false);
555 });
556});
557
558describe("hasMarkdownFilePrimaryAction", () => {
559 it("keeps the chip interactive when an editor, browser, or panel can open it", () => {
560 expect(
561 hasMarkdownFilePrimaryAction({
562 canOpenInEditor: true,
563 canOpenInBrowser: false,
564 canOpenInPanel: false,
565 }),
566 ).toBe(true);
567 expect(
568 hasMarkdownFilePrimaryAction({
569 canOpenInEditor: false,
570 canOpenInBrowser: true,
571 canOpenInPanel: false,
572 }),
573 ).toBe(true);
574 expect(
575 hasMarkdownFilePrimaryAction({
576 canOpenInEditor: false,
577 canOpenInBrowser: false,
578 canOpenInPanel: true,
579 }),
580 ).toBe(true);
581 });
582
583 it("removes the link affordance when no primary action can open the file", () => {
584 expect(
585 hasMarkdownFilePrimaryAction({
586 canOpenInEditor: false,
587 canOpenInBrowser: false,
588 canOpenInPanel: false,
589 }),
590 ).toBe(false);
591 });
592});
593
594describe("ChatMarkdown skill chips", () => {
595 it("updates digit-leading skill labels when discovered skills change", async () => {
596 vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
597 let renderer: ReactTestRenderer | undefined;
598 const text = "Use $2spec with a $20k budget.";
599 try {
600 await act(async () => {
601 renderer = create(<ChatMarkdown cwd="/tmp/project" text={text} />);
602 });
603 const mounted = renderer!;
604 const labels = (label: string) =>
605 mounted.root.findAllByType("span").filter((node) => node.children.includes(label));
606 expect(labels("2Spec")).toHaveLength(0);
607
608 await act(async () => {
609 mounted.update(
610 <ChatMarkdown
611 cwd="/tmp/project"
612 text={text}
613 skills={[
614 { name: "2spec", displayName: "2Spec" },
615 { name: "20k", displayName: "MoneySkill" },
616 ]}
617 />,
618 );
619 });
620 expect(labels("2Spec")).toHaveLength(1);
621 expect(labels("MoneySkill")).toHaveLength(0);
622
623 await act(async () => {
624 mounted.update(<ChatMarkdown cwd="/tmp/project" text={text} skills={[]} />);
625 });
626 expect(labels("2Spec")).toHaveLength(0);
627 } finally {
628 await act(async () => renderer?.unmount());
629 vi.unstubAllGlobals();
630 }
631 });
632});
633
634describe("ChatMarkdown file option chips", () => {
635 it("keeps the fallback button text selectable", () => {
636 const html = renderToStaticMarkup(
637 <ChatMarkdown cwd="/tmp/project" text="[Source](/tmp/project/src/main.ts)" />,
638 );
639
640 expect(html).toContain("<button");
641 expect(html).toContain('aria-haspopup="menu"');
642 expect(html).toContain("select-text");
643 });
644
645 it.each([true, false])(
646 "renders Codex file citations as file chips with parseRawHtml=%s",
647 (parseRawHtml) => {
648 const html = renderToStaticMarkup(
649 <ChatMarkdown
650 cwd="/tmp/project"
651 text={
652 'Created :codex-file-citation{path="/tmp/project/outputs/report.xlsx" purpose="output"}.'
653 }
654 lineBreaks={!parseRawHtml}
655 parseRawHtml={parseRawHtml}
656 />,
657 );
658
659 expect(html).not.toContain("codex-file-citation");
660 expect(html).toContain("chat-markdown-file-link");
661 expect(html).toContain(
662 'data-markdown-copy="[report.xlsx](/tmp/project/outputs/report.xlsx)"',
663 );
664 expect(html).toContain("report.xlsx");
665 },
666 );
667
668 it("leaves an unfinished streaming citation visible until it is complete", () => {
669 const html = renderToStaticMarkup(
670 <ChatMarkdown
671 cwd="/tmp/project"
672 text={'Created :codex-file-citation{path="/tmp/project/outputs/report.xlsx"'}
673 isStreaming
674 />,
675 );
676
677 expect(html).toContain(":codex-file-citation");
678 expect(html).not.toContain("chat-markdown-file-link");
679 });
680
681 it("leaves malformed and similarly named file directives literal", () => {
682 for (const text of [
683 ':codex-file-citation{purpose="output"}',
684 ':codex-file-citation-extra{path="/tmp/project/outputs/report.xlsx"}',
685 ]) {
686 const html = renderToStaticMarkup(<ChatMarkdown cwd="/tmp/project" text={text} />);
687
688 expect(html).toContain(text.replaceAll('"', """));
689 expect(html).not.toContain("chat-markdown-file-link");
690 }
691 });
692
693 it("preserves Codex file citation examples inside code", () => {
694 const directive = ':codex-file-citation{path="/tmp/project/outputs/report.xlsx"}';
695 const html = renderToStaticMarkup(
696 <ChatMarkdown
697 cwd="/tmp/project"
698 text={`Example: \`${directive}\`\n\n\`\`\`text\n${directive}\n\`\`\``}
699 />,
700 );
701
702 expect(html.match(/:codex-file-citation/g)).toHaveLength(2);
703 expect(html).not.toContain("chat-markdown-file-link");
704 });
705
706 it("preserves escaped Codex file citations as literal text", () => {
707 const html = renderToStaticMarkup(
708 <ChatMarkdown
709 cwd="/tmp/project"
710 text={'Example: \\:codex-file-citation{path="/tmp/project/outputs/report.xlsx"}'}
711 />,
712 );
713
714 expect(html).toContain(":codex-file-citation");
715 expect(html).not.toContain("chat-markdown-file-link");
716 });
717
718 it("does not create a nested link for citations inside link text", () => {
719 const directive = ':codex-file-citation{path="/tmp/project/outputs/report.xlsx"}';
720 const html = renderToStaticMarkup(
721 <ChatMarkdown cwd="/tmp/project" text={`[See ${directive}](https://example.com)`} />,
722 );
723 const renderedText = html.replace(/<[^>]+>/g, "");
724
725 expect(renderedText).toContain("codex-file-citation");
726 expect(html).not.toContain("chat-markdown-file-link");
727 });
728
729 it("renders file citations created by over-indented list recovery", () => {
730 const html = renderToStaticMarkup(
731 <ChatMarkdown
732 cwd="/tmp/project"
733 text={'- Created :codex-file-citation{path="/tmp/project/outputs/report.xlsx"}'}
734 />,
735 );
736
737 expect(html).not.toContain("<pre>");
738 expect(html).toContain("Created ");
739 expect(html).toContain("chat-markdown-file-link");
740 expect(html).toContain("report.xlsx");
741 });
742
743 it("disambiguates Codex citations with the same basename", () => {
744 const html = renderToStaticMarkup(
745 <ChatMarkdown
746 cwd="/tmp/project"
747 text={
748 'Changed :codex-file-citation{path="/tmp/project/src/index.ts"} and :codex-file-citation{path="/tmp/project/test/index.ts"}.'
749 }
750 />,
751 );
752
753 expect(html).toContain("index.ts · project/src");
754 expect(html).toContain("index.ts · project/test");
755 });
756
757 it("preserves rejected citations created by over-indented list recovery", () => {
758 const malformedHtml = renderToStaticMarkup(
759 <ChatMarkdown
760 cwd="/tmp/project"
761 text={'Leading text before list.\n\n- Bad :codex-file-citation{purpose="output"}'}
762 />,
763 );
764 const nestedLinkHtml = renderToStaticMarkup(
765 <ChatMarkdown
766 cwd="/tmp/project"
767 text={
768 'Leading text before list.\n\n- [Bad :codex-file-citation{path="/tmp/project/report.xlsx"}](https://example.com)'
769 }
770 />,
771 );
772 const nestedLinkText = nestedLinkHtml.replace(/<[^>]+>/g, "");
773
774 expect(malformedHtml).toContain(
775 "<li>Bad :codex-file-citation{purpose="output"}</li>",
776 );
777 expect(nestedLinkText).toContain(
778 "Bad :codex-file-citation{path="/tmp/project/report.xlsx"}",
779 );
780 });
781});
782
783const ARTIFACT_TEMPLATE_DIRECTIVE =
784 '::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"}';
785
786describe("ChatMarkdown artifact-template cards", () => {
787 it.each([true, false])("renders the Codex result card with parseRawHtml=%s", (parseRawHtml) => {
788 const html = renderToStaticMarkup(
789 <ChatMarkdown
790 cwd="/tmp/project"
791 text={ARTIFACT_TEMPLATE_DIRECTIVE}
792 parseRawHtml={parseRawHtml}
793 onUseArtifactTemplate={() => undefined}
794 />,
795 );
796
797 expect(html).not.toContain("::artifact-template");
798 expect(html).toContain("data-chat-markdown-artifact-template");
799 expect(html).toContain('data-artifact-kind="document"');
800 expect(html).toContain('data-markdown-copy="Hello World (Document template)\n\n"');
801 expect(html).toContain('data-skill-name="artifact-template-hello-world"');
802 expect(html).toContain("Hello World");
803 expect(html).toContain("Document template");
804 expect(html).toContain("Use template");
805 expect(html).not.toContain("<p><div");
806 });
807
808 it("renders a passive card outside a composer-backed timeline", () => {
809 const html = renderToStaticMarkup(
810 <ChatMarkdown cwd="/tmp/project" text={ARTIFACT_TEMPLATE_DIRECTIVE} />,
811 );
812
813 expect(html).toContain("data-chat-markdown-artifact-template");
814 expect(html).not.toContain("Use template");
815 });
816
817 it("leaves malformed and unfinished artifact-template directives literal", () => {
818 const malformed =
819 '::artifact-template{skill_name="artifact-template-hello-world" display_name="Hello World" artifact_kind="document"}';
820 const unfinished = ARTIFACT_TEMPLATE_DIRECTIVE.slice(0, -1);
821
822 for (const text of [malformed, unfinished]) {
823 const html = renderToStaticMarkup(<ChatMarkdown cwd="/tmp/project" text={text} />);
824 expect(html).toContain("::artifact-template");
825 expect(html).not.toContain("data-chat-markdown-artifact-template");
826 }
827 });
828
829 it("leaves escaped and similarly named artifact-template directives literal", () => {
830 for (const text of [
831 `\\${ARTIFACT_TEMPLATE_DIRECTIVE}`,
832 ARTIFACT_TEMPLATE_DIRECTIVE.replace("::artifact-template", "::artifact-template-extra"),
833 ]) {
834 const html = renderToStaticMarkup(<ChatMarkdown cwd="/tmp/project" text={text} />);
835
836 expect(html).toContain("::artifact-template");
837 expect(html).not.toContain("data-chat-markdown-artifact-template");
838 }
839 });
840
841 it("preserves artifact-template examples inside code", () => {
842 const html = renderToStaticMarkup(
843 <ChatMarkdown
844 cwd="/tmp/project"
845 text={`\`${ARTIFACT_TEMPLATE_DIRECTIVE}\`\n\n\`\`\`text\n${ARTIFACT_TEMPLATE_DIRECTIVE}\n\`\`\``}
846 />,
847 );
848
849 expect(html.match(/::artifact-template/g)).toHaveLength(2);
850 expect(html).not.toContain("data-chat-markdown-artifact-template");
851 });
852});
853
854describe("ChatMarkdown heading levels", () => {
855 it("exposes headings below the host heading without changing their tags", () => {
856 const html = renderToStaticMarkup(
857 <ChatMarkdown
858 cwd="/tmp/project"
859 text={"# Top\n\n## Section\n\n###### Fine print"}
860 headingLevelOffset={3}
861 />,
862 );
863
864 expect(html).toContain('<h1 aria-level="4">Top</h1>');
865 expect(html).toContain('<h2 aria-level="5">Section</h2>');
866 expect(html).toContain('<h6 aria-level="6">Fine print</h6>');
867 });
868
869 it("leaves heading levels alone when the markdown is not nested", () => {
870 const html = renderToStaticMarkup(<ChatMarkdown cwd="/tmp/project" text="# Top" />);
871
872 expect(html).toContain("<h1>Top</h1>");
873 });
874});
875
876describe("shouldUseMarkdownFileBrowserPrimaryAction", () => {
877 it("uses the browser when it is the only available primary action", () => {
878 expect(
879 shouldUseMarkdownFileBrowserPrimaryAction({
880 iconPath: "/tmp/report.html",
881 canOpenInEditor: false,
882 canOpenInBrowser: true,
883 canOpenInPanel: false,
884 }),
885 ).toBe(true);
886 });
887
888 it("preserves the normal editor and panel defaults for HTML files", () => {
889 expect(
890 shouldUseMarkdownFileBrowserPrimaryAction({
891 iconPath: "/tmp/report.html",
892 canOpenInEditor: true,
893 canOpenInBrowser: true,
894 canOpenInPanel: false,
895 }),
896 ).toBe(false);
897 expect(
898 shouldUseMarkdownFileBrowserPrimaryAction({
899 iconPath: "/tmp/report.html",
900 canOpenInEditor: false,
901 canOpenInBrowser: true,
902 canOpenInPanel: true,
903 }),
904 ).toBe(false);
905 });
906
907 it("continues to open PDF files in the browser by default", () => {
908 expect(
909 shouldUseMarkdownFileBrowserPrimaryAction({
910 iconPath: "/tmp/report.pdf",
911 canOpenInEditor: true,
912 canOpenInBrowser: true,
913 canOpenInPanel: true,
914 }),
915 ).toBe(true);
916 });
917});
918
919describe("ChatMarkdown Windows file links", () => {
920 const environmentId = EnvironmentId.make("env-windows");
921
922 it.each([true, false])("preserves drive paths with parseRawHtml=%s", (parseRawHtml) => {
923 const html = renderToStaticMarkup(
924 <ChatMarkdown
925 cwd="C:/Users/shawn/project"
926 environmentId={environmentId}
927 text="[Open](C:/Users/shawn/project/src/main.ts)"
928 lineBreaks={!parseRawHtml}
929 parseRawHtml={parseRawHtml}
930 />,
931 );
932
933 expect(html).toContain('href="C:/Users/shawn/project/src/main.ts"');
934 expect(html).toContain("chat-markdown-file-link");
935 });
936
937 it.each([true, false])("normalizes backslashes with parseRawHtml=%s", (parseRawHtml) => {
938 const html = renderToStaticMarkup(
939 <ChatMarkdown
940 cwd="C:/Users/shawn/project"
941 environmentId={environmentId}
942 text={String.raw`[Open](C:\Users\shawn\project\src\main.ts)`}
943 lineBreaks={!parseRawHtml}
944 parseRawHtml={parseRawHtml}
945 />,
946 );
947
948 expect(html).toContain('href="C:/Users/shawn/project/src/main.ts"');
949 expect(html).toContain("chat-markdown-file-link");
950 });
951
952 it.each([true, false])(
953 "keeps backslashes CommonMark would read as escapes with parseRawHtml=%s",
954 (parseRawHtml) => {
955 const html = renderToStaticMarkup(
956 <ChatMarkdown
957 cwd="C:/Users/shawn/project"
958 environmentId={environmentId}
959 text={String.raw`[settings](C:\Users\shawn\.claude\settings.json)`}
960 lineBreaks={!parseRawHtml}
961 parseRawHtml={parseRawHtml}
962 />,
963 );
964
965 expect(html).toContain('href="C:/Users/shawn/.claude/settings.json"');
966 },
967 );
968
969 it.each([true, false])(
970 "distinguishes same-named backslash paths with parseRawHtml=%s",
971 (parseRawHtml) => {
972 const html = renderToStaticMarkup(
973 <ChatMarkdown
974 cwd="C:/Users/shawn/project"
975 environmentId={environmentId}
976 text={String.raw`[Source](C:\Users\shawn\project\src\index.ts) and [Test](C:\Users\shawn\project\test\index.ts)`}
977 lineBreaks={!parseRawHtml}
978 parseRawHtml={parseRawHtml}
979 />,
980 );
981
982 expect(html).toContain("index.ts · project/src");
983 expect(html).toContain("index.ts · project/test");
984 },
985 );
986
987 it.each([true, false])(
988 "does not disambiguate the same file in links and inline code with parseRawHtml=%s",
989 (parseRawHtml) => {
990 const path = String.raw`C:\Users\shawn\project\src\main.ts`;
991 const html = renderToStaticMarkup(
992 <ChatMarkdown
993 cwd="C:/Users/shawn/project"
994 environmentId={environmentId}
995 text={`[Source](${path}) and \`${path}\``}
996 lineBreaks={!parseRawHtml}
997 parseRawHtml={parseRawHtml}
998 />,
999 );
1000
1001 expect(html.match(/chat-markdown-file-link/g)).toHaveLength(2);
1002 expect(html).not.toContain("main.ts ·");
1003 },
1004 );
1005
1006 it.each([true, false])("preserves reference links with parseRawHtml=%s", (parseRawHtml) => {
1007 const html = renderToStaticMarkup(
1008 <ChatMarkdown
1009 cwd="C:/Users/shawn/project"
1010 environmentId={environmentId}
1011 text={"[Open][source]\n\n[source]: C:/Users/shawn/project/src/main.ts"}
1012 lineBreaks={!parseRawHtml}
1013 parseRawHtml={parseRawHtml}
1014 />,
1015 );
1016
1017 expect(html).toContain('href="C:/Users/shawn/project/src/main.ts"');
1018 expect(html).toContain("chat-markdown-file-link");
1019 });
1020
1021 it.each([true, false])("still rejects unsafe schemes with parseRawHtml=%s", (parseRawHtml) => {
1022 const html = renderToStaticMarkup(
1023 <ChatMarkdown
1024 cwd="C:/Users/shawn/project"
1025 environmentId={environmentId}
1026 text="[unsafe](javascript:alert(1)) and [unknown](d:alert(1))"
1027 lineBreaks={!parseRawHtml}
1028 parseRawHtml={parseRawHtml}
1029 />,
1030 );
1031
1032 expect(html).not.toContain("javascript:");
1033 expect(html).not.toContain("d:alert");
1034 expect(html).not.toContain("chat-markdown-file-link");
1035 });
1036});