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

ChatMarkdown.workspace-images.test.tsx

408 lines14.9 KB

1import { EnvironmentId, ThreadId } from "@t3tools/contracts";
2import { renderToStaticMarkup } from "react-dom/server";
3import { beforeEach, describe, expect, it, vi } from "vite-plus/test";
4​
5const testState = vi.hoisted(() => ({
6 resources: [] as Array<unknown>,
7 assetState: "success" as "success" | "loading" | "failure",
8 imageDimensions: undefined as { width: number; height: number } | undefined,
9}));
10​
11vi.mock("@effect/atom-react", () => ({ useAtomValue: () => null }));
12vi.mock("../assets/assetUrls", () => ({
13 useAssetUrlRefresh: () => vi.fn(),
14 useAssetUrlState: (_environmentId: unknown, resource: unknown) => {
15 testState.resources.push(resource);
16 if (testState.assetState === "loading") return { _tag: "Loading" };
17 if (testState.assetState === "failure") return { _tag: "Failure" };
18 return {
19 _tag: "Success",
20 url: "https://signed.test/workspace-image.svg",
21 ...(testState.imageDimensions ? { imageDimensions: testState.imageDimensions } : {}),
22 };
23 },
24}));
25vi.mock("../hooks/useTheme", () => ({ useTheme: () => ({ resolvedTheme: "dark" }) }));
26vi.mock("../state/use-atom-query-runner", () => ({ useAtomQueryRunner: () => vi.fn() }));
27vi.mock("../state/use-atom-command", () => ({ useAtomCommand: () => vi.fn() }));
28vi.mock("../state/session", async (importOriginal) => ({
29 ...(await importOriginal<typeof import("../state/session")>()),
30 usePreparedConnection: () => ({ _tag: "Loading" }),
31}));
32vi.mock("../state/entities", () => ({
33 readThreadShell: () => null,
34 useProjects: () => [],
35 useServerConfigs: () => new Map(),
36}));
37vi.mock("../remoteOpen", () => ({
38 useRemoteOpenResolution: () => ({ state: { mode: "local-exec" }, isResolved: true }),
39}));
40vi.mock("../editorPreferences", () => ({
41 useOpenInPreferredEditor: () => vi.fn(),
42 usePreferredEditor: () => [null, vi.fn()],
43}));
44vi.mock("~/lib/openPullRequestLink", () => ({
45 findProjectOnChangeRequestHost: () => undefined,
46 parseChangeRequestUrl: () => null,
47 resolvePullRequestPreviewTarget: () => null,
48 useOpenChangeRequestLink: () => vi.fn(),
49}));
50​
51import ChatMarkdown, { ChatMarkdownAssetImage } from "./ChatMarkdown";
52import { FileMarkdownPreview } from "./files/FileMarkdownPreview";
53​
54const threadRef = {
55 environmentId: EnvironmentId.make("env-windows"),
56 threadId: ThreadId.make("thread-windows"),
57};
58​
59function render(markdown: string): string {
60 return renderToStaticMarkup(
61 <ChatMarkdown cwd={"C:\\Users\\shawn\\project"} threadRef={threadRef} text={markdown} />,
62 );
64​
65function renderWithoutThread(markdown: string): string {
66 return renderToStaticMarkup(<ChatMarkdown cwd={"C:\\Users\\shawn\\project"} text={markdown} />);
68​
69function renderFilePreview(cwd: string, relativePath: string): string {
70 return renderToStaticMarkup(
71 <FileMarkdownPreview
72 cwd={cwd}
73 relativePath={relativePath}
74 text="![diagram](images/diagram.png)"
75 threadRef={threadRef}
76 />,
77 );
79​
80function copiedMarkdownFrom(html: string): string {
81 const copy = /data-markdown-copy="([^"]*)"/.exec(html)?.[1]?.replaceAll("&quot;", '"');
82 expect(copy).toBeDefined();
83 return copy ?? "";
85​
86function firstInlineStyle(html: string): Record<string, string> {
87 const style = /style="([^"]+)"/.exec(html)?.[1];
88 expect(style).toBeDefined();
89 return Object.fromEntries(
90 (style ?? "").split(";").map((declaration) => {
91 const separator = declaration.indexOf(":");
92 return [declaration.slice(0, separator), declaration.slice(separator + 1)];
93 }),
94 );
96​
97describe("ChatMarkdown workspace images", () => {
98 beforeEach(() => {
99 testState.resources = [];
100 testState.assetState = "success";
101 testState.imageDimensions = undefined;
102 });
103​
104 it.each([
105 ["/workspace/project", "docs/README.md", "/workspace/project/docs/images/diagram.png"],
106 [
107 "C:\\Users\\shawn\\project",
108 "docs\\README.md",
109 "C:\\Users\\shawn\\project\\docs\\images\\diagram.png",
110 ],
111 ["/workspace/project", "README.md", "/workspace/project/images/diagram.png"],
112 ])("resolves images beside a nested file in %s", (cwd, relativePath, expectedPath) => {
113 renderFilePreview(cwd, relativePath);
114​
115 expect(testState.resources).toEqual([
116 {
117 _tag: "media-file",
118 threadId: threadRef.threadId,
119 path: expectedPath,
120 },
121 ]);
122 });
123​
124 it("loads every Windows workspace path form through a signed asset URL", () => {
125 const imagePath = "C:/Users/shawn/project/.t3/workspace-image.svg";
126 const html = render(
127 [
128 "![relative](.t3/workspace-image.svg)",
129 `![absolute](${imagePath})`,
130 `![file URL](file:///${imagePath})`,
131 "![UNC file URL](file://server/share/workspace-image.svg)",
132 ].join("\n\n"),
133 );
134​
135 expect(testState.resources).toEqual([
136 {
137 _tag: "media-file",
138 threadId: threadRef.threadId,
139 path: "C:\\Users\\shawn\\project\\.t3\\workspace-image.svg",
140 },
141 { _tag: "media-file", threadId: threadRef.threadId, path: imagePath },
142 { _tag: "media-file", threadId: threadRef.threadId, path: imagePath },
143 {
144 _tag: "media-file",
145 threadId: threadRef.threadId,
146 path: "\\\\server\\share\\workspace-image.svg",
147 },
148 ]);
149 expect(html.match(/<img[^>]*src="https:\/\/signed\.test\/workspace-image\.svg"/g)).toHaveLength(
150 4,
151 );
152 expect(html.match(/max-w-\[min\(100%,30rem\)\]/g)).toHaveLength(4);
153 expect(html).not.toContain("Image unavailable");
154 });
155​
156 it("loads a POSIX absolute path and file URI through a signed asset URL", () => {
157 const html = renderToStaticMarkup(
158 <ChatMarkdown
159 cwd="/workspace/project"
160 threadRef={threadRef}
161 text={[
162 "![absolute](/tmp/embed-test/2.png)",
163 "![file URL](file:///tmp/embed-test/5.png)",
164 ].join("\n\n")}
165 />,
166 );
167​
168 expect(testState.resources).toEqual([
169 { _tag: "media-file", threadId: threadRef.threadId, path: "/tmp/embed-test/2.png" },
170 { _tag: "media-file", threadId: threadRef.threadId, path: "/tmp/embed-test/5.png" },
171 ]);
172 expect(html).not.toContain("Image unavailable");
173 });
174​
175 it("normalizes a drive-absolute src in raw image HTML", () => {
176 const html = render(String.raw`<img src="D:\screens\workspace-image.svg" alt="raw">`);
177​
178 expect(testState.resources).toEqual([
179 {
180 _tag: "media-file",
181 threadId: threadRef.threadId,
182 path: "D:/screens/workspace-image.svg",
183 },
184 ]);
185 expect(html).toContain("https://signed.test/workspace-image.svg");
186 });
187​
188 it("keeps a tall image placeholder and loaded image at the same proportional bounds", () => {
189 const markdown = '<img src=".t3/workspace-image.svg" alt="sized" width="96" height="128">';
190 const loadedStyle = firstInlineStyle(render(markdown));
191 testState.assetState = "loading";
192 const loadingStyle = firstInlineStyle(render(markdown));
193​
194 expect(loadedStyle).toMatchObject({
195 width: "96px",
196 height: "auto",
197 "aspect-ratio": "96 / 128",
198 "max-width": "min(100%, 30rem, 22.5rem)",
199 });
200 expect(loadingStyle).toEqual(loadedStyle);
201 });
202​
203 it.each([
204 ["width", "max-width", "min(100%, 30rem, 300px)"],
205 ["height", "max-height", "min(30rem, 300px)"],
206 ])("treats a lone authored %s as a cap", (axis, constraint, expectedValue) => {
207 const markdown = `<img src=".t3/workspace-image.svg" alt="sized" ${axis}="300">`;
208 const loadedStyle = firstInlineStyle(render(markdown));
209​
210 expect(loadedStyle).not.toHaveProperty(axis);
211 expect(loadedStyle).toHaveProperty(constraint, expectedValue);
212 });
213​
214 it("keeps images that share a line inline and lets a standalone one reserve a slot", () => {
215 const html = render(
216 "![remote](https://example.com/badge.svg) ![workspace](.t3/workspace-image.svg)",
217 );
218​
219 // Two images in one paragraph are badges: neither reserves a slot.
220 expect(html).not.toContain("aspect-video");
221 expect(html).toContain('src="https://example.com/badge.svg"');
222 expect(html).toContain('src="https://signed.test/workspace-image.svg"');
223 expect(html.match(/<img[^>]*class="[^"]*inline-block![^"]*"/g)).toHaveLength(1);
224 expect(html).not.toContain("invisible");
225​
226 const centeredHtml = render(
227 '<p align="center"><img src=".t3/workspace-image.svg" alt="logo"></p>',
228 );
229 const frame = /<span[^>]*role="status"[^>]*>/.exec(centeredHtml)?.[0];
230​
231 expect(frame).toContain("inline-block!");
232 expect(frame).toContain("aspect-video");
233 });
234​
235 it("reserves a slot for an image that is the only content of its link", () => {
236 const html = render("[![shot](.t3/workspace-image.svg)](https://example.com)");
237​
238 expect(html).toContain("aspect-video");
239 });
240​
241 it.each([
242 ["a link", "Figure: [![shot](.t3/workspace-image.svg)](https://example.com)"],
243 ["emphasis", "**![shot](.t3/workspace-image.svg)** caption"],
244 ])("keeps an image wrapped in %s inline when text shares its block", (_wrapper, markdown) => {
245 expect(render(markdown)).not.toContain("aspect-video");
246 });
247​
248 it("keeps an authored id on a remote image so fragment links resolve", () => {
249 const html = render('<img id="diagram" src="https://example.com/diagram.png" alt="diagram">');
250​
251 // The sanitizer prefixes authored ids; the loading slot carries it too.
252 expect(html).toContain('<span id="user-content-diagram"');
253 });
254​
255 it("sizes the slot from server-reported dimensions so a portrait image never grows", () => {
256 testState.imageDimensions = { width: 720, height: 1400 };
257​
258 const style = firstInlineStyle(render("![shot](.t3/workspace-image.svg)"));
259​
260 expect(style).toMatchObject({ width: "720px", "aspect-ratio": "720 / 1400" });
261 });
262​
263 it("folds a caller's height cap into the width bound so the ratio holds", () => {
264 testState.imageDimensions = { width: 720, height: 1400 };
265​
266 const html = renderToStaticMarkup(
267 <ChatMarkdownAssetImage
268 environmentId={threadRef.environmentId}
269 resource={{ _tag: "media-file", threadId: threadRef.threadId, path: "/shot.png" }}
270 alt="shot"
271 maxHeightRem={16}
272 />,
273 );
274​
275 expect(firstInlineStyle(html)).toMatchObject({
276 "aspect-ratio": "720 / 1400",
277 "max-width": `min(100%, 30rem, ${(16 * 720) / 1400}rem)`,
278 });
279 });
280​
281 it("lets an authored size override server-reported dimensions", () => {
282 testState.imageDimensions = { width: 720, height: 1400 };
283​
284 const style = firstInlineStyle(
285 render('<img src=".t3/workspace-image.svg" alt="sized" width="96" height="128">'),
286 );
287​
288 expect(style).toMatchObject({ width: "96px", "aspect-ratio": "96 / 128" });
289 });
290​
291 it("reserves a slot for an image that is alone in a list item", () => {
292 expect(render("- ![shot](.t3/workspace-image.svg)")).toContain("aspect-video");
293 });
294​
295 it("retains an authored SVG fragment on the signed URL", () => {
296 const html = render("![logo](icons.svg#logo)");
297​
298 expect(html).toContain('src="https://signed.test/workspace-image.svg#logo"');
299 });
300​
301 it.each(["success", "loading", "failure", "no-thread"] as const)(
302 "copies the authored workspace source (%s)",
303 (scenario) => {
304 if (scenario === "no-thread") {
305 const html = renderWithoutThread("![diagram](images/diagram.png)");
306 expect(copiedMarkdownFrom(html)).toBe("![diagram](images/diagram.png)");
307 return;
308 }
309​
310 testState.assetState = scenario;
311 const html = render("![diagram](images/diagram.png#preview)");
312​
313 expect(copiedMarkdownFrom(html)).toBe("![diagram](images/diagram.png#preview)");
314 },
315 );
316​
317 it("copies an authored title with a workspace image", () => {
318 const html = render('![logo](images/logo.svg "My Title")');
319​
320 expect(copiedMarkdownFrom(html)).toBe('![logo](images/logo.svg "My Title")');
321 });
322​
323 it("escapes double quotes in an authored image title", () => {
324 const html = render(`![logo](images/logo.svg 'My "Title"')`);
325​
326 expect(copiedMarkdownFrom(html)).toBe('![logo](images/logo.svg "My \\"Title\\"")');
327 });
328​
329 it("escapes a closing bracket in authored image alt text", () => {
330 const markdown = String.raw`![build\] badge](badge.svg)`;
331​
332 expect(copiedMarkdownFrom(render(markdown))).toBe(markdown);
333 });
334​
335 it("escapes a literal backslash in authored image alt text", () => {
336 const markdown = String.raw`![folder\\name](badge.svg)`;
337​
338 expect(copiedMarkdownFrom(render(markdown))).toBe(markdown);
339 });
340​
341 it("escapes a literal backslash before a quote in an authored image title", () => {
342 const html = render(
343 String.raw`<img src="images/logo.svg" alt="logo" title="Path \&quot;Title\&quot;">`,
344 );
345​
346 expect(copiedMarkdownFrom(html)).toBe(
347 String.raw`![logo](images/logo.svg "Path \\\"Title\\\"")`,
348 );
349 });
350​
351 it("reserves the same 16:9 frame while the URL, the bytes, and a failure resolve", () => {
352 const frameClassName = (html: string) => {
353 const frame = /<span[^>]*role="(?:status|alert)"[^>]*>/.exec(html)?.[0] ?? "";
354 return /class="([^"]*)"/.exec(frame)?.[1]?.split(" ") ?? [];
355 };
356 const markdown = "![shot](.t3/workspace-image.svg)";
357​
358 testState.assetState = "loading";
359 const loadingUrl = frameClassName(render(markdown));
360 testState.assetState = "success";
361 const loadingBytes = render(markdown);
362 testState.assetState = "failure";
363 const failure = render(markdown);
364​
365 expect(loadingUrl).toEqual(expect.arrayContaining(["aspect-video", "w-full"]));
366 expect(loadingUrl).not.toContain("animate-pulse");
367 expect(frameClassName(loadingBytes)).toEqual(loadingUrl);
368 expect(frameClassName(failure)).toEqual(loadingUrl);
369 expect(failure).toContain("Image unavailable");
370 // The bytes are requested inside the frame but never paint at an unknown size.
371 expect(loadingBytes).toMatch(/<img[^>]*src="https:\/\/signed[^>]*class="invisible/);
372 expect(loadingBytes).not.toContain('loading="lazy"');
373 });
374​
375 it("gives a standalone remote image the same frame instead of a bare tag", () => {
376 const html = render("![remote](https://example.com/shot.png)");
377​
378 expect(html).toContain('aria-label="Loading image"');
379 expect(html).toContain("aspect-video");
380 });
381​
382 it("never passes a workspace source to a raw image when thread context is unavailable", () => {
383 const html = renderWithoutThread(
384 "![file URL](file:///C:/Users/shawn/project/workspace-image.svg)",
385 );
386​
387 expect(testState.resources).toEqual([]);
388 expect(html).toContain("Image unavailable");
389 expect(html).not.toContain("file://");
390 });
391​
392 it("blocks unsupported image schemes instead of passing them to a raw image", () => {
393 const html = render("![unsupported](content://media/image/1)");
394​
395 expect(testState.resources).toEqual([]);
396 expect(html).toContain("Image unavailable");
397 expect(html).not.toContain("content://");
398 });
399​
400 it("keeps remote images directly loadable", () => {
401 const html = render("![remote](https://example.com/image.png)");
402​
403 expect(testState.resources).toEqual([]);
404 expect(html).toContain('src="https://example.com/image.png"');
405 expect(html).toContain("max-w-[min(100%,30rem)]");
406 expect(html).not.toContain("Image unavailable");
407 });
408});