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