Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
23 commits
Select commit Hold shift + click to select a range
fe90615
Fix iOS HEIC gallery batch conversion OOM
nabi-ebrahimi Aug 4, 2026
2d682c3
Merge branch 'main' into fix-gallery-heic-sequential-processing
nabi-ebrahimi Aug 12, 2026
5604790
test added
nabi-ebrahimi Aug 12, 2026
4b3d0a5
Merge branch 'main' into fix-gallery-heic-sequential-processing
nabi-ebrahimi Aug 27, 2026
5881365
Merge branch 'main' into fix-gallery-heic-sequential-processing
nabi-ebrahimi Aug 27, 2026
6621abc
Merge branch 'main' into fix-gallery-heic-sequential-processing
nabi-ebrahimi Aug 28, 2026
b6ab747
Merge branch 'main' into fix-gallery-heic-sequential-processing
nabi-ebrahimi Aug 29, 2026
66de2e9
Localize attachment error fallback copy
nabi-ebrahimi Aug 29, 2026
35f6439
Merge branch 'main' into fix-gallery-heic-sequential-processing
nabi-ebrahimi Aug 31, 2026
574be48
Merge branch 'main' into fix-gallery-heic-sequential-processing
nabi-ebrahimi Sep 1, 2026
ee0b963
Collapse picker failures into a single alert
nabi-ebrahimi Sep 1, 2026
0c5e13a
Use canonical translate type
nabi-ebrahimi Sep 1, 2026
a796615
Keep converted asset fileName a string
nabi-ebrahimi Sep 1, 2026
2c5a4f5
Move picker asset processing to a lib module
nabi-ebrahimi Sep 1, 2026
a459c8d
Add coverage for skip and order preservation
nabi-ebrahimi Sep 1, 2026
d2cb822
Release native images quietly
nabi-ebrahimi Sep 1, 2026
7eb377b
Merge branch 'main' into fix-gallery-heic-sequential-processing
nabi-ebrahimi Sep 3, 2026
15eb441
Merge branch 'main' into fix-gallery-heic-sequential-processing
nabi-ebrahimi Sep 5, 2026
6c904c5
Resolve picker asset processing per platform
nabi-ebrahimi Sep 5, 2026
c8b7e71
Mock getFileName in picker asset tests
nabi-ebrahimi Sep 5, 2026
b1534c2
Add shared type for picker asset processing
nabi-ebrahimi Sep 5, 2026
a3f8c01
Add tests for fallbacks and partial success
nabi-ebrahimi Sep 5, 2026
bd99257
Document heicConverter divergence
nabi-ebrahimi Sep 5, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
89 changes: 3 additions & 86 deletions src/components/AttachmentPicker/index.native.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,9 @@ import useStyleUtils from '@hooks/useStyleUtils';
import useTheme from '@hooks/useTheme';
import useThemeStyles from '@hooks/useThemeStyles';

import {cleanFileName, showCameraPermissionsAlert, verifyFileFormat} from '@libs/fileDownload/FileUtils';
import {cleanFileName, showCameraPermissionsAlert} from '@libs/fileDownload/FileUtils';
import processPickedAssetsSequentially from '@libs/fileDownload/processPickedAssets';
import fileURIToPath from '@libs/fileURIToPath';
import Log from '@libs/Log';
import ReceiptStorage from '@libs/ReceiptStorage';
import {getPickerCaptureSource, logReceiptAdoptFailed} from '@libs/telemetry/ReceiptObservability';

