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

composerFiles.test.ts

1,046 lines36.2 KB

1import { beforeEach, describe, expect, it, vi } from "vite-plus/test";
2import { PROVIDER_SEND_TURN_MAX_IMAGE_BYTES } from "@t3tools/contracts";
3import type { ImagePickerAsset } from "expo-image-picker";
4​
5// Bytes of image files the tests create, so stored attachments can be read back and measured.
6const imageFiles = new Map<string, string>();
7​
8const mocks = vi.hoisted(() => ({
9 documentUri: "file:///documents",
10 pickFile: vi.fn(),
11 pickMedia: vi.fn(),
12 copy: vi.fn(),
13 delete: vi.fn(),
14 open: vi.fn(),
15 size: vi.fn(),
16 readBase64: vi.fn(),
17 manipulate: vi.fn(),
18 release: vi.fn(),
19}));
20​
21vi.mock("expo-file-system", () => {
22 class Directory {
23 readonly uri: string;
24​
25 constructor(root: string | { readonly uri: string }, name: string) {
26 this.uri = `${typeof root === "string" ? root : root.uri}/${name}`;
27 }
28​
29 create(): void {}
30 }
31​
32 class File {
33 readonly uri: string;
34​
35 constructor(source: string | Directory, name?: string) {
36 this.uri = source instanceof Directory ? `${source.uri}/${name}` : source;
37 }
38​
39 get exists(): boolean {
40 return true;
41 }
42​
43 get size(): number | null {
44 return mocks.size(this.uri) ?? null;
45 }
46​
47 get name(): string {
48 return this.uri.split("/").at(-1) ?? "";
49 }
50​
51 get type(): string {
52 return "video/quicktime";
53 }
54​
55 create(): void {}
56​
57 open(mode: string) {
58 return mocks.open(this.uri, mode);
59 }
60​
61 async copy(destination: File): Promise<void> {
62 mocks.copy(this.uri, destination.uri);
63 const bytes = imageFiles.get(this.uri);
64 if (bytes !== undefined) imageFiles.set(destination.uri, bytes);
65 }
66​
67 async base64(): Promise<string> {
68 return mocks.readBase64(this.uri);
69 }
70​
71 delete(): void {
72 mocks.delete(this.uri);
73 }
74 }
75​
76 return {
77 Directory,
78 File,
79 FileMode: { ReadOnly: "r", WriteOnly: "w" },
80 Paths: {
81 get document() {
82 return { uri: mocks.documentUri };
83 },
84 },
85 };
86});
87​
88vi.mock("expo-image-picker", () => ({ launchImageLibraryAsync: mocks.pickMedia }));
89vi.mock("expo-document-picker", () => ({ getDocumentAsync: mocks.pickFile }));
90vi.mock("expo-image-manipulator", () => ({
91 SaveFormat: { JPEG: "jpeg", PNG: "png", WEBP: "webp" },
92 ImageManipulator: { manipulate: mocks.manipulate },
93}));
94vi.mock("./uuid", () => ({ uuidv4: () => "attachment-id" }));
95​
96import {
97 persistComposerAttachmentFile,
98 isComposerImageAttachment,
99 pickComposerFiles,
100 pickComposerImages,
101 pickComposerMedia,
102 removePersistedComposerAttachmentFile,
103} from "./composerImages";
104import { isForegroundHandoffActive } from "./foreground-handoff";
105import { retainComposerAttachmentFile } from "./composerAttachmentFiles";
106​
107const STORED = "file:///documents/t3-composer-attachments/attachment-id";
108​
109function sizeOtherFilesAs(bytes: number): void {
110 mocks.size.mockImplementation((uri: string) => {
111 if (uri.startsWith("content:")) return null;
112 const stored = imageFiles.get(uri);
113 return stored === undefined ? bytes : Buffer.from(stored, "base64").byteLength;
114 });
116​
117describe("composer file attachments", () => {
118 beforeEach(() => {
119 mocks.documentUri = "file:///documents";
120 mocks.pickFile.mockReset();
121 mocks.pickMedia.mockReset();
122 mocks.copy.mockReset();
123 mocks.delete.mockReset();
124 mocks.open.mockReset();
125 mocks.size.mockReset();
126 mocks.readBase64.mockReset();
127 mocks.manipulate.mockReset();
128 imageFiles.clear();
129 sizeOtherFilesAs(42);
130 });
131​
132 describe("photo library image conversion", () => {
133 const rendered = { uri: "file:///cache/ImageManipulator/photo.jpg", base64: "/9j/2Q==" };
134 const photo: ImagePickerAsset = {
135 uri: "file:///picker/photo.heic",
136 type: "image",
137 fileName: "photo.HEIC",
138 mimeType: "image/heic",
139 fileSize: 4 * 1024 * 1024,
140 width: 4032,
141 height: 3024,
142 };
143 type Size = { width: number; height: number };
144 const native = {
145 size: { width: 1, height: 1 } as Size,
146 resizes: [] as Size[],
147 saved: rendered as { uri: string; base64?: string },
148 encode: null as ((size: Size, format: string) => { uri: string; base64?: string }) | null,
149 };
150​
151 beforeEach(() => {
152 native.size = { width: 1, height: 1 };
153 native.resizes = [];
154 native.saved = rendered;
155 native.encode = null;
156 mocks.manipulate.mockReset();
157 mocks.release.mockReset();
158 mocks.manipulate.mockImplementation((source: string | Size) => {
159 let size = typeof source === "string" ? native.size : source;
160 const context = {
161 resize(next: Size) {
162 native.resizes.push(next);
163 size = next;
164 return context;
165 },
166 renderAsync: async () => ({
167 width: size.width,
168 height: size.height,
169 release: mocks.release,
170 saveAsync: async (options: { format: string }) => {
171 const saved = native.encode?.(size, options.format) ?? native.saved;
172 if (saved.base64 !== undefined) imageFiles.set(saved.uri, saved.base64);
173 return saved;
174 },
175 }),
176 };
177 return context;
178 });
179 });
180​
181 it.each(["image/heic", "image/heif", undefined])(
182 "renders a %s photo to JPEG natively and stores it in an owned file",
183 async (mimeType) => {
184 mocks.pickMedia.mockResolvedValue({
185 canceled: false,
186 assets: [{ ...photo, mimeType }],
187 });
188​
189 const result = await pickComposerImages({ existingCount: 0 });
190​
191 expect(mocks.pickMedia).toHaveBeenCalledWith(expect.objectContaining({ base64: false }));
192 expect(mocks.manipulate).toHaveBeenCalledWith(photo.uri);
193 expect(mocks.readBase64).not.toHaveBeenCalled();
194 expect(result).toEqual({
195 images: [
196 {
197 id: "attachment-id",
198 type: "image",
199 name: "photo.jpg",
200 mimeType: "image/jpeg",
201 sizeBytes: 4,
202 fileUri: `${STORED}-photo.jpg`,
203 previewUri: `${STORED}-photo.jpg`,
204 },
205 ],
206 error: null,
207 });
208 },
209 );
210​
211 it.each([
212 { extension: "png", mimeType: "image/png", base64: "iVBORw0KGgo=" },
213 { extension: "gif", mimeType: "image/gif", base64: "R0lGODlh" },
214 { extension: "webp", mimeType: "image/webp", base64: "UklGRgQAAABXRUJQ" },
215 ])("keeps original $extension bytes from the picker file", async (original) => {
216 const name = `photo.${original.extension}`;
217 mocks.pickMedia.mockResolvedValue({
218 canceled: false,
219 assets: [{ ...photo, fileName: name, mimeType: original.mimeType }],
220 });
221 mocks.readBase64.mockResolvedValue(original.base64);
222 imageFiles.set(photo.uri, original.base64);
223​
224 const result = await pickComposerImages({ existingCount: 0 });
225​
226 expect(mocks.manipulate).not.toHaveBeenCalled();
227 expect(mocks.readBase64).toHaveBeenCalledWith(photo.uri);
228 expect(result.error).toBeNull();
229 expect(result.images).toEqual([
230 expect.objectContaining({
231 name,
232 mimeType: original.mimeType,
233 fileUri: `${STORED}-${name}`,
234 sizeBytes: Buffer.from(original.base64, "base64").byteLength,
235 }),
236 ]);
237 expect(result.images[0]).not.toHaveProperty("dataUrl");
238 expect(imageFiles.get(`${STORED}-${name}`)).toBe(original.base64);
239 });
240​
241 it("shrinks a fitted PNG further when re-encoding it exceeds the image limit", async () => {
242 const header = Buffer.alloc(24);
243 Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]).copy(header);
244 header.write("IHDR", 12);
245 header.writeUInt32BE(1668, 16);
246 header.writeUInt32BE(2388, 20);
247 native.size = { width: 1668, height: 2388 };
248 // Native PNG encoding of the 2000px resample is larger than the 7 MB original.
249 native.encode = (size, format) => ({
250 uri: `file:///cache/fitted-${size.width}x${size.height}.${format}`,
251 base64: Buffer.alloc(size.width * size.height * 4).toString("base64"),
252 });
253 sizeOtherFilesAs(7 * 1024 * 1024);
254 mocks.readBase64.mockResolvedValue(header.toString("base64"));
255 mocks.pickMedia.mockResolvedValue({
256 canceled: false,
257 assets: [{ ...photo, fileName: "IMG_9280.png", mimeType: "image/png" }],
258 });
259​
260 const result = await pickComposerImages({ existingCount: 0 });
261​
262 expect(result.error).toBeNull();
263 const [image] = result.images;
264 const last = native.resizes.at(-1)!;
265 expect(native.resizes[0]).toEqual({ width: 1397, height: 2000 });
266 expect(Math.max(last.width, last.height)).toBeLessThan(2000);
267 expect(image).toEqual(
268 expect.objectContaining({
269 name: "IMG_9280.png",
270 mimeType: "image/png",
271 sizeBytes: last.width * last.height * 4,
272 fileUri: `${STORED}-IMG_9280.png`,
273 }),
274 );
275 expect(image!.sizeBytes).toBeLessThanOrEqual(PROVIDER_SEND_TURN_MAX_IMAGE_BYTES);
276 expect(mocks.delete).toHaveBeenCalledWith("file:///cache/fitted-1397x2000.png");
277 expect(imageFiles.get(image!.previewUri)).toBe(
278 Buffer.alloc(last.width * last.height * 4).toString("base64"),
279 );
280 });
281​
282 it("measures the picker file instead of trusting the reported size", async () => {
283 mocks.pickMedia.mockResolvedValue({
284 canceled: false,
285 assets: [{ ...photo, fileName: "photo.png", mimeType: "image/png", fileSize: 42 }],
286 });
287 sizeOtherFilesAs(PROVIDER_SEND_TURN_MAX_IMAGE_BYTES + 1);
288​
289 const result = await pickComposerImages({ existingCount: 0 });
290​
291 expect(mocks.readBase64).not.toHaveBeenCalled();
292 expect(mocks.manipulate).toHaveBeenCalledWith(photo.uri);
293 expect(result.images).toEqual([expect.objectContaining({ mimeType: "image/jpeg" })]);
294 });
295​
296 // regression: #11440 render photo library picks to a bounded JPEG off the JS thread
297 it("renders a supported original whose size cannot be measured", async () => {
298 mocks.pickMedia.mockResolvedValue({
299 canceled: false,
300 assets: [
301 { ...photo, uri: "content://media/1", fileName: "photo.png", mimeType: "image/png" },
302 ],
303 });
304​
305 const result = await pickComposerImages({ existingCount: 0 });
306​
307 expect(mocks.readBase64).not.toHaveBeenCalled();
308 expect(mocks.manipulate).toHaveBeenCalledWith("content://media/1");
309 expect(result.images).toEqual([expect.objectContaining({ mimeType: "image/jpeg" })]);
310 });
311​
312 it("checks the rendered JPEG against the image limit", async () => {
313 native.saved = {
314 uri: rendered.uri,
315 base64:
316 rendered.base64.slice(0, 4) +
317 "A".repeat(Math.ceil(PROVIDER_SEND_TURN_MAX_IMAGE_BYTES / 3) * 4),
318 };
319 mocks.pickMedia.mockResolvedValue({ canceled: false, assets: [photo] });
320​
321 await expect(pickComposerImages({ existingCount: 0 })).resolves.toEqual({
322 images: [],
323 error: "'photo.HEIC' exceeds the 10 MB attachment limit.",
324 });
325 });
326​
327 it("retains a rendered photo when another original cannot be read", async () => {
328 mocks.pickMedia.mockResolvedValue({
329 canceled: false,
330 assets: [{ ...photo, fileName: "missing.gif", mimeType: "image/gif" }, photo],
331 });
332 mocks.readBase64.mockRejectedValue(new Error("missing file"));
333​
334 const result = await pickComposerImages({ existingCount: 0 });
335​
336 expect(result.images).toEqual([expect.objectContaining({ name: "photo.jpg" })]);
337 expect(result.error).toBe("Failed to read 'missing.gif'.");
338 });
339​
340 // regression: #11440 render photo library picks to a bounded JPEG off the JS thread
341 it("reports a photo the native renderer cannot decode", async () => {
342 mocks.manipulate.mockImplementation(() => ({
343 resize: () => {
344 throw new Error("unreachable");
345 },
346 renderAsync: () => Promise.reject(new Error("corrupt")),
347 }));
348 mocks.pickMedia.mockResolvedValue({ canceled: false, assets: [photo] });
349​
350 await expect(pickComposerImages({ existingCount: 0 })).resolves.toEqual({
351 images: [],
352 error: "Failed to read 'photo.HEIC'.",
353 });
354 });
355 });
356​
357 describe("photo library videos", () => {
358 const image: ImagePickerAsset = {
359 uri: "file:///picker/photo.png",
360 type: "image",
361 fileName: "photo.png",
362 mimeType: "image/png",
363 fileSize: 3,
364 width: 1,
365 height: 1,
366 };
367​
368 beforeEach(() => {
369 mocks.readBase64.mockResolvedValue("YWJj");
370 });
371 const video: ImagePickerAsset = {
372 uri: "file:///picker/clip.mov",
373 type: "video",
374 fileName: "clip.mov",
375 mimeType: "video/quicktime",
376 fileSize: 20 * 1024 * 1024,
377 base64: null,
378 width: 1920,
379 height: 1080,
380 };
381​
382 it("retains mixed photos and videos, keeping video bytes in durable file storage", async () => {
383 mocks.pickMedia.mockResolvedValue({ canceled: false, assets: [image, video] });
384 mocks.size.mockImplementation((uri: string) =>
385 uri.endsWith("clip.mov") ? video.fileSize : 3,
386 );
387​
388 const result = await pickComposerMedia({ existingCount: 0, maxVideoBytes: 50 * 1024 * 1024 });
389​
390 expect(mocks.pickMedia).toHaveBeenCalledWith(
391 expect.objectContaining({
392 mediaTypes: ["images", "videos"],
393 shouldDownloadFromNetwork: true,
394 }),
395 );
396 expect(result).toEqual({
397 attachments: [
398 expect.objectContaining({ type: "image", fileUri: `${STORED}-photo.png` }),
399 {
400 id: "attachment-id",
401 type: "file",
402 name: "clip.mov",
403 mimeType: "video/quicktime",
404 sizeBytes: video.fileSize,
405 fileUri: "file:///documents/t3-composer-attachments/attachment-id-clip.mov",
406 },
407 ],
408 error: null,
409 });
410 expect(mocks.copy).toHaveBeenCalledWith(
411 video.uri,
412 "file:///documents/t3-composer-attachments/attachment-id-clip.mov",
413 );
414 expect(mocks.delete).not.toHaveBeenCalled();
415 });
416​
417 it("does not persist videos when the destination lacks file support", async () => {
418 mocks.pickMedia.mockResolvedValue({ canceled: false, assets: [video, image] });
419​
420 const result = await pickComposerMedia({ existingCount: 0 });
421​
422 expect(result.attachments).toEqual([expect.objectContaining({ type: "image" })]);
423 expect(result.error).toBe("Video attachments are unavailable here.");
424 expect(mocks.copy).not.toHaveBeenCalledWith(video.uri, expect.anything());
425 });
426​
427 it("uses local video metadata when the picker omits its name, MIME type, or size", async () => {
428 mocks.pickMedia.mockResolvedValue({
429 canceled: false,
430 assets: [{ ...video, fileName: null, mimeType: undefined, fileSize: undefined }],
431 });
432​
433 const result = await pickComposerMedia({ existingCount: 0, maxVideoBytes: 1024 });
434​
435 expect(result.error).toBeNull();
436 expect(result.attachments).toEqual([
437 expect.objectContaining({
438 type: "file",
439 name: "clip.mov",
440 mimeType: "video/quicktime",
441 sizeBytes: 42,
442 }),
443 ]);
444 });
445​
446 it.each([
447 {
448 reason: "actual size exceeds the server limit",
449 reported: 42,
450 stored: 2 * 1024 * 1024,
451 limit: 1024 * 1024,
452 error: "'clip.mov' exceeds the 1 MB attachment limit.",
453 },
454 {
455 reason: "stored copy is empty",
456 reported: 42,
457 stored: 0,
458 limit: 1024 * 1024,
459 error: "'clip.mov' is empty or could not be read.",
460 },
461 {
462 reason: "server advertises more than the contract limit",
463 reported: 51 * 1024 * 1024,
464 stored: 42,
465 limit: 80 * 1024 * 1024,
466 error: "'clip.mov' exceeds the 50 MB attachment limit.",
467 },
468 ])(
469 "rejects a video when $reason while retaining the selected photo",
470 async ({ reported, stored, limit, error }) => {
471 mocks.pickMedia.mockResolvedValue({
472 canceled: false,
473 assets: [{ ...video, fileSize: reported }, image],
474 });
475 mocks.size.mockImplementation((uri: string) => (uri.endsWith("clip.mov") ? stored : 3));
476​
477 const result = await pickComposerMedia({ existingCount: 0, maxVideoBytes: limit });
478​
479 expect(result).toEqual({
480 attachments: [expect.objectContaining({ type: "image" })],
481 error,
482 });
483 if (stored === 0) {
484 expect(mocks.delete).toHaveBeenCalledWith(
485 "file:///documents/t3-composer-attachments/attachment-id-clip.mov",
486 );
487 }
488 },
489 );
490​
491 it("applies the remaining attachment slots to photos and videos together", async () => {
492 mocks.pickMedia.mockResolvedValue({ canceled: false, assets: [image, video] });
493​
494 const result = await pickComposerMedia({
495 existingCount: 99,
496 maxVideoBytes: 50 * 1024 * 1024,
497 });
498​
499 expect(result.attachments).toEqual([expect.objectContaining({ type: "image" })]);
500 expect(result.error).toBe("You can attach up to 100 attachments per message.");
501 expect(mocks.pickMedia).toHaveBeenCalledWith(expect.objectContaining({ selectionLimit: 1 }));
502 expect(mocks.copy).not.toHaveBeenCalledWith(video.uri, expect.anything());
503 });
504​
505 it("reports a native video retrieval error and ends the foreground handoff", async () => {
506 mocks.pickMedia.mockRejectedValue(new Error("Could not download video from iCloud."));
507​
508 await expect(pickComposerMedia({ existingCount: 0, maxVideoBytes: 1024 })).resolves.toEqual({
509 attachments: [],
510 error: "Could not download video from iCloud.",
511 });
512 expect(isForegroundHandoffActive()).toBe(false);
513 });
514 });
515​
516 describe("images chosen through the file picker", () => {
517 it.each([
518 { name: "photo.bin", mimeType: "image/jpeg", expected: "image/jpeg" },
519 { name: "photo.png", mimeType: "image/png", expected: "image/png" },
520 { name: "photo.gif", mimeType: "image/gif", expected: "image/gif" },
521 { name: "photo.webp", mimeType: "image/webp", expected: "image/webp" },
522 { name: "photo.JPG", mimeType: undefined, expected: "image/jpeg" },
523 { name: "photo.PNG", mimeType: "application/octet-stream", expected: "image/png" },
524 { name: "photo.gif", mimeType: "binary/octet-stream", expected: "image/gif" },
525 { name: "photo.webp", mimeType: "application/unknown", expected: "image/webp" },
526 { name: "photo.jpg", mimeType: "IMAGE/PNG; charset=binary", expected: "image/png" },
527 ])("prepares $name ($mimeType) as $expected", async ({ name, mimeType, expected }) => {
528 mocks.pickFile.mockResolvedValue({
529 canceled: false,
530 assets: [{ uri: `file:///picker/${name}`, name, mimeType, size: 3 }],
531 });
532 sizeOtherFilesAs(3);
533 mocks.readBase64.mockResolvedValue("YWJj");
534​
535 const result = await pickComposerFiles({ existingCount: 0 });
536​
537 expect(result).toEqual({
538 files: [
539 {
540 id: "attachment-id",
541 type: "image",
542 name,
543 mimeType: expected,
544 sizeBytes: 3,
545 fileUri: `${STORED}-${name}`,
546 previewUri: `${STORED}-${name}`,
547 },
548 ],
549 error: null,
550 });
551 expect(mocks.manipulate).not.toHaveBeenCalled();
552 expect(mocks.delete).not.toHaveBeenCalled();
553 });
554​
555 it.each([
556 { name: "diagram.svg", mimeType: "image/svg+xml" },
557 { name: "photo.heic", mimeType: "image/heic" },
558 { name: "photo.tiff", mimeType: "image/tiff" },
559 { name: "photo.png", mimeType: "application/pdf" },
560 { name: "unknown.bin", mimeType: "application/octet-stream" },
561 ])("keeps $name ($mimeType) as a file", async ({ name, mimeType }) => {
562 mocks.pickFile.mockResolvedValue({
563 canceled: false,
564 assets: [{ uri: `file:///picker/${name}`, name, mimeType, size: 42 }],
565 });
566​
567 const result = await pickComposerFiles({ existingCount: 0 });
568​
569 expect(result.error).toBeNull();
570 expect(result.files).toEqual([expect.objectContaining({ type: "file", name, mimeType })]);
571 expect(mocks.readBase64).not.toHaveBeenCalled();
572 expect(mocks.manipulate).not.toHaveBeenCalled();
573 expect(mocks.delete).not.toHaveBeenCalled();
574 });
575​
576 it.each([PROVIDER_SEND_TURN_MAX_IMAGE_BYTES, PROVIDER_SEND_TURN_MAX_IMAGE_BYTES + 1])(
577 "classifies a measured %s byte PNG independently of picker metadata and file limit",
578 async (size) => {
579 mocks.pickFile.mockResolvedValue({
580 canceled: false,
581 assets: [
582 { uri: "file:///picker/photo.png", name: "photo.png", mimeType: "image/png", size: 1 },
583 ],
584 });
585 mocks.size.mockReturnValue(size);
586 mocks.readBase64.mockResolvedValue("YWJj");
587​
588 const result = await pickComposerFiles({
589 existingCount: 0,
590 maxBytes: size > PROVIDER_SEND_TURN_MAX_IMAGE_BYTES ? size : 1024,
591 });
592​
593 expect(result.error).toBeNull();
594 expect(result.files[0]?.type).toBe(
595 size > PROVIDER_SEND_TURN_MAX_IMAGE_BYTES ? "file" : "image",
596 );
597 expect(isComposerImageAttachment(result.files[0]!)).toBe(
598 size <= PROVIDER_SEND_TURN_MAX_IMAGE_BYTES,
599 );
600 expect(mocks.readBase64).toHaveBeenCalledTimes(
601 size > PROVIDER_SEND_TURN_MAX_IMAGE_BYTES ? 0 : 1,
602 );
603 },
604 );
605​
606 it.each([false, true])("fits a large PNG with oversized output: %s", async (oversized) => {
607 const header = Buffer.alloc(24);
608 Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]).copy(header);
609 header.write("IHDR", 12);
610 header.writeUInt32BE(4000, 16);
611 header.writeUInt32BE(3000, 20);
612 const original = header.toString("base64");
613 mocks.readBase64.mockResolvedValue(original);
614 imageFiles.set("file:///picker/photo.png", original);
615 const resize = vi.fn();
616 const renderAsync = vi.fn(async () => ({
617 width: 4000,
618 height: 3000,
619 release: vi.fn(),
620 saveAsync: vi.fn(async () => {
621 const base64 = oversized
622 ? Buffer.alloc(PROVIDER_SEND_TURN_MAX_IMAGE_BYTES + 1).toString("base64")
623 : "YWJj";
624 imageFiles.set("file:///cache/fitted.png", base64);
625 return { uri: "file:///cache/fitted.png", base64 };
626 }),
627 }));
628 mocks.manipulate.mockImplementation(() => {
629 const context = {
630 resize: (size: unknown) => {
631 resize(size);
632 return context;
633 },
634 renderAsync,
635 };
636 return context;
637 });
638 mocks.pickFile.mockResolvedValue({
639 canceled: false,
640 assets: [{ uri: "file:///picker/photo.png", name: "photo.png", mimeType: "image/png" }],
641 });
642​
643 const result = await pickComposerFiles({ existingCount: 0 });
644​
645 expect(resize).toHaveBeenCalledWith({ width: 2000, height: 1500 });
646 expect(result).toEqual({
647 files: [
648 expect.objectContaining({
649 type: "image",
650 mimeType: "image/png",
651 sizeBytes: oversized ? header.length : 3,
652 fileUri: `${STORED}-photo.png`,
653 }),
654 ],
655 error: null,
656 });
657 expect(imageFiles.get(`${STORED}-photo.png`)).toBe(oversized ? original : "YWJj");
658 });
659​
660 it("releases the owned copy when reading an image fails", async () => {
661 mocks.pickFile.mockResolvedValue({
662 canceled: false,
663 assets: [{ uri: "file:///picker/photo.png", name: "photo.png", mimeType: "image/png" }],
664 });
665 mocks.readBase64.mockRejectedValue(new Error("unreadable image"));
666​
667 expect(await pickComposerFiles({ existingCount: 0 })).toEqual({
668 files: [],
669 error: "unreadable image",
670 });
671 expect(mocks.delete).toHaveBeenCalledWith(
672 "file:///documents/t3-composer-attachments/attachment-id-photo.png",
673 );
674 });
675 });
676​
677 it("copies picked files into app-owned storage without loading their contents", async () => {
678 mocks.pickFile.mockResolvedValue({
679 canceled: false,
680 assets: [
681 {
682 uri: "file:///downloads/report.pdf",
683 name: "report.pdf",
684 mimeType: "application/pdf",
685 size: 42,
686 },
687 ],
688 });
689​
690 await expect(pickComposerFiles({ existingCount: 0 })).resolves.toEqual({
691 files: [
692 {
693 id: "attachment-id",
694 type: "file",
695 name: "report.pdf",
696 mimeType: "application/pdf",
697 sizeBytes: 42,
698 fileUri: "file:///documents/t3-composer-attachments/attachment-id-report.pdf",
699 },
700 ],
701 error: null,
702 });
703 expect(mocks.copy).toHaveBeenCalledWith(
704 "file:///downloads/report.pdf",
705 "file:///documents/t3-composer-attachments/attachment-id-report.pdf",
706 );
707 });
708​
709 it("keeps the app-owned copy of a long valid filename within the filesystem limit", async () => {
710 const name = `${"a".repeat(246)}.txt`;
711 mocks.pickFile.mockResolvedValue({
712 canceled: false,
713 assets: [{ uri: "file:///downloads/long.txt", name, mimeType: "text/plain", size: 42 }],
714 });
715​
716 const result = await pickComposerFiles({ existingCount: 0 });
717​
718 expect(result.error).toBeNull();
719 expect(result.files.map((file) => file.name)).toEqual([name]);
720 // The stored basename fills the 255-byte limit and keeps the extension.
721 expect(result.files[0]).toMatchObject({
722 fileUri: `${STORED}-${"a".repeat(237)}.txt`,
723 });
724 });
725​
726 it("preserves Android picker metadata instead of using the content URI document id", async () => {
727 const uri = "content://com.android.providers.media.documents/document/video%3A18";
728 mocks.pickFile.mockResolvedValue({
729 canceled: false,
730 assets: [
731 {
732 uri,
733 name: "preview-h264.mp4",
734 mimeType: "video/mp4",
735 size: 620_992,
736 lastModified: 0,
737 },
738 ],
739 });
740 mocks.size.mockReturnValue(620_992);
741​
742 await expect(pickComposerFiles({ existingCount: 0 })).resolves.toEqual({
743 files: [
744 {
745 id: "attachment-id",
746 type: "file",
747 name: "preview-h264.mp4",
748 mimeType: "video/mp4",
749 sizeBytes: 620_992,
750 fileUri: "file:///documents/t3-composer-attachments/attachment-id-preview-h264.mp4",
751 },
752 ],
753 error: null,
754 });
755 expect(mocks.pickFile).toHaveBeenCalledWith({ multiple: true, copyToCacheDirectory: true });
756 expect(mocks.copy).toHaveBeenCalledWith(
757 uri,
758 "file:///documents/t3-composer-attachments/attachment-id-preview-h264.mp4",
759 );
760 expect(mocks.delete).not.toHaveBeenCalled();
761 });
762​
763 it("persists provider selections that require a readable cache copy", async () => {
764 const providerUri = "content://cloud-provider/documents/clip";
765 const cachedUri = "file:///cache/DocumentPicker/clip.mp4";
766 mocks.pickFile.mockImplementation(async (options) => ({
767 canceled: false,
768 assets: [
769 {
770 uri: options.copyToCacheDirectory ? cachedUri : providerUri,
771 name: "Cloud recording.mp4",
772 mimeType: "video/mp4",
773 size: 42,
774 lastModified: 0,
775 },
776 ],
777 }));
778 mocks.copy.mockImplementation((uri: string) => {
779 if (uri === providerUri) throw new Error("The provider URI is not directly readable.");
780 });
781​
782 const result = await pickComposerFiles({ existingCount: 0 });
783​
784 expect(result.error).toBeNull();
785 expect(result.files).toEqual([
786 expect.objectContaining({
787 name: "Cloud recording.mp4",
788 fileUri: "file:///documents/t3-composer-attachments/attachment-id-Cloud recording.mp4",
789 }),
790 ]);
791 expect(mocks.copy).toHaveBeenCalledWith(cachedUri, result.files[0]!.fileUri);
792 });
793​
794 it("ends the foreground handoff when the picker is canceled without copying files", async () => {
795 mocks.pickFile.mockImplementation(async () => {
796 expect(isForegroundHandoffActive()).toBe(true);
797 return { canceled: true, assets: null };
798 });
799​
800 await expect(pickComposerFiles({ existingCount: 0 })).resolves.toEqual({
801 files: [],
802 error: null,
803 });
804​
805 expect(isForegroundHandoffActive()).toBe(false);
806 expect(mocks.copy).not.toHaveBeenCalled();
807 expect(mocks.open).not.toHaveBeenCalled();
808 });
809​
810 it("does not open the picker when the draft has no remaining attachment slots", async () => {
811 await expect(pickComposerFiles({ existingCount: 100 })).resolves.toEqual({
812 files: [],
813 error: "You can attach up to 100 files per message.",
814 });
815​
816 expect(mocks.pickFile).not.toHaveBeenCalled();
817 expect(isForegroundHandoffActive()).toBe(false);
818 });
819​
820 it("rejects files that exceed the environment's advertised upload limit", async () => {
821 mocks.pickFile.mockResolvedValue({
822 canceled: false,
823 assets: [
824 {
825 uri: "file:///downloads/archive.zip",
826 name: "archive.zip",
827 mimeType: "application/zip",
828 size: 2 * 1024 * 1024,
829 },
830 ],
831 });
832​
833 await expect(pickComposerFiles({ existingCount: 0, maxBytes: 1024 * 1024 })).resolves.toEqual({
834 files: [],
835 error: "'archive.zip' exceeds the 1 MB attachment limit.",
836 });
837 expect(mocks.copy).not.toHaveBeenCalled();
838 });
839​
840 it("rejects a file that grew after the picker reported its size", async () => {
841 mocks.pickFile.mockResolvedValue({
842 canceled: false,
843 assets: [
844 {
845 uri: "file:///downloads/archive.zip",
846 name: "archive.zip",
847 mimeType: "application/zip",
848 size: 42,
849 },
850 ],
851 });
852 mocks.size.mockReturnValue(2 * 1024 * 1024);
853​
854 await expect(pickComposerFiles({ existingCount: 0, maxBytes: 1024 * 1024 })).resolves.toEqual({
855 files: [],
856 error: "'archive.zip' exceeds the 1 MB attachment limit.",
857 });
858 expect(mocks.copy).not.toHaveBeenCalled();
859 });
860​
861 it("stops copying an unknown-size content URI when it exceeds the attachment limit", async () => {
862 const maxBytes = 1024 * 1024;
863 let remainingBytes = maxBytes + 1;
864 const source = {
865 readBytes: vi.fn((length: number) => {
866 const size = Math.min(length, remainingBytes);
867 remainingBytes -= size;
868 return new Uint8Array(size);
869 }),
870 close: vi.fn(),
871 };
872 const destination = { writeBytes: vi.fn(), close: vi.fn() };
873 mocks.open.mockImplementation((uri: string) =>
874 uri.startsWith("content:") ? source : destination,
875 );
876​
877 await expect(
878 persistComposerAttachmentFile("content://shared/large", "large.bin", maxBytes),
879 ).rejects.toThrow("'large.bin' exceeds the 1 MB attachment limit.");
880​
881 expect(source.close).toHaveBeenCalledOnce();
882 expect(destination.close).toHaveBeenCalledOnce();
883 expect(mocks.delete).toHaveBeenCalledWith(
884 "file:///documents/t3-composer-attachments/attachment-id-large.bin",
885 );
886 expect(mocks.copy).not.toHaveBeenCalled();
887 });
888​
889 it("rejects a copy that delivered more bytes than the source reported", async () => {
890 const maxBytes = 1024 * 1024;
891 mocks.size.mockImplementation((uri: string) =>
892 uri.startsWith("content:") ? 42 : 2 * 1024 * 1024,
893 );
894​
895 await expect(
896 persistComposerAttachmentFile("content://shared/liar", "liar.bin", maxBytes),
897 ).rejects.toThrow("'liar.bin' exceeds the 1 MB attachment limit.");
898​
899 expect(mocks.copy).toHaveBeenCalledOnce();
900 expect(mocks.delete).toHaveBeenCalledWith(
901 "file:///documents/t3-composer-attachments/attachment-id-liar.bin",
902 );
903 });
904​
905 it.each([0, undefined])("copies an Android SAF file when the picker size is %s", async (size) => {
906 const reader = {
907 readBytes: vi
908 .fn()
909 .mockReturnValueOnce(new Uint8Array(42))
910 .mockReturnValueOnce(new Uint8Array()),
911 close: vi.fn(),
912 };
913 const writer = { writeBytes: vi.fn(), close: vi.fn() };
914 mocks.size.mockImplementation((uri: string) => (uri.startsWith("content:") ? 0 : 42));
915 mocks.open.mockImplementation((uri: string) => (uri.startsWith("content:") ? reader : writer));
916 mocks.pickFile.mockResolvedValue({
917 canceled: false,
918 assets: [
919 {
920 uri: "content://shared/report",
921 name: "report.pdf",
922 mimeType: "application/pdf",
923 size,
924 },
925 ],
926 });
927​
928 await expect(pickComposerFiles({ existingCount: 0 })).resolves.toEqual({
929 files: [
930 {
931 id: "attachment-id",
932 type: "file",
933 name: "report.pdf",
934 mimeType: "application/pdf",
935 sizeBytes: 42,
936 fileUri: "file:///documents/t3-composer-attachments/attachment-id-report.pdf",
937 },
938 ],
939 error: null,
940 });
941 });
942​
943 it("uses the remaining slot for the first valid file after an oversized selection", async () => {
944 mocks.pickFile.mockResolvedValue({
945 canceled: false,
946 assets: [
947 {
948 uri: "file:///downloads/huge.zip",
949 name: "huge.zip",
950 mimeType: "application/zip",
951 size: 2 * 1024 * 1024,
952 },
953 {
954 uri: "file:///downloads/report.pdf",
955 name: "report.pdf",
956 mimeType: "application/pdf",
957 size: 42,
958 },
959 ],
960 });
961​
962 const result = await pickComposerFiles({ existingCount: 99, maxBytes: 1024 * 1024 });
963​
964 expect(result.files.map((file) => file.name)).toEqual(["report.pdf"]);
965 });
966​
967 it("removes the partial destination file when a copy fails midway", async () => {
968 mocks.copy.mockImplementation(() => {
969 throw new Error("disk full");
970 });
971​
972 await expect(
973 persistComposerAttachmentFile("file:///downloads/report.pdf", "report.pdf"),
974 ).rejects.toThrow("disk full");
975​
976 expect(mocks.delete).toHaveBeenCalledWith(
977 "file:///documents/t3-composer-attachments/attachment-id-report.pdf",
978 );
979 });
980​
981 it("deletes app-owned attachments without touching user-owned files", async () => {
982 await removePersistedComposerAttachmentFile(
983 "file:///documents/t3-composer-attachments/report.pdf",
984 );
985 await removePersistedComposerAttachmentFile("file:///downloads/report.pdf");
986​
987 expect(mocks.delete).toHaveBeenCalledOnce();
988 expect(mocks.delete).toHaveBeenCalledWith(
989 "file:///documents/t3-composer-attachments/report.pdf",
990 );
991 });
992​
993 it("removes a restored attachment from the current iOS document container", async () => {
994 const fileName = "33333333-3333-4333-8333-333333333333-report%20%23.pdf";
995 const oldUri = `file:///private/var/mobile/Containers/Data/Application/11111111-1111-4111-8111-111111111111/Documents/t3-composer-attachments/${fileName}`;
996 mocks.documentUri =
997 "file:///var/mobile/Containers/Data/Application/22222222-2222-4222-8222-222222222222/Documents";
998​
999 await removePersistedComposerAttachmentFile(oldUri);
1000 await removePersistedComposerAttachmentFile(
1001 `file:///var/mobile/Containers/Shared/FileProvider/other/Documents/t3-composer-attachments/${fileName}`,
1002 );
1003 await removePersistedComposerAttachmentFile(
1004 `${mocks.documentUri}/t3-composer-attachments/..%2F..%2Fsender.pdf`,
1005 );
1006​
1007 expect(mocks.delete.mock.calls).toEqual([
1008 [`${mocks.documentUri}/t3-composer-attachments/${fileName}`],
1009 ]);
1010 });
1011​
1012 it("rechecks preview ownership after loading the native filesystem", async () => {
1013 const fileName = "33333333-3333-4333-8333-333333333333-recording.mp4";
1014 const oldUri = `file:///private/var/mobile/Containers/Data/Application/11111111-1111-4111-8111-111111111111/Documents/t3-composer-attachments/${fileName}`;
1015 mocks.documentUri =
1016 "file:///var/mobile/Containers/Data/Application/22222222-2222-4222-8222-222222222222/Documents";
1017 const currentUri = `${mocks.documentUri}/t3-composer-attachments/${fileName}`;
1018​
1019 const deleting = removePersistedComposerAttachmentFile(oldUri);
1020 const release = retainComposerAttachmentFile(currentUri, () => {});
1021 try {
1022 await deleting;
1023 expect(mocks.delete).not.toHaveBeenCalled();
1024 } finally {
1025 release();
1027​
1028 await removePersistedComposerAttachmentFile(oldUri);
1029 expect(mocks.delete.mock.calls).toEqual([[currentUri]]);
1030 });
1031​
1032 it("copies an open-in-place source from its actual container without rebasing it", async () => {
1033 const sourceUri =
1034 "file:///var/mobile/Containers/Data/Application/11111111-1111-4111-8111-111111111111/Documents/t3-composer-attachments/33333333-3333-4333-8333-333333333333-report.pdf";
1035 mocks.documentUri =
1036 "file:///var/mobile/Containers/Data/Application/22222222-2222-4222-8222-222222222222/Documents";
1037​
1038 await persistComposerAttachmentFile(sourceUri, "report.pdf");
1039​
1040 expect(mocks.copy).toHaveBeenCalledWith(
1041 sourceUri,
1042 `${mocks.documentUri}/t3-composer-attachments/attachment-id-report.pdf`,
1043 );
1044 expect(mocks.delete).not.toHaveBeenCalled();
1045 });
1046});