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

composerFiles.test.ts

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