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