Open History to see the last commit
1import { EnvironmentId } from "@t3tools/contracts";
2import * as Option from "effect/Option";
3import { beforeEach, describe, expect, it, vi } from "vite-plus/test";
4
5const mocks = vi.hoisted(() => ({
6 documentUri: "file:///documents",
7 createAssetUrl: vi.fn(),
8 createUploadUrl: Symbol("create-upload-url"),
9 executeAtomQuery: vi.fn(),
10 removeUpload: Symbol("remove-upload"),
11 preparedConnection: Symbol("prepared-connection"),
12 runAtomCommand: vi.fn(),
13 readAtom: vi.fn(),
14 upload: vi.fn(),
15}));
16
17vi.mock("@t3tools/client-runtime/state/runtime", () => ({
18 // The client-runtime attachments module resolves the same file through its
19 // relative import, so these fakes also feed runAttachmentUploadCycle and
20 // verifyPersistedAttachmentUpload.
21 createEnvironmentRpcCommand: () => Symbol("rpc-command"),
22 executeAtomQuery: mocks.executeAtomQuery,
23 runAtomCommand: mocks.runAtomCommand,
24 squashAtomCommandFailure: (result: { readonly error: unknown }) => result.error,
25}));
26
27vi.mock("../state/atom-registry", () => ({
28 appAtomRegistry: { get: mocks.readAtom },
29}));
30
31vi.mock("../state/assets", () => ({
32 assetEnvironment: { createUrl: mocks.createAssetUrl },
33}));
34
35vi.mock("../state/attachments", () => ({
36 attachmentEnvironment: {
37 createUploadUrl: mocks.createUploadUrl,
38 remove: mocks.removeUpload,
39 },
40}));
41
42vi.mock("../state/session", () => ({
43 environmentSession: {
44 preparedConnectionValueAtom: () => mocks.preparedConnection,
45 },
46}));
47
48// Cuts the expo-crypto -> react-native import chain out of the test graph.
49vi.mock("./uuid", () => ({
50 uuidv4: () => "uuid",
51 randomHex: () => "0000",
52}));
53
54vi.mock("expo-file-system", () => ({
55 File: class {
56 constructor(readonly uri: string) {}
57
58 upload(url: string, options: unknown) {
59 return mocks.upload(this.uri, url, options);
60 }
61 },
62 Paths: {
63 get document() {
64 return { uri: mocks.documentUri };
65 },
66 },
67 UploadType: { BINARY_CONTENT: 0 },
68}));
69
70import {
71 prepareTurnAttachments,
72 releasePendingAttachmentUploads,
73 withUploadedMobileAttachmentReferences,
74 validateDraftFileAttachments,
75} from "./attachmentUpload";
76import type { DraftComposerAttachment } from "./composerImages";
77
78const environmentId = EnvironmentId.make("environment-1");
79const MINTED_ID = "pending-00000000-0000-4000-8000-000000000001-pdf";
80
81const image = {
82 id: "image-1",
83 type: "image",
84 name: "screenshot.png",
85 mimeType: "image/png",
86 sizeBytes: 3,
87 dataUrl: "data:image/png;base64,YWJj",
88 previewUri: "file:///images/screenshot.png",
89} as const satisfies DraftComposerAttachment;
90
91const file = {
92 id: "file-1",
93 type: "file",
94 name: "report.pdf",
95 mimeType: "application/pdf",
96 sizeBytes: 42,
97 fileUri: "file:///documents/report.pdf",
98} as const satisfies DraftComposerAttachment;
99
100describe("validateDraftFileAttachments", () => {
101 it("allows legacy image-only sends without server config", () => {
102 expect(validateDraftFileAttachments({ attachments: [image], serverConfig: null })).toBeNull();
103 });
104
105 it("blocks files while config is unknown or file uploads are unsupported", () => {
106 expect(validateDraftFileAttachments({ attachments: [file], serverConfig: null })).toBe(
107 "Server attachment support is still loading.",
108 );
109 expect(
110 validateDraftFileAttachments({
111 attachments: [file],
112 serverConfig: { environment: { capabilities: { attachmentUploads: true } } },
113 }),
114 ).toBe("This server does not support file attachments.");
115 });
116
117 it("uses the current clamped limit and allows valid mixed attachments", () => {
118 const lowerLimit = {
119 environment: {
120 capabilities: {
121 attachmentUploads: true,
122 fileAttachments: { maxUploadBytes: 20 },
123 },
124 },
125 };
126 expect(validateDraftFileAttachments({ attachments: [file], serverConfig: lowerLimit })).toBe(
127 "'report.pdf' exceeds the 20 bytes attachment limit.",
128 );
129 const allowed = {
130 environment: {
131 capabilities: {
132 attachmentUploads: true,
133 fileAttachments: { maxUploadBytes: 100 },
134 },
135 },
136 };
137 expect(
138 validateDraftFileAttachments({ attachments: [image, file], serverConfig: allowed }),
139 ).toBeNull();
140 });
141});
142
143function removeCallsFor(attachmentId: string): number {
144 return mocks.runAtomCommand.mock.calls.filter(
145 ([, command, target]) =>
146 command === mocks.removeUpload &&
147 (target as { input: { attachmentId: string } }).input.attachmentId === attachmentId,
148 ).length;
149}
150
151describe("prepareTurnAttachments", () => {
152 beforeEach(() => {
153 mocks.documentUri = "file:///documents";
154 mocks.createAssetUrl.mockReset();
155 mocks.createAssetUrl.mockImplementation((target: unknown) => target);
156 mocks.executeAtomQuery.mockReset();
157 mocks.executeAtomQuery.mockResolvedValue({ _tag: "Success", value: {} });
158 mocks.runAtomCommand.mockReset();
159 mocks.readAtom.mockReset();
160 mocks.upload.mockReset();
161 mocks.readAtom.mockReturnValue(Option.some({ httpBaseUrl: "https://environment.example/" }));
162 mocks.runAtomCommand.mockImplementation(async (_registry: unknown, command: unknown) =>
163 command === mocks.createUploadUrl
164 ? {
165 _tag: "Success",
166 value: {
167 attachmentId: MINTED_ID,
168 relativeUrl: "/api/attachments/upload/signed",
169 expiresAt: 1,
170 },
171 }
172 : { _tag: "Success", value: undefined },
173 );
174 mocks.upload.mockResolvedValue({ status: 204, body: "", headers: {} });
175 });
176
177 it("keeps existing image attachments on the legacy wire path", async () => {
178 const prepared = await prepareTurnAttachments({ environmentId, attachments: [image] });
179
180 expect(prepared.status).toBe("ready");
181 if (prepared.status !== "ready") return;
182 expect(prepared.attachments).toEqual([
183 {
184 type: "image",
185 name: "screenshot.png",
186 mimeType: "image/png",
187 sizeBytes: 3,
188 dataUrl: "data:image/png;base64,YWJj",
189 },
190 ]);
191 expect(prepared.pendingAttachmentIds).toEqual([]);
192 expect(mocks.upload).not.toHaveBeenCalled();
193 });
194
195 it("uploads generic file bytes directly and keeps mixed attachment order", async () => {
196 const prepared = await prepareTurnAttachments({ environmentId, attachments: [file, image] });
197
198 expect(mocks.upload).toHaveBeenCalledWith(
199 "file:///documents/report.pdf",
200 "https://environment.example/api/attachments/upload/signed",
201 {
202 httpMethod: "POST",
203 uploadType: 0,
204 headers: { "Content-Type": "application/pdf" },
205 },
206 );
207 expect(prepared.status).toBe("ready");
208 if (prepared.status !== "ready") return;
209 expect(prepared.attachments[0]).toEqual({
210 type: "file",
211 id: MINTED_ID,
212 name: "report.pdf",
213 mimeType: "application/pdf",
214 sizeBytes: 42,
215 });
216 expect(prepared.attachments[1]?.type).toBe("image");
217 expect(prepared.pendingAttachmentIds).toEqual([MINTED_ID]);
218 expect(prepared.draftAttachments[0]).toEqual({
219 ...file,
220 uploadedAttachmentId: MINTED_ID,
221 uploadEnvironmentId: environmentId,
222 });
223 });
224
225 it("uses the current connection when an environment reconnects during URL creation", async () => {
226 mocks.readAtom
227 .mockReturnValueOnce(Option.some({ httpBaseUrl: "https://old-environment.example/" }))
228 .mockReturnValueOnce(Option.some({ httpBaseUrl: "https://new-environment.example/" }));
229
230 await prepareTurnAttachments({ environmentId, attachments: [file] });
231
232 expect(mocks.upload).toHaveBeenCalledWith(
233 file.fileUri,
234 "https://new-environment.example/api/attachments/upload/signed",
235 expect.anything(),
236 );
237 });
238
239 it("uploads a restored draft file from the current iOS document container", async () => {
240 const fileName = "33333333-3333-4333-8333-333333333333-report%20%23.pdf";
241 const restoredFile = {
242 ...file,
243 fileUri: `file:///private/var/mobile/Containers/Data/Application/11111111-1111-4111-8111-111111111111/Documents/t3-composer-attachments/${fileName}`,
244 };
245 mocks.documentUri =
246 "file:///var/mobile/Containers/Data/Application/22222222-2222-4222-8222-222222222222/Documents";
247 const currentUri = `${mocks.documentUri}/t3-composer-attachments/${fileName}`;
248 mocks.upload.mockImplementation(async (uri: string) => {
249 if (uri !== currentUri) {
250 throw new Error("File does not exist in the previous application container.");
251 }
252 return { status: 204, body: "", headers: {} };
253 });
254
255 const prepared = await prepareTurnAttachments({
256 environmentId,
257 attachments: [restoredFile],
258 });
259
260 expect(prepared.status).toBe("ready");
261 expect(mocks.upload).toHaveBeenCalledWith(
262 currentUri,
263 "https://environment.example/api/attachments/upload/signed",
264 expect.anything(),
265 );
266 });
267
268 it("adds uploaded file references to durable drafts without changing images", () => {
269 expect(
270 withUploadedMobileAttachmentReferences({
271 environmentId,
272 attachments: [file, image],
273 uploadedAttachments: [
274 {
275 type: "file",
276 id: "pending-existing-pdf",
277 name: file.name,
278 mimeType: file.mimeType,
279 sizeBytes: file.sizeBytes,
280 },
281 {
282 type: "image",
283 name: image.name,
284 mimeType: image.mimeType,
285 sizeBytes: image.sizeBytes,
286 dataUrl: image.dataUrl,
287 },
288 ],
289 }),
290 ).toEqual([
291 {
292 ...file,
293 uploadedAttachmentId: "pending-existing-pdf",
294 uploadEnvironmentId: environmentId,
295 },
296 image,
297 ]);
298 });
299
300 it("reuses a pending file upload from a previous outbox attempt", async () => {
301 const previouslyUploaded = {
302 ...file,
303 uploadedAttachmentId: "pending-existing-pdf",
304 uploadEnvironmentId: environmentId,
305 };
306
307 const prepared = await prepareTurnAttachments({
308 environmentId,
309 attachments: [previouslyUploaded, image],
310 });
311
312 expect(prepared.status).toBe("ready");
313 if (prepared.status !== "ready") return;
314 expect(prepared.attachments).toEqual([
315 {
316 type: "file",
317 id: "pending-existing-pdf",
318 name: "report.pdf",
319 mimeType: "application/pdf",
320 sizeBytes: 42,
321 },
322 {
323 type: "image",
324 name: "screenshot.png",
325 mimeType: "image/png",
326 sizeBytes: 3,
327 dataUrl: "data:image/png;base64,YWJj",
328 },
329 ]);
330 expect(prepared.pendingAttachmentIds).toEqual(["pending-existing-pdf"]);
331 expect(mocks.upload).not.toHaveBeenCalled();
332 expect(mocks.runAtomCommand).not.toHaveBeenCalled();
333 });
334
335 it("uploads a file again when its saved pending upload has expired", async () => {
336 mocks.executeAtomQuery.mockResolvedValueOnce({
337 _tag: "Failure",
338 error: { _tag: "AssetAttachmentNotFoundError" },
339 });
340 const previouslyUploaded = {
341 ...file,
342 uploadedAttachmentId: "pending-expired-pdf",
343 uploadEnvironmentId: environmentId,
344 };
345
346 const prepared = await prepareTurnAttachments({
347 environmentId,
348 attachments: [previouslyUploaded],
349 });
350
351 expect(mocks.upload).toHaveBeenCalledOnce();
352 expect(prepared.status).toBe("ready");
353 if (prepared.status !== "ready") return;
354 expect(prepared.pendingAttachmentIds).toEqual([MINTED_ID]);
355 });
356
357 it("removes pending uploads when the native HTTP request fails", async () => {
358 mocks.upload.mockResolvedValue({ status: 500, body: "failed", headers: {} });
359
360 await expect(prepareTurnAttachments({ environmentId, attachments: [file] })).rejects.toThrow(
361 "Upload failed for 'report.pdf' (500).",
362 );
363 expect(removeCallsFor(MINTED_ID)).toBe(1);
364 });
365
366 it("keeps a previously persisted upload when a later attachment fails", async () => {
367 const previouslyUploaded = {
368 ...file,
369 id: "file-existing",
370 uploadedAttachmentId: "pending-existing-pdf",
371 uploadEnvironmentId: environmentId,
372 };
373 mocks.upload.mockResolvedValue({ status: 500, body: "failed", headers: {} });
374
375 await expect(
376 prepareTurnAttachments({ environmentId, attachments: [previouslyUploaded, file] }),
377 ).rejects.toThrow("Upload failed for 'report.pdf' (500).");
378
379 expect(removeCallsFor("pending-existing-pdf")).toBe(0);
380 });
381
382 it("deletes the minted uploads when the owner abandons the send", async () => {
383 const result = await prepareTurnAttachments({
384 environmentId,
385 attachments: [file],
386 persistUploadedReferences: async () => "abandon",
387 });
388
389 expect(result.status).toBe("abandoned");
390 expect(removeCallsFor(MINTED_ID)).toBe(1);
391 });
392
393 it("deletes the minted uploads when persisting the references throws", async () => {
394 await expect(
395 prepareTurnAttachments({
396 environmentId,
397 attachments: [file],
398 persistUploadedReferences: async () => {
399 throw new Error("draft write failed");
400 },
401 }),
402 ).rejects.toThrow("draft write failed");
403
404 expect(removeCallsFor(MINTED_ID)).toBe(1);
405 });
406
407 it("skips persisting when every reference is already stored", async () => {
408 const previouslyUploaded = {
409 ...file,
410 uploadedAttachmentId: "pending-existing-pdf",
411 uploadEnvironmentId: environmentId,
412 };
413 const persist = vi.fn(async () => "persisted" as const);
414
415 const prepared = await prepareTurnAttachments({
416 environmentId,
417 attachments: [previouslyUploaded],
418 persistUploadedReferences: persist,
419 });
420
421 expect(prepared.status).toBe("ready");
422 expect(persist).not.toHaveBeenCalled();
423 });
424});
425
426describe("releasePendingAttachmentUploads", () => {
427 beforeEach(() => {
428 mocks.runAtomCommand.mockReset();
429 });
430
431 it("retries a failed delete once before reporting it", async () => {
432 mocks.runAtomCommand
433 .mockResolvedValueOnce({ _tag: "Failure", error: new Error("offline") })
434 .mockResolvedValue({ _tag: "Success", value: undefined });
435
436 await expect(
437 releasePendingAttachmentUploads(environmentId, ["pending-a"]),
438 ).resolves.toBeUndefined();
439 expect(mocks.runAtomCommand).toHaveBeenCalledTimes(2);
440 });
441
442 it("throws when a delete keeps failing so the caller sees the leak", async () => {
443 mocks.runAtomCommand.mockResolvedValue({ _tag: "Failure", error: new Error("offline") });
444
445 await expect(releasePendingAttachmentUploads(environmentId, ["pending-a"])).rejects.toThrow(
446 "pending-a",
447 );
448 });
449
450 it("treats an already-deleted pending upload as released", async () => {
451 mocks.runAtomCommand.mockResolvedValue({
452 _tag: "Failure",
453 error: { _tag: "AssetAttachmentNotFoundError" },
454 });
455
456 await expect(
457 releasePendingAttachmentUploads(environmentId, ["pending-a"]),
458 ).resolves.toBeUndefined();
459 expect(mocks.runAtomCommand).toHaveBeenCalledTimes(1);
460 });
461});