App icon indicating copy to clipboard operation
App copied to clipboard

[Due for payment 2026-11-20] [$250] Chrome - 2FA - Clicking Download codes, closes the 2FA page

Open applause-bot[bot] opened this issue 5 months ago • 78 comments

If you haven’t already, check out our contributing guidelines for onboarding and email [email protected] to request to join our Slack channel!


Version Number: v9.3.98-0 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-37778/folder/13176687/41236669/1459452159?sort=%2Bidentifier Email or phone of affected tester (no customers): n/a Issue reported by: Applause Internal Team Bug source: Exploratory - Significant User Experience Deterioration Device used: Mac 16.4.1 Chrome App Component: User Settings

Action Performed:

  1. Go to https://staging.new.expensify.com
  2. Navigate to Account > Security > Two Factor Authentication (2FA)
  3. Click on "Download codes"
  4. If the issue does not reproduce on the first attempt, repeat steps 2–3

Expected Result:

After saving the codes, the next page containing the QR code should be displayed

Actual Result:

After clicking ‘Download codes’, the 2FA page closes instead of navigating to the QR code page. Note:

  • Only repro on macOS/Chrome, and not repro on Windows 11/Chrome
  • Repro when there is save confirmation modal that appears

Workaround:

Unknown

Platforms:

  • [ ] Android: App
  • [ ] Android: mWeb Chrome
  • [ ] iOS: App
  • [ ] iOS: mWeb Safari
  • [ ] iOS: mWeb Chrome
  • [ ] Windows: Chrome
  • [x] MacOS: Chrome Safari

Screenshots/Videos

https://github.com/user-attachments/assets/54e50f55-51e1-4ab7-957b-5d89b1764005

View all open jobs on GitHub

Applause Internal Information Exported by: Rizky Gunawan Bug ID: 7170624

Upwork Automation - Do Not Edit
Issue OwnerCurrent Issue Owner: @parasharrajat

applause-bot[bot] avatar Jun 03 '26 18:06 applause-bot[bot]

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

applause-bot[bot] avatar Jun 03 '26 18:06 applause-bot[bot]

Proposal

What is the root cause of that problem?

The 2FA RHP doesn't actually close — the Verify (QR) page renders a "not here" / Not-Found view instead of the QR code, which looks identical to a dismissed RHP.

The "Download codes" handler does two things in the wrong order:

  1. It calls setCodesAreCopied(), which is an async Onyx.merge of codesAreCopied: true.
  2. It synchronously navigates to the Verify page.

But the Verify step is gated: TwoFactorAuthWrapper shows a FullPageNotFoundView whenever !account.codesAreCopied. Because navigation fires before the Onyx.merge has propagated to subscribers, the Verify page mounts while codesAreCopied is still false, so the guard shows the not-found view.

Why only macOS Chrome + the native "Save As" dialog: localFileDownload fires link.click() inside a microtask. On macOS the "ask where to save" dialog opens as a separate OS window and blurs the browser tab. Chromium throttles rendering/timers of a blurred tab, which delays the Onyx-driven re-render that would flip codesAreCopied to true and clear the guard — so the not-found view stays on screen. Windows Chrome's download prompt is a child window that doesn't steal focus the same way, so the re-render isn't throttled and the guard clears before it's ever visible. This also explains why it's intermittent ("repeat steps 2–3 if it doesn't repro").

There is no code path that actively dismisses the RHP on download or on window blur — confirmed by tracing forceReplace (a plain React-Navigation REPLACE, no pop) and all blur/visibilitychange/AppState listeners. So the fix is purely about the navigation/Onyx ordering.

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

Navigate to the Verify page only after the codesAreCopied write is committed, rather than synchronously:

  • Have setCodesAreCopied() return its Onyx.merge promise, and move the Navigation.navigate(...VERIFY..., {forceReplace: true}) call into that promise's .then() in the Download-codes handler.

This guarantees the Verify guard reads codesAreCopied === true at mount, so the QR page renders regardless of background-tab render throttling.

What alternative solutions did you explore? (Optional)

  • Relax the Verify guard (e.g. also accept twoFactorAuthSetupInProgress, which the same merge sets). Reasonable as defense-in-depth, but on its own it's a workaround — the guard exists to block deep-linking straight to Verify, and the real bug is the ordering. Best paired with the ordering fix, not used instead of it.
Code references (sha 1a25481)

This 2FA flow was migrated to the "Dynamic" pages in late May 2026 (file first added ~2026-05-08), and this issue was filed 2026-06-03 — so this is most likely a regression from that migration.

Confidence: High on the root cause (the navigate-before-Onyx.merge race + the Verify guard — strong code evidence). Medium on the exact macOS-only explanation (blurred-tab render throttling), which can't be reproduced in a headless environment and would benefit from runtime confirmation.

Possibly related: https://github.com/Expensify/App/issues/92544 — "After clicking Got it, the Two-factor authentication RHP is closed" (same flow/era; may share this guard/ordering class of bug).


Next Steps for Contributor+ team: To accept: @MelvinBot implement this to create a draft PR. To refine: @MelvinBot <your feedback> To reject: Explain why you are rejecting Melvin's proposal.

MelvinBot avatar Jun 03 '26 18:06 MelvinBot

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

Proposal

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

On macOS Chrome, clicking "Download codes" on the 2FA recovery-codes step closes the entire 2FA right-hand panel. Focus returns to Account > Security instead of advancing to the QR / Verify step. Windows Chrome and the native mobile builds render the QR step correctly.

What is the root cause of that problem?

The Download click dispatches a forceReplace navigation to the Verify step in the same synchronous tick as setCodesAreCopied() and localFileDownload(...):

https://github.com/Expensify/App/blob/753ada2f46facc924a340c6e85b76941196dc911/src/pages/settings/Security/TwoFactorAuth/DynamicTwoFactorAuthPage.tsx#L183-L189

forceReplace: true produces a REPLACE action so VERIFY lands in the modal stack in place of COPY_CODES. React Navigation's web linking integration runs its state-to-URL reconciliation via useLinking.onStateChange (in node_modules/@react-navigation/native/lib/module/useLinking.js, around line 373 in v7.1.33). Because REPLACE must not grow browser history, the reconciliation calls await history.go(-1) on the package-internal createMemoryHistory, then pushState(/verify) to write the new URL at the back-navigated position.

createMemoryHistory.go(n) wraps window.history.go(n) with a pending queue and a 100 ms safety timeout (same package, createMemoryHistory.js around line 197). The contract is: when the browser's popstate arrives in time, the pending entry is consumed and createMemoryHistory.listen's registered popstate handler filters the event from useLinking's listener (since it was internally initiated). When the popstate arrives later than 100 ms, the safety timeout drains the pending entry first, and the delayed popstate is delivered as if it were a user-initiated back / forward.

useLinking's listener then handles the URL /settings/security that the browser is now sitting at, finds a record.state cached for that path from before the user entered 2FA, and calls navigation.resetRoot(record.state). That reset state has no RightModalNavigator in it, so the TWO_FACTOR_AUTH RHP screen is unmounted. The beforeRemove listener registered on the RHP screen fires clearTwoFactorAuthData(true):

https://github.com/Expensify/App/blob/753ada2f46facc924a340c6e85b76941196dc911/src/libs/Navigation/AppNavigator/Navigators/RightModalNavigator.tsx#L235-L243

That clears the recovery codes and resets codesAreCopied to false. The user sees Account > Security again, with the entire 2FA right-hand panel gone.

Verified at runtime by instrumenting window.history.go / pushState / replaceState, createMemoryHistory.listen, and the branches inside useLinking. Two consecutive Download clicks produced two outcomes:

  • Run that succeeded: after the navigate, history.go(-1) was called from useLinking.onStateChange. The browser popstate arrived with pendingLength: 1 and was filtered. pushState(/verify) settled the URL. The RHP stayed open and the QR step rendered.
  • Run that failed: the same history.go(-1) was called. The 100 ms safety timeout drained pending. The popstate then arrived with pendingLength: 0, was treated as external, and entered useLinking's BRANCH=record-match. resetRoot(record.state) ran with the cached /settings/security state, which removed the RHP.

The only variable between the two runs was when the browser delivered the popstate. macOS Chrome with the native "ask where to save" dialog reliably extends that delay because the dialog blurs the tab, but the race also fires without the dialog when the click tick is heavy enough (file-blob creation, Onyx.merge, multiple renders in one task) to push popstate past the 100 ms window. The save dialog in the Applause repro is one source of the delay, not the cause; that is why the issue is intermittent ("repeat steps 2 to 3 if it does not repro").

