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