Open History to see the last commit
1import { beforeEach, describe, expect, it, vi } from "vite-plus/test";
2import { PROVIDER_SEND_TURN_MAX_ATTACHMENTS } from "@t3tools/contracts";
3
4const files = new Map<string, { base64: string; deleted: boolean; text?: string }>();
5
6const clipboard = vi.hoisted(() => ({
7 hasImageAsync: vi.fn(),
8 getImageAsync: vi.fn(),
9 hasStringAsync: vi.fn(),
10 getStringAsync: vi.fn(),
11}));
12
13vi.mock("expo-clipboard", () => clipboard);
14
15const manipulator = vi.hoisted(() => {
16 const state = { sourceSize: { width: 0, height: 0 } };
17 const manipulate = vi.fn((source: string | { width: number; height: number }) => {
18 let size = typeof source === "string" ? state.sourceSize : source;
19 const context = {
20 resize: vi.fn((next: { width: number; height: number }) => {
21 size = next;
22 return context;
23 }),
24 renderAsync: vi.fn(async () => ({
25 ...size,
26 release: vi.fn(),
27 saveAsync: vi.fn(async (options: { format: string }) => ({
28 uri: `file:///cache/rendered.${options.format}`,
29 base64: `cmVuZGVyZWQ=`,
30 })),
31 })),
32 };
33 return context;
34 });
35 return { state, manipulate };
36});
37
38vi.mock("expo-image-manipulator", () => ({
39 ImageManipulator: { manipulate: manipulator.manipulate },
40 SaveFormat: { JPEG: "jpeg", PNG: "png" },
41}));
42
43vi.mock("expo-file-system", () => ({
44 File: class {
45 readonly uri: string;
46 readonly name: string;
47 readonly parentDirectory: { readonly uri: string };
48
49 constructor(parent: string | { readonly uri: string }, name?: string) {
50 const parentUri = typeof parent === "string" ? parent : parent.uri;
51 this.uri = name ? `${parentUri}/${name}` : parentUri;
52 this.name = name ?? this.uri.split("/").at(-1) ?? "file";
53 this.parentDirectory = { uri: this.uri.slice(0, -(this.name.length + 1)) };
54 }
55
56 get exists(): boolean {
57 return files.has(this.uri) && files.get(this.uri)?.deleted === false;
58 }
59
60 async base64(): Promise<string> {
61 const entry = files.get(this.uri);
62 if (!entry || entry.deleted) {
63 throw new Error("missing file");
64 }
65 return entry.base64;
66 }
67
68 delete(): void {
69 const entry = files.get(this.uri);
70 if (entry) {
71 entry.deleted = true;
72 }
73 }
74
75 create(): void {
76 files.set(this.uri, { base64: "", deleted: false });
77 }
78
79 write(text: string): void {
80 files.set(this.uri, { base64: "", deleted: false, text });
81 }
82
83 moveSync(destination: { readonly uri: string }): void {
84 const entry = files.get(this.uri);
85 if (!entry) throw new Error("missing staged file");
86 files.set(destination.uri, entry);
87 files.delete(this.uri);
88 }
89 },
90 Directory: class {
91 readonly uri: string;
92
93 constructor(parent: string, name: string) {
94 this.uri = `${parent}/${name}`;
95 }
96
97 create(): void {}
98 },
99 Paths: { document: "file:///documents" },
100}));
101
102vi.mock("./uuid", () => ({
103 uuidv4: () => "attachment-id",
104}));
105
106import {
107 convertPastedImagesToAttachments,
108 createPastedTextComposerAttachment,
109 isOwnedPastedImageUri,
110 pasteComposerClipboard,
111} from "./composerImages";
112
113describe("composer clipboard paste", () => {
114 beforeEach(() => {
115 vi.clearAllMocks();
116 clipboard.hasImageAsync.mockResolvedValue(false);
117 clipboard.hasStringAsync.mockResolvedValue(true);
118 clipboard.getStringAsync.mockResolvedValue("clipboard text");
119 clipboard.getImageAsync.mockResolvedValue({ data: "data:image/png;base64,aGVsbG8=" });
120 });
121
122 it("returns only the image when the clipboard contains both image and text", async () => {
123 clipboard.hasImageAsync.mockResolvedValue(true);
124 const result = await pasteComposerClipboard({ existingCount: 0 });
125 expect(result).toEqual({
126 images: [expect.objectContaining({ type: "image", name: "pasted-image.png" })],
127 text: null,
128 error: null,
129 });
130 expect(clipboard.getStringAsync).not.toHaveBeenCalled();
131 });
132
133 it("does not paste alternate text when the image cannot fit", async () => {
134 clipboard.hasImageAsync.mockResolvedValue(true);
135 expect(
136 await pasteComposerClipboard({ existingCount: PROVIDER_SEND_TURN_MAX_ATTACHMENTS }),
137 ).toEqual({ images: [], text: null, error: expect.stringContaining("up to") });
138 expect(clipboard.getStringAsync).not.toHaveBeenCalled();
139 });
140
141 it("returns plain text without image chips", async () => {
142 expect(await pasteComposerClipboard({ existingCount: 0 })).toEqual({
143 images: [],
144 text: "clipboard text",
145 error: null,
146 });
147 });
148
149 it("reports an empty text clipboard", async () => {
150 clipboard.getStringAsync.mockResolvedValue("");
151 expect(await pasteComposerClipboard({ existingCount: 0 })).toEqual({
152 images: [],
153 text: null,
154 error: "Clipboard is empty.",
155 });
156 });
157});
158
159describe("oversized pasted images", () => {
160 const u32 = (n: number) => [(n >>> 24) & 0xff, (n >>> 16) & 0xff, (n >>> 8) & 0xff, n & 0xff];
161 const pngDataUrl = (width: number, height: number) =>
162 `data:image/png;base64,${Buffer.from([
163 0x89,
164 0x50,
165 0x4e,
166 0x47,
167 0x0d,
168 0x0a,
169 0x1a,
170 0x0a,
171 ...u32(13),
172 0x49,
173 0x48,
174 0x44,
175 0x52,
176 ...u32(width),
177 ...u32(height),
178 8,
179 6,
180 0,
181 0,
182 0,
183 ]).toString("base64")}`;
184
185 beforeEach(() => {
186 vi.clearAllMocks();
187 clipboard.hasImageAsync.mockResolvedValue(true);
188 });
189
190 it("scales a clipboard screenshot over 2000px to 2000px and keeps it a PNG", async () => {
191 manipulator.state.sourceSize = { width: 3024, height: 1964 };
192 const pasted = pngDataUrl(3024, 1964);
193 clipboard.getImageAsync.mockResolvedValue({ data: pasted });
194
195 const result = await pasteComposerClipboard({ existingCount: 0 });
196
197 expect(manipulator.manipulate).toHaveBeenCalledWith(pasted);
198 const resize = manipulator.manipulate.mock.results.at(-1)?.value.resize;
199 expect(resize).toHaveBeenCalledWith({ width: 2000, height: 1299 });
200 expect(result.images).toEqual([
201 expect.objectContaining({
202 mimeType: "image/png",
203 dataUrl: "data:image/png;base64,cmVuZGVyZWQ=",
204 previewUri: "data:image/png;base64,cmVuZGVyZWQ=",
205 }),
206 ]);
207 });
208
209 it("keeps a 2000px clipboard image byte for byte without rendering it", async () => {
210 const pasted = pngDataUrl(2000, 1200);
211 clipboard.getImageAsync.mockResolvedValue({ data: pasted });
212
213 const result = await pasteComposerClipboard({ existingCount: 0 });
214
215 expect(manipulator.manipulate).not.toHaveBeenCalled();
216 expect(result.images).toEqual([expect.objectContaining({ dataUrl: pasted })]);
217 });
218});
219
220describe("native pasted image cleanup", () => {
221 beforeEach(() => {
222 files.clear();
223 });
224
225 it("recognizes only files created in the native composer paste directory", () => {
226 expect(
227 isOwnedPastedImageUri(
228 "file:///private/var/mobile/Containers/Data/Application/app/tmp/t3-composer-paste/id.png",
229 ),
230 ).toBe(true);
231 expect(isOwnedPastedImageUri("file:///private/var/mobile/photos/id.png")).toBe(false);
232 expect(isOwnedPastedImageUri("https://example.com/t3-composer-paste/id.png")).toBe(false);
233 });
234
235 it("converts owned files to data-backed previews and deletes the source", async () => {
236 const uri =
237 "file:///private/var/mobile/Containers/Data/Application/app/tmp/t3-composer-paste/id.png";
238 files.set(uri, { base64: "aGVsbG8=", deleted: false });
239
240 const attachments = await convertPastedImagesToAttachments({
241 uris: [uri],
242 existingCount: 0,
243 });
244
245 expect(attachments).toEqual([
246 expect.objectContaining({
247 dataUrl: "data:image/png;base64,aGVsbG8=",
248 previewUri: "data:image/png;base64,aGVsbG8=",
249 }),
250 ]);
251 expect(files.get(uri)?.deleted).toBe(true);
252 });
253
254 it("deletes rejected and overflow owned files without deleting user-owned files", async () => {
255 const rejected =
256 "file:///private/var/mobile/Containers/Data/Application/app/tmp/t3-composer-paste/bad.png";
257 const overflow =
258 "file:///private/var/mobile/Containers/Data/Application/app/tmp/t3-composer-paste/overflow.png";
259 const userOwned = "file:///private/var/mobile/photos/library.png";
260 files.set(rejected, { base64: "", deleted: false });
261 files.set(overflow, { base64: "aGVsbG8=", deleted: false });
262 files.set(userOwned, { base64: "aGVsbG8=", deleted: false });
263
264 await convertPastedImagesToAttachments({
265 uris: [rejected, overflow, userOwned],
266 existingCount: PROVIDER_SEND_TURN_MAX_ATTACHMENTS - 1,
267 });
268
269 expect(files.get(rejected)?.deleted).toBe(true);
270 expect(files.get(overflow)?.deleted).toBe(true);
271 expect(files.get(userOwned)?.deleted).toBe(false);
272 });
273
274 it("persists folded text unchanged in the app-owned attachment directory", async () => {
275 const text = "first line\nUnicode: 🙂\n";
276 const attachment = await createPastedTextComposerAttachment({
277 text,
278 name: "pasted-text.txt",
279 maxBytes: 1024,
280 });
281
282 expect(attachment).toEqual({
283 id: "attachment-id",
284 type: "file",
285 name: "pasted-text.txt",
286 mimeType: "text/plain;charset=utf-8",
287 sizeBytes: new TextEncoder().encode(text).byteLength,
288 fileUri: "file:///documents/t3-composer-attachments/attachment-id-pasted-text.txt",
289 source: { _tag: "pasted-text" },
290 });
291 expect(files.get(attachment.fileUri)?.text).toBe(text);
292 });
293});
294
295describe("composerStripAttachments", () => {
296 const image = {
297 id: "img-1",
298 type: "image" as const,
299 name: "shot.jpg",
300 mimeType: "image/jpeg",
301 sizeBytes: 10,
302 dataUrl: "",
303 };
304 const video = {
305 id: "vid-1",
306 type: "file" as const,
307 name: "clip.mp4",
308 mimeType: "video/mp4",
309 sizeBytes: 20,
310 fileUri: "file:///clip.mp4",
311 };
312 const doc = {
313 id: "doc-1",
314 type: "file" as const,
315 name: "notes.txt",
316 mimeType: "text/plain",
317 sizeBytes: 5,
318 fileUri: "file:///notes.txt",
319 };
320
321 it("keeps media, because a thumbnail is the only way to see it", async () => {
322 const { composerStripAttachments } = await import("./composerImages");
323 const kept = composerStripAttachments([image, video] as never);
324 expect(kept.map((a) => a.id)).toEqual(["img-1", "vid-1"]);
325 });
326
327 it("never shows a non-media file above the composer", async () => {
328 const { composerStripAttachments } = await import("./composerImages");
329 expect(composerStripAttachments([doc] as never)).toEqual([]);
330 });
331
332 it("keeps media beside a document rather than dropping the whole strip", async () => {
333 const { composerStripAttachments } = await import("./composerImages");
334 expect(composerStripAttachments([doc, image, video] as never).map((a) => a.id)).toEqual([
335 "img-1",
336 "vid-1",
337 ]);
338 });
339
340 it("treats a picture picked through the document picker as media", async () => {
341 const { composerStripAttachments } = await import("./composerImages");
342 const pickedImage = {
343 id: "pick-1",
344 type: "file" as const,
345 name: "photo.png",
346 mimeType: "image/png",
347 sizeBytes: 30,
348 fileUri: "file:///photo.png",
349 };
350 expect(composerStripAttachments([pickedImage] as never).map((a) => a.id)).toEqual(["pick-1"]);
351 });
352});
353
354describe("composerAttachmentInlineUri", () => {
355 it("offers the inline bytes of a picture that owns no file", async () => {
356 const { composerAttachmentInlineUri } = await import("./composerImages");
357 expect(
358 composerAttachmentInlineUri({
359 id: "img-1",
360 type: "image",
361 name: "IMG_0111.jpg",
362 mimeType: "image/jpeg",
363 sizeBytes: 9_100_000,
364 dataUrl: "data:image/jpeg;base64,AAAA",
365 previewUri: "ph://asset",
366 } as never),
367 ).toBe("data:image/jpeg;base64,AAAA");
368 });
369
370 it("falls back to the preview when a picture kept only its asset uri", async () => {
371 const { composerAttachmentInlineUri } = await import("./composerImages");
372 expect(
373 composerAttachmentInlineUri({
374 id: "img-2",
375 type: "image",
376 name: "IMG_0112.jpg",
377 mimeType: "image/jpeg",
378 sizeBytes: 10,
379 previewUri: "ph://asset",
380 } as never),
381 ).toBe("ph://asset");
382 });
383
384 it("leaves a file-backed attachment to the retain-lease path", async () => {
385 const { composerAttachmentInlineUri } = await import("./composerImages");
386 expect(
387 composerAttachmentInlineUri({
388 id: "img-3",
389 type: "image",
390 name: "IMG_0113.jpg",
391 mimeType: "image/jpeg",
392 sizeBytes: 10,
393 fileUri: "file:///owned.jpg",
394 previewUri: "file:///owned.jpg",
395 } as never),
396 ).toBeUndefined();
397 });
398
399 it("has nothing to offer for a plain file or a missing attachment", async () => {
400 const { composerAttachmentInlineUri } = await import("./composerImages");
401 expect(composerAttachmentInlineUri(undefined)).toBeUndefined();
402 expect(
403 composerAttachmentInlineUri({
404 id: "doc-1",
405 type: "file",
406 name: "notes.txt",
407 mimeType: "text/plain",
408 sizeBytes: 4,
409 fileUri: "file:///notes.txt",
410 } as never),
411 ).toBeUndefined();
412 });
413});