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

ChatMarkdown.test.tsx

1,274 lines45.2 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("@effect/atom-react", () => ({ useAtomValue: () => null }));
21vi.mock("./chat/MermaidDiagram", () => ({
22 // Real Mermaid needs layout APIs jsdom lacks; a rendered diagram is an SVG.
23 MermaidDiagram: () => <svg aria-label="Diagram" />,
24}));
25vi.mock("../hooks/useTheme", () => ({ useTheme: () => ({ resolvedTheme: "dark" }) }));
26vi.mock("../hooks/useSettings", async (importOriginal) => {
27 const actual = await importOriginal<typeof import("../hooks/useSettings")>();
28 const settings = actual.getClientSettings();
29 return {
30 ...actual,
31 useClientSettings: (select?: (value: typeof settings) => unknown) =>
32 select ? select(settings) : settings,
33 };
34});
35vi.mock("./ui/tooltip", async () => {
36 const { cloneElement, isValidElement } = await import("react");
37 return {
38 Tooltip: ({ children }: { children: ReactNode }) => <>{children}</>,
39 TooltipTrigger({
40 render,
41 children,
42 }: ComponentProps<typeof import("./ui/tooltip").TooltipTrigger>) {
43 if (!isValidElement(render)) return <>{children}</>;
44 return children === undefined ? render : cloneElement(render, undefined, children);
45 },
46 TooltipPopup: () => null,
47 };
48});
49vi.mock("../state/use-atom-query-runner", () => ({ useAtomQueryRunner: () => vi.fn() }));
50vi.mock("../state/use-atom-command", () => ({ useAtomCommand: () => vi.fn() }));
51vi.mock("../state/session", async (importOriginal) => {
52 const actual = await importOriginal<typeof import("../state/session")>();
53 const { AuthStandardClientScopes } = await import("@t3tools/contracts");
54 const grantedScopes = new Set<AuthEnvironmentScope>(AuthStandardClientScopes);
55 const hasScope = (environmentId: EnvironmentId | null, scope: AuthEnvironmentScope) =>
56 environmentId !== null && grantedScopes.has(scope);
57 return {
58 ...actual,
59 useEnvironmentScope: hasScope,
60 readEnvironmentScope: hasScope,
61 usePreparedConnection: () => ({ _tag: "Loading" }),
62 };
63});
64vi.mock("../state/entities", () => ({
65 readThreadShell: () => null,
66 useProjects: () => [],
67 useServerConfigs: () => new Map(),
68}));
69vi.mock("../remoteOpen", () => ({
70 useRemoteOpenResolution: () => ({ state: { mode: "local-exec" }, isResolved: true }),
71}));
72vi.mock("../editorPreferences", () => ({
73 useOpenInPreferredEditor: () => vi.fn(),
74 usePreferredEditor: () => [null, vi.fn()],
75}));
76vi.mock("~/lib/openPullRequestLink", () => ({
77 findProjectOnChangeRequestHost: () => undefined,
78 parseChangeRequestUrl: () => null,
79 resolvePullRequestPreviewTarget: () => null,
80 useOpenChangeRequestLink: () => vi.fn(),
81}));
82​
83import ChatMarkdown, {
84 canUseMarkdownFileShellActions,
85 hasMarkdownFilePrimaryAction,
86 shouldUseMarkdownFileBrowserPrimaryAction,
87} from "./ChatMarkdown";
88​
89function codeButton(renderer: ReactTestRenderer, label: string) {
90 const button = renderer.root
91 .findAllByType(Button)
92 .find((instance) => instance.props["aria-label"] === label);
93 if (!button) throw new Error(`Missing code button: ${label}`);
94 return button.props as ComponentProps<typeof Button>;
96​
97describe("ChatMarkdown bare anchor placeholders", () => {
98 it.each(["<A>", "<a>", "<a >", "<a/>", "<A/>", "<a />"])(
99 "preserves unmatched %s without linking later blocks",
100 (token) => {
101 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>.`;
102 const document = new DOMParser().parseFromString(
103 renderToStaticMarkup(<ChatMarkdown cwd="/tmp/project" text={text} />),
104 "text/html",
105 );
106​
107 expect(document.querySelector("strong")?.textContent).toBe(`"From ${token}"`);
108 expect([...document.querySelectorAll("a")].map((link) => link.textContent)).toEqual([
109 "the link",
110 ]);
111 expect(document.querySelectorAll("li")).toHaveLength(2);
112 expect(
113 [...document.querySelectorAll("p")].map((paragraph) => paragraph.textContent),
114 ).toContain("The deferred move continues on B.");
115 },
116 );
117​
118 it.each(["</a> ", "<div>more</div>\n</a>"])(
119 "preserves a paired anchor closing in the raw block %s",
120 (closing) => {
121 const document = new DOMParser().parseFromString(
122 renderToStaticMarkup(
123 <ChatMarkdown cwd="/tmp/project" text={`See <a>label\n\n${closing}\n\nfinish`} />,
124 ),
125 "text/html",
126 );
127 expect(document.querySelector("p")?.textContent).toBe("See label");
128 },
129 );
130​
131 it("preserves a paired anchor after comment-looking raw text", () => {
132 const document = new DOMParser().parseFromString(
133 renderToStaticMarkup(
134 <ChatMarkdown cwd="/tmp/project" text="See <a>label<script><!-- </script> --></a>" />,
135 ),
136 "text/html",
137 );
138 expect(document.querySelector("p")?.textContent).toBe("See label -->");
139 });
140​
141 it.each(["<!-- </a> -->", '<div title="</a>">more</div>', '<script>"</a>"</script>'])(
142 "ignores apparent closing anchors inside %s",
143 (html) => {
144 const document = new DOMParser().parseFromString(
145 renderToStaticMarkup(
146 <ChatMarkdown cwd="/tmp/project" text={`Before <A>.\n\n${html}\n\nAfter.`} />,
147 ),
148 "text/html",
149 );
150 expect(document.querySelector("p")?.textContent).toBe("Before <A>.");
151 expect(document.querySelectorAll("a")).toHaveLength(0);
152 },
153 );
154​
155 it("preserves paired HTML anchors, details, markdown links, and inline code", () => {
156 const text =
157 'Bare <a>label</a>, <a id="section"></a>, `<A>`, and [docs](https://example.com).\n\n<details><summary>More</summary>Details</details>';
158 const document = new DOMParser().parseFromString(
159 renderToStaticMarkup(<ChatMarkdown cwd="/tmp/project" text={text} />),
160 "text/html",
161 );
162​
163 expect([...document.querySelectorAll("a")].map((link) => link.textContent)).toEqual([
164 "label",
165 "",
166 "docs",
167 ]);
168 expect(document.querySelector("code")?.textContent).toBe("<A>");
169 expect(document.querySelector("[data-markdown-details]")?.textContent).toContain("More");
170 });
171});
172​
173describe("ChatMarkdown context references", () => {
174 it("renders text and image references through the chip renderer, with readable fallback", async () => {
175 vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
176 let renderer: ReactTestRenderer | undefined;
177 const text =
178 "See [Terminal output](t3-context://v1/terminal/term-1) and ![Error image](t3-context://v1/image/img-1).";
179 try {
180 await act(async () => {
181 renderer = create(
182 <ChatMarkdown
183 cwd={undefined}
184 text={text}
185 renderContextReference={({ kind, label }) => (
186 <button>
187 {kind}: {label}
188 </button>
189 )}
190 />,
191 );
192 });
193 expect(
194 renderer!.root.findAllByType("button").map((button) => button.children.join("")),
195 ).toEqual(["terminal: Terminal output", "image: Error image"]);
196 expect(renderer!.root.findAllByType("img")).toHaveLength(0);
197 expect(renderer!.root.findAllByType("a")).toHaveLength(0);
198 await act(async () => {
199 renderer!.update(<ChatMarkdown cwd={undefined} text={text} />);
200 });
201 expect(renderer!.root.findAllByType("span").map((span) => span.children.join(""))).toEqual([
202 "Terminal output",
203 "Error image",
204 ]);
205 expect(renderer!.root.findAllByType("img")).toHaveLength(0);
206 } finally {
207 await act(async () => {
208 renderer?.unmount();
209 });
210 vi.unstubAllGlobals();
211 }
212 });
213​
214 it("reads formatted context labels through nested markup instead of the context id", async () => {
215 vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
216 let renderer: ReactTestRenderer | undefined;
217 const seen: Array<string> = [];
218 try {
219 await act(async () => {
220 renderer = create(
221 <ChatMarkdown
222 cwd={undefined}
223 text="See [**Bold** `code`](t3-context://v1/terminal/term-1)."
224 renderContextReference={({ kind, label }) => {
225 seen.push(`${kind}: ${label}`);
226 return <button>{label}</button>;
227 }}
228 />,
229 );
230 });
231 expect(seen).toEqual(["terminal: Bold code"]);
232 } finally {
233 await act(async () => {
234 renderer?.unmount();
235 });
236 vi.unstubAllGlobals();
237 }
238 });
239});
240​
241describe("ChatMarkdown favicon privacy", () => {
242 it("suppresses private link images while preserving public links across updates", async () => {
243 vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
244 let renderer: ReactTestRenderer | undefined;
245 const markdown = (url: string) => <ChatMarkdown cwd="/tmp/project" text={`[Link](${url})`} />;
246 try {
247 await act(async () => {
248 renderer = create(markdown("https://example.com"));
249 });
250 expect(renderer!.root.findAllByType("img").map((image) => image.props.src)).toEqual([
251 "https://www.google.com/s2/favicons?domain=example.com&sz=32",
252 ]);
253 for (const url of ["http://192.168.1.10:8080", "http://localhost:3000", "http://home.arpa"]) {
254 await act(async () => {
255 renderer!.update(markdown(url));
256 });
257 expect(renderer!.root.findAllByType("img")).toHaveLength(0);
258 }
259 await act(async () => {
260 renderer!.update(markdown("https://example.com"));
261 });
262 expect(renderer!.root.findAllByType("img")).toHaveLength(1);
263 // GitHub links draw the brand mark in currentColor instead of fetching a favicon.
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: { taskMarkerOffset: String(listItem.props["data-task-marker-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('"', "&quot;"));
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=&quot;output&quot;}</li>",
786 );
787 expect(nestedLinkText).toContain(
788 "Bad :codex-file-citation{path=&quot;/tmp/project/report.xlsx&quot;}",
789 );
790 });
791});
792​
793const ARTIFACT_TEMPLATE_DIRECTIVE =
794 '::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"}';
795​
796describe("ChatMarkdown artifact-template cards", () => {
797 it.each([true, false])("renders the Codex result card with parseRawHtml=%s", (parseRawHtml) => {
798 const html = renderToStaticMarkup(
799 <ChatMarkdown
800 cwd="/tmp/project"
801 text={ARTIFACT_TEMPLATE_DIRECTIVE}
802 parseRawHtml={parseRawHtml}
803 onUseArtifactTemplate={() => undefined}
804 />,
805 );
806​
807 expect(html).not.toContain("::artifact-template");
808 expect(html).toContain("data-chat-markdown-artifact-template");
809 expect(html).toContain('data-artifact-kind="document"');
810 expect(html).toContain('data-markdown-copy="Hello World (Document template)\n\n"');
811 expect(html).toContain('data-skill-name="artifact-template-hello-world"');
812 expect(html).toContain("Hello World");
813 expect(html).toContain("Document template");
814 expect(html).toContain("Use template");
815 expect(html).not.toContain("<p><div");
816 });
817​
818 it("renders a passive card outside a composer-backed timeline", () => {
819 const html = renderToStaticMarkup(
820 <ChatMarkdown cwd="/tmp/project" text={ARTIFACT_TEMPLATE_DIRECTIVE} />,
821 );
822​
823 expect(html).toContain("data-chat-markdown-artifact-template");
824 expect(html).not.toContain("Use template");
825 });
826​
827 it("leaves malformed and unfinished artifact-template directives literal", () => {
828 const malformed =
829 '::artifact-template{skill_name="artifact-template-hello-world" display_name="Hello World" artifact_kind="document"}';
830 const unfinished = ARTIFACT_TEMPLATE_DIRECTIVE.slice(0, -1);
831​
832 for (const text of [malformed, unfinished]) {
833 const html = renderToStaticMarkup(<ChatMarkdown cwd="/tmp/project" text={text} />);
834 expect(html).toContain("::artifact-template");
835 expect(html).not.toContain("data-chat-markdown-artifact-template");
836 }
837 });
838​
839 it("leaves escaped and similarly named artifact-template directives literal", () => {
840 for (const text of [
841 `\\${ARTIFACT_TEMPLATE_DIRECTIVE}`,
842 ARTIFACT_TEMPLATE_DIRECTIVE.replace("::artifact-template", "::artifact-template-extra"),
843 ]) {
844 const html = renderToStaticMarkup(<ChatMarkdown cwd="/tmp/project" text={text} />);
845​
846 expect(html).toContain("::artifact-template");
847 expect(html).not.toContain("data-chat-markdown-artifact-template");
848 }
849 });
850​
851 it("preserves artifact-template examples inside code", () => {
852 const html = renderToStaticMarkup(
853 <ChatMarkdown
854 cwd="/tmp/project"
855 text={`\`${ARTIFACT_TEMPLATE_DIRECTIVE}\`\n\n\`\`\`text\n${ARTIFACT_TEMPLATE_DIRECTIVE}\n\`\`\``}
856 />,
857 );
858​
859 expect(html.match(/::artifact-template/g)).toHaveLength(2);
860 expect(html).not.toContain("data-chat-markdown-artifact-template");
861 });
862});
863​
864describe("ChatMarkdown heading levels", () => {
865 it("exposes headings below the host heading without changing their tags", () => {
866 const html = renderToStaticMarkup(
867 <ChatMarkdown
868 cwd="/tmp/project"
869 text={"# Top\n\n## Section\n\n###### Fine print"}
870 headingLevelOffset={3}
871 />,
872 );
873​
874 expect(html).toContain('<h1 aria-level="4">Top</h1>');
875 expect(html).toContain('<h2 aria-level="5">Section</h2>');
876 expect(html).toContain('<h6 aria-level="6">Fine print</h6>');
877 });
878​
879 it("leaves heading levels alone when the markdown is not nested", () => {
880 const html = renderToStaticMarkup(<ChatMarkdown cwd="/tmp/project" text="# Top" />);
881​
882 expect(html).toContain("<h1>Top</h1>");
883 });
884});
885​
886describe("shouldUseMarkdownFileBrowserPrimaryAction", () => {
887 it("uses the browser when it is the only available primary action", () => {
888 expect(
889 shouldUseMarkdownFileBrowserPrimaryAction({
890 iconPath: "/tmp/report.html",
891 canOpenInEditor: false,
892 canOpenInBrowser: true,
893 canOpenInPanel: false,
894 }),
895 ).toBe(true);
896 });
897​
898 it("preserves the normal editor and panel defaults for HTML files", () => {
899 expect(
900 shouldUseMarkdownFileBrowserPrimaryAction({
901 iconPath: "/tmp/report.html",
902 canOpenInEditor: true,
903 canOpenInBrowser: true,
904 canOpenInPanel: false,
905 }),
906 ).toBe(false);
907 expect(
908 shouldUseMarkdownFileBrowserPrimaryAction({
909 iconPath: "/tmp/report.html",
910 canOpenInEditor: false,
911 canOpenInBrowser: true,
912 canOpenInPanel: true,
913 }),
914 ).toBe(false);
915 });
916​
917 it("continues to open PDF files in the browser by default", () => {
918 expect(
919 shouldUseMarkdownFileBrowserPrimaryAction({
920 iconPath: "/tmp/report.pdf",
921 canOpenInEditor: true,
922 canOpenInBrowser: true,
923 canOpenInPanel: true,
924 }),
925 ).toBe(true);
926 });
927});
928​
929describe("ChatMarkdown Windows file links", () => {
930 const environmentId = EnvironmentId.make("env-windows");
931​
932 it.each([true, false])("preserves drive paths with parseRawHtml=%s", (parseRawHtml) => {
933 const html = renderToStaticMarkup(
934 <ChatMarkdown
935 cwd="C:/Users/shawn/project"
936 environmentId={environmentId}
937 text="[Open](C:/Users/shawn/project/src/main.ts)"
938 lineBreaks={!parseRawHtml}
939 parseRawHtml={parseRawHtml}
940 />,
941 );
942​
943 expect(html).toContain('href="C:/Users/shawn/project/src/main.ts"');
944 expect(html).toContain("chat-markdown-file-link");
945 });
946​
947 it.each([true, false])("normalizes backslashes with parseRawHtml=%s", (parseRawHtml) => {
948 const html = renderToStaticMarkup(
949 <ChatMarkdown
950 cwd="C:/Users/shawn/project"
951 environmentId={environmentId}
952 text={String.raw`[Open](C:\Users\shawn\project\src\main.ts)`}
953 lineBreaks={!parseRawHtml}
954 parseRawHtml={parseRawHtml}
955 />,
956 );
957​
958 expect(html).toContain('href="C:/Users/shawn/project/src/main.ts"');
959 expect(html).toContain("chat-markdown-file-link");
960 });
961​
962 it.each([true, false])(
963 "keeps backslashes CommonMark would read as escapes with parseRawHtml=%s",
964 (parseRawHtml) => {
965 const html = renderToStaticMarkup(
966 <ChatMarkdown
967 cwd="C:/Users/shawn/project"
968 environmentId={environmentId}
969 text={String.raw`[settings](C:\Users\shawn\.claude\settings.json)`}
970 lineBreaks={!parseRawHtml}
971 parseRawHtml={parseRawHtml}
972 />,
973 );
974​
975 expect(html).toContain('href="C:/Users/shawn/.claude/settings.json"');
976 },
977 );
978​
979 it.each([true, false])(
980 "distinguishes same-named backslash paths with parseRawHtml=%s",
981 (parseRawHtml) => {
982 const html = renderToStaticMarkup(
983 <ChatMarkdown
984 cwd="C:/Users/shawn/project"
985 environmentId={environmentId}
986 text={String.raw`[Source](C:\Users\shawn\project\src\index.ts) and [Test](C:\Users\shawn\project\test\index.ts)`}
987 lineBreaks={!parseRawHtml}
988 parseRawHtml={parseRawHtml}
989 />,
990 );
991​
992 expect(html).toContain("index.ts · project/src");
993 expect(html).toContain("index.ts · project/test");
994 },
995 );
996​
997 it.each([true, false])(
998 "does not disambiguate the same file in links and inline code with parseRawHtml=%s",
999 (parseRawHtml) => {
1000 const path = String.raw`C:\Users\shawn\project\src\main.ts`;
1001 const html = renderToStaticMarkup(
1002 <ChatMarkdown
1003 cwd="C:/Users/shawn/project"
1004 environmentId={environmentId}
1005 text={`[Source](${path}) and \`${path}\``}
1006 lineBreaks={!parseRawHtml}
1007 parseRawHtml={parseRawHtml}
1008 />,
1009 );
1010​
1011 expect(html.match(/chat-markdown-file-link/g)).toHaveLength(2);
1012 expect(html).not.toContain("main.ts ·");
1013 },
1014 );
1015​
1016 it.each([true, false])("preserves reference links with parseRawHtml=%s", (parseRawHtml) => {
1017 const html = renderToStaticMarkup(
1018 <ChatMarkdown
1019 cwd="C:/Users/shawn/project"
1020 environmentId={environmentId}
1021 text={"[Open][source]\n\n[source]: C:/Users/shawn/project/src/main.ts"}
1022 lineBreaks={!parseRawHtml}
1023 parseRawHtml={parseRawHtml}
1024 />,
1025 );
1026​
1027 expect(html).toContain('href="C:/Users/shawn/project/src/main.ts"');
1028 expect(html).toContain("chat-markdown-file-link");
1029 });
1030​
1031 it.each([true, false])("still rejects unsafe schemes with parseRawHtml=%s", (parseRawHtml) => {
1032 const html = renderToStaticMarkup(
1033 <ChatMarkdown
1034 cwd="C:/Users/shawn/project"
1035 environmentId={environmentId}
1036 text="[unsafe](javascript:alert(1)) and [unknown](d:alert(1))"
1037 lineBreaks={!parseRawHtml}
1038 parseRawHtml={parseRawHtml}
1039 />,
1040 );
1041​
1042 expect(html).not.toContain("javascript:");
1043 expect(html).not.toContain("d:alert");
1044 expect(html).not.toContain("chat-markdown-file-link");
1045 });
1046});
1047​
1048it("opens a disclosure only when find selects a match inside it", async () => {
1049 vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
1050 vi.stubGlobal(
1051 "Highlight",
1052 class extends Set<Range> {
1053 constructor(...ranges: Range[]) {
1054 super(ranges);
1056 },
1057 );
1058 const highlights = new Map<string, Set<Range>>();
1059 vi.stubGlobal("CSS", { highlights, escape: (value: string) => value });
1060 const container = document.createElement("div");
1061 document.body.append(container);
1062 const root = createRoot(container);
1063 const openStates = () =>
1064 [...container.querySelectorAll("[data-markdown-details-open]")].map((node) =>
1065 node.getAttribute("data-markdown-details-open"),
1066 );
1067 function Probe({
1068 activeOccurrence,
1069 searching = true,
1070 }: {
1071 activeOccurrence: number;
1072 searching?: boolean;
1073 }) {
1074 useThreadFindHighlights({
1075 container,
1076 query: searching ? "needle" : "",
1077 activeRowId: "row",
1078 activeOccurrence,
1079 onActiveRange: () => {},
1080 });
1081 return (
1082 <div data-timeline-row-id="row">
1083 <div data-thread-find-text>
1084 <MarkdownFindContext value={searching}>
1085 <ChatMarkdown
1086 cwd={undefined}
1087 text={[
1088 "Visible needle.",
1089 "<details><summary>Unrelated</summary><p>nothing here</p></details>",
1090 "<details><summary>Outer</summary><details><summary>Inner</summary><p>needle</p></details></details>",
1091 ].join("\n\n")}
1092 />
1093 </MarkdownFindContext>
1094 </div>
1095 </div>
1096 );
1098 const frame = () =>
1099 act(() => new Promise<void>((resolve) => requestAnimationFrame(() => resolve())));
1100 try {
1101 // Closed panels are unmounted until find starts, as in the app.
1102 await act(() => root.render(<Probe activeOccurrence={0} searching={false} />));
1103 expect(container.textContent).not.toContain("nothing here");
1104 await act(() => root.render(<Probe activeOccurrence={0} />));
1105 await frame();
1106 // Selecting the visible match opens nothing; the folded one is counted but not painted.
1107 expect(openStates()).toEqual(["false", "false", "false"]);
1108 expect(container.textContent).toContain("nothing here");
1109 expect(
1110 [...(highlights.get("t3-thread-find-active") ?? [])].map((range) => range.toString()),
1111 ).toEqual(["needle"]);
1112 expect(highlights.get("t3-thread-find")?.size).toBe(0);
1113​
1114 await act(() => root.render(<Probe activeOccurrence={1} />));
1115 await frame();
1116 await frame();
1117 // Stepping to the folded match opens its two ancestors, not the unrelated one.
1118 expect(openStates()).toEqual(["false", "true", "true"]);
1119 expect(highlights.get("t3-thread-find-active")?.size).toBe(1);
1120 } finally {
1121 await act(() => root.unmount());
1122 container.remove();
1123 vi.unstubAllGlobals();
1125});
1126​
1127it("keeps Mermaid diagrams rendered until find selects a match in their source", async () => {
1128 vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
1129 vi.stubGlobal(
1130 "Highlight",
1131 class extends Set<Range> {
1132 constructor(...ranges: Range[]) {
1133 super(ranges);
1135 },
1136 );
1137 const highlights = new Map<string, Set<Range>>();
1138 vi.stubGlobal("CSS", { highlights, escape: (value: string) => value });
1139 const container = document.createElement("div");
1140 document.body.append(container);
1141 const root = createRoot(container);
1142 const diagram = "```mermaid\ngraph TD; Alpha-->Beta\n```";
1143 function Probe({ query }: { query: string }) {
1144 useThreadFindHighlights({
1145 container,
1146 query,
1147 activeRowId: "row",
1148 activeOccurrence: 0,
1149 onActiveRange: () => {},
1150 });
1151 return (
1152 <div data-timeline-row-id="row">
1153 <div data-thread-find-text>
1154 <MarkdownFindContext value={true}>
1155 <ChatMarkdown cwd={undefined} text={`Needle first.\n\n${diagram}\n\n${diagram}`} />
1156 </MarkdownFindContext>
1157 </div>
1158 </div>
1159 );
1161 const frame = () =>
1162 act(() => new Promise<void>((resolve) => requestAnimationFrame(() => resolve())));
1163 const diagrams = () => container.querySelectorAll('svg[aria-label="Diagram"]').length;
1164 try {
1165 await act(() => root.render(<Probe query="Needle" />));
1166 await frame();
1167 expect(diagrams()).toBe(2);
1168 await act(() => root.render(<Probe query="Alpha" />));
1169 await frame();
1170 await frame();
1171 // Only the diagram holding the selected match switches to source.
1172 expect(diagrams()).toBe(1);
1173 expect(
1174 [...(highlights.get("t3-thread-find-active") ?? [])].map((range) => range.toString()),
1175 ).toEqual(["Alpha"]);
1176 } finally {
1177 await act(() => root.unmount());
1178 container.remove();
1179 vi.unstubAllGlobals();
1181});
1182​
1183it.each([
1185 text: "```mermaid\ngraph TD; SearchSourceAlpha-->B\n```",
1186 query: "SearchSourceAlpha",
1187 count: 1,
1188 },
1190 text: "★ Insight ─────\nfirst line\nsecond line",
1191 query: "first line second",
1192 count: 0,
1193 lineBreaks: true,
1194 },
1195 { text: '```ts title="src/needle.ts"\nconst a = 1;\n```', query: "needle", count: 0 },
1196 { text: "```weirdlang\nconst a = 1;\n```", query: "weirdlang", count: 0 },
1197 { text: "Use $test-t3-app now", query: "T3 App Testing", count: 1 },
1198 { text: "`/tmp/file.ts:42`", query: "file.ts · L42", count: 1, user: true, lineBreaks: true },
1199 { text: "> [!NOTE]\n> Searchable alert", query: "Searchable alert", count: 1 },
1201 text: "<details><summary>Folded</summary><p>Hidden needle</p></details>",
1202 query: "Hidden needle",
1203 count: 1,
1204 },
1205 { text: ARTIFACT_TEMPLATE_DIRECTIVE, query: "Hello World", count: 1, useTemplate: true },
1206 { text: ARTIFACT_TEMPLATE_DIRECTIVE, query: "Document template", count: 1, useTemplate: true },
1207 { text: ARTIFACT_TEMPLATE_DIRECTIVE, query: "World Document", count: 0, useTemplate: true },
1208 { text: ARTIFACT_TEMPLATE_DIRECTIVE, query: "Use template", count: 0, useTemplate: true },
1209])(
1210 "highlights the indexed occurrences of $query in $text",
1211 async ({ text, query, count, lineBreaks, user, useTemplate }) => {
1212 const skills = [{ name: "test-t3-app", displayName: "T3 App Testing" }];
1213 const highlights = new Map<string, Set<Range>>();
1214 vi.stubGlobal(
1215 "Highlight",
1216 class extends Set<Range> {
1217 constructor(...ranges: Range[]) {
1218 super(ranges);
1220 },
1221 );
1222 vi.stubGlobal("CSS", { highlights, escape: (value: string) => value });
1223 vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
1224 const container = document.createElement("div");
1225 document.body.append(container);
1226 const root = createRoot(container);
1227 function Probe() {
1228 useThreadFindHighlights({
1229 container,
1230 query,
1231 activeRowId: "row",
1232 activeOccurrence: 0,
1233 onActiveRange: () => {},
1234 });
1235 return (
1236 <div data-timeline-row-id="row">
1237 <div data-thread-find-text>
1238 <MarkdownFindContext value={true}>
1239 <ChatMarkdown
1240 text={text}
1241 cwd={undefined}
1242 skills={skills}
1243 lineBreaks={lineBreaks ?? false}
1244 parseRawHtml={!user}
1245 onUseArtifactTemplate={useTemplate ? () => undefined : undefined}
1246 />
1247 </MarkdownFindContext>
1248 </div>
1249 </div>
1250 );
1252 try {
1253 await act(() => root.render(<Probe />));
1254 await act(() => new Promise<void>((resolve) => requestAnimationFrame(() => resolve())));
1255 const ranges = [...highlights.values()].flatMap((value) => [...value]);
1256 expect(ranges.map((range) => range.toString())).toEqual(
1257 Array.from({ length: count }, () => query),
1258 );
1259 const segments =
1260 searchableMessageSegments(
1261 { role: user ? "user" : "assistant", text, streaming: false },
1262 undefined,
1263 skills,
1264 ) ?? [];
1265 expect(
1266 segments.reduce((sum, segment) => sum + countThreadSearchOccurrences(segment, query), 0),
1267 ).toBe(count);
1268 } finally {
1269 await act(() => root.unmount());
1270 container.remove();
1271 vi.unstubAllGlobals();
1273 },