The two empirically observed escape valves both reduce or remove the race rather than masking a downstream symptom:

  • Clicking Copy before Download. setCodesAreCopied then merges values equal to current Onyx state, the click tick stays light, and popstate arrives inside the 100 ms window. No bug.
  • Removing forceReplace: true. The navigate becomes PUSH, useLinking writes the new URL through pushState, and createMemoryHistory.go(-1) is never called. No race window exists.

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

Drop forceReplace: true from the Navigation.navigate(...VERIFY...) call in the Download-codes handler. Without forceReplace, the action stays as the default navigate behavior, useLinking's state-to-URL sync writes the new URL through pushState, and the createMemoryHistory.go(-1) -versus- popstate race cannot occur. The Verify step renders, the RHP stays open, the download still fires from the synchronous click handler so the user-gesture flag for the anchor click is preserved.

Manual verification with the change applied: file downloads, QR page renders behind any save dialog and stays after dismissal, back from Verify returns to Step 1 (Recovery codes) which matches the natural back behavior of a two-step form. The original forceReplace: true did not deliver any user-visible different back behavior in practice, because the bug it triggered removed the entire RHP before any back press could exercise that intent.

What alternative solutions did you explore? (Optional)

  • Defer the navigate by one task with setTimeout(0) or Navigation.isNavigationReady().then(...). Rejected. Tested at runtime and the RHP still closed. The race is between createMemoryHistory's internal 100 ms timer and the browser popstate, neither of which is influenced by deferring the navigate by one macrotask.

  • Have setCodesAreCopied return its Onyx.merge promise and chain the navigate via .then(...). Rejected as a primary fix. It reduces the click-tick workload enough to make popstate arrive within 100 ms in some runs, but it does not remove the race. Any other source of JS thread contention (file blob creation, GC pause, focus loss from the save dialog) re-opens the window. Only avoiding history.go(-1) removes the race entirely.

MobileMage avatar Jun 03 '26 18:06 MobileMage

Proposal

What is the root cause of that problem?

In DynamicTwoFactorAuthPage, clicking Download codes starts a browser download via localFileDownload() and also immediately forceReplaces the 2FA RHP to the verify/QR route.

On macOS Chrome, when the download triggers Chrome’s native save confirmation dialog, that dialog steals focus while the right-modal route replacement is still in progress. This creates a race between the native download prompt and the RHP navigation transition, so when focus returns the 2FA modal can be dismissed/closed instead of reliably settling on the QR verification page.

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

Decouple the browser-native download prompt from the active RHP transition.

In DynamicTwoFactorAuthPage, first update the 2FA flow state and navigate to the verify/QR route, then trigger the file download from the navigation afterTransition callback:

setError('');
setCodesAreCopied();
announceStatus(translate('fileDownload.success.title'));

Navigation.navigate(createDynamicRoute(DYNAMIC_ROUTES.TWO_FACTOR_AUTH_VERIFY.path, backPath), {
    forceReplace: true,
    afterTransition: () => {
        localFileDownload(TWO_FACTOR_AUTH_RECOVERY_CODES_FILENAME, recoveryCodes, translate, undefined, undefined, false);
    },
});

This ensures the QR page is already mounted before Chrome shows the save dialog. After the user saves/confirms the file, focus returns to the settled verify route instead of racing the modal replacement.

I would also update localFileDownload to mirror the shared web download helper more closely: append the temporary anchor to document.body, hide it, click it, then remove it and revoke the object URL after the click. That makes local blob downloads behave consistently with the existing fileDownload path.

Tests:

  • Add/adjust a unit test for the 2FA download button to verify it navigates to TWO_FACTOR_AUTH_VERIFY with forceReplace and an afterTransition callback.
  • Invoke the callback in the test and assert localFileDownload is called with the recovery-code filename/content.
  • Manually verify on macOS Chrome with download confirmation enabled: Account > Security > 2FA > Download codes, confirm save, QR code page remains visible.

What alternative solutions did you explore? (Optional)

A simple setTimeout around the download would reduce the race, but it would still depend on timing and animation duration. Using afterTransition is deterministic and matches the existing navigation API for work that must happen after an RHP transition completes.

