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

composerImages.test.ts

385 lines13.3 KB

1import { beforeEach, describe, expect, it, vi } from "vite-plus/test";
2import {
3 PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
4 PROVIDER_SEND_TURN_MAX_IMAGE_BYTES,
5} from "@t3tools/contracts";
6import type { ComposerAttachmentUploadState } from "./composerAttachmentUploadQueue";
7​
8const files = new Map<
9 string,
10 { base64: string; deleted: boolean; text?: string; mimeType?: string }
11>();
12​
13const manipulator = vi.hoisted(() => {
14 const state = { sourceSize: { width: 0, height: 0 }, renderedBase64: "cmVuZGVyZWQ=" };
15 const manipulate = vi.fn((source: string | { width: number; height: number }) => {
16 let size = typeof source === "string" ? state.sourceSize : source;
17 const context = {
18 resize: vi.fn((next: { width: number; height: number }) => {
19 size = next;
20 return context;
21 }),
22 renderAsync: vi.fn(async () => ({
23 ...size,
24 release: vi.fn(),
25 saveAsync: vi.fn(async (options: { format: string }) => {
26 const uri = `file:///cache/rendered.${options.format}`;
27 files.set(uri, { base64: state.renderedBase64, deleted: false });
28 return { uri, base64: state.renderedBase64 };
29 }),
30 })),
31 };
32 return context;
33 });
34 return { state, manipulate };
35});
36​
37vi.mock("expo-image-manipulator", () => ({
38 ImageManipulator: { manipulate: manipulator.manipulate },
39 SaveFormat: { JPEG: "jpeg", PNG: "png" },
40}));
41​
42vi.mock("expo-file-system", () => ({
43 File: class {
44 readonly uri: string;
45 readonly name: string;
46 readonly parentDirectory: { readonly uri: string };
47​
48 constructor(parent: string | { readonly uri: string }, name?: string) {
49 const parentUri = typeof parent === "string" ? parent : parent.uri;
50 this.uri = name ? `${parentUri}/${name}` : parentUri;
51 this.name = name ?? this.uri.split("/").at(-1) ?? "file";
52 this.parentDirectory = { uri: this.uri.slice(0, -(this.name.length + 1)) };
53 }
54​
55 get exists(): boolean {
56 return files.has(this.uri) && files.get(this.uri)?.deleted === false;
57 }
58​
59 get type(): string {
60 return files.get(this.uri)?.mimeType ?? "";
61 }
62​
63 get size(): number | null {
64 const entry = files.get(this.uri);
65 return entry && !entry.deleted
66 ? Math.floor((entry.base64.replace(/=+$/, "").length * 3) / 4)
67 : null;
68 }
69​
70 async copy(destination: { readonly uri: string }): Promise<void> {
71 const entry = files.get(this.uri);
72 if (!entry) throw new Error("missing file");
73 files.set(destination.uri, { ...entry });
74 }
75​
76 async base64(): Promise<string> {
77 const entry = files.get(this.uri);
78 if (!entry || entry.deleted) {
79 throw new Error("missing file");
80 }
81 return entry.base64;
82 }
83​
84 delete(): void {
85 const entry = files.get(this.uri);
86 if (entry) {
87 entry.deleted = true;
88 }
89 }
90​
91 create(): void {
92 files.set(this.uri, { base64: "", deleted: false });
93 }
94​
95 write(text: string): void {
96 files.set(this.uri, { base64: "", deleted: false, text });
97 }
98​
99 moveSync(destination: { readonly uri: string }): void {
100 const entry = files.get(this.uri);
101 if (!entry) throw new Error("missing staged file");
102 files.set(destination.uri, entry);
103 files.delete(this.uri);
104 }
105 },
106 Directory: class {
107 readonly uri: string;
108​
109 constructor(parent: string, name: string) {
110 this.uri = `${parent}/${name}`;
111 }
112​
113 create(): void {}
114 },
115 FileMode: { ReadOnly: "r", WriteOnly: "w" },
116 Paths: { document: "file:///documents" },
117}));
118​
119vi.mock("expo-crypto", () => ({
120 CryptoDigestAlgorithm: { SHA256: "SHA-256" },
121 digestStringAsync: async (_algorithm: string, data: string) => `sha256:${data}`,
122}));
123​
124vi.mock("./uuid", () => ({
125 uuidv4: () => "attachment-id",
126}));
127​
128import { convertPastedImagesToAttachments, persistComposerAttachmentFile } from "./composerImages";
129​
130const STORED = "file:///documents/t3-composer-attachments/attachment-id";
131​
132function oversizedPng(): string {
133 const png = Buffer.alloc(PROVIDER_SEND_TURN_MAX_IMAGE_BYTES + 1);
134 Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]).copy(png);
135 png.write("IHDR", 12);
136 png.writeUInt32BE(2000, 16);
137 png.writeUInt32BE(2000, 20);
138 return png.toString("base64");
140​
141describe("native pasted image cleanup", () => {
142 beforeEach(() => {
143 files.clear();
144 manipulator.state.renderedBase64 = "cmVuZGVyZWQ=";
145 });
146​
147 it("preserves the reported image type of extensionless Android content URIs", async () => {
148 const uri = "content://media/external/images/media/42";
149 files.set(uri, { base64: "aGVsbG8=", deleted: false, mimeType: "image/jpeg" });
150​
151 const { attachments } = await convertPastedImagesToAttachments({
152 uris: [uri],
153 existingCount: 0,
154 });
155​
156 expect(attachments).toEqual([
157 expect.objectContaining({
158 name: "pasted-image.jpeg",
159 mimeType: "image/jpeg",
160 fileUri: `${STORED}-pasted-image.jpeg`,
161 previewUri: `${STORED}-pasted-image.jpeg`,
162 contentDigest: "sha256:aGVsbG8=",
163 }),
164 ]);
165 expect(attachments[0]).not.toHaveProperty("dataUrl");
166 expect(files.get(`${STORED}-pasted-image.jpeg`)?.base64).toBe("aGVsbG8=");
167 expect(files.get(uri)?.deleted).toBe(false);
168 });
169​
170 it("renders unsupported images to JPEG and removes the cache file after attaching", async () => {
171 const uri = "content://media/external/images/media/43";
172 files.set(uri, { base64: "b3JpZ2luYWw=", deleted: false, mimeType: "image/heic" });
173 manipulator.state.sourceSize = { width: 100, height: 100 };
174​
175 const { attachments } = await convertPastedImagesToAttachments({
176 uris: [uri],
177 existingCount: 0,
178 });
179​
180 expect(attachments).toEqual([
181 expect.objectContaining({
182 name: "pasted-image.jpeg",
183 mimeType: "image/jpeg",
184 fileUri: `${STORED}-pasted-image.jpeg`,
185 }),
186 ]);
187 expect(files.get(`${STORED}-pasted-image.jpeg`)?.base64).toBe("cmVuZGVyZWQ=");
188 expect(files.get("file:///cache/rendered.jpeg")?.deleted).toBe(true);
189 expect(files.get(uri)?.deleted).toBe(false);
190 });
191​
192 it("removes the rendered JPEG when its bytes exceed the image limit", async () => {
193 const uri = "content://media/external/images/media/43";
194 files.set(uri, { base64: "b3JpZ2luYWw=", deleted: false, mimeType: "image/heic" });
195 manipulator.state.sourceSize = { width: 100, height: 100 };
196 manipulator.state.renderedBase64 = "A".repeat(
197 Math.ceil((PROVIDER_SEND_TURN_MAX_IMAGE_BYTES + 1) / 3) * 4,
198 );
199​
200 const { attachments } = await convertPastedImagesToAttachments({
201 uris: [uri],
202 existingCount: 0,
203 });
204​
205 expect(attachments).toEqual([]);
206 expect(files.get("file:///cache/rendered.jpeg")?.deleted).toBe(true);
207 expect(files.get(uri)?.deleted).toBe(false);
208 });
209​
210 it("stores owned pastes in an attachment file and deletes the source", async () => {
211 const uri =
212 "file:///private/var/mobile/Containers/Data/Application/app/tmp/t3-composer-paste/id.png";
213 const gif =
214 "file:///private/var/mobile/Containers/Data/Application/app/tmp/t3-composer-paste/anim.gif";
215 files.set(uri, { base64: "aGVsbG8=", deleted: false });
216 files.set(gif, { base64: "R0lGODlh", deleted: false });
217​
218 const { attachments } = await convertPastedImagesToAttachments({
219 uris: [uri, gif],
220 existingCount: 0,
221 });
222​
223 expect(attachments).toEqual([
224 expect.objectContaining({
225 fileUri: `${STORED}-pasted-image.png`,
226 previewUri: `${STORED}-pasted-image.png`,
227 }),
228 expect.objectContaining({ mimeType: "image/gif", fileUri: `${STORED}-pasted-image.gif` }),
229 ]);
230 expect(files.get(`${STORED}-pasted-image.png`)?.base64).toBe("aGVsbG8=");
231 expect(files.get(`${STORED}-pasted-image.gif`)?.base64).toBe("R0lGODlh");
232 expect(files.get(uri)?.deleted).toBe(true);
233 expect(files.get(gif)?.deleted).toBe(true);
234 });
235​
236 it("deletes rejected and overflow owned files without deleting user-owned files", async () => {
237 const rejected =
238 "file:///private/var/mobile/Containers/Data/Application/app/tmp/t3-composer-paste/bad.png";
239 const overflow =
240 "file:///private/var/mobile/Containers/Data/Application/app/tmp/t3-composer-paste/overflow.png";
241 const userOwned = "file:///private/var/mobile/photos/library.png";
242 files.set(rejected, { base64: "", deleted: false });
243 files.set(overflow, { base64: "aGVsbG8=", deleted: false });
244 files.set(userOwned, { base64: "aGVsbG8=", deleted: false });
245​
246 await convertPastedImagesToAttachments({
247 uris: [rejected, overflow, userOwned],
248 existingCount: PROVIDER_SEND_TURN_MAX_ATTACHMENTS - 1,
249 });
250​
251 expect(files.get(rejected)?.deleted).toBe(true);
252 expect(files.get(overflow)?.deleted).toBe(true);
253 expect(files.get(userOwned)?.deleted).toBe(false);
254 });
255​
256 it("re-renders an over-limit paste whose dimensions already fit, like the photo picker", async () => {
257 const uri =
258 "file:///private/var/mobile/Containers/Data/Application/app/tmp/t3-composer-paste/photo.png";
259 files.set(uri, { base64: oversizedPng(), deleted: false });
260 manipulator.state.sourceSize = { width: 2000, height: 2000 };
261​
262 const { attachments } = await convertPastedImagesToAttachments({
263 uris: [uri],
264 existingCount: 0,
265 });
266​
267 expect(attachments).toHaveLength(1);
268 expect(attachments[0]?.sizeBytes).toBeLessThanOrEqual(PROVIDER_SEND_TURN_MAX_IMAGE_BYTES);
269 expect(files.get("file:///cache/rendered.jpeg")?.deleted).toBe(true);
270 });
271​
272 it("keeps the readable images of a paste and still reports the one it dropped", async () => {
273 const gone =
274 "file:///private/var/mobile/Containers/Data/Application/app/tmp/t3-composer-paste/gone.png";
275 const kept =
276 "file:///private/var/mobile/Containers/Data/Application/app/tmp/t3-composer-paste/kept.png";
277 files.set(kept, { base64: "aGVsbG8=", deleted: false });
278​
279 const result = await convertPastedImagesToAttachments({ uris: [gone, kept], existingCount: 0 });
280​
281 expect(result.attachments).toEqual([
282 expect.objectContaining({ fileUri: `${STORED}-pasted-image.png` }),
283 ]);
284 expect(result.error).toBe("Could not read a pasted image.");
285 });
286​
287 it("reports the size limit when even the JPEG re-render is too large", async () => {
288 const uri =
289 "file:///private/var/mobile/Containers/Data/Application/app/tmp/t3-composer-paste/huge.png";
290 files.set(uri, { base64: oversizedPng(), deleted: false });
291 manipulator.state.sourceSize = { width: 2000, height: 2000 };
292 manipulator.state.renderedBase64 = oversizedPng();
293​
294 const result = await convertPastedImagesToAttachments({ uris: [uri], existingCount: 0 });
295​
296 expect(result).toEqual({
297 attachments: [],
298 error: "A pasted image exceeds the 10 MB attachment limit.",
299 });
300 expect(files.get(uri)?.deleted).toBe(true);
301 });
302});
303​
304describe("persistComposerAttachmentFile", () => {
305 beforeEach(() => {
306 files.clear();
307 });
308​
309 it("stores picked files under a name Android's java.net.URI accepts", async () => {
310 const source = "file:///cache/DocumentPicker/Report [draft].pdf";
311 files.set(source, { base64: "JVBERg==", deleted: false });
312​
313 const fileUri = await persistComposerAttachmentFile(source, "Report [draft].pdf");
314​
315 // expo-file-system encodes spaces and `%` but leaves `[`, `]`, `|` and `^` raw.
316 expect(fileUri.split("/").at(-1)).toMatch(/^[\w\-.!~*'();:@&=+$, %]+\.pdf$/);
317 });
318});
319​
320describe("composerStripAttachments", () => {
321 const image = {
322 id: "img-1",
323 type: "image" as const,
324 name: "shot.jpg",
325 mimeType: "image/jpeg",
326 sizeBytes: 10,
327 dataUrl: "",
328 };
329 const video = {
330 id: "vid-1",
331 type: "file" as const,
332 name: "clip.mp4",
333 mimeType: "video/mp4",
334 sizeBytes: 20,
335 fileUri: "file:///clip.mp4",
336 };
337 const doc = {
338 id: "doc-1",
339 type: "file" as const,
340 name: "notes.txt",
341 mimeType: "text/plain",
342 sizeBytes: 5,
343 fileUri: "file:///notes.txt",
344 };
345​
346 it("keeps media beside a document rather than dropping the whole strip", async () => {
347 const { composerStripAttachments } = await import("./composerImages");
348 expect(
349 composerStripAttachments([doc, image, video] as never, () => ({
350 status: "uploading",
351 progress: 0.5,
352 })).map((a) => a.id),
353 ).toEqual(["img-1", "vid-1"]);
354 });
355​
356 it("shows a document whose upload failed until its retry finishes", async () => {
357 const { composerStripAttachments } = await import("./composerImages");
358 const strip = (upload: ComposerAttachmentUploadState) =>
359 composerStripAttachments([doc, image] as never, (a) =>
360 a.id === "doc-1" ? upload : undefined,
361 ).map((a) => a.id);
362 expect(strip({ status: "failed", reason: "Service unavailable" })).toEqual(["doc-1", "img-1"]);
363 expect(strip({ status: "uploading", progress: 0.4, retrying: true })).toEqual([
364 "doc-1",
365 "img-1",
366 ]);
367 expect(strip({ status: "ready" })).toEqual(["img-1"]);
368 });
369​
370 it("keeps oversized document-picked images visible while sending them as files", async () => {
371 const { composerStripAttachments, isComposerImageAttachment } =
372 await import("./composerImages");
373 const oversizedImage = {
374 ...video,
375 id: "large-image",
376 name: "large.png",
377 mimeType: "image/png",
378 fileUri: "file:///large.png",
379 sizeBytes: PROVIDER_SEND_TURN_MAX_IMAGE_BYTES + 1,
380 };
381​
382 expect(composerStripAttachments([oversizedImage], () => undefined)).toEqual([oversizedImage]);
383 expect(isComposerImageAttachment(oversizedImage)).toBe(false);
384 });
385});