Skip to content

[$250] mWeb - Avatar - Discard changes modal cannot be closed after swiping back and tapping Cancel #92793

Closed

Description

@applause-bot

If you haven’t already, check out our contributing guidelines for onboarding and email contributors@expensify.com to request to join our Slack channel!


Version Number: v9.3.99-9
Reproducible in staging?: Yes
Reproducible in production?: Yes
If this was caught during regression testing, add the test name, ID and link from BrowserStack: https://test-management.browserstack.com/projects/2219752/test-runs/TR-38986/folder/13176687/41236648/1465314600?sort=%2Bidentifier
Email or phone of affected tester (no customers): n/a
Issue reported by: Applause Internal Team
Bug source: Regression TC Execution
Device used: iPhone 13 26.5 Safari/Chrome
App Component: User Settings

Action Performed:

  1. Go to https://staging.new.expensify.com
  2. Navigate to settings by clicking on the user avatar over LHN
  3. Click on Profile
  4. Click on the avatar
  5. Select any Custom Image Avatar
  6. Swipe back and verify a Discard changes? modal is displayed
  7. Tap Cancel

Expected Result:

The Discard changes modal closes and the Edit profile picture appears

Actual Result:

Discard changes modal cannot be closed after swiping back and tapping Cancel

Workaround:

Unknown

Platforms:

  • Android: App
  • Android: mWeb Chrome
  • iOS: App
  • iOS: mWeb Safari
  • iOS: mWeb Chrome
  • Windows: Chrome
  • MacOS: Chrome Safari

Screenshots/Videos

Bug7172757_1780674757775.ScreenRecording_06-05-2026_10-46-07_1.mp4

View all open jobs on GitHub

Applause Internal Information
Exported by: Svetlana Lazutkina
Bug ID: 7172757

Upwork Automation - Do Not Edit

