diff --git a/src/components/Attachments/AttachmentView/index.tsx b/src/components/Attachments/AttachmentView/index.tsx index ab69b29dfa5b..fab3d89e637f 100644 --- a/src/components/Attachments/AttachmentView/index.tsx +++ b/src/components/Attachments/AttachmentView/index.tsx @@ -235,6 +235,21 @@ function AttachmentView({ const isSourcePDF = typeof source === 'string' && Str.isPDF(source); const isFilePDF = file && Str.isPDF(file.name ?? translate('attachmentView.unknownFilename')); if (!hasPDFFailedToLoad && !isUploading && (isSourcePDF || isFilePDF)) { + // Every mounted PDF viewer is a full PDF.js document parse (its own worker + parsed document), so in a + // carousel the memory cost scales with the number of PDF attachments — enough to OOM the WebContent + // process on iOS Safari and reload the tab when several PDFs are added at once. Only mount the viewer + // for the item the carousel currently focuses; off-screen items render a lightweight placeholder until + // they're swiped to. isFocused is undefined outside the carousel (single-attachment hosts), which must + // keep mounting immediately. + if (isFocused === false) { + return ( + + ); + } const encryptedSourceUrl = isAuthTokenRequired ? addEncryptedAuthTokenToURL(source as string, encryptedAuthToken) : (source as string); const onPDFLoadComplete = (path: string) => { diff --git a/src/hooks/useFilesValidation.tsx b/src/hooks/useFilesValidation.tsx index b9a21e841e7c..f16a6a37dbfa 100644 --- a/src/hooks/useFilesValidation.tsx +++ b/src/hooks/useFilesValidation.tsx @@ -48,6 +48,9 @@ function useFilesValidation(onFilesValidated: (files: FileObject[], dataTransfer const [isErrorModalVisible, setIsErrorModalVisible] = useState(false); const [fileError, setFileError] = useState(null); const [pdfFilesToRender, setPdfFilesToRender] = useState([]); + // Index of the PDF currently being validated — thumbnails are rendered one at a time (see + // PDFValidationComponent below), and this advances to the next PDF when the current one settles. + const [validatedPDFCount, setValidatedPDFCount] = useState(0); const [validFilesToUpload, setValidFilesToUpload] = useState([] as FileObject[]); const [errorQueue, setErrorQueue] = useState([]); const [currentErrorIndex, setCurrentErrorIndex] = useState(0); @@ -96,6 +99,7 @@ function useFilesValidation(onFilesValidated: (files: FileObject[], dataTransfer setIsValidatingReceipts(undefined); setIsErrorModalVisible(false); setPdfFilesToRender([]); + setValidatedPDFCount(0); setIsLoaderVisible(false); setValidFilesToUpload([]); setFileError(null); @@ -174,37 +178,40 @@ function useFilesValidation(onFilesValidated: (files: FileObject[], dataTransfer const filesToResize: FileObject[] = []; const filesToConvert: FileObject[] = []; - await Promise.all( - files.map(async (file, index) => { - const result = await validateAttachmentFile(file, items.at(index), validationState.isValidatingReceipts); + // Validate sequentially so only one image is decoded and held in memory at a time. Validating the + // whole batch with Promise.all multiplies peak memory by the number of selected files (each pass + // decodes the full-resolution image), which can kill the WebContent process on memory-constrained + // mobile Safari when 3+ photos are selected — the tab reloads and the attachments are lost. + for (const [index, file] of files.entries()) { + // eslint-disable-next-line no-await-in-loop + const result = await validateAttachmentFile(file, items.at(index), validationState.isValidatingReceipts); - if (result.isValid) { - if (Str.isPDF(result.file.name ?? '')) { - pdfsToLoad.push(result.file); - } else { - validNonPdfFiles.push(result.file); - } - return; + if (result.isValid) { + if (Str.isPDF(result.file.name ?? '')) { + pdfsToLoad.push(result.file); + } else { + validNonPdfFiles.push(result.file); } + continue; + } - if (result.error === CONST.FILE_VALIDATION_ERRORS.FILE_TOO_LARGE && isImageFile(file)) { - filesToResize.push(file); - return; - } + if (result.error === CONST.FILE_VALIDATION_ERRORS.FILE_TOO_LARGE && isImageFile(file)) { + filesToResize.push(file); + continue; + } - if (result.error === CONST.FILE_VALIDATION_ERRORS.HEIC_OR_HEIF_IMAGE) { - filesToConvert.push(file); - return; - } + if (result.error === CONST.FILE_VALIDATION_ERRORS.HEIC_OR_HEIF_IMAGE) { + filesToConvert.push(file); + continue; + } - const errorData = { - error: result.error, - isValidatingMultipleFiles: validationState.isValidatingMultipleFiles, - fileType: result.error === CONST.FILE_VALIDATION_ERRORS.WRONG_FILE_TYPE ? splitExtensionFromFileName(file.name ?? '').fileExtension : undefined, - } satisfies FileValidationError; - collectedErrors.current.push(errorData); - }), - ); + const errorData = { + error: result.error, + isValidatingMultipleFiles: validationState.isValidatingMultipleFiles, + fileType: result.error === CONST.FILE_VALIDATION_ERRORS.WRONG_FILE_TYPE ? splitExtensionFromFileName(file.name ?? '').fileExtension : undefined, + } satisfies FileValidationError; + collectedErrors.current.push(errorData); + } if (filesToConvert.length > 0) { showLoader(); @@ -277,6 +284,7 @@ function useFilesValidation(onFilesValidated: (files: FileObject[], dataTransfer const handleNext = () => { if (pdfsToLoad.length) { validFiles.current = validNonPdfFiles; + setValidatedPDFCount(0); setPdfFilesToRender(pdfsToLoad); return; } @@ -398,34 +406,41 @@ function useFilesValidation(onFilesValidated: (files: FileObject[], dataTransfer } }; - const PDFValidationComponent = pdfFilesToRender.length - ? pdfFilesToRender.map((file) => ( - { - validatedPDFs.current.push(file); - validFiles.current.push(file); - checkIfAllValidatedAndProceed(); - }} - onPassword={() => { - validatedPDFs.current.push(file); - if (isValidatingReceipts === true) { - collectedErrors.current.push({error: CONST.FILE_VALIDATION_ERRORS.PROTECTED_FILE}); - } else { - validFiles.current.push(file); - } - checkIfAllValidatedAndProceed(); - }} - onLoadError={() => { - validatedPDFs.current.push(file); - collectedErrors.current.push({error: CONST.FILE_VALIDATION_ERRORS.FILE_CORRUPTED}); - checkIfAllValidatedAndProceed(); - }} - /> - )) - : undefined; + // Validate the PDFs one at a time: every mounted PDFThumbnail is a full PDF.js document parse (its own + // worker + parsed document), so rendering the whole batch at once multiplies peak memory by the number of + // selected PDFs — the same batch-decode problem the sequential image validation above avoids — which can + // kill the WebContent process on memory-constrained mobile Safari and reload the tab. Each thumbnail + // advances validatedPDFCount when it settles (success/password/error), mounting the next one. + const pdfFileToValidate = pdfFilesToRender.at(validatedPDFCount); + const PDFValidationComponent = pdfFileToValidate ? ( + { + validatedPDFs.current.push(pdfFileToValidate); + validFiles.current.push(pdfFileToValidate); + setValidatedPDFCount((count) => count + 1); + checkIfAllValidatedAndProceed(); + }} + onPassword={() => { + validatedPDFs.current.push(pdfFileToValidate); + if (isValidatingReceipts === true) { + collectedErrors.current.push({error: CONST.FILE_VALIDATION_ERRORS.PROTECTED_FILE}); + } else { + validFiles.current.push(pdfFileToValidate); + } + setValidatedPDFCount((count) => count + 1); + checkIfAllValidatedAndProceed(); + }} + onLoadError={() => { + validatedPDFs.current.push(pdfFileToValidate); + collectedErrors.current.push({error: CONST.FILE_VALIDATION_ERRORS.FILE_CORRUPTED}); + setValidatedPDFCount((count) => count + 1); + checkIfAllValidatedAndProceed(); + }} + /> + ) : undefined; const fileValidationErrorText = getFileValidationErrorText(translate, fileError, {isValidatingReceipt: isValidatingReceipts}); diff --git a/src/libs/validateAttachmentFile.ts b/src/libs/validateAttachmentFile.ts index 4470e45b4a00..acf42e3308a3 100644 --- a/src/libs/validateAttachmentFile.ts +++ b/src/libs/validateAttachmentFile.ts @@ -70,7 +70,16 @@ async function validateAttachmentFile(file: FileObject, item?: DataTransferItem, if (updatedFile.name !== cleanName) { updatedFile = new File([updatedFile], cleanName, {type: updatedFile.type}); } + // Read the superseded URI from normalizedFile: when the name needed cleaning, updatedFile was + // reassigned to a fresh File that doesn't carry the custom .uri property, so reading it there + // would skip the revoke exactly for cleaned filenames (e.g. default macOS screenshot names). + const previousUri = normalizedFile.uri; const inputSource = URL.createObjectURL(updatedFile); + if (previousUri && previousUri !== inputSource && previousUri.startsWith('blob:')) { + // Release the superseded object URL (e.g. the one AttachmentPicker assigned) so its Blob can be + // garbage-collected; orphaned blob: URLs keep the full-size file resident until the document dies. + URL.revokeObjectURL(previousUri); + } updatedFile.uri = inputSource; return {isValid: true, file: updatedFile}; diff --git a/src/pages/media/AttachmentModalScreen/routes/report/ReportAddAttachmentModalContent/index.tsx b/src/pages/media/AttachmentModalScreen/routes/report/ReportAddAttachmentModalContent/index.tsx index 4f3effad2963..f3f745bef251 100644 --- a/src/pages/media/AttachmentModalScreen/routes/report/ReportAddAttachmentModalContent/index.tsx +++ b/src/pages/media/AttachmentModalScreen/routes/report/ReportAddAttachmentModalContent/index.tsx @@ -6,7 +6,6 @@ import {openReport} from '@libs/actions/Report'; import {getValidatedImageSource} from '@libs/AvatarUtils'; import Navigation from '@libs/Navigation/Navigation'; import {canUserPerformWriteAction, isReportNotFound} from '@libs/ReportUtils'; -import validateAttachmentFile from '@libs/validateAttachmentFile'; import type {AttachmentModalBaseContentProps} from '@pages/media/AttachmentModalScreen/AttachmentModalBaseContent/types'; import AttachmentModalContainer from '@pages/media/AttachmentModalScreen/AttachmentModalContainer'; @@ -23,7 +22,7 @@ import {isEmptyObject} from '@src/types/utils/EmptyObject'; import type {View} from 'react-native'; -import React, {useCallback, useEffect, useMemo, useRef, useState} from 'react'; +import React, {useCallback, useEffect, useMemo, useRef} from 'react'; import AddAttachmentModalCarouselView from './AddAttachmentModalCarouselView'; @@ -83,33 +82,21 @@ function ReportAddAttachmentModalContent({route, navigation}: AttachmentModalScr fetchReport(); }, [reportID, fetchReport, shouldFetchReport]); - const [source, setSource] = useState(() => getValidatedImageSource(sourceParam)); - - const [validFiles, setValidFiles] = useState(fileParam); - useEffect(() => { - async function validateFiles() { - if (!fileParam) { - return; - } - - const files = Array.isArray(fileParam) ? fileParam : [fileParam]; - const results = await Promise.all(files.map(async (file) => validateAttachmentFile(file))); - - const validResults = results.filter((r) => r.isValid); - if (validResults.length === 0) { - return; - } - - const validatedFiles = validResults.map((r) => r.file); - const firstValidSource = validResults.at(0)?.file.uri; - - setSource(firstValidSource); - setValidFiles(validatedFiles); + // Files reaching this screen were already validated, HEIC-converted and resized by useFilesValidation + // before navigation (useAttachmentPicker's onFilesValidated is the only entry point to this route). + // Re-running validateAttachmentFile here decodes every image a second time and allocates a duplicate + // set of object URLs at the exact moment the carousel decodes the same images for display — on + // memory-constrained mobile Safari that doubled peak is enough to kill the WebContent process and + // reload the tab, silently dropping the attachments. Trust the validated params and derive directly. + const validFiles = useMemo(() => { + if (!fileParam) { + return undefined; } - - validateFiles(); + return Array.isArray(fileParam) ? fileParam : [fileParam]; }, [fileParam]); + const source = useMemo(() => (validFiles ? validFiles.at(0)?.uri : getValidatedImageSource(sourceParam)), [validFiles, sourceParam]); + const modalType = useReportAttachmentModalType(source, validFiles); useNavigateToReportOnRefresh({source: sourceParam, file: validFiles, reportID}); @@ -138,8 +125,6 @@ function ReportAddAttachmentModalContent({route, navigation}: AttachmentModalScr isAuthTokenRequired, }); - useNavigateToReportOnRefresh({source: sourceParam, file: validFiles, reportID}); - const contentProps = useMemo(() => { if (validFiles === undefined || (Array.isArray(validFiles) && validFiles.length === 0)) { return { diff --git a/tests/unit/ValidateAttachmentFileTest.ts b/tests/unit/ValidateAttachmentFileTest.ts index 794b5d7d6434..4f86e96fe1f7 100644 --- a/tests/unit/ValidateAttachmentFileTest.ts +++ b/tests/unit/ValidateAttachmentFileTest.ts @@ -331,4 +331,76 @@ describe('validateAttachmentFile', () => { } }); }); + + describe('object URL revocation', () => { + it('revokes the superseded blob: uri and assigns the new object URL', async () => { + // In Node/Jest the react-native-url-polyfill throws for createObjectURL (no BlobModule). + // Mock it so the File path that assigns file.uri can run. + const createObjectURLSpy = jest.spyOn(URL, 'createObjectURL').mockReturnValue('blob:new-url'); + const revokeObjectURLSpy = jest.spyOn(URL, 'revokeObjectURL').mockImplementation(() => {}); + try { + const previousUri = 'blob:previous-url'; + const fileWithUri: FileObject = new File([new Blob(['content'], {type: 'text/plain'})], 'image.png', {type: 'image/png'}); + fileWithUri.uri = previousUri; + + const error = await validateAttachmentFile(fileWithUri); + + expect(error.isValid).toBe(true); + if (!error.isValid) { + throw new Error('validateAttachmentFile should return a valid result'); + } + expect(revokeObjectURLSpy).toHaveBeenCalledWith(previousUri); + expect(error.file.uri).toBe('blob:new-url'); + } finally { + createObjectURLSpy.mockRestore(); + revokeObjectURLSpy.mockRestore(); + } + }); + + it('still revokes the superseded blob: uri when the filename needs cleaning (new File() drops the custom .uri)', async () => { + const createObjectURLSpy = jest.spyOn(URL, 'createObjectURL').mockReturnValue('blob:new-url'); + const revokeObjectURLSpy = jest.spyOn(URL, 'revokeObjectURL').mockImplementation(() => {}); + try { + const previousUri = 'blob:previous-url'; + // A name cleanFileName rewrites (spaces), forcing the `new File(...)` reassignment that does + // not carry over the custom .uri property — the revoke must still target the original URI. + const fileWithUri: FileObject = new File([new Blob(['content'], {type: 'text/plain'})], 'Screenshot 2026-07-11 at 9.15.03 AM.png', {type: 'image/png'}); + fileWithUri.uri = previousUri; + + const error = await validateAttachmentFile(fileWithUri); + + expect(error.isValid).toBe(true); + if (!error.isValid) { + throw new Error('validateAttachmentFile should return a valid result'); + } + expect(revokeObjectURLSpy).toHaveBeenCalledWith(previousUri); + expect(error.file.uri).toBe('blob:new-url'); + } finally { + createObjectURLSpy.mockRestore(); + revokeObjectURLSpy.mockRestore(); + } + }); + + it('does not revoke any object URL when the incoming file has no uri', async () => { + // In Node/Jest the react-native-url-polyfill throws for createObjectURL (no BlobModule). + // Mock it so the File path that assigns file.uri can run. + const createObjectURLSpy = jest.spyOn(URL, 'createObjectURL').mockReturnValue('blob:new-url'); + const revokeObjectURLSpy = jest.spyOn(URL, 'revokeObjectURL').mockImplementation(() => {}); + try { + const fileWithoutUri: FileObject = new File([new Blob(['content'], {type: 'text/plain'})], 'image.png', {type: 'image/png'}); + + const error = await validateAttachmentFile(fileWithoutUri); + + expect(error.isValid).toBe(true); + if (!error.isValid) { + throw new Error('validateAttachmentFile should return a valid result'); + } + expect(revokeObjectURLSpy).not.toHaveBeenCalled(); + expect(error.file.uri).toBe('blob:new-url'); + } finally { + createObjectURLSpy.mockRestore(); + revokeObjectURLSpy.mockRestore(); + } + }); + }); });