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

ChatMarkdown.browser.test.tsx

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