Activity

  1. added
    BugSomething is broken. Auto assigns a BugZero manager.
    on Jun 5, 2026
  2. applause-bot commented on Jun 5, 2026

    @applause-bot
    Author

    While Applause doesn't embed attachments for this bug, here are the links for quick view:
    https://platform.applause.com/services/links/v1/external/be0049962dc88df61a38b9b8e98b5bb8b38a7ba9efdb83d0fe2d2aa7c37de818

  3. MelvinBot commented on Jun 5, 2026

    @MelvinBot
    Contributor

    Proposal

    Generated by MelvinBot · Confidence: High (root cause) / Medium-High (exact fix)

    What is the root cause of that problem?

    The "Discard changes?" modal is opened by two different code paths in useDiscardChangesConfirmation, and only one of them is guarded against re-entry.

    • Header back-button (all platforms) / Android back: goes through React Navigation's beforeRemove event (index.ts:93-114).
    • iOS mWeb Safari swipe-back: the browser-native swipe completes before RN can intercept it, so RN only catches up via popstate → the transitionStart listener (index.ts:121-136). This is the path that shows the modal on swipe-back.

    When the user taps Cancel, the global Modal's hideModal runs a deferred window.history.back() (Modal/index.tsx:63-80) to consume the synthetic {shouldGoBack: true} history entry it pushed when it opened. That history.back() fires popstate, which makes RN fire transitionStart again.

    The transitionStart listener has no re-entry guard — it only checks getHasUnsavedChanges() (still true, because Cancel correctly keeps the form dirty). So it immediately re-runs window.history.go(1) + showDiscardModal() and the modal pops straight back up. The modal can never be dismissed. This is iOS mWeb Safari only because that is the only platform where the modal is opened via transitionStart instead of beforeRemove.

    The recent fix for the sibling issue #86585 (PR #89789) added the shouldIgnoreNextBeforeRemove / markNextBeforeRemoveAsModalCleanup guard — but that guard is only consulted in the beforeRemove path (index.ts:100-104), never in transitionStart. That is why it fixed the header-back-button case but left the iOS swipe-back case broken.

    Step-by-step event timeline (swipe-back → Cancel)
    1. Form is dirty (custom avatar selected). User swipes back in Safari → browser back completes → popstate.
    2. RN fires transitionStart (closing: true). Listener sets shouldNavigateBack.current = true, calls window.history.go(1) to undo the back.
    3. history.go(1) re-fires transitionStart (closing: false) → listener calls navigateAfterInteraction(showDiscardModal) → modal opens; Modal.showModal pushes a {shouldGoBack: true} history entry (Modal/index.tsx:82-92).
    4. User taps Cancel → modal animates closed → Modal.hideModal schedules setTimeout(0) → withInternalPopstate(() => history.back()).
    5. The Cancel .then() resolves: isDiscardModalOpen.current = false, shouldNavigateBack.current = false, onCancel() (index.ts:60-91).
    6. The deferred history.back() fires popstate → RN fires transitionStart again → listener has no guard → re-shows the modal. Loop.

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

    Make the transitionStart listener ignore the navigation event that originates from the Modal's own internal history.back(), exactly the way Popover/index.tsx already does for this same class of re-entrancy.

    There is a purpose-built helper for this: isInternalPopstateInProgress() — it returns true precisely while the Modal's withInternalPopstate(() => history.back()) is running. At the top of the transitionStart listener in useDiscardChangesConfirmation/index.ts:121-136, return early (without history.go(1) or showDiscardModal()) when the popstate is internal. This stops the Cancel-triggered history.back() from re-opening the modal, while still reacting to genuine user swipe-backs.

    What alternative solutions did you explore? (Optional)

    • Mirror the beforeRemove guard: add if (isDiscardModalOpen.current || shouldIgnoreNextBeforeRemove.current) { return; } at the top of the transitionStart listener — reusing the shouldIgnoreNextBeforeRemove flag that markNextBeforeRemoveAsModalCleanup already arms for ~250ms on Cancel. This works because the flag is armed before the deferred history.back() fires, but it is timing-dependent (250ms window); the isInternalPopstateInProgress() approach is deterministic and preferred.
    • shouldHandleNavigationBack: false for the discard modal (explored in the closed PRs Disable modal navigation back handling for discard changes confirmation on mWeb #89391 and Fix confirm modal not showing (loops to Merchant page) #88250) — rejected previously because it breaks the Modal's history bookkeeping.

    Related issues


    Next Steps for Contributor+ team:
    To accept: @MelvinBot implement [this](https://github.com/Expensify/App/issues/92793) to create a draft PR.
    To refine: @MelvinBot <your feedback>
    To reject: Explain why you are rejecting Melvin's proposal.

  4. added
    ExternalAdded to denote the issue can be worked on by a contributor
    on Jun 5, 2026
  5. added
    Help WantedApply this label when an issue is open to proposals by contributors
    on Jun 5, 2026
  6. MobileMage commented on Jun 5, 2026

    @MobileMage
    Contributor

    🚨 Edited by proposal-police: This proposal was edited at 2026-06-05 18:03:04 UTC.

    Proposal

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

    On mWeb Safari, after selecting an avatar on the Edit profile picture page, swiping back to trigger the Discard changes confirmation, and tapping Cancel, the modal briefly animates out and then immediately re-appears. It can never be dismissed via Cancel because each Cancel tap is followed by an instant re-open, leaving the user permanently stuck on the discard prompt.

    What is the root cause of that problem?

    The Discard changes flow on web is driven by useDiscardChangesConfirmation, which listens to React Navigation's transitionStart event to detect browser-level back navigation (e.g. an iOS Safari swipe back) and reopen the page with window.history.go(1) while showing the confirm modal. The confirm modal itself is rendered through useConfirmModal -> ConfirmModalWrapper with shouldHandleNavigationBack: true, which makes Modal/index.tsx push an extra browser history entry tagged shouldGoBack: true when the modal opens and pop it back with withInternalPopstate(() => window.history.back()) when it closes:

    const hideModal = () => {
    window.removeEventListener('popstate', handlePopState);
    if ((window.history.state as WindowState)?.shouldGoBack && shouldHandleNavigationBack) {
    onModalHide();
    // Defer history.back() so it runs after any pending navigation
    // callbacks (from onModalDidClose) have pushed their history entries.
    // This prevents the popstate from undoing navigations triggered by
    // menu item selection callbacks.
    setTimeout(() => {
    if (!(window.history.state as WindowState)?.shouldGoBack) {
    return;
    }
    withInternalPopstate(() => window.history.back());
    }, 0);
    } else {
    onModalHide();
    }
    };

    A recent fix (markNextBeforeRemoveAsModalCleanup) was added precisely to prevent that cleanup history.back() from re-firing the discard modal, by setting shouldIgnoreNextBeforeRemove.current = true for 250ms when the modal closes. The flag is consumed in the useBeforeRemove handler, which guards the in-app navigation path. But on mWeb Safari, the swipe back never goes through beforeRemove (the comment in the hook explicitly states: "We cannot programmatically stop the browser's back navigation like react-navigation's beforeRemove"). It goes through transitionStart instead — and the transitionStart listener has no equivalent guard:

    useEffect(() => {
    const unsubscribe = navigation.addListener('transitionStart', ({data: {closing}}) => {
    if (!getHasUnsavedChanges()) {
    return;
    }
    shouldNavigateBack.current = true;
    if (closing) {
    window.history.go(1);
    return;
    }
    window.history.go(1);
    navigateAfterInteraction(showDiscardModal);
    });
    return unsubscribe;
    }, [navigation, getHasUnsavedChanges, showDiscardModal]);

    So the sequence on Cancel is: (1) ConfirmModalWrapper.handleCancel flips isVisible to false, the modal animates out, and Modal/index.tsx.hideModal schedules withInternalPopstate(() => window.history.back()) in a setTimeout(0). (2) The hook's .then() runs, calling markNextBeforeRemoveAsModalCleanup() (sets shouldIgnoreNextBeforeRemove = true), resetting isDiscardModalOpen.current = false, and clearing shouldNavigateBack.current = false. (3) The deferred history.back() fires popstate; React Navigation's useLinking resets the root to the AvatarPage record, which emits a fresh transitionStart while getHasUnsavedChanges() is still true (the avatar selection lives on selected/imageData state and was never cleared by Cancel). (4) The transitionStart listener doesn't check shouldIgnoreNextBeforeRemove.current or isDiscardModalOpen.current, so it runs window.history.go(1) and immediately calls navigateAfterInteraction(showDiscardModal) again — pushing a brand-new ConfirmModalWrapper onto the global modal stack:

    shouldNavigateBack.current = true;
    if (closing) { window.history.go(1); return; }
    window.history.go(1);
    navigateAfterInteraction(showDiscardModal); // <- fires again after Cancel cleanup

    Visually this looks like Cancel "did nothing": the user's tap closes modal A, but modal B is pushed onto the stack in the same frame, and ModalContext only renders the topmost modal (modalStack.modals.at(-1)), so the prompt never disappears. Every subsequent Cancel just trades modal N for modal N+1.

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

    Extend the existing modal-cleanup suppression so it also short-circuits the transitionStart re-trigger, mirroring what useBeforeRemove already does. The hook already owns shouldIgnoreNextBeforeRemove and the 250ms self-clearing timer set by markNextBeforeRemoveAsModalCleanup — we just need to honor it on the web back path too, and clear it on consumption so it doesn't leak into a real subsequent back gesture. We should also guard against isDiscardModalOpen.current to avoid the edge case where the initial swipe-back popstate chain queues two showDiscardModal calls before the first one mounts.

    Concretely, in src/hooks/useDiscardChangesConfirmation/index.ts, update the transitionStart listener to consume the cleanup flag and bail out, and avoid stacking a second modal:

    navigation.addListener('transitionStart', ({data: {closing}}) => {
        if (!getHasUnsavedChanges()) { return; }
        if (shouldIgnoreNextBeforeRemove.current || isDiscardModalOpen.current) {
            clearShouldIgnoreNextBeforeRemove();
            window.history.go(1); // still revert the browser back
            return;
        }
        shouldNavigateBack.current = true;
        if (closing) { window.history.go(1); return; }
        window.history.go(1);
        navigateAfterInteraction(showDiscardModal);
    });

    This is safe because the suppression flag is already scoped to the post-cancel cleanup window (set inside .then() only when history.state.shouldGoBack === true, auto-cleared after 250ms), so legitimate future back gestures still show the discard modal. The isDiscardModalOpen.current check also protects the in-flight case where beforeRemove already queued showDiscardModal and transitionStart would otherwise stack a duplicate. Other consumers of the hook (IOURequestStepMerchant, IOURequestStepDescription, IOURequestStepDistanceOdometer, EditAgentAvatarPage) all rely on the same modal cleanup path, so they benefit from the fix without any per-caller change.

    What alternative solutions did you explore? (Optional)

    We considered making Modal/index.tsx skip the cleanup withInternalPopstate(() => window.history.back()) entirely when the modal closes via Cancel, but that would break global modals that legitimately rely on the shouldGoBack history entry to recover the URL state after dismissal — too broad. Another option was to gate showDiscardModal itself with an if (isDiscardModalOpen.current) return; early return, but that only blocks duplicate stacking — it doesn't address the post-cancel re-trigger where the flag was already reset to false by the .then() callback before transitionStart fires.

  7. wildan-m commented on Jun 5, 2026

    @wildan-m
    Contributor

    🚫 Duplicated proposal withdrawn by 🤖 ProposalPolice.

  8. melvin-bot commented on Jun 5, 2026

    @melvin-bot

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

  9. changed the title [-]mWeb - Avatar - Discard changes modal cannot be closed after swiping back and tapping Cancel[/-] [+][$250] mWeb - Avatar - Discard changes modal cannot be closed after swiping back and tapping Cancel[/+] on Jun 5, 2026
  10. melvin-bot commented on Jun 5, 2026

    @melvin-bot
  11. github-actions commented on Jun 5, 2026

    @github-actions
    Contributor

    ⚠️ @wildan-m Your proposal is a duplicate of an already existing proposal and has been automatically withdrawn to prevent spam. Please review the existing proposals before submitting a new one.

  12. oqildev commented on Jun 5, 2026

    @oqildev
    Contributor

    🚨 Edited by proposal-police: This proposal was edited at 2026-06-19 11:36:28 UTC.

    Proposal

    What is the root cause of that problem?

    This is iOS mWeb Safari only, and it's a release gap: the 9.3.99-9 build (tag SHA 4ba31d7) ships the old useDiscardChangesConfirmation web hook that has no protection against a second beforeRemove firing after the user taps Cancel.

    The Profile → Avatar screen renders inside an RHP modal and wires the discard guard with getHasUnsavedChanges: () => !isSavingRef.current && isDirty, where isDirty stays true for any selected/uploaded avatar — AvatarPage.tsx#L44-L48.

    When that RHP modal opens, Modal.showModal pushes a history entry tagged {shouldGoBack: true}, and on close it defers a history.back() to reconcile it — Modal/index.tsx#L63-L92. The swipe-back gesture is a browser POP, so the history is mid-cleanup when the discard flow starts.

    The break is in the web hook's useBeforeRemove handler — index.ts#L64-L71. Its only early-out is !getHasUnsavedChanges() || shouldNavigateBack.current; otherwise it calls e.preventDefault() + navigateAfterInteraction(showDiscardModal). The Cancel branch — index.ts#L56-L62 — only resets blockedNavigationAction/shouldNavigateBack and calls onCancel. It sets no flag to suppress the next event.

    So the sequence is:

    1. Swipe back → beforeRemove fires → unsaved changes → discard modal shows.
    2. Tap Cancel → modal resolves, shouldNavigateBack reset to false, but the avatar is still selected so getHasUnsavedChanges() is still true.
    3. The RHP modal's deferred history.back() / popstate reconciliation (the {shouldGoBack: true} entry) fires a second beforeRemove. It re-enters L64-71, passes the early-out, preventDefault()s and calls showDiscardModal() again → the modal immediately re-appears.

    To the user, Cancel does nothing and the modal can't be dismissed. This is web-specific because the native hook (index.native.ts) doesn't use this popstate/transitionStart machinery.

    The fix for exactly this symptom already exists on main (merged mid-May, commit b68f37c, preceded by 462b3d5/5ae96ba) but the 9.3.99-9 release branch diverged and doesn't contain it.

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

    Layer: the hook (src/hooks/useDiscardChangesConfirmation/index.ts). The render/modal layer is fine — the problem is the re-entrant beforeRemove.

    Bring the guard that's already on main into this release. It adds two pieces:

    • An isDiscardModalOpen ref and a shouldIgnoreNextBeforeRemove ref. In useBeforeRemove, if either is set, preventDefault() and return without calling showDiscardModal — see index.ts#L93-L114 @ b68f37c.
    • markNextBeforeRemoveAsModalCleanup() (called in the modal's .then, before branching) which, only when window.history.state.shouldGoBack === true, arms shouldIgnoreNextBeforeRemove and auto-clears it after 250ms — index.ts#L34-L47 @ b68f37c and the call site at index.ts#L60-L72.

    Net effect: the spurious post-cancel beforeRemove triggered by the RHP modal's history cleanup is swallowed instead of re-opening the discard modal, so Cancel returns the user to the avatar editor as expected. The shouldGoBack === true gate keys precisely on the RHP modal's guard entry, so non-RHP discard flows (e.g. central-pane) are unaffected, and the timeout prevents a stale flag from suppressing a legitimate later back press.

    So the concrete ask is: cherry-pick / re-merge b68f37c (with its prerequisites) onto the 9.3.99 release, or confirm why it was excluded if the divergence was intentional.

    What alternative solutions did you explore? (Optional)

    Pass shouldHandleNavigationBack to the discard ConfirmModal so it manages its own history entry symmetrically with the RHP. Rejected: the discard modal is deliberately shown with only shouldIgnoreBackHandlerDuringTransition: true and no shouldHandleNavigationBack — index.ts#L36-L42. Adding a second {shouldGoBack} guard entry on top of the RHP's would create competing history.back() calls and a worse history tangle; the real defect is that the hook never suppresses the re-entrant beforeRemove, which is what the main fix addresses directly.

    Gate on getHasUnsavedChanges() differently (e.g. clear isDirty on Cancel). Rejected: that would discard the user's selection, which is the opposite of what Cancel should do — the user explicitly chose to keep editing, so the data must stay dirty.

  13. 37 remaining items

  14. melvin-bot commented on Jul 1, 2026

    @melvin-bot

    @abdulrahuman5196 10 days overdue. Is anyone even seeing these? Hello?

  15. mvtglobally commented on Jul 3, 2026

    @mvtglobally

    Issue not reproducible during KI retests. (Third week)

  16. melvin-bot commented on Jul 3, 2026

    @melvin-bot

    📣 It's been a week! Do we have any satisfactory proposals yet? Do we need to adjust the bounty for this issue? 💸

  17. melvin-bot commented on Jul 3, 2026

    @melvin-bot

    @abdulrahuman5196 this issue is now 4 weeks old, please consider:

    • Finding a contributor to fix the bug
    • Closing the issue if BZ has been unable to add the issue to a VIP or Wave project
    • If you have any questions, don't hesitate to start a discussion in #expensify-open-source

    Thanks!

  18. melvin-bot commented on Jul 3, 2026

    @melvin-bot

    @abdulrahuman5196 12 days overdue. Walking. Toward. The. Light...

  19. melvin-bot commented on Jul 4, 2026

    @melvin-bot

    @abdulrahuman5196 12 days overdue now... This issue's end is nigh!

  20. melvin-bot commented on Jul 6, 2026

    @melvin-bot

    This issue has not been updated in over 14 days. @abdulrahuman5196 eroding to Weekly issue.

  21. melvin-bot commented on Jul 10, 2026

    @melvin-bot

    📣 It's been a week! Do we have any satisfactory proposals yet? Do we need to adjust the bounty for this issue? 💸

  22. mvtglobally commented on Jul 11, 2026

    @mvtglobally

    Issue not reproducible during KI retests. (Fourth week)

  23. abdulrahuman5196 commented on Jul 12, 2026

    @abdulrahuman5196
    Contributor

    Issue not reproducible during KI retests. (Fourth week)

    QA also not reproducing, asking in slack to close.

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

Metadata

Metadata

Labels

BugSomething is broken. Auto assigns a BugZero manager.ExternalAdded to denote the issue can be worked on by a contributorHelp WantedApply this label when an issue is open to proposals by contributorsWeeklyKSv2

Type

No type

Projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions