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 pickComposerFiles,
94 pickComposerImages,
95 pickComposerMedia,
96 removePersistedComposerAttachmentFile,
97} from "./composerImages";
98import { isForegroundHandoffActive } from "./foreground-handoff";
99import { retainComposerAttachmentFile } from "./composerAttachmentFiles";
100
101describe("composer file attachments", () => {
102 beforeEach(() => {
103 mocks.documentUri = "file:///documents";
104 mocks.pickFile.mockReset();
105 mocks.pickMedia.mockReset();
106 mocks.copy.mockReset();
107 mocks.delete.mockReset();
108 mocks.open.mockReset();
109 mocks.size.mockReset();
110 mocks.readBase64.mockReset();
111 mocks.size.mockImplementation((uri: string) => (uri.startsWith("content:") ? null : 42));
112 });
113
114 describe("photo library image conversion", () => {
115 const rendered = { uri: "file:///cache/ImageManipulator/photo.jpg", base64: "/9j/2Q==" };
116 const photo: ImagePickerAsset = {
117 uri: "file:///picker/photo.heic",
118 type: "image",
119 fileName: "photo.HEIC",
120 mimeType: "image/heic",
121 fileSize: 4 * 1024 * 1024,
122 width: 4032,
123 height: 3024,
124 };
125 const native = {
126 size: { width: 1, height: 1 },
127 resizes: [] as Array<{ width?: number | null; height?: number | null }>,
128 saved: rendered as { uri: string; base64?: string },
129 };
130
131 beforeEach(() => {
132 native.size = { width: 1, height: 1 };
133 native.resizes = [];
134 native.saved = rendered;
135 mocks.manipulate.mockReset();
136 mocks.release.mockReset();
137 mocks.manipulate.mockImplementation(() => {
138 const context = {
139 resize(size: { width?: number | null; height?: number | null }) {
140 native.resizes.push(size);
141 return context;
142 },
143 renderAsync: async () => ({
144 ...native.size,
145 release: mocks.release,
146 saveAsync: async () => native.saved,
147 }),
148 };
149 return context;
150 });
151 });
152
153 it.each(["image/heic", "image/heif", undefined])(
154 "renders a %s photo to JPEG natively and previews the rendered file",
155 async (mimeType) => {
156 mocks.pickMedia.mockResolvedValue({
157 canceled: false,
158 assets: [{ ...photo, mimeType }],
159 });
160
161 const result = await pickComposerImages({ existingCount: 0 });
162
163 expect(mocks.pickMedia).toHaveBeenCalledWith(expect.objectContaining({ base64: false }));
164 expect(mocks.manipulate).toHaveBeenCalledWith(photo.uri);
165 expect(mocks.readBase64).not.toHaveBeenCalled();
166 expect(result).toEqual({
167 images: [
168 {
169 id: "attachment-id",
170 type: "image",
171 name: "photo.jpg",
172 mimeType: "image/jpeg",
173 sizeBytes: 4,
174 dataUrl: `data:image/jpeg;base64,${rendered.base64}`,
175 previewUri: rendered.uri,
176 },
177 ],
178 error: null,
179 });
180 },
181 );
182
183 it.each([
184 { extension: "png", mimeType: "image/png", base64: "iVBORw0KGgo=" },
185 { extension: "gif", mimeType: "image/gif", base64: "R0lGODlh" },
186 { extension: "webp", mimeType: "image/webp", base64: "UklGRgQAAABXRUJQ" },
187 ])("keeps original $extension bytes from the picker file", async (original) => {
188 const name = `photo.${original.extension}`;
189 mocks.pickMedia.mockResolvedValue({
190 canceled: false,
191 assets: [{ ...photo, fileName: name, mimeType: original.mimeType }],
192 });
193 mocks.readBase64.mockResolvedValue(original.base64);
194
195 const result = await pickComposerImages({ existingCount: 0 });
196
197 expect(mocks.manipulate).not.toHaveBeenCalled();
198 expect(mocks.readBase64).toHaveBeenCalledWith(photo.uri);
199 expect(result.error).toBeNull();
200 expect(result.images).toEqual([
201 expect.objectContaining({
202 name,
203 mimeType: original.mimeType,
204 dataUrl: `data:${original.mimeType};base64,${original.base64}`,
205 sizeBytes: Buffer.from(original.base64, "base64").byteLength,
206 previewUri: photo.uri,
207 }),
208 ]);
209 });
210
211 it("measures the picker file instead of trusting the reported size", async () => {
212 mocks.pickMedia.mockResolvedValue({
213 canceled: false,
214 assets: [{ ...photo, fileName: "photo.png", mimeType: "image/png", fileSize: 42 }],
215 });
216 mocks.size.mockReturnValue(PROVIDER_SEND_TURN_MAX_IMAGE_BYTES + 1);
217
218 const result = await pickComposerImages({ existingCount: 0 });
219
220 expect(mocks.readBase64).not.toHaveBeenCalled();
221 expect(mocks.manipulate).toHaveBeenCalledWith(photo.uri);
222 expect(result.images).toEqual([expect.objectContaining({ mimeType: "image/jpeg" })]);
223 });
224
225 // regression: #11440 render photo library picks to a bounded JPEG off the JS thread
226 it("renders a supported original whose size cannot be measured", async () => {
227 mocks.pickMedia.mockResolvedValue({
228 canceled: false,
229 assets: [
230 { ...photo, uri: "content://media/1", fileName: "photo.png", mimeType: "image/png" },
231 ],
232 });
233
234 const result = await pickComposerImages({ existingCount: 0 });
235
236 expect(mocks.readBase64).not.toHaveBeenCalled();
237 expect(mocks.manipulate).toHaveBeenCalledWith("content://media/1");
238 expect(result.images).toEqual([expect.objectContaining({ mimeType: "image/jpeg" })]);
239 });
240
241 it("checks the rendered JPEG against the image limit", async () => {
242 native.saved = {
243 uri: rendered.uri,
244 base64:
245 rendered.base64.slice(0, 4) +
246 "A".repeat(Math.ceil(PROVIDER_SEND_TURN_MAX_IMAGE_BYTES / 3) * 4),
247 };
248 mocks.pickMedia.mockResolvedValue({ canceled: false, assets: [photo] });
249
250 await expect(pickComposerImages({ existingCount: 0 })).resolves.toEqual({
251 images: [],
252 error: "'photo.HEIC' exceeds the 10 MB attachment limit.",
253 });
254 });
255
256 it("retains a rendered photo when another original cannot be read", async () => {
257 mocks.pickMedia.mockResolvedValue({
258 canceled: false,
259 assets: [{ ...photo, fileName: "missing.gif", mimeType: "image/gif" }, photo],
260 });
261 mocks.readBase64.mockRejectedValue(new Error("missing file"));
262
263 const result = await pickComposerImages({ existingCount: 0 });
264
265 expect(result.images).toEqual([expect.objectContaining({ name: "photo.jpg" })]);
266 expect(result.error).toBe("Failed to read 'missing.gif'.");
267 });
268
269 // regression: #11440 render photo library picks to a bounded JPEG off the JS thread
270 it("reports a photo the native renderer cannot decode", async () => {
271 mocks.manipulate.mockImplementation(() => ({
272 resize: () => {
273 throw new Error("unreachable");
274 },
275 renderAsync: () => Promise.reject(new Error("corrupt")),
276 }));
277 mocks.pickMedia.mockResolvedValue({ canceled: false, assets: [photo] });
278
279 await expect(pickComposerImages({ existingCount: 0 })).resolves.toEqual({
280 images: [],
281 error: "Failed to read 'photo.HEIC'.",
282 });
283 });
284 });
285
286 describe("photo library videos", () => {
287 const image: ImagePickerAsset = {
288 uri: "file:///picker/photo.png",
289 type: "image",
290 fileName: "photo.png",
291 mimeType: "image/png",
292 fileSize: 3,
293 width: 1,
294 height: 1,
295 };
296
297 beforeEach(() => {
298 mocks.readBase64.mockResolvedValue("YWJj");
299 });
300 const video: ImagePickerAsset = {
301 uri: "file:///picker/clip.mov",
302 type: "video",
303 fileName: "clip.mov",
304 mimeType: "video/quicktime",
305 fileSize: 20 * 1024 * 1024,
306 base64: null,
307 width: 1920,
308 height: 1080,
309 };
310
311 it("retains mixed photos and videos, keeping video bytes in durable file storage", async () => {
312 mocks.pickMedia.mockResolvedValue({ canceled: false, assets: [image, video] });
313 mocks.size.mockImplementation((uri: string) =>
314 uri.endsWith("clip.mov") ? video.fileSize : 3,
315 );
316
317 const result = await pickComposerMedia({ existingCount: 0, maxVideoBytes: 50 * 1024 * 1024 });
318
319 expect(mocks.pickMedia).toHaveBeenCalledWith(
320 expect.objectContaining({
321 mediaTypes: ["images", "videos"],
322 shouldDownloadFromNetwork: true,
323 }),
324 );
325 expect(result).toEqual({
326 attachments: [
327 expect.objectContaining({ type: "image", dataUrl: "data:image/png;base64,YWJj" }),
328 {
329 id: "attachment-id",
330 type: "file",
331 name: "clip.mov",
332 mimeType: "video/quicktime",
333 sizeBytes: video.fileSize,
334 fileUri: "file:///documents/t3-composer-attachments/attachment-id-clip.mov",
335 },
336 ],
337 error: null,
338 });
339 expect(mocks.copy).toHaveBeenCalledWith(
340 video.uri,
341 "file:///documents/t3-composer-attachments/attachment-id-clip.mov",
342 );
343 expect(mocks.delete).not.toHaveBeenCalled();
344 });
345
346 it("does not persist videos when the destination lacks file support", async () => {
347 mocks.pickMedia.mockResolvedValue({ canceled: false, assets: [video, image] });
348
349 const result = await pickComposerMedia({ existingCount: 0 });
350
351 expect(result.attachments).toEqual([expect.objectContaining({ type: "image" })]);
352 expect(result.error).toBe("Video attachments are unavailable here.");
353 expect(mocks.copy).not.toHaveBeenCalled();
354 });
355
356 it("uses local video metadata when the picker omits its name, MIME type, or size", async () => {
357 mocks.pickMedia.mockResolvedValue({
358 canceled: false,
359 assets: [{ ...video, fileName: null, mimeType: undefined, fileSize: undefined }],
360 });
361
362 const result = await pickComposerMedia({ existingCount: 0, maxVideoBytes: 1024 });
363
364 expect(result.error).toBeNull();
365 expect(result.attachments).toEqual([
366 expect.objectContaining({
367 type: "file",
368 name: "clip.mov",
369 mimeType: "video/quicktime",
370 sizeBytes: 42,
371 }),
372 ]);
373 });
374
375 it.each([
376 {
377 reason: "actual size exceeds the server limit",
378 reported: 42,
379 stored: 2 * 1024 * 1024,
380 limit: 1024 * 1024,
381 error: "'clip.mov' exceeds the 1 MB attachment limit.",
382 },
383 {
384 reason: "stored copy is empty",
385 reported: 42,
386 stored: 0,
387 limit: 1024 * 1024,
388 error: "'clip.mov' is empty or could not be read.",
389 },
390 {
391 reason: "server advertises more than the contract limit",
392 reported: 51 * 1024 * 1024,
393 stored: 42,
394 limit: 80 * 1024 * 1024,
395 error: "'clip.mov' exceeds the 50 MB attachment limit.",
396 },
397 ])(
398 "rejects a video when $reason while retaining the selected photo",
399 async ({ reported, stored, limit, error }) => {
400 mocks.pickMedia.mockResolvedValue({
401 canceled: false,
402 assets: [{ ...video, fileSize: reported }, image],
403 });
404 mocks.size.mockImplementation((uri: string) => (uri.endsWith("clip.mov") ? stored : 3));
405
406 const result = await pickComposerMedia({ existingCount: 0, maxVideoBytes: limit });
407
408 expect(result).toEqual({
409 attachments: [expect.objectContaining({ type: "image" })],
410 error,
411 });
412 if (stored === 0) {
413 expect(mocks.delete).toHaveBeenCalledWith(
414 "file:///documents/t3-composer-attachments/attachment-id-clip.mov",
415 );
416 }
417 },
418 );
419
420 it("applies the remaining attachment slots to photos and videos together", async () => {
421 mocks.pickMedia.mockResolvedValue({ canceled: false, assets: [image, video] });
422
423 const result = await pickComposerMedia({
424 existingCount: 99,
425 maxVideoBytes: 50 * 1024 * 1024,
426 });
427
428 expect(result.attachments).toEqual([expect.objectContaining({ type: "image" })]);
429 expect(result.error).toBe("You can attach up to 100 attachments per message.");
430 expect(mocks.pickMedia).toHaveBeenCalledWith(expect.objectContaining({ selectionLimit: 1 }));
431 expect(mocks.copy).not.toHaveBeenCalled();
432 });
433
434 it("reports a native video retrieval error and ends the foreground handoff", async () => {
435 mocks.pickMedia.mockRejectedValue(new Error("Could not download video from iCloud."));
436
437 await expect(pickComposerMedia({ existingCount: 0, maxVideoBytes: 1024 })).resolves.toEqual({
438 attachments: [],
439 error: "Could not download video from iCloud.",
440 });
441 expect(isForegroundHandoffActive()).toBe(false);
442 });
443 });
444
445 it("copies picked files into app-owned storage without loading their contents", async () => {
446 mocks.pickFile.mockResolvedValue({
447 canceled: false,
448 assets: [
449 {
450 uri: "file:///downloads/report.pdf",
451 name: "report.pdf",
452 mimeType: "application/pdf",
453 size: 42,
454 },
455 ],
456 });
457
458 await expect(pickComposerFiles({ existingCount: 0 })).resolves.toEqual({
459 files: [
460 {
461 id: "attachment-id",
462 type: "file",
463 name: "report.pdf",
464 mimeType: "application/pdf",
465 sizeBytes: 42,
466 fileUri: "file:///documents/t3-composer-attachments/attachment-id-report.pdf",
467 },
468 ],
469 error: null,
470 });
471 expect(mocks.copy).toHaveBeenCalledWith(
472 "file:///downloads/report.pdf",
473 "file:///documents/t3-composer-attachments/attachment-id-report.pdf",
474 );
475 });
476
477 it("preserves Android picker metadata instead of using the content URI document id", async () => {
478 const uri = "content://com.android.providers.media.documents/document/video%3A18";
479 mocks.pickFile.mockResolvedValue({
480 canceled: false,
481 assets: [
482 {
483 uri,
484 name: "preview-h264.mp4",
485 mimeType: "video/mp4",
486 size: 620_992,
487 lastModified: 0,
488 },
489 ],
490 });
491 mocks.size.mockReturnValue(620_992);
492
493 await expect(pickComposerFiles({ existingCount: 0 })).resolves.toEqual({
494 files: [
495 {
496 id: "attachment-id",
497 type: "file",
498 name: "preview-h264.mp4",
499 mimeType: "video/mp4",
500 sizeBytes: 620_992,
501 fileUri: "file:///documents/t3-composer-attachments/attachment-id-preview-h264.mp4",
502 },
503 ],
504 error: null,
505 });
506 expect(mocks.pickFile).toHaveBeenCalledWith({ multiple: true, copyToCacheDirectory: true });
507 expect(mocks.copy).toHaveBeenCalledWith(
508 uri,
509 "file:///documents/t3-composer-attachments/attachment-id-preview-h264.mp4",
510 );
511 expect(mocks.delete).not.toHaveBeenCalled();
512 });
513
514 it("persists provider selections that require a readable cache copy", async () => {
515 const providerUri = "content://cloud-provider/documents/clip";
516 const cachedUri = "file:///cache/DocumentPicker/clip.mp4";
517 mocks.pickFile.mockImplementation(async (options) => ({
518 canceled: false,
519 assets: [
520 {
521 uri: options.copyToCacheDirectory ? cachedUri : providerUri,
522 name: "Cloud recording.mp4",
523 mimeType: "video/mp4",
524 size: 42,
525 lastModified: 0,
526 },
527 ],
528 }));
529 mocks.copy.mockImplementation((uri: string) => {
530 if (uri === providerUri) throw new Error("The provider URI is not directly readable.");
531 });
532
533 const result = await pickComposerFiles({ existingCount: 0 });
534
535 expect(result.error).toBeNull();
536 expect(result.files).toEqual([
537 expect.objectContaining({
538 name: "Cloud recording.mp4",
539 fileUri: "file:///documents/t3-composer-attachments/attachment-id-Cloud recording.mp4",
540 }),
541 ]);
542 expect(mocks.copy).toHaveBeenCalledWith(cachedUri, result.files[0]!.fileUri);
543 });
544
545 it("ends the foreground handoff when the picker is canceled without copying files", async () => {
546 mocks.pickFile.mockImplementation(async () => {
547 expect(isForegroundHandoffActive()).toBe(true);
548 return { canceled: true, assets: null };
549 });
550
551 await expect(pickComposerFiles({ existingCount: 0 })).resolves.toEqual({
552 files: [],
553 error: null,
554 });
555
556 expect(isForegroundHandoffActive()).toBe(false);
557 expect(mocks.copy).not.toHaveBeenCalled();
558 expect(mocks.open).not.toHaveBeenCalled();
559 });
560
561 it("does not open the picker when the draft has no remaining attachment slots", async () => {
562 await expect(pickComposerFiles({ existingCount: 100 })).resolves.toEqual({
563 files: [],
564 error: "You can attach up to 100 files per message.",
565 });
566
567 expect(mocks.pickFile).not.toHaveBeenCalled();
568 expect(isForegroundHandoffActive()).toBe(false);
569 });
570
571 it("rejects files that exceed the environment's advertised upload limit", async () => {
572 mocks.pickFile.mockResolvedValue({
573 canceled: false,
574 assets: [
575 {
576 uri: "file:///downloads/archive.zip",
577 name: "archive.zip",
578 mimeType: "application/zip",
579 size: 2 * 1024 * 1024,
580 },
581 ],
582 });
583
584 await expect(pickComposerFiles({ existingCount: 0, maxBytes: 1024 * 1024 })).resolves.toEqual({
585 files: [],
586 error: "'archive.zip' exceeds the 1 MB attachment limit.",
587 });
588 expect(mocks.copy).not.toHaveBeenCalled();
589 });
590
591 it("rejects a file that grew after the picker reported its size", async () => {
592 mocks.pickFile.mockResolvedValue({
593 canceled: false,
594 assets: [
595 {
596 uri: "file:///downloads/archive.zip",
597 name: "archive.zip",
598 mimeType: "application/zip",
599 size: 42,
600 },
601 ],
602 });
603 mocks.size.mockReturnValue(2 * 1024 * 1024);
604
605 await expect(pickComposerFiles({ existingCount: 0, maxBytes: 1024 * 1024 })).resolves.toEqual({
606 files: [],
607 error: "'archive.zip' exceeds the 1 MB attachment limit.",
608 });
609 expect(mocks.copy).not.toHaveBeenCalled();
610 });
611
612 it("stops copying an unknown-size content URI when it exceeds the attachment limit", async () => {
613 const maxBytes = 1024 * 1024;
614 let remainingBytes = maxBytes + 1;
615 const source = {
616 readBytes: vi.fn((length: number) => {
617 const size = Math.min(length, remainingBytes);
618 remainingBytes -= size;
619 return new Uint8Array(size);
620 }),
621 close: vi.fn(),
622 };
623 const destination = { writeBytes: vi.fn(), close: vi.fn() };
624 mocks.open.mockImplementation((uri: string) =>
625 uri.startsWith("content:") ? source : destination,
626 );
627
628 await expect(
629 persistComposerAttachmentFile("content://shared/large", "large.bin", maxBytes),
630 ).rejects.toThrow("'large.bin' exceeds the 1 MB attachment limit.");
631
632 expect(source.close).toHaveBeenCalledOnce();
633 expect(destination.close).toHaveBeenCalledOnce();
634 expect(mocks.delete).toHaveBeenCalledWith(
635 "file:///documents/t3-composer-attachments/attachment-id-large.bin",
636 );
637 expect(mocks.copy).not.toHaveBeenCalled();
638 });
639
640 it("rejects a copy that delivered more bytes than the source reported", async () => {
641 const maxBytes = 1024 * 1024;
642 mocks.size.mockImplementation((uri: string) =>
643 uri.startsWith("content:") ? 42 : 2 * 1024 * 1024,
644 );
645
646 await expect(
647 persistComposerAttachmentFile("content://shared/liar", "liar.bin", maxBytes),
648 ).rejects.toThrow("'liar.bin' exceeds the 1 MB attachment limit.");
649
650 expect(mocks.copy).toHaveBeenCalledOnce();
651 expect(mocks.delete).toHaveBeenCalledWith(
652 "file:///documents/t3-composer-attachments/attachment-id-liar.bin",
653 );
654 });
655
656 it.each([0, undefined])("copies an Android SAF file when the picker size is %s", async (size) => {
657 const reader = {
658 readBytes: vi
659 .fn()
660 .mockReturnValueOnce(new Uint8Array(42))
661 .mockReturnValueOnce(new Uint8Array()),
662 close: vi.fn(),
663 };
664 const writer = { writeBytes: vi.fn(), close: vi.fn() };
665 mocks.size.mockImplementation((uri: string) => (uri.startsWith("content:") ? 0 : 42));
666 mocks.open.mockImplementation((uri: string) => (uri.startsWith("content:") ? reader : writer));
667 mocks.pickFile.mockResolvedValue({
668 canceled: false,
669 assets: [
670 {
671 uri: "content://shared/report",
672 name: "report.pdf",
673 mimeType: "application/pdf",
674 size,
675 },
676 ],
677 });
678
679 await expect(pickComposerFiles({ existingCount: 0 })).resolves.toEqual({
680 files: [
681 {
682 id: "attachment-id",
683 type: "file",
684 name: "report.pdf",
685 mimeType: "application/pdf",
686 sizeBytes: 42,
687 fileUri: "file:///documents/t3-composer-attachments/attachment-id-report.pdf",
688 },
689 ],
690 error: null,
691 });
692 });
693
694 it("uses the remaining slot for the first valid file after an oversized selection", async () => {
695 mocks.pickFile.mockResolvedValue({
696 canceled: false,
697 assets: [
698 {
699 uri: "file:///downloads/huge.zip",
700 name: "huge.zip",
701 mimeType: "application/zip",
702 size: 2 * 1024 * 1024,
703 },
704 {
705 uri: "file:///downloads/report.pdf",
706 name: "report.pdf",
707 mimeType: "application/pdf",
708 size: 42,
709 },
710 ],
711 });
712
713 const result = await pickComposerFiles({ existingCount: 99, maxBytes: 1024 * 1024 });
714
715 expect(result.files.map((file) => file.name)).toEqual(["report.pdf"]);
716 });
717
718 it("removes the partial destination file when a copy fails midway", async () => {
719 mocks.copy.mockImplementation(() => {
720 throw new Error("disk full");
721 });
722
723 await expect(
724 persistComposerAttachmentFile("file:///downloads/report.pdf", "report.pdf"),
725 ).rejects.toThrow("disk full");
726
727 expect(mocks.delete).toHaveBeenCalledWith(
728 "file:///documents/t3-composer-attachments/attachment-id-report.pdf",
729 );
730 });
731
732 it("deletes app-owned attachments without touching user-owned files", async () => {
733 await removePersistedComposerAttachmentFile(
734 "file:///documents/t3-composer-attachments/report.pdf",
735 );
736 await removePersistedComposerAttachmentFile("file:///downloads/report.pdf");
737
738 expect(mocks.delete).toHaveBeenCalledOnce();
739 expect(mocks.delete).toHaveBeenCalledWith(
740 "file:///documents/t3-composer-attachments/report.pdf",
741 );
742 });
743
744 it("removes a restored attachment from the current iOS document container", async () => {
745 const fileName = "33333333-3333-4333-8333-333333333333-report%20%23.pdf";
746 const oldUri = `file:///private/var/mobile/Containers/Data/Application/11111111-1111-4111-8111-111111111111/Documents/t3-composer-attachments/${fileName}`;
747 mocks.documentUri =
748 "file:///var/mobile/Containers/Data/Application/22222222-2222-4222-8222-222222222222/Documents";
749
750 await removePersistedComposerAttachmentFile(oldUri);
751 await removePersistedComposerAttachmentFile(
752 `file:///var/mobile/Containers/Shared/FileProvider/other/Documents/t3-composer-attachments/${fileName}`,
753 );
754 await removePersistedComposerAttachmentFile(
755 `${mocks.documentUri}/t3-composer-attachments/..%2F..%2Fsender.pdf`,
756 );
757
758 expect(mocks.delete.mock.calls).toEqual([
759 [`${mocks.documentUri}/t3-composer-attachments/${fileName}`],
760 ]);
761 });
762
763 it("rechecks preview ownership after loading the native filesystem", async () => {
764 const fileName = "33333333-3333-4333-8333-333333333333-recording.mp4";
765 const oldUri = `file:///private/var/mobile/Containers/Data/Application/11111111-1111-4111-8111-111111111111/Documents/t3-composer-attachments/${fileName}`;
766 mocks.documentUri =
767 "file:///var/mobile/Containers/Data/Application/22222222-2222-4222-8222-222222222222/Documents";
768 const currentUri = `${mocks.documentUri}/t3-composer-attachments/${fileName}`;
769
770 const deleting = removePersistedComposerAttachmentFile(oldUri);
771 const release = retainComposerAttachmentFile(currentUri, () => {});
772 try {
773 await deleting;
774 expect(mocks.delete).not.toHaveBeenCalled();
775 } finally {
776 release();
777 }
778
779 await removePersistedComposerAttachmentFile(oldUri);
780 expect(mocks.delete.mock.calls).toEqual([[currentUri]]);
781 });
782
783 it("copies an open-in-place source from its actual container without rebasing it", async () => {
784 const sourceUri =
785 "file:///var/mobile/Containers/Data/Application/11111111-1111-4111-8111-111111111111/Documents/t3-composer-attachments/33333333-3333-4333-8333-333333333333-report.pdf";
786 mocks.documentUri =
787 "file:///var/mobile/Containers/Data/Application/22222222-2222-4222-8222-222222222222/Documents";
788
789 await persistComposerAttachmentFile(sourceUri, "report.pdf");
790
791 expect(mocks.copy).toHaveBeenCalledWith(
792 sourceUri,
793 `${mocks.documentUri}/t3-composer-attachments/attachment-id-report.pdf`,
794 );
795 expect(mocks.delete).not.toHaveBeenCalled();
796 });
797});