App icon indicating copy to clipboard operation
App copied to clipboard

[$175] Converted and edited images are not kept, so the app stores and uploads the original file

Open mountiny opened this issue 2 weeks ago • 11 comments

Part of https://github.com/Expensify/App/issues/106153 (receipt retention). Found by @adhorodyski.

Problem

The app converts HEIC and RAW (DNG) photos, resizes images, and crops receipts. Then it stores and uploads the original file, not the converted or edited one.

This can be related to other HEIC receipt problems.

Impact

  • Severity: P2
  • Not counted yet, because nothing logs it.

Code

Expected behavior

The app stores and uploads the converted, resized, or cropped file.

Issue OwnerCurrent Issue Owner: @rinej
Upwork Automation - Do Not Edit

mountiny avatar Nov 16 '26 04:11 mountiny

Triggered auto assignment to Contributor-plus team member for initial proposal review - @rojiphil (External)

Job added to Upwork: https://www.upwork.com/jobs/~022122192805540128965

Issue Analysis

⚠️ Preliminary analysis — the reported original-file upload is not yet confirmed. The cited revision forwards successfully processed files rather than discarding them.

Findings

  • Conversion: HEIC conversion creates a new File containing JPEG bytes, and validation forwards that replacement.
  • Cropping: The cited helper returns croppedImage and its matching URI—not the original file.
  • Resizing: A separate, confirmed threshold mismatch can leave an image unchanged: receipt validation uses 10 MiB, but the resize helper skips images ≤24 MiB. This is a skipped transformation, not a successful transformation being discarded.
Code evidence

Separate retention risk

Some native scan paths save the processed URI without adopting the replacement into durable storage. That could explain a processed image disappearing after cache eviction, but not uploading the original instead. Other paths explicitly adopt the final output, so this is not universal.

Retention evidence

buildReceiptFiles:61–74 saves the processed source without adoption. setMoneyRequestReceipt:489–514 calls retain, which is a native no-op:263–275.

What is needed to confirm this issue

Obtain one affected flow, app revision, and sample comparing the successfully processed output with the uploaded bytes or dimensions. Regression coverage should inspect actual file content—not just filenames or preview URIs.

This was source-only investigation; no browser reproduction or production-log confirmation was performed. The broader Receipt retention bug remains related context, not proof of this mechanism.


Next Steps: Reply with @MelvinBot <your feedback> and an affected flow or reproduction to refine this analysis.


view run

MelvinBot avatar Nov 16 '26 04:11 MelvinBot

Proposal

What is the root cause of that problem?

When a receipt image is over the receipt limit, useFilesValidation.tsx sends it to resizeImageIfNeeded (the filesToResize branch, and convertedFilesToResize for HEIC/DNG output above RECEIPT_MAX_SIZE). But resizeImageIfNeeded in src/libs/fileDownload/FileUtils.ts:737 returns the file untouched when size <= CONST.API_ATTACHMENT_VALIDATIONS.MAX_SIZE (the attachment limit, 24 MiB), not RECEIPT_MAX_SIZE (10 MiB). So any receipt image between 10 and 24 MiB, including a freshly converted HEIC/DNG JPEG, goes through the "resize" step, comes back identical, and is stored and uploaded as the large original. The helper's threshold does not know it is validating a receipt. Nothing is logged, so it looks like an edit that was thrown away.

What changes do you think we should make in order to solve the problem?

  1. Give resizeImageIfNeeded(file, maxSize = CONST.API_ATTACHMENT_VALIDATIONS.MAX_SIZE) a size parameter and use it in the early return at FileUtils.ts:737.
  2. In useFilesValidation.tsx, pass validationState.isValidatingReceipts ? RECEIPT_MAX_SIZE : MAX_SIZE in the filesToResize.map(...) call. It is the only production caller, so the default keeps everything else unchanged.
  3. Add a Log.info when a resize returns a file with the same size as its input, so this case is counted from now on.

Test (tests/unit/FileUtilsTest.ts): with a 12 MiB image file, resizeImageIfNeeded(file, RECEIPT_MAX_SIZE) must call the image manipulator and return a different file object. Assert on the returned file's size and uri, not on the name. Add the same case to tests/unit/hooks/useFilesValidation.test.ts with isValidatingReceipts: true, and check that onFilesValidated receives the resized file.