Expand All @@ -27,7 +27,6 @@ import type {Asset, Callback, CameraOptions, ImageLibraryOptions, ImagePickerRes

import {keepLocalCopy, pick, types} from '@react-native-documents/picker';
import {Str} from 'expensify-common';
import {ImageManipulator, SaveFormat} from 'expo-image-manipulator';
import React, {useCallback, useMemo, useRef, useState} from 'react';
import {Alert, View} from 'react-native';
import RNFetchBlob from 'react-native-blob-util';
Expand Down Expand Up @@ -72,27 +71,6 @@ type Item = {
/** Function to call when the user clicks the item */
pickAttachment: () => Promise<Asset[] | void | LocalCopy[]>;
};

/**
* Ensures asset has proper fileName and type properties
*/
const processAssetWithFallbacks = (asset: Asset): Asset => {
// Generate fallback name: extract from URI if available, otherwise use timestamped default
const fallbackName = asset.uri
? asset.uri
.substring(asset.uri.lastIndexOf('/') + 1)
.split('?')
.at(0)
: `image_${Date.now()}.jpeg`;
const fileName = asset.fileName ?? fallbackName;
return {
...asset,
fileName,
// Default to JPEG if no type specified
type: asset.type ?? 'image/jpeg',
};
};

/**
* Return imagePickerOptions based on the type
*/
Expand Down Expand Up @@ -225,68 +203,7 @@ function AttachmentPicker({
return resolve();
}

const processedAssets: Asset[] = [];
let processedCount = 0;

const checkAllProcessed = () => {
processedCount++;
if (processedCount === assets.length) {
resolve(processedAssets.length > 0 ? processedAssets : undefined);
}
};

for (const asset of assets) {
if (!asset.uri) {
checkAllProcessed();
continue;
}

if (asset.type?.startsWith('image')) {
verifyFileFormat({fileUri: asset.uri, formatSignatures: CONST.HEIC_SIGNATURES})
.then((isHEIC) => {
// react-native-image-picker incorrectly changes file extension without transcoding the HEIC file, so we are doing it manually if we detect HEIC signature
if (isHEIC && asset.uri) {
ImageManipulator.manipulate(asset.uri)
.renderAsync()
.then((manipulatedImage) => manipulatedImage.saveAsync({format: SaveFormat.JPEG}))
.then((manipulationResult) => {
const uri = manipulationResult.uri;
const convertedAsset = {
uri,
name: uri
.substring(uri.lastIndexOf('/') + 1)
.split('?')
.at(0),
type: 'image/jpeg',
width: manipulationResult.width,
height: manipulationResult.height,
};
processedAssets.push(convertedAsset);
checkAllProcessed();
})
.catch((error: Error) => {
Log.warn('Failed to convert HEIC image, skipping asset', {error: error.message});
showGeneralAlert(translate('attachmentPicker.errorWhileConvertingHeic'));
checkAllProcessed();
});
} else {
// Ensure the asset has proper fileName and type for non-HEIC images
const processedAsset = processAssetWithFallbacks(asset);
processedAssets.push(processedAsset);
checkAllProcessed();
}
})
.catch((error: Error) => {
showGeneralAlert(error.message ?? 'An unknown error occurred');
checkAllProcessed();
});
} else {
// Ensure the asset has proper fileName and type
const processedAsset = processAssetWithFallbacks(asset);
processedAssets.push(processedAsset);
checkAllProcessed();
}
}
processPickedAssetsSequentially(assets, showGeneralAlert, translate).then(resolve).catch(reject);
});
}),
[fileLimit, showGeneralAlert, translate, type],
Expand Down
132 changes: 132 additions & 0 deletions src/libs/fileDownload/processPickedAssets/index.native.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,132 @@
import {getFileName, verifyFileFormat} from '@libs/fileDownload/FileUtils';
import Log from '@libs/Log';

import CONST from '@src/CONST';

import type {Asset} from 'react-native-image-picker';

import {ImageManipulator, SaveFormat} from 'expo-image-manipulator';

import type ProcessPickedAssetsFunction from './types';

/**
* Ensures asset has proper fileName and type properties. Callers only pass assets that have a `uri`.
*/
function processAssetWithFallbacks(asset: Asset): Asset {
return {
...asset,
fileName: asset.fileName ?? getFileName(asset.uri ?? ''),
// Default to JPEG if no type specified
type: asset.type ?? 'image/jpeg',
};
}

function getErrorMessage(error: unknown, fallback: string): string {
return error instanceof Error && error.message ? error.message : fallback;
}

/**
* Frees a native image resource. Releasing is best-effort cleanup, so a failure here must never change
* whether the converted asset is kept.
*/
function releaseQuietly(releasable: {release: () => void}) {
try {
releasable.release();
} catch (error) {
Log.warn('Failed to release native image resource', {error: getErrorMessage(error, 'An unknown error occurred')});
}
}

