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

ChatMarkdown.browser.test.tsx

897 lines34.2 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 remarkGfm from "remark-gfm";
6import { describe, expect, it, vi } from "vite-plus/test";
7import { page, userEvent } from "vite-plus/test/browser";
8​
9import { act, render } from "../../test/render";
10import "../index.css";
11​
12import { filesystemEnvironment } from "../state/filesystem";
13import { useRightPanelStore } from "../rightPanelStore";
14import {
15 CHAT_USER_MARKDOWN_REMARK_PLUGINS,
16 remarkEnableOrderedListNumbers,
17} from "@t3tools/shared/markdownPipeline";
18import { setMarkdownTaskChecked } from "@t3tools/shared/markdownTaskList";
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("mdast-util-from-markdown"), async (original) => {
28 const actual = await original();
29 return {
30 ...actual,
31 fromMarkdown: ((source: string, ...rest: never[]) => {
32 parsedSources.push(String(source));
33 return (actual.fromMarkdown as (...args: unknown[]) => unknown)(source, ...rest);
34 }) as typeof actual.fromMarkdown,
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 { chatMarkdownClipboardPayload } from "../markdown-clipboard";
141import { AudioPreview } from "./files/AudioPreview";
142​
143it("keeps compact audio playback loaded across signed URL renewals", async () => {
144 const original =
145 "data:audio/wav;base64,UklGRiUAAABXQVZFZm10IBAAAAABAAEAQB8AAEAfAAABAAgAZGF0YQEAAACA";
146 const renewed = `${original}#renewed`;
147 const preview = (src: string, revision = "clip-v1") => (
148 <AudioPreview compact name="clip.wav" src={src} revision={revision} />
149 );
150 await using screen = await render(preview(original));
151 const audio = screen.container.querySelector("audio")!;
152 await act(() => {
153 audio.dispatchEvent(new Event("loadedmetadata"));
154 audio.dispatchEvent(new Event("play"));
155 });
156 await screen.rerender(preview(renewed));
157 expect(screen.container.querySelector("audio")).toBe(audio);
158 expect(audio.getAttribute("src")).toBe(original);
159 await expect.element(screen.getByRole("button", { name: "Pause clip.wav" })).toBeEnabled();
160 await screen.rerender(preview(renewed, "clip-v2"));
161 expect(screen.container.querySelector("audio")).not.toBe(audio);
162 expect(screen.container.querySelector("audio")?.getAttribute("src")).toBe(renewed);
163});
164​
165function setup() {
166 appearance.value = "light";
167 parsedSources.length = 0;
168 settingsOverrides.mathRenderingEnabled = false;
169 renderDiagram.mockReset();
170 workspaceSearch.mockReset().mockResolvedValue(AsyncResult.success({ entries: [] }));
171 filesystemMetadata.mockReset().mockResolvedValue(AsyncResult.success({ entries: [null] }));
173​
174function renderText(text: string, props: Partial<Parameters<typeof ChatMarkdown>[0]> = {}) {
175 return render(<ChatMarkdown cwd="/tmp/project" text={text} {...props} />);
177​
178function buttonsLabelled(container: HTMLElement, label: string) {
179 return [...container.querySelectorAll<HTMLButtonElement>("button")].filter(
180 (button) => button.getAttribute("aria-label") === label,
181 );
183​
184const SOURCE_NUMBER_PLUGINS = [remarkEnableOrderedListNumbers];
185​
186it("keeps decimal markers in nested user lists while documents keep their counter styles", async () => {
187 setup();
188 const text = "1. Outer\n 1. Nested\n 7. Skipped\n 1. Deeper\n 4. Fourth";
189 await using screen = await render(
190 <div className="grid grid-cols-2 gap-8 p-8">
191 <section>
192 <h2>User message</h2>
193 <ChatMarkdown
194 cwd={undefined}
195 text={text}
196 className="user-message-markdown"
197 extraRemarkPlugins={SOURCE_NUMBER_PLUGINS}
198 />
199 </section>
200 <section>
201 <h2>Markdown preview</h2>
202 <ChatMarkdown cwd={undefined} text={text} />
203 </section>
204 </div>,
205 );
206 await expect.element(screen.getByText("User message", { exact: true })).toBeVisible();
207 const [message, preview] = screen.container.querySelectorAll(".chat-markdown");
208 expect(
209 [...message!.querySelectorAll("ol")].map((list) => getComputedStyle(list).listStyleType),
210 ).toEqual(["decimal", "decimal", "decimal"]);
211 expect(
212 [...preview!.querySelectorAll("ol")].map((list) => getComputedStyle(list).listStyleType),
213 ).toEqual(["decimal", "lower-alpha", "lower-roman"]);
214});
215​
216it("shows unavailable audio when a workspace embed has no thread", async () => {
217 setup();
218 await using screen = await renderText("![recording](clip.wav)");
219 expect(screen.container.textContent).toContain("Audio unavailable");
220 expect(screen.container.textContent).not.toContain("Loading audio");
221 expect(screen.container.querySelector("audio")).toBeNull();
222});
223​
224it("loads a host image through the page's own route when there is no environment", async () => {
225 setup();
226 const pixel =
227 "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=";
228 const hostImageUrl = vi.fn((_path: string) => pixel);
229 await using screen = await render(
230 <HostImageUrlContext value={hostImageUrl}>
231 <ChatMarkdown cwd={undefined} text="![Shot](</work/my shot.png>)" />
232 </HostImageUrlContext>,
233 );
234 await expect.element(screen.getByAltText("Shot")).toHaveAttribute("src", pixel);
235 expect(new Set(hostImageUrl.mock.calls.map(([path]) => path))).toEqual(
236 new Set(["/work/my shot.png"]),
237 );
238});
239​
240it("loads the <picture> source for the current theme through the image route", async () => {
241 setup();
242 const pixel =
243 "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=";
244 const hostImageUrl = (path: string) => `${pixel}#${path}`;
245 await using screen = await render(
246 <HostImageUrlContext value={hostImageUrl}>
247 <ChatMarkdown
248 cwd={undefined}
249 text={
250 '<picture><source media="(prefers-color-scheme: dark)" srcset="/work/dark.png"><img src="/work/light.png" alt="Shot"></picture>'
251 }
252 />
253 </HostImageUrlContext>,
254 );
255 await expect
256 .element(screen.getByAltText("Shot"))
257 .toHaveAttribute("src", `${pixel}#/work/light.png`);
258​
259 await act(() => {
260 appearance.value = "dark";
261 for (const listener of appearance.listeners) listener();
262 });
263 await expect
264 .element(screen.getByAltText("Shot"))
265 .toHaveAttribute("src", `${pixel}#/work/dark.png`);
266});
267​
268it("sizes a raw HTML image by width and height written with px units", async () => {
269 setup();
270 const largeImage = `data:image/svg+xml,${encodeURIComponent(
271 '<svg xmlns="http://www.w3.org/2000/svg" width="200" height="200"/>',
272 )}`;
273 await using screen = await render(
274 <HostImageUrlContext value={() => largeImage}>
275 <ChatMarkdown
276 cwd={undefined}
277 parseRawHtml
278 text={
279 '### PR Review in progress <img src="/work/spinner.gif" alt="spinner" width="14px" height="7px" />'
280 }
281 />
282 </HostImageUrlContext>,
283 );
284 const image = screen.getByAltText("spinner");
285 await expect.element(image).toHaveAttribute("src", largeImage);
286 const element = image.element() as HTMLImageElement;
287 await element.decode();
288 const { width, height } = element.getBoundingClientRect();
289 expect({ width, height }).toEqual({ width: 14, height: 7 });
290});
291​
292it("reuses the parse of a streaming reply's finished blocks when it remounts", async () => {
293 setup();
294 const message = (
295 <ChatMarkdown cwd="/tmp/project" text={"Finished block\n\nStill growing"} isStreaming />
296 );
297 {
298 await using first = await render(
299 <ChatMarkdown cwd="/tmp/project" text={"Finished block\n\n"} isStreaming />,
300 );
301 await first.rerender(message);
302 }
303 await using screen = await render(message);
304 await expect.element(screen.getByText("Still growing")).toBeVisible();
305 expect(parsedSources.filter((source) => source.includes("Finished block"))).toHaveLength(1);
306});
307​
308it("reuses the parse of a remounted message that has stable extra plugins", async () => {
309 setup();
310 const parsed = vi.fn();
311 const countingPlugins = [() => () => void parsed()];
312 const message = (
313 <ChatMarkdown cwd="/tmp/project" text="Cached text" extraRemarkPlugins={countingPlugins} />
314 );
315 {
316 await using first = await render(
317 <ChatMarkdown
318 cwd="/tmp/project"
319 text="Cached text"
320 extraRemarkPlugins={countingPlugins}
321 isStreaming
322 />,
323 );
324 await first.rerender(message);
325 }
326 await using screen = await render(message);
327 await expect.element(screen.getByText("Cached text")).toBeVisible();
328 expect(parsed).toHaveBeenCalledTimes(1);
329 const changed = vi.fn();
330 await screen.rerender(
331 <ChatMarkdown
332 cwd="/tmp/project"
333 text="Cached text"
334 extraRemarkPlugins={[() => () => void changed()]}
335 />,
336 );
337 expect(changed).toHaveBeenCalledTimes(1);
338});
339​
340it("highlights a code block's own source when an earlier block of the same length was cached", async () => {
341 setup();
342 const highlightedText = (container: HTMLElement) =>
343 container.querySelector(".chat-markdown-shiki")?.textContent?.trim();
344 // These two lines share a 32-bit FNV-1a hash and a length.
345 const first = 'const commitSha = "f36a6d8fe0aa";';
346 const second = 'const commitSha = "cb06f8d135b3";';
347 // The block suspends until the shared highlighter loads, which can outlast vi.waitFor on a busy runner.
348 await getSyntaxHighlighterPromise("ts");
349 {
350 await using screen = await renderText(`\`\`\`ts\n${first}\n\`\`\``);
351 await vi.waitFor(() => expect(highlightedText(screen.container)).toBe(first));
352 }
353 await using screen = await renderText(`\`\`\`ts\n${second}\n\`\`\``);
354 await vi.waitFor(() => expect(highlightedText(screen.container)).toBe(second));
355});
356​
357describe("ChatMarkdown favicon privacy", () => {
358 it("suppresses private link images while preserving public links across updates", async () => {
359 setup();
360 const markdown = (url: string) => <ChatMarkdown cwd="/tmp/project" text={`[Link](${url})`} />;
361 await using screen = await render(markdown("https://example.com"));
362 const { container, rerender } = screen;
363 expect([...container.querySelectorAll("img")].map((image) => image.src)).toEqual([
364 "https://www.google.com/s2/favicons?domain=example.com&sz=32",
365 ]);
366 for (const url of ["http://192.168.1.10:8080", "http://localhost:3000", "http://home.arpa"]) {
367 await rerender(markdown(url));
368 expect(container.querySelectorAll("img")).toHaveLength(0);
369 }
370 await rerender(markdown("https://example.com"));
371 expect(container.querySelectorAll("img")).toHaveLength(1);
372 await rerender(markdown("https://github.com/pingdotgg/t3code/pull/1"));
373 expect(container.querySelectorAll("img")).toHaveLength(0);
374 expect(container.querySelector("a svg")).not.toBeNull();
375 });
376});
377​
378describe("ChatMarkdown external link labels", () => {
379 it("keeps a leading emoji whole", async () => {
380 setup();
381 await using screen = await render(
382 <ChatMarkdown cwd="/tmp/project" text="[πŸ˜€ Read the documentation](https://example.com)" />,
383 );
384 await vi.waitFor(() => {
385 const link = screen.container.querySelector("a");
386 expect(link?.textContent).toContain("πŸ˜€ Read");
387 const walker = document.createTreeWalker(link!, NodeFilter.SHOW_TEXT);
388 const textNodes: string[] = [];
389 while (walker.nextNode()) textNodes.push(walker.currentNode.nodeValue ?? "");
390 expect(textNodes.filter((node) => /\p{Surrogate}/u.test(node))).toEqual([]);
391 });
392 });
393});
394​
395describe("ChatMarkdown streaming", () => {
396 it("runs only a complete single-line shell block after a click", async () => {
397 setup();
398 const onRunShellCommand = vi.fn();
399 const message = (text: string, isStreaming = false) => (
400 <ChatMarkdown
401 cwd="/tmp/project"
402 text={text}
403 isStreaming={isStreaming}
404 onRunShellCommand={onRunShellCommand}
405 />
406 );
407 await using screen = await render(message("```bash\necho hello\n```", true));
408 const { container, rerender } = screen;
409 const runButtons = () => buttonsLabelled(container, "Run in terminal");
410 expect(runButtons()).toHaveLength(0);
411​
412 await rerender(message("```bash\necho hello\n```"));
413 await act(async () => runButtons()[0]!.click());
414 expect(onRunShellCommand).toHaveBeenCalledExactlyOnceWith("echo hello");
415​
416 for (const text of [
417 "~~~bash\necho tilde\n~~~",
418 "> ```bash\n> echo quote\n> ```",
419 "````bash\necho four\n````",
420 "- Command\n\n ```bash\n echo list\n ```",
421 "```bash\r\necho crlf\r\n```\r",
422 ]) {
423 await rerender(message(text));
424 expect(runButtons()).toHaveLength(1);
425 }
426​
427 for (const text of [
428 "```bash\necho one\necho two\n```",
429 "```typescript\necho hello\n```",
430 "```bash\n\n```",
431 "```bash\necho hello\n\n```",
432 "```bash\necho hello\\\n```",
433 "```bash\necho safe \u202e#\n```",
434 "```bash\necho incomplete",
435 "~~~bash\necho incomplete",
436 "````bash\necho incomplete\n```",
437 '<pre><code class="language-bash">echo html</code></pre>',
438 ]) {
439 await rerender(message(text));
440 expect(runButtons()).toHaveLength(0);
441 }
442 });
443​
444 it("edits the current task text and marker after reusing a renderer", async () => {
445 setup();
446 let editedText: string | undefined;
447 let rerender: (next: ReactElement) => Promise<void> = async () => {};
448 const message = (text: string): ReactElement => (
449 <ChatMarkdown
450 cwd="/tmp/project"
451 text={text}
452 onTaskListChange={({ markerOffset, checked }) => {
453 editedText = setMarkdownTaskChecked(text, markerOffset, checked);
454 void rerender(message(editedText));
455 }}
456 />
457 );
458 await using rendered = await render(message("- [ ] First\n- [ ] Second"));
459 rerender = rendered.rerender;
460 const { container } = rendered;
461 const checkboxes = () => container.querySelectorAll<HTMLInputElement>('input[type="checkbox"]');
462 const original = checkboxes()[1]!;
463 await rerender(message("- [ ] A longer first task\n- [ ] Second"));
464 expect(checkboxes()[1]).toBe(original);
465​
466 await act(async () => original.click());
467 expect(editedText).toBe("- [ ] A longer first task\n- [x] Second");
468 await vi.waitFor(() => expect(checkboxes()[1]!.checked).toBe(true));
469 await rerender(message("- [ ] A longer first task\n- [ ] Second"));
470 expect(checkboxes()[1]).toBe(original);
471 expect(checkboxes()[1]!.checked).toBe(false);
472 });
473​
474 it.each([
475 ["read-only", undefined],
476 ["editable", () => {}],
477 ])(
478 "unchecks the remaining %s task when the checked row above it is removed",
479 async (_, onTaskListChange) => {
480 setup();
481 const message = (text: string) => (
482 <ChatMarkdown cwd="/tmp/project" text={text} onTaskListChange={onTaskListChange} />
483 );
484 await using screen = await render(message("- [x] Completed item\n- [ ] Pending item"));
485 await screen.rerender(message("- [ ] Pending item"));
486 const checkboxes =
487 screen.container.querySelectorAll<HTMLInputElement>('input[type="checkbox"]');
488 expect(checkboxes).toHaveLength(1);
489 expect(checkboxes[0]!.checked).toBe(false);
490 },
491 );
492});
493​
494describe("ChatMarkdown workspace file opens", () => {
495 const threadRef = {
496 environmentId: EnvironmentId.make("workspace"),
497 threadId: ThreadId.make("thread"),
498 };
499​
500 it("keeps a newer absolute file open when an earlier repo-relative lookup finishes", async () => {
501 setup();
502 const result = AsyncResult.success({
503 entries: [{ path: "notes/a.md", kind: "file" }],
504 truncated: false,
505 });
506 let resolvePending!: (value: typeof result) => void;
507 const pending = new Promise<typeof result>((resolve) => {
508 resolvePending = resolve;
509 });
510 workspaceSearch.mockReturnValueOnce(pending);
511 using openFile = vi
512 .spyOn(useRightPanelStore.getState(), "openFile")
513 .mockImplementation(() => {});
514 await using screen = await renderText(
515 "[Notes](physics/notes/a.md) and [Other](/elsewhere/b.md:9)",
516 {
517 cwd: "/school/physics",
518 threadRef,
519 },
520 );
521 const { container } = screen;
522 const [notes, other] = container.querySelectorAll("a");
523 await act(async () => notes!.click());
524 expect(workspaceSearch).toHaveBeenCalledOnce();
525 expect(openFile).not.toHaveBeenCalled();
526​
527 await act(async () => other!.click());
528 await act(async () => resolvePending(result));
529​
530 expect(openFile).toHaveBeenCalledExactlyOnceWith(threadRef, "/elsewhere/b.md", 9);
531 expect(workspaceSearch).toHaveBeenCalledOnce();
532 });
533});
534​
535describe("ChatMarkdown skill chips", () => {
536 it("shows the skill's details and opens its instructions, closing the details", async () => {
537 setup();
538 const threadRef = {
539 environmentId: EnvironmentId.make("workspace"),
540 threadId: ThreadId.make("thread"),
541 };
542 await using screen = await renderText("Run $review now", {
543 threadRef,
544 skills: [
545 {
546 name: "review",
547 displayName: "Review",
548 description: "Reviews the current branch.",
549 path: "/skills/review/SKILL.md",
550 enabled: true,
551 },
552 ],
553 });
554 using openFile = vi
555 .spyOn(useRightPanelStore.getState(), "openFile")
556 .mockImplementation(() => {});
557​
558 await userEvent.click(screen.getByRole("button", { name: "Skill Review. Show details" }));
559 await expect.element(page.getByText("Reviews the current branch.")).toBeVisible();
560 await userEvent.click(page.getByRole("button", { name: "View instructions" }));
561​
562 expect(openFile).toHaveBeenCalledExactlyOnceWith(threadRef, "/skills/review/SKILL.md");
563 await expect.element(page.getByText("Reviews the current branch.")).not.toBeInTheDocument();
564 });
565​
566 it("names a mentioned model as its provider does, without a thread", async () => {
567 setup();
568 await using screen = await renderText("Ask (model:codex/gpt-6.1), not model:openai/gpt-4o.", {
569 environmentId: EnvironmentId.make("models"),
570 });
571​
572 await expect
573 .element(screen.getByRole("button", { name: "Model GPT-6.1. Show details" }))
574 .toBeVisible();
575 expect(buttonsLabelled(screen.container, "Model gpt-4o. Show details")).toEqual([]);
576 expect(screen.container.textContent).toBe("Ask (GPT-6.1), not model:openai/gpt-4o.");
577 });
578});
579​
580describe("ChatMarkdown headings", () => {
581 it("keeps insight streaming, reference links, and heading anchors in one message", async () => {
582 setup();
583 const rule = "─".repeat(20);
584 const text = `## Setup\n\nBefore [source][src].\n\nβ˜… Insight ${rule}\nA **streaming** note.`;
585 const message = (text: string, isStreaming: boolean) => (
586 <ChatMarkdown
587 cwd={undefined}
588 text={text}
589 renderInsights
590 lineBreaks
591 isStreaming={isStreaming}
592 />
593 );
594 await using screen = await render(message(text, true));
595 await expect.element(screen.getByRole("note")).toHaveTextContent("Insight A streaming note.");
596 await screen.rerender(
597 message(
598 `${text}\n${rule}\n\n## Setup\n\nAfter [source][src].\n\n[src]:\n https://example.com`,
599 false,
600 ),
601 );
602 await expect.element(screen.getByRole("note")).toHaveTextContent("Insight A streaming note.");
603 expect([...screen.container.querySelectorAll("h2")].map((heading) => heading.id)).toEqual([
604 "user-content-setup",
605 "user-content-setup-1",
606 ]);
607 expect(
608 [...screen.container.querySelectorAll("a")].filter(
609 (link) => link.href === "https://example.com/",
610 ),
611 ).toHaveLength(2);
612 await expect.element(screen.getByRole("note")).not.toHaveTextContent("After");
613 });
614​
615 it("never gives two headings the same id, even when a suffix matches another heading", async () => {
616 setup();
617 await using screen = await renderText(
618 '## Setup\n\n## Setup\n\n## Setup-1\n\n<h2 id="install-1">Pinned</h2>\n\n## Install\n\n## Install',
619 { parseRawHtml: true },
620 );
621 const { container } = screen;
622 expect([...container.querySelectorAll("h2")].map((heading) => heading.id)).toEqual([
623 "user-content-setup",
624 "user-content-setup-1",
625 "user-content-setup-1-1",
626 "user-content-install-1",
627 "user-content-install",
628 "user-content-install-2",
629 ]);
630 });
631});
632​
633describe("ChatMarkdown inline code selection", () => {
634 it("selects only a word on double-click in inline and fenced code", async () => {
635 setup();
636 await using screen = await renderText(
637 "Run `migration-gate --dry-run` first.\n\n```txt\nfenced-block word\n```",
638 );
639 await userEvent.dblClick(screen.getByText("migration-gate --dry-run"), {
640 position: { x: 12, y: 8 },
641 });
642 expect(window.getSelection()?.toString()).toBe("migration");
643​
644 window.getSelection()?.removeAllRanges();
645 const fenced = screen.container.querySelector("pre code")!;
646 await userEvent.dblClick(fenced, { position: { x: 4, y: 4 } });
647 expect(window.getSelection()?.toString()).toBe("fenced");
648 });
649​
650 it("selects the whole line on triple-click beside a favicon link or a file chip", async () => {
651 setup();
652 await using screen = await renderText(
653 "Before [docs](https://example.com/docs) after words\n\nBefore [App.tsx](/tmp/project/src/App.tsx) after words",
654 );
655 const tripleClickWord = async (paragraph: HTMLElement, word: string) => {
656 const text = [...paragraph.childNodes].find((node) => node.textContent?.includes(word))!;
657 const range = document.createRange();
658 range.setStart(text, text.textContent!.indexOf(word));
659 range.setEnd(text, text.textContent!.indexOf(word) + word.length);
660 const wordBox = range.getBoundingClientRect();
661 const paragraphBox = paragraph.getBoundingClientRect();
662 window.getSelection()?.removeAllRanges();
663 await userEvent.tripleClick(paragraph, {
664 position: {
665 x: wordBox.left - paragraphBox.left + wordBox.width / 2,
666 y: wordBox.top - paragraphBox.top + wordBox.height / 2,
667 },
668 });
669 return window.getSelection()?.toString().trim();
670 };
671​
672 const paragraphs = screen.container.querySelectorAll("p");
673 expect(paragraphs).toHaveLength(2);
674 const selections = [];
675 const lines = [];
676 for (const paragraph of paragraphs) {
677 lines.push(paragraph.textContent?.trim(), paragraph.textContent?.trim());
678 selections.push(
679 await tripleClickWord(paragraph, "Before"),
680 await tripleClickWord(paragraph, "after"),
681 );
682 }
683 expect(selections).toEqual(lines);
684 });
685});
686​
687describe("ChatMarkdown copy", () => {
688 it("copies a fully selected callout as alert Markdown and a partial one as text", async () => {
689 setup();
690 await using screen = await renderText("> [!WARNING]\n> Back up first.");
691 const [label, body] = screen.container.querySelectorAll('[role="note"] > p');
692 const select = (startNode: Node, endNode: Node, endOffset: number) => {
693 const range = document.createRange();
694 range.setStart(startNode, 0);
695 range.setEnd(endNode, endOffset);
696 const selection = window.getSelection()!;
697 selection.removeAllRanges();
698 selection.addRange(range);
699 return chatMarkdownClipboardPayload(selection)?.text;
700 };
701 const labelText = label!.lastChild!;
702 const bodyText = body!.firstChild!;
703​
704 expect(select(labelText, bodyText, bodyText.textContent!.length)).toBe(
705 "> [!WARNING]\n> Back up first.",
706 );
707 expect(select(labelText, bodyText, "Back up".length)).toBe("Warning\n\nBack up");
708 });
709​
710 it.each([
711 { text: " Plan\nnext" },
712 { text: "Plan\n Deep\n Deeper" },
713 { text: "Plan\n\tTabbed\n \t Mixed" },
714 { text: "- item\n more\n deeper\n- next" },
715 { text: "Plan\n Step one\n Detail a", from: "Step one" },
716 ])(
717 "copies and selects user lines the same whether their typed indentation shows: $text",
718 async (copy) => {
719 setup();
720 const copied = async (extraRemarkPlugins: typeof CHAT_USER_MARKDOWN_REMARK_PLUGINS) => {
721 await using screen = await renderText(copy.text, {
722 className: "user-message-markdown",
723 lineBreaks: true,
724 parseRawHtml: false,
725 extraRemarkPlugins,
726 });
727 const range = document.createRange();
728 range.selectNodeContents(screen.container);
729 if (copy.from) {
730 const walker = document.createTreeWalker(screen.container, NodeFilter.SHOW_TEXT);
731 let line = walker.nextNode();
732 while (line && !line.textContent!.includes(copy.from)) line = walker.nextNode();
733 // Start mid-line, three characters into the line's text.
734 range.setStart(line!, line!.textContent!.indexOf(copy.from) + 3);
735 }
736 const selection = window.getSelection()!;
737 selection.removeAllRanges();
738 selection.addRange(range);
739 // A drag or anything else that reads the selection gets its text, not the copy payload.
740 return { payload: chatMarkdownClipboardPayload(selection), selected: selection.toString() };
741 };
742 const shown = await copied(CHAT_USER_MARKDOWN_REMARK_PLUGINS);
743 // The user pipeline as it was before typed indentation was shown.
744 expect(shown).toEqual(await copied([[remarkGfm, { singleTilde: false }]]));
745 },
746 );
747​
748 it("copies part of inline code without prose escapes", async () => {
749 setup();
750 await using screen = await renderText("Read `items[0]*_x` and a*b*c.");
751 const code = screen.container.querySelector("p code")!.firstChild!;
752 const range = document.createRange();
753 range.setStart(code, 0);
754 range.setEnd(code, "items[0]*_".length);
755 const selection = window.getSelection()!;
756 selection.removeAllRanges();
757 selection.addRange(range);
758 expect(chatMarkdownClipboardPayload(selection)?.text).toBe("items[0]*_");
759 });
760​
761 it.each([
762 {
763 source: "10. First\n11. Second\n12. Third\n\nAfter.",
764 from: "Second",
765 text: "11. Second\n12. Third\n\nAfter.",
766 },
767 {
768 source: "1. A\n2. B\n7. C\n8. D\n\nAfter.",
769 from: "D",
770 userMessage: true,
771 text: "8. D\n\nAfter.",
772 },
773 {
774 source: "1. Outer\n2. Next\n 1. Inner\n 2. Deeper\n\nAfter.",
775 from: "Deeper",
776 text: "2. 2. Deeper\n\nAfter.",
777 },
778 ])(
779 "keeps the shown numbers when a copy starts at $from and ends past the list",
780 async ({ source, from, userMessage, text }) => {
781 setup();
782 await using screen = await renderText(
783 source,
784 userMessage ? { extraRemarkPlugins: SOURCE_NUMBER_PLUGINS } : {},
785 );
786 const start = [...screen.container.querySelectorAll("li")]
787 .flatMap((item) => [...item.childNodes])
788 .find((node) => node.nodeType === Node.TEXT_NODE && node.textContent === from)!;
789 const after = [...screen.container.querySelectorAll("p")].at(-1)!.firstChild!;
790 const range = document.createRange();
791 range.setStart(start, 0);
792 range.setEnd(after, after.textContent!.length);
793 const selection = window.getSelection()!;
794 selection.removeAllRanges();
795 selection.addRange(range);
796 const payload = chatMarkdownClipboardPayload(selection);
797 expect(payload?.text).toBe(text);
798 // Rich paste numbers its list from the same start.
799 expect(
800 new DOMParser()
801 .parseFromString(payload!.html, "text/html")
802 .querySelector("li")
803 ?.closest("ol")?.start,
804 ).toBe(Number(text.split(".")[0]));
805 },
806 );
807});
808​
809describe("ChatMarkdown file chip tooltips", () => {
810 it("wraps a long path so its file name stays inside the tooltip", async () => {
811 setup();
812 const path =
813 "/tmp/project/packages/client-runtime/src/state/generated/environment-connection-handshake-retry-policy-fixtures.ts";
814 await using screen = await renderText(`See [the fixtures](${path}).`);
815​
816 await userEvent.hover(screen.container.querySelector(".chat-markdown-file-link")!);
817 const tooltip = page.getByText(path);
818 await expect.element(tooltip).toBeVisible();
819​
820 const popup = tooltip.element().closest("[data-side]")!;
821 const pathEnd = document.createRange();
822 pathEnd.selectNodeContents(tooltip.element());
823 expect(pathEnd.getBoundingClientRect().right).toBeLessThanOrEqual(
824 popup.getBoundingClientRect().right,
825 );
826 });
827});
828​
829describe("ChatMarkdown editor deep links", () => {
830 const hrefs = (container: HTMLElement) =>
831 [...container.querySelectorAll("a")].map((link) => link.getAttribute("href"));
832​
833 it("keeps local editor file links", async () => {
834 setup();
835 await using screen = await renderText(
836 "[file.md line 3](cursor://file/Users/me/repo/file.md:3) and [same](vscode://file/Users/me/repo/file.md:3:7)",
837 );
838 expect(hrefs(screen.container)).toEqual([
839 "cursor://file/Users/me/repo/file.md:3",
840 "vscode://file/Users/me/repo/file.md:3:7",
841 ]);
842 });
843​
844 it("still drops other editor links and unknown schemes", async () => {
845 setup();
846 await using screen = await renderText(
847 "[prompt](cursor://anysphere.cursor-deeplink/prompt?text=hi) [user](cursor://me@file/Users/me/file.md) [unknown](foo://file/Users/me/file.md)",
848 );
849 expect(screen.container.innerHTML).not.toContain("://");
850 expect(hrefs(screen.container).filter(Boolean)).toEqual([]);
851 });
852});
853​
854describe("ChatMarkdown Windows file links", () => {
855 const environmentId = EnvironmentId.make("env-windows");
856 const renderWindows = (text: string, parseRawHtml: boolean) =>
857 renderText(text, {
858 cwd: "C:/Users/shawn/project",
859 environmentId,
860 lineBreaks: !parseRawHtml,
861 parseRawHtml,
862 });
863 const fileHrefs = (container: HTMLElement) =>
864 [...container.querySelectorAll(".chat-markdown-file-link")].map((chip) =>
865 chip.getAttribute("href"),
866 );
867​
868 it("still rejects unsafe schemes", async () => {
869 setup();
870 for (const parseRawHtml of [true, false]) {
871 await using screen = await renderWindows(
872 "[unsafe](javascript:alert(1)) and [unknown](d:alert(1))",
873 parseRawHtml,
874 );
875 const { container } = screen;
876 expect(container.innerHTML).not.toContain("javascript:");
877 expect(container.innerHTML).not.toContain("d:alert");
878 expect(fileHrefs(container)).toEqual([]);
879 }
880 });
881});
882​
883describe("ChatMarkdown host media", () => {
884 it("explains a host video the connection cannot read instead of offering a retry", async () => {
885 setup();
886 await using screen = await renderText("![Demo](/tmp/demo.mp4)", {
887 threadRef: {
888 environmentId: EnvironmentId.make(deniedEnvironmentId),
889 threadId: ThreadId.make("thread"),
890 },
891 });
892 await vi.waitFor(() =>
893 expect(screen.container.textContent).toContain(MISSING_FILE_ACCESS_MESSAGE),
894 );
895 expect(screen.container.textContent).not.toContain("Retry video");
896 });
897});