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

ChatMarkdown.browser.test.tsx

1,267 lines48.3 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 { commands, page, userEvent } from "vite-plus/test/browser";
7​
8import { act, render } from "../../test/render";
9import "../index.css";
10​
11import { filesystemEnvironment } from "../state/filesystem";
12import {
13 hostRightPanel,
14 selectActiveRightPanelSurface,
15 useRightPanelStore,
16} from "../rightPanelStore";
17import type { MarkdownExtensions } from "../markdown/wordsHast";
18import { setMarkdownTaskChecked } from "@t3tools/shared/markdownTaskEdits";
19import { HostImageUrlContext } from "./chat/hostImageUrl";
20import { getSyntaxHighlighterPromise } from "~/lib/syntaxHighlighting";
21​
22const { workspaceSearch, filesystemMetadata } = vi.hoisted(() => ({
23 workspaceSearch: vi.fn(),
24 filesystemMetadata: vi.fn(),
25}));
26const parsedSources = vi.hoisted(() => [] as string[]);
27const nativeFileDrag = vi.hoisted(() => ({ enabled: false }));
28vi.mock(import("../useNativeFileDrag"), async (original) => {
29 const actual = await original();
30 return {
31 useNativeFileDrag: (...args: Parameters<typeof actual.useNativeFileDrag>) => {
32 const drag = actual.useNativeFileDrag(...args);
33 return nativeFileDrag.enabled ? { ...drag, draggable: true } : drag;
34 },
35 };
36});
37vi.mock(import("../markdown/wordsHast"), async (original) => {
38 const actual = await original();
39 return {
40 ...actual,
41 wordsHast: (source, options) => {
42 parsedSources.push(source);
43 return actual.wordsHast(source, options);
44 },
45 };
46});
47​
48vi.mock(import("../state/use-atom-query-runner"), async (original) => ({
49 ...(await original()),
50 useAtomQueryRunner: ((family: unknown) =>
51 family === filesystemEnvironment.getMetadata ? filesystemMetadata : workspaceSearch) as never,
52}));
53​
54// Atoms derived from the server config run in the real registry over a missing config.
55vi.mock(import("../state/server"), async (original) => {
56 const actual = await original();
57 const { Atom } = await import("effect/reactivity");
58 const noConfig = Atom.make(null);
59 const modelsConfig = Atom.make({
60 environment: { platform: { os: "darwin" }, capabilities: {} },
61 availableEditors: [],
62 settings: { providerInstances: {} },
63 providers: [
64 {
65 instanceId: "codex",
66 driver: "codex",
67 displayName: "Codex",
68 models: [{ slug: "gpt-6.1", name: "GPT-6.1", isCustom: false, capabilities: {} }],
69 },
70 ],
71 });
72 return {
73 ...actual,
74 serverEnvironment: {
75 ...actual.serverEnvironment,
76 configValueAtom: ((environmentId: string) =>
77 environmentId === "models" ? modelsConfig : noConfig) as never,
78 },
79 };
80});
81vi.mock(import("../state/session"), async (original) => {
82 const { AuthStandardClientScopes } = await import("@t3tools/contracts");
83 const granted = new Set<string>(AuthStandardClientScopes);
84 const hasScope = (environmentId: unknown, scope: string) =>
85 environmentId !== null && granted.has(scope);
86 return {
87 ...(await original()),
88 useEnvironmentScope: hasScope as never,
89 readEnvironmentScope: hasScope as never,
90 };
91});
92const deniedEnvironmentId = vi.hoisted(() => "denied-environment");
93vi.mock(import("../state/filesystem"), async (original) => {
94 const actual = await original();
95 return {
96 ...actual,
97 useFilesystemReadAccess: ((environmentId: EnvironmentId | null) =>
98 environmentId === deniedEnvironmentId
99 ? { canReadFiles: false, isPending: false, error: null }
100 : actual.useFilesystemReadAccess(environmentId)) as never,
101 };
102});
103const threadWorktrees = vi.hoisted(() => new Map<string, string>());
104vi.mock(import("../state/entities"), async (original) => {
105 const actual = await original();
106 return {
107 ...actual,
108 readThreadShell: ((ref: { threadId: string }) => {
109 const worktreePath = threadWorktrees.get(ref.threadId);
110 return worktreePath === undefined ? actual.readThreadShell(ref as never) : { worktreePath };
111 }) as never,
112 };
113});
114vi.mock(import("../remoteOpen"), async (original) => ({
115 ...(await original()),
116 useRemoteOpenResolution: () => ({ state: { mode: "local-exec" }, isResolved: true }) as never,
117}));
118const { renderDiagram } = vi.hoisted(() => ({
119 renderDiagram: vi.fn<(source: string) => Promise<string> | undefined>(),
120}));
121// Control rendering latency without running Mermaid layout.
122vi.mock(import("./chat/MermaidDiagram"), async (original) => {
123 const { use } = await import("react");
124 return {
125 ...(await original()),
126 MermaidDiagram: ({ source }: { source: string }) => {
127 const pending = renderDiagram(source);
128 return <svg role="img" aria-label={pending ? use(pending) : "Diagram"} />;
129 },
130 };
131});
132​
133const appearance = vi.hoisted(() => ({
134 value: "light" as "light" | "dark",
135 listeners: new Set<() => void>(),
136}));
137vi.mock(import("../hooks/useTheme"), async (original) => {
138 const { useSyncExternalStore } = await import("react");
139 const subscribe = (listener: () => void) => {
140 appearance.listeners.add(listener);
141 return () => appearance.listeners.delete(listener);
142 };
143 return {
144 ...(await original()),
145 useRenderedAppearance: () => useSyncExternalStore(subscribe, () => appearance.value),
146 };
147});
148​
149const settingsOverrides = vi.hoisted(() => ({ mathRenderingEnabled: false }));
150vi.mock(import("../hooks/useSettings"), async (original) => {
151 const actual = await original();
152 type Settings = ReturnType<typeof actual.getClientSettings>;
153 function useClientSettings<T = Settings>(select?: (settings: Settings) => T): T {
154 const settings = { ...actual.getClientSettings(), ...settingsOverrides };
155 return select ? select(settings) : (settings as T);
156 }
157 return { ...actual, useClientSettings };
158});
159​
160import ChatMarkdown from "./ChatMarkdown";
161import {
162 chatMarkdownClipboardPayload,
163 serializeRenderedMarkdownFragment,
164} from "../markdown-clipboard";
165import { AudioPreview } from "./files/AudioPreview";
166​
167it("keeps compact audio playback loaded across signed URL renewals", async () => {
168 const original =
169 "data:audio/wav;base64,UklGRiUAAABXQVZFZm10IBAAAAABAAEAQB8AAEAfAAABAAgAZGF0YQEAAACA";
170 const renewed = `${original}#renewed`;
171 const preview = (src: string, revision = "clip-v1") => (
172 <AudioPreview compact name="clip.wav" src={src} revision={revision} />
173 );
174 await using screen = await render(preview(original));
175 const audio = screen.container.querySelector("audio")!;
176 await act(() => {
177 audio.dispatchEvent(new Event("loadedmetadata"));
178 audio.dispatchEvent(new Event("play"));
179 });
180 await screen.rerender(preview(renewed));
181 expect(screen.container.querySelector("audio")).toBe(audio);
182 expect(audio.getAttribute("src")).toBe(original);
183 await expect.element(screen.getByRole("button", { name: "Pause clip.wav" })).toBeEnabled();
184 await screen.rerender(preview(renewed, "clip-v2"));
185 expect(screen.container.querySelector("audio")).not.toBe(audio);
186 expect(screen.container.querySelector("audio")?.getAttribute("src")).toBe(renewed);
187});
188​
189function setup() {
190 appearance.value = "light";
191 parsedSources.length = 0;
192 settingsOverrides.mathRenderingEnabled = false;
193 nativeFileDrag.enabled = false;
194 renderDiagram.mockReset();
195 threadWorktrees.clear();
196 workspaceSearch.mockReset().mockResolvedValue(AsyncResult.success({ entries: [] }));
197 filesystemMetadata.mockReset().mockResolvedValue(AsyncResult.success({ entries: [null] }));
199​
200function renderText(text: string, props: Partial<Parameters<typeof ChatMarkdown>[0]> = {}) {
201 return render(<ChatMarkdown cwd="/tmp/project" text={text} {...props} />);
203​
204function buttonsLabelled(container: HTMLElement, label: string) {
205 return [...container.querySelectorAll<HTMLButtonElement>("button")].filter(
206 (button) => button.getAttribute("aria-label") === label,
207 );
209​
210const USER_MESSAGE = { userMessage: true };
211​
212it("keeps decimal markers in nested user lists while documents keep their counter styles", async () => {
213 setup();
214 const text = "1. Outer\n 1. Nested\n 7. Skipped\n 1. Deeper\n 4. Fourth";
215 await using screen = await render(
216 <div className="grid grid-cols-2 gap-8 p-8">
217 <section>
218 <h2>User message</h2>
219 <ChatMarkdown
220 cwd={undefined}
221 text={text}
222 className="user-message-markdown"
223 extensions={USER_MESSAGE}
224 />
225 </section>
226 <section>
227 <h2>Markdown preview</h2>
228 <ChatMarkdown cwd={undefined} text={text} />
229 </section>
230 </div>,
231 );
232 await expect.element(screen.getByText("User message", { exact: true })).toBeVisible();
233 const [message, preview] = screen.container.querySelectorAll(".chat-markdown");
234 expect(
235 [...message!.querySelectorAll("ol")].map((list) => getComputedStyle(list).listStyleType),
236 ).toEqual(["decimal", "decimal", "decimal"]);
237 expect(
238 [...preview!.querySelectorAll("ol")].map((list) => getComputedStyle(list).listStyleType),
239 ).toEqual(["decimal", "lower-alpha", "lower-roman"]);
240});
241​
242it("shows unavailable audio when a workspace embed has no thread", async () => {
243 setup();
244 await using screen = await renderText("![recording](clip.wav)");
245 expect(screen.container.textContent).toContain("Audio unavailable");
246 expect(screen.container.textContent).not.toContain("Loading audio");
247 expect(screen.container.querySelector("audio")).toBeNull();
248});
249​
250it("loads a host image through the page's own route when there is no environment", async () => {
251 setup();
252 const pixel =
253 "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=";
254 const hostImageUrl = vi.fn((_path: string) => pixel);
255 await using screen = await render(
256 <HostImageUrlContext value={hostImageUrl}>
257 <ChatMarkdown cwd={undefined} text="![Shot](</work/my shot.png>)" />
258 </HostImageUrlContext>,
259 );
260 await expect.element(screen.getByAltText("Shot")).toHaveAttribute("src", pixel);
261 expect(new Set(hostImageUrl.mock.calls.map(([path]) => path))).toEqual(
262 new Set(["/work/my shot.png"]),
263 );
264});
265​
266it("loads the <picture> source for the current theme through the image route", async () => {
267 setup();
268 const pixel =
269 "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=";
270 const hostImageUrl = (path: string) => `${pixel}#${path}`;
271 await using screen = await render(
272 <HostImageUrlContext value={hostImageUrl}>
273 <ChatMarkdown
274 cwd={undefined}
275 text={
276 '<picture><source media="(prefers-color-scheme: dark)" srcset="/work/dark.png"><img src="/work/light.png" alt="Shot"></picture>'
277 }
278 />
279 </HostImageUrlContext>,
280 );
281 await expect
282 .element(screen.getByAltText("Shot"))
283 .toHaveAttribute("src", `${pixel}#/work/light.png`);
284​
285 await act(() => {
286 appearance.value = "dark";
287 for (const listener of appearance.listeners) listener();
288 });
289 await expect
290 .element(screen.getByAltText("Shot"))
291 .toHaveAttribute("src", `${pixel}#/work/dark.png`);
292});
293​
294it("sizes a raw HTML image by width and height written with px units", async () => {
295 setup();
296 const largeImage = `data:image/svg+xml,${encodeURIComponent(
297 '<svg xmlns="http://www.w3.org/2000/svg" width="200" height="200"/>',
298 )}`;
299 await using screen = await render(
300 <HostImageUrlContext value={() => largeImage}>
301 <ChatMarkdown
302 cwd={undefined}
303 parseRawHtml
304 text={
305 '### PR Review in progress <img src="/work/spinner.gif" alt="spinner" width="14px" height="7px" />'
306 }
307 />
308 </HostImageUrlContext>,
309 );
310 const image = screen.getByAltText("spinner");
311 await expect.element(image).toHaveAttribute("src", largeImage);
312 const element = image.element() as HTMLImageElement;
313 await element.decode();
314 const { width, height } = element.getBoundingClientRect();
315 expect({ width, height }).toEqual({ width: 14, height: 7 });
316});
317​
318it("fades a streaming reply's blocks in once, not again when it remounts", async () => {
319 setup();
320 const isFading = (element: Element) =>
321 element.getAnimations().some((animation) => animation instanceof CSSTransition);
322 const message = (
323 <ChatMarkdown
324 cwd="/tmp/project"
325 text={"Finished block\n\nStill growing"}
326 isStreaming
327 streamingId="remounted-reply"
328 />
329 );
330 {
331 await using first = await render(
332 <ChatMarkdown
333 cwd="/tmp/project"
334 text={"Finished block\n\n"}
335 isStreaming
336 streamingId="remounted-reply"
337 />,
338 );
339 await vi.waitFor(() =>
340 expect(isFading(first.getByText("Finished block").element())).toBe(true),
341 );
342 await first.rerender(message);
343 await vi.waitFor(() => expect(isFading(first.getByText("Still growing").element())).toBe(true));
344 }
345 await using screen = await render(message);
346 await expect
347 .element(screen.getByText("Still growing"))
348 .toHaveStyle({ opacity: "1", transitionDuration: "0s" });
349 expect(parsedSources.filter((source) => source.includes("Finished block"))).toHaveLength(1);
350});
351​
352it("reuses the parse of a remounted message that has stable extensions", async () => {
353 setup();
354 const extensions = { userMessage: true };
355 const message = <ChatMarkdown cwd="/tmp/project" text="Cached text" extensions={extensions} />;
356 {
357 await using first = await render(
358 <ChatMarkdown cwd="/tmp/project" text="Cached text" extensions={extensions} isStreaming />,
359 );
360 await first.rerender(message);
361 }
362 await using screen = await render(message);
363 await expect.element(screen.getByText("Cached text")).toBeVisible();
364 const parses = () => parsedSources.filter((source) => source === "Cached text").length;
365 expect(parses()).toBe(1);
366 await screen.rerender(
367 <ChatMarkdown cwd="/tmp/project" text="Cached text" extensions={{ userMessage: true }} />,
368 );
369 expect(parses()).toBe(2);
370});
371​
372it("highlights a code block's own source when an earlier block of the same length was cached", async () => {
373 setup();
374 const highlightedText = (container: HTMLElement) =>
375 container.querySelector(".chat-markdown-shiki")?.textContent?.trim();
376 // These two lines share a 32-bit FNV-1a hash and a length.
377 const first = 'const commitSha = "f36a6d8fe0aa";';
378 const second = 'const commitSha = "cb06f8d135b3";';
379 // The block suspends until the shared highlighter loads, which can outlast vi.waitFor on a busy runner.
380 await getSyntaxHighlighterPromise("ts");
381 {
382 await using screen = await renderText(`\`\`\`ts\n${first}\n\`\`\``);
383 await vi.waitFor(() => expect(highlightedText(screen.container)).toBe(first));
384 }
385 await using screen = await renderText(`\`\`\`ts\n${second}\n\`\`\``);
386 await vi.waitFor(() => expect(highlightedText(screen.container)).toBe(second));
387});
388​
389describe("ChatMarkdown favicon privacy", () => {
390 it("suppresses private link images while preserving public links across updates", async () => {
391 setup();
392 const markdown = (url: string) => <ChatMarkdown cwd="/tmp/project" text={`[Link](${url})`} />;
393 await using screen = await render(markdown("https://example.com"));
394 const { container, rerender } = screen;
395 expect([...container.querySelectorAll("img")].map((image) => image.src)).toEqual([
396 "https://www.google.com/s2/favicons?domain=example.com&sz=32",
397 ]);
398 for (const url of ["http://192.168.1.10:8080", "http://localhost:3000", "http://home.arpa"]) {
399 await rerender(markdown(url));
400 expect(container.querySelectorAll("img")).toHaveLength(0);
401 }
402 await rerender(markdown("https://example.com"));
403 expect(container.querySelectorAll("img")).toHaveLength(1);
404 await rerender(markdown("https://github.com/pingdotgg/t3code/pull/1"));
405 expect(container.querySelectorAll("img")).toHaveLength(0);
406 expect(container.querySelector("a svg")).not.toBeNull();
407 });
408});
409​
410describe("ChatMarkdown external link labels", () => {
411 it("keeps a leading emoji whole", async () => {
412 setup();
413 await using screen = await render(
414 <ChatMarkdown cwd="/tmp/project" text="[πŸ˜€ Read the documentation](https://example.com)" />,
415 );
416 await vi.waitFor(() => {
417 const link = screen.container.querySelector("a");
418 expect(link?.textContent).toContain("πŸ˜€ Read");
419 const walker = document.createTreeWalker(link!, NodeFilter.SHOW_TEXT);
420 const textNodes: string[] = [];
421 while (walker.nextNode()) textNodes.push(walker.currentNode.nodeValue ?? "");
422 expect(textNodes.filter((node) => /\p{Surrogate}/u.test(node))).toEqual([]);
423 });
424 });
425});
426​
427describe("ChatMarkdown link tooltips", () => {
428 it("shows each link's address on one shared tooltip as the pointer moves between links", async () => {
429 setup();
430 await using screen = await render(
431 <ChatMarkdown
432 cwd="/tmp/project"
433 text="[First](https://example.com/a) and [Second](https://example.org/b)"
434 />,
435 );
436 await userEvent.hover(screen.getByRole("link", { name: /First/ }));
437 await expect.element(page.getByText("https://example.com/a")).toBeVisible();
438 await userEvent.hover(screen.getByRole("link", { name: /Second/ }));
439 await expect.element(page.getByText("https://example.org/b")).toBeVisible();
440 expect(document.querySelectorAll('[data-slot="tooltip-popup"]')).toHaveLength(1);
441 });
442});
443​
444describe("ChatMarkdown details", () => {
445 it("opens collapsed details by click, and by keyboard without losing focus", async () => {
446 setup();
447 await using screen = await render(
448 <ChatMarkdown
449 cwd="/tmp/project"
450 text={
451 "<details><summary>First</summary>\n\nHidden one\n\n</details>\n\n<details><summary>Second</summary>\n\nHidden two\n\n</details>"
452 }
453 />,
454 );
455 await userEvent.click(screen.getByRole("button", { name: "First" }));
456 await expect.element(screen.getByText("Hidden one")).toBeVisible();
457 await userEvent.tab();
458 const second = screen.getByRole("button", { name: "Second" });
459 await expect.element(second).toHaveFocus();
460 await userEvent.keyboard("{Enter}");
461 await expect.element(screen.getByText("Hidden two")).toBeVisible();
462 await expect.element(screen.getByRole("button", { name: "Second" })).toHaveFocus();
463 });
464});
465​
466describe("ChatMarkdown streaming", () => {
467 it("runs only a complete single-line shell block after a click", async () => {
468 setup();
469 const onRunShellCommand = vi.fn();
470 const message = (text: string, isStreaming = false) => (
471 <ChatMarkdown
472 cwd="/tmp/project"
473 text={text}
474 isStreaming={isStreaming}
475 onRunShellCommand={onRunShellCommand}
476 />
477 );
478 await using screen = await render(message("```bash\necho hello\n```", true));
479 const { container, rerender } = screen;
480 const runButtons = () => buttonsLabelled(container, "Run in terminal");
481 expect(runButtons()).toHaveLength(0);
482​
483 await rerender(message("```bash\necho hello\n```"));
484 await act(async () => runButtons()[0]!.click());
485 expect(onRunShellCommand).toHaveBeenCalledExactlyOnceWith("echo hello");
486​
487 for (const text of [
488 "~~~bash\necho tilde\n~~~",
489 "> ```bash\n> echo quote\n> ```",
490 "````bash\necho four\n````",
491 "- Command\n\n ```bash\n echo list\n ```",
492 "```bash\r\necho crlf\r\n```\r",
493 ]) {
494 await rerender(message(text));
495 expect(runButtons()).toHaveLength(1);
496 }
497​
498 for (const text of [
499 "```bash\necho one\necho two\n```",
500 "```typescript\necho hello\n```",
501 "```bash\n\n```",
502 "```bash\necho hello\n\n```",
503 "```bash\necho hello\\\n```",
504 "```bash\necho safe \u202e#\n```",
505 "```bash\necho incomplete",
506 "~~~bash\necho incomplete",
507 "````bash\necho incomplete\n```",
508 '<pre><code class="language-bash">echo html</code></pre>',
509 ]) {
510 await rerender(message(text));
511 expect(runButtons()).toHaveLength(0);
512 }
513 });
514​
515 it("edits the current task text and marker after reusing a renderer", async () => {
516 setup();
517 let editedText: string | undefined;
518 let rerender: (next: ReactElement) => Promise<void> = async () => {};
519 const message = (text: string): ReactElement => (
520 <ChatMarkdown
521 cwd="/tmp/project"
522 text={text}
523 onTaskListChange={({ markerOffset, checked }) => {
524 editedText = setMarkdownTaskChecked(text, markerOffset, checked);
525 void rerender(message(editedText));
526 }}
527 />
528 );
529 await using rendered = await render(message("- [ ] First\n- [ ] Second"));
530 rerender = rendered.rerender;
531 const { container } = rendered;
532 const checkboxes = () => container.querySelectorAll<HTMLInputElement>('input[type="checkbox"]');
533 const original = checkboxes()[1]!;
534 await rerender(message("- [ ] A longer first task\n- [ ] Second"));
535 expect(checkboxes()[1]).toBe(original);
536​
537 await act(async () => original.click());
538 expect(editedText).toBe("- [ ] A longer first task\n- [x] Second");
539 await vi.waitFor(() => expect(checkboxes()[1]!.checked).toBe(true));
540 await rerender(message("- [ ] A longer first task\n- [ ] Second"));
541 expect(checkboxes()[1]).toBe(original);
542 expect(checkboxes()[1]!.checked).toBe(false);
543 });
544​
545 it.each([
546 ["read-only", undefined],
547 ["editable", () => {}],
548 ])(
549 "unchecks the remaining %s task when the checked row above it is removed",
550 async (_, onTaskListChange) => {
551 setup();
552 const message = (text: string) => (
553 <ChatMarkdown cwd="/tmp/project" text={text} onTaskListChange={onTaskListChange} />
554 );
555 await using screen = await render(message("- [x] Completed item\n- [ ] Pending item"));
556 await screen.rerender(message("- [ ] Pending item"));
557 const checkboxes =
558 screen.container.querySelectorAll<HTMLInputElement>('input[type="checkbox"]');
559 expect(checkboxes).toHaveLength(1);
560 expect(checkboxes[0]!.checked).toBe(false);
561 },
562 );
563});
564​
565describe("ChatMarkdown workspace file opens", () => {
566 const threadRef = {
567 environmentId: EnvironmentId.make("workspace"),
568 threadId: ThreadId.make("thread"),
569 };
570​
571 it("keeps a newer absolute file open when an earlier repo-relative lookup finishes", async () => {
572 setup();
573 const result = AsyncResult.success({
574 entries: [{ path: "notes/a.md", kind: "file" }],
575 truncated: false,
576 });
577 let resolvePending!: (value: typeof result) => void;
578 const pending = new Promise<typeof result>((resolve) => {
579 resolvePending = resolve;
580 });
581 workspaceSearch.mockReturnValueOnce(pending);
582 using openFile = vi.spyOn(useRightPanelStore.getState(), "openFile");
583 await using screen = await renderText(
584 "[Notes](physics/notes/a.md) and [Other](/elsewhere/b.md:9)",
585 {
586 cwd: "/school/physics",
587 threadRef,
588 },
589 );
590 const { container } = screen;
591 const [notes, other] = container.querySelectorAll("a");
592 await act(async () => notes!.click());
593 expect(workspaceSearch).toHaveBeenCalledOnce();
594 expect(openFile).not.toHaveBeenCalled();
595​
596 await act(async () => other!.click());
597 await act(async () => resolvePending(result));
598​
599 expect(openFile).toHaveBeenCalledExactlyOnceWith(threadRef, "/elsewhere/b.md", 9);
600 expect(workspaceSearch).toHaveBeenCalledOnce();
601 });
602​
603 it("opens a path from markdown rendered in another checkout under that checkout", async () => {
604 setup();
605 const scratchThread = { ...threadRef, threadId: ThreadId.make("scratch-thread") };
606 threadWorktrees.set(scratchThread.threadId, "/scratch/thread");
607 filesystemMetadata.mockResolvedValue(AsyncResult.success({ entries: [{ kind: "file" }] }));
608 using openFile = vi.spyOn(useRightPanelStore.getState(), "openFile");
609 await using screen = await renderText("[State](packages/state/filesystem.ts)", {
610 cwd: "/repo-a",
611 threadRef: scratchThread,
612 });
613 await act(async () => screen.container.querySelector("a")!.click());
614​
615 await vi.waitFor(() =>
616 expect(openFile).toHaveBeenCalledExactlyOnceWith(
617 scratchThread,
618 "/repo-a/packages/state/filesystem.ts",
619 undefined,
620 ),
621 );
622 });
623​
624 it.each([
625 ["its own panel", "thread-own-panel", false],
626 ["its parent's panel from a side chat", "thread-side-chat", true],
627 ])(
628 "keeps a file opened elsewhere in %s when an earlier link lookup finishes",
629 async (_, threadId, sideChat) => {
630 setup();
631 const host = { environmentId: threadRef.environmentId, threadId: ThreadId.make(threadId) };
632 const linkRef = sideChat ? { ...host, threadId: ThreadId.make(`${threadId}-guest`) } : host;
633 using _hosted = { [Symbol.dispose]: sideChat ? hostRightPanel(linkRef, host) : () => {} };
634 const result = AsyncResult.success({
635 entries: [{ path: "notes/cited-note.txt", kind: "file" }],
636 truncated: false,
637 });
638 const { promise: pending, resolve: resolvePending } = Promise.withResolvers<typeof result>();
639 workspaceSearch.mockReturnValueOnce(pending);
640 await using screen = await renderText("[Cited](cited-note.txt)", {
641 cwd: "/repo",
642 threadRef: linkRef,
643 });
644 await act(async () => screen.container.querySelector("a")!.click());
645 expect(workspaceSearch).toHaveBeenCalledOnce();
646​
647 useRightPanelStore.getState().openFile(host, "picker-note.txt");
648 await act(async () => resolvePending(result));
649​
650 expect(
651 selectActiveRightPanelSurface(useRightPanelStore.getState().byThreadKey, host),
652 ).toMatchObject({ kind: "file", relativePath: "picker-note.txt" });
653 },
654 );
655​
656 it.each([
657 ["open a link in another panel", "separate-panels"],
658 ["unhost the side chat", "unhosted-side-chat"],
659 ] as const)("keeps a citation in its original panel scope if you %s", async (action, scope) => {
660 setup();
661 const host = { ...threadRef, threadId: ThreadId.make(`${scope}-host`) };
662 const guest = { ...threadRef, threadId: ThreadId.make(`${scope}-guest`) };
663 const other = { ...threadRef, threadId: ThreadId.make(`${scope}-other`) };
664 const unhost = hostRightPanel(guest, host);
665 using _hosted = { [Symbol.dispose]: unhost };
666 const result = AsyncResult.success({
667 entries: [{ path: "notes/cited-note.txt", kind: "file" }],
668 truncated: false,
669 });
670 const { promise: pending, resolve: resolvePending } = Promise.withResolvers<typeof result>();
671 workspaceSearch.mockReturnValueOnce(pending);
672 await using screen = await render(
673 <>
674 <ChatMarkdown cwd="/repo" threadRef={guest} text="[Cited](cited-note.txt)" />
675 <ChatMarkdown cwd="/repo" threadRef={other} text="[Other](/elsewhere/other.md)" />
676 </>,
677 );
678 const [cited, otherLink] = screen.container.querySelectorAll("a");
679 await act(async () => cited!.click());
680 expect(workspaceSearch).toHaveBeenCalledOnce();
681 if (action === "open a link in another panel") {
682 await act(async () => otherLink!.click());
683 } else {
684 unhost();
685 }
686 await act(async () => resolvePending(result));
687​
688 const { byThreadKey } = useRightPanelStore.getState();
689 expect(selectActiveRightPanelSurface(byThreadKey, guest)).toBeNull();
690 if (action === "unhost the side chat") {
691 expect(selectActiveRightPanelSurface(byThreadKey, host)).toBeNull();
692 } else {
693 expect(selectActiveRightPanelSurface(byThreadKey, host)).toMatchObject({
694 kind: "file",
695 relativePath: "notes/cited-note.txt",
696 });
697 expect(selectActiveRightPanelSurface(byThreadKey, other)).toMatchObject({
698 kind: "file",
699 relativePath: "/elsewhere/other.md",
700 });
701 }
702 });
703});
704​
705describe("ChatMarkdown skill chips", () => {
706 it("shows the skill's details and opens its instructions, closing the details", async () => {
707 setup();
708 const threadRef = {
709 environmentId: EnvironmentId.make("workspace"),
710 threadId: ThreadId.make("thread"),
711 };
712 await using screen = await renderText("Run $review now", {
713 threadRef,
714 skills: [
715 {
716 name: "review",
717 displayName: "Review",
718 description: "Reviews the current branch.",
719 path: "/skills/review/SKILL.md",
720 enabled: true,
721 },
722 ],
723 });
724 using openFile = vi
725 .spyOn(useRightPanelStore.getState(), "openFile")
726 .mockImplementation(() => {});
727​
728 await userEvent.click(screen.getByRole("button", { name: "Skill Review. Show details" }));
729 await expect.element(page.getByText("Reviews the current branch.")).toBeVisible();
730 await userEvent.click(page.getByRole("button", { name: "View instructions" }));
731​
732 expect(openFile).toHaveBeenCalledExactlyOnceWith(threadRef, "/skills/review/SKILL.md");
733 await expect.element(page.getByText("Reviews the current branch.")).not.toBeInTheDocument();
734 });
735​
736 it("names a mentioned model as its provider does, without a thread", async () => {
737 setup();
738 await using screen = await renderText("Ask (model:codex/gpt-6.1), not model:openai/gpt-4o.", {
739 environmentId: EnvironmentId.make("models"),
740 });
741​
742 await expect
743 .element(screen.getByRole("button", { name: "Model GPT-6.1. Show details" }))
744 .toBeVisible();
745 expect(buttonsLabelled(screen.container, "Model gpt-4o. Show details")).toEqual([]);
746 expect(screen.container.textContent).toBe("Ask (GPT-6.1), not model:openai/gpt-4o.");
747 });
748});
749​
750describe("ChatMarkdown headings", () => {
751 it("keeps insight streaming, reference links, and heading anchors in one message", async () => {
752 setup();
753 const rule = "─".repeat(20);
754 const text = `## Setup\n\nBefore [source][src].\n\nβ˜… Insight ${rule}\nA **streaming** note.`;
755 const message = (text: string, isStreaming: boolean) => (
756 <ChatMarkdown
757 cwd={undefined}
758 text={text}
759 renderInsights
760 lineBreaks
761 isStreaming={isStreaming}
762 />
763 );
764 await using screen = await render(message(text, true));
765 await expect.element(screen.getByRole("note")).toHaveTextContent("Insight A streaming note.");
766 await screen.rerender(
767 message(
768 `${text}\n${rule}\n\n## Setup\n\nAfter [source][src].\n\n[src]:\n https://example.com`,
769 false,
770 ),
771 );
772 await expect.element(screen.getByRole("note")).toHaveTextContent("Insight A streaming note.");
773 expect([...screen.container.querySelectorAll("h2")].map((heading) => heading.id)).toEqual([
774 "user-content-setup",
775 "user-content-setup-1",
776 ]);
777 expect(
778 [...screen.container.querySelectorAll("a")].filter(
779 (link) => link.href === "https://example.com/",
780 ),
781 ).toHaveLength(2);
782 await expect.element(screen.getByRole("note")).not.toHaveTextContent("After");
783 });
784​
785 it("never gives two headings the same id, even when a suffix matches another heading", async () => {
786 setup();
787 await using screen = await renderText(
788 '## Setup\n\n## Setup\n\n## Setup-1\n\n<h2 id="install-1">Pinned</h2>\n\n## Install\n\n## Install',
789 { parseRawHtml: true },
790 );
791 const { container } = screen;
792 expect([...container.querySelectorAll("h2")].map((heading) => heading.id)).toEqual([
793 "user-content-setup",
794 "user-content-setup-1",
795 "user-content-setup-1-1",
796 "user-content-install-1",
797 "user-content-install",
798 "user-content-install-2",
799 ]);
800 });
801});
802​
803describe("ChatMarkdown inline code selection", () => {
804 it("selects only a word on double-click in inline and fenced code", async () => {
805 setup();
806 await using screen = await renderText(
807 "Run `migration-gate --dry-run` first.\n\n```txt\nfenced-block word\n```",
808 );
809 await userEvent.dblClick(screen.getByText("migration-gate --dry-run"), {
810 position: { x: 12, y: 8 },
811 });
812 expect(window.getSelection()?.toString()).toBe("migration");
813​
814 window.getSelection()?.removeAllRanges();
815 const fenced = screen.container.querySelector("pre code")!;
816 await userEvent.dblClick(fenced, { position: { x: 4, y: 4 } });
817 expect(window.getSelection()?.toString()).toBe("fenced");
818 });
819​
820 it("selects the whole line on triple-click beside a favicon link or a file chip", async () => {
821 setup();
822 await using screen = await renderText(
823 "Before [docs](https://example.com/docs) after words\n\nBefore [App.tsx](/tmp/project/src/App.tsx) after words",
824 );
825 const tripleClickWord = async (paragraph: HTMLElement, word: string) => {
826 const text = [...paragraph.childNodes].find((node) => node.textContent?.includes(word))!;
827 const range = document.createRange();
828 range.setStart(text, text.textContent!.indexOf(word));
829 range.setEnd(text, text.textContent!.indexOf(word) + word.length);
830 const wordBox = range.getBoundingClientRect();
831 const paragraphBox = paragraph.getBoundingClientRect();
832 window.getSelection()?.removeAllRanges();
833 await userEvent.tripleClick(paragraph, {
834 position: {
835 x: wordBox.left - paragraphBox.left + wordBox.width / 2,
836 y: wordBox.top - paragraphBox.top + wordBox.height / 2,
837 },
838 });
839 return window.getSelection()?.toString().trim();
840 };
841​
842 const paragraphs = screen.container.querySelectorAll("p");
843 expect(paragraphs).toHaveLength(2);
844 const selections = [];
845 const lines = [];
846 for (const paragraph of paragraphs) {
847 lines.push(paragraph.textContent?.trim(), paragraph.textContent?.trim());
848 selections.push(
849 await tripleClickWord(paragraph, "Before"),
850 await tripleClickWord(paragraph, "after"),
851 );
852 }
853 expect(selections).toEqual(lines);
854 });
855​
856 it("selects the whole line on triple-click beside a desktop-draggable inline-code file chip", async () => {
857 setup();
858 // Desktop on macOS and Windows makes local file chips draggable for native file drags.
859 nativeFileDrag.enabled = true;
860 filesystemMetadata.mockResolvedValue(AsyncResult.success({ entries: [{ kind: "file" }] }));
861 await using screen = await renderText(
862 "The template (`config/app.yaml.example`) and two docs still say 5 fps.",
863 {
864 threadRef: {
865 environmentId: EnvironmentId.make("workspace"),
866 threadId: ThreadId.make("thread"),
867 },
868 },
869 );
870 await vi.waitFor(() =>
871 expect(
872 screen.container.querySelector("a.chat-markdown-file-link")?.getAttribute("draggable"),
873 ).toBe("true"),
874 );
875 const paragraph = screen.container.querySelector("p")!;
876 const text = [...paragraph.childNodes].find((node) =>
877 node.textContent?.includes("and two docs"),
878 )!;
879 const range = document.createRange();
880 range.setStart(text, text.textContent!.indexOf("and"));
881 range.setEnd(text, text.textContent!.indexOf("and") + 3);
882 const wordBox = range.getBoundingClientRect();
883 const paragraphBox = paragraph.getBoundingClientRect();
884 await userEvent.tripleClick(paragraph, {
885 position: {
886 x: wordBox.left - paragraphBox.left + wordBox.width / 2,
887 y: wordBox.top - paragraphBox.top + wordBox.height / 2,
888 },
889 });
890 expect(window.getSelection()?.toString().trim()).toBe(paragraph.textContent?.trim());
891 });
892});
893​
894describe("ChatMarkdown copy", () => {
895 it("copies a fully selected callout as alert Markdown and a partial one as text", async () => {
896 setup();
897 await using screen = await renderText("> [!WARNING]\n> Back up first.");
898 const [label, body] = screen.container.querySelectorAll('[role="note"] > p');
899 const select = (startNode: Node, endNode: Node, endOffset: number) => {
900 const range = document.createRange();
901 range.setStart(startNode, 0);
902 range.setEnd(endNode, endOffset);
903 const selection = window.getSelection()!;
904 selection.removeAllRanges();
905 selection.addRange(range);
906 return chatMarkdownClipboardPayload(selection)?.text;
907 };
908 const labelText = label!.lastChild!;
909 const bodyText = body!.firstChild!;
910​
911 expect(select(labelText, bodyText, bodyText.textContent!.length)).toBe(
912 "> [!WARNING]\n> Back up first.",
913 );
914 expect(select(labelText, bodyText, "Back up".length)).toBe("Warning\n\nBack up");
915 });
916​
917 it.each([
918 { text: " Plan\nnext" },
919 { text: "Plan\n Deep\n Deeper" },
920 { text: "Plan\n\tTabbed\n \t Mixed" },
921 { text: "- item\n more\n deeper\n- next" },
922 { text: "Plan\n Step one\n Detail a", from: "Step one" },
923 ])(
924 "copies and selects user lines the same whether their typed indentation shows: $text",
925 async (copy) => {
926 setup();
927 const copied = async (extensions: MarkdownExtensions) => {
928 await using screen = await renderText(copy.text, {
929 className: "user-message-markdown",
930 lineBreaks: true,
931 parseRawHtml: false,
932 extensions,
933 });
934 const range = document.createRange();
935 range.selectNodeContents(screen.container);
936 if (copy.from) {
937 const walker = document.createTreeWalker(screen.container, NodeFilter.SHOW_TEXT);
938 let line = walker.nextNode();
939 while (line && !line.textContent!.includes(copy.from)) line = walker.nextNode();
940 // Start mid-line, three characters into the line's text.
941 range.setStart(line!, line!.textContent!.indexOf(copy.from) + 3);
942 }
943 const selection = window.getSelection()!;
944 selection.removeAllRanges();
945 selection.addRange(range);
946 // A drag or anything else that reads the selection gets its text, not the copy payload.
947 return { payload: chatMarkdownClipboardPayload(selection), selected: selection.toString() };
948 };
949 const shown = await copied({ userMessage: true, leadingWhitespace: true });
950 // The user pipeline as it was before typed indentation was shown.
951 expect(shown).toEqual(await copied({ userMessage: true }));
952 },
953 );
954​
955 it("copies part of inline code without prose escapes", async () => {
956 setup();
957 await using screen = await renderText("Read `items[0]*_x` and a*b*c.");
958 const code = screen.container.querySelector("p code")!.firstChild!;
959 const range = document.createRange();
960 range.setStart(code, 0);
961 range.setEnd(code, "items[0]*_".length);
962 const selection = window.getSelection()!;
963 selection.removeAllRanges();
964 selection.addRange(range);
965 expect(chatMarkdownClipboardPayload(selection)?.text).toBe("items[0]*_");
966 });
967​
968 it.each([
969 {
970 source: "10. First\n11. Second\n12. Third\n\nAfter.",
971 from: "Second",
972 text: "11. Second\n12. Third\n\nAfter.",
973 },
974 {
975 source: "1. A\n2. B\n7. C\n8. D\n\nAfter.",
976 from: "D",
977 userMessage: true,
978 text: "8. D\n\nAfter.",
979 },
980 {
981 source: "1. Outer\n2. Next\n 1. Inner\n 2. Deeper\n\nAfter.",
982 from: "Deeper",
983 text: "2. 2. Deeper\n\nAfter.",
984 },
985 {
986 source: "1. Install\n2. Configure\n3. Deploy",
987 from: "Configure",
988 to: "Deploy",
989 text: "2. Configure\n3. Deploy",
990 },
991 {
992 source: "1. A\n2. B\n7. C\n8. D",
993 from: "B",
994 to: "C",
995 userMessage: true,
996 text: "2. B\n7. C",
997 },
998 {
999 source: "- Install\n- Configure\n- Deploy",
1000 from: "Configure",
1001 to: "Deploy",
1002 text: "- Configure\n- Deploy",
1003 },
1004 ])(
1005 "copies $text with the markers its list shows",
1006 async ({ source, from, to, userMessage, text }) => {
1007 setup();
1008 await using screen = await renderText(
1009 source,
1010 userMessage ? { extensions: USER_MESSAGE } : {},
1011 );
1012 const itemText = (shown: string) =>
1013 [...screen.container.querySelectorAll("li")]
1014 .flatMap((item) => [...item.childNodes])
1015 .find((node) => node.nodeType === Node.TEXT_NODE && node.textContent === shown)!;
1016 const end = to
1017 ? itemText(to)
1018 : [...screen.container.querySelectorAll("p")].at(-1)!.firstChild!;
1019 const range = document.createRange();
1020 range.setStart(itemText(from), 0);
1021 range.setEnd(end, end.textContent!.length);
1022 const selection = window.getSelection()!;
1023 selection.removeAllRanges();
1024 selection.addRange(range);
1025 const payload = chatMarkdownClipboardPayload(selection);
1026 expect(payload?.text).toBe(text);
1027 // Rich paste reads back as the same list.
1028 expect(
1029 serializeRenderedMarkdownFragment(
1030 new DOMParser().parseFromString(payload!.html, "text/html").body,
1031 ),
1032 ).toBe(text);
1033 },
1034 );
1035​
1036 it.each([
1038 source: "1. [ ] Install\n2. [x] Configure\n3. [ ] Test\n4. [x] Deploy",
1039 from: "Configure",
1040 to: "Deploy",
1041 text: "2. [x] Configure\n3. [ ] Test\n4. [x] Deploy",
1042 htmlText: "2. Configure\n3. Test\n4. Deploy",
1043 },
1045 source:
1046 "1. First\n2. [x] Outer\n 1. [ ] Setup\n 2. [ ] Configure\n 3. [x] Deploy\n\nAfter.",
1047 from: "Configure",
1048 text: "2. [x] 2. [ ] Configure\n 3. [x] Deploy\n\nAfter.",
1049 htmlText: "2. 2. Configure\n 3. Deploy\n\nAfter.",
1050 },
1051 ])(
1052 "copies task items with the markers its list shows: $text",
1053 async ({ source, from, to, text, htmlText }) => {
1054 setup();
1055 await using screen = await renderText(source);
1056 const itemText = (label: string) =>
1057 [...screen.container.querySelectorAll("li")]
1058 .flatMap((item) => [...item.childNodes])
1059 .find((node) => node.nodeType === Node.TEXT_NODE && node.textContent?.trim() === label)!;
1060 const start = itemText(from);
1061 const end = to ? itemText(to) : screen.container.querySelector("p")!.firstChild!;
1062 const range = document.createRange();
1063 range.setStart(start, start.textContent!.indexOf(from));
1064 range.setEnd(end, end.textContent!.length);
1065 const selection = window.getSelection()!;
1066 selection.removeAllRanges();
1067 selection.addRange(range);
1068 const payload = chatMarkdownClipboardPayload(selection);
1069 expect(payload?.text).toBe(text);
1070 // HTML sanitization strips form controls.
1071 expect(
1072 serializeRenderedMarkdownFragment(
1073 new DOMParser().parseFromString(payload!.html, "text/html").body,
1074 ),
1075 ).toBe(htmlText);
1076 },
1077 );
1078​
1079 it.each([
1081 source: "1. First\n2. Second\n\nAfter.",
1082 from: "First",
1083 skipFrom: true,
1084 text: "2. Second\n\nAfter.",
1085 items: 1,
1086 },
1088 source: "Before.\n\n1. First\n2. Second",
1089 from: "Before.",
1090 to: "Second",
1091 skipTo: true,
1092 text: "Before.\n\n1. First",
1093 items: 1,
1094 },
1096 source: "1. Outer\n 1. Inner\n 2. Deeper\n2. Next",
1097 from: "Inner",
1098 to: "Next",
1099 skipFrom: true,
1100 text: "1. 2. Deeper\n2. Next",
1101 items: 3,
1102 },
1104 source: "1. Outer\n 1. Inner\n2. Next",
1105 from: "Inner",
1106 to: "Next",
1107 skipFrom: true,
1108 text: "2. Next",
1109 items: 1,
1110 },
1111 ])(
1112 "omits edge items outside the selection when copying with the markers its list shows: $text",
1113 async ({ source, from, to, skipFrom, skipTo, text, items }) => {
1114 setup();
1115 await using screen = await renderText(source);
1116 const textNode = (shown: string) => {
1117 const walker = document.createTreeWalker(screen.container, NodeFilter.SHOW_TEXT);
1118 for (let node = walker.nextNode(); node; node = walker.nextNode()) {
1119 if (node.textContent === shown) return node;
1121 throw new Error(`Could not find text: ${shown}`);
1122 };
1123 const end = to ? textNode(to) : textNode("After.");
1124 const range = document.createRange();
1125 range.setStart(textNode(from), skipFrom ? from.length : 0);
1126 range.setEnd(end, skipTo ? 0 : end.textContent!.length);
1127 const selection = window.getSelection()!;
1128 selection.removeAllRanges();
1129 selection.addRange(range);
1130​
1131 const payload = chatMarkdownClipboardPayload(selection);
1132 expect(payload?.text).toBe(text);
1133 const pasted = new DOMParser().parseFromString(payload!.html, "text/html");
1134 expect(serializeRenderedMarkdownFragment(pasted.body)).toBe(text);
1135 expect(pasted.querySelectorAll("li")).toHaveLength(items);
1136 },
1137 );
1138​
1139 it("omits an end item whose selected edge sits inside its link", async () => {
1140 setup();
1141 await using screen = await renderText(
1142 "1. Install\n2. Configure\n3. Deploy\n4. [Verify](https://example.com/verify)",
1143 );
1144 const items = [...screen.container.querySelectorAll("li")];
1145 const start = items.find((item) => item.textContent === "Configure")!.firstChild!;
1146 const end = items.at(-1)!.querySelector("a > span")!.lastChild!;
1147 const range = document.createRange();
1148 range.setStart(start, 0);
1149 range.setEnd(end, 0);
1150 const selection = window.getSelection()!;
1151 selection.removeAllRanges();
1152 selection.addRange(range);
1153​
1154 const payload = chatMarkdownClipboardPayload(selection);
1155 expect(payload?.text).toBe("2. Configure\n3. Deploy");
1156 const pasted = new DOMParser().parseFromString(payload!.html, "text/html");
1157 expect(
1158 [...pasted.querySelectorAll('ol[start="2"] > li')].map((item) => item.textContent),
1159 ).toEqual(["Configure", "Deploy"]);
1160 });
1161});
1162​
1163describe("ChatMarkdown file chip tooltips", () => {
1164 it("stays open while the pointer selects the path, then closes when it leaves", async () => {
1165 setup();
1166 await using screen = await renderText("[notes](/tmp/project/docs/notes.md)");
1167 await userEvent.hover(screen.container.querySelector(".chat-markdown-file-link")!);
1168 const path = page.getByText("/tmp/project/docs/notes.md");
1169 await expect.element(path).toBeVisible();
1170​
1171 // Forced so the pointer lands on the popup even when it ignores pointer events.
1172 await userEvent.tripleClick(path, { force: true });
1173 expect(window.getSelection()?.toString().trim()).toBe("/tmp/project/docs/notes.md");
1174 await expect.element(path).toBeVisible();
1175​
1176 await commands.resetPointer();
1177 await expect.element(path).not.toBeInTheDocument();
1178 });
1179​
1180 it("wraps a long path so its file name stays inside the tooltip", async () => {
1181 setup();
1182 const path =
1183 "/tmp/project/packages/client-runtime/src/state/generated/environment-connection-handshake-retry-policy-fixtures.ts";
1184 await using screen = await renderText(`See [the fixtures](${path}).`);
1185​
1186 await userEvent.hover(screen.container.querySelector(".chat-markdown-file-link")!);
1187 const tooltip = page.getByText(path);
1188 await expect.element(tooltip).toBeVisible();
1189​
1190 const popup = tooltip.element().closest("[data-side]")!;
1191 const pathEnd = document.createRange();
1192 pathEnd.selectNodeContents(tooltip.element());
1193 expect(pathEnd.getBoundingClientRect().right).toBeLessThanOrEqual(
1194 popup.getBoundingClientRect().right,
1195 );
1196 });
1197});
1198​
1199describe("ChatMarkdown editor deep links", () => {
1200 const hrefs = (container: HTMLElement) =>
1201 [...container.querySelectorAll("a")].map((link) => link.getAttribute("href"));
1202​
1203 it("keeps local editor file links", async () => {
1204 setup();
1205 await using screen = await renderText(
1206 "[file.md line 3](cursor://file/Users/me/repo/file.md:3) and [same](vscode://file/Users/me/repo/file.md:3:7)",
1207 );
1208 expect(hrefs(screen.container)).toEqual([
1209 "cursor://file/Users/me/repo/file.md:3",
1210 "vscode://file/Users/me/repo/file.md:3:7",
1211 ]);
1212 });
1213​
1214 it("still drops other editor links and unknown schemes", async () => {
1215 setup();
1216 await using screen = await renderText(
1217 "[prompt](cursor://anysphere.cursor-deeplink/prompt?text=hi) [user](cursor://me@file/Users/me/file.md) [unknown](foo://file/Users/me/file.md)",
1218 );
1219 expect(screen.container.innerHTML).not.toContain("://");
1220 expect(hrefs(screen.container).filter(Boolean)).toEqual([]);
1221 });
1222});
1223​
1224describe("ChatMarkdown Windows file links", () => {
1225 const environmentId = EnvironmentId.make("env-windows");
1226 const renderWindows = (text: string, parseRawHtml: boolean) =>
1227 renderText(text, {
1228 cwd: "C:/Users/shawn/project",
1229 environmentId,
1230 lineBreaks: !parseRawHtml,
1231 parseRawHtml,
1232 });
1233 const fileHrefs = (container: HTMLElement) =>
1234 [...container.querySelectorAll(".chat-markdown-file-link")].map((chip) =>
1235 chip.getAttribute("href"),
1236 );
1237​
1238 it("still rejects unsafe schemes", async () => {
1239 setup();
1240 for (const parseRawHtml of [true, false]) {
1241 await using screen = await renderWindows(
1242 "[unsafe](javascript:alert(1)) and [unknown](d:alert(1))",
1243 parseRawHtml,
1244 );
1245 const { container } = screen;
1246 expect(container.innerHTML).not.toContain("javascript:");
1247 expect(container.innerHTML).not.toContain("d:alert");
1248 expect(fileHrefs(container)).toEqual([]);
1250 });
1251});
1252​
1253describe("ChatMarkdown host media", () => {
1254 it("explains a host video the connection cannot read instead of offering a retry", async () => {
1255 setup();
1256 await using screen = await renderText("![Demo](/tmp/demo.mp4)", {
1257 threadRef: {
1258 environmentId: EnvironmentId.make(deniedEnvironmentId),
1259 threadId: ThreadId.make("thread"),
1260 },
1261 });
1262 await vi.waitFor(() =>
1263 expect(screen.container.textContent).toContain(MISSING_FILE_ACCESS_MESSAGE),
1264 );
1265 expect(screen.container.textContent).not.toContain("Retry video");
1266 });
1267});