Open History to see the last commit
1import { EnvironmentId } from "@t3tools/contracts";
2import { searchableMessageSegments } from "@t3tools/shared/threadFindText";
3import { countThreadSearchOccurrences } from "@t3tools/shared/threadSearch";
4import { act, type ReactElement } from "react";
5import { createRoot, type Root } from "react-dom/client";
6import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
7
8import { getSyntaxHighlighterPromise } from "../lib/syntaxHighlighting";
9import { MarkdownFindContext } from "./chat/markdownFindContext";
10import { useThreadFindHighlights } from "./chat/threadFindHighlights";
11import { setMarkdownTaskChecked } from "./files/filePreviewMode";
12
13// Atoms derived from the server config run in the real registry over a missing config.
14vi.mock(import("../state/server"), async (original) => {
15 const actual = await original();
16 const { Atom } = await import("effect/reactivity");
17 const noConfig = Atom.make(null);
18 return {
19 ...actual,
20 serverEnvironment: { ...actual.serverEnvironment, configValueAtom: (() => noConfig) as never },
21 };
22});
23// A standard client session, so environment-owned file links can open.
24vi.mock(import("../state/session"), async (original) => {
25 const { AuthStandardClientScopes } = await import("@t3tools/contracts");
26 const granted = new Set<string>(AuthStandardClientScopes);
27 const hasScope = (environmentId: unknown, scope: string) =>
28 environmentId !== null && granted.has(scope);
29 return {
30 ...(await original()),
31 useEnvironmentScope: hasScope as never,
32 readEnvironmentScope: hasScope as never,
33 };
34});
35vi.mock(import("../remoteOpen"), async (original) => ({
36 ...(await original()),
37 useRemoteOpenResolution: () => ({ state: { mode: "local-exec" }, isResolved: true }) as never,
38}));
39// A rendered diagram is an SVG; real Mermaid layout is not what these tests exercise.
40vi.mock(import("./chat/MermaidDiagram"), async (original) => ({
41 ...(await original()),
42 MermaidDiagram: () => <svg aria-label="Diagram" />,
43}));
44
45import ChatMarkdown from "./ChatMarkdown";
46
47const roots: Root[] = [];
48
49beforeEach(() => {
50 vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
51});
52
53afterEach(async () => {
54 for (const root of roots.splice(0)) await act(async () => root.unmount());
55 document.body.replaceChildren();
56 CSS.highlights.clear();
57 vi.restoreAllMocks();
58 vi.unstubAllGlobals();
59});
60
61async function render(element: ReactElement) {
62 const container = document.body.appendChild(document.createElement("div"));
63 const root = createRoot(container);
64 roots.push(root);
65 await act(async () => root.render(element));
66 return {
67 container,
68 rerender: (next: ReactElement) => act(async () => root.render(next)),
69 };
70}
71
72async function renderText(text: string, props: Partial<Parameters<typeof ChatMarkdown>[0]> = {}) {
73 return (await render(<ChatMarkdown cwd="/tmp/project" text={text} {...props} />)).container;
74}
75
76function linkTexts(container: HTMLElement) {
77 return [...container.querySelectorAll("a")].map((link) => link.textContent);
78}
79
80function buttonsLabelled(container: HTMLElement, label: string) {
81 return [...container.querySelectorAll<HTMLButtonElement>("button")].filter(
82 (button) => button.getAttribute("aria-label") === label,
83 );
84}
85
86function fileOptions(container: HTMLElement) {
87 return [...container.querySelectorAll("button")]
88 .map((button) => button.getAttribute("aria-label"))
89 .filter((label) => label?.startsWith("File options for "));
90}
91
92describe("ChatMarkdown bare anchor placeholders", () => {
93 it.each(["<A>", "<a>", "<a >", "<a/>", "<A/>", "<a />"])(
94 "preserves unmatched %s without linking later blocks",
95 async (token) => {
96 const container = await renderText(
97 `- **"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>.`,
98 );
99 expect(container.querySelector("strong")?.textContent).toBe(`"From ${token}"`);
100 expect(linkTexts(container)).toEqual(["the link"]);
101 expect(container.querySelectorAll("li")).toHaveLength(2);
102 expect([...container.querySelectorAll("p")].map((p) => p.textContent)).toContain(
103 "The deferred move continues on B.",
104 );
105 },
106 );
107
108 it.each(["</a> ", "<div>more</div>\n</a>"])(
109 "preserves a paired anchor closing in the raw block %s",
110 async (closing) => {
111 const container = await renderText(`See <a>label\n\n${closing}\n\nfinish`);
112 expect(container.querySelector("p")?.textContent).toBe("See label");
113 },
114 );
115
116 it("preserves a paired anchor after comment-looking raw text", async () => {
117 const container = await renderText("See <a>label<script><!-- </script> --></a>");
118 expect(container.querySelector("p")?.textContent).toBe("See label -->");
119 });
120
121 it.each(["<!-- </a> -->", '<div title="</a>">more</div>', '<script>"</a>"</script>'])(
122 "ignores apparent closing anchors inside %s",
123 async (html) => {
124 const container = await renderText(`Before <A>.\n\n${html}\n\nAfter.`);
125 expect(container.querySelector("p")?.textContent).toBe("Before <A>.");
126 expect(container.querySelectorAll("a")).toHaveLength(0);
127 },
128 );
129
130 it("preserves paired HTML anchors, details, markdown links, and inline code", async () => {
131 const container = await renderText(
132 'Bare <a>label</a>, <a id="section"></a>, `<A>`, and [docs](https://example.com).\n\n<details><summary>More</summary>Details</details>',
133 );
134 expect(linkTexts(container)).toEqual(["label", "", "docs"]);
135 expect(container.querySelector("code")?.textContent).toBe("<A>");
136 expect(container.querySelector("[data-markdown-details]")?.textContent).toContain("More");
137 });
138});
139
140describe("ChatMarkdown context references", () => {
141 it("renders text and image references through the chip renderer, with readable fallback", async () => {
142 const text =
143 "See [Terminal output](t3-context://v1/terminal/term-1) and .";
144 const { container, rerender } = await render(
145 <ChatMarkdown
146 cwd={undefined}
147 text={text}
148 renderContextReference={({ kind, label }) => (
149 <button>
150 {kind}: {label}
151 </button>
152 )}
153 />,
154 );
155 expect([...container.querySelectorAll("button")].map((button) => button.textContent)).toEqual([
156 "terminal: Terminal output",
157 "image: Error image",
158 ]);
159 expect(container.querySelectorAll("img, a")).toHaveLength(0);
160 await rerender(<ChatMarkdown cwd={undefined} text={text} />);
161 expect(container.textContent).toBe("See Terminal output and Error image.");
162 expect(container.querySelectorAll("img, a, button")).toHaveLength(0);
163 });
164
165 it("reads formatted context labels through nested markup instead of the context id", async () => {
166 const seen: Array<string> = [];
167 await render(
168 <ChatMarkdown
169 cwd={undefined}
170 text="See [**Bold** `code`](t3-context://v1/terminal/term-1)."
171 renderContextReference={({ kind, label }) => {
172 seen.push(`${kind}: ${label}`);
173 return <button>{label}</button>;
174 }}
175 />,
176 );
177 expect(new Set(seen)).toEqual(new Set(["terminal: Bold code"]));
178 });
179});
180
181describe("ChatMarkdown favicon privacy", () => {
182 it("suppresses private link images while preserving public links across updates", async () => {
183 const markdown = (url: string) => <ChatMarkdown cwd="/tmp/project" text={`[Link](${url})`} />;
184 const { container, rerender } = await render(markdown("https://example.com"));
185 expect([...container.querySelectorAll("img")].map((image) => image.src)).toEqual([
186 "https://www.google.com/s2/favicons?domain=example.com&sz=32",
187 ]);
188 for (const url of ["http://192.168.1.10:8080", "http://localhost:3000", "http://home.arpa"]) {
189 await rerender(markdown(url));
190 expect(container.querySelectorAll("img")).toHaveLength(0);
191 }
192 await rerender(markdown("https://example.com"));
193 expect(container.querySelectorAll("img")).toHaveLength(1);
194 await rerender(markdown("https://github.com/pingdotgg/t3code/pull/1"));
195 expect(container.querySelectorAll("img")).toHaveLength(0);
196 expect(container.querySelector("a svg")).not.toBeNull();
197 });
198});
199
200describe("ChatMarkdown streaming", () => {
201 it("runs only a complete single-line shell block after a click", async () => {
202 const onRunShellCommand = vi.fn();
203 const message = (text: string, isStreaming = false) => (
204 <ChatMarkdown
205 cwd="/tmp/project"
206 text={text}
207 isStreaming={isStreaming}
208 onRunShellCommand={onRunShellCommand}
209 />
210 );
211 const { container, rerender } = await render(message("```bash\necho hello\n```", true));
212 const runButtons = () => buttonsLabelled(container, "Run in terminal");
213 expect(runButtons()).toHaveLength(0);
214
215 await rerender(message("```bash\necho hello\n```"));
216 await act(async () => runButtons()[0]!.click());
217 expect(onRunShellCommand).toHaveBeenCalledExactlyOnceWith("echo hello");
218
219 for (const text of [
220 "~~~bash\necho tilde\n~~~",
221 "> ```bash\n> echo quote\n> ```",
222 "````bash\necho four\n````",
223 ]) {
224 await rerender(message(text));
225 expect(runButtons()).toHaveLength(1);
226 }
227
228 for (const text of [
229 "```bash\necho one\necho two\n```",
230 "```typescript\necho hello\n```",
231 "```bash\n\n```",
232 "```bash\necho hello\n\n```",
233 "```bash\necho hello\\\n```",
234 "```bash\necho safe \u202e#\n```",
235 "```bash\necho incomplete",
236 "~~~bash\necho incomplete",
237 "````bash\necho incomplete\n```",
238 '<pre><code class="language-bash">echo html</code></pre>',
239 ]) {
240 await rerender(message(text));
241 expect(runButtons()).toHaveLength(0);
242 }
243 });
244
245 it("does not retokenize completed lines when streaming finishes", async () => {
246 const highlighter = await getSyntaxHighlighterPromise("typescript");
247 const highlight = vi.spyOn(highlighter, "codeToHast");
248 const text = "```typescript\nconst completed = 1;\nconst current = 2;";
249 const { rerender } = await render(<ChatMarkdown cwd="/tmp/project" text={text} isStreaming />);
250 await vi.waitFor(() => expect(highlight).toHaveBeenCalled());
251 highlight.mockClear();
252 await rerender(<ChatMarkdown cwd="/tmp/project" text={text + "\n```"} />);
253 expect(highlight.mock.calls.every(([code]) => !code.includes("const completed"))).toBe(true);
254 });
255
256 it("recovers highlighting after a failed fence changes without resetting its controls", async () => {
257 const highlighter = await getSyntaxHighlighterPromise("text");
258 const codeToHast = highlighter.codeToHast.bind(highlighter);
259 let fail = true;
260 vi.spyOn(highlighter, "codeToHast").mockImplementation((...args) => {
261 if (fail) throw new Error("Temporary highlighter failure");
262 return codeToHast(...args);
263 });
264 vi.spyOn(console, "error").mockImplementation(() => {});
265 vi.spyOn(console, "warn").mockImplementation(() => {});
266
267 const { container, rerender } = await render(
268 <ChatMarkdown cwd="/tmp/project" text={"```text\ninitial\n```"} isStreaming />,
269 );
270 const codeBlock = container.querySelector<HTMLElement>('[data-language="text"]')!;
271 const initialWrap = codeBlock.dataset.wrap === "true";
272 await act(async () =>
273 buttonsLabelled(container, initialWrap ? "Disable line wrap" : "Wrap lines")[0]!.click(),
274 );
275 expect(container.querySelectorAll(".chat-markdown-shiki")).toHaveLength(0);
276
277 fail = false;
278 await rerender(
279 <ChatMarkdown cwd="/tmp/project" text={"```text\nrecovered\n```"} isStreaming />,
280 );
281 await vi.waitFor(() =>
282 expect(container.querySelectorAll(".chat-markdown-shiki")).toHaveLength(1),
283 );
284 expect(container.querySelector('[data-language="text"]')).toBe(codeBlock);
285 expect(codeBlock.dataset.wrap).toBe(String(!initialWrap));
286 });
287
288 it("preserves code controls and details without highlighting an unchanged fence again", async () => {
289 const highlighter = await getSyntaxHighlighterPromise("text");
290 const highlight = vi.spyOn(highlighter, "codeToHast");
291 const writeText = vi
292 .spyOn(navigator.clipboard, "writeText")
293 .mockImplementation(async () => undefined);
294 const text = [
295 "```text",
296 "First code block",
297 "```",
298 "",
299 "<details><summary>More</summary>",
300 "",
301 "Details content",
302 "",
303 "</details>",
304 "",
305 "Streaming reply",
306 ].join("\n");
307
308 const { container, rerender } = await render(
309 <ChatMarkdown cwd="/tmp/project" text={text} isStreaming />,
310 );
311 const codeBlock = container.querySelector<HTMLElement>('[data-language="text"]')!;
312 const initialWrap = codeBlock.dataset.wrap === "true";
313 await act(async () => {
314 buttonsLabelled(container, initialWrap ? "Disable line wrap" : "Wrap lines")[0]!.click();
315 buttonsLabelled(container, "Copy code")[0]!.click();
316 });
317 await act(async () =>
318 container.querySelector<HTMLButtonElement>("[data-markdown-details-summary]")!.click(),
319 );
320 const details = container.querySelector<HTMLElement>("[data-markdown-details]")!;
321 expect(details.dataset.markdownDetailsOpen).toBe("true");
322 expect(container.textContent).toContain("Details content");
323 expect(writeText).toHaveBeenCalledWith("First code block\n");
324 expect(highlight).toHaveBeenCalledTimes(1);
325
326 for (let index = 0; index < 10; index += 1) {
327 await rerender(<ChatMarkdown cwd="/tmp/project" text={`${text} ${index}`} isStreaming />);
328 }
329
330 expect(highlight).toHaveBeenCalledTimes(1);
331 expect(container.querySelector('[data-language="text"]')).toBe(codeBlock);
332 expect(codeBlock.dataset.wrap).toBe(String(!initialWrap));
333 expect(container.querySelector("[data-markdown-details]")).toBe(details);
334 expect(details.dataset.markdownDetailsOpen).toBe("true");
335 await rerender(
336 <ChatMarkdown
337 cwd="/tmp/project"
338 text={text.replace("First code block", "Updated code block")}
339 isStreaming
340 />,
341 );
342 const copy = [
343 ...buttonsLabelled(container, "Copied"),
344 ...buttonsLabelled(container, "Copy code"),
345 ][0]!;
346 await act(async () => copy.click());
347 expect(writeText).toHaveBeenLastCalledWith("Updated code block\n");
348 expect(highlight).toHaveBeenCalledTimes(2);
349 });
350
351 it("edits the current task text and marker after reusing a renderer", async () => {
352 let editedText: string | undefined;
353 let rerender: (next: ReactElement) => Promise<void> = async () => {};
354 const message = (text: string): ReactElement => (
355 <ChatMarkdown
356 cwd="/tmp/project"
357 text={text}
358 onTaskListChange={({ markerOffset, checked }) => {
359 editedText = setMarkdownTaskChecked(text, markerOffset, checked);
360 void rerender(message(editedText));
361 }}
362 />
363 );
364 const rendered = await render(message("- [ ] First\n- [ ] Second"));
365 rerender = rendered.rerender;
366 const { container } = rendered;
367 const checkboxes = () => container.querySelectorAll<HTMLInputElement>('input[type="checkbox"]');
368 const original = checkboxes()[1]!;
369 await rerender(message("- [ ] A longer first task\n- [ ] Second"));
370 expect(checkboxes()[1]).toBe(original);
371
372 await act(async () => original.click());
373 expect(editedText).toBe("- [ ] A longer first task\n- [x] Second");
374 await vi.waitFor(() => expect(checkboxes()[1]!.checked).toBe(true));
375 });
376});
377
378describe("ChatMarkdown skill chips", () => {
379 it("updates digit-leading skill labels when discovered skills change", async () => {
380 const text = "Use $2spec with a $20k budget.";
381 const { container, rerender } = await render(<ChatMarkdown cwd="/tmp/project" text={text} />);
382 expect(container.textContent).not.toContain("2Spec");
383
384 await rerender(
385 <ChatMarkdown
386 cwd="/tmp/project"
387 text={text}
388 skills={[
389 { name: "2spec", displayName: "2Spec" },
390 { name: "20k", displayName: "MoneySkill" },
391 ]}
392 />,
393 );
394 expect(container.textContent).toContain("2Spec");
395 expect(container.textContent).toContain("$20k budget");
396 expect(container.textContent).not.toContain("MoneySkill");
397
398 await rerender(<ChatMarkdown cwd="/tmp/project" text={text} skills={[]} />);
399 expect(container.textContent).not.toContain("2Spec");
400 });
401});
402
403describe("ChatMarkdown file citations", () => {
404 it.each([true, false])(
405 "renders Codex file citations as file chips with parseRawHtml=%s",
406 async (parseRawHtml) => {
407 const container = await renderText(
408 'Created :codex-file-citation{path="/tmp/project/outputs/report.xlsx" purpose="output"}.',
409 { lineBreaks: !parseRawHtml, parseRawHtml },
410 );
411 expect(container.textContent).not.toContain("codex-file-citation");
412 expect(fileOptions(container)).toEqual(["File options for report.xlsx"]);
413 },
414 );
415
416 it("leaves an unfinished streaming citation visible until it is complete", async () => {
417 const container = await renderText(
418 'Created :codex-file-citation{path="/tmp/project/outputs/report.xlsx"',
419 { isStreaming: true },
420 );
421 expect(container.textContent).toContain(":codex-file-citation");
422 expect(fileOptions(container)).toEqual([]);
423 });
424
425 it.each([
426 ':codex-file-citation{purpose="output"}',
427 ':codex-file-citation-extra{path="/tmp/project/outputs/report.xlsx"}',
428 'Example: \\:codex-file-citation{path="/tmp/project/outputs/report.xlsx"}',
429 ])("leaves %s literal", async (text) => {
430 const container = await renderText(text);
431 expect(container.textContent).toContain(text.replace("\\", ""));
432 expect(fileOptions(container)).toEqual([]);
433 });
434
435 it("preserves Codex file citation examples inside code", async () => {
436 const directive = ':codex-file-citation{path="/tmp/project/outputs/report.xlsx"}';
437 const container = await renderText(
438 `Example: \`${directive}\`\n\n\`\`\`text\n${directive}\n\`\`\``,
439 );
440 expect(container.textContent?.match(/:codex-file-citation/g)).toHaveLength(2);
441 expect(fileOptions(container)).toEqual([]);
442 });
443
444 it("does not create a nested link for citations inside link text", async () => {
445 const directive = ':codex-file-citation{path="/tmp/project/outputs/report.xlsx"}';
446 const container = await renderText(`[See ${directive}](https://example.com)`);
447 expect(container.textContent).toContain("codex-file-citation");
448 expect(fileOptions(container)).toEqual([]);
449 });
450
451 it("renders file citations created by over-indented list recovery", async () => {
452 const container = await renderText(
453 '- Created :codex-file-citation{path="/tmp/project/outputs/report.xlsx"}',
454 );
455 expect(container.querySelector("pre")).toBeNull();
456 expect(container.querySelector("li")?.textContent).toContain("Created ");
457 expect(fileOptions(container)).toEqual(["File options for report.xlsx"]);
458 });
459
460 it("disambiguates Codex citations with the same basename", async () => {
461 const container = await renderText(
462 'Changed :codex-file-citation{path="/tmp/project/src/index.ts"} and :codex-file-citation{path="/tmp/project/test/index.ts"}.',
463 );
464 expect(container.textContent).toContain("index.ts · project/src");
465 expect(container.textContent).toContain("index.ts · project/test");
466 });
467
468 it("preserves rejected citations created by over-indented list recovery", async () => {
469 const malformed = await renderText(
470 'Leading text before list.\n\n- Bad :codex-file-citation{purpose="output"}',
471 );
472 expect(malformed.querySelector("li")?.textContent).toBe(
473 'Bad :codex-file-citation{purpose="output"}',
474 );
475 const nestedLink = await renderText(
476 'Leading text before list.\n\n- [Bad :codex-file-citation{path="/tmp/project/report.xlsx"}](https://example.com)',
477 );
478 expect(nestedLink.textContent).toContain(
479 'Bad :codex-file-citation{path="/tmp/project/report.xlsx"}',
480 );
481 });
482});
483
484describe("ChatMarkdown Codex follow-up suggestions", () => {
485 it.each([true, false])("renders the label with parseRawHtml=%s", async (parseRawHtml) => {
486 const container = await renderText(
487 'Done.\n\n- :codex-followup[Prepare print version]{prompt="Prepare the document for printing."}',
488 { lineBreaks: !parseRawHtml, parseRawHtml },
489 );
490 expect(container.textContent).toContain("Prepare print version");
491 expect(container.textContent).not.toContain("codex-followup");
492 expect(container.textContent).not.toContain("Prepare the document for printing.");
493 });
494
495 it("keeps the label of a malformed follow-up created by over-indented list recovery", async () => {
496 const container = await renderText("- Next :codex-followup[Prepare print version]");
497 expect(container.querySelector("li")?.textContent).toBe(
498 "Next :codex-followup[Prepare print version]",
499 );
500 });
501});
502
503const ARTIFACT_TEMPLATE_DIRECTIVE =
504 '::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"}';
505
506describe("ChatMarkdown artifact-template cards", () => {
507 it.each([true, false])(
508 "offers the Codex template from its card with parseRawHtml=%s",
509 async (parseRawHtml) => {
510 const onUseArtifactTemplate = vi.fn();
511 const container = await renderText(ARTIFACT_TEMPLATE_DIRECTIVE, {
512 parseRawHtml,
513 onUseArtifactTemplate,
514 });
515 expect(container.textContent).not.toContain("::artifact-template");
516 expect(container.textContent).toContain("Hello World");
517 expect(container.textContent).toContain("Document template");
518 expect(container.querySelector("p div")).toBeNull();
519 const use = [...container.querySelectorAll("button")].find(
520 (button) => button.textContent === "Use template",
521 )!;
522 await act(async () => use.click());
523 expect(onUseArtifactTemplate).toHaveBeenCalledWith(
524 expect.objectContaining({
525 skillName: "artifact-template-hello-world",
526 displayName: "Hello World",
527 }),
528 );
529 },
530 );
531
532 it("renders a passive card outside a composer-backed timeline", async () => {
533 const container = await renderText(ARTIFACT_TEMPLATE_DIRECTIVE);
534 expect(container.textContent).toContain("Hello World");
535 expect(container.textContent).not.toContain("Use template");
536 });
537
538 it.each([
539 '::artifact-template{skill_name="artifact-template-hello-world" display_name="Hello World" artifact_kind="document"}',
540 ARTIFACT_TEMPLATE_DIRECTIVE.slice(0, -1),
541 `\\${ARTIFACT_TEMPLATE_DIRECTIVE}`,
542 ARTIFACT_TEMPLATE_DIRECTIVE.replace("::artifact-template", "::artifact-template-extra"),
543 ])("leaves %s literal", async (text) => {
544 const container = await renderText(text);
545 expect(container.textContent).toContain("::artifact-template");
546 expect(container.textContent).not.toContain("Document template");
547 });
548
549 it("preserves artifact-template examples inside code", async () => {
550 const container = await renderText(
551 `\`${ARTIFACT_TEMPLATE_DIRECTIVE}\`\n\n\`\`\`text\n${ARTIFACT_TEMPLATE_DIRECTIVE}\n\`\`\``,
552 );
553 expect(container.textContent?.match(/::artifact-template/g)).toHaveLength(2);
554 expect(container.textContent).not.toContain("Document template");
555 });
556});
557
558describe("ChatMarkdown headings", () => {
559 it("exposes headings below the host heading without changing their tags", async () => {
560 const container = await renderText("# Top\n\n## Section\n\n###### Fine print", {
561 headingLevelOffset: 3,
562 });
563 expect(
564 [...container.querySelectorAll("h1, h2, h6")].map((heading) => [
565 heading.tagName,
566 heading.getAttribute("aria-level"),
567 ]),
568 ).toEqual([
569 ["H1", "4"],
570 ["H2", "5"],
571 ["H6", "6"],
572 ]);
573 const flat = await renderText("# Top");
574 expect(flat.querySelector("h1")?.hasAttribute("aria-level")).toBe(false);
575 });
576
577 it("never gives two headings the same id, even when a suffix matches another heading", async () => {
578 const container = await renderText(
579 '## Setup\n\n## Setup\n\n## Setup-1\n\n<h2 id="install-1">Pinned</h2>\n\n## Install\n\n## Install',
580 { parseRawHtml: true },
581 );
582 expect([...container.querySelectorAll("h2")].map((heading) => heading.id)).toEqual([
583 "user-content-setup",
584 "user-content-setup-1",
585 "user-content-setup-1-1",
586 "user-content-install-1",
587 "user-content-install",
588 "user-content-install-2",
589 ]);
590 });
591});
592
593describe("ChatMarkdown Windows file links", () => {
594 const environmentId = EnvironmentId.make("env-windows");
595 const renderWindows = (text: string, parseRawHtml: boolean) =>
596 renderText(text, {
597 cwd: "C:/Users/shawn/project",
598 environmentId,
599 lineBreaks: !parseRawHtml,
600 parseRawHtml,
601 });
602 const fileHrefs = (container: HTMLElement) =>
603 [...container.querySelectorAll(".chat-markdown-file-link")].map((chip) =>
604 chip.getAttribute("href"),
605 );
606
607 it.each([
608 ["drive paths", "[Open](C:/Users/shawn/project/src/main.ts)"],
609 ["backslashes", String.raw`[Open](C:\Users\shawn\project\src\main.ts)`],
610 ["reference links", "[Open][source]\n\n[source]: C:/Users/shawn/project/src/main.ts"],
611 ])("resolves %s to the workspace file", async (_, text) => {
612 for (const parseRawHtml of [true, false]) {
613 const container = await renderWindows(text, parseRawHtml);
614 expect(fileHrefs(container)).toEqual(["C:/Users/shawn/project/src/main.ts"]);
615 }
616 });
617
618 it("keeps backslashes CommonMark would read as escapes", async () => {
619 for (const parseRawHtml of [true, false]) {
620 const container = await renderWindows(
621 String.raw`[settings](C:\Users\shawn\.claude\settings.json)`,
622 parseRawHtml,
623 );
624 expect(fileHrefs(container)).toEqual(["C:/Users/shawn/.claude/settings.json"]);
625 }
626 });
627
628 it("distinguishes same-named backslash paths but not the same file twice", async () => {
629 for (const parseRawHtml of [true, false]) {
630 const distinct = await renderWindows(
631 String.raw`[Source](C:\Users\shawn\project\src\index.ts) and [Test](C:\Users\shawn\project\test\index.ts)`,
632 parseRawHtml,
633 );
634 expect(distinct.textContent).toContain("index.ts · project/src");
635 expect(distinct.textContent).toContain("index.ts · project/test");
636 const path = String.raw`C:\Users\shawn\project\src\main.ts`;
637 const same = await renderWindows(`[Source](${path}) and \`${path}\``, parseRawHtml);
638 expect(fileHrefs(same)).toHaveLength(2);
639 expect(same.textContent).not.toContain("main.ts ·");
640 }
641 });
642
643 it("still rejects unsafe schemes", async () => {
644 for (const parseRawHtml of [true, false]) {
645 const container = await renderWindows(
646 "[unsafe](javascript:alert(1)) and [unknown](d:alert(1))",
647 parseRawHtml,
648 );
649 expect(container.innerHTML).not.toContain("javascript:");
650 expect(container.innerHTML).not.toContain("d:alert");
651 expect(fileHrefs(container)).toEqual([]);
652 }
653 });
654});
655
656describe("ChatMarkdown in-page links", () => {
657 it.each([true, false])(
658 "scrolls a table-of-contents link to its heading without touching the URL (parseRawHtml=%s)",
659 async (parseRawHtml) => {
660 const scrollIntoView = vi
661 .spyOn(HTMLElement.prototype, "scrollIntoView")
662 .mockImplementation(() => {});
663 const href = window.location.href;
664 const container = await renderText(
665 "- [Operating model](#1-operating-model)\n- [Missing](#nowhere)\n\n## 1. Operating model\n\n## 1. Operating model",
666 { parseRawHtml },
667 );
668 const headings = [...container.querySelectorAll("h2")];
669 expect(headings.map((heading) => heading.id)).toEqual([
670 "user-content-1-operating-model",
671 "user-content-1-operating-model-1",
672 ]);
673 const [tocLink, missingLink] = [...container.querySelectorAll("a")];
674 await act(async () => tocLink!.click());
675 expect(scrollIntoView.mock.contexts).toEqual([headings[0]]);
676 await act(async () => missingLink!.click());
677 expect(scrollIntoView).toHaveBeenCalledTimes(1);
678 expect(window.location.href).toBe(href);
679 },
680 );
681});
682
683describe("ChatMarkdown thread find", () => {
684 function FindProbe(props: {
685 container: HTMLElement;
686 query: string;
687 activeOccurrence?: number;
688 children: ReactElement;
689 }) {
690 useThreadFindHighlights({
691 container: props.container,
692 query: props.query,
693 activeRowId: "row",
694 activeOccurrence: props.activeOccurrence ?? 0,
695 onActiveRange: () => {},
696 });
697 return (
698 <div data-timeline-row-id="row">
699 <div data-thread-find-text>
700 <MarkdownFindContext value={props.query !== ""}>{props.children}</MarkdownFindContext>
701 </div>
702 </div>
703 );
704 }
705 const frame = () =>
706 act(() => new Promise<void>((resolve) => requestAnimationFrame(() => resolve())));
707 const activeHighlights = () =>
708 [...(CSS.highlights.get("t3-thread-find-active") ?? [])].map((range) =>
709 (range as Range).toString(),
710 );
711
712 it("opens a disclosure only when find selects a match inside it", async () => {
713 const container = document.body.appendChild(document.createElement("div"));
714 const root = createRoot(container);
715 roots.push(root);
716 const markdown = (
717 <ChatMarkdown
718 cwd={undefined}
719 text={[
720 "Visible needle.",
721 "<details><summary>Unrelated</summary><p>nothing here</p></details>",
722 "<details><summary>Outer</summary><details><summary>Inner</summary><p>needle</p></details></details>",
723 ].join("\n\n")}
724 />
725 );
726 const show = (query: string, activeOccurrence: number) =>
727 act(() =>
728 root.render(
729 <FindProbe container={container} query={query} activeOccurrence={activeOccurrence}>
730 {markdown}
731 </FindProbe>,
732 ),
733 );
734 const openStates = () =>
735 [...container.querySelectorAll<HTMLElement>("[data-markdown-details-open]")].map(
736 (node) => node.dataset.markdownDetailsOpen,
737 );
738
739 await show("", 0);
740 expect(container.textContent).not.toContain("nothing here");
741 await show("needle", 0);
742 await frame();
743 expect(openStates()).toEqual(["false", "false", "false"]);
744 expect(container.textContent).toContain("nothing here");
745 expect(activeHighlights()).toEqual(["needle"]);
746 expect(CSS.highlights.get("t3-thread-find")?.size ?? 0).toBe(0);
747
748 await show("needle", 1);
749 await frame();
750 await frame();
751 expect(openStates()).toEqual(["false", "true", "true"]);
752 expect(CSS.highlights.get("t3-thread-find-active")?.size).toBe(1);
753 });
754
755 it("keeps Mermaid diagrams rendered until find selects a match in their source", async () => {
756 const container = document.body.appendChild(document.createElement("div"));
757 const root = createRoot(container);
758 roots.push(root);
759 const diagram = "```mermaid\ngraph TD; Alpha-->Beta\n```";
760 const show = (query: string) =>
761 act(() =>
762 root.render(
763 <FindProbe container={container} query={query}>
764 <ChatMarkdown cwd={undefined} text={`Needle first.\n\n${diagram}\n\n${diagram}`} />
765 </FindProbe>,
766 ),
767 );
768 const diagrams = () => container.querySelectorAll('svg[aria-label="Diagram"]').length;
769
770 await show("Needle");
771 await frame();
772 expect(diagrams()).toBe(2);
773 await show("Alpha");
774 await frame();
775 await frame();
776 expect(diagrams()).toBe(1);
777 await vi.waitFor(() => expect(activeHighlights()).toEqual(["Alpha"]));
778 });
779
780 it.each([
781 {
782 text: "```mermaid\ngraph TD; SearchSourceAlpha-->B\n```",
783 query: "SearchSourceAlpha",
784 count: 1,
785 },
786 {
787 text: "★ Insight ─────\nfirst line\nsecond line",
788 query: "first line second",
789 count: 0,
790 lineBreaks: true,
791 },
792 { text: '```ts title="src/needle.ts"\nconst a = 1;\n```', query: "needle", count: 0 },
793 { text: "```weirdlang\nconst a = 1;\n```", query: "weirdlang", count: 0 },
794 { text: "Use $test-t3-app now", query: "T3 App Testing", count: 1 },
795 { text: "`/tmp/file.ts:42`", query: "file.ts · L42", count: 1, user: true, lineBreaks: true },
796 { text: "> [!NOTE]\n> Searchable alert", query: "Searchable alert", count: 1 },
797 {
798 text: "<details><summary>Folded</summary><p>Hidden needle</p></details>",
799 query: "Hidden needle",
800 count: 1,
801 },
802 { text: ARTIFACT_TEMPLATE_DIRECTIVE, query: "Hello World", count: 1, withTemplate: true },
803 {
804 text: ARTIFACT_TEMPLATE_DIRECTIVE,
805 query: "Document template",
806 count: 1,
807 withTemplate: true,
808 },
809 { text: ARTIFACT_TEMPLATE_DIRECTIVE, query: "World Document", count: 0, withTemplate: true },
810 { text: ARTIFACT_TEMPLATE_DIRECTIVE, query: "Use template", count: 0, withTemplate: true },
811 ])(
812 "highlights the indexed occurrences of $query in $text",
813 async ({ text, query, count, lineBreaks, user, withTemplate }) => {
814 const skills = [{ name: "test-t3-app", displayName: "T3 App Testing" }];
815 const container = document.body.appendChild(document.createElement("div"));
816 const root = createRoot(container);
817 roots.push(root);
818 await act(() =>
819 root.render(
820 <FindProbe container={container} query={query}>
821 <ChatMarkdown
822 text={text}
823 cwd={undefined}
824 skills={skills}
825 lineBreaks={lineBreaks ?? false}
826 parseRawHtml={!user}
827 onUseArtifactTemplate={withTemplate ? () => undefined : undefined}
828 />
829 </FindProbe>,
830 ),
831 );
832 await frame();
833 // Lazy blocks such as Mermaid can swap their source text after the first frame,
834 // emptying a range for a moment, so wait for the highlights to settle.
835 await vi.waitFor(() => {
836 const ranges = [...CSS.highlights.values()].flatMap((value) => [...value]);
837 expect(ranges.map((range) => (range as Range).toString())).toEqual(
838 Array.from({ length: count }, () => query),
839 );
840 });
841 const segments =
842 searchableMessageSegments(
843 { role: user ? "user" : "assistant", text, streaming: false },
844 undefined,
845 skills,
846 ) ?? [];
847 expect(
848 segments.reduce((sum, segment) => sum + countThreadSearchOccurrences(segment, query), 0),
849 ).toBe(count);
850 },
851 );
852});