Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

ChatMarkdown.browser.test.tsx

772 lines29.6 KB

1import { MISSING_FILE_ACCESS_MESSAGE } from "@t3tools/client-runtime/state/assets";
2import { EnvironmentId, ThreadId } from "@t3tools/contracts";
3import { AsyncResult } from "effect/reactivity";
4import { type ReactElement } from "react";
5import { describe, expect, it, vi } from "vite-plus/test";
6import { page, userEvent } from "vite-plus/test/browser";
7​
8import { act, render } from "../../test/render";
9import "../index.css";
10​
11import { filesystemEnvironment } from "../state/filesystem";
12import { useRightPanelStore } from "../rightPanelStore";
13import { remarkEnableOrderedListNumbers } from "@t3tools/shared/markdownPipeline";
14import { setMarkdownTaskChecked } from "@t3tools/shared/markdownTaskList";
15import { HostImageUrlContext } from "./chat/hostImageUrl";
16import { getSyntaxHighlighterPromise } from "~/lib/syntaxHighlighting";
17​
18const { workspaceSearch, filesystemMetadata } = vi.hoisted(() => ({
19 workspaceSearch: vi.fn(),
20 filesystemMetadata: vi.fn(),
21}));
22const parsedSources = vi.hoisted(() => [] as string[]);
23vi.mock(import("mdast-util-from-markdown"), async (original) => {
24 const actual = await original();
25 return {
26 ...actual,
27 fromMarkdown: ((source: string, ...rest: never[]) => {
28 parsedSources.push(String(source));
29 return (actual.fromMarkdown as (...args: unknown[]) => unknown)(source, ...rest);
30 }) as typeof actual.fromMarkdown,
31 };
32});
33​
34vi.mock(import("../state/use-atom-query-runner"), async (original) => ({
35 ...(await original()),
36 useAtomQueryRunner: ((family: unknown) =>
37 family === filesystemEnvironment.getMetadata ? filesystemMetadata : workspaceSearch) as never,
38}));
39​
40// Atoms derived from the server config run in the real registry over a missing config.
41vi.mock(import("../state/server"), async (original) => {
42 const actual = await original();
43 const { Atom } = await import("effect/reactivity");
44 const noConfig = Atom.make(null);
45 const modelsConfig = Atom.make({
46 environment: { platform: { os: "darwin" } },
47 availableEditors: [],
48 settings: { providerInstances: {} },
49 providers: [
50 {
51 instanceId: "codex",
52 driver: "codex",
53 displayName: "Codex",
54 models: [{ slug: "gpt-6.1", name: "GPT-6.1", isCustom: false, capabilities: {} }],
55 },
56 ],
57 });
58 return {
59 ...actual,
60 serverEnvironment: {
61 ...actual.serverEnvironment,
62 configValueAtom: ((environmentId: string) =>
63 environmentId === "models" ? modelsConfig : noConfig) as never,
64 },
65 };
66});
67vi.mock(import("../state/session"), async (original) => {
68 const { AuthStandardClientScopes } = await import("@t3tools/contracts");
69 const granted = new Set<string>(AuthStandardClientScopes);
70 const hasScope = (environmentId: unknown, scope: string) =>
71 environmentId !== null && granted.has(scope);
72 return {
73 ...(await original()),
74 useEnvironmentScope: hasScope as never,
75 readEnvironmentScope: hasScope as never,
76 };
77});
78const deniedEnvironmentId = vi.hoisted(() => "denied-environment");
79vi.mock(import("../state/filesystem"), async (original) => {
80 const actual = await original();
81 return {
82 ...actual,
83 useFilesystemReadAccess: ((environmentId: EnvironmentId | null) =>
84 environmentId === deniedEnvironmentId
85 ? { canReadFiles: false, isPending: false, error: null }
86 : actual.useFilesystemReadAccess(environmentId)) as never,
87 };
88});
89vi.mock(import("../remoteOpen"), async (original) => ({
90 ...(await original()),
91 useRemoteOpenResolution: () => ({ state: { mode: "local-exec" }, isResolved: true }) as never,
92}));
93const { renderDiagram } = vi.hoisted(() => ({
94 renderDiagram: vi.fn<(source: string) => Promise<string> | undefined>(),
95}));
96// Control rendering latency without running Mermaid layout.
97vi.mock(import("./chat/MermaidDiagram"), async (original) => {
98 const { use } = await import("react");
99 return {
100 ...(await original()),
101 MermaidDiagram: ({ source }: { source: string }) => {
102 const pending = renderDiagram(source);
103 return <svg role="img" aria-label={pending ? use(pending) : "Diagram"} />;
104 },
105 };
106});
107​
108const appearance = vi.hoisted(() => ({
109 value: "light" as "light" | "dark",
110 listeners: new Set<() => void>(),
111}));
112vi.mock(import("../hooks/useTheme"), async (original) => {
113 const { useSyncExternalStore } = await import("react");
114 const subscribe = (listener: () => void) => {
115 appearance.listeners.add(listener);
116 return () => appearance.listeners.delete(listener);
117 };
118 return {
119 ...(await original()),
120 useRenderedAppearance: () => useSyncExternalStore(subscribe, () => appearance.value),
121 };
122});
123​
124const settingsOverrides = vi.hoisted(() => ({ mathRenderingEnabled: false }));
125vi.mock(import("../hooks/useSettings"), async (original) => {
126 const actual = await original();
127 type Settings = ReturnType<typeof actual.getClientSettings>;
128 function useClientSettings<T = Settings>(select?: (settings: Settings) => T): T {
129 const settings = { ...actual.getClientSettings(), ...settingsOverrides };
130 return select ? select(settings) : (settings as T);
131 }
132 return { ...actual, useClientSettings };
133});
134​
135import ChatMarkdown from "./ChatMarkdown";
136import { chatMarkdownClipboardPayload } from "../markdown-clipboard";
137import { AudioPreview } from "./files/AudioPreview";
138​
139it("keeps compact audio playback loaded across signed URL renewals", async () => {
140 const original =
141 "data:audio/wav;base64,UklGRiUAAABXQVZFZm10IBAAAAABAAEAQB8AAEAfAAABAAgAZGF0YQEAAACA";
142 const renewed = `${original}#renewed`;
143 const preview = (src: string, revision = "clip-v1") => (
144 <AudioPreview compact name="clip.wav" src={src} revision={revision} />
145 );
146 await using screen = await render(preview(original));
147 const audio = screen.container.querySelector("audio")!;
148 await act(() => {
149 audio.dispatchEvent(new Event("loadedmetadata"));
150 audio.dispatchEvent(new Event("play"));
151 });
152 await screen.rerender(preview(renewed));
153 expect(screen.container.querySelector("audio")).toBe(audio);
154 expect(audio.getAttribute("src")).toBe(original);
155 await expect.element(screen.getByRole("button", { name: "Pause clip.wav" })).toBeEnabled();
156 await screen.rerender(preview(renewed, "clip-v2"));
157 expect(screen.container.querySelector("audio")).not.toBe(audio);
158 expect(screen.container.querySelector("audio")?.getAttribute("src")).toBe(renewed);
159});
160​
161function setup() {
162 appearance.value = "light";
163 parsedSources.length = 0;
164 settingsOverrides.mathRenderingEnabled = false;
165 renderDiagram.mockReset();
166 workspaceSearch.mockReset().mockResolvedValue(AsyncResult.success({ entries: [] }));
167 filesystemMetadata.mockReset().mockResolvedValue(AsyncResult.success({ entries: [null] }));
169​
170function renderText(text: string, props: Partial<Parameters<typeof ChatMarkdown>[0]> = {}) {
171 return render(<ChatMarkdown cwd="/tmp/project" text={text} {...props} />);
173​
174function buttonsLabelled(container: HTMLElement, label: string) {
175 return [...container.querySelectorAll<HTMLButtonElement>("button")].filter(
176 (button) => button.getAttribute("aria-label") === label,
177 );
179​
180const SOURCE_NUMBER_PLUGINS = [remarkEnableOrderedListNumbers];
181​
182it("keeps decimal markers in nested user lists while documents keep their counter styles", async () => {
183 setup();
184 const text = "1. Outer\n 1. Nested\n 7. Skipped\n 1. Deeper\n 4. Fourth";
185 await using screen = await render(
186 <div className="grid grid-cols-2 gap-8 p-8">
187 <section>
188 <h2>User message</h2>
189 <ChatMarkdown
190 cwd={undefined}
191 text={text}
192 className="user-message-markdown"
193 extraRemarkPlugins={SOURCE_NUMBER_PLUGINS}
194 />
195 </section>
196 <section>
197 <h2>Markdown preview</h2>
198 <ChatMarkdown cwd={undefined} text={text} />
199 </section>
200 </div>,
201 );
202 await expect.element(screen.getByText("User message", { exact: true })).toBeVisible();
203 const [message, preview] = screen.container.querySelectorAll(".chat-markdown");
204 expect(
205 [...message!.querySelectorAll("ol")].map((list) => getComputedStyle(list).listStyleType),
206 ).toEqual(["decimal", "decimal", "decimal"]);
207 expect(
208 [...preview!.querySelectorAll("ol")].map((list) => getComputedStyle(list).listStyleType),
209 ).toEqual(["decimal", "lower-alpha", "lower-roman"]);
210});
211​
212it("shows unavailable audio when a workspace embed has no thread", async () => {
213 setup();
214 await using screen = await renderText("![recording](clip.wav)");
215 expect(screen.container.textContent).toContain("Audio unavailable");
216 expect(screen.container.textContent).not.toContain("Loading audio");
217 expect(screen.container.querySelector("audio")).toBeNull();
218});
219​
220it("loads a host image through the page's own route when there is no environment", async () => {
221 setup();
222 const pixel =
223 "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=";
224 const hostImageUrl = vi.fn((_path: string) => pixel);
225 await using screen = await render(
226 <HostImageUrlContext value={hostImageUrl}>
227 <ChatMarkdown cwd={undefined} text="![Shot](</work/my shot.png>)" />
228 </HostImageUrlContext>,
229 );
230 await expect.element(screen.getByAltText("Shot")).toHaveAttribute("src", pixel);
231 expect(new Set(hostImageUrl.mock.calls.map(([path]) => path))).toEqual(
232 new Set(["/work/my shot.png"]),
233 );
234});
235​
236it("loads the <picture> source for the current theme through the image route", async () => {
237 setup();
238 const pixel =
239 "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=";
240 const hostImageUrl = (path: string) => `${pixel}#${path}`;
241 await using screen = await render(
242 <HostImageUrlContext value={hostImageUrl}>
243 <ChatMarkdown
244 cwd={undefined}
245 text={
246 '<picture><source media="(prefers-color-scheme: dark)" srcset="/work/dark.png"><img src="/work/light.png" alt="Shot"></picture>'
247 }
248 />
249 </HostImageUrlContext>,
250 );
251 await expect
252 .element(screen.getByAltText("Shot"))
253 .toHaveAttribute("src", `${pixel}#/work/light.png`);
254​
255 await act(() => {
256 appearance.value = "dark";
257 for (const listener of appearance.listeners) listener();
258 });
259 await expect
260 .element(screen.getByAltText("Shot"))
261 .toHaveAttribute("src", `${pixel}#/work/dark.png`);
262});
263​
264it("sizes a raw HTML image by width and height written with px units", async () => {
265 setup();
266 const largeImage = `data:image/svg+xml,${encodeURIComponent(
267 '<svg xmlns="http://www.w3.org/2000/svg" width="200" height="200"/>',
268 )}`;
269 await using screen = await render(
270 <HostImageUrlContext value={() => largeImage}>
271 <ChatMarkdown
272 cwd={undefined}
273 parseRawHtml
274 text={
275 '### PR Review in progress <img src="/work/spinner.gif" alt="spinner" width="14px" height="7px" />'
276 }
277 />
278 </HostImageUrlContext>,
279 );
280 const image = screen.getByAltText("spinner");
281 await expect.element(image).toHaveAttribute("src", largeImage);
282 const element = image.element() as HTMLImageElement;
283 await element.decode();
284 const { width, height } = element.getBoundingClientRect();
285 expect({ width, height }).toEqual({ width: 14, height: 7 });
286});
287​
288it("reuses the parse of a streaming reply's finished blocks when it remounts", async () => {
289 setup();
290 const message = (
291 <ChatMarkdown cwd="/tmp/project" text={"Finished block\n\nStill growing"} isStreaming />
292 );
293 {
294 await using _first = await render(message);
295 }
296 await using screen = await render(message);
297 await expect.element(screen.getByText("Still growing")).toBeVisible();
298 expect(parsedSources.filter((source) => source.includes("Finished block"))).toHaveLength(1);
299});
300​
301it("reuses the parse of a remounted message that has stable extra plugins", async () => {
302 setup();
303 const parsed = vi.fn();
304 const countingPlugins = [() => () => void parsed()];
305 const message = (
306 <ChatMarkdown cwd="/tmp/project" text="Cached text" extraRemarkPlugins={countingPlugins} />
307 );
308 {
309 await using _first = await render(message);
310 }
311 await using screen = await render(message);
312 await expect.element(screen.getByText("Cached text")).toBeVisible();
313 expect(parsed).toHaveBeenCalledTimes(1);
314});
315​
316it("highlights a code block's own source when an earlier block of the same length was cached", async () => {
317 setup();
318 const highlightedText = (container: HTMLElement) =>
319 container.querySelector(".chat-markdown-shiki")?.textContent?.trim();
320 // These two lines share a 32-bit FNV-1a hash and a length.
321 const first = 'const commitSha = "f36a6d8fe0aa";';
322 const second = 'const commitSha = "cb06f8d135b3";';
323 // The block suspends until the shared highlighter loads, which can outlast vi.waitFor on a busy runner.
324 await getSyntaxHighlighterPromise("ts");
325 {
326 await using screen = await renderText(`\`\`\`ts\n${first}\n\`\`\``);
327 await vi.waitFor(() => expect(highlightedText(screen.container)).toBe(first));
328 }
329 await using screen = await renderText(`\`\`\`ts\n${second}\n\`\`\``);
330 await vi.waitFor(() => expect(highlightedText(screen.container)).toBe(second));
331});
332​
333describe("ChatMarkdown favicon privacy", () => {
334 it("suppresses private link images while preserving public links across updates", async () => {
335 setup();
336 const markdown = (url: string) => <ChatMarkdown cwd="/tmp/project" text={`[Link](${url})`} />;
337 await using screen = await render(markdown("https://example.com"));
338 const { container, rerender } = screen;
339 expect([...container.querySelectorAll("img")].map((image) => image.src)).toEqual([
340 "https://www.google.com/s2/favicons?domain=example.com&sz=32",
341 ]);
342 for (const url of ["http://192.168.1.10:8080", "http://localhost:3000", "http://home.arpa"]) {
343 await rerender(markdown(url));
344 expect(container.querySelectorAll("img")).toHaveLength(0);
345 }
346 await rerender(markdown("https://example.com"));
347 expect(container.querySelectorAll("img")).toHaveLength(1);
348 await rerender(markdown("https://github.com/pingdotgg/t3code/pull/1"));
349 expect(container.querySelectorAll("img")).toHaveLength(0);
350 expect(container.querySelector("a svg")).not.toBeNull();
351 });
352});
353​
354describe("ChatMarkdown external link labels", () => {
355 it("keeps a leading emoji whole", async () => {
356 setup();
357 await using screen = await render(
358 <ChatMarkdown cwd="/tmp/project" text="[😀 Read the documentation](https://example.com)" />,
359 );
360 await vi.waitFor(() => {
361 const link = screen.container.querySelector("a");
362 expect(link?.textContent).toContain("😀 Read");
363 const walker = document.createTreeWalker(link!, NodeFilter.SHOW_TEXT);
364 const textNodes: string[] = [];
365 while (walker.nextNode()) textNodes.push(walker.currentNode.nodeValue ?? "");
366 expect(textNodes.filter((node) => /\p{Surrogate}/u.test(node))).toEqual([]);
367 });
368 });
369});
370​
371describe("ChatMarkdown streaming", () => {
372 it("runs only a complete single-line shell block after a click", async () => {
373 setup();
374 const onRunShellCommand = vi.fn();
375 const message = (text: string, isStreaming = false) => (
376 <ChatMarkdown
377 cwd="/tmp/project"
378 text={text}
379 isStreaming={isStreaming}
380 onRunShellCommand={onRunShellCommand}
381 />
382 );
383 await using screen = await render(message("```bash\necho hello\n```", true));
384 const { container, rerender } = screen;
385 const runButtons = () => buttonsLabelled(container, "Run in terminal");
386 expect(runButtons()).toHaveLength(0);
387​
388 await rerender(message("```bash\necho hello\n```"));
389 await act(async () => runButtons()[0]!.click());
390 expect(onRunShellCommand).toHaveBeenCalledExactlyOnceWith("echo hello");
391​
392 for (const text of [
393 "~~~bash\necho tilde\n~~~",
394 "> ```bash\n> echo quote\n> ```",
395 "````bash\necho four\n````",
396 "- Command\n\n ```bash\n echo list\n ```",
397 "```bash\r\necho crlf\r\n```\r",
398 ]) {
399 await rerender(message(text));
400 expect(runButtons()).toHaveLength(1);
401 }
402​
403 for (const text of [
404 "```bash\necho one\necho two\n```",
405 "```typescript\necho hello\n```",
406 "```bash\n\n```",
407 "```bash\necho hello\n\n```",
408 "```bash\necho hello\\\n```",
409 "```bash\necho safe \u202e#\n```",
410 "```bash\necho incomplete",
411 "~~~bash\necho incomplete",
412 "````bash\necho incomplete\n```",
413 '<pre><code class="language-bash">echo html</code></pre>',
414 ]) {
415 await rerender(message(text));
416 expect(runButtons()).toHaveLength(0);
417 }
418 });
419​
420 it("edits the current task text and marker after reusing a renderer", async () => {
421 setup();
422 let editedText: string | undefined;
423 let rerender: (next: ReactElement) => Promise<void> = async () => {};
424 const message = (text: string): ReactElement => (
425 <ChatMarkdown
426 cwd="/tmp/project"
427 text={text}
428 onTaskListChange={({ markerOffset, checked }) => {
429 editedText = setMarkdownTaskChecked(text, markerOffset, checked);
430 void rerender(message(editedText));
431 }}
432 />
433 );
434 await using rendered = await render(message("- [ ] First\n- [ ] Second"));
435 rerender = rendered.rerender;
436 const { container } = rendered;
437 const checkboxes = () => container.querySelectorAll<HTMLInputElement>('input[type="checkbox"]');
438 const original = checkboxes()[1]!;
439 await rerender(message("- [ ] A longer first task\n- [ ] Second"));
440 expect(checkboxes()[1]).toBe(original);
441​
442 await act(async () => original.click());
443 expect(editedText).toBe("- [ ] A longer first task\n- [x] Second");
444 await vi.waitFor(() => expect(checkboxes()[1]!.checked).toBe(true));
445 await rerender(message("- [ ] A longer first task\n- [ ] Second"));
446 expect(checkboxes()[1]).toBe(original);
447 expect(checkboxes()[1]!.checked).toBe(false);
448 });
449​
450 it.each([
451 ["read-only", undefined],
452 ["editable", () => {}],
453 ])(
454 "unchecks the remaining %s task when the checked row above it is removed",
455 async (_, onTaskListChange) => {
456 setup();
457 const message = (text: string) => (
458 <ChatMarkdown cwd="/tmp/project" text={text} onTaskListChange={onTaskListChange} />
459 );
460 await using screen = await render(message("- [x] Completed item\n- [ ] Pending item"));
461 await screen.rerender(message("- [ ] Pending item"));
462 const checkboxes =
463 screen.container.querySelectorAll<HTMLInputElement>('input[type="checkbox"]');
464 expect(checkboxes).toHaveLength(1);
465 expect(checkboxes[0]!.checked).toBe(false);
466 },
467 );
468});
469​
470describe("ChatMarkdown workspace file opens", () => {
471 const threadRef = {
472 environmentId: EnvironmentId.make("workspace"),
473 threadId: ThreadId.make("thread"),
474 };
475​
476 it("keeps a newer absolute file open when an earlier repo-relative lookup finishes", async () => {
477 setup();
478 const result = AsyncResult.success({
479 entries: [{ path: "notes/a.md", kind: "file" }],
480 truncated: false,
481 });
482 let resolvePending!: (value: typeof result) => void;
483 const pending = new Promise<typeof result>((resolve) => {
484 resolvePending = resolve;
485 });
486 workspaceSearch.mockReturnValueOnce(pending);
487 using openFile = vi
488 .spyOn(useRightPanelStore.getState(), "openFile")
489 .mockImplementation(() => {});
490 await using screen = await renderText(
491 "[Notes](physics/notes/a.md) and [Other](/elsewhere/b.md:9)",
492 {
493 cwd: "/school/physics",
494 threadRef,
495 },
496 );
497 const { container } = screen;
498 const [notes, other] = container.querySelectorAll("a");
499 await act(async () => notes!.click());
500 expect(workspaceSearch).toHaveBeenCalledOnce();
501 expect(openFile).not.toHaveBeenCalled();
502​
503 await act(async () => other!.click());
504 await act(async () => resolvePending(result));
505​
506 expect(openFile).toHaveBeenCalledExactlyOnceWith(threadRef, "/elsewhere/b.md", 9);
507 expect(workspaceSearch).toHaveBeenCalledOnce();
508 });
509});
510​
511describe("ChatMarkdown skill chips", () => {
512 it("shows the skill's details and opens its instructions", async () => {
513 setup();
514 const threadRef = {
515 environmentId: EnvironmentId.make("workspace"),
516 threadId: ThreadId.make("thread"),
517 };
518 await using screen = await renderText("Run $review now", {
519 threadRef,
520 skills: [
521 {
522 name: "review",
523 displayName: "Review",
524 description: "Reviews the current branch.",
525 path: "/skills/review/SKILL.md",
526 enabled: true,
527 },
528 ],
529 });
530 using openFile = vi
531 .spyOn(useRightPanelStore.getState(), "openFile")
532 .mockImplementation(() => {});
533​
534 await userEvent.click(screen.getByRole("button", { name: "Skill Review. Show details" }));
535 await expect.element(page.getByText("Reviews the current branch.")).toBeVisible();
536 await userEvent.click(page.getByRole("button", { name: "View instructions" }));
537​
538 expect(openFile).toHaveBeenCalledExactlyOnceWith(threadRef, "/skills/review/SKILL.md");
539 });
540​
541 it("names a mentioned model as its provider does, without a thread", async () => {
542 setup();
543 await using screen = await renderText("Ask (model:codex/gpt-6.1), not model:openai/gpt-4o.", {
544 environmentId: EnvironmentId.make("models"),
545 });
546​
547 await expect
548 .element(screen.getByRole("button", { name: "Model GPT-6.1. Show details" }))
549 .toBeVisible();
550 expect(buttonsLabelled(screen.container, "Model gpt-4o. Show details")).toEqual([]);
551 expect(screen.container.textContent).toBe("Ask (GPT-6.1), not model:openai/gpt-4o.");
552 });
553});
554​
555describe("ChatMarkdown headings", () => {
556 it("keeps insight streaming, reference links, and heading anchors in one message", async () => {
557 setup();
558 const rule = "─".repeat(20);
559 const text = `## Setup\n\nBefore [source][src].\n\n★ Insight ${rule}\nA **streaming** note.`;
560 const message = (text: string, isStreaming: boolean) => (
561 <ChatMarkdown
562 cwd={undefined}
563 text={text}
564 renderInsights
565 lineBreaks
566 isStreaming={isStreaming}
567 />
568 );
569 await using screen = await render(message(text, true));
570 await expect.element(screen.getByRole("note")).toHaveTextContent("Insight A streaming note.");
571 await screen.rerender(
572 message(
573 `${text}\n${rule}\n\n## Setup\n\nAfter [source][src].\n\n[src]:\n https://example.com`,
574 false,
575 ),
576 );
577 await expect.element(screen.getByRole("note")).toHaveTextContent("Insight A streaming note.");
578 expect([...screen.container.querySelectorAll("h2")].map((heading) => heading.id)).toEqual([
579 "user-content-setup",
580 "user-content-setup-1",
581 ]);
582 expect(
583 [...screen.container.querySelectorAll("a")].filter(
584 (link) => link.href === "https://example.com/",
585 ),
586 ).toHaveLength(2);
587 await expect.element(screen.getByRole("note")).not.toHaveTextContent("After");
588 });
589​
590 it("never gives two headings the same id, even when a suffix matches another heading", async () => {
591 setup();
592 await using screen = await renderText(
593 '## Setup\n\n## Setup\n\n## Setup-1\n\n<h2 id="install-1">Pinned</h2>\n\n## Install\n\n## Install',
594 { parseRawHtml: true },
595 );
596 const { container } = screen;
597 expect([...container.querySelectorAll("h2")].map((heading) => heading.id)).toEqual([
598 "user-content-setup",
599 "user-content-setup-1",
600 "user-content-setup-1-1",
601 "user-content-install-1",
602 "user-content-install",
603 "user-content-install-2",
604 ]);
605 });
606});
607​
608describe("ChatMarkdown inline code selection", () => {
609 it("selects the whole inline code span on double-click, but only a word in fenced code", async () => {
610 setup();
611 await using screen = await renderText(
612 "Run `migration-gate --dry-run` first.\n\n```txt\nfenced-block word\n```",
613 );
614 await userEvent.dblClick(screen.getByText("migration-gate --dry-run"));
615 expect(window.getSelection()?.toString()).toBe("migration-gate --dry-run");
616​
617 window.getSelection()?.removeAllRanges();
618 const fenced = screen.container.querySelector("pre code")!;
619 await userEvent.dblClick(fenced, { position: { x: 4, y: 4 } });
620 expect(window.getSelection()?.toString()).toBe("fenced");
621 });
622​
623 it("selects the whole line on triple-click beside a favicon link or a file chip", async () => {
624 setup();
625 await using screen = await renderText(
626 "Before [docs](https://example.com/docs) after words\n\nBefore [App.tsx](/tmp/project/src/App.tsx) after words",
627 );
628 const tripleClickWord = async (paragraph: HTMLElement, word: string) => {
629 const text = [...paragraph.childNodes].find((node) => node.textContent?.includes(word))!;
630 const range = document.createRange();
631 range.setStart(text, text.textContent!.indexOf(word));
632 range.setEnd(text, text.textContent!.indexOf(word) + word.length);
633 const wordBox = range.getBoundingClientRect();
634 const paragraphBox = paragraph.getBoundingClientRect();
635 window.getSelection()?.removeAllRanges();
636 await userEvent.tripleClick(paragraph, {
637 position: {
638 x: wordBox.left - paragraphBox.left + wordBox.width / 2,
639 y: wordBox.top - paragraphBox.top + wordBox.height / 2,
640 },
641 });
642 return window.getSelection()?.toString().trim();
643 };
644​
645 const paragraphs = screen.container.querySelectorAll("p");
646 expect(paragraphs).toHaveLength(2);
647 const selections = [];
648 const lines = [];
649 for (const paragraph of paragraphs) {
650 lines.push(paragraph.textContent?.trim(), paragraph.textContent?.trim());
651 selections.push(
652 await tripleClickWord(paragraph, "Before"),
653 await tripleClickWord(paragraph, "after"),
654 );
655 }
656 expect(selections).toEqual(lines);
657 });
658});
659​
660describe("ChatMarkdown alert copy", () => {
661 it("copies a fully selected callout as alert Markdown and a partial one as text", async () => {
662 setup();
663 await using screen = await renderText("> [!WARNING]\n> Back up first.");
664 const [label, body] = screen.container.querySelectorAll('[role="note"] > p');
665 const select = (startNode: Node, endNode: Node, endOffset: number) => {
666 const range = document.createRange();
667 range.setStart(startNode, 0);
668 range.setEnd(endNode, endOffset);
669 const selection = window.getSelection()!;
670 selection.removeAllRanges();
671 selection.addRange(range);
672 return chatMarkdownClipboardPayload(selection)?.text;
673 };
674 const labelText = label!.lastChild!;
675 const bodyText = body!.firstChild!;
676​
677 expect(select(labelText, bodyText, bodyText.textContent!.length)).toBe(
678 "> [!WARNING]\n> Back up first.",
679 );
680 expect(select(labelText, bodyText, "Back up".length)).toBe("Warning\n\nBack up");
681 });
682});
683​
684describe("ChatMarkdown file chip tooltips", () => {
685 it("wraps a long path so its file name stays inside the tooltip", async () => {
686 setup();
687 const path =
688 "/tmp/project/packages/client-runtime/src/state/generated/environment-connection-handshake-retry-policy-fixtures.ts";
689 await using screen = await renderText(`See [the fixtures](${path}).`);
690​
691 await userEvent.hover(screen.container.querySelector(".chat-markdown-file-link")!);
692 const tooltip = page.getByText(path);
693 await expect.element(tooltip).toBeVisible();
694​
695 const popup = tooltip.element().closest("[data-side]")!;
696 const pathEnd = document.createRange();
697 pathEnd.selectNodeContents(tooltip.element());
698 expect(pathEnd.getBoundingClientRect().right).toBeLessThanOrEqual(
699 popup.getBoundingClientRect().right,
700 );
701 });
702});
703​
704describe("ChatMarkdown editor deep links", () => {
705 const hrefs = (container: HTMLElement) =>
706 [...container.querySelectorAll("a")].map((link) => link.getAttribute("href"));
707​
708 it("keeps local editor file links", async () => {
709 setup();
710 await using screen = await renderText(
711 "[file.md line 3](cursor://file/Users/me/repo/file.md:3) and [same](vscode://file/Users/me/repo/file.md:3:7)",
712 );
713 expect(hrefs(screen.container)).toEqual([
714 "cursor://file/Users/me/repo/file.md:3",
715 "vscode://file/Users/me/repo/file.md:3:7",
716 ]);
717 });
718​
719 it("still drops other editor links and unknown schemes", async () => {
720 setup();
721 await using screen = await renderText(
722 "[prompt](cursor://anysphere.cursor-deeplink/prompt?text=hi) [user](cursor://me@file/Users/me/file.md) [unknown](foo://file/Users/me/file.md)",
723 );
724 expect(screen.container.innerHTML).not.toContain("://");
725 expect(hrefs(screen.container).filter(Boolean)).toEqual([]);
726 });
727});
728​
729describe("ChatMarkdown Windows file links", () => {
730 const environmentId = EnvironmentId.make("env-windows");
731 const renderWindows = (text: string, parseRawHtml: boolean) =>
732 renderText(text, {
733 cwd: "C:/Users/shawn/project",
734 environmentId,
735 lineBreaks: !parseRawHtml,
736 parseRawHtml,
737 });
738 const fileHrefs = (container: HTMLElement) =>
739 [...container.querySelectorAll(".chat-markdown-file-link")].map((chip) =>
740 chip.getAttribute("href"),
741 );
742​
743 it("still rejects unsafe schemes", async () => {
744 setup();
745 for (const parseRawHtml of [true, false]) {
746 await using screen = await renderWindows(
747 "[unsafe](javascript:alert(1)) and [unknown](d:alert(1))",
748 parseRawHtml,
749 );
750 const { container } = screen;
751 expect(container.innerHTML).not.toContain("javascript:");
752 expect(container.innerHTML).not.toContain("d:alert");
753 expect(fileHrefs(container)).toEqual([]);
754 }
755 });
756});
757​
758describe("ChatMarkdown host media", () => {
759 it("explains a host video the connection cannot read instead of offering a retry", async () => {
760 setup();
761 await using screen = await renderText("![Demo](/tmp/demo.mp4)", {
762 threadRef: {
763 environmentId: EnvironmentId.make(deniedEnvironmentId),
764 threadId: ThreadId.make("thread"),
765 },
766 });
767 await vi.waitFor(() =>
768 expect(screen.container.textContent).toContain(MISSING_FILE_ACCESS_MESSAGE),
769 );
770 expect(screen.container.textContent).not.toContain("Retry video");
771 });
772});