moxw avatar Jun 03 '26 18:06 moxw

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

melvin-bot[bot] avatar Jun 03 '26 18:06 melvin-bot[bot]

🚫 Duplicated proposal withdrawn by 🤖 ProposalPolice.

aswin-s avatar Jun 03 '26 18:06 aswin-s

Job added to Upwork: https://www.upwork.com/jobs/~022062240227867818938

melvin-bot[bot] avatar Jun 03 '26 18:06 melvin-bot[bot]

⚠️ @aswin-s 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.

github-actions[bot] avatar Jun 03 '26 18:06 github-actions[bot]

Proposal

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

On macOS Chrome, clicking Download on the 2FA recovery-code step can dismiss/close the 2FA right-hand panel instead of leaving the user in the setup flow and allowing them to continue to the QR-code verification step.

What is the root cause of that problem?

The 2FA recovery-code download now uses a fixed filename and explicitly disables timestamping:

localFileDownload(TWO_FACTOR_AUTH_RECOVERY_CODES_FILENAME, account?.recoveryCodes ?? '', translate, undefined, undefined, false);

That changed behavior was introduced in commit 7f04e3ae115. Before that, the local download helper appended a timestamp, so repeat downloads did not hit the browser/OS overwrite confirmation path.

With the fixed filename, repeating the flow on macOS Chrome commonly opens the native save/replace confirmation. That native modal interrupts the web press flow while the 2FA RHP is still active. When Chrome returns control to the page, the click/focus sequence can be interpreted by the underlying RHP overlay/navigation layer as a dismissal, so SCREENS.RIGHT_MODAL.TWO_FACTOR_AUTH is removed. The navigator then runs its normal beforeRemove cleanup and clears the in-progress 2FA data via clearTwoFactorAuthData(true), which makes the user land back outside the setup flow instead of continuing to the QR-code page.

There is also a contributing fragility in PressableWithDelayToggle: for non-inline usage it renders a PressableWithoutFeedback inside another PressableWithoutFeedback, and both are wired to the same updatePressState. Each pressable has its own execution guard, so the download handler can be invoked more than once from a single pointer interaction before React state disables the button. That makes native download/overwrite prompts more likely and makes this flow especially sensitive to Chrome's save confirmation behavior.

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

Make the 2FA recovery-code download resilient to the native save confirmation path instead of letting that path dismiss the setup RHP.

Concretely:

  1. Restore unique filenames for the web 2FA recovery-code download by allowing localFileDownload() to append a timestamp for this button again, while keeping the new base filename:
localFileDownload(TWO_FACTOR_AUTH_RECOVERY_CODES_FILENAME, account?.recoveryCodes ?? '', translate);

This preserves the recognizable DO-NOT-DELETE_Expensify-2FA-RecoveryCodes name but avoids Chrome/macOS overwrite confirmation on repeated attempts.

  1. Harden PressableWithDelayToggle so non-inline buttons do not call the same onPress from both the outer and inner pressable. The outer wrapper should provide the accessible button target, and the inner visual pressable should not also invoke updatePressState for pointer activation, or the nested pressable event should stop propagation. This prevents duplicate downloads from one user click and reduces the chance of re-entering the browser save flow.

The 2FA flow should continue to use setCodesAreCopied() after a successful click so the Next button can navigate to ROUTES.SETTINGS_2FA_VERIFY.

What specific scenarios should we cover in automated tests to prevent reintroducing this issue in the future?

Add coverage for the 2FA recovery-code step that verifies clicking Download marks account.codesAreCopied and keeps the user on the 2FA route, then pressing Next navigates to settings/security/two-factor-auth/verify.

Add a unit/component test for PressableWithDelayToggle with inline={false} that asserts one pointer click calls onPress exactly once.

What alternative solutions did you explore? (Optional)

We could keep the fixed filename and add a short dismissal guard around the 2FA RHP while a local download is being initiated. That is broader and more navigation-specific than needed. Avoiding the overwrite confirmation path and fixing the duplicate press handling addresses the regression closer to the source.

KJ21-ENG avatar Jun 03 '26 18:06 KJ21-ENG

⚠️ @KJ21-ENG 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.

github-actions[bot] avatar Jun 03 '26 18:06 github-actions[bot]

What is the root cause of that problem?

