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