Skip to content

Prevent OOM tab reload when attaching multiple files on mWeb#93234

Merged
robertjchen merged 8 commits into
Expensify:mainfrom
trasnake87:attachments-oom-92108
Jul 16, 2026
Merged

Prevent OOM tab reload when attaching multiple files on mWeb#93234
robertjchen merged 8 commits into
Expensify:mainfrom
trasnake87:attachments-oom-92108

Conversation

@trasnake87

@trasnake87 trasnake87 commented Jun 11, 2026

Copy link
Copy Markdown
Contributor

Explanation of Change

Selecting multiple full-resolution photos could kill the browser's WebContent process on memory-constrained mobile Safari and reload the tab. The picked files only live in an in-memory ref, so after the reload useNavigateToReportOnRefresh sees no file params and navigates back to the report — the attachments are silently dropped. Since File/blob: handles cannot survive a WebContent reload, the fix prevents the reload by removing three compounding memory costs in the selection chain:

  1. Redundant second decode pass. ReportAddAttachmentModalContent re-ran validateAttachmentFile on files that useFilesValidation had already validated, HEIC-converted and resized before navigation — decoding every image a second time (at the same moment the carousel decodes them for display) and allocating a duplicate set of object URLs. The screen is only reachable from the pre-validated picker path (useAttachmentPicker.onFilesValidated), so it now trusts the validated params and derives validFiles/source directly. This also removes a duplicated useNavigateToReportOnRefresh call — the same hook was invoked twice, and two identical effects racing Navigation.goBack can over-pop the stack on the refresh path.
  2. Parallel decoding. useFilesValidation validated the whole batch with Promise.all, so peak memory scaled with the number of selected files (3 concurrent full-size decodes instead of one). Validation now runs sequentially, bounding the peak to a single decoded image regardless of how many files were selected.
  3. Orphaned object URLs. validateAttachmentFile overwrote file.uri with a fresh object URL without revoking the previous one, so each superseded blob: URL kept its full-size Blob resident until the document died. The superseded URL is now revoked.

Fixed Issues

$ #92108
PROPOSAL: #92108 (comment)

Tests

  1. Open any report.
  2. Click + (compose) → Add attachment → choose 3 photos (use large, full-resolution photos).
  3. Verify the send-attachment preview opens showing all 3 images and the page does not reload.
  4. Click Send. Verify all 3 attachments post to the report.
  5. Repeat steps 2–4 with a single photo and verify the single-attachment flow still works.
  6. Repeat steps 2–4 attaching a mix of a photo and a PDF and verify both preview and send correctly.
  7. Failure scenario: attempt to attach a file larger than 24 MB and verify the "Attachment too large" error modal appears.
  8. iOS mWeb Safari (the platform from the issue): repeat steps 2–4 with 3 large camera-roll photos and verify the tab does not reload and the attachments are sent.
  • Verify that no errors appear in the JS console

Offline tests

  1. Go offline.
  2. Open a report → +Add attachment → choose 3 photos.
  3. Verify the preview opens and sending queues the attachments in the report (shown as pending).
  4. Go back online and verify the attachments upload and render in the report.

QA Steps

Same as Tests.

  • Verify that no errors appear in the JS console

PR Author Checklist

  • I linked the correct issue in the ### Fixed Issues section above
  • I wrote clear testing steps that cover the changes made in this PR
    • I added steps for local testing in the Tests section
    • I added steps for the expected offline behavior in the Offline steps section
    • I added steps for Staging and/or Production testing in the QA steps section
    • I added steps to cover failure scenarios (i.e. verify an input displays the correct error message if the entered data is not correct)
    • I turned off my network connection and tested it while offline to ensure it matches the expected behavior (i.e. verify the default avatar icon is displayed if app is offline)
    • I tested this PR with a High Traffic account against the staging or production API to ensure there are no regressions (e.g. long loading states that impact usability).
  • I included screenshots or videos for tests on all platforms
  • I ran the tests on all platforms & verified they passed on:
    • Android: Native
    • Android: mWeb Chrome
    • iOS: Native
    • iOS: mWeb Safari
    • MacOS: Chrome / Safari
  • I verified there are no console errors (if there's a console error not related to the PR, report it or open an issue for it to be fixed)
  • I followed proper code patterns (see Reviewing the code)
    • I verified that any callback methods that were added or modified are named for what the method does and never what callback they handle (i.e. toggleReport and not onIconClick)
    • I verified that comments were added to code that is not self explanatory
    • I verified that any new or modified comments were clear, correct English, and explained "why" the code was doing something instead of only explaining "what" the code was doing.
    • I verified any copy / text shown in the product is localized by adding it to src/languages/* files and using the translation method
    • I verified all numbers, amounts, dates and phone numbers shown in the product are using the localization methods
    • I verified any copy / text that was added to the app is grammatically correct in English. It adheres to proper capitalization guidelines (note: only the first word of header/labels should be capitalized), and is either coming verbatim from figma or has been approved by marketing (in order to get marketing approval, ask the Bug Zero team member to add the Waiting for copy label to the issue)
    • I verified proper file naming conventions were followed for any new files or renamed files. All non-platform specific files are named after what they export and are not named "index.js". All platform-specific files are named for the platform the code supports as outlined in the README.
    • I verified the JSDocs style guidelines (in STYLE.md) were followed
  • If a new code pattern is added I verified it was agreed to be used by multiple Expensify engineers
  • I followed the guidelines as stated in the Review Guidelines
  • I tested other components that can be impacted by my changes (i.e. if the PR modifies a shared library or component like Avatar, I verified the components using Avatar are working as expected)
  • I verified all code is DRY (the PR doesn't include any logic written more than once, with the exception of tests)
  • I verified any variables that can be defined as constants (ie. in CONST.ts or at the top of the file that uses the constant) are defined as such
  • I verified that if a function's arguments changed that all usages have also been updated correctly
  • If any new file was added I verified that:
    • The file has a description of what it does and/or why is needed at the top of the file if the code is not self explanatory
  • If a new CSS style is added I verified that:
    • A similar style doesn't already exist
    • The style can't be created with an existing StyleUtils function (i.e. StyleUtils.getBackgroundAndBorderStyle(theme.componentBG))
  • If new assets were added or existing ones were modified, I verified that:
    • The assets are optimized and compressed (for SVG files, run npm run compress-svg)
    • The assets load correctly across all supported platforms.
  • If the PR modifies code that runs when editing or sending messages, I tested and verified there is no unexpected behavior for all supported markdown - URLs, single line code, code blocks, quotes, headings, bold, strikethrough, and italic.
  • If the PR modifies a generic component, I tested and verified that those changes do not break usages of that component in the rest of the App (i.e. if a shared library or component like Avatar is modified, I verified that Avatar is working as expected in all cases)
  • If the PR modifies a component related to any of the existing Storybook stories, I tested and verified all stories for that component are still working as expected.
  • If the PR modifies a component or page that can be accessed by a direct deeplink, I verified that the code functions as expected when the deeplink is used - from a logged in and logged out account.
  • If the PR modifies the UI (e.g. new buttons, new UI components, changing the padding/spacing/sizing, moving components, etc) or modifies the form input styles:
    • I verified that all the inputs inside a form are aligned with each other.
    • I added Design label and/or tagged @Expensify/design so the design team can review the changes.
  • If a new page is added, I verified it's using the ScrollView component to make it scrollable when more elements are added to the page.
  • I added unit tests for any new feature or bug fix in this PR to help automatically prevent regressions in this user flow.
  • If the main branch was merged into this PR after a review, I tested again and verified the outcome was still expected according to the Test steps.

Screenshots/Videos

Android: Native

N/A — the only available test account is SAML-required, and a known unrelated app bug (#86705) signs the session out ~15s after login, before the multi-step attachment flow completes, so a full native recording can't be captured. This fix is platform-agnostic JavaScript (attachment validation/memory handling); the behavior is demonstrated on Web, both mWeb platforms, and iOS Native above.

Android: mWeb Chrome
92108_android_mweb.mp4
iOS: Native
92108_ios_native_small.mp4
iOS: mWeb Safari
92108_ios_mweb_small.mp4
MacOS: Chrome / Safari

https://github.com/user-attachments/assets/c441b646-7817-4ede-bc20-d9d307e73c8b Offline test: https://github.com/user-attachments/assets/c4942472-829e-427c-a65b-763ac2118678

- 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
@trasnake87
trasnake87 requested review from a team as code owners June 11, 2026 01:29
@melvin-bot
melvin-bot Bot requested review from JmillsExpensify and ZhenjaHorbach and removed request for a team June 11, 2026 01:30
@melvin-bot

melvin-bot Bot commented Jun 11, 2026

Copy link
Copy Markdown

@ZhenjaHorbach Please copy/paste the Reviewer Checklist from here into a new comment on this PR and complete it. If you have the K2 extension, you can simply click: [this button]

@melvin-bot
melvin-bot Bot removed the request for review from a team June 11, 2026 01:30
@codecov

codecov Bot commented Jun 11, 2026

Copy link
Copy Markdown

Codecov Report

❌ Looks like you've decreased code coverage for some files. Please write tests to increase, or at least maintain, the existing level of code coverage. See our documentation here for how to interpret this table.

Files with missing lines Coverage Δ
src/libs/validateAttachmentFile.ts 97.50% <100.00%> (+2.90%) ⬆️
...s/report/ReportAddAttachmentModalContent/index.tsx 0.00% <0.00%> (ø)
...rc/components/Attachments/AttachmentView/index.tsx 51.14% <25.00%> (-1.80%) ⬇️
src/hooks/useFilesValidation.tsx 34.37% <18.75%> (+0.83%) ⬆️
... and 632 files with indirect coverage changes

@JmillsExpensify JmillsExpensify left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

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.
@ZhenjaHorbach

Copy link
Copy Markdown
Contributor

Sorry for the delay
@trasnake87
Could you fix the conflicts, please?

# Conflicts:
#	config/eslint/eslint.seatbelt.tsv
@trasnake87

Copy link
Copy Markdown
Contributor Author

@ZhenjaHorbach done 👍 — merged main and resolved the conflict (just the eslint.seatbelt.tsv baseline; took the union). Branch is mergeable again at fc93e344, and everything's green locally (typecheck, ESLint, Prettier, and the attachment suites — ValidateAttachmentFileTest + ReportAttachments, 64 tests). Ready for your review whenever you have a moment — thanks!

@JmillsExpensify JmillsExpensify left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't think a product review is required for this one.

@trasnake87

Copy link
Copy Markdown
Contributor Author

Hi @ZhenjaHorbach 👋 Friendly bump — I resolved the conflicts you flagged (head fc93e344), and the PR's ready for your review. Everything's green now except the Reviewer Checklist itself, which is yours to complete. Whenever you have a chance to do the C+ review, thanks!

@ZhenjaHorbach

Copy link
Copy Markdown
Contributor

Will check tomorrow morning!

@ZhenjaHorbach

ZhenjaHorbach commented Jun 18, 2026

Copy link
Copy Markdown
Contributor

Reviewer Checklist

  • I have verified the author checklist is complete (all boxes are checked off).
  • I verified the correct issue is linked in the ### Fixed Issues section above
  • I verified testing steps are clear and they cover the changes made in this PR
    • I verified the steps for local testing are in the Tests section
    • I verified the steps for Staging and/or Production testing are in the QA steps section
    • I verified the steps cover any possible failure scenarios (i.e. verify an input displays the correct error message if the entered data is not correct)
    • I turned off my network connection and tested it while offline to ensure it matches the expected behavior (i.e. verify the default avatar icon is displayed if app is offline)
  • I checked that screenshots or videos are included for tests on all platforms
  • I included screenshots or videos for tests on all platforms
  • I verified that the composer does not automatically focus or open the keyboard on mobile unless explicitly intended. This includes checking that returning the app from the background does not unexpectedly open the keyboard.
  • I verified tests pass on all platforms & I tested again on:
    • Android: HybridApp
    • Android: mWeb Chrome
    • iOS: HybridApp
    • iOS: mWeb Safari
    • MacOS: Chrome / Safari
  • If there are any errors in the console that are unrelated to this PR, I either fixed them (preferred) or linked to where I reported them in Slack
  • I verified proper code patterns were followed (see Reviewing the code)
    • I verified that any callback methods that were added or modified are named for what the method does and never what callback they handle (i.e. toggleReport and not onIconClick).
    • I verified that comments were added to code that is not self explanatory
    • I verified that any new or modified comments were clear, correct English, and explained "why" the code was doing something instead of only explaining "what" the code was doing.
    • I verified any copy / text that was added to the app is grammatically correct in English. It adheres to proper capitalization guidelines (note: only the first word of header/labels should be capitalized), and is either coming verbatim from figma or has been approved by marketing (in order to get marketing approval, ask the Bug Zero team member to add the Waiting for copy label to the issue)
  • If a new code pattern is added I verified it was agreed to be used by multiple Expensify engineers
  • I verified that this PR follows the guidelines as stated in the Review Guidelines
  • I verified other components that can be impacted by these changes have been tested, and I retested again (i.e. if the PR modifies a shared library or component like Avatar, I verified the components using Avatar have been tested & I retested again)
  • If a new component is created I verified that:
    • A similar component doesn't exist in the codebase
    • All props are defined accurately and each prop has a /** comment above it */
    • The file is named correctly
    • The component has a clear name that is non-ambiguous and the purpose of the component can be inferred from the name alone
    • The only data being stored in the state is data necessary for rendering and nothing else
    • For Class Components, any internal methods passed to components event handlers are bound to this properly so there are no scoping issues (i.e. for onClick={this.submit} the method this.submit should be bound to this in the constructor)
    • Any internal methods bound to this are necessary to be bound (i.e. avoid this.submit = this.submit.bind(this); if this.submit is never passed to a component event handler like onClick)
    • All JSX used for rendering exists in the render method
    • The component has the minimum amount of code necessary for its purpose, and it is broken down into smaller components in order to separate concerns and functions
  • If any new file was added I verified that:
    • The file has a description of what it does and/or why is needed at the top of the file if the code is not self explanatory
  • If a new CSS style is added I verified that:
    • A similar style doesn't already exist
    • The style can't be created with an existing StyleUtils function (i.e. StyleUtils.getBackgroundAndBorderStyle(theme.componentBG)
  • If the PR modifies code that runs when editing or sending messages, I tested and verified there is no unexpected behavior for all supported markdown - URLs, single line code, code blocks, quotes, headings, bold, strikethrough, and italic.
  • If the PR modifies a generic component, I tested and verified that those changes do not break usages of that component in the rest of the App (i.e. if a shared library or component like Avatar is modified, I verified that Avatar is working as expected in all cases)
  • If the PR modifies a component related to any of the existing Storybook stories, I tested and verified all stories for that component are still working as expected.
  • If the PR modifies a component or page that can be accessed by a direct deeplink, I verified that the code functions as expected when the deeplink is used - from a logged in and logged out account.
  • If the PR modifies the UI (e.g. new buttons, new UI components, changing the padding/spacing/sizing, moving components, etc) or modifies the form input styles:
    • I verified that all the inputs inside a form are aligned with each other.
    • I added Design label and/or tagged @Expensify/design so the design team can review the changes.
  • For any bug fix or new feature in this PR, I verified that sufficient unit tests are included to prevent regressions in this flow.
  • If the main branch was merged into this PR after a review, I tested again and verified the outcome was still expected according to the Test steps.
  • I have checked off every checkbox in the PR reviewer checklist, including those that don't apply to this PR.

Screenshots/Videos

Android: HybridApp
IMG_2685.MP4
Android: mWeb Chrome
IMG_2684.MP4
iOS: HybridApp
IMG_2685.MP4
iOS: mWeb Safari
IMG_2684.MP4
MacOS: Chrome / Safari
2026-07-08.10.44.31.mov

@ZhenjaHorbach

Copy link
Copy Markdown
Contributor

Looks like on iOS web attachments don't work

2026-06-18.14.32.59.mov

@trasnake87

Copy link
Copy Markdown
Contributor Author

Thanks for testing this and grabbing the video, @ZhenjaHorbach 🙏

I dug into that red screen. It's a SecurityError: Blocked a frame with origin … from accessing a cross-origin frame, and the call stack is addValueToProperties → addObjectDiffProperties → logComponentRender → commitPassiveMountOnFiber. That path is React's dev profiling build serializing component render data for the performance timeline — and when that walk reaches our Group-IB fraud-detection iframe (//eu.id.group-ib.com/id.html, injected app-wide by FraudProtection/GroupIBSdkBridge), the cross-origin access throws. It's a dev-build-only profiling artifact, and the overlay is dismissable ("Error 1 of 2" → Close).

It isn't coming from this PR's changes: the diff only touches validation scheduling (sequential vs Promise.all) and object-URL lifecycle — none of the changed files reference iframes, windows, the fraud SDK, or React profiling. If anything it reduces render churn (useMemo replacing a setState-after-async-validation, plus removing a duplicate effect), so it makes that profiling path fire less often, not more.

The attachments themselves do work — in your own video the carousel renders the photos both before and after the overlay (waterfall → flowers), and I reproduced the flow on iOS Safari/WebKit on this branch with attachments rendering correctly and no error.

Could you double-check whether the same SecurityError shows up on main when adding attachments in the dev build? I'm fairly sure it's pre-existing and unrelated to this PR, but happy to pair on it. And if you saw the attachments actually fail to render (beyond the overlay), let me know the exact step and I'll dig back in.

@ZhenjaHorbach

ZhenjaHorbach commented Jun 21, 2026

Copy link
Copy Markdown
Contributor

Thanks for testing this and grabbing the video, @ZhenjaHorbach 🙏

I dug into that red screen. It's a SecurityError: Blocked a frame with origin … from accessing a cross-origin frame, and the call stack is addValueToProperties → addObjectDiffProperties → logComponentRender → commitPassiveMountOnFiber. That path is React's dev profiling build serializing component render data for the performance timeline — and when that walk reaches our Group-IB fraud-detection iframe (//eu.id.group-ib.com/id.html, injected app-wide by FraudProtection/GroupIBSdkBridge), the cross-origin access throws. It's a dev-build-only profiling artifact, and the overlay is dismissable ("Error 1 of 2" → Close).

It isn't coming from this PR's changes: the diff only touches validation scheduling (sequential vs Promise.all) and object-URL lifecycle — none of the changed files reference iframes, windows, the fraud SDK, or React profiling. If anything it reduces render churn (useMemo replacing a setState-after-async-validation, plus removing a duplicate effect), so it makes that profiling path fire less often, not more.

The attachments themselves do work — in your own video the carousel renders the photos both before and after the overlay (waterfall → flowers), and I reproduced the flow on iOS Safari/WebKit on this branch with attachments rendering correctly and no error.

Could you double-check whether the same SecurityError shows up on main when adding attachments in the dev build? I'm fairly sure it's pre-existing and unrelated to this PR, but happy to pair on it. And if you saw the attachments actually fail to render (beyond the overlay), let me know the exact step and I'll dig back in.

I'm not talking about the red screen 😅
I'm talking about the fact that when I try to send
Nothing happens

@trasnake87

Copy link
Copy Markdown
Contributor Author

Ah — the Send action itself, not the overlay. Got it, and sorry for chasing the red herring there 😄

Let me reproduce the Send path on this branch (and compare against main) and dig into why it's not firing. I'll follow up with findings shortly.

@trasnake87

Copy link
Copy Markdown
Contributor Author

Thanks for flagging the Send issue — I reproduced it on the iOS Simulator (Mobile Safari) and dug in:

  • On real iOS Safari, tapping Send on the attachment preview does nothing — matches what you saw.
  • I reverted this PR's changes back to main and ran the identical flow on the same simulator — Send still does nothing on main, so it isn't introduced by this PR.
  • On Chrome (desktop + mobile-emulated) the same flow sends fine, so it's WebKit-specific. Consistent with that, this PR doesn't touch the send path — submitAndClose / onConfirm / the composer's addAttachment are all unchanged; it only changes attachment validation + memory handling.

So I don't think this PR should be blocked on it. I'm happy to file a separate issue for the pre-existing iOS-Safari Send behavior and take a crack at the fix. Let me know if the repro details/screenshots would help.

@trasnake87

Copy link
Copy Markdown
Contributor Author

Quick correction on my last comment — I want to be accurate here.

The send itself works on iOS: a real click on the Send button fires the whole flow and the attachment posts (I verified this on the simulator with instrumentation on submitAndCloseonConfirmaddAttachment, and the modal dismisses + the attachment sends). My earlier "tapping Send does nothing" turned out to be my automated tap not landing on the button in the simulator — not a real failure — so please disregard that part.

The key point still stands: this PR doesn't touch the send path, so it isn't a regression from these changes. If you're still seeing Send do nothing with a normal tap on your device, that would be a separate touch-level thing and I'm glad to dig into it with your exact steps.

@trasnake87

Copy link
Copy Markdown
Contributor Author

@ZhenjaHorbach — gentle bump. On the Send behavior you flagged: on my end a normal tap fires the full send flow and the attachment posts, and this PR doesn't touch the send path — but I want to be sure we're not missing something device-specific. If you're still seeing Send do nothing, could you share your device + exact steps and I'll dig back in? Otherwise the OOM reload fix is ready for another review. Thanks! 🙏

@ZhenjaHorbach

Copy link
Copy Markdown
Contributor

Sorry
Missed this PR
Will complete today or tomorrow!

@trasnake87

Copy link
Copy Markdown
Contributor Author

@ZhenjaHorbach — no rush, just keeping this on your radar 🙏 Whenever you get a chance to wrap the review, I'm around to turn anything you find around quickly. Thanks!

@trasnake87

Copy link
Copy Markdown
Contributor Author

@robertjchen @ZhenjaHorbach — two updates:

1. Conflicts resolved ✅ — main's repo-wide Oxfmt formatting sweep collided with this PR's edits in ReportAddAttachmentModalContent. Merged latest main and re-formatted; the PR is mergeable again (head 3b5a5f8, same 4-file surface, no semantic changes).

2. Important: yesterday's adhoc build didn't contain this fix. The build in run 28650145991 was dispatched from main @ 8ab1ea9a — neither this PR's head nor any of its commits are ancestors of that SHA (git merge-base --is-ancestor confirms), so the retest video was exercising main without the fix. That's consistent with it still reproducing 🙂

Could you trigger a fresh adhoc build now that the branch is mergeable? Happy to record the before/after on our side as well once the build's up.

@github-actions

github-actions Bot commented Jul 3, 2026

Copy link
Copy Markdown
Contributor

🚧 robertjchen has triggered a test Expensify/App build. You can view the workflow run here.

@github-actions

This comment has been minimized.

@ZhenjaHorbach

Copy link
Copy Markdown
Contributor

Still have this issue
@trasnake87
An issue not only about photos
But first of all, about PDFs that we added not from the media library on the iPhone

@trasnake87

Copy link
Copy Markdown
Contributor Author

Thanks for the careful retest @ZhenjaHorbach — confirmed, and since this build did contain the fix, this is a real second front we hadn't closed.

Traced it: the merged fix targets the image decode path (validateAttachmentFile → corruption-check/resize only run for images), which is why media-library photos are stable now. PDFs never take that path — each one spins up its own PDF.js engine instead. Two spots let that scale with the batch:

  1. The preview carousel mounts a PDFView (react-fast-pdf <Document>) for every PDF at once — the FlatList renders all 3 on first paint (initialNumToRender={3}) and AttachmentView has no "only the focused page" gate for PDFs — so 3 picked PDFs = 3 full PDF.js document parses live simultaneously. That's enough to blow the WebContent memory budget on iOS Safari and reload the tab.
  2. The pre-navigation PDF validation renders all N PDFThumbnail documents at once — a matching N-way parse spike right before the carousel's.

Fix incoming on this PR: mount the PDF viewer only for the currently-visible carousel item (lightweight placeholder for off-screen ones, gated on the isFocused state the carousel already threads through), and validate PDF thumbnails sequentially — so at most one PDF is parsed at a time regardless of attachment count, mirroring the one-decode-at-a-time approach the image fix already uses. Will update here when it's pushed for a fresh adhoc.

…d PDF validation

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.
@trasnake87

Copy link
Copy Markdown
Contributor Author

Pushed bf7ea9f with both PDF fixes:

  1. Carousel: AttachmentView now mounts the PDF viewer only for the focused carousel item — off-screen PDFs show a lightweight placeholder until swiped to (single-attachment hosts are unaffected; they don't pass isFocused). Live PDF.js documents no longer scale with attachment count.
  2. Validation: the pre-navigation PDFThumbnail checks now run one at a time, advancing as each settles — same sequential principle as the image validation.

Net effect: at most one PDF is parsed at any moment during add-and-preview, regardless of how many are picked. tsc/lint/tests green. @robertjchen could you trigger a fresh adhoc when you get a chance? @ZhenjaHorbach the repro to beat is your exact one — 3 file-picker PDFs on iPhone.

@github-actions

github-actions Bot commented Jul 7, 2026

Copy link
Copy Markdown
Contributor

🚧 robertjchen has triggered a test Expensify/App build. You can view the workflow run here.

@github-actions

This comment has been minimized.

@robertjchen

Copy link
Copy Markdown
Contributor

Let me know how the new adhoc tests 🤞

Comment thread src/libs/validateAttachmentFile.ts Outdated
if (updatedFile.name !== cleanName) {
updatedFile = new File([updatedFile], cleanName, {type: updatedFile.type});
}
const previousUri = updatedFile.uri;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

previousUri is read from updatedFile after it may have been reassigned to a new File via new File([...], cleanName, ...) on line 71, and the new File doesn't carry over the custom .uri property
So the revoke never fires whenever the filename needs cleaning (cleanFileName replaces spaces/unicode/special chars with _ for example, default macOS screenshot names)
In that case, the previous blob URL from AttachmentPicker is never released — part of the memory-leak fix silently doesn't work

So I think it's better to use normalizedFile.uri here

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@trasnake87
Friendly bump

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What about this comment?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Great catch — you're right, and it was worse than cosmetic: the new File(...) reassignment drops the custom .uri, so the revoke silently skipped exactly the cleaned-name files. Fixed in 1ea534d (previousUri now reads from normalizedFile) + added a regression test with a macOS-screenshot-style name that forces the cleaning path. Apologies for missing this thread earlier — the two bumps were on the review thread while I was watching the main conversation.

@ZhenjaHorbach

ZhenjaHorbach commented Jul 8, 2026

Copy link
Copy Markdown
Contributor

But overall, the changes look good

@trasnake87

Copy link
Copy Markdown
Contributor Author

@ZhenjaHorbach Glad the changes look good! Did the 3-PDF retest on the new adhoc come back clean on your iPhone? If so, would you mind completing the reviewer checklist so this can head to merge? Happy to address anything else first.

…es filename cleaning

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.
@trasnake87

Copy link
Copy Markdown
Contributor Author

@ZhenjaHorbach Checking in — the previousUri fix from your catch has been up since Saturday (1ea534d, regression test included) and CI is green. Anything else you'd like addressed before the reviewer checklist? cc @robertjchen in case a fresh adhoc for the 3-PDF retest is the remaining step.

@ZhenjaHorbach

Copy link
Copy Markdown
Contributor

Will recheck today before approving!

@github-actions

Copy link
Copy Markdown
Contributor

🚧 robertjchen has triggered a test Expensify/App build. You can view the workflow run here.

@github-actions

This comment has been minimized.

@ZhenjaHorbach

Copy link
Copy Markdown
Contributor

LGTM

@robertjchen robertjchen left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

thanks!

@github-actions

This comment has been minimized.

@robertjchen
robertjchen merged commit ed8d624 into Expensify:main Jul 16, 2026
36 checks passed
@melvin-bot

melvin-bot Bot commented Jul 16, 2026

Copy link
Copy Markdown

Congrats, that's your 5th PR merged! 🎉 Do you know about the ContributorPlus role? It's an opportunity to earn more in the Expensify Open Source community. Keep up the great work - thanks!

@github-actions

Copy link
Copy Markdown
Contributor

🚧 robertjchen has triggered a test Expensify/App build. You can view the workflow run here.

@OSBotify

Copy link
Copy Markdown
Contributor

✋ This PR was not deployed to staging yet because QA is ongoing. It will be automatically deployed to staging after the next production release.

@OSBotify

Copy link
Copy Markdown
Contributor

🚀 Deployed to staging by https://github.com/robertjchen in version: 9.4.36-0 🚀

platform result
🕸 web 🕸 success ✅
🤖 android 🤖 success ✅
🍎 iOS 🍎 success ✅

@MelvinBot

Copy link
Copy Markdown
Contributor

Help site review: no changes required

I reviewed the changes in this PR against the help site content under docs/articles, and no help site updates are required. I did not create a draft PR.

Why: This PR is an internal memory/performance fix. It prevents the mWeb (iOS Safari) WebContent process from OOM-ing and reloading the tab when several full-resolution photos or PDFs are attached at once. The changes are entirely in the attachment validation/rendering internals:

  • useFilesValidation now validates files sequentially instead of with Promise.all (bounds peak memory to one decode).
  • ReportAddAttachmentModalContent trusts the already-validated params instead of re-decoding.
  • validateAttachmentFile revokes superseded blob: object URLs.
  • AttachmentView only mounts the focused PDF viewer in the carousel.

None of this changes any documented, user-facing behavior — no new features, no renamed tabs/settings/buttons, and no change to the steps a user follows to add an attachment. The "Add attachment" flow works exactly the same from the user's perspective; it just no longer crashes. There is no help article documenting the attachment-selection memory internals, and the attachment-related articles that do exist (e.g. Attach-and-edit-receipts-on-expenses.md, Chat-Features-and-Moderation-Tools.md) describe user workflows that are unaffected here.

⚠️ Note: I could not verify anything in a live browser for this run (browser control was unavailable), so this conclusion is based on static review of the diff and the help site content. Since the PR introduces no user-facing behavior change, browser verification wouldn't alter the docs conclusion.

Since no docs changes are needed, there is no linked help site PR to review.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants