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