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

ChatMarkdown.test.tsx

1,349 lines48.1 KB

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>;
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 ![Error image](t3-context://v1/image/img-1).";
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('"', "&quot;"));
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=&quot;output&quot;}</li>",
787 );
788 expect(nestedLinkText).toContain(
789 "Bad :codex-file-citation{path=&quot;/tmp/project/report.xlsx&quot;}",
790 );
791 });
792});
793​
794const ARTIFACT_TEMPLATE_DIRECTIVE =
795 '::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"}';
796​
797describe("ChatMarkdown artifact-template cards", () => {
798 it.each([true, false])("renders the Codex result card with parseRawHtml=%s", (parseRawHtml) => {
799 const html = renderToStaticMarkup(
800 <ChatMarkdown
801 cwd="/tmp/project"
802 text={ARTIFACT_TEMPLATE_DIRECTIVE}
803 parseRawHtml={parseRawHtml}
804 onUseArtifactTemplate={() => undefined}
805 />,
806 );
807​
808 expect(html).not.toContain("::artifact-template");
809 expect(html).toContain("data-chat-markdown-artifact-template");
810 expect(html).toContain('data-artifact-kind="document"');
811 expect(html).toContain('data-markdown-copy="Hello World (Document template)\n\n"');
812 expect(html).toContain('data-skill-name="artifact-template-hello-world"');
813 expect(html).toContain("Hello World");
814 expect(html).toContain("Document template");
815 expect(html).toContain("Use template");
816 expect(html).not.toContain("<p><div");
817 });
818​
819 it("renders a passive card outside a composer-backed timeline", () => {
820 const html = renderToStaticMarkup(
821 <ChatMarkdown cwd="/tmp/project" text={ARTIFACT_TEMPLATE_DIRECTIVE} />,
822 );
823​
824 expect(html).toContain("data-chat-markdown-artifact-template");
825 expect(html).not.toContain("Use template");
826 });
827​
828 it("leaves malformed and unfinished artifact-template directives literal", () => {
829 const malformed =
830 '::artifact-template{skill_name="artifact-template-hello-world" display_name="Hello World" artifact_kind="document"}';
831 const unfinished = ARTIFACT_TEMPLATE_DIRECTIVE.slice(0, -1);
832​
833 for (const text of [malformed, unfinished]) {
834 const html = renderToStaticMarkup(<ChatMarkdown cwd="/tmp/project" text={text} />);
835 expect(html).toContain("::artifact-template");
836 expect(html).not.toContain("data-chat-markdown-artifact-template");
837 }
838 });
839​
840 it("leaves escaped and similarly named artifact-template directives literal", () => {
841 for (const text of [
842 `\\${ARTIFACT_TEMPLATE_DIRECTIVE}`,
843 ARTIFACT_TEMPLATE_DIRECTIVE.replace("::artifact-template", "::artifact-template-extra"),
844 ]) {
845 const html = renderToStaticMarkup(<ChatMarkdown cwd="/tmp/project" text={text} />);
846​
847 expect(html).toContain("::artifact-template");
848 expect(html).not.toContain("data-chat-markdown-artifact-template");
849 }
850 });
851​
852 it("preserves artifact-template examples inside code", () => {
853 const html = renderToStaticMarkup(
854 <ChatMarkdown
855 cwd="/tmp/project"
856 text={`\`${ARTIFACT_TEMPLATE_DIRECTIVE}\`\n\n\`\`\`text\n${ARTIFACT_TEMPLATE_DIRECTIVE}\n\`\`\``}
857 />,
858 );
859​
860 expect(html.match(/::artifact-template/g)).toHaveLength(2);
861 expect(html).not.toContain("data-chat-markdown-artifact-template");
862 });
863});
864​
865describe("ChatMarkdown heading levels", () => {
866 it("exposes headings below the host heading without changing their tags", () => {
867 const html = renderToStaticMarkup(
868 <ChatMarkdown
869 cwd="/tmp/project"
870 text={"# Top\n\n## Section\n\n###### Fine print"}
871 headingLevelOffset={3}
872 />,
873 );
874​
875 expect(html).toContain('<h1 id="user-content-top" aria-level="4">Top</h1>');
876 expect(html).toContain('<h2 id="user-content-section" aria-level="5">Section</h2>');
877 expect(html).toContain('<h6 id="user-content-fine-print" aria-level="6">Fine print</h6>');
878 });
879​
880 it("leaves heading levels alone when the markdown is not nested", () => {
881 const html = renderToStaticMarkup(<ChatMarkdown cwd="/tmp/project" text="# Top" />);
882​
883 expect(html).toContain('<h1 id="user-content-top">Top</h1>');
884 });
885});
886​
887describe("shouldUseMarkdownFileBrowserPrimaryAction", () => {
888 it("uses the browser when it is the only available primary action", () => {
889 expect(
890 shouldUseMarkdownFileBrowserPrimaryAction({
891 iconPath: "/tmp/report.html",
892 canOpenInEditor: false,
893 canOpenInBrowser: true,
894 canOpenInPanel: false,
895 }),
896 ).toBe(true);
897 });
898​
899 it("preserves the normal editor and panel defaults for HTML files", () => {
900 expect(
901 shouldUseMarkdownFileBrowserPrimaryAction({
902 iconPath: "/tmp/report.html",
903 canOpenInEditor: true,
904 canOpenInBrowser: true,
905 canOpenInPanel: false,
906 }),
907 ).toBe(false);
908 expect(
909 shouldUseMarkdownFileBrowserPrimaryAction({
910 iconPath: "/tmp/report.html",
911 canOpenInEditor: false,
912 canOpenInBrowser: true,
913 canOpenInPanel: true,
914 }),
915 ).toBe(false);
916 });
917​
918 it("continues to open PDF files in the browser by default", () => {
919 expect(
920 shouldUseMarkdownFileBrowserPrimaryAction({
921 iconPath: "/tmp/report.pdf",
922 canOpenInEditor: true,
923 canOpenInBrowser: true,
924 canOpenInPanel: true,
925 }),
926 ).toBe(true);
927 });
928});
929​
930describe("ChatMarkdown Windows file links", () => {
931 const environmentId = EnvironmentId.make("env-windows");
932​
933 it.each([true, false])("preserves drive paths with parseRawHtml=%s", (parseRawHtml) => {
934 const html = renderToStaticMarkup(
935 <ChatMarkdown
936 cwd="C:/Users/shawn/project"
937 environmentId={environmentId}
938 text="[Open](C:/Users/shawn/project/src/main.ts)"
939 lineBreaks={!parseRawHtml}
940 parseRawHtml={parseRawHtml}
941 />,
942 );
943​
944 expect(html).toContain('href="C:/Users/shawn/project/src/main.ts"');
945 expect(html).toContain("chat-markdown-file-link");
946 });
947​
948 it.each([true, false])("normalizes backslashes with parseRawHtml=%s", (parseRawHtml) => {
949 const html = renderToStaticMarkup(
950 <ChatMarkdown
951 cwd="C:/Users/shawn/project"
952 environmentId={environmentId}
953 text={String.raw`[Open](C:\Users\shawn\project\src\main.ts)`}
954 lineBreaks={!parseRawHtml}
955 parseRawHtml={parseRawHtml}
956 />,
957 );
958​
959 expect(html).toContain('href="C:/Users/shawn/project/src/main.ts"');
960 expect(html).toContain("chat-markdown-file-link");
961 });
962​
963 it.each([true, false])(
964 "keeps backslashes CommonMark would read as escapes with parseRawHtml=%s",
965 (parseRawHtml) => {
966 const html = renderToStaticMarkup(
967 <ChatMarkdown
968 cwd="C:/Users/shawn/project"
969 environmentId={environmentId}
970 text={String.raw`[settings](C:\Users\shawn\.claude\settings.json)`}
971 lineBreaks={!parseRawHtml}
972 parseRawHtml={parseRawHtml}
973 />,
974 );
975​
976 expect(html).toContain('href="C:/Users/shawn/.claude/settings.json"');
977 },
978 );
979​
980 it.each([true, false])(
981 "distinguishes same-named backslash paths with parseRawHtml=%s",
982 (parseRawHtml) => {
983 const html = renderToStaticMarkup(
984 <ChatMarkdown
985 cwd="C:/Users/shawn/project"
986 environmentId={environmentId}
987 text={String.raw`[Source](C:\Users\shawn\project\src\index.ts) and [Test](C:\Users\shawn\project\test\index.ts)`}
988 lineBreaks={!parseRawHtml}
989 parseRawHtml={parseRawHtml}
990 />,
991 );
992​
993 expect(html).toContain("index.ts · project/src");
994 expect(html).toContain("index.ts · project/test");
995 },
996 );
997​
998 it.each([true, false])(
999 "does not disambiguate the same file in links and inline code with parseRawHtml=%s",
1000 (parseRawHtml) => {
1001 const path = String.raw`C:\Users\shawn\project\src\main.ts`;
1002 const html = renderToStaticMarkup(
1003 <ChatMarkdown
1004 cwd="C:/Users/shawn/project"
1005 environmentId={environmentId}
1006 text={`[Source](${path}) and \`${path}\``}
1007 lineBreaks={!parseRawHtml}
1008 parseRawHtml={parseRawHtml}
1009 />,
1010 );
1011​
1012 expect(html.match(/chat-markdown-file-link/g)).toHaveLength(2);
1013 expect(html).not.toContain("main.ts ·");
1014 },
1015 );
1016​
1017 it.each([true, false])("preserves reference links with parseRawHtml=%s", (parseRawHtml) => {
1018 const html = renderToStaticMarkup(
1019 <ChatMarkdown
1020 cwd="C:/Users/shawn/project"
1021 environmentId={environmentId}
1022 text={"[Open][source]\n\n[source]: C:/Users/shawn/project/src/main.ts"}
1023 lineBreaks={!parseRawHtml}
1024 parseRawHtml={parseRawHtml}
1025 />,
1026 );
1027​
1028 expect(html).toContain('href="C:/Users/shawn/project/src/main.ts"');
1029 expect(html).toContain("chat-markdown-file-link");
1030 });
1031​
1032 it.each([true, false])("still rejects unsafe schemes with parseRawHtml=%s", (parseRawHtml) => {
1033 const html = renderToStaticMarkup(
1034 <ChatMarkdown
1035 cwd="C:/Users/shawn/project"
1036 environmentId={environmentId}
1037 text="[unsafe](javascript:alert(1)) and [unknown](d:alert(1))"
1038 lineBreaks={!parseRawHtml}
1039 parseRawHtml={parseRawHtml}
1040 />,
1041 );
1042​
1043 expect(html).not.toContain("javascript:");
1044 expect(html).not.toContain("d:alert");
1045 expect(html).not.toContain("chat-markdown-file-link");
1046 });
1047});
1048​
1049it("opens a disclosure only when find selects a match inside it", async () => {
1050 vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
1051 vi.stubGlobal(
1052 "Highlight",
1053 class extends Set<Range> {
1054 constructor(...ranges: Range[]) {
1055 super(ranges);
1057 },
1058 );
1059 const highlights = new Map<string, Set<Range>>();
1060 vi.stubGlobal("CSS", { highlights, escape: (value: string) => value });
1061 const container = document.createElement("div");
1062 document.body.append(container);
1063 const root = createRoot(container);
1064 const openStates = () =>
1065 [...container.querySelectorAll("[data-markdown-details-open]")].map((node) =>
1066 node.getAttribute("data-markdown-details-open"),
1067 );
1068 function Probe({
1069 activeOccurrence,
1070 searching = true,
1071 }: {
1072 activeOccurrence: number;
1073 searching?: boolean;
1074 }) {
1075 useThreadFindHighlights({
1076 container,
1077 query: searching ? "needle" : "",
1078 activeRowId: "row",
1079 activeOccurrence,
1080 onActiveRange: () => {},
1081 });
1082 return (
1083 <div data-timeline-row-id="row">
1084 <div data-thread-find-text>
1085 <MarkdownFindContext value={searching}>
1086 <ChatMarkdown
1087 cwd={undefined}
1088 text={[
1089 "Visible needle.",
1090 "<details><summary>Unrelated</summary><p>nothing here</p></details>",
1091 "<details><summary>Outer</summary><details><summary>Inner</summary><p>needle</p></details></details>",
1092 ].join("\n\n")}
1093 />
1094 </MarkdownFindContext>
1095 </div>
1096 </div>
1097 );
1099 const frame = () =>
1100 act(() => new Promise<void>((resolve) => requestAnimationFrame(() => resolve())));
1101 try {
1102 // Closed panels are unmounted until find starts, as in the app.
1103 await act(() => root.render(<Probe activeOccurrence={0} searching={false} />));
1104 expect(container.textContent).not.toContain("nothing here");
1105 await act(() => root.render(<Probe activeOccurrence={0} />));
1106 await frame();
1107 // Selecting the visible match opens nothing; the folded one is counted but not painted.
1108 expect(openStates()).toEqual(["false", "false", "false"]);
1109 expect(container.textContent).toContain("nothing here");
1110 expect(
1111 [...(highlights.get("t3-thread-find-active") ?? [])].map((range) => range.toString()),
1112 ).toEqual(["needle"]);
1113 expect(highlights.get("t3-thread-find")?.size).toBe(0);
1114​
1115 await act(() => root.render(<Probe activeOccurrence={1} />));
1116 await frame();
1117 await frame();
1118 // Stepping to the folded match opens its two ancestors, not the unrelated one.
1119 expect(openStates()).toEqual(["false", "true", "true"]);
1120 expect(highlights.get("t3-thread-find-active")?.size).toBe(1);
1121 } finally {
1122 await act(() => root.unmount());
1123 container.remove();
1124 vi.unstubAllGlobals();
1126});
1127​
1128it("keeps Mermaid diagrams rendered until find selects a match in their source", async () => {
1129 vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
1130 vi.stubGlobal(
1131 "Highlight",
1132 class extends Set<Range> {
1133 constructor(...ranges: Range[]) {
1134 super(ranges);
1136 },
1137 );
1138 const highlights = new Map<string, Set<Range>>();
1139 vi.stubGlobal("CSS", { highlights, escape: (value: string) => value });
1140 const container = document.createElement("div");
1141 document.body.append(container);
1142 const root = createRoot(container);
1143 const diagram = "```mermaid\ngraph TD; Alpha-->Beta\n```";
1144 function Probe({ query }: { query: string }) {
1145 useThreadFindHighlights({
1146 container,
1147 query,
1148 activeRowId: "row",
1149 activeOccurrence: 0,
1150 onActiveRange: () => {},
1151 });
1152 return (
1153 <div data-timeline-row-id="row">
1154 <div data-thread-find-text>
1155 <MarkdownFindContext value={true}>
1156 <ChatMarkdown cwd={undefined} text={`Needle first.\n\n${diagram}\n\n${diagram}`} />
1157 </MarkdownFindContext>
1158 </div>
1159 </div>
1160 );
1162 const frame = () =>
1163 act(() => new Promise<void>((resolve) => requestAnimationFrame(() => resolve())));
1164 const diagrams = () => container.querySelectorAll('svg[aria-label="Diagram"]').length;
1165 try {
1166 await act(() => root.render(<Probe query="Needle" />));
1167 await frame();
1168 expect(diagrams()).toBe(2);
1169 await act(() => root.render(<Probe query="Alpha" />));
1170 await frame();
1171 await frame();
1172 // Only the diagram holding the selected match switches to source.
1173 expect(diagrams()).toBe(1);
1174 expect(
1175 [...(highlights.get("t3-thread-find-active") ?? [])].map((range) => range.toString()),
1176 ).toEqual(["Alpha"]);
1177 } finally {
1178 await act(() => root.unmount());
1179 container.remove();
1180 vi.unstubAllGlobals();
1182});
1183​
1184it.each([
1186 text: "```mermaid\ngraph TD; SearchSourceAlpha-->B\n```",
1187 query: "SearchSourceAlpha",
1188 count: 1,
1189 },
1191 text: "★ Insight ─────\nfirst line\nsecond line",
1192 query: "first line second",
1193 count: 0,
1194 lineBreaks: true,
1195 },
1196 { text: '```ts title="src/needle.ts"\nconst a = 1;\n```', query: "needle", count: 0 },
1197 { text: "```weirdlang\nconst a = 1;\n```", query: "weirdlang", count: 0 },
1198 { text: "Use $test-t3-app now", query: "T3 App Testing", count: 1 },
1199 { text: "`/tmp/file.ts:42`", query: "file.ts · L42", count: 1, user: true, lineBreaks: true },
1200 { text: "> [!NOTE]\n> Searchable alert", query: "Searchable alert", count: 1 },
1202 text: "<details><summary>Folded</summary><p>Hidden needle</p></details>",
1203 query: "Hidden needle",
1204 count: 1,
1205 },
1206 { text: ARTIFACT_TEMPLATE_DIRECTIVE, query: "Hello World", count: 1, useTemplate: true },
1207 { text: ARTIFACT_TEMPLATE_DIRECTIVE, query: "Document template", count: 1, useTemplate: true },
1208 { text: ARTIFACT_TEMPLATE_DIRECTIVE, query: "World Document", count: 0, useTemplate: true },
1209 { text: ARTIFACT_TEMPLATE_DIRECTIVE, query: "Use template", count: 0, useTemplate: true },
1210])(
1211 "highlights the indexed occurrences of $query in $text",
1212 async ({ text, query, count, lineBreaks, user, useTemplate }) => {
1213 const skills = [{ name: "test-t3-app", displayName: "T3 App Testing" }];
1214 const highlights = new Map<string, Set<Range>>();
1215 vi.stubGlobal(
1216 "Highlight",
1217 class extends Set<Range> {
1218 constructor(...ranges: Range[]) {
1219 super(ranges);
1221 },
1222 );
1223 vi.stubGlobal("CSS", { highlights, escape: (value: string) => value });
1224 vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
1225 const container = document.createElement("div");
1226 document.body.append(container);
1227 const root = createRoot(container);
1228 function Probe() {
1229 useThreadFindHighlights({
1230 container,
1231 query,
1232 activeRowId: "row",
1233 activeOccurrence: 0,
1234 onActiveRange: () => {},
1235 });
1236 return (
1237 <div data-timeline-row-id="row">
1238 <div data-thread-find-text>
1239 <MarkdownFindContext value={true}>
1240 <ChatMarkdown
1241 text={text}
1242 cwd={undefined}
1243 skills={skills}
1244 lineBreaks={lineBreaks ?? false}
1245 parseRawHtml={!user}
1246 onUseArtifactTemplate={useTemplate ? () => undefined : undefined}
1247 />
1248 </MarkdownFindContext>
1249 </div>
1250 </div>
1251 );
1253 try {
1254 await act(() => root.render(<Probe />));
1255 await act(() => new Promise<void>((resolve) => requestAnimationFrame(() => resolve())));
1256 const ranges = [...highlights.values()].flatMap((value) => [...value]);
1257 expect(ranges.map((range) => range.toString())).toEqual(
1258 Array.from({ length: count }, () => query),
1259 );
1260 const segments =
1261 searchableMessageSegments(
1262 { role: user ? "user" : "assistant", text, streaming: false },
1263 undefined,
1264 skills,
1265 ) ?? [];
1266 expect(
1267 segments.reduce((sum, segment) => sum + countThreadSearchOccurrences(segment, query), 0),
1268 ).toBe(count);
1269 } finally {
1270 await act(() => root.unmount());
1271 container.remove();
1272 vi.unstubAllGlobals();
1274 },
1276​
1277describe("ChatMarkdown heading ids", () => {
1278 it("never gives two headings the same id, even when a suffix matches another heading", () => {
1279 const html = renderToStaticMarkup(
1280 <ChatMarkdown
1281 cwd="/tmp/project"
1282 parseRawHtml
1283 text={
1284 '## Setup\n\n## Setup\n\n## Setup-1\n\n<h2 id="install-1">Pinned</h2>\n\n## Install\n\n## Install'
1286 />,
1287 );
1288 const ids = [...html.matchAll(/<h2 id="([^"]+)"/g)].map((match) => match[1]);
1289 expect(ids).toEqual([
1290 "user-content-setup",
1291 "user-content-setup-1",
1292 "user-content-setup-1-1",
1293 "user-content-install-1",
1294 "user-content-install",
1295 "user-content-install-2",
1296 ]);
1297 expect(new Set(ids).size).toBe(ids.length);
1298 });
1299});
1300​
1301describe("ChatMarkdown in-page links", () => {
1302 it.each([true, false])(
1303 "scrolls a table-of-contents link to its heading without touching the URL (parseRawHtml=%s)",
1304 async (parseRawHtml) => {
1305 vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
1306 const { createRoot } = await import("react-dom/client");
1307 const container = document.createElement("div");
1308 document.body.append(container);
1309 const root = createRoot(container);
1310 window.history.replaceState(null, "", "/#/env/thread");
1311 const scrollIntoView = vi.fn();
1312 HTMLElement.prototype.scrollIntoView = scrollIntoView;
1313 try {
1314 await act(async () => {
1315 root.render(
1316 <ChatMarkdown
1317 cwd="/tmp/project"
1318 parseRawHtml={parseRawHtml}
1319 text={
1320 "- [Operating model](#1-operating-model)\n- [Missing](#nowhere)\n\n## 1. Operating model\n\n## 1. Operating model"
1322 />,
1323 );
1324 });
1325 const headings = [...container.querySelectorAll("h2")];
1326 expect(headings.map((heading) => heading.id)).toEqual([
1327 "user-content-1-operating-model",
1328 "user-content-1-operating-model-1",
1329 ]);
1330​
1331 const [tocLink, missingLink] = [...container.querySelectorAll("a")];
1332 const click = () => new MouseEvent("click", { bubbles: true, cancelable: true });
1333 const tocClick = click();
1334 tocLink!.dispatchEvent(tocClick);
1335 expect(tocClick.defaultPrevented).toBe(true);
1336 expect(scrollIntoView.mock.contexts).toEqual([headings[0]]);
1337​
1338 const missingClick = click();
1339 missingLink!.dispatchEvent(missingClick);
1340 expect(missingClick.defaultPrevented).toBe(true);
1341 expect(scrollIntoView).toHaveBeenCalledTimes(1);
1342 expect(window.location.hash).toBe("#/env/thread");
1343 } finally {
1344 await act(async () => root.unmount());
1345 container.remove();
1347 },
1348 );
1349});