What alternative solutions did you explore? (Optional)

MelvinBot's analysis found the same 10 MiB vs 24 MiB mismatch but called the report unconfirmed and stopped at analysis. I propose the concrete parameter change plus the test that would have caught it. I also looked at the HEIC converter and cropImageToAspectRatio, which do return the new file. The separate native retention path (ReceiptStorage retain being a no-op) is a different bug (#106153) and is left out of this fix.

Stephen3453 avatar Nov 16 '26 05:11 Stephen3453

Proposal

Please re-state the problem that we are trying to solve in this issue.

The app converts HEIC and RAW (DNG) photos to JPEG, resizes oversized images, and crops receipts. However, during receipt storage and upload, the app uploads the original, unedited file rather than the converted, resized, or cropped version.

What is the root cause of that problem?

There are two interacting points where converted/edited files are discarded in favor of original files:

  1. ReceiptStorage.adopt runs before validation on native (src/components/AttachmentPicker/index.native.tsx:133-143):

    • When picking an image from the gallery, AttachmentPicker immediately calls ReceiptStorage.adopt(file.uri, file.name), which copies the original file (e.g. .heic or full-size photo) into the durable receipts/ directory and returns a durable URI pointing to that original file.
    • Subsequently, useFilesValidation.tsx:309-340 calls convertHeicImage (producing a converted JPEG convertedFile) and useFilesValidation.tsx:349-369 calls resizeImageIfNeeded (producing a resized value).
    • However, these converted and resized files are never adopted into ReceiptStorage to overwrite the original durable file.
    • When Receipt.ts subsequently reads the receipt for upload via ReceiptStorage.resolve(receiptPath) (src/libs/actions/IOU/Receipt.ts:518), it resolves the durable path in the receipts folder, which still points to the un-converted, un-resized original file.
  2. Cropped images are not adopted or replaced in persistent receipt storage (src/pages/iou/request/step/IOURequestStepScan/cropImageToAspectRatio.ts:71-78):

    • cropImageToAspectRatio creates a temporary cropped image via cropOrRotateImage, but callers that persist or upload the receipt do not adopt or overwrite the durable receipt storage with the cropped output file, causing the app to read and upload the uncropped original.

What changes do you think we should make in order to solve the problem?

  1. Adopt converted and resized files into ReceiptStorage in useFilesValidation / validation handlers:

    • In src/hooks/useFilesValidation.tsx (and AttachmentPicker / buildReceiptFiles): When convertHeicImage or resizeImageIfNeeded outputs a new convertedFile / resizedFile, adopt the new file into ReceiptStorage (using ReceiptStorage.adopt or ReceiptStorage.overwrite) and update the file's uri, source, and name to reference the adopted converted/resized artifact.
    • On native, replace the old adopted original file with the converted JPEG so ReceiptStorage.resolve(receiptPath) serves the converted JPEG to readReceiptFile.
  2. Adopt cropped images into ReceiptStorage in cropImageToAspectRatio:

    • In src/pages/iou/request/step/IOURequestStepScan/cropImageToAspectRatio.ts: When cropOrRotateImage resolves with croppedImage, adopt the cropped image into ReceiptStorage so that the cropped file becomes the persistent local file used for preview and upload.
  3. Ensure onFilesValidated passes the validated/converted files consistently:

    • Ensure onFilesValidated(sortedFiles) in useFilesValidation.tsx:397 passes the converted/resized files and that consumers (ScanFromReport.tsx, IOURequestStepConfirmation, buildReceiptFiles.ts) use the converted FileObject rather than referencing raw unvalidated DataTransferItemList data.

What alternative solutions did you explore? (Optional)

  • Converting files only at upload time: Rejected because it would cause high memory spikes during background upload and leaves the preview UI rendering unconverted HEIC/DNG formats that may not render consistently across all native platforms.

What specific scenarios should we cover in automated tests to prevent reoccurrence?

