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

ChatMarkdown.browser.test.tsx

556 lines20.9 KB

1import { EnvironmentId, ThreadId } from "@t3tools/contracts";
2import { AsyncResult } from "effect/reactivity";
3import { type ReactElement } from "react";
4import { describe, expect, it, vi } from "vite-plus/test";
5import { page, userEvent } from "vite-plus/test/browser";
6​
7import { act, render } from "../../test/render";
8import "../index.css";
9​
10import { filesystemEnvironment } from "../state/filesystem";
11import { useRightPanelStore } from "../rightPanelStore";
12import { setMarkdownTaskChecked } from "@t3tools/shared/markdownTaskList";
13import { HostImageUrlContext } from "./chat/hostImageUrl";
14​
15const { workspaceSearch, filesystemMetadata } = vi.hoisted(() => ({
16 workspaceSearch: vi.fn(),
17 filesystemMetadata: vi.fn(),
18}));
19const parsedSources = vi.hoisted(() => [] as string[]);
20vi.mock(import("mdast-util-from-markdown"), async (original) => {
21 const actual = await original();
22 return {
23 ...actual,
24 fromMarkdown: ((source: string, ...rest: never[]) => {
25 parsedSources.push(String(source));
26 return (actual.fromMarkdown as (...args: unknown[]) => unknown)(source, ...rest);
27 }) as typeof actual.fromMarkdown,
28 };
29});
30​
31vi.mock(import("../state/use-atom-query-runner"), async (original) => ({
32 ...(await original()),
33 useAtomQueryRunner: ((family: unknown) =>
34 family === filesystemEnvironment.getMetadata ? filesystemMetadata : workspaceSearch) as never,
35}));
36​
37// Atoms derived from the server config run in the real registry over a missing config.
38vi.mock(import("../state/server"), async (original) => {
39 const actual = await original();
40 const { Atom } = await import("effect/reactivity");
41 const noConfig = Atom.make(null);
42 const modelsConfig = Atom.make({
43 availableEditors: [],
44 settings: { providerInstances: {} },
45 providers: [
46 {
47 instanceId: "codex",
48 driver: "codex",
49 displayName: "Codex",
50 models: [{ slug: "gpt-6.1", name: "GPT-6.1", isCustom: false, capabilities: {} }],
51 },
52 ],
53 });
54 return {
55 ...actual,
56 serverEnvironment: {
57 ...actual.serverEnvironment,
58 configValueAtom: ((environmentId: string) =>
59 environmentId === "models" ? modelsConfig : noConfig) as never,
60 },
61 };
62});
63vi.mock(import("../state/session"), async (original) => {
64 const { AuthStandardClientScopes } = await import("@t3tools/contracts");
65 const granted = new Set<string>(AuthStandardClientScopes);
66 const hasScope = (environmentId: unknown, scope: string) =>
67 environmentId !== null && granted.has(scope);
68 return {
69 ...(await original()),
70 useEnvironmentScope: hasScope as never,
71 readEnvironmentScope: hasScope as never,
72 };
73});
74vi.mock(import("../remoteOpen"), async (original) => ({
75 ...(await original()),
76 useRemoteOpenResolution: () => ({ state: { mode: "local-exec" }, isResolved: true }) as never,
77}));
78const { renderDiagram } = vi.hoisted(() => ({
79 renderDiagram: vi.fn<(source: string) => Promise<string> | undefined>(),
80}));
81// Control rendering latency without running Mermaid layout.
82vi.mock(import("./chat/MermaidDiagram"), async (original) => {
83 const { use } = await import("react");
84 return {
85 ...(await original()),
86 MermaidDiagram: ({ source }: { source: string }) => {
87 const pending = renderDiagram(source);
88 return <svg role="img" aria-label={pending ? use(pending) : "Diagram"} />;
89 },
90 };
91});
92​
93const appearance = vi.hoisted(() => ({
94 value: "light" as "light" | "dark",
95 listeners: new Set<() => void>(),
96}));
97vi.mock(import("../hooks/useTheme"), async (original) => {
98 const { useSyncExternalStore } = await import("react");
99 const subscribe = (listener: () => void) => {
100 appearance.listeners.add(listener);
101 return () => appearance.listeners.delete(listener);
102 };
103 return {
104 ...(await original()),
105 useRenderedAppearance: () => useSyncExternalStore(subscribe, () => appearance.value),
106 };
107});
108​
109const settingsOverrides = vi.hoisted(() => ({ mathRenderingEnabled: false }));
110vi.mock(import("../hooks/useSettings"), async (original) => {
111 const actual = await original();
112 type Settings = ReturnType<typeof actual.getClientSettings>;
113 function useClientSettings<T = Settings>(select?: (settings: Settings) => T): T {
114 const settings = { ...actual.getClientSettings(), ...settingsOverrides };
115 return select ? select(settings) : (settings as T);
116 }
117 return { ...actual, useClientSettings };
118});
119​
120import ChatMarkdown from "./ChatMarkdown";
121import { AudioPreview } from "./files/AudioPreview";
122​
123it("keeps compact audio playback loaded across signed URL renewals", async () => {
124 const original =
125 "data:audio/wav;base64,UklGRiUAAABXQVZFZm10IBAAAAABAAEAQB8AAEAfAAABAAgAZGF0YQEAAACA";
126 const renewed = `${original}#renewed`;
127 const preview = (src: string, revision = "clip-v1") => (
128 <AudioPreview compact name="clip.wav" src={src} revision={revision} />
129 );
130 await using screen = await render(preview(original));
131 const audio = screen.container.querySelector("audio")!;
132 await act(() => {
133 audio.dispatchEvent(new Event("loadedmetadata"));
134 audio.dispatchEvent(new Event("play"));
135 });
136 await screen.rerender(preview(renewed));
137 expect(screen.container.querySelector("audio")).toBe(audio);
138 expect(audio.getAttribute("src")).toBe(original);
139 await expect.element(screen.getByRole("button", { name: "Pause clip.wav" })).toBeEnabled();
140 await screen.rerender(preview(renewed, "clip-v2"));
141 expect(screen.container.querySelector("audio")).not.toBe(audio);
142 expect(screen.container.querySelector("audio")?.getAttribute("src")).toBe(renewed);
143});
144​
145function setup() {
146 appearance.value = "light";
147 parsedSources.length = 0;
148 settingsOverrides.mathRenderingEnabled = false;
149 renderDiagram.mockReset();
150 workspaceSearch.mockReset().mockResolvedValue(AsyncResult.success({ entries: [] }));
151 filesystemMetadata.mockReset().mockResolvedValue(AsyncResult.success({ entries: [null] }));
153​
154function renderText(text: string, props: Partial<Parameters<typeof ChatMarkdown>[0]> = {}) {
155 return render(<ChatMarkdown cwd="/tmp/project" text={text} {...props} />);
157​
158function buttonsLabelled(container: HTMLElement, label: string) {
159 return [...container.querySelectorAll<HTMLButtonElement>("button")].filter(
160 (button) => button.getAttribute("aria-label") === label,
161 );
163​
164it("shows unavailable audio when a workspace embed has no thread", async () => {
165 setup();
166 await using screen = await renderText("![recording](clip.wav)");
167 expect(screen.container.textContent).toContain("Audio unavailable");
168 expect(screen.container.textContent).not.toContain("Loading audio");
169 expect(screen.container.querySelector("audio")).toBeNull();
170});
171​
172it("loads a host image through the page's own route when there is no environment", async () => {
173 setup();
174 const pixel =
175 "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=";
176 const hostImageUrl = vi.fn((_path: string) => pixel);
177 await using screen = await render(
178 <HostImageUrlContext value={hostImageUrl}>
179 <ChatMarkdown cwd={undefined} text="![Shot](</work/my shot.png>)" />
180 </HostImageUrlContext>,
181 );
182 await expect.element(screen.getByAltText("Shot")).toHaveAttribute("src", pixel);
183 expect(new Set(hostImageUrl.mock.calls.map(([path]) => path))).toEqual(
184 new Set(["/work/my shot.png"]),
185 );
186});
187​
188it("loads the <picture> source for the current theme through the image route", async () => {
189 setup();
190 const pixel =
191 "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=";
192 const hostImageUrl = (path: string) => `${pixel}#${path}`;
193 await using screen = await render(
194 <HostImageUrlContext value={hostImageUrl}>
195 <ChatMarkdown
196 cwd={undefined}
197 text={
198 '<picture><source media="(prefers-color-scheme: dark)" srcset="/work/dark.png"><img src="/work/light.png" alt="Shot"></picture>'
199 }
200 />
201 </HostImageUrlContext>,
202 );
203 await expect
204 .element(screen.getByAltText("Shot"))
205 .toHaveAttribute("src", `${pixel}#/work/light.png`);
206​
207 await act(() => {
208 appearance.value = "dark";
209 for (const listener of appearance.listeners) listener();
210 });
211 await expect
212 .element(screen.getByAltText("Shot"))
213 .toHaveAttribute("src", `${pixel}#/work/dark.png`);
214});
215​
216it("reuses the parse of a streaming reply's finished blocks when it remounts", async () => {
217 setup();
218 const message = (
219 <ChatMarkdown cwd="/tmp/project" text={"Finished block\n\nStill growing"} isStreaming />
220 );
221 {
222 await using _first = await render(message);
223 }
224 await using screen = await render(message);
225 await expect.element(screen.getByText("Still growing")).toBeVisible();
226 expect(parsedSources.filter((source) => source.includes("Finished block"))).toHaveLength(1);
227});
228​
229it("reuses the parse of a remounted message that has stable extra plugins", async () => {
230 setup();
231 const parsed = vi.fn();
232 const countingPlugins = [() => () => void parsed()];
233 const message = (
234 <ChatMarkdown cwd="/tmp/project" text="Cached text" extraRemarkPlugins={countingPlugins} />
235 );
236 {
237 await using _first = await render(message);
238 }
239 await using screen = await render(message);
240 await expect.element(screen.getByText("Cached text")).toBeVisible();
241 expect(parsed).toHaveBeenCalledTimes(1);
242});
243​
244describe("ChatMarkdown favicon privacy", () => {
245 it("suppresses private link images while preserving public links across updates", async () => {
246 setup();
247 const markdown = (url: string) => <ChatMarkdown cwd="/tmp/project" text={`[Link](${url})`} />;
248 await using screen = await render(markdown("https://example.com"));
249 const { container, rerender } = screen;
250 expect([...container.querySelectorAll("img")].map((image) => image.src)).toEqual([
251 "https://www.google.com/s2/favicons?domain=example.com&sz=32",
252 ]);
253 for (const url of ["http://192.168.1.10:8080", "http://localhost:3000", "http://home.arpa"]) {
254 await rerender(markdown(url));
255 expect(container.querySelectorAll("img")).toHaveLength(0);
256 }
257 await rerender(markdown("https://example.com"));
258 expect(container.querySelectorAll("img")).toHaveLength(1);
259 await rerender(markdown("https://github.com/pingdotgg/t3code/pull/1"));
260 expect(container.querySelectorAll("img")).toHaveLength(0);
261 expect(container.querySelector("a svg")).not.toBeNull();
262 });
263});
264​
265describe("ChatMarkdown streaming", () => {
266 it("runs only a complete single-line shell block after a click", async () => {
267 setup();
268 const onRunShellCommand = vi.fn();
269 const message = (text: string, isStreaming = false) => (
270 <ChatMarkdown
271 cwd="/tmp/project"
272 text={text}
273 isStreaming={isStreaming}
274 onRunShellCommand={onRunShellCommand}
275 />
276 );
277 await using screen = await render(message("```bash\necho hello\n```", true));
278 const { container, rerender } = screen;
279 const runButtons = () => buttonsLabelled(container, "Run in terminal");
280 expect(runButtons()).toHaveLength(0);
281​
282 await rerender(message("```bash\necho hello\n```"));
283 await act(async () => runButtons()[0]!.click());
284 expect(onRunShellCommand).toHaveBeenCalledExactlyOnceWith("echo hello");
285​
286 for (const text of [
287 "~~~bash\necho tilde\n~~~",
288 "> ```bash\n> echo quote\n> ```",
289 "````bash\necho four\n````",
290 "- Command\n\n ```bash\n echo list\n ```",
291 "```bash\r\necho crlf\r\n```\r",
292 ]) {
293 await rerender(message(text));
294 expect(runButtons()).toHaveLength(1);
295 }
296​
297 for (const text of [
298 "```bash\necho one\necho two\n```",
299 "```typescript\necho hello\n```",
300 "```bash\n\n```",
301 "```bash\necho hello\n\n```",
302 "```bash\necho hello\\\n```",
303 "```bash\necho safe \u202e#\n```",
304 "```bash\necho incomplete",
305 "~~~bash\necho incomplete",
306 "````bash\necho incomplete\n```",
307 '<pre><code class="language-bash">echo html</code></pre>',
308 ]) {
309 await rerender(message(text));
310 expect(runButtons()).toHaveLength(0);
311 }
312 });
313​
314 it("edits the current task text and marker after reusing a renderer", async () => {
315 setup();
316 let editedText: string | undefined;
317 let rerender: (next: ReactElement) => Promise<void> = async () => {};
318 const message = (text: string): ReactElement => (
319 <ChatMarkdown
320 cwd="/tmp/project"
321 text={text}
322 onTaskListChange={({ markerOffset, checked }) => {
323 editedText = setMarkdownTaskChecked(text, markerOffset, checked);
324 void rerender(message(editedText));
325 }}
326 />
327 );
328 await using rendered = await render(message("- [ ] First\n- [ ] Second"));
329 rerender = rendered.rerender;
330 const { container } = rendered;
331 const checkboxes = () => container.querySelectorAll<HTMLInputElement>('input[type="checkbox"]');
332 const original = checkboxes()[1]!;
333 await rerender(message("- [ ] A longer first task\n- [ ] Second"));
334 expect(checkboxes()[1]).toBe(original);
335​
336 await act(async () => original.click());
337 expect(editedText).toBe("- [ ] A longer first task\n- [x] Second");
338 await vi.waitFor(() => expect(checkboxes()[1]!.checked).toBe(true));
339 await rerender(message("- [ ] A longer first task\n- [ ] Second"));
340 expect(checkboxes()[1]).toBe(original);
341 expect(checkboxes()[1]!.checked).toBe(false);
342 });
343​
344 it.each([
345 ["read-only", undefined],
346 ["editable", () => {}],
347 ])(
348 "unchecks the remaining %s task when the checked row above it is removed",
349 async (_, onTaskListChange) => {
350 setup();
351 const message = (text: string) => (
352 <ChatMarkdown cwd="/tmp/project" text={text} onTaskListChange={onTaskListChange} />
353 );
354 await using screen = await render(message("- [x] Completed item\n- [ ] Pending item"));
355 await screen.rerender(message("- [ ] Pending item"));
356 const checkboxes =
357 screen.container.querySelectorAll<HTMLInputElement>('input[type="checkbox"]');
358 expect(checkboxes).toHaveLength(1);
359 expect(checkboxes[0]!.checked).toBe(false);
360 },
361 );
362});
363​
364describe("ChatMarkdown workspace file opens", () => {
365 const threadRef = {
366 environmentId: EnvironmentId.make("workspace"),
367 threadId: ThreadId.make("thread"),
368 };
369​
370 it("keeps a newer absolute file open when an earlier repo-relative lookup finishes", async () => {
371 setup();
372 const result = AsyncResult.success({
373 entries: [{ path: "notes/a.md", kind: "file" }],
374 truncated: false,
375 });
376 let resolvePending!: (value: typeof result) => void;
377 const pending = new Promise<typeof result>((resolve) => {
378 resolvePending = resolve;
379 });
380 workspaceSearch.mockReturnValueOnce(pending);
381 using openFile = vi
382 .spyOn(useRightPanelStore.getState(), "openFile")
383 .mockImplementation(() => {});
384 await using screen = await renderText(
385 "[Notes](physics/notes/a.md) and [Other](/elsewhere/b.md:9)",
386 {
387 cwd: "/school/physics",
388 threadRef,
389 },
390 );
391 const { container } = screen;
392 const [notes, other] = container.querySelectorAll("a");
393 await act(async () => notes!.click());
394 expect(workspaceSearch).toHaveBeenCalledOnce();
395 expect(openFile).not.toHaveBeenCalled();
396​
397 await act(async () => other!.click());
398 await act(async () => resolvePending(result));
399​
400 expect(openFile).toHaveBeenCalledExactlyOnceWith(threadRef, "/elsewhere/b.md", 9);
401 expect(workspaceSearch).toHaveBeenCalledOnce();
402 });
403});
404​
405describe("ChatMarkdown skill chips", () => {
406 it("shows the skill's details and opens its instructions", async () => {
407 setup();
408 const threadRef = {
409 environmentId: EnvironmentId.make("workspace"),
410 threadId: ThreadId.make("thread"),
411 };
412 await using screen = await renderText("Run $review now", {
413 threadRef,
414 skills: [
415 {
416 name: "review",
417 displayName: "Review",
418 description: "Reviews the current branch.",
419 path: "/skills/review/SKILL.md",
420 enabled: true,
421 },
422 ],
423 });
424 using openFile = vi
425 .spyOn(useRightPanelStore.getState(), "openFile")
426 .mockImplementation(() => {});
427​
428 await userEvent.click(screen.getByRole("button", { name: "Skill Review. Show details" }));
429 await expect.element(page.getByText("Reviews the current branch.")).toBeVisible();
430 await userEvent.click(page.getByRole("button", { name: "View instructions" }));
431​
432 expect(openFile).toHaveBeenCalledExactlyOnceWith(threadRef, "/skills/review/SKILL.md");
433 });
434​
435 it("names a mentioned model as its provider does, without a thread", async () => {
436 setup();
437 await using screen = await renderText("Ask (model:codex/gpt-6.1), not model:openai/gpt-4o.", {
438 environmentId: EnvironmentId.make("models"),
439 });
440​
441 await expect
442 .element(screen.getByRole("button", { name: "Model GPT-6.1. Show details" }))
443 .toBeVisible();
444 expect(buttonsLabelled(screen.container, "Model gpt-4o. Show details")).toEqual([]);
445 expect(screen.container.textContent).toBe("Ask (GPT-6.1), not model:openai/gpt-4o.");
446 });
447});
448​
449describe("ChatMarkdown headings", () => {
450 it("never gives two headings the same id, even when a suffix matches another heading", async () => {
451 setup();
452 await using screen = await renderText(
453 '## Setup\n\n## Setup\n\n## Setup-1\n\n<h2 id="install-1">Pinned</h2>\n\n## Install\n\n## Install',
454 { parseRawHtml: true },
455 );
456 const { container } = screen;
457 expect([...container.querySelectorAll("h2")].map((heading) => heading.id)).toEqual([
458 "user-content-setup",
459 "user-content-setup-1",
460 "user-content-setup-1-1",
461 "user-content-install-1",
462 "user-content-install",
463 "user-content-install-2",
464 ]);
465 });
466});
467​
468describe("ChatMarkdown inline code selection", () => {
469 it("selects the whole inline code span on double-click, but only a word in fenced code", async () => {
470 setup();
471 await using screen = await renderText(
472 "Run `migration-gate --dry-run` first.\n\n```txt\nfenced-block word\n```",
473 );
474 await userEvent.dblClick(screen.getByText("migration-gate --dry-run"));
475 expect(window.getSelection()?.toString()).toBe("migration-gate --dry-run");
476​
477 window.getSelection()?.removeAllRanges();
478 const fenced = screen.container.querySelector("pre code")!;
479 await userEvent.dblClick(fenced, { position: { x: 4, y: 4 } });
480 expect(window.getSelection()?.toString()).toBe("fenced");
481 });
482});
483​
484describe("ChatMarkdown file chip tooltips", () => {
485 it("wraps a long path so its file name stays inside the tooltip", async () => {
486 setup();
487 const path =
488 "/tmp/project/packages/client-runtime/src/state/generated/environment-connection-handshake-retry-policy-fixtures.ts";
489 await using screen = await renderText(`See [the fixtures](${path}).`);
490​
491 await userEvent.hover(screen.container.querySelector(".chat-markdown-file-link")!);
492 const tooltip = page.getByText(path);
493 await expect.element(tooltip).toBeVisible();
494​
495 const popup = tooltip.element().closest("[data-side]")!;
496 const pathEnd = document.createRange();
497 pathEnd.selectNodeContents(tooltip.element());
498 expect(pathEnd.getBoundingClientRect().right).toBeLessThanOrEqual(
499 popup.getBoundingClientRect().right,
500 );
501 });
502});
503​
504describe("ChatMarkdown editor deep links", () => {
505 const hrefs = (container: HTMLElement) =>
506 [...container.querySelectorAll("a")].map((link) => link.getAttribute("href"));
507​
508 it("keeps local editor file links", async () => {
509 setup();
510 await using screen = await renderText(
511 "[file.md line 3](cursor://file/Users/me/repo/file.md:3) and [same](vscode://file/Users/me/repo/file.md:3:7)",
512 );
513 expect(hrefs(screen.container)).toEqual([
514 "cursor://file/Users/me/repo/file.md:3",
515 "vscode://file/Users/me/repo/file.md:3:7",
516 ]);
517 });
518​
519 it("still drops other editor links and unknown schemes", async () => {
520 setup();
521 await using screen = await renderText(
522 "[prompt](cursor://anysphere.cursor-deeplink/prompt?text=hi) [user](cursor://me@file/Users/me/file.md) [unknown](foo://file/Users/me/file.md)",
523 );
524 expect(screen.container.innerHTML).not.toContain("://");
525 expect(hrefs(screen.container).filter(Boolean)).toEqual([]);
526 });
527});
528​
529describe("ChatMarkdown Windows file links", () => {
530 const environmentId = EnvironmentId.make("env-windows");
531 const renderWindows = (text: string, parseRawHtml: boolean) =>
532 renderText(text, {
533 cwd: "C:/Users/shawn/project",
534 environmentId,
535 lineBreaks: !parseRawHtml,
536 parseRawHtml,
537 });
538 const fileHrefs = (container: HTMLElement) =>
539 [...container.querySelectorAll(".chat-markdown-file-link")].map((chip) =>
540 chip.getAttribute("href"),
541 );
542​
543 it("still rejects unsafe schemes", async () => {
544 setup();
545 for (const parseRawHtml of [true, false]) {
546 await using screen = await renderWindows(
547 "[unsafe](javascript:alert(1)) and [unknown](d:alert(1))",
548 parseRawHtml,
549 );
550 const { container } = screen;
551 expect(container.innerHTML).not.toContain("javascript:");
552 expect(container.innerHTML).not.toContain("d:alert");
553 expect(fileHrefs(container)).toEqual([]);
554 }
555 });
556});