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