In tests/unit/useFilesValidationTest.tsx and tests/unit/cropImageToAspectRatioTest.ts:

  1. HEIC/DNG conversion persistence:
    • Provide a mock HEIC file to useFilesValidation.
    • Verify that convertHeicImage produces a JPEG convertedFile.
    • Verify that onFilesValidated receives the converted JPEG file with .jpeg extension and updated URI, and that ReceiptStorage.adopt is called for the converted file.
  2. Resized image persistence:
    • Provide a file exceeding RECEIPT_MAX_SIZE.
    • Verify that resizeImageIfNeeded runs and the resulting resized FileObject is preserved in the validated output.
  3. Cropped image persistence:
    • Call cropImageToAspectRatio with an image object.
    • Verify that the returned ImageObject points to the cropped file and durable URI.

Contributor details

  • Email: [email protected]
  • Upwork Profile: https://www.upwork.com/freelancers/~0131dae36abcf59374

kevinjosh10 avatar Nov 16 '26 05:11 kevinjosh10

Contributor details Your Expensify account email: [email protected] Upwork Profile Link: https://www.upwork.com/freelancers/~013b564a690d9bcdab

Proposal

Problem

Receipt images that the app converts or resizes are not the images that end up stored and uploaded. Oversize receipts pass through the resize step unchanged, and converted files live at temporary paths that can disappear before the upload runs - so the stored receipt is the unprocessed original, or nothing durable at all.

Root cause

Two verified defects, and one claim in the issue that does not survive checking:

  1. The resize step uses the wrong limit for receipts. useFilesValidation (src/hooks/useFilesValidation.tsx:311) routes a HEIC-converted file into the resize list when it exceeds CONST.API_ATTACHMENT_VALIDATIONS.RECEIPT_MAX_SIZE (10 MiB, src/CONST/index.ts:474). But resizeImageIfNeeded (src/libs/fileDownload/FileUtils.ts:736-743) returns the file untouched whenever its size is at or below CONST.API_ATTACHMENT_VALIDATIONS.MAX_SIZE (24 MiB, src/CONST/index.ts:471) - the general attachment limit. A converted receipt between 10 and 24 MiB is therefore sent to resize and comes back identical: never resized to the receipt limit, never rejected. Both constants are server limits (per their CONST comments); the defect is purely that the receipt flow resizes against the wrong one.

  2. Converted/resized files are never adopted into durable storage at the scan step. There is no ReceiptStorage.adopt call in useFilesValidation, in IOURequestStepScan, or in buildReceiptFiles - the file keeps its temp/cache URI from the converter or the manipulator. If the OS evicts that temp file before the queued upload runs, the receipt is gone. Relatedly, getTransactionWithPreservedLocalReceiptSource relies on ReceiptStorage.retain(), which is a literal no-op in the native implementation - so on native it preserves nothing.

  3. Correction - the crop path is not part of this bug. The receipt crop in TransactionReceiptModalContent DOES adopt its result (ReceiptStorage.adopt at line 367, then toLocalUri). And cropImageToAspectRatio, whose .catch(() => image) silently falls back to the original, is only called from the ODOMETER image step - it never touches receipts. Chasing either would be fixing the wrong code; this proposal leaves both alone and says so explicitly.

Changes

  1. Resize receipts against the receipt limit. resizeImageIfNeeded gains an optional maxSize parameter, defaulting to CONST.API_ATTACHMENT_VALIDATIONS.MAX_SIZE so every existing caller (chat attachments and others) behaves exactly as today. useFilesValidation passes CONST.API_ATTACHMENT_VALIDATIONS.RECEIPT_MAX_SIZE when validating receipts. A 15 MiB converted receipt now actually resizes to at most 10 MiB; a 9 MiB one is returned untouched, as before.

  2. Adopt the final file at the scan step. In src/pages/iou/request/step/IOURequestStepScan/utils/buildReceiptFiles.ts - the point where the receipt trace id is minted and setMoneyRequestReceipt is called (lines 71-74) - adopt the file before the receipt is set:

    • Native: ReceiptStorage.adopt(uri, filename), then toLocalUri, and store the durable URI as both the receipt source and localSource.
    • Web: ReceiptStorage.retain(uri). Web adopt is a passthrough by design (there is no filesystem); the session set in src/libs/ReceiptStorage/index.ts is the web durability mechanism, and retain is what makes resolve() keep accepting the URI for the session. Adoption failure falls back to the current URI (the existing logReceiptAdoptFailed pattern in the modal flow), so a storage error never blocks expense creation.
  3. Stop relying on the native no-op. In getTransactionWithPreservedLocalReceiptSource, resolve through ReceiptStorage.resolve() (which already refuses sources that are not durable) instead of calling the no-op native retain() and setting localSource unconditionally - localSource is only set when the source actually resolves to a durable location.

