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

composerFiles.test.ts

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