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 { setMarkdownTaskChecked } from "./files/filePreviewMode";
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 return {
43 ...actual,
44 serverEnvironment: { ...actual.serverEnvironment, configValueAtom: (() => noConfig) as never },
45 };
46});
47vi.mock(import("../state/session"), async (original) => {
48 const { AuthStandardClientScopes } = await import("@t3tools/contracts");
49 const granted = new Set<string>(AuthStandardClientScopes);
50 const hasScope = (environmentId: unknown, scope: string) =>
51 environmentId !== null && granted.has(scope);
52 return {
53 ...(await original()),
54 useEnvironmentScope: hasScope as never,
55 readEnvironmentScope: hasScope as never,
56 };
57});
58vi.mock(import("../remoteOpen"), async (original) => ({
59 ...(await original()),
60 useRemoteOpenResolution: () => ({ state: { mode: "local-exec" }, isResolved: true }) as never,
61}));
62const { renderDiagram } = vi.hoisted(() => ({
63 renderDiagram: vi.fn<(source: string) => Promise<string> | undefined>(),
64}));
65// Control rendering latency without running Mermaid layout.
66vi.mock(import("./chat/MermaidDiagram"), async (original) => {
67 const { use } = await import("react");
68 return {
69 ...(await original()),
70 MermaidDiagram: ({ source }: { source: string }) => {
71 const pending = renderDiagram(source);
72 return <svg role="img" aria-label={pending ? use(pending) : "Diagram"} />;
73 },
74 };
75});
76
77const settingsOverrides = vi.hoisted(() => ({ mathRenderingEnabled: false }));
78vi.mock(import("../hooks/useSettings"), async (original) => {
79 const actual = await original();
80 type Settings = ReturnType<typeof actual.getClientSettings>;
81 function useClientSettings<T = Settings>(select?: (settings: Settings) => T): T {
82 const settings = { ...actual.getClientSettings(), ...settingsOverrides };
83 return select ? select(settings) : (settings as T);
84 }
85 return { ...actual, useClientSettings };
86});
87
88import ChatMarkdown from "./ChatMarkdown";
89import { AudioPreview } from "./files/AudioPreview";
90
91it("keeps compact audio playback loaded across signed URL renewals", async () => {
92 const original =
93 "data:audio/wav;base64,UklGRiUAAABXQVZFZm10IBAAAAABAAEAQB8AAEAfAAABAAgAZGF0YQEAAACA";
94 const renewed = `${original}#renewed`;
95 const preview = (src: string, revision = "clip-v1") => (
96 <AudioPreview compact name="clip.wav" src={src} revision={revision} />
97 );
98 await using screen = await render(preview(original));
99 const audio = screen.container.querySelector("audio")!;
100 await act(() => {
101 audio.dispatchEvent(new Event("loadedmetadata"));
102 audio.dispatchEvent(new Event("play"));
103 });
104 await screen.rerender(preview(renewed));
105 expect(screen.container.querySelector("audio")).toBe(audio);
106 expect(audio.getAttribute("src")).toBe(original);
107 await expect.element(screen.getByRole("button", { name: "Pause clip.wav" })).toBeEnabled();
108 await screen.rerender(preview(renewed, "clip-v2"));
109 expect(screen.container.querySelector("audio")).not.toBe(audio);
110 expect(screen.container.querySelector("audio")?.getAttribute("src")).toBe(renewed);
111});
112
113function setup() {
114 parsedSources.length = 0;
115 settingsOverrides.mathRenderingEnabled = false;
116 renderDiagram.mockReset();
117 workspaceSearch.mockReset().mockResolvedValue(AsyncResult.success({ entries: [] }));
118 filesystemMetadata.mockReset().mockResolvedValue(AsyncResult.success({ entries: [null] }));
119}
120
121function renderText(text: string, props: Partial<Parameters<typeof ChatMarkdown>[0]> = {}) {
122 return render(<ChatMarkdown cwd="/tmp/project" text={text} {...props} />);
123}
124
125function buttonsLabelled(container: HTMLElement, label: string) {
126 return [...container.querySelectorAll<HTMLButtonElement>("button")].filter(
127 (button) => button.getAttribute("aria-label") === label,
128 );
129}
130
131it("shows unavailable audio when a workspace embed has no thread", async () => {
132 setup();
133 await using screen = await renderText("");
134 expect(screen.container.textContent).toContain("Audio unavailable");
135 expect(screen.container.textContent).not.toContain("Loading audio");
136 expect(screen.container.querySelector("audio")).toBeNull();
137});
138
139it("loads a host image through the page's own route when there is no environment", async () => {
140 setup();
141 const pixel =
142 "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=";
143 const hostImageUrl = vi.fn((_path: string) => pixel);
144 await using screen = await render(
145 <HostImageUrlContext value={hostImageUrl}>
146 <ChatMarkdown cwd={undefined} text="" />
147 </HostImageUrlContext>,
148 );
149 await expect.element(screen.getByAltText("Shot")).toHaveAttribute("src", pixel);
150 expect(new Set(hostImageUrl.mock.calls.map(([path]) => path))).toEqual(
151 new Set(["/work/my shot.png"]),
152 );
153});
154
155it("reuses the parse of a streaming reply's finished blocks when it remounts", async () => {
156 setup();
157 const message = (
158 <ChatMarkdown cwd="/tmp/project" text={"Finished block\n\nStill growing"} isStreaming />
159 );
160 {
161 await using _first = await render(message);
162 }
163 await using screen = await render(message);
164 await expect.element(screen.getByText("Still growing")).toBeVisible();
165 expect(parsedSources.filter((source) => source.includes("Finished block"))).toHaveLength(1);
166});
167
168it("reuses the parse of a remounted message that has stable extra plugins", async () => {
169 setup();
170 const parsed = vi.fn();
171 const countingPlugins = [() => () => void parsed()];
172 const message = (
173 <ChatMarkdown cwd="/tmp/project" text="Cached text" extraRemarkPlugins={countingPlugins} />
174 );
175 {
176 await using _first = await render(message);
177 }
178 await using screen = await render(message);
179 await expect.element(screen.getByText("Cached text")).toBeVisible();
180 expect(parsed).toHaveBeenCalledTimes(1);
181});
182
183describe("ChatMarkdown favicon privacy", () => {
184 it("suppresses private link images while preserving public links across updates", async () => {
185 setup();
186 const markdown = (url: string) => <ChatMarkdown cwd="/tmp/project" text={`[Link](${url})`} />;
187 await using screen = await render(markdown("https://example.com"));
188 const { container, rerender } = screen;
189 expect([...container.querySelectorAll("img")].map((image) => image.src)).toEqual([
190 "https://www.google.com/s2/favicons?domain=example.com&sz=32",
191 ]);
192 for (const url of ["http://192.168.1.10:8080", "http://localhost:3000", "http://home.arpa"]) {
193 await rerender(markdown(url));
194 expect(container.querySelectorAll("img")).toHaveLength(0);
195 }
196 await rerender(markdown("https://example.com"));
197 expect(container.querySelectorAll("img")).toHaveLength(1);
198 await rerender(markdown("https://github.com/pingdotgg/t3code/pull/1"));
199 expect(container.querySelectorAll("img")).toHaveLength(0);
200 expect(container.querySelector("a svg")).not.toBeNull();
201 });
202});
203
204describe("ChatMarkdown streaming", () => {
205 it("runs only a complete single-line shell block after a click", async () => {
206 setup();
207 const onRunShellCommand = vi.fn();
208 const message = (text: string, isStreaming = false) => (
209 <ChatMarkdown
210 cwd="/tmp/project"
211 text={text}
212 isStreaming={isStreaming}
213 onRunShellCommand={onRunShellCommand}
214 />
215 );
216 await using screen = await render(message("```bash\necho hello\n```", true));
217 const { container, rerender } = screen;
218 const runButtons = () => buttonsLabelled(container, "Run in terminal");
219 expect(runButtons()).toHaveLength(0);
220
221 await rerender(message("```bash\necho hello\n```"));
222 await act(async () => runButtons()[0]!.click());
223 expect(onRunShellCommand).toHaveBeenCalledExactlyOnceWith("echo hello");
224
225 for (const text of [
226 "~~~bash\necho tilde\n~~~",
227 "> ```bash\n> echo quote\n> ```",
228 "````bash\necho four\n````",
229 "- Command\n\n ```bash\n echo list\n ```",
230 "```bash\r\necho crlf\r\n```\r",
231 ]) {
232 await rerender(message(text));
233 expect(runButtons()).toHaveLength(1);
234 }
235
236 for (const text of [
237 "```bash\necho one\necho two\n```",
238 "```typescript\necho hello\n```",
239 "```bash\n\n```",
240 "```bash\necho hello\n\n```",
241 "```bash\necho hello\\\n```",
242 "```bash\necho safe \u202e#\n```",
243 "```bash\necho incomplete",
244 "~~~bash\necho incomplete",
245 "````bash\necho incomplete\n```",
246 '<pre><code class="language-bash">echo html</code></pre>',
247 ]) {
248 await rerender(message(text));
249 expect(runButtons()).toHaveLength(0);
250 }
251 });
252
253 it("edits the current task text and marker after reusing a renderer", async () => {
254 setup();
255 let editedText: string | undefined;
256 let rerender: (next: ReactElement) => Promise<void> = async () => {};
257 const message = (text: string): ReactElement => (
258 <ChatMarkdown
259 cwd="/tmp/project"
260 text={text}
261 onTaskListChange={({ markerOffset, checked }) => {
262 editedText = setMarkdownTaskChecked(text, markerOffset, checked);
263 void rerender(message(editedText));
264 }}
265 />
266 );
267 await using rendered = await render(message("- [ ] First\n- [ ] Second"));
268 rerender = rendered.rerender;
269 const { container } = rendered;
270 const checkboxes = () => container.querySelectorAll<HTMLInputElement>('input[type="checkbox"]');
271 const original = checkboxes()[1]!;
272 await rerender(message("- [ ] A longer first task\n- [ ] Second"));
273 expect(checkboxes()[1]).toBe(original);
274
275 await act(async () => original.click());
276 expect(editedText).toBe("- [ ] A longer first task\n- [x] Second");
277 await vi.waitFor(() => expect(checkboxes()[1]!.checked).toBe(true));
278 });
279});
280
281describe("ChatMarkdown workspace file opens", () => {
282 const threadRef = {
283 environmentId: EnvironmentId.make("workspace"),
284 threadId: ThreadId.make("thread"),
285 };
286
287 it("keeps a newer absolute file open when an earlier repo-relative lookup finishes", async () => {
288 setup();
289 const result = AsyncResult.success({
290 entries: [{ path: "notes/a.md", kind: "file" }],
291 truncated: false,
292 });
293 let resolvePending!: (value: typeof result) => void;
294 const pending = new Promise<typeof result>((resolve) => {
295 resolvePending = resolve;
296 });
297 workspaceSearch.mockReturnValueOnce(pending);
298 using openFile = vi
299 .spyOn(useRightPanelStore.getState(), "openFile")
300 .mockImplementation(() => {});
301 await using screen = await renderText(
302 "[Notes](physics/notes/a.md) and [Other](/elsewhere/b.md:9)",
303 {
304 cwd: "/school/physics",
305 threadRef,
306 },
307 );
308 const { container } = screen;
309 const [notes, other] = container.querySelectorAll("a");
310 await act(async () => notes!.click());
311 expect(workspaceSearch).toHaveBeenCalledOnce();
312 expect(openFile).not.toHaveBeenCalled();
313
314 await act(async () => other!.click());
315 await act(async () => resolvePending(result));
316
317 expect(openFile).toHaveBeenCalledExactlyOnceWith(threadRef, "/elsewhere/b.md", 9);
318 expect(workspaceSearch).toHaveBeenCalledOnce();
319 });
320});
321
322describe("ChatMarkdown skill chips", () => {
323 it("shows the skill's details and opens its instructions", async () => {
324 setup();
325 const threadRef = {
326 environmentId: EnvironmentId.make("workspace"),
327 threadId: ThreadId.make("thread"),
328 };
329 await using screen = await renderText("Run $review now", {
330 threadRef,
331 skills: [
332 {
333 name: "review",
334 displayName: "Review",
335 description: "Reviews the current branch.",
336 path: "/skills/review/SKILL.md",
337 enabled: true,
338 },
339 ],
340 });
341 using openFile = vi
342 .spyOn(useRightPanelStore.getState(), "openFile")
343 .mockImplementation(() => {});
344
345 await userEvent.click(screen.getByRole("button", { name: "Skill Review. Show details" }));
346 await expect.element(page.getByText("Reviews the current branch.")).toBeVisible();
347 await userEvent.click(page.getByRole("button", { name: "View instructions" }));
348
349 expect(openFile).toHaveBeenCalledExactlyOnceWith(threadRef, "/skills/review/SKILL.md");
350 });
351});
352
353describe("ChatMarkdown headings", () => {
354 it("never gives two headings the same id, even when a suffix matches another heading", async () => {
355 setup();
356 await using screen = await renderText(
357 '## Setup\n\n## Setup\n\n## Setup-1\n\n<h2 id="install-1">Pinned</h2>\n\n## Install\n\n## Install',
358 { parseRawHtml: true },
359 );
360 const { container } = screen;
361 expect([...container.querySelectorAll("h2")].map((heading) => heading.id)).toEqual([
362 "user-content-setup",
363 "user-content-setup-1",
364 "user-content-setup-1-1",
365 "user-content-install-1",
366 "user-content-install",
367 "user-content-install-2",
368 ]);
369 });
370});
371
372describe("ChatMarkdown inline code selection", () => {
373 it("selects the whole inline code span on double-click, but only a word in fenced code", async () => {
374 setup();
375 await using screen = await renderText(
376 "Run `migration-gate --dry-run` first.\n\n```txt\nfenced-block word\n```",
377 );
378 await userEvent.dblClick(screen.getByText("migration-gate --dry-run"));
379 expect(window.getSelection()?.toString()).toBe("migration-gate --dry-run");
380
381 window.getSelection()?.removeAllRanges();
382 const fenced = screen.container.querySelector("pre code")!;
383 await userEvent.dblClick(fenced, { position: { x: 4, y: 4 } });
384 expect(window.getSelection()?.toString()).toBe("fenced");
385 });
386});
387
388describe("ChatMarkdown Windows file links", () => {
389 const environmentId = EnvironmentId.make("env-windows");
390 const renderWindows = (text: string, parseRawHtml: boolean) =>
391 renderText(text, {
392 cwd: "C:/Users/shawn/project",
393 environmentId,
394 lineBreaks: !parseRawHtml,
395 parseRawHtml,
396 });
397 const fileHrefs = (container: HTMLElement) =>
398 [...container.querySelectorAll(".chat-markdown-file-link")].map((chip) =>
399 chip.getAttribute("href"),
400 );
401
402 it("still rejects unsafe schemes", async () => {
403 setup();
404 for (const parseRawHtml of [true, false]) {
405 await using screen = await renderWindows(
406 "[unsafe](javascript:alert(1)) and [unknown](d:alert(1))",
407 parseRawHtml,
408 );
409 const { container } = screen;
410 expect(container.innerHTML).not.toContain("javascript:");
411 expect(container.innerHTML).not.toContain("d:alert");
412 expect(fileHrefs(container)).toEqual([]);
413 }
414 });
415});