Not changed: the 24 MiB general attachment limit and its callers, the modal crop/rotate flow (already correct), the odometer crop, and the upload request itself - it already uploads whatever the receipt source points at; the fix makes that pointer durable and correctly sized.

Tests

  • tests/unit/FileUtilsTest.ts (exists): resizeImageIfNeeded with maxSize = RECEIPT_MAX_SIZE resizes a 15 MiB image and returns a 9 MiB image untouched; with no maxSize argument, behaviour is byte-for-byte the current behaviour.
  • useFilesValidation coverage: a HEIC receipt that converts to 15 MiB ends validation at or below 10 MiB (today it passes through at 15 MiB).
  • Scan-step coverage: after buildReceiptFiles, the transaction's receipt source points inside the receipts folder on native (not the converter's temp path), and the receipt trace id is unchanged.
  • Regression: a chat attachment of 15 MiB still validates against the 24 MiB limit, not the receipt limit.

Alternatives considered

  • Lower MAX_SIZE to 10 MiB globally. Rejected: 24 MiB is the server limit for general attachments (per the CONST comment, set with wider internal discussion); receipts have their own limit precisely so the two can differ.
  • Reject converted receipts over 10 MiB. Rejected: the resize path exists to accept them; rejecting would lose receipts the app can perfectly well shrink.
  • Adopt inside useFilesValidation. Rejected: validation is shared with chat attachments, which must not be moved into the receipts folder. Adoption belongs to the receipt flow, at the point the receipt is created.
  • "Fix" ReceiptStorage.resolve() to redirect temp URIs to originals. Rejected: resolve() correctly refuses non-durable sources; the defect is that nothing adopts the converted file in the first place, not that resolve() fails to guess.

dankezo avatar Nov 16 '26 06:11 dankezo

✅ Contributor details stored successfully. Thank you for contributing to Expensify!

melvin-bot[bot] avatar Nov 16 '26 06:11 melvin-bot[bot]

Proposal

Please re-state the problem that we are trying to solve in this issue.

