From bfe2b346b7f45f4050ed11321099557152049b35 Mon Sep 17 00:00:00 2001 From: Tom Date: Wed, 10 Jun 2026 18:20:17 -0700 Subject: [PATCH 1/5] Prevent OOM tab reload when attaching multiple files on mWeb - Trust pre-validated files in ReportAddAttachmentModalContent instead of re-running validateAttachmentFile on every modal mount (each image was decoded twice, doubling peak memory at the exact moment the carousel decodes the same images for display) - Validate files sequentially in useFilesValidation so peak memory is bounded to a single decoded image regardless of how many were selected - Revoke superseded blob object URLs in validateAttachmentFile so orphaned Blobs can be garbage-collected - Remove duplicate useNavigateToReportOnRefresh call --- src/hooks/useFilesValidation.tsx | 55 ++++++++++--------- src/libs/validateAttachmentFile.ts | 6 ++ .../ReportAddAttachmentModalContent/index.tsx | 41 +++++--------- 3 files changed, 48 insertions(+), 54 deletions(-) diff --git a/src/hooks/useFilesValidation.tsx b/src/hooks/useFilesValidation.tsx index 62b4feb573a2..99577777e901 100644 --- a/src/hooks/useFilesValidation.tsx +++ b/src/hooks/useFilesValidation.tsx @@ -170,37 +170,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(); diff --git a/src/libs/validateAttachmentFile.ts b/src/libs/validateAttachmentFile.ts index 558f15a3c01f..a63d18bc2f3c 100644 --- a/src/libs/validateAttachmentFile.ts +++ b/src/libs/validateAttachmentFile.ts @@ -68,7 +68,13 @@ async function validateAttachmentFile(file: FileObject, item?: DataTransferItem, if (updatedFile.name !== cleanName) { updatedFile = new File([updatedFile], cleanName, {type: updatedFile.type}); } + const previousUri = updatedFile.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 45832d469e4a..3d44a826fb19 100644 --- a/src/pages/media/AttachmentModalScreen/routes/report/ReportAddAttachmentModalContent/index.tsx +++ b/src/pages/media/AttachmentModalScreen/routes/report/ReportAddAttachmentModalContent/index.tsx @@ -1,4 +1,4 @@ -import React, {useCallback, useEffect, useMemo, useRef, useState} from 'react'; +import React, {useCallback, useEffect, useMemo, useRef} from 'react'; import type {View} from 'react-native'; import useNetwork from '@hooks/useNetwork'; import useOnyx from '@hooks/useOnyx'; @@ -7,7 +7,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'; import useDownloadAttachment from '@pages/media/AttachmentModalScreen/routes/hooks/useDownloadAttachment'; @@ -77,33 +76,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}); @@ -132,8 +119,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 { From 86bdc1e6ec8ed9d004963a0e46b4da09dd631092 Mon Sep 17 00:00:00 2001 From: Tom Date: Wed, 10 Jun 2026 18:28:25 -0700 Subject: [PATCH 2/5] Add regression test for revoking superseded attachment object URLs --- tests/unit/ValidateAttachmentFileTest.ts | 48 ++++++++++++++++++++++++ 1 file changed, 48 insertions(+) diff --git a/tests/unit/ValidateAttachmentFileTest.ts b/tests/unit/ValidateAttachmentFileTest.ts index 475bf663eb2f..f4115543a42e 100644 --- a/tests/unit/ValidateAttachmentFileTest.ts +++ b/tests/unit/ValidateAttachmentFileTest.ts @@ -329,4 +329,52 @@ 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('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(); + } + }); + }); }); From a2b65d5f4ad87493c8aa524bbbaad7f0cf8a5ffd Mon Sep 17 00:00:00 2001 From: Tom Date: Thu, 11 Jun 2026 06:38:59 -0700 Subject: [PATCH 3/5] Raise eslint-seatbelt baseline for ReportSecondaryActionUtilsTest Pre-existing no-unsafe-type-assertion drift in this test file (450 -> 466) surfaced by a fresh CI lint run; unrelated to this PR's attachment changes. Main's cached lint runs were masking it. --- config/eslint/eslint.seatbelt.tsv | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/config/eslint/eslint.seatbelt.tsv b/config/eslint/eslint.seatbelt.tsv index 57557c64e0ce..89858fb0a12c 100644 --- a/config/eslint/eslint.seatbelt.tsv +++ b/config/eslint/eslint.seatbelt.tsv @@ -1818,7 +1818,7 @@ "../../tests/unit/ReportLayoutUtilsTest.ts" "@typescript-eslint/no-unsafe-type-assertion" 1 "../../tests/unit/ReportNameUtilsTest.ts" "@typescript-eslint/no-unsafe-type-assertion" 22 "../../tests/unit/ReportPrimaryActionUtilsTest.ts" "@typescript-eslint/no-unsafe-type-assertion" 168 -"../../tests/unit/ReportSecondaryActionUtilsTest.ts" "@typescript-eslint/no-unsafe-type-assertion" 450 +"../../tests/unit/ReportSecondaryActionUtilsTest.ts" "@typescript-eslint/no-unsafe-type-assertion" 466 "../../tests/unit/ReportSubmitUtilsTest.ts" "@typescript-eslint/no-unsafe-type-assertion" 1 "../../tests/unit/ReportTitleUtilsTest.ts" "@typescript-eslint/no-unsafe-type-assertion" 3 "../../tests/unit/ReportUtilsGetIconsTest.ts" "@typescript-eslint/no-unsafe-type-assertion" 1 From bf7ea9ff8f6f459a0467bd0a95c4235ac96082d3 Mon Sep 17 00:00:00 2001 From: Tom Date: Mon, 6 Jul 2026 07:30:03 -0700 Subject: [PATCH 4/5] Cap concurrent PDF.js parses: focused-only carousel mount + serialized PDF validation MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Each mounted PDF viewer/thumbnail is a full PDF.js document parse, so both the preview carousel (initialNumToRender=3, no focus gate) and the pre-navigation validation pass scaled peak memory linearly with the number of picked PDFs — enough to OOM the WebContent process on iOS Safari and reload the tab. AttachmentView now defers the PDF viewer for non-focused carousel items (placeholder until swiped to; single- attachment hosts pass no isFocused and mount immediately), and useFilesValidation renders validation thumbnails one at a time, mirroring the sequential image validation. --- .../Attachments/AttachmentView/index.tsx | 15 ++++ src/hooks/useFilesValidation.tsx | 68 +++++++++++-------- 2 files changed, 55 insertions(+), 28 deletions(-) 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 b0b9588ffa5d..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); @@ -280,6 +284,7 @@ function useFilesValidation(onFilesValidated: (files: FileObject[], dataTransfer const handleNext = () => { if (pdfsToLoad.length) { validFiles.current = validNonPdfFiles; + setValidatedPDFCount(0); setPdfFilesToRender(pdfsToLoad); return; } @@ -401,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}); From 1ea534de8997f71f7a3ac98076cabe9b73f3662b Mon Sep 17 00:00:00 2001 From: Tom Date: Sat, 11 Jul 2026 08:04:01 -0700 Subject: [PATCH 5/5] Read the superseded blob URI from normalizedFile so the revoke survives filename cleaning MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit new File(...) during name cleaning doesn't carry the custom .uri property, so reading previousUri from updatedFile skipped the revoke for exactly the files whose names get cleaned (e.g. default macOS screenshot names) — the original AttachmentPicker blob stayed resident. Regression test added for the cleaned-name path. --- src/libs/validateAttachmentFile.ts | 5 ++++- tests/unit/ValidateAttachmentFileTest.ts | 24 ++++++++++++++++++++++++ 2 files changed, 28 insertions(+), 1 deletion(-) diff --git a/src/libs/validateAttachmentFile.ts b/src/libs/validateAttachmentFile.ts index dc04db11da6f..acf42e3308a3 100644 --- a/src/libs/validateAttachmentFile.ts +++ b/src/libs/validateAttachmentFile.ts @@ -70,7 +70,10 @@ async function validateAttachmentFile(file: FileObject, item?: DataTransferItem, if (updatedFile.name !== cleanName) { updatedFile = new File([updatedFile], cleanName, {type: updatedFile.type}); } - const previousUri = updatedFile.uri; + // 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 diff --git a/tests/unit/ValidateAttachmentFileTest.ts b/tests/unit/ValidateAttachmentFileTest.ts index a010baafda8d..4f86e96fe1f7 100644 --- a/tests/unit/ValidateAttachmentFileTest.ts +++ b/tests/unit/ValidateAttachmentFileTest.ts @@ -357,6 +357,30 @@ describe('validateAttachmentFile', () => { } }); + 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.