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