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

ChatMarkdown.browser.test.tsx

656 lines24.9 KB

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