On the recovery-codes step, "Download codes" is the primary success button and its onPress does two competing things in the same synchronous tick — it fires the file download and forceReplace-navigates to the Verify (QR) step:

https://github.com/Expensify/App/blob/3052a5d2051294792c857dbfdbebafd7a0371365/src/pages/settings/Security/TwoFactorAuth/DynamicTwoFactorAuthPage.tsx#L177-L191

On web localFileDownload doesn't click synchronously — it does the real link.click() inside a .then() (a microtask):

https://github.com/Expensify/App/blob/3052a5d2051294792c857dbfdbebafd7a0371365/src/libs/localFileDownload/index.ts#L10-L20

So the anchor click that pops Chrome's native "Save as" panel lands right as the forceReplace route swap is being dispatched (forceReplace → REPLACE):

https://github.com/Expensify/App/blob/3052a5d2051294792c857dbfdbebafd7a0371365/src/libs/Navigation/helpers/linkTo/index.ts#L173-L175

On macOS Chrome (with "Ask where to save each file before downloading" on) the Save panel appears and steals window focus the instant the download fires. That focus theft collides with the in-flight RHP transition, and the modal ends up dismissed — through one of the RHP's normal dismiss paths (the overlay-backdrop goBack, or the global Escape handler) — instead of cleanly replacing the codes screen with the Verify/QR screen:

  • https://github.com/Expensify/App/blob/3052a5d2051294792c857dbfdbebafd7a0371365/src/libs/Navigation/AppNavigator/Navigators/RightModalNavigator.tsx#L167-L186
  • https://github.com/Expensify/App/blob/3052a5d2051294792c857dbfdbebafd7a0371365/src/libs/Navigation/AppNavigator/KeyboardShortcutsHandler/EscapeHandler.tsx#L48-L90

On Windows Chrome the file saves silently — no panel, no focus theft — so the REPLACE completes and the QR page shows. That's exactly why it's macOS-only and flaky ("repeat the steps if it doesn't repro the first time"): it only breaks when the save dialog actually appears and races the navigation. The point is the coupling: a focus-stealing side effect and a route swap fired in the same tick. The old (pre-"Dynamic-2FA") codes screen kept these apart — Download only downloaded, and a separate "Next" button navigated — so the race didn't exist.

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

Render/handler layer, in DynamicTwoFactorAuthPage's download onPress. The data flow (setCodesAreCopied, recoveryCodes) is correct; only the ordering is wrong. Dispatch the forceReplace navigation to the Verify step first, then fire localFileDownload(...) on the next tick (setTimeout(fn, 0)) so the route swap commits and the RHP settles before the focus-stealing Save dialog appears.

Note: InteractionManager.runAfterInteractions would read more intentfully, but it's flagged deprecated by our lint config, so setTimeout(fn, 0) is the right primitive here (already used elsewhere in the app for "let navigation settle" deferrals).

localFileDownload is a module-level helper that captures recoveryCodes/translate in its closure, so it still runs correctly after the codes screen unmounts.

