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

composerImages.test.ts

329 lines10.6 KB

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​
15vi.mock("expo-file-system", () => ({
16 File: class {
17 readonly uri: string;
18 readonly name: string;
19 readonly parentDirectory: { readonly uri: string };
20​
21 constructor(parent: string | { readonly uri: string }, name?: string) {
22 const parentUri = typeof parent === "string" ? parent : parent.uri;
23 this.uri = name ? `${parentUri}/${name}` : parentUri;
24 this.name = name ?? this.uri.split("/").at(-1) ?? "file";
25 this.parentDirectory = { uri: this.uri.slice(0, -(this.name.length + 1)) };
26 }
27​
28 get exists(): boolean {
29 return files.has(this.uri) && files.get(this.uri)?.deleted === false;
30 }
31​
32 async base64(): Promise<string> {
33 const entry = files.get(this.uri);
34 if (!entry || entry.deleted) {
35 throw new Error("missing file");
36 }
37 return entry.base64;
38 }
39​
40 delete(): void {
41 const entry = files.get(this.uri);
42 if (entry) {
43 entry.deleted = true;
44 }
45 }
46​
47 create(): void {
48 files.set(this.uri, { base64: "", deleted: false });
49 }
50​
51 write(text: string): void {
52 files.set(this.uri, { base64: "", deleted: false, text });
53 }
54​
55 moveSync(destination: { readonly uri: string }): void {
56 const entry = files.get(this.uri);
57 if (!entry) throw new Error("missing staged file");
58 files.set(destination.uri, entry);
59 files.delete(this.uri);
60 }
61 },
62 Directory: class {
63 readonly uri: string;
64​
65 constructor(parent: string, name: string) {
66 this.uri = `${parent}/${name}`;
67 }
68​
69 create(): void {}
70 },
71 Paths: { document: "file:///documents" },
72}));
73​
74vi.mock("./uuid", () => ({
75 uuidv4: () => "attachment-id",
76}));
77​
78import {
79 convertPastedImagesToAttachments,
80 createPastedTextComposerAttachment,
81 isOwnedPastedImageUri,
82 pasteComposerClipboard,
83} from "./composerImages";
84​
85describe("composer clipboard paste", () => {
86 beforeEach(() => {
87 vi.clearAllMocks();
88 clipboard.hasImageAsync.mockResolvedValue(false);
89 clipboard.hasStringAsync.mockResolvedValue(true);
90 clipboard.getStringAsync.mockResolvedValue("clipboard text");
91 clipboard.getImageAsync.mockResolvedValue({ data: "data:image/png;base64,aGVsbG8=" });
92 });
93​
94 it("returns only the image when the clipboard contains both image and text", async () => {
95 clipboard.hasImageAsync.mockResolvedValue(true);
96 const result = await pasteComposerClipboard({ existingCount: 0 });
97 expect(result).toEqual({
98 images: [expect.objectContaining({ type: "image", name: "pasted-image.png" })],
99 text: null,
100 error: null,
101 });
102 expect(clipboard.getStringAsync).not.toHaveBeenCalled();
103 });
104​
105 it("does not paste alternate text when the image cannot fit", async () => {
106 clipboard.hasImageAsync.mockResolvedValue(true);
107 expect(
108 await pasteComposerClipboard({ existingCount: PROVIDER_SEND_TURN_MAX_ATTACHMENTS }),
109 ).toEqual({ images: [], text: null, error: expect.stringContaining("up to") });
110 expect(clipboard.getStringAsync).not.toHaveBeenCalled();
111 });
112​
113 it("returns plain text without image chips", async () => {
114 expect(await pasteComposerClipboard({ existingCount: 0 })).toEqual({
115 images: [],
116 text: "clipboard text",
117 error: null,
118 });
119 });
120​
121 it("reports an empty text clipboard", async () => {
122 clipboard.getStringAsync.mockResolvedValue("");
123 expect(await pasteComposerClipboard({ existingCount: 0 })).toEqual({
124 images: [],
125 text: null,
126 error: "Clipboard is empty.",
127 });
128 });
129});
130​
131describe("native pasted image cleanup", () => {
132 beforeEach(() => {
133 files.clear();
134 });
135​
136 it("recognizes only files created in the native composer paste directory", () => {
137 expect(
138 isOwnedPastedImageUri(
139 "file:///private/var/mobile/Containers/Data/Application/app/tmp/t3-composer-paste/id.png",
140 ),
141 ).toBe(true);
142 expect(isOwnedPastedImageUri("file:///private/var/mobile/photos/id.png")).toBe(false);
143 expect(isOwnedPastedImageUri("https://example.com/t3-composer-paste/id.png")).toBe(false);
144 });
145​
146 it("converts owned files to data-backed previews and deletes the source", async () => {
147 const uri =
148 "file:///private/var/mobile/Containers/Data/Application/app/tmp/t3-composer-paste/id.png";
149 files.set(uri, { base64: "aGVsbG8=", deleted: false });
150​
151 const attachments = await convertPastedImagesToAttachments({
152 uris: [uri],
153 existingCount: 0,
154 });
155​
156 expect(attachments).toEqual([
157 expect.objectContaining({
158 dataUrl: "data:image/png;base64,aGVsbG8=",
159 previewUri: "data:image/png;base64,aGVsbG8=",
160 }),
161 ]);
162 expect(files.get(uri)?.deleted).toBe(true);
163 });
164​
165 it("deletes rejected and overflow owned files without deleting user-owned files", async () => {
166 const rejected =
167 "file:///private/var/mobile/Containers/Data/Application/app/tmp/t3-composer-paste/bad.png";
168 const overflow =
169 "file:///private/var/mobile/Containers/Data/Application/app/tmp/t3-composer-paste/overflow.png";
170 const userOwned = "file:///private/var/mobile/photos/library.png";
171 files.set(rejected, { base64: "", deleted: false });
172 files.set(overflow, { base64: "aGVsbG8=", deleted: false });
173 files.set(userOwned, { base64: "aGVsbG8=", deleted: false });
174​
175 await convertPastedImagesToAttachments({
176 uris: [rejected, overflow, userOwned],
177 existingCount: PROVIDER_SEND_TURN_MAX_ATTACHMENTS - 1,
178 });
179​
180 expect(files.get(rejected)?.deleted).toBe(true);
181 expect(files.get(overflow)?.deleted).toBe(true);
182 expect(files.get(userOwned)?.deleted).toBe(false);
183 });
184​
185 it("persists folded text unchanged in the app-owned attachment directory", async () => {
186 const text = "first line\nUnicode: 🙂\n";
187 const attachment = await createPastedTextComposerAttachment({
188 text,
189 name: "pasted-text.txt",
190 maxBytes: 1024,
191 });
192​
193 expect(attachment).toEqual({
194 id: "attachment-id",
195 type: "file",
196 name: "pasted-text.txt",
197 mimeType: "text/plain;charset=utf-8",
198 sizeBytes: new TextEncoder().encode(text).byteLength,
199 fileUri: "file:///documents/t3-composer-attachments/attachment-id-pasted-text.txt",
200 source: { _tag: "pasted-text" },
201 });
202 expect(files.get(attachment.fileUri)?.text).toBe(text);
203 });
204});
205​
206describe("composerStripAttachments", () => {
207 const image = {
208 id: "img-1",
209 type: "image" as const,
210 name: "shot.jpg",
211 mimeType: "image/jpeg",
212 sizeBytes: 10,
213 dataUrl: "",
214 };
215 const video = {
216 id: "vid-1",
217 type: "file" as const,
218 name: "clip.mp4",
219 mimeType: "video/mp4",
220 sizeBytes: 20,
221 fileUri: "file:///clip.mp4",
222 };
223 const doc = {
224 id: "doc-1",
225 type: "file" as const,
226 name: "notes.txt",
227 mimeType: "text/plain",
228 sizeBytes: 5,
229 fileUri: "file:///notes.txt",
230 };
231​
232 it("keeps media, because a thumbnail is the only way to see it", async () => {
233 const { composerStripAttachments } = await import("./composerImages");
234 const kept = composerStripAttachments([image, video] as never);
235 expect(kept.map((a) => a.id)).toEqual(["img-1", "vid-1"]);
236 });
237​
238 it("never shows a non-media file above the composer", async () => {
239 const { composerStripAttachments } = await import("./composerImages");
240 // A document reads as its inline chip. A tile with a generic glyph says less than the
241 // chip does, so it is not a fallback worth having, chip present or not.
242 expect(composerStripAttachments([doc] as never)).toEqual([]);
243 });
244​
245 it("keeps media beside a document rather than dropping the whole strip", async () => {
246 const { composerStripAttachments } = await import("./composerImages");
247 expect(composerStripAttachments([doc, image, video] as never).map((a) => a.id)).toEqual([
248 "img-1",
249 "vid-1",
250 ]);
251 });
252​
253 it("treats a picture picked through the document picker as media", async () => {
254 const { composerStripAttachments } = await import("./composerImages");
255 // The document picker types every pick as a plain file; what it *is* decides the strip.
256 const pickedImage = {
257 id: "pick-1",
258 type: "file" as const,
259 name: "photo.png",
260 mimeType: "image/png",
261 sizeBytes: 30,
262 fileUri: "file:///photo.png",
263 };
264 expect(composerStripAttachments([pickedImage] as never).map((a) => a.id)).toEqual(["pick-1"]);
265 });
266});
267​
268describe("composerAttachmentInlineUri", () => {
269 it("offers the inline bytes of a picture that owns no file", async () => {
270 const { composerAttachmentInlineUri } = await import("./composerImages");
271 // The photo library and the clipboard both produce this shape. Its `attachmentId` is a
272 // local draft id, so a remote asset lookup for it can only fail.
273 expect(
274 composerAttachmentInlineUri({
275 id: "img-1",
276 type: "image",
277 name: "IMG_0111.jpg",
278 mimeType: "image/jpeg",
279 sizeBytes: 9_100_000,
280 dataUrl: "data:image/jpeg;base64,AAAA",
281 previewUri: "ph://asset",
282 } as never),
283 ).toBe("data:image/jpeg;base64,AAAA");
284 });
285​
286 it("falls back to the preview when a picture kept only its asset uri", async () => {
287 const { composerAttachmentInlineUri } = await import("./composerImages");
288 expect(
289 composerAttachmentInlineUri({
290 id: "img-2",
291 type: "image",
292 name: "IMG_0112.jpg",
293 mimeType: "image/jpeg",
294 sizeBytes: 10,
295 previewUri: "ph://asset",
296 } as never),
297 ).toBe("ph://asset");
298 });
299​
300 it("leaves a file-backed attachment to the retain-lease path", async () => {
301 const { composerAttachmentInlineUri } = await import("./composerImages");
302 expect(
303 composerAttachmentInlineUri({
304 id: "img-3",
305 type: "image",
306 name: "IMG_0113.jpg",
307 mimeType: "image/jpeg",
308 sizeBytes: 10,
309 fileUri: "file:///owned.jpg",
310 previewUri: "file:///owned.jpg",
311 } as never),
312 ).toBeUndefined();
313 });
314​
315 it("has nothing to offer for a plain file or a missing attachment", async () => {
316 const { composerAttachmentInlineUri } = await import("./composerImages");
317 expect(composerAttachmentInlineUri(undefined)).toBeUndefined();
318 expect(
319 composerAttachmentInlineUri({
320 id: "doc-1",
321 type: "file",
322 name: "notes.txt",
323 mimeType: "text/plain",
324 sizeBytes: 4,
325 fileUri: "file:///notes.txt",
326 } as never),
327 ).toBeUndefined();
328 });
329});