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}));
9
10vi.mock("@effect/atom-react", () => ({ useAtomValue: () => null }));
11vi.mock("../assets/assetUrls", () => ({
12 useAssetUrlRefresh: () => vi.fn(),
13 useAssetUrlState: (_environmentId: unknown, resource: unknown) => {
14 testState.resources.push(resource);
15 if (testState.assetState === "loading") return { _tag: "Loading" };
16 if (testState.assetState === "failure") return { _tag: "Failure" };
17 return { _tag: "Success", url: "https://signed.test/workspace-image.svg" };
18 },
19}));
20vi.mock("../hooks/useTheme", () => ({ useTheme: () => ({ resolvedTheme: "dark" }) }));
21vi.mock("../state/use-atom-query-runner", () => ({ useAtomQueryRunner: () => vi.fn() }));
22vi.mock("../state/use-atom-command", () => ({ useAtomCommand: () => vi.fn() }));
23vi.mock("../state/session", async (importOriginal) => ({
24 ...(await importOriginal<typeof import("../state/session")>()),
25 usePreparedConnection: () => ({ _tag: "Loading" }),
26}));
27vi.mock("../state/entities", () => ({
28 readThreadShell: () => null,
29 useProjects: () => [],
30}));
31vi.mock("../remoteOpen", () => ({
32 useRemoteOpenResolution: () => ({ state: { mode: "local-exec" }, isResolved: true }),
33}));
34vi.mock("../editorPreferences", () => ({
35 useOpenInPreferredEditor: () => vi.fn(),
36 usePreferredEditor: () => [null, vi.fn()],
37}));
38vi.mock("~/lib/openPullRequestLink", () => ({
39 findProjectForChangeRequest: () => undefined,
40 matchesLinkedPullRequestUrl: () => false,
41 parseChangeRequestUrl: () => null,
42 useOpenChangeRequestLink: () => vi.fn(),
43}));
44
45import ChatMarkdown from "./ChatMarkdown";
46import { FileMarkdownPreview } from "./files/FileMarkdownPreview";
47
48const threadRef = {
49 environmentId: EnvironmentId.make("env-windows"),
50 threadId: ThreadId.make("thread-windows"),
51};
52
53function render(markdown: string): string {
54 return renderToStaticMarkup(
55 <ChatMarkdown cwd={"C:\\Users\\shawn\\project"} threadRef={threadRef} text={markdown} />,
56 );
57}
58
59function renderWithoutThread(markdown: string): string {
60 return renderToStaticMarkup(<ChatMarkdown cwd={"C:\\Users\\shawn\\project"} text={markdown} />);
61}
62
63function renderFilePreview(cwd: string, relativePath: string): string {
64 return renderToStaticMarkup(
65 <FileMarkdownPreview
66 cwd={cwd}
67 relativePath={relativePath}
68 text=""
69 threadRef={threadRef}
70 />,
71 );
72}
73
74function copiedMarkdownFrom(html: string): string {
75 const copy = /data-markdown-copy="([^"]*)"/.exec(html)?.[1]?.replaceAll(""", '"');
76 expect(copy).toBeDefined();
77 return copy ?? "";
78}
79
80function firstInlineStyle(html: string): Record<string, string> {
81 const style = /style="([^"]+)"/.exec(html)?.[1];
82 expect(style).toBeDefined();
83 return Object.fromEntries(
84 (style ?? "").split(";").map((declaration) => {
85 const separator = declaration.indexOf(":");
86 return [declaration.slice(0, separator), declaration.slice(separator + 1)];
87 }),
88 );
89}
90
91describe("ChatMarkdown workspace images", () => {
92 beforeEach(() => {
93 testState.resources = [];
94 testState.assetState = "success";
95 });
96
97 it.each([
98 ["/workspace/project", "docs/README.md", "/workspace/project/docs/images/diagram.png"],
99 [
100 "C:\\Users\\shawn\\project",
101 "docs\\README.md",
102 "C:\\Users\\shawn\\project\\docs\\images\\diagram.png",
103 ],
104 ["/workspace/project", "README.md", "/workspace/project/images/diagram.png"],
105 ])("resolves images beside a nested file in %s", (cwd, relativePath, expectedPath) => {
106 renderFilePreview(cwd, relativePath);
107
108 expect(testState.resources).toEqual([
109 {
110 _tag: "media-file",
111 threadId: threadRef.threadId,
112 path: expectedPath,
113 },
114 ]);
115 });
116
117 it("loads every Windows workspace path form through a signed asset URL", () => {
118 const imagePath = "C:/Users/shawn/project/.t3/workspace-image.svg";
119 const html = render(
120 [
121 "",
122 ``,
123 ``,
124 "",
125 ].join("\n\n"),
126 );
127
128 expect(testState.resources).toEqual([
129 {
130 _tag: "media-file",
131 threadId: threadRef.threadId,
132 path: "C:\\Users\\shawn\\project\\.t3\\workspace-image.svg",
133 },
134 { _tag: "media-file", threadId: threadRef.threadId, path: imagePath },
135 { _tag: "media-file", threadId: threadRef.threadId, path: imagePath },
136 {
137 _tag: "media-file",
138 threadId: threadRef.threadId,
139 path: "\\\\server\\share\\workspace-image.svg",
140 },
141 ]);
142 expect(html.match(/https:\/\/signed\.test\/workspace-image\.svg/g)).toHaveLength(4);
143 expect(html.match(/max-w-\[min\(100%,30rem\)\]/g)).toHaveLength(4);
144 expect(html.match(/max-h-\[30rem\]/g)).toHaveLength(4);
145 expect(html).not.toContain("Image unavailable");
146 });
147
148 it("loads a POSIX absolute path and file URI through a signed asset URL", () => {
149 const html = renderToStaticMarkup(
150 <ChatMarkdown
151 cwd="/workspace/project"
152 threadRef={threadRef}
153 text={[
154 "",
155 "",
156 ].join("\n\n")}
157 />,
158 );
159
160 expect(testState.resources).toEqual([
161 { _tag: "media-file", threadId: threadRef.threadId, path: "/tmp/embed-test/2.png" },
162 { _tag: "media-file", threadId: threadRef.threadId, path: "/tmp/embed-test/5.png" },
163 ]);
164 expect(html).not.toContain("Image unavailable");
165 });
166
167 it("normalizes a drive-absolute src in raw image HTML", () => {
168 const html = render(String.raw`<img src="D:\screens\workspace-image.svg" alt="raw">`);
169
170 expect(testState.resources).toEqual([
171 {
172 _tag: "media-file",
173 threadId: threadRef.threadId,
174 path: "D:/screens/workspace-image.svg",
175 },
176 ]);
177 expect(html).toContain("https://signed.test/workspace-image.svg");
178 });
179
180 it("keeps a tall image placeholder and loaded image at the same proportional bounds", () => {
181 const markdown = '<img src=".t3/workspace-image.svg" alt="sized" width="96" height="128">';
182 const loadedStyle = firstInlineStyle(render(markdown));
183 testState.assetState = "loading";
184 const loadingStyle = firstInlineStyle(render(markdown));
185
186 expect(loadedStyle).toMatchObject({
187 width: "96px",
188 height: "auto",
189 "aspect-ratio": "96 / 128",
190 "max-width": "min(100%, 30rem, 22.5rem)",
191 });
192 expect(loadingStyle).toEqual(loadedStyle);
193 });
194
195 it.each([
196 ["width", "max-width", "min(100%, 30rem, 300px)"],
197 ["height", "max-height", "min(30rem, 300px)"],
198 ])("treats a lone authored %s as a cap", (axis, constraint, expectedValue) => {
199 const markdown = `<img src=".t3/workspace-image.svg" alt="sized" ${axis}="300">`;
200 const loadedStyle = firstInlineStyle(render(markdown));
201
202 expect(loadedStyle).not.toHaveProperty(axis);
203 expect(loadedStyle).toHaveProperty(constraint, expectedValue);
204 });
205
206 it("keeps all images baseline-aligned and workspace images inline", () => {
207 const html = render(
208 " ",
209 );
210 const classNames = Array.from(html.matchAll(/<img[^>]*class="([^"]*)"/g), (match) =>
211 match[1]?.split(" "),
212 );
213
214 expect(classNames).toHaveLength(2);
215 expect(classNames[1]).toContain("inline-block!");
216
217 const centeredHtml = render(
218 '<p align="center"><img src=".t3/workspace-image.svg" alt="logo"></p>',
219 );
220 const centeredClassName = /<img[^>]*class="([^"]*)"/.exec(centeredHtml)?.[1];
221
222 expect(centeredClassName?.split(" ")).toContain("inline-block!");
223 });
224
225 it("retains an authored SVG fragment on the signed URL", () => {
226 const html = render("");
227
228 expect(html).toContain('src="https://signed.test/workspace-image.svg#logo"');
229 });
230
231 it.each(["success", "loading", "failure", "no-thread"] as const)(
232 "copies the authored workspace source (%s)",
233 (scenario) => {
234 if (scenario === "no-thread") {
235 const html = renderWithoutThread("");
236 expect(copiedMarkdownFrom(html)).toBe("");
237 return;
238 }
239
240 testState.assetState = scenario;
241 const html = render("");
242
243 expect(copiedMarkdownFrom(html)).toBe("");
244 },
245 );
246
247 it("copies an authored title with a workspace image", () => {
248 const html = render('');
249
250 expect(copiedMarkdownFrom(html)).toBe('');
251 });
252
253 it("escapes double quotes in an authored image title", () => {
254 const html = render(``);
255
256 expect(copiedMarkdownFrom(html)).toBe('');
257 });
258
259 it("escapes a closing bracket in authored image alt text", () => {
260 const markdown = String.raw`![build\] badge](badge.svg)`;
261
262 expect(copiedMarkdownFrom(render(markdown))).toBe(markdown);
263 });
264
265 it("escapes a literal backslash in authored image alt text", () => {
266 const markdown = String.raw``;
267
268 expect(copiedMarkdownFrom(render(markdown))).toBe(markdown);
269 });
270
271 it("escapes a literal backslash before a quote in an authored image title", () => {
272 const html = render(
273 String.raw`<img src="images/logo.svg" alt="logo" title="Path \"Title\"">`,
274 );
275
276 expect(copiedMarkdownFrom(html)).toBe(
277 String.raw``,
278 );
279 });
280
281 it("uses a static bounded-width placeholder while a signed asset URL loads", () => {
282 testState.assetState = "loading";
283
284 const html = render("");
285 const className = /<span[^>]*aria-label="Loading image"[^>]*class="([^"]*)"/.exec(html)?.[1];
286
287 expect(html).toContain('aria-label="Loading image"');
288 expect(html).not.toContain("animate-pulse");
289 expect(className?.split(" ")).toContain("w-64");
290 });
291
292 it("never passes a workspace source to a raw image when thread context is unavailable", () => {
293 const html = renderWithoutThread(
294 "",
295 );
296
297 expect(testState.resources).toEqual([]);
298 expect(html).toContain("Image unavailable");
299 expect(html).not.toContain("file://");
300 });
301
302 it("blocks unsupported image schemes instead of passing them to a raw image", () => {
303 const html = render("");
304
305 expect(testState.resources).toEqual([]);
306 expect(html).toContain("Image unavailable");
307 expect(html).not.toContain("content://");
308 });
309
310 it("keeps remote images directly loadable", () => {
311 const html = render("");
312
313 expect(testState.resources).toEqual([]);
314 expect(html).toContain('src="https://example.com/image.png"');
315 expect(html).toContain("max-w-[min(100%,30rem)]");
316 expect(html).toContain("max-h-[30rem]");
317 expect(html).not.toContain("Image unavailable");
318 });
319});