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

ChatMarkdown.browser.test.tsx

1,168 lines44.6 KB

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