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