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

main
ts 346 lines 11.9 KB
Raw
1 import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
2
3 const mocks = vi.hoisted(() => ({
4 directories: new Set<string>(),
5 deleted: vi.fn(),
6 download: vi.fn(),
7 copy: vi.fn(),
8 share: vi.fn(),
9 shareFromSource: vi.fn(),
10 available: vi.fn(),
11 open: vi.fn(),
12 uuid: vi.fn(),
13 }));
14
15 vi.mock("expo-file-system", () => {
16 class Directory {
17 readonly uri: string;
18
19 constructor(...parts: Array<string | Directory>) {
20 this.uri = parts.map((part) => (typeof part === "string" ? part : part.uri)).join("/");
21 }
22
23 get name(): string {
24 return this.uri.split("/").at(-1)!;
25 }
26
27 get exists(): boolean {
28 return mocks.directories.has(this.uri);
29 }
30
31 create(): void {
32 mocks.directories.add(this.uri);
33 }
34
35 list(): Directory[] {
36 const prefix = `${this.uri}/`;
37 return [...mocks.directories]
38 .filter((uri) => uri.startsWith(prefix) && !uri.slice(prefix.length).includes("/"))
39 .map((uri) => new Directory(uri));
40 }
41
42 delete(): void {
43 mocks.deleted(this.uri);
44 mocks.directories.delete(this.uri);
45 }
46 }
47
48 class File {
49 static downloadFileAsync = mocks.download;
50 readonly uri: string;
51
52 constructor(source: Directory | string, name?: string) {
53 this.uri = typeof source === "string" ? source : `${source.uri}/${encodeURIComponent(name!)}`;
54 }
55
56 async copy(destination: File): Promise<void> {
57 await mocks.copy(this.uri, destination.uri);
58 }
59 }
60
61 return { Directory, File, Paths: { cache: "file:///cache" } };
62 });
63
64 vi.mock("expo", () => ({ requireNativeModule: () => ({ openFile: mocks.open }) }));
65
66 vi.mock("expo-sharing", () => ({
67 isAvailableAsync: mocks.available,
68 shareAsync: mocks.share,
69 }));
70
71 vi.mock("./uuid", () => ({ uuidv4: mocks.uuid }));
72 vi.mock("./shareFileFromSource", () => ({ shareFileFromSource: mocks.shareFromSource }));
73
74 import {
75 downloadAndShareAttachment,
76 downloadAttachmentForPreview,
77 shareLocalAttachment,
78 } from "./attachmentDownload";
79 import { isForegroundHandoffActive } from "./foreground-handoff";
80
81 const NOW = 1_787_990_400_000;
82 const DAY_MS = 24 * 60 * 60_000;
83 const input = {
84 url: "https://chosen-environment.example/api/assets/signed-token/report.pdf",
85 attachment: { name: "report.pdf", mimeType: "application/pdf" },
86 };
87
88 beforeEach(() => {
89 mocks.open.mockReset();
90 mocks.open.mockResolvedValue(undefined);
91 mocks.directories.clear();
92 mocks.deleted.mockReset();
93 mocks.download.mockReset();
94 mocks.copy.mockReset();
95 mocks.share.mockReset();
96 mocks.shareFromSource.mockReset();
97 mocks.available.mockReset();
98 mocks.uuid.mockReset();
99 mocks.download.mockImplementation(async (_url: string, file: { uri: string }) => file);
100 mocks.copy.mockResolvedValue(undefined);
101 mocks.share.mockResolvedValue(undefined);
102 mocks.shareFromSource.mockResolvedValue(undefined);
103 mocks.available.mockResolvedValue(true);
104 let sequence = 0;
105 mocks.uuid.mockImplementation(
106 () => `00000000-0000-4000-8000-${String(++sequence).padStart(12, "0")}`,
107 );
108 vi.spyOn(Date, "now").mockReturnValue(NOW);
109 });
110
111 afterEach(() => {
112 vi.restoreAllMocks();
113 expect(isForegroundHandoffActive()).toBe(false);
114 });
115
116 describe("downloadAndShareAttachment", () => {
117 it("downloads the chosen environment's signed URL and shares the local file", async () => {
118 const controller = new AbortController();
119 await downloadAndShareAttachment({ ...input, signal: controller.signal });
120
121 expect(mocks.download).toHaveBeenCalledWith(
122 input.url,
123 expect.objectContaining({ uri: expect.stringMatching(/\/report\.pdf$/) }),
124 { signal: controller.signal },
125 );
126 expect(mocks.share).toHaveBeenCalledWith(
127 expect.stringMatching(/^file:\/\/\/cache\/.+\/report\.pdf$/),
128 {
129 mimeType: "application/pdf",
130 dialogTitle: "report.pdf",
131 },
132 );
133 expect(mocks.deleted).not.toHaveBeenCalled();
134 });
135
136 it.each([
137 ["../../résumé.pdf", "résumé.pdf"],
138 ["C:\\folder\\clip.mp4", "clip.mp4"],
139 ["..", "attachment"],
140 ["\ud800file\u0000.txt", "_file_.txt"],
141 ])("uses a safe basename for %j", async (name, expected) => {
142 await downloadAndShareAttachment({
143 ...input,
144 attachment: { ...input.attachment, name },
145 signal: new AbortController().signal,
146 });
147 const file = mocks.download.mock.calls[0]![1] as { uri: string };
148 expect(decodeURIComponent(file.uri.split("/").at(-1)!)).toBe(expected);
149 });
150
151 it("bounds the UTF-8 filename length while preserving its extension", async () => {
152 await downloadAndShareAttachment({
153 ...input,
154 attachment: { name: `${"🙂".repeat(80)}.mp4`, mimeType: "video/mp4" },
155 signal: new AbortController().signal,
156 });
157 const file = mocks.download.mock.calls[0]![1] as { uri: string };
158 const name = decodeURIComponent(file.uri.split("/").at(-1)!);
159 expect(name.endsWith(".mp4")).toBe(true);
160 expect(new TextEncoder().encode(name).length).toBeLessThanOrEqual(255);
161 });
162
163 it("reports unavailable sharing before downloading or creating files", async () => {
164 mocks.available.mockResolvedValue(false);
165 await expect(
166 downloadAndShareAttachment({ ...input, signal: new AbortController().signal }),
167 ).rejects.toThrow("Saving and sharing files is unavailable on this device.");
168 expect(mocks.download).not.toHaveBeenCalled();
169 expect(mocks.directories.size).toBe(0);
170 });
171
172 it("cleans an interrupted download only after the native request settles", async () => {
173 const started = Promise.withResolvers<void>();
174 const download = Promise.withResolvers<{ uri: string }>();
175 mocks.download.mockImplementation(() => {
176 started.resolve();
177 return download.promise;
178 });
179 const controller = new AbortController();
180 const task = downloadAndShareAttachment({ ...input, signal: controller.signal });
181 await started.promise;
182 controller.abort();
183 expect(mocks.deleted).not.toHaveBeenCalled();
184 download.reject(new Error("Canceled native request"));
185 await task;
186 expect(mocks.deleted).toHaveBeenCalledTimes(1);
187 expect(mocks.share).not.toHaveBeenCalled();
188 });
189
190 it("retains an export when its row unmounts during the native handoff", async () => {
191 const opened = Promise.withResolvers<void>();
192 const share = Promise.withResolvers<void>();
193 mocks.share.mockImplementation(() => {
194 expect(isForegroundHandoffActive()).toBe(true);
195 opened.resolve();
196 return share.promise;
197 });
198 const controller = new AbortController();
199 const task = downloadAndShareAttachment({ ...input, signal: controller.signal });
200 await opened.promise;
201 controller.abort();
202 share.resolve();
203 await task;
204 expect(mocks.deleted).not.toHaveBeenCalled();
205 });
206
207 it("cleans failed exports and releases the foreground handoff", async () => {
208 mocks.share.mockRejectedValue(new Error("No activity can open this file"));
209 await expect(
210 downloadAndShareAttachment({ ...input, signal: new AbortController().signal }),
211 ).rejects.toThrow("Could not open the share sheet. Try again.");
212 expect(mocks.deleted).toHaveBeenCalledTimes(1);
213 });
214
215 it("does not prune an active export even if it passes the cache expiry", async () => {
216 const opened = Promise.withResolvers<void>();
217 const share = Promise.withResolvers<void>();
218 mocks.share.mockImplementationOnce(() => {
219 opened.resolve();
220 return share.promise;
221 });
222 const first = downloadAndShareAttachment({ ...input, signal: new AbortController().signal });
223 await opened.promise;
224 vi.mocked(Date.now).mockReturnValue(NOW + DAY_MS + 1);
225
226 await downloadAndShareAttachment({ ...input, signal: new AbortController().signal });
227 expect(mocks.deleted).not.toHaveBeenCalled();
228 share.resolve();
229 await first;
230 });
231 });
232
233 describe("attachment preview files", () => {
234 it("does not start a native request after cancellation during setup", async () => {
235 const controller = new AbortController();
236 const loading = downloadAttachmentForPreview({ ...input, signal: controller.signal });
237 controller.abort();
238 await expect(loading).resolves.toBeNull();
239 expect(mocks.download).not.toHaveBeenCalled();
240 expect(mocks.share).not.toHaveBeenCalled();
241 });
242
243 it("downloads for playback without requiring a share sheet and removes the file on close", async () => {
244 mocks.available.mockResolvedValue(false);
245 const file = await downloadAttachmentForPreview({
246 ...input,
247 signal: new AbortController().signal,
248 });
249 expect(file?.uri.endsWith("/report.pdf")).toBe(true);
250 expect(mocks.available).not.toHaveBeenCalled();
251 expect(mocks.deleted).not.toHaveBeenCalled();
252 file?.dispose();
253 file?.dispose();
254 expect(mocks.deleted).toHaveBeenCalledTimes(1);
255 });
256
257 it.each([undefined, "share-button"])(
258 "keeps a shared preview after its owner closes (source: %s)",
259 async (sourceIdentifier) => {
260 const opened = Promise.withResolvers<void>();
261 const sharing = Promise.withResolvers<void>();
262 const nativeShare = sourceIdentifier ? mocks.shareFromSource : mocks.share;
263 nativeShare.mockImplementationOnce(() => {
264 opened.resolve();
265 return sharing.promise;
266 });
267 const file = await downloadAttachmentForPreview({
268 ...input,
269 signal: new AbortController().signal,
270 });
271 const share = file!.share(new AbortController().signal, sourceIdentifier);
272 await opened.promise;
273 file!.dispose();
274 expect(mocks.deleted).not.toHaveBeenCalled();
275 expect(isForegroundHandoffActive()).toBe(true);
276 sharing.resolve();
277 await share;
278 expect(isForegroundHandoffActive()).toBe(false);
279 expect(mocks.deleted).not.toHaveBeenCalled();
280 expect(mocks.download).toHaveBeenCalledTimes(1);
281 expect(mocks.copy).not.toHaveBeenCalled();
282 },
283 );
284
285 it.each([undefined, "share-button"])(
286 "does not share a disposed preview after availability checking (source: %s)",
287 async (sourceIdentifier) => {
288 const checking = Promise.withResolvers<void>();
289 const available = Promise.withResolvers<boolean>();
290 mocks.available.mockImplementation(() => {
291 checking.resolve();
292 return available.promise;
293 });
294 const file = await downloadAttachmentForPreview({
295 ...input,
296 signal: new AbortController().signal,
297 });
298 const share = file!.share(new AbortController().signal, sourceIdentifier);
299 await checking.promise;
300 file!.dispose();
301 available.resolve(true);
302 await share;
303 expect(mocks.share).not.toHaveBeenCalled();
304 expect(mocks.shareFromSource).not.toHaveBeenCalled();
305 expect(mocks.deleted).toHaveBeenCalledTimes(1);
306 },
307 );
308
309 it("copies a local original before sharing without downloading or deleting the source", async () => {
310 const uri = "file:///documents/draft/report.pdf";
311 await shareLocalAttachment({
312 uri,
313 attachment: input.attachment,
314 signal: new AbortController().signal,
315 });
316 expect(mocks.copy).toHaveBeenCalledWith(
317 uri,
318 expect.stringMatching(/^file:\/\/\/cache\/.+\/report\.pdf$/),
319 );
320 expect(mocks.share).toHaveBeenCalledWith(mocks.copy.mock.calls[0]![1], expect.any(Object));
321 expect(mocks.download).not.toHaveBeenCalled();
322 expect(mocks.deleted).not.toHaveBeenCalled();
323 });
324
325 it("waits for a local copy to finish before cleaning up a canceled share", async () => {
326 const copying = Promise.withResolvers<void>();
327 const copied = Promise.withResolvers<void>();
328 mocks.copy.mockImplementation(() => {
329 copying.resolve();
330 return copied.promise;
331 });
332 const controller = new AbortController();
333 const task = shareLocalAttachment({
334 uri: "file:///documents/draft/report.pdf",
335 attachment: input.attachment,
336 signal: controller.signal,
337 });
338 await copying.promise;
339 controller.abort();
340 expect(mocks.deleted).not.toHaveBeenCalled();
341 copied.resolve();
342 await task;
343 expect(mocks.share).not.toHaveBeenCalled();
344 expect(mocks.deleted).toHaveBeenCalledTimes(1);
345 });
346 });