Edge cases this touches: offline (recovery codes are optimistic, navigation must still work) and the Copy-then-advance path (the Copy button doesn't navigate, so "Download codes" stays the advance action). Optionally, as defense-in-depth against the Esc-to-cancel-panel variant, MODAL.disableDismissOnEscape could be set during the download window (EscapeHandler already early-returns on that flag) — but deferring the download alone resolves the reported race.

What alternative solutions did you explore? (Optional)

  • Guarding only the Escape path (setDisableDismissOnEscape while downloading) as the whole fix. Rejected as the primary fix: react-native-key-command binds keydown with {capture:true} and the native Save panel consumes the keydown, so a plain Save (no Esc) would still race the navigation through the overlay/transition path. Deferring the download fixes the race at its source regardless of which dismiss path fires.
  • VERIFY page's own redirect effect bouncing the user to SUCCESS (https://github.com/Expensify/App/blob/3052a5d2051294792c857dbfdbebafd7a0371365/src/pages/settings/Security/TwoFactorAuth/DynamicVerifyPage.tsx#L50-L55). Rejected: that effect requires account.requiresTwoFactorAuth, which is still false at the codes/verify step (2FA only becomes "required" after the code is validated), so it returns early and never navigates — confirmed by reading the guard.

Abdulloh0109 avatar Jun 03 '26 18:06 Abdulloh0109

🚫 Duplicated proposal withdrawn by 🤖 ProposalPolice.

trasnake87 avatar Jun 03 '26 18:06 trasnake87

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

github-actions[bot] avatar Jun 03 '26 18:06 github-actions[bot]

Proposal

[!IMPORTANT] This is not a duplicate — it provides a deeper root cause analysis and proposes multiple distinct solutions with trade-offs.

What is the root cause of that problem?

The "Download codes" button does three things in one synchronous onPress, and they race each other:

onPress={() => {
    localFileDownload(TWO_FACTOR_AUTH_RECOVERY_CODES_FILENAME, recoveryCodes, translate, undefined, undefined, false);
    setError('');
    setCodesAreCopied();
    announceStatus(translate('fileDownload.success.title'));
    Navigation.navigate(createDynamicRoute(DYNAMIC_ROUTES.TWO_FACTOR_AUTH_VERIFY.path, backPath), {forceReplace: true});
}}

DynamicTwoFactorAuthPage.tsx#L183-L190

Three facts that combine into the bug:

  1. The download steals window focus, but only on some setups. localFileDownload builds a Blob and programmatically clicks an <a download> (localFileDownload/index.ts#L10-L20). On macOS Chrome with "Ask where to save each file before downloading" enabled, that click opens the native Save panel, which blurs the page. On Windows/Chrome (or macOS without that setting) the file drops straight into Downloads, the page never loses focus — which is exactly the "only repro on macOS, only when the save modal appears" split in the report. The anchor click is also deferred to a microtask (localFileCreate resolves via Promise.resolve), so the focus-steal lands right after the synchronous Navigation.navigate is dispatched.

  2. setCodesAreCopied() is an async Onyx write. It does Onyx.merge(ACCOUNT, {codesAreCopied: true, ...}) (TwoFactorAuthActions.ts#L20-L22), so the flag is not set synchronously — subscribers update on a later tick.

  3. The VERIFY step is gated on that exact flag, and its only fallback is to leave the RHP. TwoFactorAuthWrapper renders the "not found" blocking view for VERIFY whenever !account.codesAreCopied:

    case CONST.TWO_FACTOR_AUTH_STEPS.VERIFY:
        return !account.codesAreCopied;
    

    TwoFactorAuthWrapper.tsx#L55-L56, and that view's escape hatch is quitAndNavigateBack(backTo ?? ROUTES.SETTINGS_SECURITY) (L68, wired at L81/L86). quitAndNavigateBack both pops the whole RHP to Security and clears the 2FA data via clearTwoFactorAuthData (codesAreCopied: false) (TwoFactorAuthActions.ts#L10-L25).

So VERIFY's correctness depends on the async codesAreCopied write, while the navigation that mounts VERIFY is synchronous and fired in the same tick as a focus-stealing native dialog. I confirmed the destination from the repro video: the URL goes .../two-factor-auth → .../two-factor-auth/verify (QR briefly shows) → .../settings/security with the RHP gone while the Save panel is still open. /settings/security is precisely where quitAndNavigateBack lands. On the no-dialog platforms the page keeps focus, the Onyx write settles cleanly, and VERIFY holds the QR. On macOS the Save-panel focus-steal interleaves with the in-flight forceReplace + the not-yet-committed codesAreCopied, the VERIFY gate trips, and the flow unwinds through its SETTINGS_SECURITY fallback.

The trigger is the focus-stealing download fired in the same synchronous handler as a forceReplace jump into a step whose render gate (codesAreCopied) hasn't committed yet.

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

Layer: the onPress handler — make the step transition deterministic instead of racing the download.

  • Commit codesAreCopied and land on VERIFY before the file download can steal focus. Concretely, do the navigation (and ensure the setCodesAreCopied() merge is applied) first, and trigger localFileDownload last, deferred off the critical path — e.g. inside InteractionManager.runAfterInteractions(...) / after Navigation.isNavigationReady() — so the native Save panel only appears once VERIFY is mounted and its codesAreCopied gate is already satisfied. With the dialog opening after the RHP has settled, the focus-steal has nothing in-flight to disrupt.
  • Since VERIFY hard-depends on codesAreCopied (TwoFactorAuthWrapper.tsx#L55-L56), the navigate must not run before that write is observable. Awaiting/chaining the merge (or flipping the flag through a path that's already committed when VERIFY reads it) removes the window where VERIFY mounts as "not found."

This keeps the intended UX (download → QR page) and only touches the ordering in this one handler — no change to the modal/RHP infrastructure.

Edge cases this touches: the offline case (download still works, navigation still happens) and the "Copy codes" button (L142), which already sets codesAreCopied without navigating and so is unaffected.

What alternative solutions did you explore?

  • The VERIFY → SUCCESS auto-redirect in DynamicVerifyPage (L50-L55). Rejected: it requires account.requiresTwoFactorAuth === true, which is false during setup — if it were true, the codes page's own if (isFocused && is2FAEnabled) guard (DynamicTwoFactorAuthPage.tsx#L73) would have bounced the user to the ENABLED page before the codes screen ever rendered. Also, this redirect lands on SUCCESS, not on /settings/security.
  • A focus/visibility handler closing the panel — the PopoverProvider visibilitychange + document.hasFocus() listener (PopoverProvider/index.tsx#L107-L118). Rejected on two counts: it only closes a registered popover, not an RHP navigation modal, and a native Save panel keeps the tab visible (visibilityState stays visible), so visibilitychange doesn't even fire — it's a window blur, not a visibility change. The RHP's own modal only closes on Escape/backdrop/hardware-back, none of which a Save panel triggers, which is why the dismiss has to be a navigation (quitAndNavigateBack), not a modal-internal close.
  • Drop forceReplace / split download from progression. A separate "Next" button after download would also sidestep the race, but the issue's expected result is explicitly "after saving the codes, the QR page should be displayed," so auto-advance should stay. Listed here only as a fallback if sequencing proves insufficient.

oqildev avatar Jun 03 '26 18:06 oqildev

⚠️ @oqildev 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.

github-actions[bot] avatar Jun 03 '26 18:06 github-actions[bot]

Proposal

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

On macOS/Chrome, when enabling Two Factor Authentication, clicking "Download codes" closes the 2FA page instead of navigating to the next step (the QR code page). It only reproduces when the browser shows a "save file" confirmation dialog, and it does not reproduce on Windows 11/Chrome. We want the flow to reliably advance to the QR code page after the recovery codes are downloaded.

What is the root cause of that problem?

In the "Download codes" handler, localFileDownload(...) is called and then Navigation.navigate(... VERIFY ..., {forceReplace: true}) runs synchronously right after it. The navigation that swaps the RHP step to the QR page is therefore kicked off immediately.

https://github.com/Expensify/App/blob/4c215edd54b44d15fcc91915d83be4e0fd0e4be6/src/pages/settings/Security/TwoFactorAuth/DynamicTwoFactorAuthPage.tsx#L183-L189

localFileDownload does not perform the download synchronously: it first awaits localFileCreate(...) and only then creates the anchor and calls link.click(). So the link.click() that opens the macOS/Chrome save confirmation dialog fires in a microtask after Navigation.navigate has already started the RHP transition. The save dialog opening in the middle of that transition interrupts it, so the modal closes instead of completing navigation to the QR page. On Windows/Chrome the file downloads silently with no save dialog, so there is nothing to interrupt the transition and the bug does not occur.

https://github.com/Expensify/App/blob/4c215edd54b44d15fcc91915d83be4e0fd0e4be6/src/libs/localFileDownload/index.ts#L10-L20

Because localFileDownload returns void, the caller cannot wait for the download to be triggered before navigating, which is what allows the navigation and the deferred link.click() to race.

https://github.com/Expensify/App/blob/4c215edd54b44d15fcc91915d83be4e0fd0e4be6/src/libs/localFileDownload/types.ts#L3

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

Make localFileDownload return the download promise and have the page trigger the download (and its save dialog) first, then navigate inside .then() so navigation is the last action and is no longer interrupted.

https://github.com/Expensify/App/blob/4c215edd54b44d15fcc91915d83be4e0fd0e4be6/src/libs/localFileDownload/types.ts#L3

type LocalFileDownload = (fileName: string, textContent: string, translate: LocalizedTranslate, successMessage?: string, shouldShowSuccessAlert?: boolean, appendTimestamp?: boolean) => Promise<void>;

https://github.com/Expensify/App/blob/4c215edd54b44d15fcc91915d83be4e0fd0e4be6/src/libs/localFileDownload/index.ts#L10-L20

const localFileDownload: LocalFileDownload = (fileName, textContent, translate, successMessage, shouldShowSuccessAlert, appendTimestamp = true) =>
    localFileCreate(fileName, textContent, appendTimestamp).then(({path, newFileName}) => {
        const link = document.createElement('a');
        link.download = newFileName;
        link.href = path;
        link.click();
        if (shouldShowSuccessAlert) {
            showSuccessAlert(translate, successMessage);
        }
    });

https://github.com/Expensify/App/blob/4c215edd54b44d15fcc91915d83be4e0fd0e4be6/src/libs/localFileDownload/index.android.ts#L12

    return localFileCreate(fileName, textContent, appendTimestamp).then(({path, newFileName}) => {

https://github.com/Expensify/App/blob/4c215edd54b44d15fcc91915d83be4e0fd0e4be6/src/libs/localFileDownload/index.ios.ts#L13

    return localFileCreate(fileName, textContent, appendTimestamp).then(({path, newFileName}) => {

https://github.com/Expensify/App/blob/4c215edd54b44d15fcc91915d83be4e0fd0e4be6/src/pages/settings/Security/TwoFactorAuth/DynamicTwoFactorAuthPage.tsx#L183-L189

                            onPress={() => {
                                setError('');
                                setCodesAreCopied();
                                localFileDownload(TWO_FACTOR_AUTH_RECOVERY_CODES_FILENAME, recoveryCodes, translate, undefined, undefined, false).then(() => {
                                    announceStatus(translate('fileDownload.success.title'));
                                    Navigation.navigate(createDynamicRoute(DYNAMIC_ROUTES.TWO_FACTOR_AUTH_VERIFY.path, backPath), {forceReplace: true});
                                });
                            }}

abbasifaizan70 avatar Jun 03 '26 19:06 abbasifaizan70

⚠️ @abbasifaizan70 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.

github-actions[bot] avatar Jun 03 '26 19:06 github-actions[bot]

🚫 Duplicated proposal withdrawn by 🤖 ProposalPolice.

15antonian avatar Jun 03 '26 19:06 15antonian

⚠️ @15antonian 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.

github-actions[bot] avatar Jun 03 '26 19:06 github-actions[bot]

Proposal

Root Cause

I reproduced the issue on Web.

When the user clicks Download codes, localFileDownload() triggers the browser's native Save As dialog and we immediately navigate to the verification step. Since the browser dialog takes focus away from the app, the RHP gets dismissed during the navigation transition.

As a result, the recovery codes are downloaded successfully, but the user is no longer inside the 2FA flow and has to reopen it to continue setup.

Solution

I propose handling this specifically on Web by completing the RHP navigation before triggering the file download.

In DynamicTwoFactorAuthPage.tsx, I'll move the download call into the afterTransition callback of Navigation.navigate() so that the verification page is already mounted before the browser opens the Save As dialog.

if (isWeb) {
    Navigation.navigate(verifyRoute, {
        forceReplace: true,
        afterTransition: () => {
            localFileDownload(
                TWO_FACTOR_AUTH_RECOVERY_CODES_FILENAME,
                recoveryCodes,
                translate,
                undefined,
                undefined,
                false,
            );
        },
    });

    return;
}

localFileDownload(...);
Navigation.navigate(verifyRoute, {forceReplace: true});

This keeps the existing behavior on native platforms unchanged and limits the fix to the affected Web flow only.

Why this approach?

  • Addresses the actual timing issue between RHP navigation and the browser's Save As dialog.
  • Doesn't require changes to localFileDownload(), which is shared by other download flows.
  • Preserves existing navigation/history behavior.
  • Keeps the change isolated to a single component and a single user action.

Testing

  1. Go to Settings > Security > Two-factor authentication on Web.
  2. Start the 2FA setup flow and click Download codes.
  3. Verify the Save As dialog opens and the RHP remains on the verification step.
  4. Save the file and complete the setup.
  5. Cancel the Save As dialog and verify the user stays on the verification step.
  6. Verify the Copy codes flow still works.

hamsahmedansari avatar Jun 03 '26 20:06 hamsahmedansari