Open History to see the last commit
1import { EnvironmentId, ThreadId } from "@t3tools/contracts";
2import { searchableMessageSegments } from "@t3tools/shared/threadFindText";
3import { countThreadSearchOccurrences } from "@t3tools/shared/threadSearch";
4import { AsyncResult } from "effect/reactivity";
5import { act, type ReactElement } from "react";
6import { createRoot, type Root } from "react-dom/client";
7import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
8import { page, userEvent } from "vite-plus/test/browser";
9
10import "../index.css";
11
12import { filesystemEnvironment } from "../state/filesystem";
13import { useRightPanelStore } from "../rightPanelStore";
14import { getSyntaxHighlighterPromise } from "../lib/syntaxHighlighting";
15import { MarkdownFindContext } from "./chat/markdownFindContext";
16import { useThreadFindHighlights } from "./chat/threadFindHighlights";
17import { setMarkdownTaskChecked } from "./files/filePreviewMode";
18
19const { workspaceSearch, filesystemMetadata } = vi.hoisted(() => ({
20 workspaceSearch: vi.fn(),
21 filesystemMetadata: vi.fn(),
22}));
23vi.mock(import("../state/use-atom-query-runner"), async (original) => ({
24 ...(await original()),
25 useAtomQueryRunner: ((family: unknown) =>
26 family === filesystemEnvironment.getMetadata ? filesystemMetadata : workspaceSearch) as never,
27}));
28
29// Atoms derived from the server config run in the real registry over a missing config.
30vi.mock(import("../state/server"), async (original) => {
31 const actual = await original();
32 const { Atom } = await import("effect/reactivity");
33 const noConfig = Atom.make(null);
34 return {
35 ...actual,
36 serverEnvironment: { ...actual.serverEnvironment, configValueAtom: (() => noConfig) as never },
37 };
38});
39// A standard client session, so environment-owned file links can open.
40vi.mock(import("../state/session"), async (original) => {
41 const { AuthStandardClientScopes } = await import("@t3tools/contracts");
42 const granted = new Set<string>(AuthStandardClientScopes);
43 const hasScope = (environmentId: unknown, scope: string) =>
44 environmentId !== null && granted.has(scope);
45 return {
46 ...(await original()),
47 useEnvironmentScope: hasScope as never,
48 readEnvironmentScope: hasScope as never,
49 };
50});
51vi.mock(import("../remoteOpen"), async (original) => ({
52 ...(await original()),
53 useRemoteOpenResolution: () => ({ state: { mode: "local-exec" }, isResolved: true }) as never,
54}));
55const { renderDiagram } = vi.hoisted(() => ({
56 renderDiagram: vi.fn<(source: string) => Promise<string> | undefined>(),
57}));
58// Control rendering latency without running Mermaid layout.
59vi.mock(import("./chat/MermaidDiagram"), async (original) => {
60 const { use } = await import("react");
61 return {
62 ...(await original()),
63 MermaidDiagram: ({ source }: { source: string }) => {
64 const pending = renderDiagram(source);
65 return <svg role="img" aria-label={pending ? use(pending) : "Diagram"} />;
66 },
67 };
68});
69
70const settingsOverrides = vi.hoisted(() => ({ mathRenderingEnabled: false }));
71vi.mock(import("../hooks/useSettings"), async (original) => {
72 const actual = await original();
73 type Settings = ReturnType<typeof actual.getClientSettings>;
74 function useClientSettings<T = Settings>(select?: (settings: Settings) => T): T {
75 const settings = { ...actual.getClientSettings(), ...settingsOverrides };
76 return select ? select(settings) : (settings as T);
77 }
78 return { ...actual, useClientSettings };
79});
80
81import ChatMarkdown from "./ChatMarkdown";
82import { serializeTableElementToCsv, chatMarkdownClipboardPayload } from "../markdown-clipboard";
83import { captureAssistantTextSelection } from "../lib/assistantTextSelection";
84
85const roots: Root[] = [];
86
87beforeEach(() => {
88 settingsOverrides.mathRenderingEnabled = false;
89 renderDiagram.mockReset();
90 workspaceSearch.mockReset().mockResolvedValue(AsyncResult.success({ entries: [] }));
91 filesystemMetadata.mockReset().mockResolvedValue(AsyncResult.success({ entries: [null] }));
92 vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
93});
94
95afterEach(async () => {
96 for (const root of roots.splice(0)) await act(async () => root.unmount());
97 document.body.replaceChildren();
98 CSS.highlights.clear();
99 vi.restoreAllMocks();
100 vi.unstubAllGlobals();
101});
102
103async function render(element: ReactElement) {
104 const container = document.body.appendChild(document.createElement("div"));
105 const root = createRoot(container);
106 roots.push(root);
107 await act(async () => root.render(element));
108 return {
109 container,
110 rerender: (next: ReactElement) => act(async () => root.render(next)),
111 };
112}
113
114async function renderText(text: string, props: Partial<Parameters<typeof ChatMarkdown>[0]> = {}) {
115 return (await render(<ChatMarkdown cwd="/tmp/project" text={text} {...props} />)).container;
116}
117
118function linkTexts(container: HTMLElement) {
119 return [...container.querySelectorAll("a")].map((link) => link.textContent);
120}
121
122function buttonsLabelled(container: HTMLElement, label: string) {
123 return [...container.querySelectorAll<HTMLButtonElement>("button")].filter(
124 (button) => button.getAttribute("aria-label") === label,
125 );
126}
127
128function fileOptions(container: HTMLElement) {
129 return [...container.querySelectorAll("button")]
130 .map((button) => button.getAttribute("aria-label"))
131 .filter((label) => label?.startsWith("File options for "));
132}
133
134describe("ChatMarkdown table layout", () => {
135 it.each([
136 { width: 36, timeline: true, fits: true },
137 { width: 48, timeline: true, fits: true },
138 { width: 35, timeline: true, fits: false },
139 { width: 48, timeline: false, fits: false },
140 ])(
141 "wraps expanded cells with fit=$fits in a $width rem container (timeline=$timeline)",
142 async ({ width, timeline, fits }) => {
143 const { container } = await render(
144 <div style={{ width: `${width}rem` }}>
145 <div className={timeline ? "@container/chat-lane chat-content-lane overflow-x-clip" : ""}>
146 <ChatMarkdown
147 cwd={undefined}
148 text={[
149 "| Change summary | Reason details | Verification status | Release impact | Followup actions |",
150 "| --- | --- | --- | --- | --- |",
151 "| Keep the complete explanation readable when the table is expanded in the conversation. | Allow each column to wrap its prose within the available space in the current chat lane. | Collapse and expand the table again to check that the text still fits and remains readable. | Keep the existing layout for narrow chat lanes and file previews. | Check the table again after resizing the conversation lane. |",
152 ].join("\n")}
153 />
154 </div>
155 </div>,
156 );
157 const table = container.querySelector("table")!;
158 const viewport = table.closest<HTMLElement>('[data-slot="scroll-area-viewport"]')!;
159 const cell = table.tBodies[0]!.rows[0]!.cells[0]!;
160 const collapse = () => buttonsLabelled(container, "Collapse table cells")[0];
161 if (collapse()) await act(async () => collapse()!.click());
162
163 const collapsedWidth = table.getBoundingClientRect().width;
164 const collapsedHeight = cell.getBoundingClientRect().height;
165 expect(viewport.clientWidth).toBeGreaterThan(0);
166 expect(viewport.scrollWidth).toBeGreaterThan(viewport.clientWidth);
167 expect(cell.scrollWidth).toBeGreaterThan(cell.clientWidth);
168
169 await act(async () => buttonsLabelled(container, "Expand table cells")[0]!.click());
170 const expandedWidth = table.getBoundingClientRect().width;
171 const expandedHeight = cell.getBoundingClientRect().height;
172 if (fits) {
173 expect(viewport.scrollWidth).toBeLessThanOrEqual(viewport.clientWidth + 1);
174 expect(expandedWidth).toBeLessThanOrEqual(viewport.clientWidth + 1);
175 } else {
176 expect(viewport.scrollWidth).toBeGreaterThan(viewport.clientWidth);
177 viewport.scrollLeft = 100;
178 expect(viewport.scrollLeft).toBeGreaterThan(0);
179 }
180 expect(expandedHeight).toBeGreaterThan(collapsedHeight);
181
182 await act(async () => collapse()!.click());
183 expect(table.getBoundingClientRect().width).toBeCloseTo(collapsedWidth, 0);
184 expect(cell.getBoundingClientRect().height).toBeCloseTo(collapsedHeight, 0);
185 await act(async () => buttonsLabelled(container, "Expand table cells")[0]!.click());
186 expect(table.getBoundingClientRect().width).toBeCloseTo(expandedWidth, 0);
187 expect(cell.getBoundingClientRect().height).toBeCloseTo(expandedHeight, 0);
188 },
189 );
190});
191
192describe("ChatMarkdown bare anchor placeholders", () => {
193 it.each(["<A>", "<a>", "<a >", "<a/>", "<A/>", "<a />"])(
194 "preserves unmatched %s without linking later blocks",
195 async (token) => {
196 const container = await renderText(
197 `- **"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>.`,
198 );
199 expect(container.querySelector("strong")?.textContent).toBe(`"From ${token}"`);
200 expect(linkTexts(container)).toEqual(["the link"]);
201 expect(container.querySelectorAll("li")).toHaveLength(2);
202 expect([...container.querySelectorAll("p")].map((p) => p.textContent)).toContain(
203 "The deferred move continues on B.",
204 );
205 },
206 );
207
208 it.each(["</a> ", "<div>more</div>\n</a>"])(
209 "preserves a paired anchor closing in the raw block %s",
210 async (closing) => {
211 const container = await renderText(`See <a>label\n\n${closing}\n\nfinish`);
212 expect(container.querySelector("p")?.textContent).toBe("See label");
213 },
214 );
215
216 it("preserves a paired anchor after comment-looking raw text", async () => {
217 const container = await renderText("See <a>label<script><!-- </script> --></a>");
218 expect(container.querySelector("p")?.textContent).toBe("See label -->");
219 });
220
221 it.each(["<!-- </a> -->", '<div title="</a>">more</div>', '<script>"</a>"</script>'])(
222 "ignores apparent closing anchors inside %s",
223 async (html) => {
224 const container = await renderText(`Before <A>.\n\n${html}\n\nAfter.`);
225 expect(container.querySelector("p")?.textContent).toBe("Before <A>.");
226 expect(container.querySelectorAll("a")).toHaveLength(0);
227 },
228 );
229
230 it("preserves paired HTML anchors, details, markdown links, and inline code", async () => {
231 const container = await renderText(
232 'Bare <a>label</a>, <a id="section"></a>, `<A>`, and [docs](https://example.com).\n\n<details><summary>More</summary>Details</details>',
233 );
234 expect(linkTexts(container)).toEqual(["label", "", "docs"]);
235 expect(container.querySelector("code")?.textContent).toBe("<A>");
236 expect(container.querySelector("[data-markdown-details]")?.textContent).toContain("More");
237 });
238});
239
240describe("ChatMarkdown Mermaid streaming", () => {
241 it("reveals a completed fence while streaming and preserves it through later prose and stream end", async () => {
242 let finishRender!: (label: string) => void;
243 renderDiagram.mockReturnValue(
244 new Promise<string>((resolve) => {
245 finishRender = resolve;
246 }),
247 );
248 const source = "flowchart LR\nA --> B";
249 const open = `\`\`\`mermaid\n${source}`;
250 const closed = `${open}\n\`\`\`\n\n`;
251 const message = (text: string, isStreaming = true) => (
252 <ChatMarkdown cwd={undefined} text={text} isStreaming={isStreaming} />
253 );
254 const { container, rerender } = await render(message(open));
255 expect(container.querySelector("pre")?.textContent).toContain(source);
256 expect(renderDiagram).not.toHaveBeenCalled();
257
258 await rerender(message(closed));
259 expect(renderDiagram).toHaveBeenCalledWith(expect.stringContaining(source));
260 expect(container.querySelector('svg[role="img"]')).toBeNull();
261 expect(container.querySelector(".chat-markdown-shiki")).toBeNull();
262 const placeholder = container.querySelector("pre");
263 expect(placeholder?.getAttribute("aria-hidden")).toBe("true");
264 expect(placeholder?.textContent).toContain(source);
265
266 await act(async () => finishRender("Completed diagram"));
267 const diagram = container.querySelector('svg[role="img"]');
268 expect(diagram?.getAttribute("aria-label")).toBe("Completed diagram");
269 for (const streaming of [true, false]) {
270 await rerender(message(`${closed}The remaining explanation.`, streaming));
271 expect(container.querySelector('svg[role="img"]')).toBe(diagram);
272 expect(container.textContent).toContain("The remaining explanation.");
273 }
274
275 await act(async () => buttonsLabelled(container, "Show code")[0]!.click());
276 expect(container.querySelector('svg[role="img"]')).toBeNull();
277 expect(container.querySelector("pre")?.textContent).toContain(source);
278 await act(async () => buttonsLabelled(container, "Show diagram")[0]!.click());
279 expect(container.querySelector('svg[role="img"]')?.getAttribute("aria-label")).toBe(
280 "Completed diagram",
281 );
282 });
283
284 it.each([
285 ["short tilde marker", "~~~~mermaid\nflowchart LR\nA --> B\n~~~", "\n~~~~"],
286 [
287 "overindented blockquote marker",
288 "> ```mermaid\n> flowchart LR\n> A --> B\n> ```",
289 "\n> ```",
290 ],
291 [
292 "overindented list marker",
293 "- Diagram\n\n ```mermaid\n flowchart LR\n A --> B\n ```",
294 "\n ```",
295 ],
296 ])("keeps a %s in source until a real closer arrives", async (_, open, closing) => {
297 const message = (text: string) => <ChatMarkdown cwd={undefined} text={text} isStreaming />;
298 const { container, rerender } = await render(message(open));
299 expect(renderDiagram).not.toHaveBeenCalled();
300 expect(container.querySelector("pre")?.textContent).toContain("A --> B");
301
302 await rerender(message(`${open}${closing}`));
303 expect(container.querySelector('svg[role="img"]')?.getAttribute("aria-label")).toBe("Diagram");
304 });
305
306 it("does not mistake a CRLF stream cut after CR for a closed fence", async () => {
307 const open = "```mermaid\r\nflowchart LR\r\nA --> B\r\n\t```";
308 const message = (text: string) => <ChatMarkdown cwd={undefined} text={text} isStreaming />;
309 const { container, rerender } = await render(message(open));
310 expect(renderDiagram).not.toHaveBeenCalled();
311 await rerender(message(`${open}\r`));
312 expect(renderDiagram).not.toHaveBeenCalled();
313 expect(container.querySelector("pre")?.textContent).toContain("A --> B");
314
315 await rerender(message(`${open}\r\n\`\`\``));
316 expect(container.querySelector('svg[role="img"]')?.getAttribute("aria-label")).toBe("Diagram");
317 });
318
319 it("falls back to source when a completed diagram fails during streaming", async () => {
320 await getSyntaxHighlighterPromise("mermaid");
321 renderDiagram.mockImplementation(() => {
322 throw new Error("Invalid Mermaid diagram");
323 });
324 vi.spyOn(console, "error").mockImplementation(() => {});
325 const container = await renderText("```mermaid\ninvalid diagram\n```", { isStreaming: true });
326 expect(renderDiagram).toHaveBeenCalledWith(expect.stringContaining("invalid diagram"));
327 expect(container.querySelector('svg[role="img"]')).toBeNull();
328 expect(container.querySelector("pre")?.textContent).toContain("invalid diagram");
329 expect(container.querySelector("pre")?.getAttribute("aria-hidden")).not.toBe("true");
330 });
331});
332
333describe("ChatMarkdown context references", () => {
334 it("renders text and image references through the chip renderer, with readable fallback", async () => {
335 const text =
336 "See [Terminal output](t3-context://v1/terminal/term-1) and .";
337 const { container, rerender } = await render(
338 <ChatMarkdown
339 cwd={undefined}
340 text={text}
341 renderContextReference={({ kind, label }) => (
342 <button>
343 {kind}: {label}
344 </button>
345 )}
346 />,
347 );
348 expect([...container.querySelectorAll("button")].map((button) => button.textContent)).toEqual([
349 "terminal: Terminal output",
350 "image: Error image",
351 ]);
352 expect(container.querySelectorAll("img, a")).toHaveLength(0);
353 await rerender(<ChatMarkdown cwd={undefined} text={text} />);
354 expect(container.textContent).toBe("See Terminal output and Error image.");
355 expect(container.querySelectorAll("img, a, button")).toHaveLength(0);
356 });
357
358 it("reads formatted context labels through nested markup instead of the context id", async () => {
359 const seen: Array<string> = [];
360 await render(
361 <ChatMarkdown
362 cwd={undefined}
363 text="See [**Bold** `code`](t3-context://v1/terminal/term-1)."
364 renderContextReference={({ kind, label }) => {
365 seen.push(`${kind}: ${label}`);
366 return <button>{label}</button>;
367 }}
368 />,
369 );
370 expect(new Set(seen)).toEqual(new Set(["terminal: Bold code"]));
371 });
372});
373
374describe("ChatMarkdown favicon privacy", () => {
375 it("suppresses private link images while preserving public links across updates", async () => {
376 const markdown = (url: string) => <ChatMarkdown cwd="/tmp/project" text={`[Link](${url})`} />;
377 const { container, rerender } = await render(markdown("https://example.com"));
378 expect([...container.querySelectorAll("img")].map((image) => image.src)).toEqual([
379 "https://www.google.com/s2/favicons?domain=example.com&sz=32",
380 ]);
381 for (const url of ["http://192.168.1.10:8080", "http://localhost:3000", "http://home.arpa"]) {
382 await rerender(markdown(url));
383 expect(container.querySelectorAll("img")).toHaveLength(0);
384 }
385 await rerender(markdown("https://example.com"));
386 expect(container.querySelectorAll("img")).toHaveLength(1);
387 await rerender(markdown("https://github.com/pingdotgg/t3code/pull/1"));
388 expect(container.querySelectorAll("img")).toHaveLength(0);
389 expect(container.querySelector("a svg")).not.toBeNull();
390 });
391});
392
393describe("ChatMarkdown streaming", () => {
394 it("runs only a complete single-line shell block after a click", async () => {
395 const onRunShellCommand = vi.fn();
396 const message = (text: string, isStreaming = false) => (
397 <ChatMarkdown
398 cwd="/tmp/project"
399 text={text}
400 isStreaming={isStreaming}
401 onRunShellCommand={onRunShellCommand}
402 />
403 );
404 const { container, rerender } = await render(message("```bash\necho hello\n```", true));
405 const runButtons = () => buttonsLabelled(container, "Run in terminal");
406 expect(runButtons()).toHaveLength(0);
407
408 await rerender(message("```bash\necho hello\n```"));
409 await act(async () => runButtons()[0]!.click());
410 expect(onRunShellCommand).toHaveBeenCalledExactlyOnceWith("echo hello");
411
412 for (const text of [
413 "~~~bash\necho tilde\n~~~",
414 "> ```bash\n> echo quote\n> ```",
415 "````bash\necho four\n````",
416 "- Command\n\n ```bash\n echo list\n ```",
417 "```bash\r\necho crlf\r\n```\r",
418 ]) {
419 await rerender(message(text));
420 expect(runButtons()).toHaveLength(1);
421 }
422
423 for (const text of [
424 "```bash\necho one\necho two\n```",
425 "```typescript\necho hello\n```",
426 "```bash\n\n```",
427 "```bash\necho hello\n\n```",
428 "```bash\necho hello\\\n```",
429 "```bash\necho safe \u202e#\n```",
430 "```bash\necho incomplete",
431 "~~~bash\necho incomplete",
432 "````bash\necho incomplete\n```",
433 '<pre><code class="language-bash">echo html</code></pre>',
434 ]) {
435 await rerender(message(text));
436 expect(runButtons()).toHaveLength(0);
437 }
438 });
439
440 it("does not retokenize completed lines when streaming finishes", async () => {
441 const highlighter = await getSyntaxHighlighterPromise("typescript");
442 const highlight = vi.spyOn(highlighter, "codeToHast");
443 const text = "```typescript\nconst completed = 1;\nconst current = 2;";
444 const { rerender } = await render(<ChatMarkdown cwd="/tmp/project" text={text} isStreaming />);
445 await vi.waitFor(() => expect(highlight).toHaveBeenCalled());
446 highlight.mockClear();
447 await rerender(<ChatMarkdown cwd="/tmp/project" text={text + "\n```"} />);
448 expect(highlight.mock.calls.every(([code]) => !code.includes("const completed"))).toBe(true);
449 });
450
451 it("recovers highlighting after a failed fence changes without resetting its controls", async () => {
452 const highlighter = await getSyntaxHighlighterPromise("text");
453 const codeToHast = highlighter.codeToHast.bind(highlighter);
454 let fail = true;
455 vi.spyOn(highlighter, "codeToHast").mockImplementation((...args) => {
456 if (fail) throw new Error("Temporary highlighter failure");
457 return codeToHast(...args);
458 });
459 vi.spyOn(console, "error").mockImplementation(() => {});
460 vi.spyOn(console, "warn").mockImplementation(() => {});
461
462 const { container, rerender } = await render(
463 <ChatMarkdown cwd="/tmp/project" text={"```text\ninitial\n```"} isStreaming />,
464 );
465 const codeBlock = container.querySelector<HTMLElement>('[data-language="text"]')!;
466 const initialWrap = codeBlock.dataset.wrap === "true";
467 await act(async () =>
468 buttonsLabelled(container, initialWrap ? "Disable line wrap" : "Wrap lines")[0]!.click(),
469 );
470 expect(container.querySelectorAll(".chat-markdown-shiki")).toHaveLength(0);
471
472 fail = false;
473 await rerender(
474 <ChatMarkdown cwd="/tmp/project" text={"```text\nrecovered\n```"} isStreaming />,
475 );
476 await vi.waitFor(() =>
477 expect(container.querySelectorAll(".chat-markdown-shiki")).toHaveLength(1),
478 );
479 expect(container.querySelector('[data-language="text"]')).toBe(codeBlock);
480 expect(codeBlock.dataset.wrap).toBe(String(!initialWrap));
481 });
482
483 it("preserves code controls and details without highlighting an unchanged fence again", async () => {
484 const highlighter = await getSyntaxHighlighterPromise("text");
485 const highlight = vi.spyOn(highlighter, "codeToHast");
486 const writeText = vi
487 .spyOn(navigator.clipboard, "writeText")
488 .mockImplementation(async () => undefined);
489 const text = [
490 "```text",
491 "First code block",
492 "```",
493 "",
494 "<details><summary>More</summary>",
495 "",
496 "Details content",
497 "",
498 "</details>",
499 "",
500 "Streaming reply",
501 ].join("\n");
502
503 const { container, rerender } = await render(
504 <ChatMarkdown cwd="/tmp/project" text={text} isStreaming />,
505 );
506 const codeBlock = container.querySelector<HTMLElement>('[data-language="text"]')!;
507 const initialWrap = codeBlock.dataset.wrap === "true";
508 await act(async () => {
509 buttonsLabelled(container, initialWrap ? "Disable line wrap" : "Wrap lines")[0]!.click();
510 buttonsLabelled(container, "Copy code")[0]!.click();
511 });
512 await act(async () =>
513 container.querySelector<HTMLButtonElement>("[data-markdown-details-summary]")!.click(),
514 );
515 const details = container.querySelector<HTMLElement>("[data-markdown-details]")!;
516 expect(details.dataset.markdownDetailsOpen).toBe("true");
517 expect(container.textContent).toContain("Details content");
518 expect(writeText).toHaveBeenCalledWith("First code block\n");
519 expect(highlight).toHaveBeenCalledTimes(1);
520
521 for (let index = 0; index < 10; index += 1) {
522 await rerender(<ChatMarkdown cwd="/tmp/project" text={`${text} ${index}`} isStreaming />);
523 }
524
525 expect(highlight).toHaveBeenCalledTimes(1);
526 expect(container.querySelector('[data-language="text"]')).toBe(codeBlock);
527 expect(codeBlock.dataset.wrap).toBe(String(!initialWrap));
528 expect(container.querySelector("[data-markdown-details]")).toBe(details);
529 expect(details.dataset.markdownDetailsOpen).toBe("true");
530 await rerender(
531 <ChatMarkdown
532 cwd="/tmp/project"
533 text={text.replace("First code block", "Updated code block")}
534 isStreaming
535 />,
536 );
537 const copy = [
538 ...buttonsLabelled(container, "Copied"),
539 ...buttonsLabelled(container, "Copy code"),
540 ][0]!;
541 await act(async () => copy.click());
542 expect(writeText).toHaveBeenLastCalledWith("Updated code block\n");
543 expect(highlight).toHaveBeenCalledTimes(2);
544 });
545
546 it("edits the current task text and marker after reusing a renderer", async () => {
547 let editedText: string | undefined;
548 let rerender: (next: ReactElement) => Promise<void> = async () => {};
549 const message = (text: string): ReactElement => (
550 <ChatMarkdown
551 cwd="/tmp/project"
552 text={text}
553 onTaskListChange={({ markerOffset, checked }) => {
554 editedText = setMarkdownTaskChecked(text, markerOffset, checked);
555 void rerender(message(editedText));
556 }}
557 />
558 );
559 const rendered = await render(message("- [ ] First\n- [ ] Second"));
560 rerender = rendered.rerender;
561 const { container } = rendered;
562 const checkboxes = () => container.querySelectorAll<HTMLInputElement>('input[type="checkbox"]');
563 const original = checkboxes()[1]!;
564 await rerender(message("- [ ] A longer first task\n- [ ] Second"));
565 expect(checkboxes()[1]).toBe(original);
566
567 await act(async () => original.click());
568 expect(editedText).toBe("- [ ] A longer first task\n- [x] Second");
569 await vi.waitFor(() => expect(checkboxes()[1]!.checked).toBe(true));
570 });
571});
572
573describe("ChatMarkdown skill chips", () => {
574 it("updates digit-leading skill labels when discovered skills change", async () => {
575 const text = "Use $2spec with a $20k budget.";
576 const { container, rerender } = await render(<ChatMarkdown cwd="/tmp/project" text={text} />);
577 expect(container.textContent).not.toContain("2Spec");
578
579 await rerender(
580 <ChatMarkdown
581 cwd="/tmp/project"
582 text={text}
583 skills={[
584 { name: "2spec", displayName: "2Spec" },
585 { name: "20k", displayName: "MoneySkill" },
586 ]}
587 />,
588 );
589 expect(container.textContent).toContain("2Spec");
590 expect(container.textContent).toContain("$20k budget");
591 expect(container.textContent).not.toContain("MoneySkill");
592
593 await rerender(<ChatMarkdown cwd="/tmp/project" text={text} skills={[]} />);
594 expect(container.textContent).not.toContain("2Spec");
595 });
596});
597
598describe("ChatMarkdown workspace file opens", () => {
599 const threadRef = {
600 environmentId: EnvironmentId.make("workspace"),
601 threadId: ThreadId.make("thread"),
602 };
603
604 it.each([
605 {
606 cwd: "/school/courses/physics",
607 path: "courses/physics/notes/a.md",
608 indexedPath: "notes/a.md",
609 },
610 {
611 cwd: "C:/school/courses/Physics",
612 path: "courses/physics/notes/a.md",
613 indexedPath: "Notes/A.md",
614 },
615 ])(
616 "opens a repo-relative chip at its indexed path in $cwd",
617 async ({ cwd, path, indexedPath }) => {
618 workspaceSearch.mockResolvedValue(
619 AsyncResult.success({
620 entries: [
621 { path: indexedPath, kind: "file" },
622 { path, kind: "file" },
623 ],
624 truncated: false,
625 }),
626 );
627 const openFile = vi
628 .spyOn(useRightPanelStore.getState(), "openFile")
629 .mockImplementation(() => {});
630 const container = await renderText(`[Notes](${path}:7)`, { cwd, threadRef });
631
632 await act(async () => container.querySelector("a")!.click());
633
634 expect(openFile).toHaveBeenCalledExactlyOnceWith(threadRef, indexedPath, 7);
635 },
636 );
637
638 it("prefers an existing literal nested file over the stripped Windows match", async () => {
639 filesystemMetadata.mockResolvedValue(
640 AsyncResult.success({ entries: [{ kind: "file", byteLength: 10 }] }),
641 );
642 workspaceSearch.mockResolvedValue(
643 AsyncResult.success({
644 entries: [
645 { path: "Notes/A.md", kind: "file" },
646 { path: "Physics/Notes/A.md", kind: "file" },
647 ],
648 truncated: false,
649 }),
650 );
651 const openFile = vi
652 .spyOn(useRightPanelStore.getState(), "openFile")
653 .mockImplementation(() => {});
654 const container = await renderText("[Notes](physics/notes/a.md)", {
655 cwd: "C:/school/Physics",
656 threadRef,
657 });
658
659 await act(async () => container.querySelector("a")!.click());
660
661 expect(openFile).toHaveBeenCalledExactlyOnceWith(threadRef, "physics/notes/a.md", undefined);
662 });
663
664 it("keeps a literal file omitted by a truncated search", async () => {
665 workspaceSearch.mockResolvedValue(
666 AsyncResult.success({
667 entries: [{ path: "notes/a.md", kind: "file" }],
668 truncated: true,
669 }),
670 );
671 filesystemMetadata.mockResolvedValue(
672 AsyncResult.success({ entries: [{ kind: "file", byteLength: 10 }] }),
673 );
674 const openFile = vi
675 .spyOn(useRightPanelStore.getState(), "openFile")
676 .mockImplementation(() => {});
677 const container = await renderText("[Notes](physics/notes/a.md:7)", {
678 cwd: "/school/physics",
679 threadRef,
680 });
681
682 await act(async () => container.querySelector("a")!.click());
683
684 expect(openFile).toHaveBeenCalledExactlyOnceWith(threadRef, "physics/notes/a.md", 7);
685 expect(filesystemMetadata).toHaveBeenCalledExactlyOnceWith({
686 environmentId: threadRef.environmentId,
687 input: { paths: ["/school/physics/physics/notes/a.md"] },
688 });
689 });
690
691 it.each([
692 {
693 kind: "absolute link",
694 href: "/school/physics/physics/notes/a.md:7",
695 imageBaseDir: undefined,
696 },
697 { kind: "nested preview", href: "notes/a.md:7", imageBaseDir: "/school/physics/physics" },
698 ])(
699 "keeps the literal target for a $kind when only its stripped twin exists",
700 async ({ href, imageBaseDir }) => {
701 workspaceSearch.mockResolvedValue(
702 AsyncResult.success({
703 entries: [{ path: "notes/a.md", kind: "file" }],
704 truncated: false,
705 }),
706 );
707 const openFile = vi
708 .spyOn(useRightPanelStore.getState(), "openFile")
709 .mockImplementation(() => {});
710 const container = await renderText(`[Notes](${href})`, {
711 cwd: "/school/physics",
712 imageBaseDir,
713 threadRef,
714 });
715
716 await act(async () => container.querySelector("a")!.click());
717
718 expect(openFile).toHaveBeenCalledExactlyOnceWith(threadRef, "physics/notes/a.md", 7);
719 expect(workspaceSearch).not.toHaveBeenCalled();
720 expect(filesystemMetadata).not.toHaveBeenCalled();
721 },
722 );
723
724 it("keeps a newer absolute file open when an earlier repo-relative lookup finishes", async () => {
725 const result = AsyncResult.success({
726 entries: [{ path: "notes/a.md", kind: "file" }],
727 truncated: false,
728 });
729 let resolvePending!: (value: typeof result) => void;
730 const pending = new Promise<typeof result>((resolve) => {
731 resolvePending = resolve;
732 });
733 workspaceSearch.mockReturnValueOnce(pending);
734 const openFile = vi
735 .spyOn(useRightPanelStore.getState(), "openFile")
736 .mockImplementation(() => {});
737 const container = await renderText(
738 "[Notes](physics/notes/a.md) and [Other](/elsewhere/b.md:9)",
739 {
740 cwd: "/school/physics",
741 threadRef,
742 },
743 );
744 const [notes, other] = container.querySelectorAll("a");
745 await act(async () => notes!.click());
746 expect(workspaceSearch).toHaveBeenCalledOnce();
747 expect(openFile).not.toHaveBeenCalled();
748
749 await act(async () => other!.click());
750 await act(async () => resolvePending(result));
751
752 expect(openFile).toHaveBeenCalledExactlyOnceWith(threadRef, "/elsewhere/b.md", 9);
753 expect(workspaceSearch).toHaveBeenCalledOnce();
754 });
755});
756
757describe("ChatMarkdown file citations", () => {
758 it.each([true, false])(
759 "renders Codex file citations as file chips with parseRawHtml=%s",
760 async (parseRawHtml) => {
761 const container = await renderText(
762 'Created :codex-file-citation{path="/tmp/project/outputs/report.xlsx" purpose="output"}.',
763 { lineBreaks: !parseRawHtml, parseRawHtml },
764 );
765 expect(container.textContent).not.toContain("codex-file-citation");
766 expect(fileOptions(container)).toEqual(["File options for report.xlsx"]);
767 },
768 );
769
770 it("leaves an unfinished streaming citation visible until it is complete", async () => {
771 const container = await renderText(
772 'Created :codex-file-citation{path="/tmp/project/outputs/report.xlsx"',
773 { isStreaming: true },
774 );
775 expect(container.textContent).toContain(":codex-file-citation");
776 expect(fileOptions(container)).toEqual([]);
777 });
778
779 it.each([
780 ':codex-file-citation{purpose="output"}',
781 ':codex-file-citation-extra{path="/tmp/project/outputs/report.xlsx"}',
782 'Example: \\:codex-file-citation{path="/tmp/project/outputs/report.xlsx"}',
783 ])("leaves %s literal", async (text) => {
784 const container = await renderText(text);
785 expect(container.textContent).toContain(text.replace("\\", ""));
786 expect(fileOptions(container)).toEqual([]);
787 });
788
789 it("preserves Codex file citation examples inside code", async () => {
790 const directive = ':codex-file-citation{path="/tmp/project/outputs/report.xlsx"}';
791 const container = await renderText(
792 `Example: \`${directive}\`\n\n\`\`\`text\n${directive}\n\`\`\``,
793 );
794 expect(container.textContent?.match(/:codex-file-citation/g)).toHaveLength(2);
795 expect(fileOptions(container)).toEqual([]);
796 });
797
798 it("does not create a nested link for citations inside link text", async () => {
799 const directive = ':codex-file-citation{path="/tmp/project/outputs/report.xlsx"}';
800 const container = await renderText(`[See ${directive}](https://example.com)`);
801 expect(container.textContent).toContain("codex-file-citation");
802 expect(fileOptions(container)).toEqual([]);
803 });
804
805 it("renders file citations created by over-indented list recovery", async () => {
806 const container = await renderText(
807 '- Created :codex-file-citation{path="/tmp/project/outputs/report.xlsx"}',
808 );
809 expect(container.querySelector("pre")).toBeNull();
810 expect(container.querySelector("li")?.textContent).toContain("Created ");
811 expect(fileOptions(container)).toEqual(["File options for report.xlsx"]);
812 });
813
814 it("disambiguates Codex citations with the same basename", async () => {
815 const container = await renderText(
816 'Changed :codex-file-citation{path="/tmp/project/src/index.ts"} and :codex-file-citation{path="/tmp/project/test/index.ts"}.',
817 );
818 expect(container.textContent).toContain("index.ts · project/src");
819 expect(container.textContent).toContain("index.ts · project/test");
820 });
821
822 it("preserves rejected citations created by over-indented list recovery", async () => {
823 const malformed = await renderText(
824 'Leading text before list.\n\n- Bad :codex-file-citation{purpose="output"}',
825 );
826 expect(malformed.querySelector("li")?.textContent).toBe(
827 'Bad :codex-file-citation{purpose="output"}',
828 );
829 const nestedLink = await renderText(
830 'Leading text before list.\n\n- [Bad :codex-file-citation{path="/tmp/project/report.xlsx"}](https://example.com)',
831 );
832 expect(nestedLink.textContent).toContain(
833 'Bad :codex-file-citation{path="/tmp/project/report.xlsx"}',
834 );
835 });
836});
837
838describe("ChatMarkdown Codex follow-up suggestions", () => {
839 it.each([true, false])("renders the label with parseRawHtml=%s", async (parseRawHtml) => {
840 const container = await renderText(
841 'Done.\n\n- :codex-followup[Prepare print version]{prompt="Prepare the document for printing."}',
842 { lineBreaks: !parseRawHtml, parseRawHtml },
843 );
844 expect(container.textContent).toContain("Prepare print version");
845 expect(container.textContent).not.toContain("codex-followup");
846 expect(container.textContent).not.toContain("Prepare the document for printing.");
847 });
848
849 it("keeps the label of a malformed follow-up created by over-indented list recovery", async () => {
850 const container = await renderText("- Next :codex-followup[Prepare print version]");
851 expect(container.querySelector("li")?.textContent).toBe(
852 "Next :codex-followup[Prepare print version]",
853 );
854 });
855});
856
857const ARTIFACT_TEMPLATE_DIRECTIVE =
858 '::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"}';
859
860describe("ChatMarkdown artifact-template cards", () => {
861 it.each([true, false])(
862 "offers the Codex template from its card with parseRawHtml=%s",
863 async (parseRawHtml) => {
864 const onUseArtifactTemplate = vi.fn();
865 const container = await renderText(ARTIFACT_TEMPLATE_DIRECTIVE, {
866 parseRawHtml,
867 onUseArtifactTemplate,
868 });
869 expect(container.textContent).not.toContain("::artifact-template");
870 expect(container.textContent).toContain("Hello World");
871 expect(container.textContent).toContain("Document template");
872 expect(container.querySelector("p div")).toBeNull();
873 const use = [...container.querySelectorAll("button")].find(
874 (button) => button.textContent === "Use template",
875 )!;
876 await act(async () => use.click());
877 expect(onUseArtifactTemplate).toHaveBeenCalledWith(
878 expect.objectContaining({
879 skillName: "artifact-template-hello-world",
880 displayName: "Hello World",
881 }),
882 );
883 },
884 );
885
886 it("renders a passive card outside a composer-backed timeline", async () => {
887 const container = await renderText(ARTIFACT_TEMPLATE_DIRECTIVE);
888 expect(container.textContent).toContain("Hello World");
889 expect(container.textContent).not.toContain("Use template");
890 });
891
892 it.each([
893 '::artifact-template{skill_name="artifact-template-hello-world" display_name="Hello World" artifact_kind="document"}',
894 ARTIFACT_TEMPLATE_DIRECTIVE.slice(0, -1),
895 `\\${ARTIFACT_TEMPLATE_DIRECTIVE}`,
896 ARTIFACT_TEMPLATE_DIRECTIVE.replace("::artifact-template", "::artifact-template-extra"),
897 ])("leaves %s literal", async (text) => {
898 const container = await renderText(text);
899 expect(container.textContent).toContain("::artifact-template");
900 expect(container.textContent).not.toContain("Document template");
901 });
902
903 it("preserves artifact-template examples inside code", async () => {
904 const container = await renderText(
905 `\`${ARTIFACT_TEMPLATE_DIRECTIVE}\`\n\n\`\`\`text\n${ARTIFACT_TEMPLATE_DIRECTIVE}\n\`\`\``,
906 );
907 expect(container.textContent?.match(/::artifact-template/g)).toHaveLength(2);
908 expect(container.textContent).not.toContain("Document template");
909 });
910});
911
912describe("ChatMarkdown headings", () => {
913 it("exposes headings below the host heading without changing their tags", async () => {
914 const container = await renderText("# Top\n\n## Section\n\n###### Fine print", {
915 headingLevelOffset: 3,
916 });
917 expect(
918 [...container.querySelectorAll("h1, h2, h6")].map((heading) => [
919 heading.tagName,
920 heading.getAttribute("aria-level"),
921 ]),
922 ).toEqual([
923 ["H1", "4"],
924 ["H2", "5"],
925 ["H6", "6"],
926 ]);
927 const flat = await renderText("# Top");
928 expect(flat.querySelector("h1")?.hasAttribute("aria-level")).toBe(false);
929 });
930
931 it("never gives two headings the same id, even when a suffix matches another heading", async () => {
932 const container = await renderText(
933 '## Setup\n\n## Setup\n\n## Setup-1\n\n<h2 id="install-1">Pinned</h2>\n\n## Install\n\n## Install',
934 { parseRawHtml: true },
935 );
936 expect([...container.querySelectorAll("h2")].map((heading) => heading.id)).toEqual([
937 "user-content-setup",
938 "user-content-setup-1",
939 "user-content-setup-1-1",
940 "user-content-install-1",
941 "user-content-install",
942 "user-content-install-2",
943 ]);
944 });
945});
946
947describe("ChatMarkdown Windows file links", () => {
948 const environmentId = EnvironmentId.make("env-windows");
949 const renderWindows = (text: string, parseRawHtml: boolean) =>
950 renderText(text, {
951 cwd: "C:/Users/shawn/project",
952 environmentId,
953 lineBreaks: !parseRawHtml,
954 parseRawHtml,
955 });
956 const fileHrefs = (container: HTMLElement) =>
957 [...container.querySelectorAll(".chat-markdown-file-link")].map((chip) =>
958 chip.getAttribute("href"),
959 );
960
961 it.each([
962 ["drive paths", "[Open](C:/Users/shawn/project/src/main.ts)"],
963 ["backslashes", String.raw`[Open](C:\Users\shawn\project\src\main.ts)`],
964 ["reference links", "[Open][source]\n\n[source]: C:/Users/shawn/project/src/main.ts"],
965 ])("resolves %s to the workspace file", async (_, text) => {
966 for (const parseRawHtml of [true, false]) {
967 const container = await renderWindows(text, parseRawHtml);
968 expect(fileHrefs(container)).toEqual(["C:/Users/shawn/project/src/main.ts"]);
969 }
970 });
971
972 it("keeps backslashes CommonMark would read as escapes", async () => {
973 for (const parseRawHtml of [true, false]) {
974 const container = await renderWindows(
975 String.raw`[settings](C:\Users\shawn\.claude\settings.json)`,
976 parseRawHtml,
977 );
978 expect(fileHrefs(container)).toEqual(["C:/Users/shawn/.claude/settings.json"]);
979 }
980 });
981
982 it("distinguishes same-named backslash paths but not the same file twice", async () => {
983 for (const parseRawHtml of [true, false]) {
984 const distinct = await renderWindows(
985 String.raw`[Source](C:\Users\shawn\project\src\index.ts) and [Test](C:\Users\shawn\project\test\index.ts)`,
986 parseRawHtml,
987 );
988 expect(distinct.textContent).toContain("index.ts · project/src");
989 expect(distinct.textContent).toContain("index.ts · project/test");
990 const path = String.raw`C:\Users\shawn\project\src\main.ts`;
991 const same = await renderWindows(`[Source](${path}) and \`${path}\``, parseRawHtml);
992 expect(fileHrefs(same)).toHaveLength(2);
993 expect(same.textContent).not.toContain("main.ts ·");
994 }
995 });
996
997 it("still rejects unsafe schemes", async () => {
998 for (const parseRawHtml of [true, false]) {
999 const container = await renderWindows(
1000 "[unsafe](javascript:alert(1)) and [unknown](d:alert(1))",
1001 parseRawHtml,
1002 );
1003 expect(container.innerHTML).not.toContain("javascript:");
1004 expect(container.innerHTML).not.toContain("d:alert");
1005 expect(fileHrefs(container)).toEqual([]);
1006 }
1007 });
1008});
1009
1010describe("ChatMarkdown in-page links", () => {
1011 it.each([true, false])(
1012 "scrolls a table-of-contents link to its heading without touching the URL (parseRawHtml=%s)",
1013 async (parseRawHtml) => {
1014 const scrollIntoView = vi
1015 .spyOn(HTMLElement.prototype, "scrollIntoView")
1016 .mockImplementation(() => {});
1017 const href = window.location.href;
1018 const container = await renderText(
1019 "- [Operating model](#1-operating-model)\n- [Missing](#nowhere)\n\n## 1. Operating model\n\n## 1. Operating model",
1020 { parseRawHtml },
1021 );
1022 const headings = [...container.querySelectorAll("h2")];
1023 expect(headings.map((heading) => heading.id)).toEqual([
1024 "user-content-1-operating-model",
1025 "user-content-1-operating-model-1",
1026 ]);
1027 const [tocLink, missingLink] = [...container.querySelectorAll("a")];
1028 await act(async () => tocLink!.click());
1029 expect(scrollIntoView.mock.contexts).toEqual([headings[0]]);
1030 await act(async () => missingLink!.click());
1031 expect(scrollIntoView).toHaveBeenCalledTimes(1);
1032 expect(window.location.href).toBe(href);
1033 },
1034 );
1035});
1036
1037describe("ChatMarkdown thread find", () => {
1038 function FindProbe(props: {
1039 container: HTMLElement;
1040 query: string;
1041 activeOccurrence?: number;
1042 children: ReactElement;
1043 }) {
1044 useThreadFindHighlights({
1045 container: props.container,
1046 query: props.query,
1047 activeRowId: "row",
1048 activeOccurrence: props.activeOccurrence ?? 0,
1049 onActiveRange: () => {},
1050 });
1051 return (
1052 <div data-timeline-row-id="row">
1053 <div data-thread-find-text>
1054 <MarkdownFindContext value={props.query !== ""}>{props.children}</MarkdownFindContext>
1055 </div>
1056 </div>
1057 );
1058 }
1059 const frame = () =>
1060 act(() => new Promise<void>((resolve) => requestAnimationFrame(() => resolve())));
1061 const activeHighlights = () =>
1062 [...(CSS.highlights.get("t3-thread-find-active") ?? [])].map((range) =>
1063 (range as Range).toString(),
1064 );
1065
1066 it("opens a disclosure only when find selects a match inside it", async () => {
1067 const container = document.body.appendChild(document.createElement("div"));
1068 const root = createRoot(container);
1069 roots.push(root);
1070 const markdown = (
1071 <ChatMarkdown
1072 cwd={undefined}
1073 text={[
1074 "Visible needle.",
1075 "<details><summary>Unrelated</summary><p>nothing here</p></details>",
1076 "<details><summary>Outer</summary><details><summary>Inner</summary><p>needle</p></details></details>",
1077 ].join("\n\n")}
1078 />
1079 );
1080 const show = (query: string, activeOccurrence: number) =>
1081 act(() =>
1082 root.render(
1083 <FindProbe container={container} query={query} activeOccurrence={activeOccurrence}>
1084 {markdown}
1085 </FindProbe>,
1086 ),
1087 );
1088 const openStates = () =>
1089 [...container.querySelectorAll<HTMLElement>("[data-markdown-details-open]")].map(
1090 (node) => node.dataset.markdownDetailsOpen,
1091 );
1092
1093 await show("", 0);
1094 expect(container.textContent).not.toContain("nothing here");
1095 await show("needle", 0);
1096 await frame();
1097 expect(openStates()).toEqual(["false", "false", "false"]);
1098 expect(container.textContent).toContain("nothing here");
1099 expect(activeHighlights()).toEqual(["needle"]);
1100 expect(CSS.highlights.get("t3-thread-find")?.size ?? 0).toBe(0);
1101
1102 await show("needle", 1);
1103 await frame();
1104 await frame();
1105 expect(openStates()).toEqual(["false", "true", "true"]);
1106 expect(CSS.highlights.get("t3-thread-find-active")?.size).toBe(1);
1107 });
1108
1109 it("keeps Mermaid diagrams rendered until find selects a match in their source", async () => {
1110 const container = document.body.appendChild(document.createElement("div"));
1111 const root = createRoot(container);
1112 roots.push(root);
1113 const diagram = "```mermaid\ngraph TD; Alpha-->Beta\n```";
1114 const show = (query: string) =>
1115 act(() =>
1116 root.render(
1117 <FindProbe container={container} query={query}>
1118 <ChatMarkdown cwd={undefined} text={`Needle first.\n\n${diagram}\n\n${diagram}`} />
1119 </FindProbe>,
1120 ),
1121 );
1122 const diagrams = () => container.querySelectorAll('svg[aria-label="Diagram"]').length;
1123
1124 await show("Needle");
1125 await frame();
1126 expect(diagrams()).toBe(2);
1127 await show("Alpha");
1128 await frame();
1129 await frame();
1130 expect(diagrams()).toBe(1);
1131 await vi.waitFor(() => expect(activeHighlights()).toEqual(["Alpha"]));
1132 });
1133
1134 it.each([
1135 {
1136 text: "```mermaid\ngraph TD; SearchSourceAlpha-->B\n```",
1137 query: "SearchSourceAlpha",
1138 count: 1,
1139 },
1140 {
1141 text: "★ Insight ─────\nfirst line\nsecond line",
1142 query: "first line second",
1143 count: 0,
1144 lineBreaks: true,
1145 },
1146 { text: '```ts title="src/needle.ts"\nconst a = 1;\n```', query: "needle", count: 0 },
1147 { text: "```weirdlang\nconst a = 1;\n```", query: "weirdlang", count: 0 },
1148 { text: "Use $test-t3-app now", query: "T3 App Testing", count: 1 },
1149 { text: "`/tmp/file.ts:42`", query: "file.ts · L42", count: 1, user: true, lineBreaks: true },
1150 { text: "> [!NOTE]\n> Searchable alert", query: "Searchable alert", count: 1 },
1151 {
1152 text: "<details><summary>Folded</summary><p>Hidden needle</p></details>",
1153 query: "Hidden needle",
1154 count: 1,
1155 },
1156 { text: ARTIFACT_TEMPLATE_DIRECTIVE, query: "Hello World", count: 1, withTemplate: true },
1157 {
1158 text: ARTIFACT_TEMPLATE_DIRECTIVE,
1159 query: "Document template",
1160 count: 1,
1161 withTemplate: true,
1162 },
1163 { text: ARTIFACT_TEMPLATE_DIRECTIVE, query: "World Document", count: 0, withTemplate: true },
1164 { text: ARTIFACT_TEMPLATE_DIRECTIVE, query: "Use template", count: 0, withTemplate: true },
1165 ])(
1166 "highlights the indexed occurrences of $query in $text",
1167 async ({ text, query, count, lineBreaks, user, withTemplate }) => {
1168 const skills = [{ name: "test-t3-app", displayName: "T3 App Testing" }];
1169 const container = document.body.appendChild(document.createElement("div"));
1170 const root = createRoot(container);
1171 roots.push(root);
1172 await act(() =>
1173 root.render(
1174 <FindProbe container={container} query={query}>
1175 <ChatMarkdown
1176 text={text}
1177 cwd={undefined}
1178 skills={skills}
1179 lineBreaks={lineBreaks ?? false}
1180 parseRawHtml={!user}
1181 onUseArtifactTemplate={withTemplate ? () => undefined : undefined}
1182 />
1183 </FindProbe>,
1184 ),
1185 );
1186 await frame();
1187 // Lazy blocks such as Mermaid can swap their source text after the first frame,
1188 // emptying a range for a moment, so wait for the highlights to settle.
1189 await vi.waitFor(() => {
1190 const ranges = [...CSS.highlights.values()].flatMap((value) => [...value]);
1191 expect(ranges.map((range) => (range as Range).toString())).toEqual(
1192 Array.from({ length: count }, () => query),
1193 );
1194 });
1195 const segments =
1196 searchableMessageSegments(
1197 { role: user ? "user" : "assistant", text, streaming: false },
1198 undefined,
1199 skills,
1200 ) ?? [];
1201 expect(
1202 segments.reduce((sum, segment) => sum + countThreadSearchOccurrences(segment, query), 0),
1203 ).toBe(count);
1204 },
1205 );
1206});
1207
1208describe("ChatMarkdown math", () => {
1209 const renderMath = async (
1210 text: string,
1211 options: Partial<Parameters<typeof ChatMarkdown>[0]> = {},
1212 ) => {
1213 settingsOverrides.mathRenderingEnabled = true;
1214 const { container: host } = await render(
1215 <ChatMarkdown cwd="/tmp/project" text={text} {...options} />,
1216 );
1217 host.setAttribute("data-assistant-citation-source", "assistant");
1218 await act(async () => {
1219 await import("./chat/MathTypeset");
1220 });
1221 return { host };
1222 };
1223
1224 it.each(["$x$", "$$x$$", "```math\nx\n```", "$\\notACommand{x}$"])(
1225 "keeps keyboard focus on the parent control in compact previews of %s",
1226 async (formula) => {
1227 settingsOverrides.mathRenderingEnabled = true;
1228 const { container } = await render(
1229 <>
1230 <button type="button">
1231 Preview <ChatMarkdown inline text={formula} cwd={undefined} />
1232 </button>
1233 <button type="button">After preview</button>
1234 </>,
1235 );
1236 await act(async () => {
1237 await import("./chat/MathTypeset");
1238 });
1239 const [preview, after] = container.querySelectorAll("button");
1240 preview!.focus();
1241 await act(() => userEvent.tab());
1242 expect(document.activeElement).toBe(after);
1243 if (formula.includes("notACommand")) {
1244 expect(page.getByRole("button", { name: /notACommand/ }).element()).toBe(preview);
1245 }
1246 },
1247 );
1248
1249 it("keeps message formulas reachable by keyboard", async () => {
1250 settingsOverrides.mathRenderingEnabled = true;
1251 const { container } = await render(
1252 <>
1253 <button type="button">Before equation</button>
1254 <ChatMarkdown text="$x$" cwd={undefined} />
1255 </>,
1256 );
1257 container.querySelector("button")!.focus();
1258 await act(() => userEvent.tab());
1259 expect(document.activeElement).toBe(
1260 container.querySelector('[aria-label="Scroll inline equation"]'),
1261 );
1262 });
1263
1264 it("renders table formulas and exports their TeX instead of duplicate glyph text", async () => {
1265 const rendered = await renderMath(
1266 "| Name | Formula |\n| --- | --- |\n| Norm | $|x|$ and \\(\\|y\\|\\) |\n| Price | $5 and $10 |",
1267 );
1268
1269 const table = rendered.host.querySelector("table")!;
1270 expect([...table.rows].map((row) => row.cells.length)).toEqual([2, 2, 2]);
1271 expect(table.querySelectorAll(".katex")).toHaveLength(2);
1272 const norm = table.querySelectorAll(".katex")[1]!;
1273 expect([...norm.querySelectorAll(".katex-mathml mi")].map((node) => node.textContent)).toEqual([
1274 "∥",
1275 "y",
1276 "∥",
1277 ]);
1278 expect(serializeTableElementToCsv(table)).toBe(
1279 "Name,Formula\nNorm,\\(|x|\\) and \\(\\|y\\|\\)\nPrice,$5 and $10",
1280 );
1281 const glyph = table.querySelector(".katex-mathml mi")!.firstChild!;
1282 const range = document.createRange();
1283 range.setStart(glyph, 0);
1284 range.setEnd(glyph, 1);
1285 const selection = window.getSelection()!;
1286 selection.removeAllRanges();
1287 selection.addRange(range);
1288 const payload = chatMarkdownClipboardPayload(selection)!;
1289 expect(payload.text).toBe("\\(|x|\\)");
1290 expect(payload.html).toContain("\\(|x|\\)");
1291 expect(payload.html).not.toContain("katex");
1292 expect(captureAssistantTextSelection(rendered.host, selection)?.selector.text).toBe(
1293 "\\(|x|\\)",
1294 );
1295 });
1296
1297 it("renders explicit math fences and keeps unfinished streamed fences readable", async () => {
1298 const rendered = await renderMath("```math\nx_i^2\n```\n\n`$literal$`\n\n$unfinished");
1299
1300 expect(rendered.host.querySelectorAll(".katex")).toHaveLength(1);
1301 expect(rendered.host.textContent).toContain("$literal$");
1302 expect(rendered.host.textContent).toContain("$unfinished");
1303
1304 const streamed = await renderMath("```math\nx_i^2", { isStreaming: true });
1305
1306 expect(streamed.host.querySelector(".katex")).toBeNull();
1307 expect(streamed.host.textContent).toContain("x_i^2");
1308 });
1309
1310 it.each(["$$\nx^2\n", "\\[\nx^2\n"])(
1311 "keeps unfinished display %s and following prose readable while streaming",
1312 async (source) => {
1313 for (const text of [source, `${source}\nFollowing prose.`]) {
1314 const { host } = await renderMath(text, { isStreaming: true });
1315 expect(host.querySelector(".katex")).toBeNull();
1316 expect(host.querySelector("[data-markdown-math]")).toBeNull();
1317 expect(host.textContent).toContain("x^2");
1318 if (text.includes("Following prose."))
1319 expect(host.textContent).toContain("Following prose.");
1320 }
1321 },
1322 );
1323
1324 it.each(["$$x^2$$", "$$\nx^2\n$$", "\\[\nx^2\n\\]", "```math\nx^2\n```"])(
1325 "renders completed %s while the response is streaming",
1326 async (source) => {
1327 const { host } = await renderMath(source, { isStreaming: true });
1328 expect(host.querySelectorAll(".katex")).toHaveLength(1);
1329 expect(host.querySelector('[data-markdown-math="display"]')).not.toBeNull();
1330 },
1331 );
1332
1333 it("shows unsupported TeX as source and keeps active TeX commands inert", async () => {
1334 const rendered = await renderMath(
1335 "\\(\\notACommand{x}\\) and \\(\\href{https://example.com}{x}\\)",
1336 );
1337
1338 expect(rendered.host.textContent).toContain("\\(\\notACommand{x}\\)");
1339 expect(rendered.host.querySelector('a[href="https://example.com"]')).toBeNull();
1340 });
1341
1342 it("typesets only when enabled, keeping prices and task offsets intact", async () => {
1343 const text = "Area $\\pi r^2$ costs $5 and $10.\n\n\\[\nE = mc^2\n\\]\n\n- [ ] check \\(x\\)";
1344 const off = await renderText(text);
1345 expect(off.querySelector("[data-markdown-math]")).toBeNull();
1346 const html = await renderText('<code class="language-math math-inline">x</code>');
1347 expect(html.querySelector("[data-markdown-math]")).toBeNull();
1348 for (const parseRawHtml of [true, false]) {
1349 let editedText = text;
1350 const { host } = await renderMath(text, {
1351 parseRawHtml,
1352 onTaskListChange: ({ markerOffset, checked }) => {
1353 editedText = setMarkdownTaskChecked(text, markerOffset, checked);
1354 },
1355 });
1356 expect(
1357 [...host.querySelectorAll("[data-markdown-math]")].map((node) =>
1358 node.getAttribute("data-markdown-copy"),
1359 ),
1360 ).toEqual(["\\(\\pi r^2\\)", "\\[\nE = mc^2\n\\]\n\n", "\\(x\\)"]);
1361 await act(() => host.querySelector<HTMLInputElement>('input[type="checkbox"]')!.click());
1362 expect(editedText).toBe(text.replace("- [ ]", "- [x]"));
1363 }
1364 const { host } = await renderMath("- intro\n\n $$\n x^2\n $$");
1365 expect(
1366 [...host.querySelectorAll("[data-markdown-math]")].map((node) =>
1367 node.getAttribute("data-markdown-copy"),
1368 ),
1369 ).toEqual(["\\[\nx^2\n\\]\n\n"]);
1370 });
1371});