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("reuses the parse of a streaming reply's finished blocks when it remounts", async () => {
319 setup();
320 const message = (
321 <ChatMarkdown cwd="/tmp/project" text={"Finished block\n\nStill growing"} isStreaming />
322 );
323 {
324 await using first = await render(
325 <ChatMarkdown cwd="/tmp/project" text={"Finished block\n\n"} isStreaming />,
326 );
327 await first.rerender(message);
328 }
329 await using screen = await render(message);
330 await expect.element(screen.getByText("Still growing")).toBeVisible();
331 expect(parsedSources.filter((source) => source.includes("Finished block"))).toHaveLength(1);
332});
333β
334it("reuses the parse of a remounted message that has stable extensions", async () => {
335 setup();
336 const extensions = { userMessage: true };
337 const message = <ChatMarkdown cwd="/tmp/project" text="Cached text" extensions={extensions} />;
338 {
339 await using first = await render(
340 <ChatMarkdown cwd="/tmp/project" text="Cached text" extensions={extensions} isStreaming />,
341 );
342 await first.rerender(message);
343 }
344 await using screen = await render(message);
345 await expect.element(screen.getByText("Cached text")).toBeVisible();
346 const parses = () => parsedSources.filter((source) => source === "Cached text").length;
347 expect(parses()).toBe(1);
348 await screen.rerender(
349 <ChatMarkdown cwd="/tmp/project" text="Cached text" extensions={{ userMessage: true }} />,
350 );
351 expect(parses()).toBe(2);
352});
353β
354it("highlights a code block's own source when an earlier block of the same length was cached", async () => {
355 setup();
356 const highlightedText = (container: HTMLElement) =>
357 container.querySelector(".chat-markdown-shiki")?.textContent?.trim();
358 // These two lines share a 32-bit FNV-1a hash and a length.
359 const first = 'const commitSha = "f36a6d8fe0aa";';
360 const second = 'const commitSha = "cb06f8d135b3";';
361 // The block suspends until the shared highlighter loads, which can outlast vi.waitFor on a busy runner.
362 await getSyntaxHighlighterPromise("ts");
363 {
364 await using screen = await renderText(`\`\`\`ts\n${first}\n\`\`\``);
365 await vi.waitFor(() => expect(highlightedText(screen.container)).toBe(first));
366 }
367 await using screen = await renderText(`\`\`\`ts\n${second}\n\`\`\``);
368 await vi.waitFor(() => expect(highlightedText(screen.container)).toBe(second));
369});
370β
371describe("ChatMarkdown favicon privacy", () => {
372 it("suppresses private link images while preserving public links across updates", async () => {
373 setup();
374 const markdown = (url: string) => <ChatMarkdown cwd="/tmp/project" text={`[Link](${url})`} />;
375 await using screen = await render(markdown("https://example.com"));
376 const { container, rerender } = screen;
377 expect([...container.querySelectorAll("img")].map((image) => image.src)).toEqual([
378 "https://www.google.com/s2/favicons?domain=example.com&sz=32",
379 ]);
380 for (const url of ["http://192.168.1.10:8080", "http://localhost:3000", "http://home.arpa"]) {
381 await rerender(markdown(url));
382 expect(container.querySelectorAll("img")).toHaveLength(0);
383 }
384 await rerender(markdown("https://example.com"));
385 expect(container.querySelectorAll("img")).toHaveLength(1);
386 await rerender(markdown("https://github.com/pingdotgg/t3code/pull/1"));
387 expect(container.querySelectorAll("img")).toHaveLength(0);
388 expect(container.querySelector("a svg")).not.toBeNull();
389 });
390});
391β
392describe("ChatMarkdown external link labels", () => {
393 it("keeps a leading emoji whole", async () => {
394 setup();
395 await using screen = await render(
396 <ChatMarkdown cwd="/tmp/project" text="[π Read the documentation](https://example.com)" />,
397 );
398 await vi.waitFor(() => {
399 const link = screen.container.querySelector("a");
400 expect(link?.textContent).toContain("π Read");
401 const walker = document.createTreeWalker(link!, NodeFilter.SHOW_TEXT);
402 const textNodes: string[] = [];
403 while (walker.nextNode()) textNodes.push(walker.currentNode.nodeValue ?? "");
404 expect(textNodes.filter((node) => /\p{Surrogate}/u.test(node))).toEqual([]);
405 });
406 });
407});
408β
409describe("ChatMarkdown link tooltips", () => {
410 it("shows each link's address on one shared tooltip as the pointer moves between links", async () => {
411 setup();
412 await using screen = await render(
413 <ChatMarkdown
414 cwd="/tmp/project"
415 text="[First](https://example.com/a) and [Second](https://example.org/b)"
416 />,
417 );
418 await userEvent.hover(screen.getByRole("link", { name: /First/ }));
419 await expect.element(page.getByText("https://example.com/a")).toBeVisible();
420 await userEvent.hover(screen.getByRole("link", { name: /Second/ }));
421 await expect.element(page.getByText("https://example.org/b")).toBeVisible();
422 expect(document.querySelectorAll('[data-slot="tooltip-popup"]')).toHaveLength(1);
423 });
424});
425β
426describe("ChatMarkdown details", () => {
427 it("opens collapsed details by click, and by keyboard without losing focus", async () => {
428 setup();
429 await using screen = await render(
430 <ChatMarkdown
431 cwd="/tmp/project"
432 text={
433 "<details><summary>First</summary>\n\nHidden one\n\n</details>\n\n<details><summary>Second</summary>\n\nHidden two\n\n</details>"
434 }
435 />,
436 );
437 await userEvent.click(screen.getByRole("button", { name: "First" }));
438 await expect.element(screen.getByText("Hidden one")).toBeVisible();
439 await userEvent.tab();
440 const second = screen.getByRole("button", { name: "Second" });
441 await expect.element(second).toHaveFocus();
442 await userEvent.keyboard("{Enter}");
443 await expect.element(screen.getByText("Hidden two")).toBeVisible();
444 await expect.element(screen.getByRole("button", { name: "Second" })).toHaveFocus();
445 });
446});
447β
448describe("ChatMarkdown streaming", () => {
449 it("runs only a complete single-line shell block after a click", async () => {
450 setup();
451 const onRunShellCommand = vi.fn();
452 const message = (text: string, isStreaming = false) => (
453 <ChatMarkdown
454 cwd="/tmp/project"
455 text={text}
456 isStreaming={isStreaming}
457 onRunShellCommand={onRunShellCommand}
458 />
459 );
460 await using screen = await render(message("```bash\necho hello\n```", true));
461 const { container, rerender } = screen;
462 const runButtons = () => buttonsLabelled(container, "Run in terminal");
463 expect(runButtons()).toHaveLength(0);
464β
465 await rerender(message("```bash\necho hello\n```"));
466 await act(async () => runButtons()[0]!.click());
467 expect(onRunShellCommand).toHaveBeenCalledExactlyOnceWith("echo hello");
468β
469 for (const text of [
470 "~~~bash\necho tilde\n~~~",
471 "> ```bash\n> echo quote\n> ```",
472 "````bash\necho four\n````",
473 "- Command\n\n ```bash\n echo list\n ```",
474 "```bash\r\necho crlf\r\n```\r",
475 ]) {
476 await rerender(message(text));
477 expect(runButtons()).toHaveLength(1);
478 }
479β
480 for (const text of [
481 "```bash\necho one\necho two\n```",
482 "```typescript\necho hello\n```",
483 "```bash\n\n```",
484 "```bash\necho hello\n\n```",
485 "```bash\necho hello\\\n```",
486 "```bash\necho safe \u202e#\n```",
487 "```bash\necho incomplete",
488 "~~~bash\necho incomplete",
489 "````bash\necho incomplete\n```",
490 '<pre><code class="language-bash">echo html</code></pre>',
491 ]) {
492 await rerender(message(text));
493 expect(runButtons()).toHaveLength(0);
494 }
495 });
496β
497 it("edits the current task text and marker after reusing a renderer", async () => {
498 setup();
499 let editedText: string | undefined;
500 let rerender: (next: ReactElement) => Promise<void> = async () => {};
501 const message = (text: string): ReactElement => (
502 <ChatMarkdown
503 cwd="/tmp/project"
504 text={text}
505 onTaskListChange={({ markerOffset, checked }) => {
506 editedText = setMarkdownTaskChecked(text, markerOffset, checked);
507 void rerender(message(editedText));
508 }}
509 />
510 );
511 await using rendered = await render(message("- [ ] First\n- [ ] Second"));
512 rerender = rendered.rerender;
513 const { container } = rendered;
514 const checkboxes = () => container.querySelectorAll<HTMLInputElement>('input[type="checkbox"]');
515 const original = checkboxes()[1]!;
516 await rerender(message("- [ ] A longer first task\n- [ ] Second"));
517 expect(checkboxes()[1]).toBe(original);
518β
519 await act(async () => original.click());
520 expect(editedText).toBe("- [ ] A longer first task\n- [x] Second");
521 await vi.waitFor(() => expect(checkboxes()[1]!.checked).toBe(true));
522 await rerender(message("- [ ] A longer first task\n- [ ] Second"));
523 expect(checkboxes()[1]).toBe(original);
524 expect(checkboxes()[1]!.checked).toBe(false);
525 });
526β
527 it.each([
528 ["read-only", undefined],
529 ["editable", () => {}],
530 ])(
531 "unchecks the remaining %s task when the checked row above it is removed",
532 async (_, onTaskListChange) => {
533 setup();
534 const message = (text: string) => (
535 <ChatMarkdown cwd="/tmp/project" text={text} onTaskListChange={onTaskListChange} />
536 );
537 await using screen = await render(message("- [x] Completed item\n- [ ] Pending item"));
538 await screen.rerender(message("- [ ] Pending item"));
539 const checkboxes =
540 screen.container.querySelectorAll<HTMLInputElement>('input[type="checkbox"]');
541 expect(checkboxes).toHaveLength(1);
542 expect(checkboxes[0]!.checked).toBe(false);
543 },
544 );
545});
546β
547describe("ChatMarkdown workspace file opens", () => {
548 const threadRef = {
549 environmentId: EnvironmentId.make("workspace"),
550 threadId: ThreadId.make("thread"),
551 };
552β
553 it("keeps a newer absolute file open when an earlier repo-relative lookup finishes", async () => {
554 setup();
555 const result = AsyncResult.success({
556 entries: [{ path: "notes/a.md", kind: "file" }],
557 truncated: false,
558 });
559 let resolvePending!: (value: typeof result) => void;
560 const pending = new Promise<typeof result>((resolve) => {
561 resolvePending = resolve;
562 });
563 workspaceSearch.mockReturnValueOnce(pending);
564 using openFile = vi.spyOn(useRightPanelStore.getState(), "openFile");
565 await using screen = await renderText(
566 "[Notes](physics/notes/a.md) and [Other](/elsewhere/b.md:9)",
567 {
568 cwd: "/school/physics",
569 threadRef,
570 },
571 );
572 const { container } = screen;
573 const [notes, other] = container.querySelectorAll("a");
574 await act(async () => notes!.click());
575 expect(workspaceSearch).toHaveBeenCalledOnce();
576 expect(openFile).not.toHaveBeenCalled();
577β
578 await act(async () => other!.click());
579 await act(async () => resolvePending(result));
580β
581 expect(openFile).toHaveBeenCalledExactlyOnceWith(threadRef, "/elsewhere/b.md", 9);
582 expect(workspaceSearch).toHaveBeenCalledOnce();
583 });
584β
585 it("opens a path from markdown rendered in another checkout under that checkout", async () => {
586 setup();
587 const scratchThread = { ...threadRef, threadId: ThreadId.make("scratch-thread") };
588 threadWorktrees.set(scratchThread.threadId, "/scratch/thread");
589 filesystemMetadata.mockResolvedValue(AsyncResult.success({ entries: [{ kind: "file" }] }));
590 using openFile = vi.spyOn(useRightPanelStore.getState(), "openFile");
591 await using screen = await renderText("[State](packages/state/filesystem.ts)", {
592 cwd: "/repo-a",
593 threadRef: scratchThread,
594 });
595 await act(async () => screen.container.querySelector("a")!.click());
596β
597 await vi.waitFor(() =>
598 expect(openFile).toHaveBeenCalledExactlyOnceWith(
599 scratchThread,
600 "/repo-a/packages/state/filesystem.ts",
601 undefined,
602 ),
603 );
604 });
605β
606 it.each([
607 ["its own panel", "thread-own-panel", false],
608 ["its parent's panel from a side chat", "thread-side-chat", true],
609 ])(
610 "keeps a file opened elsewhere in %s when an earlier link lookup finishes",
611 async (_, threadId, sideChat) => {
612 setup();
613 const host = { environmentId: threadRef.environmentId, threadId: ThreadId.make(threadId) };
614 const linkRef = sideChat ? { ...host, threadId: ThreadId.make(`${threadId}-guest`) } : host;
615 using _hosted = { [Symbol.dispose]: sideChat ? hostRightPanel(linkRef, host) : () => {} };
616 const result = AsyncResult.success({
617 entries: [{ path: "notes/cited-note.txt", kind: "file" }],
618 truncated: false,
619 });
620 const { promise: pending, resolve: resolvePending } = Promise.withResolvers<typeof result>();
621 workspaceSearch.mockReturnValueOnce(pending);
622 await using screen = await renderText("[Cited](cited-note.txt)", {
623 cwd: "/repo",
624 threadRef: linkRef,
625 });
626 await act(async () => screen.container.querySelector("a")!.click());
627 expect(workspaceSearch).toHaveBeenCalledOnce();
628β
629 useRightPanelStore.getState().openFile(host, "picker-note.txt");
630 await act(async () => resolvePending(result));
631β
632 expect(
633 selectActiveRightPanelSurface(useRightPanelStore.getState().byThreadKey, host),
634 ).toMatchObject({ kind: "file", relativePath: "picker-note.txt" });
635 },
636 );
637β
638 it.each([
639 ["open a link in another panel", "separate-panels"],
640 ["unhost the side chat", "unhosted-side-chat"],
641 ] as const)("keeps a citation in its original panel scope if you %s", async (action, scope) => {
642 setup();
643 const host = { ...threadRef, threadId: ThreadId.make(`${scope}-host`) };
644 const guest = { ...threadRef, threadId: ThreadId.make(`${scope}-guest`) };
645 const other = { ...threadRef, threadId: ThreadId.make(`${scope}-other`) };
646 const unhost = hostRightPanel(guest, host);
647 using _hosted = { [Symbol.dispose]: unhost };
648 const result = AsyncResult.success({
649 entries: [{ path: "notes/cited-note.txt", kind: "file" }],
650 truncated: false,
651 });
652 const { promise: pending, resolve: resolvePending } = Promise.withResolvers<typeof result>();
653 workspaceSearch.mockReturnValueOnce(pending);
654 await using screen = await render(
655 <>
656 <ChatMarkdown cwd="/repo" threadRef={guest} text="[Cited](cited-note.txt)" />
657 <ChatMarkdown cwd="/repo" threadRef={other} text="[Other](/elsewhere/other.md)" />
658 </>,
659 );
660 const [cited, otherLink] = screen.container.querySelectorAll("a");
661 await act(async () => cited!.click());
662 expect(workspaceSearch).toHaveBeenCalledOnce();
663 if (action === "open a link in another panel") {
664 await act(async () => otherLink!.click());
665 } else {
666 unhost();
667 }
668 await act(async () => resolvePending(result));
669β
670 const { byThreadKey } = useRightPanelStore.getState();
671 expect(selectActiveRightPanelSurface(byThreadKey, guest)).toBeNull();
672 if (action === "unhost the side chat") {
673 expect(selectActiveRightPanelSurface(byThreadKey, host)).toBeNull();
674 } else {
675 expect(selectActiveRightPanelSurface(byThreadKey, host)).toMatchObject({
676 kind: "file",
677 relativePath: "notes/cited-note.txt",
678 });
679 expect(selectActiveRightPanelSurface(byThreadKey, other)).toMatchObject({
680 kind: "file",
681 relativePath: "/elsewhere/other.md",
682 });
683 }
684 });
685});
686β
687describe("ChatMarkdown skill chips", () => {
688 it("shows the skill's details and opens its instructions, closing the details", async () => {
689 setup();
690 const threadRef = {
691 environmentId: EnvironmentId.make("workspace"),
692 threadId: ThreadId.make("thread"),
693 };
694 await using screen = await renderText("Run $review now", {
695 threadRef,
696 skills: [
697 {
698 name: "review",
699 displayName: "Review",
700 description: "Reviews the current branch.",
701 path: "/skills/review/SKILL.md",
702 enabled: true,
703 },
704 ],
705 });
706 using openFile = vi
707 .spyOn(useRightPanelStore.getState(), "openFile")
708 .mockImplementation(() => {});
709β
710 await userEvent.click(screen.getByRole("button", { name: "Skill Review. Show details" }));
711 await expect.element(page.getByText("Reviews the current branch.")).toBeVisible();
712 await userEvent.click(page.getByRole("button", { name: "View instructions" }));
713β
714 expect(openFile).toHaveBeenCalledExactlyOnceWith(threadRef, "/skills/review/SKILL.md");
715 await expect.element(page.getByText("Reviews the current branch.")).not.toBeInTheDocument();
716 });
717β
718 it("names a mentioned model as its provider does, without a thread", async () => {
719 setup();
720 await using screen = await renderText("Ask (model:codex/gpt-6.1), not model:openai/gpt-4o.", {
721 environmentId: EnvironmentId.make("models"),
722 });
723β
724 await expect
725 .element(screen.getByRole("button", { name: "Model GPT-6.1. Show details" }))
726 .toBeVisible();
727 expect(buttonsLabelled(screen.container, "Model gpt-4o. Show details")).toEqual([]);
728 expect(screen.container.textContent).toBe("Ask (GPT-6.1), not model:openai/gpt-4o.");
729 });
730});
731β
732describe("ChatMarkdown headings", () => {
733 it("keeps insight streaming, reference links, and heading anchors in one message", async () => {
734 setup();
735 const rule = "β".repeat(20);
736 const text = `## Setup\n\nBefore [source][src].\n\nβ
Insight ${rule}\nA **streaming** note.`;
737 const message = (text: string, isStreaming: boolean) => (
738 <ChatMarkdown
739 cwd={undefined}
740 text={text}
741 renderInsights
742 lineBreaks
743 isStreaming={isStreaming}
744 />
745 );
746 await using screen = await render(message(text, true));
747 await expect.element(screen.getByRole("note")).toHaveTextContent("Insight A streaming note.");
748 await screen.rerender(
749 message(
750 `${text}\n${rule}\n\n## Setup\n\nAfter [source][src].\n\n[src]:\n https://example.com`,
751 false,
752 ),
753 );
754 await expect.element(screen.getByRole("note")).toHaveTextContent("Insight A streaming note.");
755 expect([...screen.container.querySelectorAll("h2")].map((heading) => heading.id)).toEqual([
756 "user-content-setup",
757 "user-content-setup-1",
758 ]);
759 expect(
760 [...screen.container.querySelectorAll("a")].filter(
761 (link) => link.href === "https://example.com/",
762 ),
763 ).toHaveLength(2);
764 await expect.element(screen.getByRole("note")).not.toHaveTextContent("After");
765 });
766β
767 it("never gives two headings the same id, even when a suffix matches another heading", async () => {
768 setup();
769 await using screen = await renderText(
770 '## Setup\n\n## Setup\n\n## Setup-1\n\n<h2 id="install-1">Pinned</h2>\n\n## Install\n\n## Install',
771 { parseRawHtml: true },
772 );
773 const { container } = screen;
774 expect([...container.querySelectorAll("h2")].map((heading) => heading.id)).toEqual([
775 "user-content-setup",
776 "user-content-setup-1",
777 "user-content-setup-1-1",
778 "user-content-install-1",
779 "user-content-install",
780 "user-content-install-2",
781 ]);
782 });
783});
784β
785describe("ChatMarkdown inline code selection", () => {
786 it("selects only a word on double-click in inline and fenced code", async () => {
787 setup();
788 await using screen = await renderText(
789 "Run `migration-gate --dry-run` first.\n\n```txt\nfenced-block word\n```",
790 );
791 await userEvent.dblClick(screen.getByText("migration-gate --dry-run"), {
792 position: { x: 12, y: 8 },
793 });
794 expect(window.getSelection()?.toString()).toBe("migration");
795β
796 window.getSelection()?.removeAllRanges();
797 const fenced = screen.container.querySelector("pre code")!;
798 await userEvent.dblClick(fenced, { position: { x: 4, y: 4 } });
799 expect(window.getSelection()?.toString()).toBe("fenced");
800 });
801β
802 it("selects the whole line on triple-click beside a favicon link or a file chip", async () => {
803 setup();
804 await using screen = await renderText(
805 "Before [docs](https://example.com/docs) after words\n\nBefore [App.tsx](/tmp/project/src/App.tsx) after words",
806 );
807 const tripleClickWord = async (paragraph: HTMLElement, word: string) => {
808 const text = [...paragraph.childNodes].find((node) => node.textContent?.includes(word))!;
809 const range = document.createRange();
810 range.setStart(text, text.textContent!.indexOf(word));
811 range.setEnd(text, text.textContent!.indexOf(word) + word.length);
812 const wordBox = range.getBoundingClientRect();
813 const paragraphBox = paragraph.getBoundingClientRect();
814 window.getSelection()?.removeAllRanges();
815 await userEvent.tripleClick(paragraph, {
816 position: {
817 x: wordBox.left - paragraphBox.left + wordBox.width / 2,
818 y: wordBox.top - paragraphBox.top + wordBox.height / 2,
819 },
820 });
821 return window.getSelection()?.toString().trim();
822 };
823β
824 const paragraphs = screen.container.querySelectorAll("p");
825 expect(paragraphs).toHaveLength(2);
826 const selections = [];
827 const lines = [];
828 for (const paragraph of paragraphs) {
829 lines.push(paragraph.textContent?.trim(), paragraph.textContent?.trim());
830 selections.push(
831 await tripleClickWord(paragraph, "Before"),
832 await tripleClickWord(paragraph, "after"),
833 );
834 }
835 expect(selections).toEqual(lines);
836 });
837β
838 it("selects the whole line on triple-click beside a desktop-draggable inline-code file chip", async () => {
839 setup();
840 // Desktop on macOS and Windows makes local file chips draggable for native file drags.
841 nativeFileDrag.enabled = true;
842 filesystemMetadata.mockResolvedValue(AsyncResult.success({ entries: [{ kind: "file" }] }));
843 await using screen = await renderText(
844 "The template (`config/app.yaml.example`) and two docs still say 5 fps.",
845 {
846 threadRef: {
847 environmentId: EnvironmentId.make("workspace"),
848 threadId: ThreadId.make("thread"),
849 },
850 },
851 );
852 await vi.waitFor(() =>
853 expect(
854 screen.container.querySelector("a.chat-markdown-file-link")?.getAttribute("draggable"),
855 ).toBe("true"),
856 );
857 const paragraph = screen.container.querySelector("p")!;
858 const text = [...paragraph.childNodes].find((node) =>
859 node.textContent?.includes("and two docs"),
860 )!;
861 const range = document.createRange();
862 range.setStart(text, text.textContent!.indexOf("and"));
863 range.setEnd(text, text.textContent!.indexOf("and") + 3);
864 const wordBox = range.getBoundingClientRect();
865 const paragraphBox = paragraph.getBoundingClientRect();
866 await userEvent.tripleClick(paragraph, {
867 position: {
868 x: wordBox.left - paragraphBox.left + wordBox.width / 2,
869 y: wordBox.top - paragraphBox.top + wordBox.height / 2,
870 },
871 });
872 expect(window.getSelection()?.toString().trim()).toBe(paragraph.textContent?.trim());
873 });
874});
875β
876describe("ChatMarkdown copy", () => {
877 it("copies a fully selected callout as alert Markdown and a partial one as text", async () => {
878 setup();
879 await using screen = await renderText("> [!WARNING]\n> Back up first.");
880 const [label, body] = screen.container.querySelectorAll('[role="note"] > p');
881 const select = (startNode: Node, endNode: Node, endOffset: number) => {
882 const range = document.createRange();
883 range.setStart(startNode, 0);
884 range.setEnd(endNode, endOffset);
885 const selection = window.getSelection()!;
886 selection.removeAllRanges();
887 selection.addRange(range);
888 return chatMarkdownClipboardPayload(selection)?.text;
889 };
890 const labelText = label!.lastChild!;
891 const bodyText = body!.firstChild!;
892β
893 expect(select(labelText, bodyText, bodyText.textContent!.length)).toBe(
894 "> [!WARNING]\n> Back up first.",
895 );
896 expect(select(labelText, bodyText, "Back up".length)).toBe("Warning\n\nBack up");
897 });
898β
899 it.each([
900 { text: " Plan\nnext" },
901 { text: "Plan\n Deep\n Deeper" },
902 { text: "Plan\n\tTabbed\n \t Mixed" },
903 { text: "- item\n more\n deeper\n- next" },
904 { text: "Plan\n Step one\n Detail a", from: "Step one" },
905 ])(
906 "copies and selects user lines the same whether their typed indentation shows: $text",
907 async (copy) => {
908 setup();
909 const copied = async (extensions: MarkdownExtensions) => {
910 await using screen = await renderText(copy.text, {
911 className: "user-message-markdown",
912 lineBreaks: true,
913 parseRawHtml: false,
914 extensions,
915 });
916 const range = document.createRange();
917 range.selectNodeContents(screen.container);
918 if (copy.from) {
919 const walker = document.createTreeWalker(screen.container, NodeFilter.SHOW_TEXT);
920 let line = walker.nextNode();
921 while (line && !line.textContent!.includes(copy.from)) line = walker.nextNode();
922 // Start mid-line, three characters into the line's text.
923 range.setStart(line!, line!.textContent!.indexOf(copy.from) + 3);
924 }
925 const selection = window.getSelection()!;
926 selection.removeAllRanges();
927 selection.addRange(range);
928 // A drag or anything else that reads the selection gets its text, not the copy payload.
929 return { payload: chatMarkdownClipboardPayload(selection), selected: selection.toString() };
930 };
931 const shown = await copied({ userMessage: true, leadingWhitespace: true });
932 // The user pipeline as it was before typed indentation was shown.
933 expect(shown).toEqual(await copied({ userMessage: true }));
934 },
935 );
936β
937 it("copies part of inline code without prose escapes", async () => {
938 setup();
939 await using screen = await renderText("Read `items[0]*_x` and a*b*c.");
940 const code = screen.container.querySelector("p code")!.firstChild!;
941 const range = document.createRange();
942 range.setStart(code, 0);
943 range.setEnd(code, "items[0]*_".length);
944 const selection = window.getSelection()!;
945 selection.removeAllRanges();
946 selection.addRange(range);
947 expect(chatMarkdownClipboardPayload(selection)?.text).toBe("items[0]*_");
948 });
949β
950 it.each([
951 {
952 source: "10. First\n11. Second\n12. Third\n\nAfter.",
953 from: "Second",
954 text: "11. Second\n12. Third\n\nAfter.",
955 },
956 {
957 source: "1. A\n2. B\n7. C\n8. D\n\nAfter.",
958 from: "D",
959 userMessage: true,
960 text: "8. D\n\nAfter.",
961 },
962 {
963 source: "1. Outer\n2. Next\n 1. Inner\n 2. Deeper\n\nAfter.",
964 from: "Deeper",
965 text: "2. 2. Deeper\n\nAfter.",
966 },
967 {
968 source: "1. Install\n2. Configure\n3. Deploy",
969 from: "Configure",
970 to: "Deploy",
971 text: "2. Configure\n3. Deploy",
972 },
973 {
974 source: "1. A\n2. B\n7. C\n8. D",
975 from: "B",
976 to: "C",
977 userMessage: true,
978 text: "2. B\n7. C",
979 },
980 {
981 source: "- Install\n- Configure\n- Deploy",
982 from: "Configure",
983 to: "Deploy",
984 text: "- Configure\n- Deploy",
985 },
986 ])(
987 "copies $text with the markers its list shows",
988 async ({ source, from, to, userMessage, text }) => {
989 setup();
990 await using screen = await renderText(
991 source,
992 userMessage ? { extensions: USER_MESSAGE } : {},
993 );
994 const itemText = (shown: string) =>
995 [...screen.container.querySelectorAll("li")]
996 .flatMap((item) => [...item.childNodes])
997 .find((node) => node.nodeType === Node.TEXT_NODE && node.textContent === shown)!;
998 const end = to
999 ? itemText(to)
1000 : [...screen.container.querySelectorAll("p")].at(-1)!.firstChild!;
1001 const range = document.createRange();
1002 range.setStart(itemText(from), 0);
1003 range.setEnd(end, end.textContent!.length);
1004 const selection = window.getSelection()!;
1005 selection.removeAllRanges();
1006 selection.addRange(range);
1007 const payload = chatMarkdownClipboardPayload(selection);
1008 expect(payload?.text).toBe(text);
1009 // Rich paste reads back as the same list.
1010 expect(
1011 serializeRenderedMarkdownFragment(
1012 new DOMParser().parseFromString(payload!.html, "text/html").body,
1013 ),
1014 ).toBe(text);
1015 },
1016 );
1017β
1018 it.each([
1019 {
1020 source: "1. [ ] Install\n2. [x] Configure\n3. [ ] Test\n4. [x] Deploy",
1021 from: "Configure",
1022 to: "Deploy",
1023 text: "2. [x] Configure\n3. [ ] Test\n4. [x] Deploy",
1024 htmlText: "2. Configure\n3. Test\n4. Deploy",
1025 },
1026 {
1027 source:
1028 "1. First\n2. [x] Outer\n 1. [ ] Setup\n 2. [ ] Configure\n 3. [x] Deploy\n\nAfter.",
1029 from: "Configure",
1030 text: "2. [x] 2. [ ] Configure\n 3. [x] Deploy\n\nAfter.",
1031 htmlText: "2. 2. Configure\n 3. Deploy\n\nAfter.",
1032 },
1033 ])(
1034 "copies task items with the markers its list shows: $text",
1035 async ({ source, from, to, text, htmlText }) => {
1036 setup();
1037 await using screen = await renderText(source);
1038 const itemText = (label: string) =>
1039 [...screen.container.querySelectorAll("li")]
1040 .flatMap((item) => [...item.childNodes])
1041 .find((node) => node.nodeType === Node.TEXT_NODE && node.textContent?.trim() === label)!;
1042 const start = itemText(from);
1043 const end = to ? itemText(to) : screen.container.querySelector("p")!.firstChild!;
1044 const range = document.createRange();
1045 range.setStart(start, start.textContent!.indexOf(from));
1046 range.setEnd(end, end.textContent!.length);
1047 const selection = window.getSelection()!;
1048 selection.removeAllRanges();
1049 selection.addRange(range);
1050 const payload = chatMarkdownClipboardPayload(selection);
1051 expect(payload?.text).toBe(text);
1052 // HTML sanitization strips form controls.
1053 expect(
1054 serializeRenderedMarkdownFragment(
1055 new DOMParser().parseFromString(payload!.html, "text/html").body,
1056 ),
1057 ).toBe(htmlText);
1058 },
1059 );
1060β
1061 it.each([
1062 {
1063 source: "1. First\n2. Second\n\nAfter.",
1064 from: "First",
1065 skipFrom: true,
1066 text: "2. Second\n\nAfter.",
1067 items: 1,
1068 },
1069 {
1070 source: "Before.\n\n1. First\n2. Second",
1071 from: "Before.",
1072 to: "Second",
1073 skipTo: true,
1074 text: "Before.\n\n1. First",
1075 items: 1,
1076 },
1077 {
1078 source: "1. Outer\n 1. Inner\n 2. Deeper\n2. Next",
1079 from: "Inner",
1080 to: "Next",
1081 skipFrom: true,
1082 text: "1. 2. Deeper\n2. Next",
1083 items: 3,
1084 },
1085 {
1086 source: "1. Outer\n 1. Inner\n2. Next",
1087 from: "Inner",
1088 to: "Next",
1089 skipFrom: true,
1090 text: "2. Next",
1091 items: 1,
1092 },
1093 ])(
1094 "omits edge items outside the selection when copying with the markers its list shows: $text",
1095 async ({ source, from, to, skipFrom, skipTo, text, items }) => {
1096 setup();
1097 await using screen = await renderText(source);
1098 const textNode = (shown: string) => {
1099 const walker = document.createTreeWalker(screen.container, NodeFilter.SHOW_TEXT);
1100 for (let node = walker.nextNode(); node; node = walker.nextNode()) {
1101 if (node.textContent === shown) return node;
1102 }
1103 throw new Error(`Could not find text: ${shown}`);
1104 };
1105 const end = to ? textNode(to) : textNode("After.");
1106 const range = document.createRange();
1107 range.setStart(textNode(from), skipFrom ? from.length : 0);
1108 range.setEnd(end, skipTo ? 0 : end.textContent!.length);
1109 const selection = window.getSelection()!;
1110 selection.removeAllRanges();
1111 selection.addRange(range);
1112β
1113 const payload = chatMarkdownClipboardPayload(selection);
1114 expect(payload?.text).toBe(text);
1115 const pasted = new DOMParser().parseFromString(payload!.html, "text/html");
1116 expect(serializeRenderedMarkdownFragment(pasted.body)).toBe(text);
1117 expect(pasted.querySelectorAll("li")).toHaveLength(items);
1118 },
1119 );
1120β
1121 it("omits an end item whose selected edge sits inside its link", async () => {
1122 setup();
1123 await using screen = await renderText(
1124 "1. Install\n2. Configure\n3. Deploy\n4. [Verify](https://example.com/verify)",
1125 );
1126 const items = [...screen.container.querySelectorAll("li")];
1127 const start = items.find((item) => item.textContent === "Configure")!.firstChild!;
1128 const end = items.at(-1)!.querySelector("a > span")!.lastChild!;
1129 const range = document.createRange();
1130 range.setStart(start, 0);
1131 range.setEnd(end, 0);
1132 const selection = window.getSelection()!;
1133 selection.removeAllRanges();
1134 selection.addRange(range);
1135β
1136 const payload = chatMarkdownClipboardPayload(selection);
1137 expect(payload?.text).toBe("2. Configure\n3. Deploy");
1138 const pasted = new DOMParser().parseFromString(payload!.html, "text/html");
1139 expect(
1140 [...pasted.querySelectorAll('ol[start="2"] > li')].map((item) => item.textContent),
1141 ).toEqual(["Configure", "Deploy"]);
1142 });
1143});
1144β
1145describe("ChatMarkdown file chip tooltips", () => {
1146 it("stays open while the pointer selects the path, then closes when it leaves", async () => {
1147 setup();
1148 await using screen = await renderText("[notes](/tmp/project/docs/notes.md)");
1149 await userEvent.hover(screen.container.querySelector(".chat-markdown-file-link")!);
1150 const path = page.getByText("/tmp/project/docs/notes.md");
1151 await expect.element(path).toBeVisible();
1152β
1153 // Forced so the pointer lands on the popup even when it ignores pointer events.
1154 await userEvent.tripleClick(path, { force: true });
1155 expect(window.getSelection()?.toString().trim()).toBe("/tmp/project/docs/notes.md");
1156 await expect.element(path).toBeVisible();
1157β
1158 await commands.resetPointer();
1159 await expect.element(path).not.toBeInTheDocument();
1160 });
1161β
1162 it("wraps a long path so its file name stays inside the tooltip", async () => {
1163 setup();
1164 const path =
1165 "/tmp/project/packages/client-runtime/src/state/generated/environment-connection-handshake-retry-policy-fixtures.ts";
1166 await using screen = await renderText(`See [the fixtures](${path}).`);
1167β
1168 await userEvent.hover(screen.container.querySelector(".chat-markdown-file-link")!);
1169 const tooltip = page.getByText(path);
1170 await expect.element(tooltip).toBeVisible();
1171β
1172 const popup = tooltip.element().closest("[data-side]")!;
1173 const pathEnd = document.createRange();
1174 pathEnd.selectNodeContents(tooltip.element());
1175 expect(pathEnd.getBoundingClientRect().right).toBeLessThanOrEqual(
1176 popup.getBoundingClientRect().right,
1177 );
1178 });
1179});
1180β
1181describe("ChatMarkdown editor deep links", () => {
1182 const hrefs = (container: HTMLElement) =>
1183 [...container.querySelectorAll("a")].map((link) => link.getAttribute("href"));
1184β
1185 it("keeps local editor file links", async () => {
1186 setup();
1187 await using screen = await renderText(
1188 "[file.md line 3](cursor://file/Users/me/repo/file.md:3) and [same](vscode://file/Users/me/repo/file.md:3:7)",
1189 );
1190 expect(hrefs(screen.container)).toEqual([
1191 "cursor://file/Users/me/repo/file.md:3",
1192 "vscode://file/Users/me/repo/file.md:3:7",
1193 ]);
1194 });
1195β
1196 it("still drops other editor links and unknown schemes", async () => {
1197 setup();
1198 await using screen = await renderText(
1199 "[prompt](cursor://anysphere.cursor-deeplink/prompt?text=hi) [user](cursor://me@file/Users/me/file.md) [unknown](foo://file/Users/me/file.md)",
1200 );
1201 expect(screen.container.innerHTML).not.toContain("://");
1202 expect(hrefs(screen.container).filter(Boolean)).toEqual([]);
1203 });
1204});
1205β
1206describe("ChatMarkdown Windows file links", () => {
1207 const environmentId = EnvironmentId.make("env-windows");
1208 const renderWindows = (text: string, parseRawHtml: boolean) =>
1209 renderText(text, {
1210 cwd: "C:/Users/shawn/project",
1211 environmentId,
1212 lineBreaks: !parseRawHtml,
1213 parseRawHtml,
1214 });
1215 const fileHrefs = (container: HTMLElement) =>
1216 [...container.querySelectorAll(".chat-markdown-file-link")].map((chip) =>
1217 chip.getAttribute("href"),
1218 );
1219β
1220 it("still rejects unsafe schemes", async () => {
1221 setup();
1222 for (const parseRawHtml of [true, false]) {
1223 await using screen = await renderWindows(
1224 "[unsafe](javascript:alert(1)) and [unknown](d:alert(1))",
1225 parseRawHtml,
1226 );
1227 const { container } = screen;
1228 expect(container.innerHTML).not.toContain("javascript:");
1229 expect(container.innerHTML).not.toContain("d:alert");
1230 expect(fileHrefs(container)).toEqual([]);
1231 }
1232 });
1233});
1234β
1235describe("ChatMarkdown host media", () => {
1236 it("explains a host video the connection cannot read instead of offering a retry", async () => {
1237 setup();
1238 await using screen = await renderText("", {
1239 threadRef: {
1240 environmentId: EnvironmentId.make(deniedEnvironmentId),
1241 threadId: ThreadId.make("thread"),
1242 },
1243 });
1244 await vi.waitFor(() =>
1245 expect(screen.container.textContent).toContain(MISSING_FILE_ACCESS_MESSAGE),
1246 );
1247 expect(screen.container.textContent).not.toContain("Retry video");
1248 });
1249});