/**
* Transcodes a single HEIC image to JPEG, returning `undefined` if the conversion fails.
*
* The native context and the rendered bitmap are released as soon as they are no longer needed rather
* than waiting for the garbage collector, which has no visibility into the native memory they retain.
*
* This repeats the manipulate/render/save sequence from `heicConverter` rather than calling it, because
* that helper decides what to convert from the `.heic`/`.heif` extension. react-native-image-picker
* relabels the extension without transcoding, so this path has to detect HEIC from the file signature
* instead and cannot go through `convertHeicImage`.
*/
async function convertHeicToJpeg(uri: string): Promise<Asset | undefined> {
const imageManipulatorContext = ImageManipulator.manipulate(uri);
try {
const manipulatedImage = await imageManipulatorContext.renderAsync();
try {
const manipulationResult = await manipulatedImage.saveAsync({format: SaveFormat.JPEG});
return {
uri: manipulationResult.uri,
fileName: getFileName(manipulationResult.uri),
type: 'image/jpeg',
width: manipulationResult.width,
height: manipulationResult.height,
};
} finally {
releaseQuietly(manipulatedImage);
}
} catch (error) {
Log.warn('Failed to convert HEIC image, skipping asset', {error: getErrorMessage(error, 'An unknown error occurred')});
return undefined;
} finally {
releaseQuietly(imageManipulatorContext);
}
}

/**
* Convert the picked assets one at a time, transcoding any HEIC images to JPEG.
*
* The conversion is deliberately sequential: `ImageManipulator` decodes each image into a full-size
* bitmap in native memory, so converting a whole selection at once (the picker allows up to
* `CONST.API_ATTACHMENT_VALIDATIONS.MAX_FILE_LIMIT` files) holds every bitmap simultaneously and the
* OS terminates the app for exceeding its memory limit. Processing one image at a time keeps the peak
* at a single bitmap regardless of how many files were picked.
*/
const processPickedAssetsSequentially: ProcessPickedAssetsFunction = async (assets, showGeneralAlert, translate) => {
const processedAssets: Asset[] = [];
// Collected instead of alerted inline so the whole selection produces a single alert: alerting per
// asset would leave the user dismissing one native modal after another.
const failureMessages = new Set<string>();

for (const asset of assets) {
if (!asset.uri) {
continue;
}

if (!asset.type?.startsWith('image')) {
// Ensure the asset has proper fileName and type
processedAssets.push(processAssetWithFallbacks(asset));
continue;
}

try {
// eslint-disable-next-line no-await-in-loop -- converting one image at a time is the point, see the doc comment above
const isHEIC = await verifyFileFormat({fileUri: asset.uri, formatSignatures: CONST.HEIC_SIGNATURES});

if (!isHEIC) {
// Ensure the asset has proper fileName and type for non-HEIC images
processedAssets.push(processAssetWithFallbacks(asset));
continue;
}

// react-native-image-picker incorrectly changes file extension without transcoding the HEIC file, so we are doing it manually if we detect HEIC signature
// eslint-disable-next-line no-await-in-loop -- converting one image at a time is the point, see the doc comment above
const convertedAsset = await convertHeicToJpeg(asset.uri);

if (convertedAsset) {
processedAssets.push(convertedAsset);
} else {
failureMessages.add(translate('attachmentPicker.errorWhileConvertingHeic'));
}
} catch (error) {
failureMessages.add(getErrorMessage(error, translate('attachmentPicker.errorWhileSelectingAttachment')));
}
}

if (failureMessages.size > 0) {
showGeneralAlert([...failureMessages].join('\n'));
}

return processedAssets.length > 0 ? processedAssets : undefined;
Comment thread
nabi-ebrahimi marked this conversation as resolved.
Resolved
};

export default processPickedAssetsSequentially;
9 changes: 9 additions & 0 deletions src/libs/fileDownload/processPickedAssets/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import type ProcessPickedAssetsFunction from './types';

/**
* Web has no native image picker, so nothing reaches this module. It exists so the native
* implementation resolves through a platform-agnostic import path.
*/
const processPickedAssetsSequentially: ProcessPickedAssetsFunction = (assets) => Promise.resolve(assets.length > 0 ? assets : undefined);

export default processPickedAssetsSequentially;
7 changes: 7 additions & 0 deletions src/libs/fileDownload/processPickedAssets/types.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import type {LocaleContextProps} from '@components/LocaleContextProvider';

import type {Asset} from 'react-native-image-picker';

type ProcessPickedAssetsFunction = (assets: Asset[], showGeneralAlert: (message?: string) => void, translate: LocaleContextProps['translate']) => Promise<Asset[] | undefined>;

export default ProcessPickedAssetsFunction;
Loading
Loading