Open History to see the last commit
1import { beforeEach, describe, expect, it, vi } from "vite-plus/test";
2import {
3 PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
4 PROVIDER_SEND_TURN_MAX_IMAGE_BYTES,
5} from "@t3tools/contracts";
6import type { ComposerAttachmentUploadState } from "./composerAttachmentUploadQueue";
7
8const files = new Map<
9 string,
10 { base64: string; deleted: boolean; text?: string; mimeType?: string }
11>();
12
13const manipulator = vi.hoisted(() => {
14 const state = { sourceSize: { width: 0, height: 0 }, renderedBase64: "cmVuZGVyZWQ=" };
15 const manipulate = vi.fn((source: string | { width: number; height: number }) => {
16 let size = typeof source === "string" ? state.sourceSize : source;
17 const context = {
18 resize: vi.fn((next: { width: number; height: number }) => {
19 size = next;
20 return context;
21 }),
22 renderAsync: vi.fn(async () => ({
23 ...size,
24 release: vi.fn(),
25 saveAsync: vi.fn(async (options: { format: string }) => {
26 const uri = `file:///cache/rendered.${options.format}`;
27 files.set(uri, { base64: state.renderedBase64, deleted: false });
28 return { uri, base64: state.renderedBase64 };
29 }),
30 })),
31 };
32 return context;
33 });
34 return { state, manipulate };
35});
36
37vi.mock("expo-image-manipulator", () => ({
38 ImageManipulator: { manipulate: manipulator.manipulate },
39 SaveFormat: { JPEG: "jpeg", PNG: "png" },
40}));
41
42vi.mock("expo-file-system", () => ({
43 File: class {
44 readonly uri: string;
45 readonly name: string;
46 readonly parentDirectory: { readonly uri: string };
47
48 constructor(parent: string | { readonly uri: string }, name?: string) {
49 const parentUri = typeof parent === "string" ? parent : parent.uri;
50 this.uri = name ? `${parentUri}/${name}` : parentUri;
51 this.name = name ?? this.uri.split("/").at(-1) ?? "file";
52 this.parentDirectory = { uri: this.uri.slice(0, -(this.name.length + 1)) };
53 }
54
55 get exists(): boolean {
56 return files.has(this.uri) && files.get(this.uri)?.deleted === false;
57 }
58
59 get type(): string {
60 return files.get(this.uri)?.mimeType ?? "";
61 }
62
63 get size(): number | null {
64 const entry = files.get(this.uri);
65 return entry && !entry.deleted
66 ? Math.floor((entry.base64.replace(/=+$/, "").length * 3) / 4)
67 : null;
68 }
69
70 async copy(destination: { readonly uri: string }): Promise<void> {
71 const entry = files.get(this.uri);
72 if (!entry) throw new Error("missing file");
73 files.set(destination.uri, { ...entry });
74 }
75
76 async base64(): Promise<string> {
77 const entry = files.get(this.uri);
78 if (!entry || entry.deleted) {
79 throw new Error("missing file");
80 }
81 return entry.base64;
82 }
83
84 delete(): void {
85 const entry = files.get(this.uri);
86 if (entry) {
87 entry.deleted = true;
88 }
89 }
90
91 create(): void {
92 files.set(this.uri, { base64: "", deleted: false });
93 }
94
95 write(text: string): void {
96 files.set(this.uri, { base64: "", deleted: false, text });
97 }
98
99 moveSync(destination: { readonly uri: string }): void {
100 const entry = files.get(this.uri);
101 if (!entry) throw new Error("missing staged file");
102 files.set(destination.uri, entry);
103 files.delete(this.uri);
104 }
105 },
106 Directory: class {
107 readonly uri: string;
108
109 constructor(parent: string, name: string) {
110 this.uri = `${parent}/${name}`;
111 }
112
113 create(): void {}
114 },
115 FileMode: { ReadOnly: "r", WriteOnly: "w" },
116 Paths: { document: "file:///documents" },
117}));
118
119vi.mock("./uuid", () => ({
120 uuidv4: () => "attachment-id",
121}));
122
123import { convertPastedImagesToAttachments, persistComposerAttachmentFile } from "./composerImages";
124
125const STORED = "file:///documents/t3-composer-attachments/attachment-id";
126
127function oversizedPng(): string {
128 const png = Buffer.alloc(PROVIDER_SEND_TURN_MAX_IMAGE_BYTES + 1);
129 Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]).copy(png);
130 png.write("IHDR", 12);
131 png.writeUInt32BE(2000, 16);
132 png.writeUInt32BE(2000, 20);
133 return png.toString("base64");
134}
135
136describe("native pasted image cleanup", () => {
137 beforeEach(() => {
138 files.clear();
139 manipulator.state.renderedBase64 = "cmVuZGVyZWQ=";
140 });
141
142 it("preserves the reported image type of extensionless Android content URIs", async () => {
143 const uri = "content://media/external/images/media/42";
144 files.set(uri, { base64: "aGVsbG8=", deleted: false, mimeType: "image/jpeg" });
145
146 const { attachments } = await convertPastedImagesToAttachments({
147 uris: [uri],
148 existingCount: 0,
149 });
150
151 expect(attachments).toEqual([
152 expect.objectContaining({
153 name: "pasted-image.jpeg",
154 mimeType: "image/jpeg",
155 fileUri: `${STORED}-pasted-image.jpeg`,
156 previewUri: `${STORED}-pasted-image.jpeg`,
157 }),
158 ]);
159 expect(attachments[0]).not.toHaveProperty("dataUrl");
160 expect(files.get(`${STORED}-pasted-image.jpeg`)?.base64).toBe("aGVsbG8=");
161 expect(files.get(uri)?.deleted).toBe(false);
162 });
163
164 it("renders unsupported images to JPEG and removes the cache file after attaching", async () => {
165 const uri = "content://media/external/images/media/43";
166 files.set(uri, { base64: "b3JpZ2luYWw=", deleted: false, mimeType: "image/heic" });
167 manipulator.state.sourceSize = { width: 100, height: 100 };
168
169 const { attachments } = await convertPastedImagesToAttachments({
170 uris: [uri],
171 existingCount: 0,
172 });
173
174 expect(attachments).toEqual([
175 expect.objectContaining({
176 name: "pasted-image.jpeg",
177 mimeType: "image/jpeg",
178 fileUri: `${STORED}-pasted-image.jpeg`,
179 }),
180 ]);
181 expect(files.get(`${STORED}-pasted-image.jpeg`)?.base64).toBe("cmVuZGVyZWQ=");
182 expect(files.get("file:///cache/rendered.jpeg")?.deleted).toBe(true);
183 expect(files.get(uri)?.deleted).toBe(false);
184 });
185
186 it("removes the rendered JPEG when its bytes exceed the image limit", async () => {
187 const uri = "content://media/external/images/media/43";
188 files.set(uri, { base64: "b3JpZ2luYWw=", deleted: false, mimeType: "image/heic" });
189 manipulator.state.sourceSize = { width: 100, height: 100 };
190 manipulator.state.renderedBase64 = "A".repeat(
191 Math.ceil((PROVIDER_SEND_TURN_MAX_IMAGE_BYTES + 1) / 3) * 4,
192 );
193
194 const { attachments } = await convertPastedImagesToAttachments({
195 uris: [uri],
196 existingCount: 0,
197 });
198
199 expect(attachments).toEqual([]);
200 expect(files.get("file:///cache/rendered.jpeg")?.deleted).toBe(true);
201 expect(files.get(uri)?.deleted).toBe(false);
202 });
203
204 it("stores owned pastes in an attachment file and deletes the source", async () => {
205 const uri =
206 "file:///private/var/mobile/Containers/Data/Application/app/tmp/t3-composer-paste/id.png";
207 const gif =
208 "file:///private/var/mobile/Containers/Data/Application/app/tmp/t3-composer-paste/anim.gif";
209 files.set(uri, { base64: "aGVsbG8=", deleted: false });
210 files.set(gif, { base64: "R0lGODlh", deleted: false });
211
212 const { attachments } = await convertPastedImagesToAttachments({
213 uris: [uri, gif],
214 existingCount: 0,
215 });
216
217 expect(attachments).toEqual([
218 expect.objectContaining({
219 fileUri: `${STORED}-pasted-image.png`,
220 previewUri: `${STORED}-pasted-image.png`,
221 }),
222 expect.objectContaining({ mimeType: "image/gif", fileUri: `${STORED}-pasted-image.gif` }),
223 ]);
224 expect(files.get(`${STORED}-pasted-image.png`)?.base64).toBe("aGVsbG8=");
225 expect(files.get(`${STORED}-pasted-image.gif`)?.base64).toBe("R0lGODlh");
226 expect(files.get(uri)?.deleted).toBe(true);
227 expect(files.get(gif)?.deleted).toBe(true);
228 });
229
230 it("deletes rejected and overflow owned files without deleting user-owned files", async () => {
231 const rejected =
232 "file:///private/var/mobile/Containers/Data/Application/app/tmp/t3-composer-paste/bad.png";
233 const overflow =
234 "file:///private/var/mobile/Containers/Data/Application/app/tmp/t3-composer-paste/overflow.png";
235 const userOwned = "file:///private/var/mobile/photos/library.png";
236 files.set(rejected, { base64: "", deleted: false });
237 files.set(overflow, { base64: "aGVsbG8=", deleted: false });
238 files.set(userOwned, { base64: "aGVsbG8=", deleted: false });
239
240 await convertPastedImagesToAttachments({
241 uris: [rejected, overflow, userOwned],
242 existingCount: PROVIDER_SEND_TURN_MAX_ATTACHMENTS - 1,
243 });
244
245 expect(files.get(rejected)?.deleted).toBe(true);
246 expect(files.get(overflow)?.deleted).toBe(true);
247 expect(files.get(userOwned)?.deleted).toBe(false);
248 });
249
250 it("re-renders an over-limit paste whose dimensions already fit, like the photo picker", async () => {
251 const uri =
252 "file:///private/var/mobile/Containers/Data/Application/app/tmp/t3-composer-paste/photo.png";
253 files.set(uri, { base64: oversizedPng(), deleted: false });
254 manipulator.state.sourceSize = { width: 2000, height: 2000 };
255
256 const { attachments } = await convertPastedImagesToAttachments({
257 uris: [uri],
258 existingCount: 0,
259 });
260
261 expect(attachments).toHaveLength(1);
262 expect(attachments[0]?.sizeBytes).toBeLessThanOrEqual(PROVIDER_SEND_TURN_MAX_IMAGE_BYTES);
263 expect(files.get("file:///cache/rendered.jpeg")?.deleted).toBe(true);
264 });
265
266 it("keeps the readable images of a paste and still reports the one it dropped", async () => {
267 const gone =
268 "file:///private/var/mobile/Containers/Data/Application/app/tmp/t3-composer-paste/gone.png";
269 const kept =
270 "file:///private/var/mobile/Containers/Data/Application/app/tmp/t3-composer-paste/kept.png";
271 files.set(kept, { base64: "aGVsbG8=", deleted: false });
272
273 const result = await convertPastedImagesToAttachments({ uris: [gone, kept], existingCount: 0 });
274
275 expect(result.attachments).toEqual([
276 expect.objectContaining({ fileUri: `${STORED}-pasted-image.png` }),
277 ]);
278 expect(result.error).toBe("Could not read a pasted image.");
279 });
280
281 it("reports the size limit when even the JPEG re-render is too large", async () => {
282 const uri =
283 "file:///private/var/mobile/Containers/Data/Application/app/tmp/t3-composer-paste/huge.png";
284 files.set(uri, { base64: oversizedPng(), deleted: false });
285 manipulator.state.sourceSize = { width: 2000, height: 2000 };
286 manipulator.state.renderedBase64 = oversizedPng();
287
288 const result = await convertPastedImagesToAttachments({ uris: [uri], existingCount: 0 });
289
290 expect(result).toEqual({
291 attachments: [],
292 error: "A pasted image exceeds the 10 MB attachment limit.",
293 });
294 expect(files.get(uri)?.deleted).toBe(true);
295 });
296});
297
298describe("persistComposerAttachmentFile", () => {
299 beforeEach(() => {
300 files.clear();
301 });
302
303 it("stores picked files under a name Android's java.net.URI accepts", async () => {
304 const source = "file:///cache/DocumentPicker/Report [draft].pdf";
305 files.set(source, { base64: "JVBERg==", deleted: false });
306
307 const fileUri = await persistComposerAttachmentFile(source, "Report [draft].pdf");
308
309 // expo-file-system encodes spaces and `%` but leaves `[`, `]`, `|` and `^` raw.
310 expect(fileUri.split("/").at(-1)).toMatch(/^[\w\-.!~*'();:@&=+$, %]+\.pdf$/);
311 });
312});
313
314describe("composerStripAttachments", () => {
315 const image = {
316 id: "img-1",
317 type: "image" as const,
318 name: "shot.jpg",
319 mimeType: "image/jpeg",
320 sizeBytes: 10,
321 dataUrl: "",
322 };
323 const video = {
324 id: "vid-1",
325 type: "file" as const,
326 name: "clip.mp4",
327 mimeType: "video/mp4",
328 sizeBytes: 20,
329 fileUri: "file:///clip.mp4",
330 };
331 const doc = {
332 id: "doc-1",
333 type: "file" as const,
334 name: "notes.txt",
335 mimeType: "text/plain",
336 sizeBytes: 5,
337 fileUri: "file:///notes.txt",
338 };
339
340 it("keeps media beside a document rather than dropping the whole strip", async () => {
341 const { composerStripAttachments } = await import("./composerImages");
342 expect(
343 composerStripAttachments([doc, image, video] as never, () => ({
344 status: "uploading",
345 progress: 0.5,
346 })).map((a) => a.id),
347 ).toEqual(["img-1", "vid-1"]);
348 });
349
350 it("shows a document whose upload failed until its retry finishes", async () => {
351 const { composerStripAttachments } = await import("./composerImages");
352 const strip = (upload: ComposerAttachmentUploadState) =>
353 composerStripAttachments([doc, image] as never, (a) =>
354 a.id === "doc-1" ? upload : undefined,
355 ).map((a) => a.id);
356 expect(strip({ status: "failed", reason: "Service unavailable" })).toEqual(["doc-1", "img-1"]);
357 expect(strip({ status: "uploading", progress: 0.4, retrying: true })).toEqual([
358 "doc-1",
359 "img-1",
360 ]);
361 expect(strip({ status: "ready" })).toEqual(["img-1"]);
362 });
363
364 it("keeps oversized document-picked images visible while sending them as files", async () => {
365 const { composerStripAttachments, isComposerImageAttachment } =
366 await import("./composerImages");
367 const oversizedImage = {
368 ...video,
369 id: "large-image",
370 name: "large.png",
371 mimeType: "image/png",
372 fileUri: "file:///large.png",
373 sizeBytes: PROVIDER_SEND_TURN_MAX_IMAGE_BYTES + 1,
374 };
375
376 expect(composerStripAttachments([oversizedImage], () => undefined)).toEqual([oversizedImage]);
377 expect(isComposerImageAttachment(oversizedImage)).toBe(false);
378 });
379});