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