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