Open History to see the last commit
1// @vitest-environment jsdom
2
3import { EnvironmentId, type AuthEnvironmentScope } from "@t3tools/contracts";
4import { createRoot } from "react-dom/client";
5import { useThreadFindHighlights } from "./chat/threadFindHighlights";
6import { searchableMessageSegments } from "@t3tools/shared/threadFindText";
7import { countThreadSearchOccurrences } from "@t3tools/shared/threadSearch";
8
9import { MarkdownFindContext } from "./chat/markdownFindContext";
10import { act, type ComponentProps, type ReactNode } from "react";
11import { renderToStaticMarkup } from "react-dom/server";
12import { create, type ReactTestRenderer } from "react-test-renderer";
13import { describe, expect, it, vi } from "vite-plus/test";
14
15import { getSyntaxHighlighterPromise } from "../lib/syntaxHighlighting";
16import { GitHubIcon } from "./Icons";
17import { Button } from "./ui/button";
18import { setMarkdownTaskChecked } from "./files/filePreviewMode";
19
20vi.mock("../hooks/useFileMetadata", () => ({ useFileMetadata: () => null }));
21vi.mock("@effect/atom-react", () => ({ useAtomValue: () => null }));
22vi.mock("./chat/MermaidDiagram", () => ({
23 // Real Mermaid needs layout APIs jsdom lacks; a rendered diagram is an SVG.
24 MermaidDiagram: () => <svg aria-label="Diagram" />,
25}));
26vi.mock("../hooks/useTheme", () => ({ useTheme: () => ({ resolvedTheme: "dark" }) }));
27vi.mock("../hooks/useSettings", async (importOriginal) => {
28 const actual = await importOriginal<typeof import("../hooks/useSettings")>();
29 const settings = actual.getClientSettings();
30 return {
31 ...actual,
32 useClientSettings: (select?: (value: typeof settings) => unknown) =>
33 select ? select(settings) : settings,
34 };
35});
36vi.mock("./ui/tooltip", async () => {
37 const { cloneElement, isValidElement } = await import("react");
38 return {
39 Tooltip: ({ children }: { children: ReactNode }) => <>{children}</>,
40 TooltipTrigger({
41 render,
42 children,
43 }: ComponentProps<typeof import("./ui/tooltip").TooltipTrigger>) {
44 if (!isValidElement(render)) return <>{children}</>;
45 return children === undefined ? render : cloneElement(render, undefined, children);
46 },
47 TooltipPopup: () => null,
48 };
49});
50vi.mock("../state/use-atom-query-runner", () => ({ useAtomQueryRunner: () => vi.fn() }));
51vi.mock("../state/use-atom-command", () => ({ useAtomCommand: () => vi.fn() }));
52vi.mock("../state/session", async (importOriginal) => {
53 const actual = await importOriginal<typeof import("../state/session")>();
54 const { AuthStandardClientScopes } = await import("@t3tools/contracts");
55 const grantedScopes = new Set<AuthEnvironmentScope>(AuthStandardClientScopes);
56 const hasScope = (environmentId: EnvironmentId | null, scope: AuthEnvironmentScope) =>
57 environmentId !== null && grantedScopes.has(scope);
58 return {
59 ...actual,
60 useEnvironmentScope: hasScope,
61 readEnvironmentScope: hasScope,
62 usePreparedConnection: () => ({ _tag: "Loading" }),
63 };
64});
65vi.mock("../state/entities", () => ({
66 readThreadShell: () => null,
67 useProjects: () => [],
68 useServerConfigs: () => new Map(),
69}));
70vi.mock("../remoteOpen", () => ({
71 useRemoteOpenResolution: () => ({ state: { mode: "local-exec" }, isResolved: true }),
72}));
73vi.mock("../editorPreferences", () => ({
74 useOpenInPreferredEditor: () => vi.fn(),
75 usePreferredEditor: () => [null, vi.fn()],
76}));
77vi.mock("~/lib/openPullRequestLink", () => ({
78 findProjectOnChangeRequestHost: () => undefined,
79 parseChangeRequestUrl: () => null,
80 resolvePullRequestPreviewTarget: () => null,
81 useOpenChangeRequestLink: () => vi.fn(),
82}));
83
84import ChatMarkdown, {
85 canUseMarkdownFileShellActions,
86 hasMarkdownFilePrimaryAction,
87 shouldUseMarkdownFileBrowserPrimaryAction,
88} from "./ChatMarkdown";
89
90function codeButton(renderer: ReactTestRenderer, label: string) {
91 const button = renderer.root
92 .findAllByType(Button)
93 .find((instance) => instance.props["aria-label"] === label);
94 if (!button) throw new Error(`Missing code button: ${label}`);
95 return button.props as ComponentProps<typeof Button>;
96}
97
98describe("ChatMarkdown bare anchor placeholders", () => {
99 it.each(["<A>", "<a>", "<a >", "<a/>", "<A/>", "<a />"])(
100 "preserves unmatched %s without linking later blocks",
101 (token) => {
102 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>.`;
103 const document = new DOMParser().parseFromString(
104 renderToStaticMarkup(<ChatMarkdown cwd="/tmp/project" text={text} />),
105 "text/html",
106 );
107
108 expect(document.querySelector("strong")?.textContent).toBe(`"From ${token}"`);
109 expect([...document.querySelectorAll("a")].map((link) => link.textContent)).toEqual([
110 "the link",
111 ]);
112 expect(document.querySelectorAll("li")).toHaveLength(2);
113 expect(
114 [...document.querySelectorAll("p")].map((paragraph) => paragraph.textContent),
115 ).toContain("The deferred move continues on B.");
116 },
117 );
118
119 it.each(["</a> ", "<div>more</div>\n</a>"])(
120 "preserves a paired anchor closing in the raw block %s",
121 (closing) => {
122 const document = new DOMParser().parseFromString(
123 renderToStaticMarkup(
124 <ChatMarkdown cwd="/tmp/project" text={`See <a>label\n\n${closing}\n\nfinish`} />,
125 ),
126 "text/html",
127 );
128 expect(document.querySelector("p")?.textContent).toBe("See label");
129 },
130 );
131
132 it("preserves a paired anchor after comment-looking raw text", () => {
133 const document = new DOMParser().parseFromString(
134 renderToStaticMarkup(
135 <ChatMarkdown cwd="/tmp/project" text="See <a>label<script><!-- </script> --></a>" />,
136 ),
137 "text/html",
138 );
139 expect(document.querySelector("p")?.textContent).toBe("See label -->");
140 });
141
142 it.each(["<!-- </a> -->", '<div title="</a>">more</div>', '<script>"</a>"</script>'])(
143 "ignores apparent closing anchors inside %s",
144 (html) => {
145 const document = new DOMParser().parseFromString(
146 renderToStaticMarkup(
147 <ChatMarkdown cwd="/tmp/project" text={`Before <A>.\n\n${html}\n\nAfter.`} />,
148 ),
149 "text/html",
150 );
151 expect(document.querySelector("p")?.textContent).toBe("Before <A>.");
152 expect(document.querySelectorAll("a")).toHaveLength(0);
153 },
154 );
155
156 it("preserves paired HTML anchors, details, markdown links, and inline code", () => {
157 const text =
158 'Bare <a>label</a>, <a id="section"></a>, `<A>`, and [docs](https://example.com).\n\n<details><summary>More</summary>Details</details>';
159 const document = new DOMParser().parseFromString(
160 renderToStaticMarkup(<ChatMarkdown cwd="/tmp/project" text={text} />),
161 "text/html",
162 );
163
164 expect([...document.querySelectorAll("a")].map((link) => link.textContent)).toEqual([
165 "label",
166 "",
167 "docs",
168 ]);
169 expect(document.querySelector("code")?.textContent).toBe("<A>");
170 expect(document.querySelector("[data-markdown-details]")?.textContent).toContain("More");
171 });
172});
173
174describe("ChatMarkdown context references", () => {
175 it("renders text and image references through the chip renderer, with readable fallback", async () => {
176 vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
177 let renderer: ReactTestRenderer | undefined;
178 const text =
179 "See [Terminal output](t3-context://v1/terminal/term-1) and .";
180 try {
181 await act(async () => {
182 renderer = create(
183 <ChatMarkdown
184 cwd={undefined}
185 text={text}
186 renderContextReference={({ kind, label }) => (
187 <button>
188 {kind}: {label}
189 </button>
190 )}
191 />,
192 );
193 });
194 expect(
195 renderer!.root.findAllByType("button").map((button) => button.children.join("")),
196 ).toEqual(["terminal: Terminal output", "image: Error image"]);
197 expect(renderer!.root.findAllByType("img")).toHaveLength(0);
198 expect(renderer!.root.findAllByType("a")).toHaveLength(0);
199 await act(async () => {
200 renderer!.update(<ChatMarkdown cwd={undefined} text={text} />);
201 });
202 expect(renderer!.root.findAllByType("span").map((span) => span.children.join(""))).toEqual([
203 "Terminal output",
204 "Error image",
205 ]);
206 expect(renderer!.root.findAllByType("img")).toHaveLength(0);
207 } finally {
208 await act(async () => {
209 renderer?.unmount();
210 });
211 vi.unstubAllGlobals();
212 }
213 });
214
215 it("reads formatted context labels through nested markup instead of the context id", async () => {
216 vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
217 let renderer: ReactTestRenderer | undefined;
218 const seen: Array<string> = [];
219 try {
220 await act(async () => {
221 renderer = create(
222 <ChatMarkdown
223 cwd={undefined}
224 text="See [**Bold** `code`](t3-context://v1/terminal/term-1)."
225 renderContextReference={({ kind, label }) => {
226 seen.push(`${kind}: ${label}`);
227 return <button>{label}</button>;
228 }}
229 />,
230 );
231 });
232 expect(seen).toEqual(["terminal: Bold code"]);
233 } finally {
234 await act(async () => {
235 renderer?.unmount();
236 });
237 vi.unstubAllGlobals();
238 }
239 });
240});
241
242describe("ChatMarkdown favicon privacy", () => {
243 it("suppresses private link images while preserving public links across updates", async () => {
244 vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
245 let renderer: ReactTestRenderer | undefined;
246 const markdown = (url: string) => <ChatMarkdown cwd="/tmp/project" text={`[Link](${url})`} />;
247 try {
248 await act(async () => {
249 renderer = create(markdown("https://example.com"));
250 });
251 expect(renderer!.root.findAllByType("img").map((image) => image.props.src)).toEqual([
252 "https://www.google.com/s2/favicons?domain=example.com&sz=32",
253 ]);
254 for (const url of ["http://192.168.1.10:8080", "http://localhost:3000", "http://home.arpa"]) {
255 await act(async () => {
256 renderer!.update(markdown(url));
257 });
258 expect(renderer!.root.findAllByType("img")).toHaveLength(0);
259 }
260 await act(async () => {
261 renderer!.update(markdown("https://example.com"));
262 });
263 expect(renderer!.root.findAllByType("img")).toHaveLength(1);
264 // GitHub links draw the brand mark in currentColor instead of fetching a favicon.
265 await act(async () => {
266 renderer!.update(markdown("https://github.com/pingdotgg/t3code/pull/1"));
267 });
268 expect(renderer!.root.findAllByType("img")).toHaveLength(0);
269 expect(renderer!.root.findAllByType(GitHubIcon)).toHaveLength(1);
270 } finally {
271 await act(async () => {
272 renderer?.unmount();
273 });
274 vi.unstubAllGlobals();
275 }
276 });
277});
278
279describe("ChatMarkdown streaming", () => {
280 it("runs only a complete single-line shell block after a click", async () => {
281 vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
282 const onRunShellCommand = vi.fn();
283 let renderer: ReactTestRenderer | undefined;
284 const message = (text: string, isStreaming = false) => (
285 <ChatMarkdown
286 cwd="/tmp/project"
287 text={text}
288 isStreaming={isStreaming}
289 onRunShellCommand={onRunShellCommand}
290 />
291 );
292 try {
293 await act(async () => {
294 renderer = create(message("```bash\necho hello\n```", true));
295 });
296 const mounted = renderer!;
297 expect(
298 mounted.root
299 .findAllByType(Button)
300 .some((button) => button.props["aria-label"] === "Run in terminal"),
301 ).toBe(false);
302
303 await act(async () => {
304 mounted.update(message("```bash\necho hello\n```"));
305 });
306 await act(async () => {
307 codeButton(mounted, "Run in terminal").onClick?.({} as never);
308 });
309 expect(onRunShellCommand).toHaveBeenCalledExactlyOnceWith("echo hello");
310
311 for (const text of [
312 "~~~bash\necho tilde\n~~~",
313 "> ```bash\n> echo quote\n> ```",
314 "````bash\necho four\n````",
315 ]) {
316 await act(async () => {
317 mounted.update(message(text));
318 });
319 expect(codeButton(mounted, "Run in terminal")).toBeDefined();
320 }
321
322 for (const text of [
323 "```bash\necho one\necho two\n```",
324 "```typescript\necho hello\n```",
325 "```bash\n\n```",
326 "```bash\necho hello\n\n```",
327 "```bash\necho hello\\\n```",
328 "```bash\necho safe \u202e#\n```",
329 "```bash\necho incomplete",
330 "~~~bash\necho incomplete",
331 "````bash\necho incomplete\n```",
332 '<pre><code class="language-bash">echo html</code></pre>',
333 ]) {
334 await act(async () => {
335 mounted.update(message(text));
336 });
337 expect(
338 mounted.root
339 .findAllByType(Button)
340 .some((button) => button.props["aria-label"] === "Run in terminal"),
341 ).toBe(false);
342 }
343 } finally {
344 await act(async () => renderer?.unmount());
345 vi.unstubAllGlobals();
346 }
347 });
348
349 it("does not retokenize completed lines when streaming finishes", async () => {
350 const highlighter = await getSyntaxHighlighterPromise("typescript");
351 const highlight = vi.spyOn(highlighter, "codeToHast");
352 vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
353 let renderer: ReactTestRenderer | undefined;
354 const text = "```typescript\nconst completed = 1;\nconst current = 2;";
355 try {
356 await act(async () => {
357 renderer = create(<ChatMarkdown cwd="/tmp/project" text={text} isStreaming />);
358 });
359 expect(highlight).toHaveBeenCalled();
360 highlight.mockClear();
361 await act(async () => {
362 renderer!.update(<ChatMarkdown cwd="/tmp/project" text={text + "\n```"} />);
363 });
364 expect(highlight.mock.calls.every(([code]) => !code.includes("const completed"))).toBe(true);
365 } finally {
366 await act(async () => renderer?.unmount());
367 vi.unstubAllGlobals();
368 vi.restoreAllMocks();
369 }
370 });
371
372 it("recovers highlighting after a failed fence changes without resetting its controls", async () => {
373 const highlighter = await getSyntaxHighlighterPromise("text");
374 const codeToHast = highlighter.codeToHast.bind(highlighter);
375 let fail = true;
376 vi.spyOn(highlighter, "codeToHast").mockImplementation((...args) => {
377 if (fail) throw new Error("Temporary highlighter failure");
378 return codeToHast(...args);
379 });
380 vi.spyOn(console, "error").mockImplementation(() => {});
381 vi.spyOn(console, "warn").mockImplementation(() => {});
382 vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
383 let renderer: ReactTestRenderer | undefined;
384
385 try {
386 await act(async () => {
387 renderer = create(
388 <ChatMarkdown cwd="/tmp/project" text={"```text\ninitial\n```"} isStreaming />,
389 );
390 });
391 const mounted = renderer!;
392 const codeBlock = mounted.root.findByProps({ "data-language": "text" });
393 const initialWrap = codeBlock.props["data-wrap"] === "true";
394 const wrap = codeButton(mounted, initialWrap ? "Disable line wrap" : "Wrap lines");
395 await act(async () => {
396 wrap.onClick?.({} as Parameters<NonNullable<typeof wrap.onClick>>[0]);
397 });
398 expect(mounted.root.findAllByProps({ className: "chat-markdown-shiki" })).toHaveLength(0);
399
400 fail = false;
401 await act(async () => {
402 mounted.update(
403 <ChatMarkdown cwd="/tmp/project" text={"```text\nrecovered\n```"} isStreaming />,
404 );
405 });
406 expect(mounted.root.findAllByProps({ className: "chat-markdown-shiki" })).toHaveLength(1);
407 expect(mounted.root.findByProps({ "data-language": "text" })).toBe(codeBlock);
408 expect(codeBlock.props["data-wrap"]).toBe(String(!initialWrap));
409 } finally {
410 await act(async () => renderer?.unmount());
411 vi.unstubAllGlobals();
412 vi.restoreAllMocks();
413 }
414 });
415
416 it("preserves code controls and details without highlighting an unchanged fence again", async () => {
417 const highlighter = await getSyntaxHighlighterPromise("text");
418 const highlight = vi.spyOn(highlighter, "codeToHast");
419 const writeText = vi.fn(async (_text: string) => {});
420 vi.stubGlobal("navigator", { clipboard: { writeText } });
421 vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
422 vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] });
423 let renderer: ReactTestRenderer | undefined;
424 const text = [
425 "```text",
426 "First code block",
427 "```",
428 "",
429 "<details><summary>More</summary>",
430 "",
431 "Details content",
432 "",
433 "</details>",
434 "",
435 "Streaming reply",
436 ].join("\n");
437
438 try {
439 await act(async () => {
440 renderer = create(<ChatMarkdown cwd="/tmp/project" text={text} isStreaming />);
441 });
442 const mounted = renderer!;
443 const codeBlock = mounted.root.findByProps({ "data-language": "text" });
444 const initialWrap = codeBlock.props["data-wrap"] === "true";
445 const wrap = codeButton(mounted, initialWrap ? "Disable line wrap" : "Wrap lines");
446 const copy = codeButton(mounted, "Copy code");
447 await act(async () => {
448 wrap.onClick?.({} as Parameters<NonNullable<typeof wrap.onClick>>[0]);
449 copy.onClick?.({} as Parameters<NonNullable<typeof copy.onClick>>[0]);
450 });
451
452 const detailsButton = mounted.root.find(
453 (instance) =>
454 instance.type === "button" && instance.props["data-markdown-details-summary"] === "",
455 );
456 await act(async () => {
457 detailsButton.props.onClick({ nativeEvent: new Event("click") });
458 });
459 const details = mounted.root.findByProps({ "data-markdown-details": "" });
460 expect(details.props["data-markdown-details-open"]).toBe("true");
461 expect(writeText).toHaveBeenCalledWith("First code block\n");
462 expect(highlight).toHaveBeenCalledTimes(1);
463
464 for (let index = 0; index < 10; index += 1) {
465 await act(async () => {
466 mounted.update(<ChatMarkdown cwd="/tmp/project" text={`${text} ${index}`} isStreaming />);
467 });
468 }
469
470 expect(highlight).toHaveBeenCalledTimes(1);
471 expect(mounted.root.findByProps({ "data-language": "text" })).toBe(codeBlock);
472 expect(codeBlock.props["data-wrap"]).toBe(String(!initialWrap));
473 expect(mounted.root.findByProps({ "data-markdown-details": "" })).toBe(details);
474 expect(details.props["data-markdown-details-open"]).toBe("true");
475 await act(async () => {
476 mounted.update(
477 <ChatMarkdown
478 cwd="/tmp/project"
479 text={text.replace("First code block", "Updated code block")}
480 isStreaming
481 />,
482 );
483 });
484 const copyUpdated = codeButton(mounted, "Copied");
485 await act(async () => {
486 copyUpdated.onClick?.({} as Parameters<NonNullable<typeof copyUpdated.onClick>>[0]);
487 });
488 expect(writeText).toHaveBeenLastCalledWith("Updated code block\n");
489 expect(highlight).toHaveBeenCalledTimes(2);
490 } finally {
491 await act(async () => renderer?.unmount());
492 vi.useRealTimers();
493 vi.unstubAllGlobals();
494 vi.restoreAllMocks();
495 }
496 });
497
498 it("edits the current task text and marker after reusing a renderer", async () => {
499 vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
500 let renderer: ReactTestRenderer | undefined;
501 let editedText: string | undefined;
502 const message = (text: string) => (
503 <ChatMarkdown
504 cwd="/tmp/project"
505 text={text}
506 onTaskListChange={({ markerOffset, checked }) => {
507 editedText = setMarkdownTaskChecked(text, markerOffset, checked);
508 renderer!.update(message(editedText));
509 }}
510 />
511 );
512
513 try {
514 await act(async () => {
515 renderer = create(message("- [ ] First\n- [ ] Second"));
516 });
517 const mounted = renderer!;
518 const originalInput = mounted.root.findAllByType("input")[1]!;
519 await act(async () => {
520 mounted.update(message("- [ ] A longer first task\n- [ ] Second"));
521 });
522
523 const input = mounted.root.findAllByType("input")[1]!;
524 const listItem = mounted.root.findAllByType("li")[1]!;
525 const { onChange } = input.props as ComponentProps<"input">;
526 if (!onChange) throw new Error("Task checkbox has no edit handler");
527 await act(async () => {
528 onChange({
529 currentTarget: {
530 checked: true,
531 closest: () => ({
532 dataset: { taskMarkerOffset: String(listItem.props["data-task-marker-offset"]) },
533 }),
534 },
535 } as unknown as Parameters<typeof onChange>[0]);
536 });
537
538 expect(input).toBe(originalInput);
539 expect(editedText).toBe("- [ ] A longer first task\n- [x] Second");
540 expect(mounted.root.findAllByType("input")[1]!.props.checked).toBe(true);
541 } finally {
542 await act(async () => renderer?.unmount());
543 vi.unstubAllGlobals();
544 }
545 });
546});
547
548describe("canUseMarkdownFileShellActions", () => {
549 const environmentId = EnvironmentId.make("environment-1");
550
551 it("allows editor and file manager actions for local environments", () => {
552 expect(canUseMarkdownFileShellActions(environmentId, "local-exec", true)).toBe(true);
553 });
554
555 it("hides shell actions until the environment mode is resolved", () => {
556 expect(canUseMarkdownFileShellActions(environmentId, "local-exec", false)).toBe(false);
557 });
558
559 it("hides editor and file manager actions for remote environments", () => {
560 expect(canUseMarkdownFileShellActions(environmentId, "remote-links", true)).toBe(false);
561 expect(canUseMarkdownFileShellActions(environmentId, "remote-unavailable", true)).toBe(false);
562 });
563
564 it("hides shell actions when no environment owns the markdown", () => {
565 expect(canUseMarkdownFileShellActions(null, "local-exec", true)).toBe(false);
566 });
567});
568
569describe("hasMarkdownFilePrimaryAction", () => {
570 it("keeps the chip interactive when an editor, browser, or panel can open it", () => {
571 expect(
572 hasMarkdownFilePrimaryAction({
573 canOpenInEditor: true,
574 canOpenInBrowser: false,
575 canOpenInPanel: false,
576 }),
577 ).toBe(true);
578 expect(
579 hasMarkdownFilePrimaryAction({
580 canOpenInEditor: false,
581 canOpenInBrowser: true,
582 canOpenInPanel: false,
583 }),
584 ).toBe(true);
585 expect(
586 hasMarkdownFilePrimaryAction({
587 canOpenInEditor: false,
588 canOpenInBrowser: false,
589 canOpenInPanel: true,
590 }),
591 ).toBe(true);
592 });
593
594 it("removes the link affordance when no primary action can open the file", () => {
595 expect(
596 hasMarkdownFilePrimaryAction({
597 canOpenInEditor: false,
598 canOpenInBrowser: false,
599 canOpenInPanel: false,
600 }),
601 ).toBe(false);
602 });
603});
604
605describe("ChatMarkdown skill chips", () => {
606 it("updates digit-leading skill labels when discovered skills change", async () => {
607 vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
608 let renderer: ReactTestRenderer | undefined;
609 const text = "Use $2spec with a $20k budget.";
610 try {
611 await act(async () => {
612 renderer = create(<ChatMarkdown cwd="/tmp/project" text={text} />);
613 });
614 const mounted = renderer!;
615 const labels = (label: string) =>
616 mounted.root.findAllByType("span").filter((node) => node.children.includes(label));
617 expect(labels("2Spec")).toHaveLength(0);
618
619 await act(async () => {
620 mounted.update(
621 <ChatMarkdown
622 cwd="/tmp/project"
623 text={text}
624 skills={[
625 { name: "2spec", displayName: "2Spec" },
626 { name: "20k", displayName: "MoneySkill" },
627 ]}
628 />,
629 );
630 });
631 expect(labels("2Spec")).toHaveLength(1);
632 expect(labels("MoneySkill")).toHaveLength(0);
633
634 await act(async () => {
635 mounted.update(<ChatMarkdown cwd="/tmp/project" text={text} skills={[]} />);
636 });
637 expect(labels("2Spec")).toHaveLength(0);
638 } finally {
639 await act(async () => renderer?.unmount());
640 vi.unstubAllGlobals();
641 }
642 });
643});
644
645describe("ChatMarkdown file option chips", () => {
646 it("keeps the fallback button text selectable", () => {
647 const html = renderToStaticMarkup(
648 <ChatMarkdown cwd="/tmp/project" text="[Source](/tmp/project/src/main.ts)" />,
649 );
650
651 expect(html).toContain("<button");
652 expect(html).toContain('aria-haspopup="menu"');
653 expect(html).toContain("select-text");
654 });
655
656 it.each([true, false])(
657 "renders Codex file citations as file chips with parseRawHtml=%s",
658 (parseRawHtml) => {
659 const html = renderToStaticMarkup(
660 <ChatMarkdown
661 cwd="/tmp/project"
662 text={
663 'Created :codex-file-citation{path="/tmp/project/outputs/report.xlsx" purpose="output"}.'
664 }
665 lineBreaks={!parseRawHtml}
666 parseRawHtml={parseRawHtml}
667 />,
668 );
669
670 expect(html).not.toContain("codex-file-citation");
671 expect(html).toContain("chat-markdown-file-link");
672 expect(html).toContain(
673 'data-markdown-copy="[report.xlsx](/tmp/project/outputs/report.xlsx)"',
674 );
675 expect(html).toContain("report.xlsx");
676 },
677 );
678
679 it("leaves an unfinished streaming citation visible until it is complete", () => {
680 const html = renderToStaticMarkup(
681 <ChatMarkdown
682 cwd="/tmp/project"
683 text={'Created :codex-file-citation{path="/tmp/project/outputs/report.xlsx"'}
684 isStreaming
685 />,
686 );
687
688 expect(html).toContain(":codex-file-citation");
689 expect(html).not.toContain("chat-markdown-file-link");
690 });
691
692 it("leaves malformed and similarly named file directives literal", () => {
693 for (const text of [
694 ':codex-file-citation{purpose="output"}',
695 ':codex-file-citation-extra{path="/tmp/project/outputs/report.xlsx"}',
696 ]) {
697 const html = renderToStaticMarkup(<ChatMarkdown cwd="/tmp/project" text={text} />);
698
699 expect(html).toContain(text.replaceAll('"', """));
700 expect(html).not.toContain("chat-markdown-file-link");
701 }
702 });
703
704 it("preserves Codex file citation examples inside code", () => {
705 const directive = ':codex-file-citation{path="/tmp/project/outputs/report.xlsx"}';
706 const html = renderToStaticMarkup(
707 <ChatMarkdown
708 cwd="/tmp/project"
709 text={`Example: \`${directive}\`\n\n\`\`\`text\n${directive}\n\`\`\``}
710 />,
711 );
712
713 expect(html.match(/:codex-file-citation/g)).toHaveLength(2);
714 expect(html).not.toContain("chat-markdown-file-link");
715 });
716
717 it("preserves escaped Codex file citations as literal text", () => {
718 const html = renderToStaticMarkup(
719 <ChatMarkdown
720 cwd="/tmp/project"
721 text={'Example: \\:codex-file-citation{path="/tmp/project/outputs/report.xlsx"}'}
722 />,
723 );
724
725 expect(html).toContain(":codex-file-citation");
726 expect(html).not.toContain("chat-markdown-file-link");
727 });
728
729 it("does not create a nested link for citations inside link text", () => {
730 const directive = ':codex-file-citation{path="/tmp/project/outputs/report.xlsx"}';
731 const html = renderToStaticMarkup(
732 <ChatMarkdown cwd="/tmp/project" text={`[See ${directive}](https://example.com)`} />,
733 );
734 const renderedText = html.replace(/<[^>]+>/g, "");
735
736 expect(renderedText).toContain("codex-file-citation");
737 expect(html).not.toContain("chat-markdown-file-link");
738 });
739
740 it("renders file citations created by over-indented list recovery", () => {
741 const html = renderToStaticMarkup(
742 <ChatMarkdown
743 cwd="/tmp/project"
744 text={'- Created :codex-file-citation{path="/tmp/project/outputs/report.xlsx"}'}
745 />,
746 );
747
748 expect(html).not.toContain("<pre>");
749 expect(html).toContain("Created ");
750 expect(html).toContain("chat-markdown-file-link");
751 expect(html).toContain("report.xlsx");
752 });
753
754 it("disambiguates Codex citations with the same basename", () => {
755 const html = renderToStaticMarkup(
756 <ChatMarkdown
757 cwd="/tmp/project"
758 text={
759 'Changed :codex-file-citation{path="/tmp/project/src/index.ts"} and :codex-file-citation{path="/tmp/project/test/index.ts"}.'
760 }
761 />,
762 );
763
764 expect(html).toContain("index.ts · project/src");
765 expect(html).toContain("index.ts · project/test");
766 });
767
768 it("preserves rejected citations created by over-indented list recovery", () => {
769 const malformedHtml = renderToStaticMarkup(
770 <ChatMarkdown
771 cwd="/tmp/project"
772 text={'Leading text before list.\n\n- Bad :codex-file-citation{purpose="output"}'}
773 />,
774 );
775 const nestedLinkHtml = renderToStaticMarkup(
776 <ChatMarkdown
777 cwd="/tmp/project"
778 text={
779 'Leading text before list.\n\n- [Bad :codex-file-citation{path="/tmp/project/report.xlsx"}](https://example.com)'
780 }
781 />,
782 );
783 const nestedLinkText = nestedLinkHtml.replace(/<[^>]+>/g, "");
784
785 expect(malformedHtml).toContain(
786 "<li>Bad :codex-file-citation{purpose="output"}</li>",
787 );
788 expect(nestedLinkText).toContain(
789 "Bad :codex-file-citation{path="/tmp/project/report.xlsx"}",
790 );
791 });
792});
793
794describe("ChatMarkdown Codex follow-up suggestions", () => {
795 it.each([true, false])("renders the label with parseRawHtml=%s", (parseRawHtml) => {
796 const html = renderToStaticMarkup(
797 <ChatMarkdown
798 cwd="/tmp/project"
799 text={
800 'Done.\n\n- :codex-followup[Prepare print version]{prompt="Prepare the document for printing."}'
801 }
802 lineBreaks={!parseRawHtml}
803 parseRawHtml={parseRawHtml}
804 />,
805 );
806
807 expect(html).toContain("Prepare print version");
808 expect(html).not.toContain("codex-followup");
809 expect(html).not.toContain("Prepare the document for printing.");
810 });
811
812 it("keeps the label of a malformed follow-up created by over-indented list recovery", () => {
813 const html = renderToStaticMarkup(
814 <ChatMarkdown
815 cwd="/tmp/project"
816 text="- Next :codex-followup[Prepare print version]"
817 />,
818 );
819
820 expect(html).toContain("<li>Next :codex-followup[Prepare print version]</li>");
821 });
822});
823
824const ARTIFACT_TEMPLATE_DIRECTIVE =
825 '::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"}';
826
827describe("ChatMarkdown artifact-template cards", () => {
828 it.each([true, false])("renders the Codex result card with parseRawHtml=%s", (parseRawHtml) => {
829 const html = renderToStaticMarkup(
830 <ChatMarkdown
831 cwd="/tmp/project"
832 text={ARTIFACT_TEMPLATE_DIRECTIVE}
833 parseRawHtml={parseRawHtml}
834 onUseArtifactTemplate={() => undefined}
835 />,
836 );
837
838 expect(html).not.toContain("::artifact-template");
839 expect(html).toContain("data-chat-markdown-artifact-template");
840 expect(html).toContain('data-artifact-kind="document"');
841 expect(html).toContain('data-markdown-copy="Hello World (Document template)\n\n"');
842 expect(html).toContain('data-skill-name="artifact-template-hello-world"');
843 expect(html).toContain("Hello World");
844 expect(html).toContain("Document template");
845 expect(html).toContain("Use template");
846 expect(html).not.toContain("<p><div");
847 });
848
849 it("renders a passive card outside a composer-backed timeline", () => {
850 const html = renderToStaticMarkup(
851 <ChatMarkdown cwd="/tmp/project" text={ARTIFACT_TEMPLATE_DIRECTIVE} />,
852 );
853
854 expect(html).toContain("data-chat-markdown-artifact-template");
855 expect(html).not.toContain("Use template");
856 });
857
858 it("leaves malformed and unfinished artifact-template directives literal", () => {
859 const malformed =
860 '::artifact-template{skill_name="artifact-template-hello-world" display_name="Hello World" artifact_kind="document"}';
861 const unfinished = ARTIFACT_TEMPLATE_DIRECTIVE.slice(0, -1);
862
863 for (const text of [malformed, unfinished]) {
864 const html = renderToStaticMarkup(<ChatMarkdown cwd="/tmp/project" text={text} />);
865 expect(html).toContain("::artifact-template");
866 expect(html).not.toContain("data-chat-markdown-artifact-template");
867 }
868 });
869
870 it("leaves escaped and similarly named artifact-template directives literal", () => {
871 for (const text of [
872 `\\${ARTIFACT_TEMPLATE_DIRECTIVE}`,
873 ARTIFACT_TEMPLATE_DIRECTIVE.replace("::artifact-template", "::artifact-template-extra"),
874 ]) {
875 const html = renderToStaticMarkup(<ChatMarkdown cwd="/tmp/project" text={text} />);
876
877 expect(html).toContain("::artifact-template");
878 expect(html).not.toContain("data-chat-markdown-artifact-template");
879 }
880 });
881
882 it("preserves artifact-template examples inside code", () => {
883 const html = renderToStaticMarkup(
884 <ChatMarkdown
885 cwd="/tmp/project"
886 text={`\`${ARTIFACT_TEMPLATE_DIRECTIVE}\`\n\n\`\`\`text\n${ARTIFACT_TEMPLATE_DIRECTIVE}\n\`\`\``}
887 />,
888 );
889
890 expect(html.match(/::artifact-template/g)).toHaveLength(2);
891 expect(html).not.toContain("data-chat-markdown-artifact-template");
892 });
893});
894
895describe("ChatMarkdown heading levels", () => {
896 it("exposes headings below the host heading without changing their tags", () => {
897 const html = renderToStaticMarkup(
898 <ChatMarkdown
899 cwd="/tmp/project"
900 text={"# Top\n\n## Section\n\n###### Fine print"}
901 headingLevelOffset={3}
902 />,
903 );
904
905 expect(html).toContain('<h1 id="user-content-top" aria-level="4">Top</h1>');
906 expect(html).toContain('<h2 id="user-content-section" aria-level="5">Section</h2>');
907 expect(html).toContain('<h6 id="user-content-fine-print" aria-level="6">Fine print</h6>');
908 });
909
910 it("leaves heading levels alone when the markdown is not nested", () => {
911 const html = renderToStaticMarkup(<ChatMarkdown cwd="/tmp/project" text="# Top" />);
912
913 expect(html).toContain('<h1 id="user-content-top">Top</h1>');
914 });
915});
916
917describe("shouldUseMarkdownFileBrowserPrimaryAction", () => {
918 it("uses the browser when it is the only available primary action", () => {
919 expect(
920 shouldUseMarkdownFileBrowserPrimaryAction({
921 iconPath: "/tmp/report.html",
922 canOpenInEditor: false,
923 canOpenInBrowser: true,
924 canOpenInPanel: false,
925 }),
926 ).toBe(true);
927 });
928
929 it("preserves the normal editor and panel defaults for HTML files", () => {
930 expect(
931 shouldUseMarkdownFileBrowserPrimaryAction({
932 iconPath: "/tmp/report.html",
933 canOpenInEditor: true,
934 canOpenInBrowser: true,
935 canOpenInPanel: false,
936 }),
937 ).toBe(false);
938 expect(
939 shouldUseMarkdownFileBrowserPrimaryAction({
940 iconPath: "/tmp/report.html",
941 canOpenInEditor: false,
942 canOpenInBrowser: true,
943 canOpenInPanel: true,
944 }),
945 ).toBe(false);
946 });
947
948 it("continues to open PDF files in the browser by default", () => {
949 expect(
950 shouldUseMarkdownFileBrowserPrimaryAction({
951 iconPath: "/tmp/report.pdf",
952 canOpenInEditor: true,
953 canOpenInBrowser: true,
954 canOpenInPanel: true,
955 }),
956 ).toBe(true);
957 });
958});
959
960describe("ChatMarkdown Windows file links", () => {
961 const environmentId = EnvironmentId.make("env-windows");
962
963 it.each([true, false])("preserves drive paths with parseRawHtml=%s", (parseRawHtml) => {
964 const html = renderToStaticMarkup(
965 <ChatMarkdown
966 cwd="C:/Users/shawn/project"
967 environmentId={environmentId}
968 text="[Open](C:/Users/shawn/project/src/main.ts)"
969 lineBreaks={!parseRawHtml}
970 parseRawHtml={parseRawHtml}
971 />,
972 );
973
974 expect(html).toContain('href="C:/Users/shawn/project/src/main.ts"');
975 expect(html).toContain("chat-markdown-file-link");
976 });
977
978 it.each([true, false])("normalizes backslashes with parseRawHtml=%s", (parseRawHtml) => {
979 const html = renderToStaticMarkup(
980 <ChatMarkdown
981 cwd="C:/Users/shawn/project"
982 environmentId={environmentId}
983 text={String.raw`[Open](C:\Users\shawn\project\src\main.ts)`}
984 lineBreaks={!parseRawHtml}
985 parseRawHtml={parseRawHtml}
986 />,
987 );
988
989 expect(html).toContain('href="C:/Users/shawn/project/src/main.ts"');
990 expect(html).toContain("chat-markdown-file-link");
991 });
992
993 it.each([true, false])(
994 "keeps backslashes CommonMark would read as escapes with parseRawHtml=%s",
995 (parseRawHtml) => {
996 const html = renderToStaticMarkup(
997 <ChatMarkdown
998 cwd="C:/Users/shawn/project"
999 environmentId={environmentId}
1000 text={String.raw`[settings](C:\Users\shawn\.claude\settings.json)`}
1001 lineBreaks={!parseRawHtml}
1002 parseRawHtml={parseRawHtml}
1003 />,
1004 );
1005
1006 expect(html).toContain('href="C:/Users/shawn/.claude/settings.json"');
1007 },
1008 );
1009
1010 it.each([true, false])(
1011 "distinguishes same-named backslash paths with parseRawHtml=%s",
1012 (parseRawHtml) => {
1013 const html = renderToStaticMarkup(
1014 <ChatMarkdown
1015 cwd="C:/Users/shawn/project"
1016 environmentId={environmentId}
1017 text={String.raw`[Source](C:\Users\shawn\project\src\index.ts) and [Test](C:\Users\shawn\project\test\index.ts)`}
1018 lineBreaks={!parseRawHtml}
1019 parseRawHtml={parseRawHtml}
1020 />,
1021 );
1022
1023 expect(html).toContain("index.ts · project/src");
1024 expect(html).toContain("index.ts · project/test");
1025 },
1026 );
1027
1028 it.each([true, false])(
1029 "does not disambiguate the same file in links and inline code with parseRawHtml=%s",
1030 (parseRawHtml) => {
1031 const path = String.raw`C:\Users\shawn\project\src\main.ts`;
1032 const html = renderToStaticMarkup(
1033 <ChatMarkdown
1034 cwd="C:/Users/shawn/project"
1035 environmentId={environmentId}
1036 text={`[Source](${path}) and \`${path}\``}
1037 lineBreaks={!parseRawHtml}
1038 parseRawHtml={parseRawHtml}
1039 />,
1040 );
1041
1042 expect(html.match(/chat-markdown-file-link/g)).toHaveLength(2);
1043 expect(html).not.toContain("main.ts ·");
1044 },
1045 );
1046
1047 it.each([true, false])("preserves reference links with parseRawHtml=%s", (parseRawHtml) => {
1048 const html = renderToStaticMarkup(
1049 <ChatMarkdown
1050 cwd="C:/Users/shawn/project"
1051 environmentId={environmentId}
1052 text={"[Open][source]\n\n[source]: C:/Users/shawn/project/src/main.ts"}
1053 lineBreaks={!parseRawHtml}
1054 parseRawHtml={parseRawHtml}
1055 />,
1056 );
1057
1058 expect(html).toContain('href="C:/Users/shawn/project/src/main.ts"');
1059 expect(html).toContain("chat-markdown-file-link");
1060 });
1061
1062 it.each([true, false])("still rejects unsafe schemes with parseRawHtml=%s", (parseRawHtml) => {
1063 const html = renderToStaticMarkup(
1064 <ChatMarkdown
1065 cwd="C:/Users/shawn/project"
1066 environmentId={environmentId}
1067 text="[unsafe](javascript:alert(1)) and [unknown](d:alert(1))"
1068 lineBreaks={!parseRawHtml}
1069 parseRawHtml={parseRawHtml}
1070 />,
1071 );
1072
1073 expect(html).not.toContain("javascript:");
1074 expect(html).not.toContain("d:alert");
1075 expect(html).not.toContain("chat-markdown-file-link");
1076 });
1077});
1078
1079it("opens a disclosure only when find selects a match inside it", async () => {
1080 vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
1081 vi.stubGlobal(
1082 "Highlight",
1083 class extends Set<Range> {
1084 constructor(...ranges: Range[]) {
1085 super(ranges);
1086 }
1087 },
1088 );
1089 const highlights = new Map<string, Set<Range>>();
1090 vi.stubGlobal("CSS", { highlights, escape: (value: string) => value });
1091 const container = document.createElement("div");
1092 document.body.append(container);
1093 const root = createRoot(container);
1094 const openStates = () =>
1095 [...container.querySelectorAll("[data-markdown-details-open]")].map((node) =>
1096 node.getAttribute("data-markdown-details-open"),
1097 );
1098 function Probe({
1099 activeOccurrence,
1100 searching = true,
1101 }: {
1102 activeOccurrence: number;
1103 searching?: boolean;
1104 }) {
1105 useThreadFindHighlights({
1106 container,
1107 query: searching ? "needle" : "",
1108 activeRowId: "row",
1109 activeOccurrence,
1110 onActiveRange: () => {},
1111 });
1112 return (
1113 <div data-timeline-row-id="row">
1114 <div data-thread-find-text>
1115 <MarkdownFindContext value={searching}>
1116 <ChatMarkdown
1117 cwd={undefined}
1118 text={[
1119 "Visible needle.",
1120 "<details><summary>Unrelated</summary><p>nothing here</p></details>",
1121 "<details><summary>Outer</summary><details><summary>Inner</summary><p>needle</p></details></details>",
1122 ].join("\n\n")}
1123 />
1124 </MarkdownFindContext>
1125 </div>
1126 </div>
1127 );
1128 }
1129 const frame = () =>
1130 act(() => new Promise<void>((resolve) => requestAnimationFrame(() => resolve())));
1131 try {
1132 // Closed panels are unmounted until find starts, as in the app.
1133 await act(() => root.render(<Probe activeOccurrence={0} searching={false} />));
1134 expect(container.textContent).not.toContain("nothing here");
1135 await act(() => root.render(<Probe activeOccurrence={0} />));
1136 await frame();
1137 // Selecting the visible match opens nothing; the folded one is counted but not painted.
1138 expect(openStates()).toEqual(["false", "false", "false"]);
1139 expect(container.textContent).toContain("nothing here");
1140 expect(
1141 [...(highlights.get("t3-thread-find-active") ?? [])].map((range) => range.toString()),
1142 ).toEqual(["needle"]);
1143 expect(highlights.get("t3-thread-find")?.size).toBe(0);
1144
1145 await act(() => root.render(<Probe activeOccurrence={1} />));
1146 await frame();
1147 await frame();
1148 // Stepping to the folded match opens its two ancestors, not the unrelated one.
1149 expect(openStates()).toEqual(["false", "true", "true"]);
1150 expect(highlights.get("t3-thread-find-active")?.size).toBe(1);
1151 } finally {
1152 await act(() => root.unmount());
1153 container.remove();
1154 vi.unstubAllGlobals();
1155 }
1156});
1157
1158it("keeps Mermaid diagrams rendered until find selects a match in their source", async () => {
1159 vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
1160 vi.stubGlobal(
1161 "Highlight",
1162 class extends Set<Range> {
1163 constructor(...ranges: Range[]) {
1164 super(ranges);
1165 }
1166 },
1167 );
1168 const highlights = new Map<string, Set<Range>>();
1169 vi.stubGlobal("CSS", { highlights, escape: (value: string) => value });
1170 const container = document.createElement("div");
1171 document.body.append(container);
1172 const root = createRoot(container);
1173 const diagram = "```mermaid\ngraph TD; Alpha-->Beta\n```";
1174 function Probe({ query }: { query: string }) {
1175 useThreadFindHighlights({
1176 container,
1177 query,
1178 activeRowId: "row",
1179 activeOccurrence: 0,
1180 onActiveRange: () => {},
1181 });
1182 return (
1183 <div data-timeline-row-id="row">
1184 <div data-thread-find-text>
1185 <MarkdownFindContext value={true}>
1186 <ChatMarkdown cwd={undefined} text={`Needle first.\n\n${diagram}\n\n${diagram}`} />
1187 </MarkdownFindContext>
1188 </div>
1189 </div>
1190 );
1191 }
1192 const frame = () =>
1193 act(() => new Promise<void>((resolve) => requestAnimationFrame(() => resolve())));
1194 const diagrams = () => container.querySelectorAll('svg[aria-label="Diagram"]').length;
1195 try {
1196 await act(() => root.render(<Probe query="Needle" />));
1197 await frame();
1198 expect(diagrams()).toBe(2);
1199 await act(() => root.render(<Probe query="Alpha" />));
1200 await frame();
1201 await frame();
1202 // Only the diagram holding the selected match switches to source.
1203 expect(diagrams()).toBe(1);
1204 expect(
1205 [...(highlights.get("t3-thread-find-active") ?? [])].map((range) => range.toString()),
1206 ).toEqual(["Alpha"]);
1207 } finally {
1208 await act(() => root.unmount());
1209 container.remove();
1210 vi.unstubAllGlobals();
1211 }
1212});
1213
1214it.each([
1215 {
1216 text: "```mermaid\ngraph TD; SearchSourceAlpha-->B\n```",
1217 query: "SearchSourceAlpha",
1218 count: 1,
1219 },
1220 {
1221 text: "★ Insight ─────\nfirst line\nsecond line",
1222 query: "first line second",
1223 count: 0,
1224 lineBreaks: true,
1225 },
1226 { text: '```ts title="src/needle.ts"\nconst a = 1;\n```', query: "needle", count: 0 },
1227 { text: "```weirdlang\nconst a = 1;\n```", query: "weirdlang", count: 0 },
1228 { text: "Use $test-t3-app now", query: "T3 App Testing", count: 1 },
1229 { text: "`/tmp/file.ts:42`", query: "file.ts · L42", count: 1, user: true, lineBreaks: true },
1230 { text: "> [!NOTE]\n> Searchable alert", query: "Searchable alert", count: 1 },
1231 {
1232 text: "<details><summary>Folded</summary><p>Hidden needle</p></details>",
1233 query: "Hidden needle",
1234 count: 1,
1235 },
1236 { text: ARTIFACT_TEMPLATE_DIRECTIVE, query: "Hello World", count: 1, useTemplate: true },
1237 { text: ARTIFACT_TEMPLATE_DIRECTIVE, query: "Document template", count: 1, useTemplate: true },
1238 { text: ARTIFACT_TEMPLATE_DIRECTIVE, query: "World Document", count: 0, useTemplate: true },
1239 { text: ARTIFACT_TEMPLATE_DIRECTIVE, query: "Use template", count: 0, useTemplate: true },
1240])(
1241 "highlights the indexed occurrences of $query in $text",
1242 async ({ text, query, count, lineBreaks, user, useTemplate }) => {
1243 const skills = [{ name: "test-t3-app", displayName: "T3 App Testing" }];
1244 const highlights = new Map<string, Set<Range>>();
1245 vi.stubGlobal(
1246 "Highlight",
1247 class extends Set<Range> {
1248 constructor(...ranges: Range[]) {
1249 super(ranges);
1250 }
1251 },
1252 );
1253 vi.stubGlobal("CSS", { highlights, escape: (value: string) => value });
1254 vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
1255 const container = document.createElement("div");
1256 document.body.append(container);
1257 const root = createRoot(container);
1258 function Probe() {
1259 useThreadFindHighlights({
1260 container,
1261 query,
1262 activeRowId: "row",
1263 activeOccurrence: 0,
1264 onActiveRange: () => {},
1265 });
1266 return (
1267 <div data-timeline-row-id="row">
1268 <div data-thread-find-text>
1269 <MarkdownFindContext value={true}>
1270 <ChatMarkdown
1271 text={text}
1272 cwd={undefined}
1273 skills={skills}
1274 lineBreaks={lineBreaks ?? false}
1275 parseRawHtml={!user}
1276 onUseArtifactTemplate={useTemplate ? () => undefined : undefined}
1277 />
1278 </MarkdownFindContext>
1279 </div>
1280 </div>
1281 );
1282 }
1283 try {
1284 await act(() => root.render(<Probe />));
1285 await act(() => new Promise<void>((resolve) => requestAnimationFrame(() => resolve())));
1286 const ranges = [...highlights.values()].flatMap((value) => [...value]);
1287 expect(ranges.map((range) => range.toString())).toEqual(
1288 Array.from({ length: count }, () => query),
1289 );
1290 const segments =
1291 searchableMessageSegments(
1292 { role: user ? "user" : "assistant", text, streaming: false },
1293 undefined,
1294 skills,
1295 ) ?? [];
1296 expect(
1297 segments.reduce((sum, segment) => sum + countThreadSearchOccurrences(segment, query), 0),
1298 ).toBe(count);
1299 } finally {
1300 await act(() => root.unmount());
1301 container.remove();
1302 vi.unstubAllGlobals();
1303 }
1304 },
1305);
1306
1307describe("ChatMarkdown heading ids", () => {
1308 it("never gives two headings the same id, even when a suffix matches another heading", () => {
1309 const html = renderToStaticMarkup(
1310 <ChatMarkdown
1311 cwd="/tmp/project"
1312 parseRawHtml
1313 text={
1314 '## Setup\n\n## Setup\n\n## Setup-1\n\n<h2 id="install-1">Pinned</h2>\n\n## Install\n\n## Install'
1315 }
1316 />,
1317 );
1318 const ids = [...html.matchAll(/<h2 id="([^"]+)"/g)].map((match) => match[1]);
1319 expect(ids).toEqual([
1320 "user-content-setup",
1321 "user-content-setup-1",
1322 "user-content-setup-1-1",
1323 "user-content-install-1",
1324 "user-content-install",
1325 "user-content-install-2",
1326 ]);
1327 expect(new Set(ids).size).toBe(ids.length);
1328 });
1329});
1330
1331describe("ChatMarkdown in-page links", () => {
1332 it.each([true, false])(
1333 "scrolls a table-of-contents link to its heading without touching the URL (parseRawHtml=%s)",
1334 async (parseRawHtml) => {
1335 vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
1336 const { createRoot } = await import("react-dom/client");
1337 const container = document.createElement("div");
1338 document.body.append(container);
1339 const root = createRoot(container);
1340 window.history.replaceState(null, "", "/#/env/thread");
1341 const scrollIntoView = vi.fn();
1342 HTMLElement.prototype.scrollIntoView = scrollIntoView;
1343 try {
1344 await act(async () => {
1345 root.render(
1346 <ChatMarkdown
1347 cwd="/tmp/project"
1348 parseRawHtml={parseRawHtml}
1349 text={
1350 "- [Operating model](#1-operating-model)\n- [Missing](#nowhere)\n\n## 1. Operating model\n\n## 1. Operating model"
1351 }
1352 />,
1353 );
1354 });
1355 const headings = [...container.querySelectorAll("h2")];
1356 expect(headings.map((heading) => heading.id)).toEqual([
1357 "user-content-1-operating-model",
1358 "user-content-1-operating-model-1",
1359 ]);
1360
1361 const [tocLink, missingLink] = [...container.querySelectorAll("a")];
1362 const click = () => new MouseEvent("click", { bubbles: true, cancelable: true });
1363 const tocClick = click();
1364 tocLink!.dispatchEvent(tocClick);
1365 expect(tocClick.defaultPrevented).toBe(true);
1366 expect(scrollIntoView.mock.contexts).toEqual([headings[0]]);
1367
1368 const missingClick = click();
1369 missingLink!.dispatchEvent(missingClick);
1370 expect(missingClick.defaultPrevented).toBe(true);
1371 expect(scrollIntoView).toHaveBeenCalledTimes(1);
1372 expect(window.location.hash).toBe("#/env/thread");
1373 } finally {
1374 await act(async () => root.unmount());
1375 container.remove();
1376 }
1377 },
1378 );
1379});