The app converts HEIC and RAW (DNG) photos to JPEG, resizes oversized images, and crops/rotates receipts, but in each of those three code paths (useFilesValidation.tsx#L309, useFilesValidation.tsx#L349, and cropImageToAspectRatio.ts#L71 / TransactionReceiptModalContent.tsx#L374), the converted, resized, or cropped output is either not adopted into ReceiptStorage, skipped because of the wrong size threshold, or overwritten by new File([file], ...) on native, causing the app to store or upload the original unedited file.

What is the root cause of that problem?

Each of the three code sites linked in the issue has a specific bug:

  1. HEIC / DNG conversion (src/hooks/useFilesValidation.tsx#L309 & src/libs/fileDownload/heicConverter/index.native.ts#L36-L43):

    • On native, AttachmentPicker (src/components/AttachmentPicker/index.native.tsx:134-137) adopts the original .heic / .dng file into ReceiptStorage first and sets file.uri = durableUri and file.source = durableUri.
    • Then useFilesValidation.tsx:309 calls convertHeicImage(file, {onSuccess: (convertedFile) => ...}). In src/libs/fileDownload/heicConverter/index.native.ts:36-43, ImageManipulator writes the converted JPEG to the ephemeral cache directory (manipulationResult.uri) and returns {uri: manipulationResult.uri, name: ..., type: 'image/jpeg', size, width, height} without adopting the converted JPEG into ReceiptStorage (or setting source to a durable URI).
    • If the cache file is evicted or if any caller reads file.source (or if ReceiptStorage still holds the original .heic file without adopting the converted JPEG), the converted JPEG is not durably stored in ReceiptStorage.
  2. Image resizing (src/hooks/useFilesValidation.tsx#L349 & src/libs/fileDownload/FileUtils.ts#L736-L743):

    • In src/hooks/useFilesValidation.tsx#L280 and #L311, when validationState.isValidatingReceipts is true, any receipt larger than CONST.API_ATTACHMENT_VALIDATIONS.RECEIPT_MAX_SIZE (10 MB) is pushed to filesToResize, and line 349 calls resizeImageIfNeeded(file).
    • However, in src/libs/fileDownload/FileUtils.ts#L736-L739:
      const resizeImageIfNeeded = (file: FileObject) => {
          if (!file || !Str.isImage(file.name ?? '') || (file?.size ?? 0) <= CONST.API_ATTACHMENT_VALIDATIONS.MAX_SIZE) {
              return Promise.resolve(file);
          }
      
      resizeImageIfNeeded checks MAX_SIZE (24 MB) instead of RECEIPT_MAX_SIZE (10 MB)! Thus, every receipt (or converted HEIC/DNG JPEG) between 10 MB and 24 MB returns the original un-resized file untouched!
    • Furthermore, when resizeImageIfNeeded does resize a file (> 24 MB), createFile(result) (FileUtils.ts:713-726) returns {uri: result.uri, name: result.name, type: result.type} in the temporary cache folder without adopting the resized file into ReceiptStorage.
  3. Cropped and rotated images (src/pages/iou/request/step/IOURequestStepScan/cropImageToAspectRatio.ts#L71-L78 & src/pages/media/AttachmentModalScreen/routes/TransactionReceiptModalContent.tsx#L374):

    • In src/pages/iou/request/step/IOURequestStepScan/cropImageToAspectRatio.ts#L71-L78, cropOrRotateImage on native (src/libs/cropOrRotateImage/index.native.ts:47-86) has an iOS .catch fallback that resolves with the original uri (resolve({uri, ...})) while giving it name: croppedFilename (receipt_cropped_<timestamp>.jpeg), disguising the uncropped original as a cropped file! And when cropOrRotateImage succeeds, cropImageToAspectRatio does not adopt the cropped file into ReceiptStorage (or ReceiptStorage.retain on web).
    • Even worse, in src/pages/media/AttachmentModalScreen/routes/TransactionReceiptModalContent.tsx#L374, after cropping or rotating a receipt (saveCrop / rotateReceipt), applyDurableReceipt runs:
      const durableFile = Object.assign(new File([file], file.name || filename, {type: file.type}), {uri: durableUri, source: durableUri});
      
      On React Native, file is a plain object {uri, name, type, size, width, height} (CustomRNImageManipulatorResult), NOT a Web Blob. Passing a plain object into new File([file], ...) on React Native creates a bogus text/blob File containing "[object Object]" (or loses enumerable name/type properties on the RN File prototype), and rotateReceipt / saveCrop pass name: fileName (the same filename as the existing receipt, e.g. receipt_123.jpg), so when ReceiptStorage.adopt(imageUri, filename) runs on a file that is already in the receipts folder or shares the name, or when isDraftTransaction calls setMoneyRequestReceipt(transaction.transactionID, durableUri, filename, ...) without updating the draft's file object in Onyx, the upload uses the old file!

What changes do you think we should make in order to solve the problem?

  1. Pass the receipt size limit into resizeImageIfNeeded and adopt converted/resized receipt files into ReceiptStorage (src/libs/fileDownload/FileUtils.ts & src/hooks/useFilesValidation.tsx):

    • Update resizeImageIfNeeded(file: FileObject, isValidatingReceipts = false) in src/libs/fileDownload/FileUtils.ts:736:
      const resizeImageIfNeeded = (file: FileObject, isValidatingReceipts = false) => {
          const maxFileSize = isValidatingReceipts ? CONST.API_ATTACHMENT_VALIDATIONS.RECEIPT_MAX_SIZE : CONST.API_ATTACHMENT_VALIDATIONS.MAX_SIZE;
          if (!file || !Str.isImage(file.name ?? '') || (file?.size ?? 0) <= maxFileSize) {
              return Promise.resolve(file);
          }
          return getImageDimensionsAfterResize(file)
              .then(({width, height}) => getImageManipulator({fileUri: file.uri ?? '', width, height, fileName: file.name ?? '', type: file.type}))
              .then((result) => createFile(result));
      };
      
    • In src/hooks/useFilesValidation.tsx:
      • At line 349, call resizeImageIfNeeded(file, validationState.isValidatingReceipts).
      • When validationState.isValidatingReceipts is true, after convertHeicImage (line 309) or resizeImageIfNeeded (line 349) produces a new convertedFile / resizedFile, adopt the new file into ReceiptStorage via ReceiptStorage.adopt(newFile.uri ?? '', newFile.name) (and discard the pre-conversion .heic/.dng file from ReceiptStorage via ReceiptStorage.discard(file.uri)), updating newFile.uri and newFile.source to ReceiptStorage.toLocalUri(durableName) (and ReceiptStorage.retain on web).
  2. Adopt cropped/rotated images properly and fix applyDurableReceipt on native (cropImageToAspectRatio.ts & TransactionReceiptModalContent.tsx):

    • In src/pages/iou/request/step/IOURequestStepScan/cropImageToAspectRatio.ts:71-78:
      • Ensure croppedImage is adopted/retained (ReceiptStorage.adopt on native / ReceiptStorage.retain on web) and if cropOrRotateImage fell back to the original image.source on iOS error, log a warning and keep the original filename instead of renaming the uncropped file to receipt_cropped_*.jpeg.
    • In src/pages/media/AttachmentModalScreen/routes/TransactionReceiptModalContent.tsx:374:
      • Use createFile (or platform check instead of new File([file], ...) on native where file is CustomRNImageManipulatorResult) and mint a fresh filename on crop/rotate so ReceiptStorage.adopt writes a distinct durable file (and for draft transactions, also update the draft transaction's receipt / file so Confirmation uploads the cropped/rotated file rather than the original).
    • Add telemetry logging when an image is converted, resized, or cropped, and unit tests in tests/unit/FileUtilsTest.ts, tests/unit/hooks/useFilesValidation.test.ts, and tests/unit/cropImageToAspectRatioTest.ts.

What alternative solutions did you explore? (Optional)

  • Deferring ReceiptStorage.adopt until after useFilesValidation finishes for all files: adopting in AttachmentPicker is still helpful for files that need no conversion, so adopting the converted/resized output in useFilesValidation (and discarding the raw .heic / oversized copy) keeps both paths durable.

cocvn157 avatar Nov 16 '26 07:11 cocvn157

Proposal updated: please review this version of my proposal above (https://github.com/Expensify/App/issues/106960#issuecomment-6909640545), reformatted into the official template. The solution and scope are unchanged.

Contributor details Your Expensify account email: [email protected] Upwork Profile Link: https://www.upwork.com/freelancers/~013b564a690d9bcdab

Please re-state the problem that we are trying to solve in this issue.

Receipt images that the app converts or resizes are not the images that end up stored and uploaded. Oversize receipts pass through the resize step unchanged, and converted files live at temporary paths that can disappear before the upload runs - so the stored receipt is the unprocessed original, or nothing durable at all.

What is the root cause of that problem?

Two verified defects, and one claim in the issue that does not survive checking:

  1. The resize step uses the wrong limit for receipts. useFilesValidation (src/hooks/useFilesValidation.tsx:311) routes a HEIC-converted file into the resize list when it exceeds CONST.API_ATTACHMENT_VALIDATIONS.RECEIPT_MAX_SIZE (10 MiB, src/CONST/index.ts:474). But resizeImageIfNeeded (src/libs/fileDownload/FileUtils.ts:736-743) returns the file untouched whenever its size is at or below CONST.API_ATTACHMENT_VALIDATIONS.MAX_SIZE (24 MiB, src/CONST/index.ts:471) - the general attachment limit. A converted receipt between 10 and 24 MiB is therefore sent to resize and comes back identical: never resized to the receipt limit, never rejected. Both constants are server limits (per their CONST comments); the defect is purely that the receipt flow resizes against the wrong one.

  2. Converted/resized files are never adopted into durable storage at the scan step. There is no ReceiptStorage.adopt call in useFilesValidation, in IOURequestStepScan, or in buildReceiptFiles - the file keeps its temp/cache URI from the converter or the manipulator. If the OS evicts that temp file before the queued upload runs, the receipt is gone. Relatedly, getTransactionWithPreservedLocalReceiptSource relies on ReceiptStorage.retain(), which is a literal no-op in the native implementation - so on native it preserves nothing.

  3. Correction - the crop path is not part of this bug. The receipt crop in TransactionReceiptModalContent DOES adopt its result (ReceiptStorage.adopt at line 367, then toLocalUri). And cropImageToAspectRatio, whose .catch(() => image) silently falls back to the original, is only called from the ODOMETER image step - it never touches receipts. Chasing either would be fixing the wrong code; this proposal leaves both alone and says so explicitly.

What changes do you think we should make in order to solve the problem?

  1. Resize receipts against the receipt limit. resizeImageIfNeeded gains an optional maxSize parameter, defaulting to CONST.API_ATTACHMENT_VALIDATIONS.MAX_SIZE so every existing caller (chat attachments and others) behaves exactly as today. useFilesValidation passes CONST.API_ATTACHMENT_VALIDATIONS.RECEIPT_MAX_SIZE when validating receipts. A 15 MiB converted receipt now actually resizes to at most 10 MiB; a 9 MiB one is returned untouched, as before.

  2. Adopt the final file at the scan step. In src/pages/iou/request/step/IOURequestStepScan/utils/buildReceiptFiles.ts - the point where the receipt trace id is minted and setMoneyRequestReceipt is called (lines 71-74) - adopt the file before the receipt is set:

    • Native: ReceiptStorage.adopt(uri, filename), then toLocalUri, and store the durable URI as both the receipt source and localSource.
    • Web: ReceiptStorage.retain(uri). Web adopt is a passthrough by design (there is no filesystem); the session set in src/libs/ReceiptStorage/index.ts is the web durability mechanism, and retain is what makes resolve() keep accepting the URI for the session. Adoption failure falls back to the current URI (the existing logReceiptAdoptFailed pattern in the modal flow), so a storage error never blocks expense creation.
  3. Stop relying on the native no-op. In getTransactionWithPreservedLocalReceiptSource, resolve through ReceiptStorage.resolve() (which already refuses sources that are not durable) instead of calling the no-op native retain() and setting localSource unconditionally - localSource is only set when the source actually resolves to a durable location.

Not changed: the 24 MiB general attachment limit and its callers, the modal crop/rotate flow (already correct), the odometer crop, and the upload request itself - it already uploads whatever the receipt source points at; the fix makes that pointer durable and correctly sized.

Tests:

  • tests/unit/FileUtilsTest.ts (exists): resizeImageIfNeeded with maxSize = RECEIPT_MAX_SIZE resizes a 15 MiB image and returns a 9 MiB image untouched; with no maxSize argument, behaviour is byte-for-byte the current behaviour.
  • useFilesValidation coverage: a HEIC receipt that converts to 15 MiB ends validation at or below 10 MiB (today it passes through at 15 MiB).
  • Scan-step coverage: after buildReceiptFiles, the transaction's receipt source points inside the receipts folder on native (not the converter's temp path), and the receipt trace id is unchanged.
  • Regression: a chat attachment of 15 MiB still validates against the 24 MiB limit, not the receipt limit.

What alternative solutions did you explore? (Optional)

  • Lower MAX_SIZE to 10 MiB globally. Rejected: 24 MiB is the server limit for general attachments (per the CONST comment, set with wider internal discussion); receipts have their own limit precisely so the two can differ.
  • Reject converted receipts over 10 MiB. Rejected: the resize path exists to accept them; rejecting would lose receipts the app can perfectly well shrink.
  • Adopt inside useFilesValidation. Rejected: validation is shared with chat attachments, which must not be moved into the receipts folder. Adoption belongs to the receipt flow, at the point the receipt is created.
  • "Fix" ReceiptStorage.resolve() to redirect temp URIs to originals. Rejected: resolve() correctly refuses non-durable sources; the defect is that nothing adopts the converted file in the first place, not that resolve() fails to guess.

dankezo avatar Nov 16 '26 10:11 dankezo

✅ Contributor details stored successfully. Thank you for contributing to Expensify!

melvin-bot[bot] avatar Nov 16 '26 10:11 melvin-bot[bot]

Hello, I am Tomek from Callstack, I'd like to work on that issue. Currently working on preparing PR with the fix

rinej avatar Nov 18 '26 17:11 rinej