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