Skip to content

[Due for payment 2026-08-25] [$250] Device back button not responsive on navigating back from public room sign in modal #96869

Closed

Description

@nlemma

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.4.43-1
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://github.com/Expensify/Expensify/issues/549371
Email or phone of affected tester (no customers): -
Issue reported by: Applause Internal Team
Bug source: Regression TC Execution
Device used: Xiaomi Redmi Note 10S - Android 13

Action Performed:

Pre-condition keep log out app

  1. In slack , click public room deep link -https://staging.new.expensify.com/r/5583419180793784
  2. Tap sign in
  3. Tap device back button

Expected Result:

Device back button must be responsive on navigating back from public room sign in modal

Actual Result:

Device back button not responsive on navigating back from public room sign in modal

Workaround:

Unknown

Platforms:

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

Screenshots/Videos

Bug7210507_1784270259404.Screenrecorder-2026-07-17-12-02-03-819.1.mp4

View all open jobs on GitHub

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

Activity

  1. added
    BugSomething is broken. Auto assigns a BugZero manager.
    on Jul 23, 2026
  2. added
    BugSomething is broken. Auto assigns a BugZero manager.
    and removed
    BugSomething is broken. Auto assigns a BugZero manager.
    on Jul 23, 2026
  3. MelvinBot commented on Jul 23, 2026

    @MelvinBot
    Contributor

    Proposal

    What is the root cause of that problem?

    SignInModal registers an Android hardwareBackPress listener that unconditionally returns true and performs no navigation — src/pages/signin/SignInModal.tsx:42-44:

    useAndroidBackButtonHandler(() => {
        return true;
    });

    The comment above it says this is meant to disable SignInModal's own back handling "leaving only SignInPage handling". But returning true from a hardwareBackPress listener tells React Native's BackHandler to stop propagation — so neither SignInPage's navigateBack (which would call Navigation.goBack()) nor React Navigation's own container back handler ever run. The press is swallowed and the modal never dismisses, so the device back button looks dead.

    Note the header's X/back button does this correctly at SignInModal.tsx:82-90 — it delegates to signinPageRef.current?.navigateBack(). Only the hardware back path is broken.

    Evidence & flow
    • Anonymous user taps "Sign in" in AnonymousReportFooter.tsx → signOutAndRedirectToSignIn() → navigates to SIGN_IN_MODAL, which is presented as an RHP modal. Dismissing it requires a navigation goBack.
    • SignInPage.tsx registers the real navigateBack handler (falls through to Navigation.goBack() and returns false in the anonymous login-form state), but it is shadowed by the parent's () => true.
    • The () => true was added for #69391; the SignInPage handler for #67883. The () => true over-blocks: it silently returns true even when nothing else ends up handling the press.
    • hardwareBackPress listeners fire in reverse-registration order and stop at the first that returns true (RN BackHandler.android.js), so a bare () => true at the modal level reliably eats the press.

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

    Make the SignInModal hardware-back handler delegate to the same logic the header button uses, instead of returning a bare true. Concretely, in SignInModal.tsx:42-44 call signinPageRef.current?.navigateBack() (mirroring the onBackButtonPress at lines 82-90) and return true, so the modal is actually dismissed/navigated back on hardware back. This keeps the #67883/#69391 behavior while restoring a responsive device back button.

    This should be verified on an Android device/emulator against the exact repro (logged-out → public room deep link → Sign in → device back) before merging, and re-checked against the two issues the current handler was added for.

    What alternative solutions did you explore? (Optional)

    Having the modal handler return false so SignInPage's handler and React Navigation's container handler take over — but explicit delegation to navigateBack() is safer and matches the header button, avoiding reliance on listener ordering.

    Possibly related: #96346 — another anonymous public-room sign-in navigation bug (first tap on Sign in opens the public room page instead of sign-in on Android). Different symptom, same flow; worth cross-checking they aren't fixed together.


    Next Steps for Contributor+ team:
    To accept: @MelvinBot implement [this](https://github.com/Expensify/App/issues/96869) 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 Jul 23, 2026
  5. added
    Help WantedApply this label when an issue is open to proposals by contributors
    on Jul 23, 2026
  6. mukhrr commented on Jul 23, 2026

    @mukhrr
    Contributor

    Proposal

    What is the root cause of that problem?

    The public-room footer opens SIGN_IN_MODAL for anonymous users.

    <View style={[styles.anonymousRoomFooterSignInButton]}>
    <Button
    success
    text={translate('common.signIn')}
    onPress={() => {
    signOutAndRedirectToSignIn();
    }}
    />

    Inside that modal two components register a focused Android back handler. SignInPage registers the real behavior, and SignInModal registers a listener that unconditionally returns true without navigating.

    const navigateBack = () => {
    if (
    shouldShouldSignUpWelcomeForm ||
    (!shouldShowAnotherLoginPageOpenedMessage &&
    (shouldShowEmailDeliveryFailurePage || shouldShowUnlinkLoginForm || shouldShowChooseSSOOrMagicCode || shouldShowSMSDeliveryFailurePage))
    ) {
    clearSignInData();
    return true;
    }
    if (shouldShowValidateCodeForm) {
    validateCodeFormRef.current?.clearSignInData();
    return true;
    }
    Navigation.goBack();
    return false;
    };
    useImperativeHandle(ref, () => ({
    navigateBack,
    }));
    useAndroidBackButtonHandler(navigateBack);

    // The SignInPage (child component of SignInModal) uses useAndroidBackButtonHandler, which adds a hardwareBackPress listener that remains active in the SignInModal.
    // Use of useAndroidBackButtonHandler with a returning true callback disables the default SignInModal hardware Android button behaviour, leaving only SignInPage handling (https://github.com/Expensify/App/issues/69391).
    // The SignInPage Android back button behavior needs to remain because it is a fix for issue (https://github.com/Expensify/App/issues/67883) that occurs in the SignInModal.
    useAndroidBackButtonHandler(() => {
    return true;
    });

    I originally assumed this was order-dependent. Testing it locally, I found it is fully deterministic, and the no-op listener always wins.

    Two facts combine. First, React Native stores hardwareBackPress subscriptions in a plain array and walks it backwards, stopping at the first listener that returns true, so the last registered listener is the first invoked (react-native/Libraries/Utilities/BackHandler.android.js):

    const _backPressSubscriptions: Array<BackPressHandler> = [];
    RCTDeviceEventEmitter.addListener(DEVICE_BACK_EVENT, function () {
      for (let i = _backPressSubscriptions.length - 1; i >= 0; i--) {
        if (_backPressSubscriptions[i]?.()) {
          return;
        }
      }
      BackHandler.exitApp();
    });

    Second, the hook subscribes from an effect, and React flushes child effects before parent effects.

    export default function useAndroidBackButtonHandler(callback: UseAndroidBackButtonHandlerCallback) {
    useFocusEffect(
    useCallback(() => {
    const backHandler = BackHandler.addEventListener('hardwareBackPress', callback);
    return () => backHandler.remove();
    }, [callback]),
    );
    }

    So SignInPage (the child) subscribes first and SignInModal (the parent) subscribes second, which puts the no-op at the end of the array and therefore first in the dispatch order. I confirmed this by recording the real subscription order while rendering SignInModal in a test, and it comes out as [SignInPage.navigateBack, SignInModal noop, NavigationContainer] every time. The press is consumed by the no-op and nothing else runs, which is exactly the "back button not responsive" report.

    The history explains why the no-op exists. The SignInPage listener came first, to stop Android back from closing the app on intermediate sign-in steps.

    const navigateBack = () => {
    if (
    shouldShouldSignUpWelcomeForm ||
    (!shouldShowAnotherLoginPageOpenedMessage &&
    (shouldShowEmailDeliveryFailurePage || shouldShowUnlinkLoginForm || shouldShowChooseSSOOrMagicCode || shouldShowSMSDeliveryFailurePage))
    ) {
    clearSignInData();
    return true;
    }
    if (shouldShowValidateCodeForm) {
    validateCodeFormRef.current?.clearSignInData();
    return true;
    }
    Navigation.goBack();
    return false;
    };
    useImperativeHandle(ref, () => ({
    navigateBack,
    }));
    useHandleBackButton(navigateBack);

    The no-op was added afterwards because the initial-form path calls Navigation.goBack() and then returns false, which let react-navigation's own container handler pop a second time. It fixed the double navigation, but on the assumption that the child listener would run first — which is the opposite of what actually happens.

    // The SignInPage (child component of SignInModal) uses useHandleBackButton, which adds a hardwareBackPress listener that remains active in the SignInModal.
    // Use of useHandleBackButton with a returning true callback disables the default SignInModal hardware Android button behaviour, leaving only SignInPage handling (https://github.com/Expensify/App/issues/69391).
    // The SignInPage Android back button behavior needs to remain because it is a fix for issue (https://github.com/Expensify/App/issues/67883) that occurs in the SignInModal.
    useHandleBackButton(() => {
    return true;
    });

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

    I think we should make SignInPage the sole owner of Android back handling, so no ordering assumption is needed at all.

    I would add a shouldConsumeInitialBackPress prop to SignInPage, defaulting to false, and have navigateBack return it instead of the hardcoded false after Navigation.goBack():

     Navigation.goBack();
    -return false;
    +return shouldConsumeInitialBackPress;

    SignInModal then passes shouldConsumeInitialBackPress to the page and drops its own useAndroidBackButtonHandler call entirely. Worth noting that the prop has to be threaded through SignInPageWrapper and the WithTheme HOC as well, since the modal renders the themed/wrapped export rather than SignInPage directly — in WithTheme this is simplest as <Component {...props} /> instead of destructuring {ref}.

    This leaves exactly one app-level listener, so the outcome no longer depends on registration order. In the modal, that listener both dismisses the modal and consumes the press, so react-navigation's container handler is never reached and cannot navigate a second time. On the standalone sign-in page the prop stays false, so the initial form still falls through and Android's default exit behavior is preserved. The intermediate states are untouched: they already clear their sign-in data and return true.

    For coverage I would add a test that renders SignInModal on a navigator that was already mounted on another screen (so react-navigation's container listener is registered first, matching the real app), records the real subscription order via BackHandler.addEventListener, and replays React Native's reverse dispatch. It asserts Navigation.goBack is called exactly once and the press is consumed. On current main that test fails with goBack called 0 times, and passes with the change. I would add a second case rendering the standalone SignInPage and asserting the initial press is not consumed, so we can't silently regress the exit-the-app behavior. I would still QA the public-room flow and standalone sign-in on a device.

    What alternative solutions did you explore? (Optional)

    I considered changing the modal's no-op to call signinPageRef.current.navigateBack() and return true. Given the dispatch order above that happens to work on mount, but it keeps two live listeners and stays order-sensitive: SignInPage re-subscribes whenever navigateBack's identity changes (for example when the form advances to the magic-code step), which moves it to the end of the array and flips the order. From then on navigateBack runs first, returns false on the initial form, and the modal's listener calls it again — recreating the double navigation the no-op was added to prevent. Removing one of the two listeners is what actually makes the behavior stable.

  7. ahmdshrif commented on Jul 23, 2026

    @ahmdshrif
    Contributor

    Proposal

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

    On Android, a logged-out (anonymous) user opens a public room deep link, taps "Sign in" to open the sign-in RHP modal, then presses the device back button — nothing happens. The hardware back press is silently swallowed, so the user cannot navigate back from the sign-in modal.

    What is the root cause of that problem?

    Two hardwareBackPress listeners are mounted on the same route, and the one that wins is an unconditional swallow.

    1. The sign-in modal route (SCREENS.SIGN_IN_ROOT) renders SignInModal:

      const SignInModalStackNavigator = createModalStackNavigator<SignInNavigatorParamList>({
      [SCREENS.SIGN_IN_ROOT]: () => require<ReactComponentModule>('../../../../pages/signin/SignInModal').default,

    2. SignInModal registers a hardware-back handler that unconditionally return true (i.e. "consumed, do nothing"). Per the comment, PR #69609 added this to fix #69391 (back popped multiple routes), intending to suppress only the navigator's default pop and "leave only SignInPage handling":

      // The SignInPage (child component of SignInModal) uses useAndroidBackButtonHandler, which adds a hardwareBackPress listener that remains active in the SignInModal.
      // Use of useAndroidBackButtonHandler with a returning true callback disables the default SignInModal hardware Android button behaviour, leaving only SignInPage handling (https://github.com/Expensify/App/issues/69391).
      // The SignInPage Android back button behavior needs to remain because it is a fix for issue (https://github.com/Expensify/App/issues/67883) that occurs in the SignInModal.
      useAndroidBackButtonHandler(() => {
      return true;
      });

    3. Its child SignInPage registers the handler that actually navigates — navigateBack (added for #67883, back closing the app on the magic-code screen):

      const navigateBack = () => {
      if (
      shouldShouldSignUpWelcomeForm ||
      (!shouldShowAnotherLoginPageOpenedMessage &&
      (shouldShowEmailDeliveryFailurePage || shouldShowUnlinkLoginForm || shouldShowChooseSSOOrMagicCode || shouldShowSMSDeliveryFailurePage))
      ) {
      clearSignInData();
      return true;
      }
      if (shouldShowValidateCodeForm) {
      validateCodeFormRef.current?.clearSignInData();
      return true;
      }
      Navigation.goBack();
      return false;
      };
      useImperativeHandle(ref, () => ({
      navigateBack,
      }));
      useAndroidBackButtonHandler(navigateBack);

    4. Both register through the same hook, which subscribes on focus:

      export default function useAndroidBackButtonHandler(callback: UseAndroidBackButtonHandlerCallback) {
      useFocusEffect(
      useCallback(() => {
      const backHandler = BackHandler.addEventListener('hardwareBackPress', callback);
      return () => backHandler.remove();
      }, [callback]),
      );
      }

    5. Ordering is the mechanism. React flushes child effects before parent effects, so on mount SignInPage subscribes first and SignInModal's () => true subscribes last. React Native's BackHandler invokes subscriptions in reverse registration order and stops at the first one returning true. So the modal's () => true runs first, consumes the event, and navigateBack never executes; React Navigation's default handler (registered earliest, invoked last) is never reached either. The press does nothing at all.

    The structural cause: PR #69609's fix assumed the opposite invocation order — it swallows the event before the child's handler, not after it. This is deterministic on a fresh open of the modal (exactly the repro: tap Sign in, immediately press back).

    This explains every symptom detail:

    • Android app only: the hook is a no-op everywhere else (
      import type UseAndroidBackButtonHandlerCallback from './type';
      // We only need this hook to handle Android back button behavior.
      // See https://reactnavigation.org/docs/custom-android-back-button-handling for more details
      // eslint-disable-next-line @typescript-eslint/no-unused-vars
      export default function useAndroidBackButtonHandler(_callback: UseAndroidBackButtonHandlerCallback) {}
      ), and BackHandler is Android-only.
    • Only the device key is dead: the header chevron works because it calls navigateBack directly via ref, bypassing BackHandler:
      <HeaderWithBackButton
      onBackButtonPress={() => {
      if (!signinPageRef.current) {
      Navigation.goBack();
      return;
      }
      signinPageRef.current?.navigateBack();
      }}
      />
    • Standalone sign-in page is unaffected: mounted without the modal parent (
      name={NAVIGATORS.TAB_NAVIGATOR}
      options={{
      ...defaultScreenOptions,
      // If you want to change this, make sure there aren't any animation bugs when signing out.
      // This was put here to prevent excessive animations when resetting the navigation state in `resetNavigationState`
      animation: Animations.NONE,
      }}
      component={SignInPage}
      />
      ), so only one listener exists there.

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

    Collapse back-handling to one listener per route so the behavior no longer depends on subscription order.

    1. Delete the useAndroidBackButtonHandler(() => true) block (and its now-unused import) from SignInModal.tsx (L39–L44 above).
    2. In SignInPage's navigateBack, consume the event whenever it actually pops (
      Navigation.goBack();
      return false;
      ):
    if (!navigationRef.current?.canGoBack()) {
        // Standalone sign-in root: let Android background the app.
        return false;
    }
    Navigation.goBack();
    return true;

    (navigationRef.current?.canGoBack() is the established pattern, e.g. BaseVerifyDomainPage.tsx L125; Navigation.goBack() already no-ops via this same guard internally — Navigation.ts L546-L549 — so only the returned boolean changes.)

    This preserves the intent of both prior fixes with a single listener: in the modal, every branch of navigateBack now returns true (sub-forms clear state, base step pops the RHP), so the navigator's default pop can never fire a second time — #69391 stays fixed without the swallow; the #67883 magic-code branch is untouched; and on the standalone logged-out root, canGoBack() is false, so back still minimizes the app exactly as today. Regression safety: the only other consumer of navigateBack is the header chevron via ref, which ignores the return value.

    Why the obvious spot-fix fails: making the modal's handler delegate (signinPageRef.current?.navigateBack(); return true;) keeps two listeners. The hook re-subscribes whenever the callback identity changes (useFocusEffect's [callback] dep), and navigateBack's identity changes every time a step flag flips (e.g. entering/leaving the magic-code form). That re-registration moves SignInPage's listener above the modal's, so a later base-step press runs navigateBack (goBack() + false), falls through to the modal's delegate, which calls navigateBack again — a second pop, i.e. exactly the multi-pop bug #69391 that #69609 was fixing. Any two-listener arrangement stays order-dependent; removing the second listener removes the dependency.

    What alternative solutions did you explore? (Optional)

    • Delegate from the modal handler (above): works on fresh open but reintroduces the #69391 double-pop once the listener order reshuffles.
    • A prop to disable SignInPage's inner handler inside the modal: functionally equivalent, but adds a navigation-behavior prop and keeps two coupled handlers; the single-listener change is smaller and removes the ordering hazard entirely.
    • Revert #69609: restores a responsive back button but brings back the multi-pop bug it fixed; the intent (suppress the default extra pop) must be preserved, which the return true in navigateBack does.
  8. MobileMage commented on Jul 23, 2026

    @MobileMage
    Contributor

    Proposal

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

    On Android native, a logged-out user opens a public room via deep link, taps "Sign in" (which opens the sign-in RHP modal for anonymous users), and then presses the device hardware back button. Nothing happens — the back press is silently swallowed instead of dismissing the sign-in modal.

    What is the root cause of that problem?

    Tapping "Sign in" as an anonymous user runs signOutAndRedirectToSignIn in src/libs/actions/Session/index.ts (line 366), which navigates to ROUTES.SIGN_IN_MODAL, rendering SignInModal in the RHP with SignInPage as its child. Both components register a hardwareBackPress listener through useAndroidBackButtonHandler (src/hooks/useAndroidBackButtonHandler/index.android.ts, a useFocusEffect around BackHandler.addEventListener). SignInPage registers its navigateBack handler (line 321), and SignInModal registers a blanket handler that unconditionally consumes the event:

    useAndroidBackButtonHandler(() => {
    return true;
    });

    React Native's BackHandler dispatches subscriptions in reverse registration order and stops at the first one that returns true (see _backPressSubscriptions iteration in Libraries/Utilities/BackHandler.android.js). React runs mount effects child-first, so on modal open SignInPage subscribes navigateBack first and SignInModal subscribes () => true second — which puts the modal's blanket handler ON TOP of the dispatch stack. Every hardware back press hits () => true first, gets consumed, and SignInPage.navigateBack (which would call Navigation.goBack() to dismiss the RHP) never runs. The ordering never self-heals either: while the user sits on the sign-in form, none of navigateBack's inputs change and () => true is a dependency-free constant, so neither listener re-subscribes and the modal's swallow stays on top for every press.

    The blanket handler was added in PR #69609 to fix #69391, where the same repro closed the entire app because back popped twice. The intent (per the comment on lines 39-41) was for it to sit BELOW SignInPage's handler and absorb only the leftover default after navigateBack runs — but the child-first effect order guarantees the opposite. The double-pop it papered over comes from navigateBack's final branch, which returns false even after it successfully navigates, letting react-navigation's container-level default handler pop a second time:

    Navigation.goBack();
    return false;

    That incorrect false (only appropriate on the standalone sign-in page at the navigation root, where the default back should exit the app) is what forced the blanket swallow in the first place, and the swallow's dispatch position is what makes the back button dead now.

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

    The fix is to make navigateBack in SignInPage.tsx report the truth — consume the event whenever it actually navigated — and then delete the blanket useAndroidBackButtonHandler(() => true) block (lines 39-44) plus its now-unused import from SignInModal.tsx, so navigateBack is the only app-level listener and dispatch order stops mattering. In navigateBack's final branch we gate on navigationRef.current?.canGoBack() (already exported from @libs/Navigation/Navigation and used the same way in BaseVerifyDomainPage.tsx line 125):

    if (navigationRef.current?.canGoBack()) {
        Navigation.goBack();
        return true;
    }
    return false;

    This is safe for every existing scenario. In the sign-in modal, back now pops the RHP exactly once and returns true, so react-navigation's default handler never fires — #69391's double-pop stays fixed without the swallow. The validate-code and signup-welcome branches (lines 300-313) are untouched, so #67883's fix (back returns to the email step instead of closing) is preserved. On the standalone logged-out SignInPage at the navigation root, canGoBack() is false, so we return false and the default back exits the app — identical to today, where Navigation.goBack() already no-ops at the root (it logs "Unable to go back" at Navigation.ts line 546-548) and false is returned anyway. The HeaderWithBackButton path in SignInModal calls navigateBack through the ref and ignores the return value, so the visible back arrow behaves exactly as before, and useAndroidBackButtonHandler is a no-op on all non-Android platforms, so the change is Android-only by construction.

    What alternative solutions did you explore? (Optional)

    We considered a single-file fix keeping both listeners and changing SignInModal's handler to delegate: signinPageRef.current?.navigateBack(); return true;. That works while the modal's listener is on top, but the moment SignInPage re-subscribes above it (its navigateBack identity changes whenever a form-state flag flips, e.g. after entering and clearing an email), the child runs first, returns false from the goBack branch, and the modal's delegate fires navigateBack a second time — a double pop that re-introduces #69391. Fixing the return value and removing the second listener eliminates the ordering dependency entirely instead of racing it.

  9. KJ21-ENG commented on Jul 23, 2026

    @KJ21-ENG
    Contributor

    🚨 Edited by proposal-police: This proposal was edited at 2026-07-23 19:27:43 UTC.

    Proposal

    What is the root cause of that problem?

    The public-room deep link opens the report for an unauthenticated user, and the anonymous Sign in actions route that session to the right-hand sign-in modal.

    function openReportFromDeepLink(
    url: string,
    reports: OnyxCollection<Report>,
    isAuthenticated: boolean,
    conciergeReportID: string | undefined,
    introSelected: OnyxEntry<IntroSelected>,
    isSelfTourViewed: boolean | undefined,
    betas: OnyxEntry<Beta[]>,
    ) {
    const reportID = getReportIDFromLink(url);
    if (reportID && !isAuthenticated) {
    // Start span for public room API call
    startSpan(CONST.TELEMETRY.SPAN_BOOTSPLASH.PUBLIC_ROOM_API, {
    name: CONST.TELEMETRY.SPAN_BOOTSPLASH.PUBLIC_ROOM_API,
    op: CONST.TELEMETRY.SPAN_BOOTSPLASH.PUBLIC_ROOM_API,
    parentSpan: getSpan(CONST.TELEMETRY.SPAN_BOOTSPLASH.PUBLIC_ROOM_CHECK),
    });
    // Call the OpenReport command to check in the server if it's a public room. If so, we'll open it as an anonymous user
    openReport({reportID, introSelected, parentReportActionID: '0', isFromDeepLink: true, betas, hasReportActions: false});

    ];
    function signOutAndRedirectToSignIn(shouldResetToHome?: boolean, shouldStashSession?: boolean, shouldSignOutFromOldDot = true, shouldForceUseStashedSession?: boolean) {
    Log.info('Redirecting to Sign In because signOut() was called');
    hideContextMenu(false);
    if (isAnonymousUser()) {
    if (!Navigation.isActiveRoute(ROUTES.SIGN_IN_MODAL)) {
    if (shouldResetToHome) {
    Navigation.resetToHome();
    }
    Navigation.navigate(ROUTES.SIGN_IN_MODAL);
    }
    return;
    }
    const isSupportal = isSupportAuthToken();

    SignInPage already owns the state-aware Android back behavior: it clears intermediate sign-in or validate-code state when necessary, otherwise calls Navigation.goBack(), and registers that navigateBack function with useAndroidBackButtonHandler.

    const navigateBack = () => {
    if (
    shouldShouldSignUpWelcomeForm ||
    (!shouldShowAnotherLoginPageOpenedMessage &&
    (shouldShowEmailDeliveryFailurePage || shouldShowUnlinkLoginForm || shouldShowChooseSSOOrMagicCode || shouldShowSMSDeliveryFailurePage))
    ) {
    clearSignInData();
    return true;
    }
    if (shouldShowValidateCodeForm) {
    validateCodeFormRef.current?.clearSignInData();
    return true;
    }
    Navigation.goBack();
    return false;
    };
    useImperativeHandle(ref, () => ({
    navigateBack,
    }));
    useAndroidBackButtonHandler(navigateBack);

    PR #69609 / commit ee930b18a219bc7d3f62ed0e6fa74308584b2009 added a second listener in SignInModal to prevent the double navigation reported in #69391. Its callback only returns true; it does not call Navigation.goBack() or the child's state-aware navigateBack() method.

    #69609

    // The SignInPage (child component of SignInModal) uses useAndroidBackButtonHandler, which adds a hardwareBackPress listener that remains active in the SignInModal.
    // Use of useAndroidBackButtonHandler with a returning true callback disables the default SignInModal hardware Android button behaviour, leaving only SignInPage handling (https://github.com/Expensify/App/issues/69391).
    // The SignInPage Android back button behavior needs to remain because it is a fix for issue (https://github.com/Expensify/App/issues/67883) that occurs in the SignInModal.
    useAndroidBackButtonHandler(() => {
    return true;
    });

    useAndroidBackButtonHandler registers both callbacks as React Native hardwareBackPress listeners. A true result consumes the event, so when the modal listener is reached before the child listener it stops dispatch without performing any navigation. The header works because it directly delegates to the child ref instead of using the no-op callback.

    export default function useAndroidBackButtonHandler(callback: UseAndroidBackButtonHandlerCallback) {
    useFocusEffect(
    useCallback(() => {
    const backHandler = BackHandler.addEventListener('hardwareBackPress', callback);
    return () => backHandler.remove();
    }, [callback]),
    );
    }

    <HeaderWithBackButton
    onBackButtonPress={() => {
    if (!signinPageRef.current) {
    Navigation.goBack();
    return;
    }
    signinPageRef.current?.navigateBack();
    }}
    />

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

    Make SignInModal the sole owner of actionable Android hardware-back handling while the modal is open. Extract its header-back logic into one callback that delegates to signinPageRef.current.navigateBack() (falling back to Navigation.goBack() before the ref is attached), use that callback for both the header and useAndroidBackButtonHandler, and return true only after performing that action.

    Add an explicit prop to SignInPage that keeps its existing hardware-back handling enabled by default for standalone sign-in, but makes its listener non-handling when rendered inside SignInModal. Pass the prop through the sign-in theme/wrapper components and disable child ownership from the modal. This removes the callback-order race while preserving the intermediate-state behavior added for #67883 and the single-pop safeguard added for #69391.

    The change covers the supplied public-room flow and the other anonymous controls that reach the same modal, including the anonymous report footer and sidebar Sign in button.

    success
    text={translate('common.signIn')}
    onPress={() => {
    signOutAndRedirectToSignIn();
    }}
    />
    </View>

    <PressableWithoutFeedback
    accessibilityLabel={translate('sidebarScreen.buttonMySettings')}
    role={CONST.ROLE.BUTTON}
    onPress={() => signOutAndRedirectToSignIn()}
    sentryLabel={CONST.SENTRY_LABEL.SIDEBAR.SIGN_IN_BUTTON}
    >
    <View style={[styles.signInButtonAvatar, styles.ph2]}>
    <Button
    success
    text={translate('common.signIn')}
    onPress={() => {
    signOutAndRedirectToSignIn();
    }}

    Test coverage:

    • Add Android-focused SignInModal coverage that captures the registered callbacks and verifies hardware back delegates exactly once, closes the initial public-room sign-in modal, returns true, and uses the Navigation.goBack() fallback before the child ref is ready.
    • Verify intermediate sign-in and validate-code states delegate exactly once and clear only their current state, and verify the header invokes the same shared callback.
    • Verify standalone SignInPage retains its existing hardware-back behavior.
    • Manually repeat the supplied public-room flow and the original [Due for payment 2025-09-16] [BACK BUTTON] Android - back button pops multiple navigation routes #69391 scenario, confirming one device-back press closes only the modal and never exits the app or performs a second navigation.

    What alternative solutions did you explore? (Optional)

    Only changing the modal's no-op listener to delegate is smaller, but it leaves both callbacks actionable: if the child listener runs first, it can call Navigation.goBack() and return false, after which the modal listener can delegate a second time. Removing the modal listener and making the child's final branch always consume is also smaller, but changes first-screen behavior for standalone sign-in and could prevent the normal Android app exit at the root. Explicit modal ownership fixes both the swallowed event and the prior double-pop without depending on subscription order.

  10. wildan-m commented on Jul 23, 2026

    @wildan-m
    Contributor

    Proposal

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

    On Android, after opening a public room deep link while logged out and tapping Sign in, the sign-in modal opens but the device (hardware) back button does nothing. The user cannot navigate back from the public room sign-in modal with the hardware back button.

    What is the root cause of that problem?

    SignInModal registers an Android hardware-back listener whose callback unconditionally returns true:

    // The SignInPage (child component of SignInModal) uses useAndroidBackButtonHandler, which adds a hardwareBackPress listener that remains active in the SignInModal.
    // Use of useAndroidBackButtonHandler with a returning true callback disables the default SignInModal hardware Android button behaviour, leaving only SignInPage handling (https://github.com/Expensify/App/issues/69391).
    // The SignInPage Android back button behavior needs to remain because it is a fix for issue (https://github.com/Expensify/App/issues/67883) that occurs in the SignInModal.
    useAndroidBackButtonHandler(() => {
    return true;
    });

    The comment there assumes that returning true only disables the modal's default back behaviour while "leaving only SignInPage handling". That assumption is inverted, because of how React Native dispatches hardwareBackPress.

    BackHandler keeps one flat list of subscriptions and iterates it in reverse registration order, stopping at the first callback that returns true (node_modules/react-native/Libraries/Utilities/BackHandler.android.js) — the last handler registered is the first one evaluated, and a true return prevents every earlier subscription (and the default behaviour) from running.

    Both handlers are registered through useAndroidBackButtonHandler, which subscribes inside useFocusEffect:

    export default function useAndroidBackButtonHandler(callback: UseAndroidBackButtonHandlerCallback) {
    useFocusEffect(
    useCallback(() => {
    const backHandler = BackHandler.addEventListener('hardwareBackPress', callback);
    return () => backHandler.remove();
    }, [callback]),
    );
    }

    SignInPage is a child of SignInModal, and React flushes child effects before parent effects. So SignInPage's navigateBack subscription is added first, and SignInModal's always-true callback is added second:

    const navigateBack = () => {
    if (
    shouldShouldSignUpWelcomeForm ||
    (!shouldShowAnotherLoginPageOpenedMessage &&
    (shouldShowEmailDeliveryFailurePage || shouldShowUnlinkLoginForm || shouldShowChooseSSOOrMagicCode || shouldShowSMSDeliveryFailurePage))
    ) {
    clearSignInData();
    return true;
    }
    if (shouldShowValidateCodeForm) {
    validateCodeFormRef.current?.clearSignInData();
    return true;
    }
    Navigation.goBack();
    return false;
    };
    useImperativeHandle(ref, () => ({
    navigateBack,
    }));
    useAndroidBackButtonHandler(navigateBack);

    Because the list is walked in reverse, SignInModal's callback runs first, returns true, and the dispatch stops immediately. SignInPage.navigateBack never runs, and neither does React Navigation's default back handling. The press is swallowed entirely, which is exactly the reported symptom: the hardware back button appears dead on the public room sign-in modal.

    In other words, the guard added for #69391 does not delegate to SignInPage as intended — it blocks the press outright, regressing the behaviour restored for #67883.

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

    Make SignInModal's hardware-back callback actually perform the back action instead of only suppressing it, mirroring the logic its own header back button already uses.

    In src/pages/signin/SignInModal.tsx, extract the existing onBackButtonPress body of HeaderWithBackButton into a stable callback — if signinPageRef.current is not attached yet, call Navigation.goBack(), otherwise call signinPageRef.current.navigateBack(). Use that same callback both for the header's onBackButtonPress prop and inside the useAndroidBackButtonHandler callback, and keep returning true from the hardware-back callback after invoking it.

    This keeps the intent of the earlier fix (the modal's default hardware back behaviour stays suppressed, so no duplicate/extra back navigation happens), while making the hardware back button behave identically to the on-screen back arrow:

    • On the magic-code / validate-code step, navigateBack clears the sign-in data and returns the user to the login form — the behaviour expected from the earlier fix.
    • On the login form step, navigateBack calls Navigation.goBack(), dismissing the sign-in modal and returning the user to the public room, which is the expected result described in this issue.

    SignInPage's own useAndroidBackButtonHandler(navigateBack) registration should stay as-is, because SignInPage is also rendered standalone as the public sign-in screen where it is the only back handler. It simply never fires while the modal is mounted, since the modal's handler now handles and consumes the press.

    Compare branch: https://github.com/Expensify/App/compare/main...wildan-m:App:wildan/96869-signin-modal-hardware-back?expand=1

    What alternative solutions did you explore? (Optional)

    Removing SignInModal's useAndroidBackButtonHandler call entirely so that SignInPage.navigateBack is the only handler. I rejected this because navigateBack returns false on the login-form step after already calling Navigation.goBack(), so React Navigation's default handling would run as well and the app would navigate back twice — the regression the modal's guard was added to prevent.

    Changing SignInPage.navigateBack to always return true. I rejected this because the same function is the back handler for the standalone public sign-in screen, where returning false on the login-form step is what lets Android's default behaviour close the app; always returning true would trap the user on that screen.

  11. melvin-bot commented on Jul 23, 2026

    @melvin-bot

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

  12. 65 remaining items

  13. situchan commented on Aug 20, 2026

    @situchan
    Contributor

    BugZero Checklist:

    Regression Test Proposal

    Pre-condition

    keep log out app

    Test:

    1. In slack, click public room deep link - https://staging.new.expensify.com/r/5583419180793784
    2. Tap sign in
    3. Tap device back button
    4. Device back button must be responsive on navigating back from public room sign in modal

    Do we agree 👍 or 👎

    Zapier Logs Run ID: 00040eee-a0c7-a288-edbf-a9a841f8bba4
  14. melvin-bot commented on Aug 24, 2026

    @melvin-bot

    Triggered auto assignment to @mallenexpensify (Awaiting Payment)

  15. melvin-bot commented on Aug 24, 2026

    @melvin-bot

    Payment Summary

    Resolving PRs:

    Upwork Job

    • Assignee: @ahmdshrif requires payment (Needs manual offer from BZ)
    • Reviewer: @situchan owed $250 via NewDot

    BugZero Checklist (@mallenexpensify)

    • I have confirmed assignees, roles, and Upwork contracts look correct
    • I have paid out Upwork contracts / manual NewDot requests
    • [BugZero Assignee] I have created a GH issue for creating/updating the regression test once above steps have been agreed upon
  16. mallenexpensify commented on Aug 26, 2026

    @mallenexpensify
    Contributor

    Payment Summary

    Contributor: @ahmdshrif paid $250 via Upwork
    Contributor+: @situchan due $250 via NewDot

  17. laurenreidexpensify commented on Sep 3, 2026

    @laurenreidexpensify
    Contributor

    $250 approved @situchan New Expensify

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

Metadata

Metadata

Labels

Awaiting PaymentAuto-added when associated PR is deployed to productionBugSomething is broken. Auto assigns a BugZero manager.DailyKSv2ExternalAdded to denote the issue can be worked on by a contributor

Type

No type

Projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions