The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 21, 04:45 UTC
| 1 | import { EnvironmentId, PROVIDER_SEND_TURN_MAX_IMAGE_BYTES } from "@t3tools/contracts"; |
| 2 | import * as Option from "effect/Option"; |
| 3 | import { describe, expect, it } from "@effect/vitest"; |
| 4 | import { beforeEach, vi } from "vite-plus/test"; |
| 5 | |
| 6 | const mocks = vi.hoisted(() => ({ |
| 7 | canOperate: true, |
| 8 | documentUri: "file:///documents", |
| 9 | createAssetUrl: vi.fn(), |
| 10 | createUploadUrl: Symbol("create-upload-url"), |
| 11 | executeAtomQuery: vi.fn(), |
| 12 | removeUpload: Symbol("remove-upload"), |
| 13 | preparedConnection: Symbol("prepared-connection"), |
| 14 | runAtomCommand: vi.fn(), |
| 15 | readAtom: vi.fn(), |
| 16 | upload: vi.fn(), |
| 17 | writeFile: vi.fn(), |
| 18 | deleteFile: vi.fn(), |
| 19 | readBase64: vi.fn(), |
| 20 | // Verification and minting run as Effects; tests steer them with the settled results above. |
| 21 | settledEffect: ( |
| 22 | Effect: typeof import("effect/Effect"), |
| 23 | settle: () => Promise<{ |
| 24 | readonly _tag: string; |
| 25 | readonly value?: unknown; |
| 26 | readonly error?: object; |
| 27 | }>, |
| 28 | ) => |
| 29 | Effect.promise(settle).pipe( |
| 30 | Effect.flatMap((result) => |
| 31 | result._tag === "Success" ? Effect.succeed(result.value) : Effect.fail(result.error), |
| 32 | ), |
| 33 | ), |
| 34 | })); |
| 35 | |
| 36 | vi.mock("@t3tools/client-runtime/state/runtime", async () => { |
| 37 | const Effect = await import("effect/Effect"); |
| 38 | return { |
| 39 | createEnvironmentRpcCommand: () => Symbol("rpc-command"), |
| 40 | awaitAtomResult: (...args: ReadonlyArray<unknown>) => |
| 41 | mocks.settledEffect(Effect, () => mocks.executeAtomQuery(...args)), |
| 42 | runAtomCommand: mocks.runAtomCommand, |
| 43 | squashAtomCommandFailure: (result: { readonly error: unknown }) => result.error, |
| 44 | }; |
| 45 | }); |
| 46 | |
| 47 | vi.mock("../state/atom-registry", () => ({ |
| 48 | appAtomRegistry: { get: mocks.readAtom }, |
| 49 | })); |
| 50 | |
| 51 | vi.mock("./composerAttachmentPreviewRetention", () => ({ |
| 52 | retainComposerAttachmentFileForPreview: () => () => {}, |
| 53 | })); |
| 54 | |
| 55 | vi.mock("../state/assets", () => ({ |
| 56 | assetEnvironment: { createUrl: mocks.createAssetUrl }, |
| 57 | })); |
| 58 | |
| 59 | vi.mock("../state/attachments", async () => { |
| 60 | const Effect = await import("effect/Effect"); |
| 61 | return { |
| 62 | attachmentEnvironment: { |
| 63 | createUploadUrl: { |
| 64 | run: (registry: unknown, input: unknown) => |
| 65 | mocks.settledEffect(Effect, () => |
| 66 | mocks.runAtomCommand(registry, mocks.createUploadUrl, input), |
| 67 | ), |
| 68 | }, |
| 69 | remove: mocks.removeUpload, |
| 70 | }, |
| 71 | }; |
| 72 | }); |
| 73 | |
| 74 | vi.mock("../state/session", () => ({ |
| 75 | readEnvironmentScope: () => mocks.canOperate, |
| 76 | environmentSession: { |
| 77 | preparedConnectionValueAtom: () => mocks.preparedConnection, |
| 78 | }, |
| 79 | })); |
| 80 | |
| 81 | // Cuts the expo-crypto -> react-native import chain out of the test graph. |
| 82 | vi.mock("./uuid", () => ({ |
| 83 | uuidv4: () => "uuid", |
| 84 | randomHex: () => "0000", |
| 85 | })); |
| 86 | |
| 87 | vi.mock("expo-file-system", () => ({ |
| 88 | File: class { |
| 89 | readonly uri: string; |
| 90 | exists = true; |
| 91 | constructor(uri: string, name?: string) { |
| 92 | this.uri = name ? `${uri}/${name}` : uri; |
| 93 | } |
| 94 | create() {} |
| 95 | write(bytes: string, options: unknown) { |
| 96 | mocks.writeFile(this.uri, bytes, options); |
| 97 | } |
| 98 | delete() { |
| 99 | mocks.deleteFile(this.uri); |
| 100 | } |
| 101 | |
| 102 | async base64() { |
| 103 | return mocks.readBase64(this.uri); |
| 104 | } |
| 105 | |
| 106 | upload(url: string, options: unknown) { |
| 107 | return mocks.upload(this.uri, url, options); |
| 108 | } |
| 109 | }, |
| 110 | Paths: { |
| 111 | cache: "file:///cache", |
| 112 | get document() { |
| 113 | return { uri: mocks.documentUri }; |
| 114 | }, |
| 115 | }, |
| 116 | UploadType: { BINARY_CONTENT: 0 }, |
| 117 | })); |
| 118 | |
| 119 | import * as Effect from "effect/Effect"; |
| 120 | import * as Exit from "effect/Exit"; |
| 121 | import * as Fiber from "effect/Fiber"; |
| 122 | import { |
| 123 | prepareTurnAttachments as prepareWithUploads, |
| 124 | releasePendingAttachmentUploads, |
| 125 | uploadComposerAttachment, |
| 126 | withUploadedMobileAttachmentReferences, |
| 127 | } from "./attachmentUpload"; |
| 128 | |
| 129 | /** Uploads each attachment directly, as the shared registry does for one holder. */ |
| 130 | function prepare( |
| 131 | input: Omit<Parameters<typeof prepareWithUploads>[0], "uploadAttachment"> & { |
| 132 | readonly onUploadProgress?: (attachmentId: string, progress: number) => void; |
| 133 | }, |
| 134 | ) { |
| 135 | return prepareWithUploads({ |
| 136 | ...input, |
| 137 | uploadAttachment: (attachment) => |
| 138 | uploadComposerAttachment( |
| 139 | input.environmentId, |
| 140 | attachment, |
| 141 | input.onUploadProgress |
| 142 | ? (progress) => input.onUploadProgress?.(attachment.id, progress) |
| 143 | : undefined, |
| 144 | ), |
| 145 | }); |
| 146 | } |
| 147 | import type { DraftComposerAttachment } from "./composerImages"; |
| 148 | |
| 149 | const environmentId = EnvironmentId.make("environment-1"); |
| 150 | const MINTED_ID = "pending-00000000-0000-4000-8000-000000000001-pdf"; |
| 151 | |
| 152 | const image = { |
| 153 | id: "image-1", |
| 154 | type: "image", |
| 155 | name: "screenshot.png", |
| 156 | mimeType: "image/png", |
| 157 | sizeBytes: 3, |
| 158 | dataUrl: "data:image/png;base64,YWJj", |
| 159 | previewUri: "file:///images/screenshot.png", |
| 160 | } as const satisfies DraftComposerAttachment; |
| 161 | |
| 162 | const fileBackedImage = { |
| 163 | id: "image-2", |
| 164 | type: "image", |
| 165 | name: "photo.png", |
| 166 | mimeType: "image/png", |
| 167 | sizeBytes: 3, |
| 168 | fileUri: "file:///documents/t3-composer-attachments/photo.png", |
| 169 | previewUri: "file:///documents/t3-composer-attachments/photo.png", |
| 170 | } as const satisfies DraftComposerAttachment; |
| 171 | |
| 172 | const file = { |
| 173 | id: "file-1", |
| 174 | type: "file", |
| 175 | name: "report.pdf", |
| 176 | mimeType: "application/pdf", |
| 177 | sizeBytes: 42, |
| 178 | fileUri: "file:///documents/report.pdf", |
| 179 | } as const satisfies DraftComposerAttachment; |
| 180 | |
| 181 | const documentPickedImage = { |
| 182 | id: "file-2", |
| 183 | type: "file", |
| 184 | name: "photo.png", |
| 185 | mimeType: "application/octet-stream", |
| 186 | sizeBytes: 3, |
| 187 | fileUri: "file:///documents/photo.png", |
| 188 | } as const satisfies DraftComposerAttachment; |
| 189 | |
| 190 | function removeCallsFor(attachmentId: string): number { |
| 191 | return mocks.runAtomCommand.mock.calls.filter( |
| 192 | ([, command, target]) => |
| 193 | command === mocks.removeUpload && |
| 194 | (target as { input: { attachmentId: string } }).input.attachmentId === attachmentId, |
| 195 | ).length; |
| 196 | } |
| 197 | |
| 198 | describe("prepareTurnAttachments", () => { |
| 199 | beforeEach(() => { |
| 200 | mocks.canOperate = true; |
| 201 | mocks.documentUri = "file:///documents"; |
| 202 | mocks.createAssetUrl.mockReset(); |
| 203 | mocks.createAssetUrl.mockImplementation((target: unknown) => target); |
| 204 | mocks.executeAtomQuery.mockReset(); |
| 205 | mocks.executeAtomQuery.mockResolvedValue({ _tag: "Success", value: {} }); |
| 206 | mocks.runAtomCommand.mockReset(); |
| 207 | mocks.readAtom.mockReset(); |
| 208 | mocks.upload.mockReset(); |
| 209 | mocks.writeFile.mockReset(); |
| 210 | mocks.deleteFile.mockReset(); |
| 211 | mocks.readBase64.mockReset(); |
| 212 | mocks.readBase64.mockResolvedValue("YWJj"); |
| 213 | mocks.readAtom.mockReturnValue(Option.some({ httpBaseUrl: "https://environment.example/" })); |
| 214 | mocks.runAtomCommand.mockImplementation(async (_registry: unknown, command: unknown) => |
| 215 | command === mocks.createUploadUrl |
| 216 | ? { |
| 217 | _tag: "Success", |
| 218 | value: { |
| 219 | attachmentId: MINTED_ID, |
| 220 | relativeUrl: "/api/attachments/upload/signed", |
| 221 | expiresAt: 1, |
| 222 | }, |
| 223 | } |
| 224 | : { _tag: "Success", value: undefined }, |
| 225 | ); |
| 226 | mocks.upload.mockResolvedValue({ status: 204, body: "", headers: {} }); |
| 227 | }); |
| 228 | |
| 229 | it.effect("does not mint or transfer attachments without task operation access", () => |
| 230 | Effect.gen(function* () { |
| 231 | mocks.canOperate = false; |
| 232 | expect( |
| 233 | (yield* Effect.flip( |
| 234 | prepare({ |
| 235 | environmentId, |
| 236 | attachments: [fileBackedImage], |
| 237 | supportsImageUploads: true, |
| 238 | }), |
| 239 | )).message, |
| 240 | ).toContain("cannot upload attachments"); |
| 241 | expect(mocks.runAtomCommand).not.toHaveBeenCalled(); |
| 242 | expect(mocks.upload).not.toHaveBeenCalled(); |
| 243 | }), |
| 244 | ); |
| 245 | |
| 246 | it.effect("rechecks access after a signed URL is minted before sending any bytes", () => |
| 247 | Effect.gen(function* () { |
| 248 | mocks.runAtomCommand.mockImplementationOnce(async () => { |
| 249 | mocks.canOperate = false; |
| 250 | return { |
| 251 | _tag: "Success", |
| 252 | value: { |
| 253 | attachmentId: MINTED_ID, |
| 254 | relativeUrl: "/api/attachments/upload/signed", |
| 255 | expiresAt: 1, |
| 256 | }, |
| 257 | }; |
| 258 | }); |
| 259 | const warning = vi.spyOn(console, "warn").mockImplementation(() => {}); |
| 260 | try { |
| 261 | expect( |
| 262 | (yield* Effect.flip( |
| 263 | prepare({ |
| 264 | environmentId, |
| 265 | attachments: [fileBackedImage], |
| 266 | supportsImageUploads: true, |
| 267 | }), |
| 268 | )).message, |
| 269 | ).toContain("cannot upload attachments"); |
| 270 | expect(mocks.upload).not.toHaveBeenCalled(); |
| 271 | expect(mocks.runAtomCommand).toHaveBeenCalledTimes(1); |
| 272 | } finally { |
| 273 | warning.mockRestore(); |
| 274 | } |
| 275 | }), |
| 276 | ); |
| 277 | |
| 278 | it.effect("does not replace an expired upload when access was revoked during verification", () => |
| 279 | Effect.gen(function* () { |
| 280 | mocks.executeAtomQuery.mockImplementationOnce(async () => { |
| 281 | mocks.canOperate = false; |
| 282 | return { _tag: "Failure", error: { _tag: "AssetAttachmentNotFoundError" } }; |
| 283 | }); |
| 284 | expect( |
| 285 | (yield* Effect.flip( |
| 286 | prepare({ |
| 287 | environmentId, |
| 288 | attachments: [ |
| 289 | { |
| 290 | ...fileBackedImage, |
| 291 | uploadedAttachmentId: MINTED_ID, |
| 292 | uploadEnvironmentId: environmentId, |
| 293 | }, |
| 294 | ], |
| 295 | supportsImageUploads: true, |
| 296 | }), |
| 297 | )).message, |
| 298 | ).toContain("cannot upload attachments"); |
| 299 | expect(mocks.runAtomCommand).not.toHaveBeenCalled(); |
| 300 | expect(mocks.upload).not.toHaveBeenCalled(); |
| 301 | }), |
| 302 | ); |
| 303 | |
| 304 | it("rechecks deletion permission before retrying a failed cleanup", async () => { |
| 305 | mocks.runAtomCommand.mockImplementationOnce(async () => { |
| 306 | mocks.canOperate = false; |
| 307 | return { _tag: "Failure", error: new Error("Retry cleanup") }; |
| 308 | }); |
| 309 | await expect(releasePendingAttachmentUploads(environmentId, [MINTED_ID])).rejects.toThrow( |
| 310 | "cannot delete pending attachments", |
| 311 | ); |
| 312 | expect(mocks.runAtomCommand).toHaveBeenCalledTimes(1); |
| 313 | }); |
| 314 | |
| 315 | it.effect("inlines a file-backed image lazily when the server lacks image uploads", () => |
| 316 | Effect.gen(function* () { |
| 317 | const prepared = yield* prepare({ |
| 318 | environmentId, |
| 319 | attachments: [fileBackedImage], |
| 320 | }); |
| 321 | |
| 322 | expect(prepared.status).toBe("ready"); |
| 323 | if (prepared.status !== "ready") return; |
| 324 | expect(prepared.attachments).toEqual([ |
| 325 | { |
| 326 | type: "image", |
| 327 | name: "photo.png", |
| 328 | mimeType: "image/png", |
| 329 | sizeBytes: 3, |
| 330 | dataUrl: "data:image/png;base64,YWJj", |
| 331 | }, |
| 332 | ]); |
| 333 | expect(mocks.readBase64).toHaveBeenCalledExactlyOnceWith(fileBackedImage.fileUri); |
| 334 | expect(mocks.upload).not.toHaveBeenCalled(); |
| 335 | }), |
| 336 | ); |
| 337 | |
| 338 | // regression: #9713 read file-backed image drafts before enabling them |
| 339 | it.effect("reads restored images from the current iOS document container for legacy sends", () => |
| 340 | Effect.gen(function* () { |
| 341 | const fileName = "33333333-3333-4333-8333-333333333333-photo.png"; |
| 342 | mocks.documentUri = |
| 343 | "file:///var/mobile/Containers/Data/Application/22222222-2222-4222-8222-222222222222/Documents"; |
| 344 | const oldUri = `file:///var/mobile/Containers/Data/Application/11111111-1111-4111-8111-111111111111/Documents/t3-composer-attachments/${fileName}`; |
| 345 | const prepared = yield* prepare({ |
| 346 | environmentId, |
| 347 | attachments: [{ ...fileBackedImage, fileUri: oldUri, previewUri: oldUri }], |
| 348 | }); |
| 349 | expect(prepared.status).toBe("ready"); |
| 350 | expect(mocks.readBase64).toHaveBeenCalledExactlyOnceWith( |
| 351 | `${mocks.documentUri}/t3-composer-attachments/${fileName}`, |
| 352 | ); |
| 353 | }), |
| 354 | ); |
| 355 | |
| 356 | // regression: #9713 read file-backed image drafts before enabling them |
| 357 | it.effect("rejects a legacy image without inline bytes or a file", () => |
| 358 | Effect.gen(function* () { |
| 359 | const { fileUri: _, ...missingImage } = fileBackedImage; |
| 360 | expect( |
| 361 | (yield* Effect.flip(prepare({ environmentId, attachments: [missingImage] }))).message, |
| 362 | ).toContain("'photo.png' is no longer available. Attach the image again."); |
| 363 | }), |
| 364 | ); |
| 365 | |
| 366 | it.effect.each(["resolve", "reject"] as const)( |
| 367 | "abandons a canceled legacy image read that later %ss", |
| 368 | (outcome) => |
| 369 | Effect.gen(function* () { |
| 370 | const readStarted = Promise.withResolvers<void>(); |
| 371 | const read = Promise.withResolvers<string>(); |
| 372 | mocks.readBase64.mockImplementation(() => { |
| 373 | readStarted.resolve(); |
| 374 | return read.promise; |
| 375 | }); |
| 376 | const preparing = yield* Effect.forkChild( |
| 377 | prepare({ environmentId, attachments: [fileBackedImage] }), |
| 378 | ); |
| 379 | yield* Effect.promise(() => readStarted.promise); |
| 380 | yield* Fiber.interrupt(preparing); |
| 381 | if (outcome === "resolve") read.resolve("YWJj"); |
| 382 | else read.reject(new Error("Native read failed after cancellation")); |
| 383 | |
| 384 | expect(Exit.hasInterrupts(yield* Fiber.await(preparing))).toBe(true); |
| 385 | }), |
| 386 | ); |
| 387 | |
| 388 | // regression: #9713 read file-backed image drafts before enabling them |
| 389 | it.effect("uploads a file-backed image from its owned copy without staging base64", () => |
| 390 | Effect.gen(function* () { |
| 391 | mocks.upload.mockImplementation( |
| 392 | async ( |
| 393 | _uri: string, |
| 394 | _url: string, |
| 395 | options: { onProgress?: (event: { bytesSent: unknown; totalBytes: unknown }) => void }, |
| 396 | ) => { |
| 397 | // expo-modules-jsi delivers native Int64 progress counts as BigInt. |
| 398 | options.onProgress?.({ bytesSent: BigInt(1), totalBytes: BigInt(4) }); |
| 399 | return { status: 204, body: "", headers: {} }; |
| 400 | }, |
| 401 | ); |
| 402 | const progress: Array<number> = []; |
| 403 | const prepared = yield* prepare({ |
| 404 | environmentId, |
| 405 | attachments: [fileBackedImage], |
| 406 | supportsImageUploads: true, |
| 407 | onUploadProgress: (_, value) => progress.push(value), |
| 408 | }); |
| 409 | |
| 410 | expect(progress).toEqual([0.25]); |
| 411 | |
| 412 | expect(mocks.upload).toHaveBeenCalledWith( |
| 413 | fileBackedImage.fileUri, |
| 414 | "https://environment.example/api/attachments/upload/signed", |
| 415 | expect.objectContaining({ headers: { "Content-Type": "image/png" } }), |
| 416 | ); |
| 417 | expect(mocks.readBase64).not.toHaveBeenCalled(); |
| 418 | expect(mocks.writeFile).not.toHaveBeenCalled(); |
| 419 | expect(mocks.deleteFile).not.toHaveBeenCalled(); |
| 420 | expect(prepared.status).toBe("ready"); |
| 421 | if (prepared.status !== "ready") return; |
| 422 | expect(prepared.attachments).toEqual([ |
| 423 | { |
| 424 | type: "image", |
| 425 | id: MINTED_ID, |
| 426 | name: "photo.png", |
| 427 | mimeType: "image/png", |
| 428 | sizeBytes: 3, |
| 429 | }, |
| 430 | ]); |
| 431 | }), |
| 432 | ); |
| 433 | |
| 434 | it.effect("sends a document-picked picture with the mime it was uploaded under", () => |
| 435 | Effect.gen(function* () { |
| 436 | const prepared = yield* prepare({ |
| 437 | environmentId, |
| 438 | attachments: [documentPickedImage], |
| 439 | }); |
| 440 | |
| 441 | expect(mocks.upload).toHaveBeenCalledWith( |
| 442 | "file:///documents/photo.png", |
| 443 | "https://environment.example/api/attachments/upload/signed", |
| 444 | expect.objectContaining({ headers: { "Content-Type": "image/png" } }), |
| 445 | ); |
| 446 | expect(prepared.status).toBe("ready"); |
| 447 | if (prepared.status !== "ready") return; |
| 448 | expect(prepared.attachments[0]).toEqual({ |
| 449 | type: "image", |
| 450 | id: MINTED_ID, |
| 451 | name: "photo.png", |
| 452 | mimeType: "image/png", |
| 453 | sizeBytes: 3, |
| 454 | }); |
| 455 | }), |
| 456 | ); |
| 457 | |
| 458 | it.effect("uploads an oversized document-picked image as a file", () => |
| 459 | Effect.gen(function* () { |
| 460 | const largeImage = { |
| 461 | ...documentPickedImage, |
| 462 | mimeType: "image/png", |
| 463 | sizeBytes: PROVIDER_SEND_TURN_MAX_IMAGE_BYTES + 1, |
| 464 | }; |
| 465 | const prepared = yield* prepare({ environmentId, attachments: [largeImage] }); |
| 466 | |
| 467 | expect(mocks.runAtomCommand).toHaveBeenCalledWith( |
| 468 | expect.anything(), |
| 469 | mocks.createUploadUrl, |
| 470 | expect.objectContaining({ |
| 471 | input: { |
| 472 | type: "file", |
| 473 | name: largeImage.name, |
| 474 | mimeType: "image/png", |
| 475 | sizeBytes: largeImage.sizeBytes, |
| 476 | }, |
| 477 | }), |
| 478 | ); |
| 479 | expect(prepared.status).toBe("ready"); |
| 480 | if (prepared.status !== "ready") return; |
| 481 | expect(prepared.attachments).toEqual([ |
| 482 | { |
| 483 | type: "file", |
| 484 | id: MINTED_ID, |
| 485 | name: largeImage.name, |
| 486 | mimeType: "image/png", |
| 487 | sizeBytes: largeImage.sizeBytes, |
| 488 | }, |
| 489 | ]); |
| 490 | expect(mocks.readBase64).not.toHaveBeenCalled(); |
| 491 | }), |
| 492 | ); |
| 493 | |
| 494 | it.effect("uploads generic file bytes directly and keeps mixed attachment order", () => |
| 495 | Effect.gen(function* () { |
| 496 | const pastedFile = { |
| 497 | ...file, |
| 498 | source: { _tag: "pasted-text" as const }, |
| 499 | }; |
| 500 | const prepared = yield* prepare({ |
| 501 | environmentId, |
| 502 | attachments: [pastedFile, image], |
| 503 | }); |
| 504 | |
| 505 | expect(mocks.upload).toHaveBeenCalledWith( |
| 506 | "file:///documents/report.pdf", |
| 507 | "https://environment.example/api/attachments/upload/signed", |
| 508 | expect.objectContaining({ |
| 509 | httpMethod: "POST", |
| 510 | uploadType: 0, |
| 511 | headers: { "Content-Type": "application/pdf" }, |
| 512 | }), |
| 513 | ); |
| 514 | expect(prepared.status).toBe("ready"); |
| 515 | if (prepared.status !== "ready") return; |
| 516 | expect(prepared.attachments[0]).toEqual({ |
| 517 | type: "file", |
| 518 | id: MINTED_ID, |
| 519 | name: "report.pdf", |
| 520 | mimeType: "application/pdf", |
| 521 | sizeBytes: 42, |
| 522 | source: { _tag: "pasted-text" }, |
| 523 | }); |
| 524 | expect(prepared.attachments[1]?.type).toBe("image"); |
| 525 | expect(prepared.pendingAttachmentIds).toEqual([MINTED_ID]); |
| 526 | expect(prepared.draftAttachments[0]).toEqual({ |
| 527 | ...pastedFile, |
| 528 | uploadedAttachmentId: MINTED_ID, |
| 529 | uploadEnvironmentId: environmentId, |
| 530 | }); |
| 531 | }), |
| 532 | ); |
| 533 | |
| 534 | it.effect("uses the current connection when an environment reconnects during URL creation", () => |
| 535 | Effect.gen(function* () { |
| 536 | mocks.readAtom |
| 537 | .mockReturnValueOnce(Option.some({ httpBaseUrl: "https://old-environment.example/" })) |
| 538 | .mockReturnValueOnce(Option.some({ httpBaseUrl: "https://new-environment.example/" })); |
| 539 | |
| 540 | yield* prepare({ environmentId, attachments: [file] }); |
| 541 | |
| 542 | expect(mocks.upload).toHaveBeenCalledWith( |
| 543 | file.fileUri, |
| 544 | "https://new-environment.example/api/attachments/upload/signed", |
| 545 | expect.anything(), |
| 546 | ); |
| 547 | }), |
| 548 | ); |
| 549 | |
| 550 | it.effect("uploads a restored draft file from the current iOS document container", () => |
| 551 | Effect.gen(function* () { |
| 552 | const fileName = "33333333-3333-4333-8333-333333333333-report%20%23.pdf"; |
| 553 | const restoredFile = { |
| 554 | ...file, |
| 555 | fileUri: `file:///private/var/mobile/Containers/Data/Application/11111111-1111-4111-8111-111111111111/Documents/t3-composer-attachments/${fileName}`, |
| 556 | }; |
| 557 | mocks.documentUri = |
| 558 | "file:///var/mobile/Containers/Data/Application/22222222-2222-4222-8222-222222222222/Documents"; |
| 559 | const currentUri = `${mocks.documentUri}/t3-composer-attachments/${fileName}`; |
| 560 | mocks.upload.mockImplementation(async (uri: string) => { |
| 561 | if (uri !== currentUri) { |
| 562 | throw new Error("File does not exist in the previous application container."); |
| 563 | } |
| 564 | return { status: 204, body: "", headers: {} }; |
| 565 | }); |
| 566 | |
| 567 | const prepared = yield* prepare({ |
| 568 | environmentId, |
| 569 | attachments: [restoredFile], |
| 570 | }); |
| 571 | |
| 572 | expect(prepared.status).toBe("ready"); |
| 573 | expect(mocks.upload).toHaveBeenCalledWith( |
| 574 | currentUri, |
| 575 | "https://environment.example/api/attachments/upload/signed", |
| 576 | expect.anything(), |
| 577 | ); |
| 578 | }), |
| 579 | ); |
| 580 | |
| 581 | it("adds uploaded file references to durable drafts without changing images", () => { |
| 582 | expect( |
| 583 | withUploadedMobileAttachmentReferences({ |
| 584 | environmentId, |
| 585 | attachments: [file, image], |
| 586 | uploadedAttachments: [ |
| 587 | { |
| 588 | type: "file", |
| 589 | id: "pending-existing-pdf", |
| 590 | name: file.name, |
| 591 | mimeType: file.mimeType, |
| 592 | sizeBytes: file.sizeBytes, |
| 593 | }, |
| 594 | { |
| 595 | type: "image", |
| 596 | name: image.name, |
| 597 | mimeType: image.mimeType, |
| 598 | sizeBytes: image.sizeBytes, |
| 599 | dataUrl: image.dataUrl, |
| 600 | }, |
| 601 | ], |
| 602 | }), |
| 603 | ).toEqual([ |
| 604 | { |
| 605 | ...file, |
| 606 | uploadedAttachmentId: "pending-existing-pdf", |
| 607 | uploadEnvironmentId: environmentId, |
| 608 | }, |
| 609 | image, |
| 610 | ]); |
| 611 | }); |
| 612 | |
| 613 | it.effect("reuses a pending file upload from a previous outbox attempt", () => |
| 614 | Effect.gen(function* () { |
| 615 | const previouslyUploaded = { |
| 616 | ...file, |
| 617 | uploadedAttachmentId: "pending-existing-pdf", |
| 618 | uploadEnvironmentId: environmentId, |
| 619 | }; |
| 620 | |
| 621 | const prepared = yield* prepare({ |
| 622 | environmentId, |
| 623 | attachments: [previouslyUploaded, image], |
| 624 | }); |
| 625 | |
| 626 | expect(prepared.status).toBe("ready"); |
| 627 | if (prepared.status !== "ready") return; |
| 628 | expect(prepared.attachments).toEqual([ |
| 629 | { |
| 630 | type: "file", |
| 631 | id: "pending-existing-pdf", |
| 632 | name: "report.pdf", |
| 633 | mimeType: "application/pdf", |
| 634 | sizeBytes: 42, |
| 635 | }, |
| 636 | { |
| 637 | type: "image", |
| 638 | name: "screenshot.png", |
| 639 | mimeType: "image/png", |
| 640 | sizeBytes: 3, |
| 641 | dataUrl: "data:image/png;base64,YWJj", |
| 642 | }, |
| 643 | ]); |
| 644 | expect(prepared.pendingAttachmentIds).toEqual(["pending-existing-pdf"]); |
| 645 | expect(mocks.upload).not.toHaveBeenCalled(); |
| 646 | expect(mocks.runAtomCommand).not.toHaveBeenCalled(); |
| 647 | }), |
| 648 | ); |
| 649 | |
| 650 | it.effect("uploads a file again when its saved pending upload has expired", () => |
| 651 | Effect.gen(function* () { |
| 652 | mocks.executeAtomQuery.mockResolvedValueOnce({ |
| 653 | _tag: "Failure", |
| 654 | error: { _tag: "AssetAttachmentNotFoundError" }, |
| 655 | }); |
| 656 | const previouslyUploaded = { |
| 657 | ...file, |
| 658 | uploadedAttachmentId: "pending-expired-pdf", |
| 659 | uploadEnvironmentId: environmentId, |
| 660 | }; |
| 661 | |
| 662 | const prepared = yield* prepare({ |
| 663 | environmentId, |
| 664 | attachments: [previouslyUploaded], |
| 665 | }); |
| 666 | |
| 667 | expect(mocks.upload).toHaveBeenCalledOnce(); |
| 668 | expect(prepared.status).toBe("ready"); |
| 669 | if (prepared.status !== "ready") return; |
| 670 | expect(prepared.pendingAttachmentIds).toEqual([MINTED_ID]); |
| 671 | }), |
| 672 | ); |
| 673 | |
| 674 | it.effect("uploads image bytes over HTTP while retaining the durable offline image", () => |
| 675 | Effect.gen(function* () { |
| 676 | const persisted = vi.fn(() => Effect.succeed("persisted" as const)); |
| 677 | const prepared = yield* prepare({ |
| 678 | environmentId, |
| 679 | attachments: [image], |
| 680 | supportsImageUploads: true, |
| 681 | persistUploadedReferences: persisted, |
| 682 | }); |
| 683 | expect(mocks.writeFile).toHaveBeenCalledWith("file:///cache/t3-upload-uuid", "YWJj", { |
| 684 | encoding: "base64", |
| 685 | }); |
| 686 | expect(mocks.upload).toHaveBeenCalledWith( |
| 687 | "file:///cache/t3-upload-uuid", |
| 688 | "https://environment.example/api/attachments/upload/signed", |
| 689 | expect.objectContaining({ headers: { "Content-Type": "image/png" } }), |
| 690 | ); |
| 691 | expect(mocks.deleteFile).toHaveBeenCalledExactlyOnceWith("file:///cache/t3-upload-uuid"); |
| 692 | expect(prepared.status).toBe("ready"); |
| 693 | if (prepared.status !== "ready") return; |
| 694 | expect(prepared.attachments).toEqual([ |
| 695 | { |
| 696 | type: "image", |
| 697 | id: MINTED_ID, |
| 698 | name: image.name, |
| 699 | mimeType: image.mimeType, |
| 700 | sizeBytes: image.sizeBytes, |
| 701 | }, |
| 702 | ]); |
| 703 | expect(prepared.draftAttachments).toEqual([ |
| 704 | { ...image, uploadedAttachmentId: MINTED_ID, uploadEnvironmentId: environmentId }, |
| 705 | ]); |
| 706 | expect(persisted).toHaveBeenCalledWith(prepared.draftAttachments); |
| 707 | }), |
| 708 | ); |
| 709 | |
| 710 | it.effect("reuses an uploaded image and reuploads its local bytes after server expiry", () => |
| 711 | Effect.gen(function* () { |
| 712 | const saved = { |
| 713 | ...image, |
| 714 | uploadedAttachmentId: "saved-image", |
| 715 | uploadEnvironmentId: environmentId, |
| 716 | }; |
| 717 | const reused = yield* prepare({ |
| 718 | environmentId, |
| 719 | attachments: [saved], |
| 720 | supportsImageUploads: true, |
| 721 | }); |
| 722 | expect(reused.status === "ready" && reused.attachments[0]).toEqual({ |
| 723 | type: "image", |
| 724 | id: "saved-image", |
| 725 | name: image.name, |
| 726 | mimeType: image.mimeType, |
| 727 | sizeBytes: image.sizeBytes, |
| 728 | }); |
| 729 | expect(mocks.upload).not.toHaveBeenCalled(); |
| 730 | mocks.executeAtomQuery.mockResolvedValueOnce({ |
| 731 | _tag: "Failure", |
| 732 | error: { _tag: "AssetAttachmentNotFoundError" }, |
| 733 | }); |
| 734 | const restored = yield* prepare({ |
| 735 | environmentId, |
| 736 | attachments: [saved], |
| 737 | supportsImageUploads: true, |
| 738 | }); |
| 739 | expect(restored.status === "ready" && restored.draftAttachments[0]).toEqual({ |
| 740 | ...saved, |
| 741 | uploadedAttachmentId: MINTED_ID, |
| 742 | }); |
| 743 | expect(mocks.writeFile).toHaveBeenCalledWith("file:///cache/t3-upload-uuid", "YWJj", { |
| 744 | encoding: "base64", |
| 745 | }); |
| 746 | }), |
| 747 | ); |
| 748 | |
| 749 | it.effect("does not reuse an image upload from another environment", () => |
| 750 | Effect.gen(function* () { |
| 751 | const prepared = yield* prepare({ |
| 752 | environmentId, |
| 753 | attachments: [ |
| 754 | { |
| 755 | ...image, |
| 756 | uploadedAttachmentId: "other-image", |
| 757 | uploadEnvironmentId: EnvironmentId.make("other"), |
| 758 | }, |
| 759 | ], |
| 760 | supportsImageUploads: true, |
| 761 | }); |
| 762 | expect(mocks.executeAtomQuery).not.toHaveBeenCalled(); |
| 763 | expect(mocks.upload).toHaveBeenCalledOnce(); |
| 764 | expect(prepared.status === "ready" && prepared.draftAttachments[0]?.uploadEnvironmentId).toBe( |
| 765 | environmentId, |
| 766 | ); |
| 767 | }), |
| 768 | ); |
| 769 | |
| 770 | it.effect( |
| 771 | "aborts an active transfer without dropping local bytes or stamping a partial upload", |
| 772 | () => |
| 773 | Effect.gen(function* () { |
| 774 | const started = Promise.withResolvers<void>(); |
| 775 | const persist = vi.fn(() => Effect.succeed("persisted" as const)); |
| 776 | mocks.upload.mockImplementation( |
| 777 | (_uri: string, _url: string, options: { signal: AbortSignal }) => |
| 778 | new Promise((_, reject) => { |
| 779 | options.signal.addEventListener("abort", () => reject(new Error("cancelled")), { |
| 780 | once: true, |
| 781 | }); |
| 782 | started.resolve(); |
| 783 | }), |
| 784 | ); |
| 785 | const preparing = yield* Effect.forkChild( |
| 786 | prepare({ environmentId, attachments: [file], persistUploadedReferences: persist }), |
| 787 | ); |
| 788 | yield* Effect.promise(() => started.promise); |
| 789 | yield* Fiber.interrupt(preparing); |
| 790 | expect(Exit.hasInterrupts(yield* Fiber.await(preparing))).toBe(true); |
| 791 | expect(persist).not.toHaveBeenCalled(); |
| 792 | expect(mocks.deleteFile).not.toHaveBeenCalled(); |
| 793 | expect(removeCallsFor(MINTED_ID)).toBe(1); |
| 794 | }), |
| 795 | ); |
| 796 | |
| 797 | it.effect("removes pending uploads when the native HTTP request fails", () => |
| 798 | Effect.gen(function* () { |
| 799 | mocks.upload.mockResolvedValue({ status: 500, body: "failed", headers: {} }); |
| 800 | |
| 801 | expect( |
| 802 | (yield* Effect.flip(prepare({ environmentId, attachments: [file] }))).message, |
| 803 | ).toContain("Upload failed for 'report.pdf' (500)."); |
| 804 | expect(removeCallsFor(MINTED_ID)).toBe(1); |
| 805 | }), |
| 806 | ); |
| 807 | |
| 808 | it.effect("keeps a previously persisted upload when a later attachment fails", () => |
| 809 | Effect.gen(function* () { |
| 810 | const previouslyUploaded = { |
| 811 | ...file, |
| 812 | id: "file-existing", |
| 813 | uploadedAttachmentId: "pending-existing-pdf", |
| 814 | uploadEnvironmentId: environmentId, |
| 815 | }; |
| 816 | mocks.upload.mockResolvedValue({ status: 500, body: "failed", headers: {} }); |
| 817 | |
| 818 | expect( |
| 819 | (yield* Effect.flip(prepare({ environmentId, attachments: [previouslyUploaded, file] }))) |
| 820 | .message, |
| 821 | ).toContain("Upload failed for 'report.pdf' (500)."); |
| 822 | |
| 823 | expect(removeCallsFor("pending-existing-pdf")).toBe(0); |
| 824 | }), |
| 825 | ); |
| 826 | }); |
| 827 | |
| 828 | describe("releasePendingAttachmentUploads", () => { |
| 829 | beforeEach(() => { |
| 830 | mocks.runAtomCommand.mockReset(); |
| 831 | }); |
| 832 | |
| 833 | it("throws when a delete keeps failing so the caller sees the leak", async () => { |
| 834 | mocks.runAtomCommand.mockResolvedValue({ _tag: "Failure", error: new Error("offline") }); |
| 835 | |
| 836 | await expect(releasePendingAttachmentUploads(environmentId, ["pending-a"])).rejects.toThrow( |
| 837 | "pending-a", |
| 838 | ); |
| 839 | }); |
| 840 | |
| 841 | it("treats an already-deleted pending upload as released", async () => { |
| 842 | mocks.runAtomCommand.mockResolvedValue({ |
| 843 | _tag: "Failure", |
| 844 | error: { _tag: "AssetAttachmentNotFoundError" }, |
| 845 | }); |
| 846 | |
| 847 | await expect( |
| 848 | releasePendingAttachmentUploads(environmentId, ["pending-a"]), |
| 849 | ).resolves.toBeUndefined(); |
| 850 | expect(mocks.runAtomCommand).toHaveBeenCalledTimes(1); |
| 851 | }); |
| 852 | }); |