The best way to control Claude Code, Codex and more from any computer or phone

main
ts 373 lines 12.8 KB
Raw
1 import { beforeEach, describe, expect, it, vi } from "vite-plus/test";
2 import {
3 PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
4 PROVIDER_SEND_TURN_MAX_IMAGE_BYTES,
5 } from "@t3tools/contracts";
6 import type { ComposerAttachmentUploadState } from "./composerAttachmentUploadQueue";
7
8 const files = new Map<
9 string,
10 { base64: string; deleted: boolean; text?: string; mimeType?: string }
11 >();
12
13 const 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
37 vi.mock("expo-image-manipulator", () => ({
38 ImageManipulator: { manipulate: manipulator.manipulate },
39 SaveFormat: { JPEG: "jpeg", PNG: "png" },
40 }));
41
42 vi.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
119 vi.mock("./uuid", () => ({
120 uuidv4: () => "attachment-id",
121 }));
122
123 import { convertPastedImagesToAttachments, persistComposerAttachmentFile } from "./composerImages";
124
125 function oversizedPng(): string {
126 const png = Buffer.alloc(PROVIDER_SEND_TURN_MAX_IMAGE_BYTES + 1);
127 Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]).copy(png);
128 png.write("IHDR", 12);
129 png.writeUInt32BE(2000, 16);
130 png.writeUInt32BE(2000, 20);
131 return png.toString("base64");
132 }
133
134 describe("native pasted image cleanup", () => {
135 beforeEach(() => {
136 files.clear();
137 manipulator.state.renderedBase64 = "cmVuZGVyZWQ=";
138 });
139
140 it("preserves the reported image type of extensionless Android content URIs", async () => {
141 const uri = "content://media/external/images/media/42";
142 files.set(uri, { base64: "aGVsbG8=", deleted: false, mimeType: "image/jpeg" });
143
144 const { attachments } = await convertPastedImagesToAttachments({
145 uris: [uri],
146 existingCount: 0,
147 });
148
149 expect(attachments).toEqual([
150 expect.objectContaining({
151 name: "pasted-image.jpeg",
152 mimeType: "image/jpeg",
153 dataUrl: "data:image/jpeg;base64,aGVsbG8=",
154 previewUri: "data:image/jpeg;base64,aGVsbG8=",
155 }),
156 ]);
157 expect(files.get(uri)?.deleted).toBe(false);
158 });
159
160 it("renders unsupported images to JPEG and removes the cache file after attaching", async () => {
161 const uri = "content://media/external/images/media/43";
162 files.set(uri, { base64: "b3JpZ2luYWw=", deleted: false, mimeType: "image/heic" });
163 manipulator.state.sourceSize = { width: 100, height: 100 };
164
165 const { attachments } = await convertPastedImagesToAttachments({
166 uris: [uri],
167 existingCount: 0,
168 });
169
170 expect(attachments).toEqual([
171 expect.objectContaining({
172 name: "pasted-image.jpeg",
173 mimeType: "image/jpeg",
174 dataUrl: "data:image/jpeg;base64,cmVuZGVyZWQ=",
175 previewUri: "data:image/jpeg;base64,cmVuZGVyZWQ=",
176 }),
177 ]);
178 expect(files.get("file:///cache/rendered.jpeg")?.deleted).toBe(true);
179 expect(files.get(uri)?.deleted).toBe(false);
180 });
181
182 it("removes the rendered JPEG when its bytes exceed the image limit", async () => {
183 const uri = "content://media/external/images/media/43";
184 files.set(uri, { base64: "b3JpZ2luYWw=", deleted: false, mimeType: "image/heic" });
185 manipulator.state.sourceSize = { width: 100, height: 100 };
186 manipulator.state.renderedBase64 = "A".repeat(
187 Math.ceil((PROVIDER_SEND_TURN_MAX_IMAGE_BYTES + 1) / 3) * 4,
188 );
189
190 const { attachments } = await convertPastedImagesToAttachments({
191 uris: [uri],
192 existingCount: 0,
193 });
194
195 expect(attachments).toEqual([]);
196 expect(files.get("file:///cache/rendered.jpeg")?.deleted).toBe(true);
197 expect(files.get(uri)?.deleted).toBe(false);
198 });
199
200 it("converts owned files to data-backed previews and deletes the source", async () => {
201 const uri =
202 "file:///private/var/mobile/Containers/Data/Application/app/tmp/t3-composer-paste/id.png";
203 const gif =
204 "file:///private/var/mobile/Containers/Data/Application/app/tmp/t3-composer-paste/anim.gif";
205 files.set(uri, { base64: "aGVsbG8=", deleted: false });
206 files.set(gif, { base64: "R0lGODlh", deleted: false });
207
208 const { attachments } = await convertPastedImagesToAttachments({
209 uris: [uri, gif],
210 existingCount: 0,
211 });
212
213 expect(attachments).toEqual([
214 expect.objectContaining({
215 dataUrl: "data:image/png;base64,aGVsbG8=",
216 previewUri: "data:image/png;base64,aGVsbG8=",
217 }),
218 expect.objectContaining({ mimeType: "image/gif", dataUrl: "data:image/gif;base64,R0lGODlh" }),
219 ]);
220 expect(files.get(uri)?.deleted).toBe(true);
221 expect(files.get(gif)?.deleted).toBe(true);
222 });
223
224 it("deletes rejected and overflow owned files without deleting user-owned files", async () => {
225 const rejected =
226 "file:///private/var/mobile/Containers/Data/Application/app/tmp/t3-composer-paste/bad.png";
227 const overflow =
228 "file:///private/var/mobile/Containers/Data/Application/app/tmp/t3-composer-paste/overflow.png";
229 const userOwned = "file:///private/var/mobile/photos/library.png";
230 files.set(rejected, { base64: "", deleted: false });
231 files.set(overflow, { base64: "aGVsbG8=", deleted: false });
232 files.set(userOwned, { base64: "aGVsbG8=", deleted: false });
233
234 await convertPastedImagesToAttachments({
235 uris: [rejected, overflow, userOwned],
236 existingCount: PROVIDER_SEND_TURN_MAX_ATTACHMENTS - 1,
237 });
238
239 expect(files.get(rejected)?.deleted).toBe(true);
240 expect(files.get(overflow)?.deleted).toBe(true);
241 expect(files.get(userOwned)?.deleted).toBe(false);
242 });
243
244 it("re-renders an over-limit paste whose dimensions already fit, like the photo picker", async () => {
245 const uri =
246 "file:///private/var/mobile/Containers/Data/Application/app/tmp/t3-composer-paste/photo.png";
247 files.set(uri, { base64: oversizedPng(), deleted: false });
248 manipulator.state.sourceSize = { width: 2000, height: 2000 };
249
250 const { attachments } = await convertPastedImagesToAttachments({
251 uris: [uri],
252 existingCount: 0,
253 });
254
255 expect(attachments).toHaveLength(1);
256 expect(attachments[0]?.sizeBytes).toBeLessThanOrEqual(PROVIDER_SEND_TURN_MAX_IMAGE_BYTES);
257 expect(files.get("file:///cache/rendered.jpeg")?.deleted).toBe(true);
258 });
259
260 it("keeps the readable images of a paste and still reports the one it dropped", async () => {
261 const gone =
262 "file:///private/var/mobile/Containers/Data/Application/app/tmp/t3-composer-paste/gone.png";
263 const kept =
264 "file:///private/var/mobile/Containers/Data/Application/app/tmp/t3-composer-paste/kept.png";
265 files.set(kept, { base64: "aGVsbG8=", deleted: false });
266
267 const result = await convertPastedImagesToAttachments({ uris: [gone, kept], existingCount: 0 });
268
269 expect(result.attachments).toEqual([
270 expect.objectContaining({ dataUrl: "data:image/png;base64,aGVsbG8=" }),
271 ]);
272 expect(result.error).toBe("Could not read a pasted image.");
273 });
274
275 it("reports the size limit when even the JPEG re-render is too large", async () => {
276 const uri =
277 "file:///private/var/mobile/Containers/Data/Application/app/tmp/t3-composer-paste/huge.png";
278 files.set(uri, { base64: oversizedPng(), deleted: false });
279 manipulator.state.sourceSize = { width: 2000, height: 2000 };
280 manipulator.state.renderedBase64 = oversizedPng();
281
282 const result = await convertPastedImagesToAttachments({ uris: [uri], existingCount: 0 });
283
284 expect(result).toEqual({
285 attachments: [],
286 error: "A pasted image exceeds the 10 MB attachment limit.",
287 });
288 expect(files.get(uri)?.deleted).toBe(true);
289 });
290 });
291
292 describe("persistComposerAttachmentFile", () => {
293 beforeEach(() => {
294 files.clear();
295 });
296
297 it("stores picked files under a name Android's java.net.URI accepts", async () => {
298 const source = "file:///cache/DocumentPicker/Report [draft].pdf";
299 files.set(source, { base64: "JVBERg==", deleted: false });
300
301 const fileUri = await persistComposerAttachmentFile(source, "Report [draft].pdf");
302
303 // expo-file-system encodes spaces and `%` but leaves `[`, `]`, `|` and `^` raw.
304 expect(fileUri.split("/").at(-1)).toMatch(/^[\w\-.!~*'();:@&=+$, %]+\.pdf$/);
305 });
306 });
307
308 describe("composerStripAttachments", () => {
309 const image = {
310 id: "img-1",
311 type: "image" as const,
312 name: "shot.jpg",
313 mimeType: "image/jpeg",
314 sizeBytes: 10,
315 dataUrl: "",
316 };
317 const video = {
318 id: "vid-1",
319 type: "file" as const,
320 name: "clip.mp4",
321 mimeType: "video/mp4",
322 sizeBytes: 20,
323 fileUri: "file:///clip.mp4",
324 };
325 const doc = {
326 id: "doc-1",
327 type: "file" as const,
328 name: "notes.txt",
329 mimeType: "text/plain",
330 sizeBytes: 5,
331 fileUri: "file:///notes.txt",
332 };
333
334 it("keeps media beside a document rather than dropping the whole strip", async () => {
335 const { composerStripAttachments } = await import("./composerImages");
336 expect(
337 composerStripAttachments([doc, image, video] as never, () => ({
338 status: "uploading",
339 progress: 0.5,
340 })).map((a) => a.id),
341 ).toEqual(["img-1", "vid-1"]);
342 });
343
344 it("shows a document whose upload failed until its retry finishes", async () => {
345 const { composerStripAttachments } = await import("./composerImages");
346 const strip = (upload: ComposerAttachmentUploadState) =>
347 composerStripAttachments([doc, image] as never, (a) =>
348 a.id === "doc-1" ? upload : undefined,
349 ).map((a) => a.id);
350 expect(strip({ status: "failed", reason: "Service unavailable" })).toEqual(["doc-1", "img-1"]);
351 expect(strip({ status: "uploading", progress: 0.4, retrying: true })).toEqual([
352 "doc-1",
353 "img-1",
354 ]);
355 expect(strip({ status: "ready" })).toEqual(["img-1"]);
356 });
357
358 it("keeps oversized document-picked images visible while sending them as files", async () => {
359 const { composerStripAttachments, isComposerImageAttachment } =
360 await import("./composerImages");
361 const oversizedImage = {
362 ...video,
363 id: "large-image",
364 name: "large.png",
365 mimeType: "image/png",
366 fileUri: "file:///large.png",
367 sizeBytes: PROVIDER_SEND_TURN_MAX_IMAGE_BYTES + 1,
368 };
369
370 expect(composerStripAttachments([oversizedImage], () => undefined)).toEqual([oversizedImage]);
371 expect(isComposerImageAttachment(oversizedImage)).toBe(false);
372 });
373 });